repo_name stringlengths 7 104 | file_path stringlengths 11 238 | context list | import_statement stringlengths 103 6.85k | code stringlengths 60 38.4k | next_line stringlengths 10 824 | gold_snippet_index int32 0 8 |
|---|---|---|---|---|---|---|
TeamCohen/SEAL | src/com/rcwang/seal/expand/WrapperSaver.java | [
"public class XMLUtil {\r\n static public Exception exception = null;\r\n static private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n static private DocumentBuilder parser = null;\r\n \r\n /**\r\n * XSL transform (identity) to create text from Document.\r\n */\r\n static private... | import java.io.File;
import java.net.URL;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import com.rcwang.seal.util.XMLUtil;
import com.rcwang.seal.util.Helper;
import com.rcwang.seal.util.StringFactory;
import com.rcwang.seal.expand.Wrapper.EntityLiteral;
import com.rcwang.seal.fetch.DocumentSet;
import com.rcwang.seal.fetch.Document;
import com.rcwang.seal.fetch.WebManager;
import com.rcwang.seal.util.StringEncoder;
| /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
*
* ... and William Cohen (wcohen@cs.cmu.edu)
**************************************************************************/
package com.rcwang.seal.expand;
public class WrapperSaver {
public static Logger log = Logger.getLogger(WrapperSaver.class);
| private static StringEncoder encoder = new StringEncoder('%',"\"\t\n\r");
| 7 |
ptitfred/magrit | server/core/src/main/java/org/kercoin/magrit/core/build/QueueServiceImpl.java | [
"@Singleton\npublic class Context {\n\t\n\tprivate final Configuration configuration = new Configuration();\n\t\n\tprivate Injector injector;\n\t\n\tprivate final GitUtils gitUtils;\n\t\n\tprivate final ExecutorService commandRunnerPool;\n\n\tpublic Context() {\n\t\tgitUtils = null;\n\t\tcommandRunnerPool = null;\n... | import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryBuilder;
import org.kercoin.magrit.core.Context;
import org.kercoin.magrit.core.Pair;
import org.kercoin.magrit.core.build.pipeline.Filter;
import org.kercoin.magrit.core.build.pipeline.Filters;
import org.kercoin.magrit.core.build.pipeline.Key;
import org.kercoin.magrit.core.build.pipeline.Listener;
import org.kercoin.magrit.core.build.pipeline.Pipeline;
import org.kercoin.magrit.core.build.pipeline.Task;
import org.kercoin.magrit.core.user.UserIdentity;
import com.google.inject.Inject;
import com.google.inject.Singleton; | /*
Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file.
This file is part of Magrit.
Magrit is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Magrit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public
License along with Magrit.
If not, see <http://www.gnu.org/licenses/>.
*/
package org.kercoin.magrit.core.build;
@Singleton
public class QueueServiceImpl implements QueueService {
| private final Context context; | 0 |
smartmarmot/DBforBIX | src/com/smartmarmot/dbforbix/DBforBix.java | [
"public class Constants {\r\n\tprivate static final String VERSION = \"Version 3.2.0-beta\";\r\n\tpublic static final String BANNER = Constants.PROJECT_NAME + \" \" + VERSION;\r\n\tprivate static final String PROJECT_NAME = \"DBforBix\";\r\n}",
"public class Config {\r\n\r\n\tinterface Validable {\r\n\r\n\t\tpubl... | import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Collection;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import com.smartmarmot.common.Constants;
import com.smartmarmot.dbforbix.config.Config;
import com.smartmarmot.dbforbix.config.ZabbixServer;
import com.smartmarmot.dbforbix.db.DBManager;
import com.smartmarmot.dbforbix.zabbix.PersistentDBSender;
import com.smartmarmot.dbforbix.zabbix.ZabbixSender;
| /*
* This file is part of DBforBix.
*
* DBforBix is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* DBforBix is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* DBforBix. If not, see <http://www.gnu.org/licenses/>.
*/
package com.smartmarmot.dbforbix;
/**
* DBforBix daemon main class
*/
public class DBforBix implements Daemon {
private static final Logger LOG = Logger.getLogger(DBforBix.class);
private static ZabbixSender _zabbixSender;
private static PersistentDBSender persSender;
//private static boolean debug = false;
private static Options options;
private static void reinit(){
//get config instance
Config config = Config.getInstance();
// read config file
try {
config.readFileConfig();
}
catch (IOException e) {
System.err.println("Error in config: " + e.getLocalizedMessage());
System.exit(-1);
}
catch (NullPointerException e) {
System.err.println("Error while getting config hash file: " + e.getLocalizedMessage());
System.exit(-1);
}
// init logging
// try {
// String logfile = config.getLogFile();
//
// if (logfile.startsWith("./"))
// logfile = logfile.replaceFirst(".", config.getBasedir());
//
// PatternLayout layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss}] [%-5p] [%t[%M(%F:%L)]]: %m%n");
// RollingFileAppender rfa = new RollingFileAppender(layout, logfile, true);
// rfa.setMaxFileSize(config.getLogFileSize());
// rfa.setMaxBackupIndex(1);
//
// Logger.getRootLogger().addAppender(rfa);
// if (!debug)
// Logger.getRootLogger().setLevel(config.getLogLevel());
// }
// catch (IOException ex) {
// System.err.println("Error while configuring logging: " + ex.getLocalizedMessage());
// LOG.error(ex.getLocalizedMessage(), ex);
// }
| LOG.info("### executing " + Constants.BANNER + ": " + new Date().toString());
| 0 |
StephenBlackWasAlreadyTaken/xDrip-Experimental | app/src/main/java/com/eveningoutpost/dexdrip/NavDrawerBuilder.java | [
"@Table(name = \"BgReadings\", id = BaseColumns._ID)\npublic class BgReading extends Model implements ShareUploadableBg{\n public static final double AGE_ADJUSTMENT_TIME = 86400000 * 1.9;\n public static final double AGE_ADJUSTMENT_FACTOR = .45;\n private static boolean predictBG;\n private final static... | import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.eveningoutpost.dexdrip.Models.BgReading;
import com.eveningoutpost.dexdrip.Models.Calibration;
import com.eveningoutpost.dexdrip.Models.Sensor;
import com.eveningoutpost.dexdrip.Services.XDripViewer;
import com.eveningoutpost.dexdrip.Tables.BgReadingTable;
import com.eveningoutpost.dexdrip.Tables.CalibrationDataTable;
import com.eveningoutpost.dexdrip.UtilityModels.CollectionServiceStarter;
import com.eveningoutpost.dexdrip.stats.StatsActivity;
import com.eveningoutpost.dexdrip.utils.Preferences;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; | package com.eveningoutpost.dexdrip;
/**
* Created by stephenblack on 11/5/14.
*/
public class NavDrawerBuilder {
public List<Calibration> last_two_calibrations = Calibration.latest(2);
public List<BgReading> last_two_bgReadings = BgReading.latestUnCalculated(2);
public List<BgReading> bGreadings_in_last_30_mins = BgReading.last30Minutes(); | public boolean is_active_sensor = Sensor.isActive(); | 2 |
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/activities/Staff/SearchVehicleActivity.java | [
"public interface CarRentalApiClient {\n /**\n * Return the list of available branches\n *\n * @return list of branches\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request if there was ... | import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.vehiclerental.R;
import com.vehiclerental.apiClient.CarRentalApiClient;
import com.vehiclerental.apiClient.CarRentalApiClientFactory;
import com.vehiclerental.contracts.SearchVehicleContract;
import com.vehiclerental.contracts.VehicleContract;
import com.vehiclerental.utils.ActivityUtils;
import com.vehiclerental.utils.SerializationUtils;
import com.vehiclerental.utils.StaticDataUtils;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife; | /**
* CarRental
*
* This activity displays a form to search vehicles in the current branch either by registration number or type
*/
package com.vehiclerental.activities.Staff;
public class SearchVehicleActivity extends AppCompatActivity {
//public message passing keys
public final static String VEHICLE_SEARCH_RESULTS_LIST_SERIALIZED_KEY = "vehicle_search_results_list_serialized";
public final static String SELECTED_VEHICLE_SERIALIZED_KEY = "selected_serialized";
//Automatic binding with Butterknife (external library)
@Bind(R.id.vehicleTypePicker)
protected Spinner vehicleTypePicker;
@Bind(R.id.registrationNumberField)
protected EditText registrationNumberField;
@Bind(R.id.searchVehiclesButton)
protected Button searchVehiclesButton;
//private members
private SearchVehicleContract searchVehicleContract; | private CarRentalApiClient apiClient = CarRentalApiClientFactory.getApiClient(); | 0 |
komamitsu/fluency | fluency-core/src/main/java/org/komamitsu/fluency/buffer/Buffer.java | [
"public class BufferFullException\n extends IOException\n{\n public BufferFullException(String s)\n {\n super(s);\n }\n}",
"@JsonSerialize(using = EventTime.Serializer.class)\npublic class EventTime\n{\n private final long seconds;\n private final long nanoseconds;\n\n /**\n * ... | import org.komamitsu.fluency.BufferFullException;
import org.komamitsu.fluency.EventTime;
import org.komamitsu.fluency.ingester.Ingester;
import org.komamitsu.fluency.recordformat.RecordFormatter;
import org.komamitsu.fluency.validation.Validatable;
import org.komamitsu.fluency.validation.annotation.DecimalMin;
import org.komamitsu.fluency.validation.annotation.Min;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong; | /*
* Copyright 2018 Mitsunori Komatsu (komamitsu)
*
* 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.komamitsu.fluency.buffer;
public class Buffer
implements Closeable
{
private static final Logger LOG = LoggerFactory.getLogger(Buffer.class);
private final FileBackup fileBackup;
private final RecordFormatter recordFormatter;
private final Config config;
private final Map<String, RetentionBuffer> retentionBuffers = new HashMap<>();
private final LinkedBlockingQueue<TaggableBuffer> flushableBuffers = new LinkedBlockingQueue<>();
private final Queue<TaggableBuffer> backupBuffers = new ConcurrentLinkedQueue<>();
private final BufferPool bufferPool;
public Buffer(RecordFormatter recordFormatter)
{
this(new Config(), recordFormatter);
}
public Buffer(final Config config, RecordFormatter recordFormatter)
{
config.validateValues();
this.config = config;
if (config.getFileBackupDir() != null) {
fileBackup = new FileBackup(new File(config.getFileBackupDir()), this, config.getFileBackupPrefix());
}
else {
fileBackup = null;
}
this.recordFormatter = recordFormatter;
bufferPool = new BufferPool(
config.getChunkInitialSize(), config.getMaxBufferSize(), config.jvmHeapBufferMode);
init();
}
private void init()
{
if (fileBackup != null) {
for (FileBackup.SavedBuffer savedBuffer : fileBackup.getSavedFiles()) {
savedBuffer.open((params, channel) -> {
try {
LOG.info("Loading buffer: params={}, buffer.size={}", params, channel.size());
}
catch (IOException e) {
LOG.error("Failed to access the backup file: params={}", params, e);
}
loadBufferFromFile(params, channel);
});
}
}
}
protected void saveBuffer(List<String> params, ByteBuffer buffer)
{
if (fileBackup == null) {
return;
}
LOG.info("Saving buffer: params={}, buffer={}", params, buffer);
fileBackup.saveBuffer(params, buffer);
}
| public void flush(Ingester ingester, boolean force) | 2 |
idega/is.idega.idegaweb.egov.bpm | src/java/is/idega/idegaweb/egov/bpm/cases/board/BoardCasesManagerImpl.java | [
"public class IWBundleStarter implements IWBundleStartable {\n\t\n\tpublic static final String IW_BUNDLE_IDENTIFIER = \"is.idega.idegaweb.egov.bpm\";\n\n\tpublic void start(IWBundle starterBundle) {\n\t\t\n//\t\tEgovBPMViewManager viewManager = EgovBPMViewManager.getInstance(starterBundle.getApplication());\n//\t\t... | import is.idega.idegaweb.egov.bpm.IWBundleStarter;
import is.idega.idegaweb.egov.bpm.business.TaskViewerHelper;
import is.idega.idegaweb.egov.bpm.cases.CaseProcessInstanceRelationImpl;
import is.idega.idegaweb.egov.bpm.cases.actionhandlers.CaseHandlerAssignmentHandler;
import is.idega.idegaweb.egov.bpm.cases.manager.BPMCasesRetrievalManager;
import is.idega.idegaweb.egov.bpm.cases.presentation.beans.BPMProcessVariablesBean;
import is.idega.idegaweb.egov.cases.business.BoardCasesComparator;
import is.idega.idegaweb.egov.cases.business.BoardCasesManager;
import is.idega.idegaweb.egov.cases.data.GeneralCase;
import is.idega.idegaweb.egov.cases.data.GeneralCaseBMPBean;
import is.idega.idegaweb.egov.cases.presentation.CasesBoardViewCustomizer;
import is.idega.idegaweb.egov.cases.presentation.CasesBoardViewer;
import is.idega.idegaweb.egov.cases.presentation.beans.CaseBoardBean;
import is.idega.idegaweb.egov.cases.presentation.beans.CaseBoardTableBean;
import is.idega.idegaweb.egov.cases.presentation.beans.CaseBoardTableBodyRowBean;
import is.idega.idegaweb.egov.cases.util.CasesConstants;
import java.io.Serializable;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.idega.block.process.business.ProcessConstants;
import com.idega.block.process.data.Case;
import com.idega.block.process.data.CaseBMPBean;
import com.idega.block.process.data.CaseHome;
import com.idega.bpm.xformsview.converters.ObjectCollectionConverter;
import com.idega.builder.bean.AdvancedProperty;
import com.idega.business.IBOLookup;
import com.idega.core.contact.data.Email;
import com.idega.data.IDOLookup;
import com.idega.data.IDOLookupException;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWMainApplication;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.jbpm.bean.VariableByteArrayInstance;
import com.idega.jbpm.bean.VariableInstanceInfo;
import com.idega.jbpm.data.VariableInstanceQuerier;
import com.idega.jbpm.data.dao.BPMDAO;
import com.idega.jbpm.utils.JBPMConstants;
import com.idega.presentation.IWContext;
import com.idega.user.business.NoEmailFoundException;
import com.idega.user.business.UserBusiness;
import com.idega.user.data.User;
import com.idega.util.ArrayUtil;
import com.idega.util.CoreConstants;
import com.idega.util.CoreUtil;
import com.idega.util.ListUtil;
import com.idega.util.StringHandler;
import com.idega.util.StringUtil;
import com.idega.util.WebUtil;
import com.idega.util.datastructures.map.MapUtil;
import com.idega.util.expression.ELUtil; | if (isEqual(column.getId(), ProcessConstants.BOARD_FINANCING_DECISION))
// Calculating board amounts
boardAmountTotal = boardAmountTotal.add(caseBoard.getBoardAmount());
else if (isEqual(column.getId(), ProcessConstants.BOARD_FINANCING_SUGGESTION))
// Calculating grant amount suggestions
grantAmountSuggestionTotal = grantAmountSuggestionTotal.add(caseBoard.getGrantAmountSuggestion());
}
index++;
}
rowBean.setValues(rowValues);
bodyRows.add(rowBean);
}
data.setBodyBeans(bodyRows);
// Footer
data.setFooterValues(getFooterValues(data.getBodyBeans().get(0).getValues().keySet().size() + (financingTableAdded ? 3 : 0),
grantAmountSuggestionTotal, boardAmountTotal, uuid));
// Everything is OK
data.setFilledWithData(Boolean.TRUE);
return data;
}
/*
* (non-Javadoc)
* @see is.idega.idegaweb.egov.cases.business.BoardCasesManager#getTableData(com.idega.presentation.IWContext, java.util.Collection, java.lang.String, java.lang.String, boolean, boolean, java.lang.String)
*/
@Override
public CaseBoardTableBean getTableData(
Collection<String> caseStatuses,
String processName,
String uuid,
boolean isSubscribedOnly,
boolean backPage,
String taskName) {
return getTableData(null, null, caseStatuses, processName, uuid, isSubscribedOnly, backPage, taskName);
}
@Override
public AdvancedProperty getHandlerInfo(IWContext iwc, User handler) {
if (handler == null)
return null;
UserBusiness userBusiness = null;
try {
userBusiness = IBOLookup.getServiceInstance(iwc, UserBusiness.class);
} catch(RemoteException e) {
LOGGER.log(Level.WARNING, "Error getting " + UserBusiness.class, e);
}
if (userBusiness == null)
return null;
AdvancedProperty info = new AdvancedProperty(handler.getName());
Email email = null;
try {
email = userBusiness.getUsersMainEmail(handler);
} catch (RemoteException e) {
LOGGER.log(Level.WARNING, "Error getting email for user: " + handler, e);
} catch (NoEmailFoundException e) {}
if (email != null)
info.setValue(new StringBuilder("mailto:").append(email.getEmailAddress()).toString());
return info;
}
protected static final String LOCALIZATION_PREFIX = "case_board_viewer.";
@Override
public List<String> getCustomColumns(String uuid) {
if (StringUtil.isEmpty(uuid))
return Collections.emptyList();
IWContext iwc = CoreUtil.getIWContext();
Object customColumns = iwc.getSessionAttribute(CasesBoardViewer.PARAMETER_CUSTOM_COLUMNS + uuid);
if (customColumns instanceof List<?>) {
@SuppressWarnings("unchecked")
List<String> columns = (List<String>) customColumns;
return columns;
}
return null;
}
@Override
public Map<Integer, List<AdvancedProperty>> getColumns(String uuid) {
Map<Integer, List<AdvancedProperty>> columns = new TreeMap<Integer, List<AdvancedProperty>>();
int index = 1;
List<String> customColumns = getCustomColumns(uuid);
if (ListUtil.isEmpty(customColumns)) {
for (AdvancedProperty header: CasesBoardViewer.CASE_FIELDS) {
if (index == 15) {
columns.put(index, Arrays.asList(
new AdvancedProperty(CasesBoardViewer.WORK_ITEM,
localize(CasesBoardViewer.WORK_ITEM, "Work item")),
new AdvancedProperty(CasesBoardViewer.ESTIMATED_COST,
localize(CasesBoardViewer.ESTIMATED_COST, "Estimated cost")),
new AdvancedProperty(CasesBoardViewer.BOARD_PROPOSAL_FOR_GRANT,
localize(CasesBoardViewer.BOARD_PROPOSAL_FOR_GRANT, "Proposed funding")),
new AdvancedProperty(CasesBoardViewer.BOARD_SUGGESTION,
localize(CasesBoardViewer.BOARD_SUGGESTION.toLowerCase(), "Handler suggestions")),
new AdvancedProperty(CasesBoardViewer.BOARD_DECISION,
localize(CasesBoardViewer.BOARD_DECISION.toLowerCase(), "Board decision"))
));
} else {
columns.put(index, Arrays.asList(new AdvancedProperty(header.getId(),
localize(new StringBuilder(LOCALIZATION_PREFIX).append(header.getId()).toString(), header.getValue()))));
}
index++;
}
columns.put(index, Arrays.asList(new AdvancedProperty(CaseHandlerAssignmentHandler.handlerUserIdVarName,
localize(LOCALIZATION_PREFIX + CaseHandlerAssignmentHandler.handlerUserIdVarName, "Case handler"))));
} else {
String localized = null;
IWContext iwc = CoreUtil.getIWContext(); | IWResourceBundle bpmIWRB = iwc.getIWMainApplication().getBundle(IWBundleStarter.IW_BUNDLE_IDENTIFIER).getResourceBundle(iwc); | 0 |
cheremin/scalarization | lab/src/main/java/ru/cheremin/scalarization/lab/plain/ReturnTupleScenario.java | [
"public abstract class AllocationScenario implements Scenario{\n\tpublic static final String SIZE_KEY = \"scenario.size\";\n\n\tpublic static final int SIZE = Integer.getInteger( SIZE_KEY, 16 );\n\n\tpublic abstract long run();\n\n\tprotected String additionalInfo() {\n\t\treturn \"\";\n\t}\n\n\n\t@Override\n\tpubl... | import java.util.*;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import ru.cheremin.scalarization.AllocationScenario;
import ru.cheremin.scalarization.ScenarioRun;
import ru.cheremin.scalarization.infra.ScenarioRunArgs;
import ru.cheremin.scalarization.lab.Utils.Pool;
import static ru.cheremin.scalarization.ScenarioRun.runWithAll;
import static ru.cheremin.scalarization.lab.Utils.randomStringsPool; | package ru.cheremin.scalarization.lab.plain;
/**
* Check pattern: method with multiple return values wrapped in composite object.
* <p/>
* For both 1.7 and 1.8:
* Simple one-type tuples are successfully scalarized with 1.7/1.8, even being casted
* to generic interface.
* <p/>
* Mixed type tuples are not scalarized.
* <p/>
* Single or mixed types with nulls are not scalarized
*
* @author ruslan
* created 09/02/16 at 21:41
*/
public class ReturnTupleScenario extends AllocationScenario {
public static final String TUPLE_TYPE_KEY = "scenario.tuple-type";
private static final TupleType TUPLE_TYPE = TupleType.valueOf(
System.getProperty( TUPLE_TYPE_KEY, TupleType.IMMUTABLE_PAIR.name() )
);
| private final Pool<String> pool = randomStringsPool( 1024 ); | 4 |
oSoc14/Artoria | app/src/main/java/be/artoria/belfortapp/activities/MainActivity.java | [
"public class DescriptionRow {\n public final Drawable imageDescription;\n public final String description;\n\n public DescriptionRow(Drawable imageDescription, String description){\n this.imageDescription = imageDescription;\n this.description = description;\n }\n}",
"public class MainA... | import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import be.artoria.belfortapp.app.adapters.DescriptionRow;
import be.artoria.belfortapp.app.adapters.MainAdapter;
import be.artoria.belfortapp.fragments.MapFragment;
import be.artoria.belfortapp.mixare.MixView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import be.artoria.belfortapp.R;
import be.artoria.belfortapp.app.DataManager;
import be.artoria.belfortapp.app.POI;
import be.artoria.belfortapp.app.PrefUtils; | package be.artoria.belfortapp.activities;
public class MainActivity extends BaseActivity {
MainAdapter menuAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initGui();
}
private static boolean downloading = false;
public static void downloadData() {
final long lastDownload = PrefUtils.getTimeStampDownloads();
final long timeSinceLastDownload = System.currentTimeMillis() - lastDownload;
/* Either there is no last download ( case == 0)
* or it is older than 12 hours, which is 43200000 milliseconds according to google */
// TODO change this back!
// if((lastDownload == 0 || timeSinceLastDownload > 5*60*1000) && !downloading){
if((lastDownload == 0 || timeSinceLastDownload > 1000*60*60*6) && !downloading){
downloading = true;
Log.i(PrefUtils.TAG,"Started downloading in the background");
new DownloadDataTask().execute(PrefUtils.DATASET_URL);
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
/*initialize the GUI content and clickhandlers*/
private void initGui(){
final ListView lstMenu = (ListView)findViewById(R.id.lstMenu);
final Button btnSettings = (Button)findViewById(R.id.btnSettings);
final Button btnAbout = (Button)findViewById(R.id.btnAbout);
final String[] strings = getResources().getStringArray(R.array.lstMenu);
final Drawable[] drawables = new Drawable[]{
getResources().getDrawable((R.drawable.panorama)),
getResources().getDrawable((R.drawable.menu)),
getResources().getDrawable((R.drawable.route))
};
final List<DescriptionRow> list = new ArrayList<DescriptionRow>();
for (int i = 0; i < strings.length; i++) {
list.add(new DescriptionRow(drawables[i],strings[i]));
}
menuAdapter = new MainAdapter(this,R.layout.main_list_item,list);
lstMenu.setAdapter(menuAdapter);
lstMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Intent intent;
switch (i) {
/* The first item is the be.artoria.belfortapp.mixare panorama */
case 0:
if(deviceSupported()) {
intent = new Intent(MainActivity.this, MixView.class);
startActivity(intent);
}
else{
Toast.makeText(PrefUtils.getContext(),R.string.unsupported, Toast.LENGTH_LONG).show();
}
break;
/* The second item are the buildings */
case 1:
intent = new Intent(MainActivity.this, MonumentDetailActivity.class);
intent.putExtra(MonumentDetailActivity.ARG_ID, 1);
startActivity(intent);
break;
/* The third item is my route */
case 2:
intent = new Intent(MainActivity.this,NewRouteActivity.class);
startActivity(intent);
break;
}
}
});
btnSettings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*Go to settings*/
final Intent i = new Intent(MainActivity.this, LanguageChoiceActivity.class);
startActivity(i);
}
});
btnAbout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*Go to the Artoria website*/
final Uri webpage = Uri.parse(getResources().getString(R.string.artoria_url));
final Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
startActivity(webIntent);
}
});
}
private boolean deviceSupported() {
final SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
return mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null && mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null;
}
private static class DownloadDataTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
StringBuilder response = new StringBuilder();
for (String url : urls) {
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet(url);
try {
final HttpResponse execute = client.execute(httpGet);
final InputStream content = execute.getEntity().getContent();
final BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s;
while ((s = buffer.readLine()) != null) {
response.append(s);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
return response.toString();
}
@Override
protected void onPostExecute(String result) {
final Gson gson = new Gson(); | final List<POI> list = gson.fromJson(result, new TypeToken<List<POI>>(){}.getType()); | 5 |
xda/XDA-One | android/src/main/java/com/xda/one/ui/PostAdapter.java | [
"@JsonIgnoreProperties(ignoreUnknown = true)\npublic class ResponseAttachment implements Parcelable {\n\n public static final Parcelable.Creator<ResponseAttachment> CREATOR\n = new Parcelable.Creator<ResponseAttachment>() {\n @Override\n public ResponseAttachment createFromParcel(Parcel ... | import com.dd.xda.CircularProgressButton;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.xda.one.R;
import com.xda.one.api.model.response.ResponseAttachment;
import com.xda.one.auth.XDAAccount;
import com.xda.one.model.augmented.AugmentedPost;
import com.xda.one.parser.TextDataStructure;
import com.xda.one.ui.helper.ActionModeHelper;
import com.xda.one.util.AccountUtils;
import com.xda.one.util.SectionUtils;
import com.xda.one.util.Utils;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List; | package com.xda.one.ui;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
private final Context mContext;
private final GoToQuoteListener mQuoteListener;
private final View.OnClickListener mMultiQuoteClickListener;
private final ActionModeHelper mModeHelper;
private final LayoutInflater mLayoutInflater;
private final View.OnClickListener mDownloadClickListener;
private final View.OnClickListener mImageClickListener;
private final View.OnClickListener mAvatarClickListener;
private final View.OnClickListener mThanksClickListener;
private final View.OnClickListener mQuoteClickListener;
private List<AugmentedPost> mPosts;
public PostAdapter(final Context context, final ActionModeHelper modeHelper,
final View.OnClickListener downloadClickListener,
final View.OnClickListener imageClickListener,
final View.OnClickListener avatarClickListener,
final View.OnClickListener thanksClickListener,
final View.OnClickListener quoteClickListener,
final View.OnClickListener multiQuoteClickListener,
final GoToQuoteListener quoteListener) {
mContext = context;
mLayoutInflater = LayoutInflater.from(context);
mModeHelper = modeHelper;
mDownloadClickListener = downloadClickListener;
mImageClickListener = imageClickListener;
mAvatarClickListener = avatarClickListener;
mThanksClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
final CircularProgressButton button = (CircularProgressButton) v;
button.setProgress(50);
thanksClickListener.onClick(v);
}
};
mQuoteClickListener = quoteClickListener;
mMultiQuoteClickListener = multiQuoteClickListener;
mQuoteListener = quoteListener;
mPosts = new ArrayList<>();
}
@Override
public PostViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final View view = mLayoutInflater.inflate(R.layout.post_list_item, parent, false);
return new PostViewHolder(view);
}
@Override
public void onBindViewHolder(PostViewHolder holder, int position) {
final AugmentedPost post = getPost(position);
holder.itemView.setOnClickListener(mModeHelper);
holder.itemView.setOnLongClickListener(mModeHelper);
mModeHelper.updateActivatedState(holder.itemView, position);
holder.userNameView.setText(post.getUserName());
// TODO - make this more efficient
holder.postLayout.removeAllViews();
final TextDataStructure structure = post.getTextDataStructure();
SectionUtils.setupSections(mContext, mLayoutInflater, holder.postLayout, structure,
mQuoteListener);
// Load the avatar into the image view
Picasso.with(mContext)
.load(post.getAvatarUrl())
.placeholder(R.drawable.account_circle)
.error(R.drawable.account_circle)
.into(holder.avatarView);
holder.avatarView.setOnClickListener(mAvatarClickListener);
holder.avatarView.setTag(post.getUserId());
holder.attachments.removeAllViews();
if (post.getAttachments() != null) {
for (final ResponseAttachment responseAttachment : post.getAttachments()) {
if (responseAttachment.hasThumbnail()) {
attachImagesThumbnail(holder, responseAttachment);
} else {
attachFiles(holder, responseAttachment);
}
}
}
| holder.dateView.setText(Utils.getRelativeDate(mContext, post.getDateline())); | 5 |
tommai78101/PokemonWalking | levelEditor/src/main/java/script_editor/ScriptToolbar.java | [
"public class EditorFileChooser extends JFileChooser {\n\tprivate static final long serialVersionUID = -649119858083751845L;\n\n\t@Override\n\tpublic void approveSelection() {\n\t\tFile selectedFile = super.getSelectedFile();\n\t\tif (selectedFile.isDirectory()) {\n\t\t\tsuper.setCurrentDirectory(selectedFile);\n\t... | import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import editor.EditorFileChooser;
import editor.EditorMouseListener;
import editor.FileControl;
import editor.LevelEditor;
import editor.Trigger; | package script_editor;
//TODO (6/25/2015): Save the already-opened file without needing to open up a JFileChooser.
public class ScriptToolbar extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private final ScriptEditor editor;
private final String[] tags = {
"New Script", "Save Script", "Open Script", ""
};
private final HashMap<String, JButton> buttonCache = new HashMap<>();
public ScriptToolbar(ScriptEditor editor) {
super();
this.editor = editor;
this.setLayout(new GridLayout(1, this.tags.length));
this.createButtons();
}
@Override
public void actionPerformed(ActionEvent event) {
final EditorFileChooser chooser = new EditorFileChooser();
final EditorMouseListener mouseListener = new EditorMouseListener(chooser);
switch (Integer.valueOf(event.getActionCommand())) {
case 0: { // New script
this.editor.scriptChanger.clearTextFields();
JList<Trigger> triggerList = this.editor.scriptViewer.getTriggerList();
DefaultListModel<Trigger> model = (DefaultListModel<Trigger>) triggerList.getModel();
model.clear();
JComboBox<Trigger> triggerComboBox = this.editor.parent.properties.getTriggerList();
DefaultComboBoxModel<Trigger> triggerComboModel = (DefaultComboBoxModel<Trigger>) triggerComboBox
.getModel();
triggerComboModel.removeAllElements();
Trigger trigger = new Trigger();
trigger.setTriggerID((short) 0);
trigger.setName("Eraser");
triggerComboModel.addElement(trigger);
triggerComboBox.setSelectedIndex(0);
triggerList.clearSelection();
this.editor.setModifiedFlag(false);
this.editor.setTitle("Script Editor (Hobby) - Untitled.script");
this.editor.setScriptName("Untitled");
this.editor.scriptChanger.disableComponent();
this.editor.parent.revalidate();
break;
}
case 1: { // Save script
try (RandomAccessFile raf = new RandomAccessFile(LevelEditor.SAVED_PATH_DATA, "rw")) {
raf.readLine(); // The second line in the cache is for the Script Editor.
ScriptEditor.lastSavedDirectory = new File(raf.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
catch (NullPointerException e) { | ScriptEditor.lastSavedDirectory = FileControl.lastSavedDirectory; | 2 |
jwtk/jjwt | impl/src/main/java/io/jsonwebtoken/impl/compression/DefaultCompressionCodecResolver.java | [
"public interface CompressionCodec {\n\n /**\n * The compression algorithm name to use as the JWT's {@code zip} header value.\n *\n * @return the compression algorithm name to use as the JWT's {@code zip} header value.\n */\n String getAlgorithmName();\n\n /**\n * Compresses the specifi... | import io.jsonwebtoken.CompressionCodec;
import io.jsonwebtoken.CompressionCodecResolver;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.CompressionException;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.impl.lang.Services;
import io.jsonwebtoken.lang.Strings;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; | /*
* Copyright (C) 2015 jsonwebtoken.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jsonwebtoken.impl.compression;
/**
* Default implementation of {@link CompressionCodecResolver} that supports the following:
* <p>
* <ul>
* <li>If the specified JWT {@link Header} does not have a {@code zip} header, this implementation does
* nothing and returns {@code null} to the caller, indicating no compression was used.</li>
* <li>If the header has a {@code zip} value of {@code DEF}, a {@link DeflateCompressionCodec} will be returned.</li>
* <li>If the header has a {@code zip} value of {@code GZIP}, a {@link GzipCompressionCodec} will be returned.</li>
* <li>If the header has any other {@code zip} value, a {@link CompressionException} is thrown to reflect an
* unrecognized algorithm.</li>
* </ul>
*
* <p>If you want to use a compression algorithm other than {@code DEF} or {@code GZIP}, you must implement your own
* {@link CompressionCodecResolver} and specify that when
* {@link io.jsonwebtoken.JwtBuilder#compressWith(CompressionCodec) building} and
* {@link io.jsonwebtoken.JwtParser#setCompressionCodecResolver(CompressionCodecResolver) parsing} JWTs.</p>
*
* @see DeflateCompressionCodec
* @see GzipCompressionCodec
* @since 0.6.0
*/
public class DefaultCompressionCodecResolver implements CompressionCodecResolver {
private static final String MISSING_COMPRESSION_MESSAGE = "Unable to find an implementation for compression algorithm [%s] using java.util.ServiceLoader. Ensure you include a backing implementation .jar in the classpath, for example jjwt-impl.jar, or your own .jar for custom implementations.";
private final Map<String, CompressionCodec> codecs;
public DefaultCompressionCodecResolver() {
Map<String, CompressionCodec> codecMap = new HashMap<>();
for (CompressionCodec codec : Services.loadAll(CompressionCodec.class)) {
codecMap.put(codec.getAlgorithmName().toUpperCase(), codec);
}
codecMap.put(CompressionCodecs.DEFLATE.getAlgorithmName().toUpperCase(), CompressionCodecs.DEFLATE);
codecMap.put(CompressionCodecs.GZIP.getAlgorithmName().toUpperCase(), CompressionCodecs.GZIP);
codecs = Collections.unmodifiableMap(codecMap);
}
@Override | public CompressionCodec resolveCompressionCodec(Header header) { | 3 |
kkrugler/yalder | core/src/main/java/org/krugler/yalder/hash/HashLanguageDetector.java | [
"public abstract class BaseLanguageDetector {\n\n public static final double DEFAULT_ALPHA = 0.000002;\n public static final double DEFAULT_DAMPENING = 0.001;\n\n protected static final double MIN_LANG_PROBABILITY = 0.1;\n protected static final double MIN_GOOD_LANG_PROBABILITY = 0.99;\n \n protec... | import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.krugler.yalder.BaseLanguageDetector;
import org.krugler.yalder.BaseLanguageModel;
import org.krugler.yalder.DetectionResult;
import org.krugler.yalder.LanguageLocale;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; | package org.krugler.yalder.hash;
/**
* Language detector that works with ngram hashes (versus text), for
* efficiency.
*
*/
public class HashLanguageDetector extends BaseLanguageDetector {
private static final int RENORMALIZE_INTERVAL = 10;
private static final int EARLY_TERMINATION_INTERVAL = RENORMALIZE_INTERVAL * 11;
// Map from language of model to index used for accessing arrays. | private Map<LanguageLocale, Integer> _langToIndex; | 3 |
SPIRIT-21/javadoc2swagger | src/main/java/com/spirit21/swagger/converter/parsers/ResourceParser.java | [
"public class Regex {\n\n public final static String PACKAGE = \"package [^;]*;\";\n public final static String JAVADOC = \"\\\\/\\\\*\\\\*((?!\\\\*\\\\/).)*\\\\*\\\\/\";\n public final static String ANNOTATION = \"@[a-zA-Z]+(\\\\([^@)]*\\\\))?\";\n public final static String METHOD = \"(public|protecte... | import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.plugin.logging.Log;
import com.spirit21.swagger.converter.Regex;
import com.spirit21.swagger.converter.loader.ClassLoader;
import com.spirit21.swagger.converter.models.Definition;
import com.spirit21.swagger.converter.models.JavaFile;
import com.spirit21.swagger.converter.models.Parameter;
import com.spirit21.swagger.converter.models.Resource;
import com.spirit21.swagger.converter.models.SwaggerModel;
import com.spirit21.swagger.converter.models.Tag; | package com.spirit21.swagger.converter.parsers;
/**
*
* @author dsimon
*
*/
public class ResourceParser extends AbstractParser implements SwaggerParser {
public ResourceParser(Log log, ClassLoader loader, List<Tag> tags, List<Definition> definitions) {
super(log, loader, tags, definitions);
}
@Override
public List<SwaggerModel> parse(List<JavaFile> javaFiles) throws ParserException, ClassNotFoundException {
List<SwaggerModel> resources = new ArrayList<>();
for (JavaFile file : javaFiles) {
Class<?> cls = loader.loadClass(
file.getPackageName() + "." + file.getFileName().substring(0, file.getFileName().length() - 5)); | Resource newResource = findResourceInJavaFile(file, cls); | 5 |
KostyaSha/github-integration-plugin | github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRBuildStatusPublisher.java | [
"public class GitHubPRCause extends GitHubCause<GitHubPRCause> {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRCause.class);\n\n private String headSha;\n private int number;\n private boolean mergeable;\n private String targetBranch;\n private String sourceBranch;\n pr... | import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractDescribableImpl;
import hudson.model.AbstractProject;
import hudson.model.Api;
import hudson.model.Descriptor;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRCause;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRMessage;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRTrigger;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.github.GHCommitState;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.io.PrintStream;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.addComment;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getCommitState;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRCauseFromRun;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRTriggerFromRun; | package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Sets build status on GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRBuildStatusPublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRBuildStatusPublisher.class);
private GitHubPRMessage statusMsg = new GitHubPRMessage("${GITHUB_PR_COND_REF} run ended");
private GHCommitState unstableAs = GHCommitState.FAILURE;
private BuildMessage buildMessage = new BuildMessage();
/**
* Constructor with defaults. Only for groovy UI.
*/
@Restricted(NoExternalUse.class)
public GitHubPRBuildStatusPublisher() {
super(null, null);
}
@DataBoundConstructor
public GitHubPRBuildStatusPublisher(GitHubPRMessage statusMsg, GHCommitState unstableAs, BuildMessage buildMessage,
StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {
super(statusVerifier, errorHandler);
if (statusMsg != null && isNotEmpty(statusMsg.getContent())) {
this.statusMsg = statusMsg;
}
this.unstableAs = unstableAs;
this.buildMessage = buildMessage;
}
@Override
public void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull Launcher launcher,
@NonNull TaskListener listener) throws InterruptedException, IOException {
PrintStream listenerLogger = listener.getLogger();
String publishedURL = getTriggerDescriptor().getJenkinsURL();
if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
return;
}
if (isEmpty(publishedURL)) {
return;
}
GHCommitState state = getCommitState(run, unstableAs);
GitHubPRCause c = ghPRCauseFromRun(run);
String statusMsgValue = getStatusMsg().expandAll(run, listener);
String buildUrl = publishedURL + run.getUrl();
LOGGER.info("Setting status of {} to {} with url {} and message: {}",
c.getHeadSha(), state, buildUrl, statusMsgValue);
// TODO check permissions to write human friendly message
final GitHubPRTrigger trigger = ghPRTriggerFromRun(run);
if (isNull(trigger)) {
listener.error("Can't get trigger for this run! Silently skipping. " +
"TODO implement error handler, like in publishers");
return;
}
try {
trigger.getRemoteRepository().createCommitStatus(c.getHeadSha(), state, buildUrl, statusMsgValue,
run.getParent().getFullName());
} catch (IOException ex) {
if (nonNull(buildMessage)) {
String comment = null;
LOGGER.error("Could not update commit status of the Pull Request on GitHub. ", ex);
if (state == GHCommitState.SUCCESS) {
comment = buildMessage.getSuccessMsg().expandAll(run, listener);
} else if (state == GHCommitState.FAILURE) {
comment = buildMessage.getFailureMsg().expandAll(run, listener);
}
listenerLogger.println("Adding comment...");
LOGGER.info("Adding comment, because: ", ex); | addComment(c.getNumber(), comment, run, listener); | 5 |
sensorstorm/StormCV | stormcv-examples/src/nl/tno/stormcv/example/E9_ContrastEnhancementTopology.java | [
"public class StormCVConfig extends Config{\n\n\tprivate static final long serialVersionUID = 6290659199719921212L;\n\n\t/**\n\t * <b>Boolean (default = false)</b> configuration parameter indicating if the spout must cache emitted tuples so they can be replayed\n\t */\n\tpublic static final String STORMCV_SPOUT_FAU... | import java.util.ArrayList;
import java.util.List;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.tuple.Fields;
import backtype.storm.utils.Utils;
import nl.tno.stormcv.StormCVConfig;
import nl.tno.stormcv.batcher.SlidingWindowBatcher;
import nl.tno.stormcv.bolt.BatchInputBolt;
import nl.tno.stormcv.bolt.SingleInputBolt;
import nl.tno.stormcv.example.util.GlobalContrastEnhancementOp;
import nl.tno.stormcv.example.util.GlobalContrastEnhancementOp.CEAlgorithm;
import nl.tno.stormcv.fetcher.StreamFrameFetcher;
import nl.tno.stormcv.model.Frame;
import nl.tno.stormcv.model.serializer.FrameSerializer;
import nl.tno.stormcv.operation.MjpegStreamingOp;
import nl.tno.stormcv.spout.CVParticleSpout; | /**
*
*/
package nl.tno.stormcv.example;
/**
* @author John Schavemaker
*
*/
public class E9_ContrastEnhancementTopology {
/**
* @param args
*/
public static void main(String[] args)
{
// first some global (topology configuration)
StormCVConfig conf = new StormCVConfig();
/**
* Sets the OpenCV library to be used which depends on the system the topology is being executed on
*/
//conf.put( StormCVConfig.STORMCV_OPENCV_LIB, "mac64_opencv_java248.dylib" );
conf.setNumWorkers( 4 ); // number of workers in the topology
conf.setMaxSpoutPending( 32 ); // maximum un-acked/un-failed frames per spout (spout blocks if this number is reached) | conf.put( StormCVConfig.STORMCV_FRAME_ENCODING, Frame.JPG_IMAGE ); // indicates frames will be encoded as JPG throughout the topology (JPG is the default when not explicitly set) | 5 |
rrauschenbach/mobi-api4java | src/main/java/org/rr/mobi4java/MobiContentIndex.java | [
"public static byte[] getBytes(byte[] buffer, int offset) {\n\tbyte[] b = new byte[buffer.length - offset];\n\tSystem.arraycopy(buffer, offset, b, 0, buffer.length - offset);\n\treturn b;\n}",
"public static int getInt(byte[] buffer, int offset, int length) {\n\treturn getInt(getBytes(buffer, offset, length));\n}... | import static org.apache.commons.lang3.BooleanUtils.negate;
import static org.rr.mobi4java.ByteUtils.getBytes;
import static org.rr.mobi4java.ByteUtils.getInt;
import static org.rr.mobi4java.ByteUtils.getString;
import static org.rr.mobi4java.ByteUtils.write;
import static org.rr.mobi4java.ByteUtils.writeInt;
import static org.rr.mobi4java.ByteUtils.writeString;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.output.TeeOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder; | package org.rr.mobi4java;
public class MobiContentIndex extends MobiContent {
private static final String IDENTIFIER = "INDX";
public static enum INDEX_TYPE {
NORMAL(0), INFLECTION(2);
private final int type;
private static Map<Integer, INDEX_TYPE> map = new HashMap<Integer, INDEX_TYPE>();
static {
for (INDEX_TYPE typeEnum : INDEX_TYPE.values()) {
if(map.put(typeEnum.type, typeEnum) != null) {
throw new IllegalArgumentException("Duplicate type " + typeEnum.type);
}
}
}
private INDEX_TYPE(final int type) {
this.type = type;
}
public static INDEX_TYPE valueOf(int type) {
return map.get(type);
}
public int getType() {
return type;
}
}
private int headerLength;
private int indexType;
private int unknown1;
private int unknown2;
private int idxtIndex;
private int indexCount;
private int indexEncoding;
private int indexLanguage;
private int totalIndexCount;
private int ordtIndex;
private int ligtIndex;
private int ordtLigtEntriesCount;
private int cncxRecordCount;
private byte[] unknownIndxHeaderPart;
private byte[] rest;
private MobiContentTagx tagx;
MobiContentIndex(byte[] content) throws IOException {
super(content, CONTENT_TYPE.INDEX);
readMobiIndex();
}
private void readMobiIndex() throws IOException {
String identifier = getString(content, 0, 4);
if (negate(StringUtils.equals(identifier, IDENTIFIER))) {
throw new IOException("Expected to find index header identifier INDX but got '" + identifier + "' instead");
}
headerLength = getInt(content, 4, 4);
indexType = getInt(content, 8, 4);
unknown1 = getInt(content, 12, 4);
unknown2 = getInt(content, 16, 4);
idxtIndex = getInt(content, 20, 4);
indexCount = getInt(content, 24, 4); // entries count
indexEncoding = getInt(content, 28, 4);
indexLanguage = getInt(content, 32, 4);
totalIndexCount = getInt(content, 36, 4); // total entries count
ordtIndex = getInt(content, 40, 4);
ligtIndex = getInt(content, 44, 4);
ordtLigtEntriesCount = getInt(content, 48, 4);
cncxRecordCount = getInt(content, 52, 4);
/* 60-148: phonetizer */
unknownIndxHeaderPart = getBytes(content, 56, headerLength - 56);
int ordtType = getInt(content, 164, 4);
int ordtEntriesCount = getInt(content, 168, 4);
int ordt1Offset = getInt(content, 172, 4);
int ordt2Offset = getInt(content, 176, 4);
int entrySize = ordtType == 0 ? 1 : 2;
int tagxIndex = getInt(content, 180, 4);
int tagxNameLength = getInt(content, 184, 4);
if(tagxIndex > 0) {
tagx = new MobiContentTagx(getBytes(content, tagxIndex));
List<MobiContentTagEntry> tags = tagx.getTags();
for (MobiContentTagEntry tag : tags) {
int value = tag.getControlByte() & tag.getBitmask();
}
MobiContentIdxt idxt = new MobiContentIdxt(getBytes(content, idxtIndex), indexCount);
rest = getBytes(content, tagxIndex + tagx.getSize());
} else {
rest = getBytes(content, headerLength);
}
}
@Override
byte[] writeContent(OutputStream out) throws IOException {
ByteArrayOutputStream branch = new ByteArrayOutputStream();
TeeOutputStream tee = new TeeOutputStream(out, branch);
writeString(IDENTIFIER, 4, tee); | writeInt(headerLength, 4, tee); | 4 |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/adapters/FriendAdapter.java | [
"@Service\npublic class FriendService {\n\n private final UserRepository userRepository;\n\n @Autowired\n public FriendService(final UserRepository userRepository) {\n this.userRepository = notNull(userRepository);\n }\n\n public Set<User> friendFor(final String username) {\n return use... | import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import se.omegapoint.facepalm.application.FriendService;
import se.omegapoint.facepalm.application.Result;
import se.omegapoint.facepalm.application.UserService;
import se.omegapoint.facepalm.client.config.Adapter;
import se.omegapoint.facepalm.client.models.Friend;
import se.omegapoint.facepalm.client.security.AuthenticatedUser;
import se.omegapoint.facepalm.domain.User;
import java.util.Set;
import static java.util.stream.Collectors.toSet;
import static org.apache.commons.lang3.Validate.notNull; | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package se.omegapoint.facepalm.client.adapters;
@Adapter
public class FriendAdapter {
private final FriendService friendService;
private final UserService userService;
@Autowired
public FriendAdapter(final FriendService friendService, final UserService userService) {
this.friendService = notNull(friendService);
this.userService = notNull(userService);
}
| public Set<Friend> friendsForCurrentUser() { | 3 |
tomgibara/bits | src/test/java/com/tomgibara/bits/sample/Examples.java | [
"public abstract class AbstractBitStore implements BitStore {\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Bits.bitStoreHasher().intHashValue(this);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) return true;\n\t\tif (!(obj instanceof BitStore)) return false;\n\t\tBitStore... | import static com.tomgibara.streams.Streams.streamInput;
import static com.tomgibara.streams.Streams.streamOutput;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.SortedSet;
import junit.framework.TestCase;
import com.tomgibara.bits.AbstractBitStore;
import com.tomgibara.bits.BitReader;
import com.tomgibara.bits.BitStore;
import com.tomgibara.bits.BitStreamException;
import com.tomgibara.bits.BitWriter;
import com.tomgibara.bits.Bits;
import com.tomgibara.bits.EndOfBitStreamException; | package com.tomgibara.bits.sample;
public class Examples extends TestCase {
public void testExamples() throws IOException {
// preamble
int distance = 0;
boolean fill = false;
BigInteger bigInt = BigInteger.ONE;
byte[] bytes = new byte[] {};
int[] ints = new int[] {};
int size = 1;
BitSet bitSet = new BitSet();
String string = "";
Random random = new Random(0L);
int from = 0;
int to = 1;
BitStore store = Bits.store(1000);
BitStore otherStore = Bits.store(1000); | BitReader reader = Bits.zeroBits(100000).openReader(); | 1 |
dmillett/prank | src/test/java/net/prank/example/ExampleScoreCard.java | [
"public class Indices\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n /** A collection of indices for any object that is subject to multiple sorts */\n private final List<Integer> _indices;\n\n public Indices(int originalIndex) {\n _indices = new ArrayList<>... | import net.prank.core.Indices;
import net.prank.core.RequestOptions;
import net.prank.core.Result;
import net.prank.core.ScoreCard;
import net.prank.core.ScoreData;
import net.prank.core.ScoreSummary;
import net.prank.core.Statistics;
import java.math.BigDecimal; | package net.prank.example;
/**
* A very simple example of a setupScoring card. More complex examples should still be stateless for
* thread safety. Typically, the higher the setupScoring, the better the result.
* <p/>
* The adjustments are just examples of how scoring might be adjusted to make some
* setupScoring cards more/less important than other setupScoring cards. If machine learning (ML)
* indicates that price is the most important factor for all customers (or individual),
* then it should have "heavier" weighting and it's setupScoring should be adjusted (+)
* <p/>
* Examples:
* Price: the lowest price has the highest setupScoring.
* Shipping cost: how much to ship the item
* Shipping time: how long it takes an item to ship
*
*
* @author dmillett
*
* Copyright 2012 David Millett
* 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.
*/
public class ExampleScoreCard
implements ScoreCard<ExampleObject> {
private final String _name = "SolutionPriceScoreCard";
// Mutable state (single threaded only) -- D
private final int _scoreAdjustment;
private final int _positionAdjustment;
private final double _averageAdjustment;
private final double _standardDeviationAdjustment;
public ExampleScoreCard() {
_scoreAdjustment = 5;
_positionAdjustment = 3;
_averageAdjustment = 2;
_standardDeviationAdjustment = 1.0;
}
public ExampleScoreCard(int scoreAdjustment, int positionAdjustment, double averageAdjustment,
double standardDeviationAdjustment) {
_scoreAdjustment = scoreAdjustment;
_positionAdjustment = positionAdjustment;
_averageAdjustment = averageAdjustment;
_standardDeviationAdjustment = standardDeviationAdjustment;
}
public ScoreSummary score(ExampleObject scoringObject) {
// Ignore the summary for now
performScoring(scoringObject);
return null;
}
@Override | public ScoreSummary scoreWith(ExampleObject scoringObject, RequestOptions options) { | 1 |
i2p/i2p.itoopie | src/net/i2p/itoopie/gui/component/chart/InboundBandwidthTracker.java | [
"public class JSONRPC2SessionException extends Exception {\n\n\t\n\t/**\n\t * The exception cause is network or I/O related.\n\t */\n\tpublic static final int NETWORK_EXCEPTION = 1;\n\t\n\t\n\t/**\n\t * Unexpected \"Content-Type\" header value of the HTTP response.\n\t */\n\tpublic static final int UNEXPECTED_CONTE... | import java.util.EnumMap;
import java.util.HashMap;
import com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException;
import net.i2p.itoopie.i2pcontrol.InvalidParametersException;
import net.i2p.itoopie.i2pcontrol.InvalidPasswordException;
import net.i2p.itoopie.i2pcontrol.methods.GetRateStat;
import net.i2p.itoopie.i2pcontrol.methods.GetRouterInfo;
import net.i2p.itoopie.i2pcontrol.methods.RouterInfo.ROUTER_INFO; | package net.i2p.itoopie.gui.component.chart;
public class InboundBandwidthTracker extends Thread implements Tracker {
/** Last read bw */
private double m_value = 0;
private final int updateInterval;
private volatile boolean running;
/**
* Start daemon that checks to current inbound bandwidth of the router.
*/
public InboundBandwidthTracker(int interval) {
super("IToopie-IBT");
updateInterval = interval;
this.setDaemon(true);
this.start();
}
/**
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
running = true;
while (running) {
runOnce();
try {
Thread.sleep(updateInterval);
} catch (InterruptedException e) {
break;
}
}
}
public synchronized void runOnce(){
try { | EnumMap<ROUTER_INFO, Object> em = GetRouterInfo.execute(ROUTER_INFO.BW_INBOUND_1S); | 4 |
itsJoKr/LocalNetwork | localnet/src/main/java/dev/jokr/localnet/ServerService.java | [
"public class DiscoveryReply implements Serializable {\n\n private String ip;\n private int port;\n\n public DiscoveryReply(String ip, int port) {\n this.ip = ip;\n this.port = port;\n }\n\n public String getIp() {\n return ip;\n }\n\n public int getPort() {\n return... | import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.NotificationCompat;
import android.text.format.Formatter;
import android.util.Log;
import java.util.HashMap;
import dev.jokr.localnet.discovery.models.DiscoveryReply;
import dev.jokr.localnet.models.ConnectedClients;
import dev.jokr.localnet.models.Payload;
import dev.jokr.localnet.models.RegisterMessage;
import dev.jokr.localnet.models.SessionMessage;
import dev.jokr.localnet.utils.NetworkUtil; | package dev.jokr.localnet;
/**
* Created by JoKr on 8/28/2016.
*/
public class ServerService extends Service implements ServerSocketThread.ServiceCallback, Communicator {
public static final String ACTION = "action";
public static final int NOTIFICATION_ID = 521;
// Keys for extras
public static final String CLASS = "class";
public static final String BUNDLE = "bundle";
public static final String PAYLOAD = "payload";
// Possible service actions:
public static final int START_SESSION = 1;
public static final int SESSION_EVENT = 2;
private HashMap<Long, RegisterMessage> registeredClients;
private LocalSession session;
private LocalBroadcastManager manager;
private Thread serverSocketThread;
private Thread discoverySocketThread;
@Override
public void onCreate() {
super.onCreate();
this.manager = LocalBroadcastManager.getInstance(this);
registeredClients = new HashMap<>();
serverSocketThread = new Thread(new ServerSocketThread(this));
serverSocketThread.start();
runServiceInForeground();
}
/*
Multiple calls to Context.startService() will result in multiple calls to onStartCommand,
but only one call to onCreate, so we use it as a way to send data to Service.
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("USER", "onStartCommand called");
int action = intent.getIntExtra(ACTION, 0);
processAction(action, intent);
return START_NOT_STICKY;
}
private void processAction(int action, Intent intent) {
if (action == 0)
return;
if (action == START_SESSION)
startSession((Class) intent.getSerializableExtra(CLASS), intent.getBundleExtra(BUNDLE));
else if (action == SESSION_EVENT)
session.onEvent((Payload<?>) intent.getSerializableExtra(PAYLOAD));
}
private void startSession(Class c, Bundle b) {
try {
Object o = c.newInstance();
if (!LocalSession.class.isInstance(o)) {
throw new IllegalArgumentException("Class " + c.getName() + " is not instance of LocalSession");
}
session = (LocalSession) o;
session.preCreateInit(this);
session.onCreate(b, new ConnectedClients(registeredClients));
sendSessionStartMessage();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private void sendSessionStartMessage() {
SessionMessage message = new SessionMessage(null, SessionMessage.START);
for (RegisterMessage client : registeredClients.values()) {
Thread t = new Thread(new SendHandler(message, client.getIp(), client.getPort()));
t.start();
}
}
private void runServiceInForeground() {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("LocalNet Session")
.setContentText("Session is currently running")
.setSmallIcon(R.drawable.ic_play_circle_filled_black_24dp)
.build();
startForeground(NOTIFICATION_ID, notification);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onInitializedSocket(int port) {
discoverySocketThread = new Thread(new DiscoverySocketThread(new DiscoveryReply(getLocalIp(), port)));
discoverySocketThread.start();
}
@Override
public void onClientConnected(RegisterMessage message) {
Log.d("USER", "onClientConnected: " + message.getPayload()); | Long id = NetworkUtil.getIdFromIpAddress(message.getIp()); | 5 |
bigjelly/AndFast | app/src/main/java/com/andfast/app/view/common/TabManager.java | [
"public class AndFastApplication extends Application {\n\n private final static String TAG = \"AndFastApplication\";\n private static Context mContext;\n\n @Override\n public void onCreate() {\n super.onCreate();\n mContext = getApplicationContext();\n StorageUtils.initExtDir(getApp... | import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.andfast.app.AndFastApplication;
import com.andfast.app.R;
import com.andfast.app.constant.GeneralID;
import com.andfast.app.util.LogUtils;
import com.andfast.app.view.common.activity.MainActivity;
import com.andfast.app.view.widget.SpacingTextView;
import java.util.ArrayList;
import java.util.List; | package com.andfast.app.view.common;
/**
* Created by mby on 17-8-1.
*/
public class TabManager {
private final static String TAG = "TabManager";
private TabLayout mTabLayout;
private Fragment mCurrentFragment;
private LayoutInflater mInflater;
private int mCurrentIdx;
private int mLastIdx;
private TextView[] mTabTextView = new TextView[MainTab.values().length];
private List<TabReselectListener> mTabReselectListeners;
public interface TabReselectListener {
void onTabReselect();
}
private TabManager(){
}
public static TabManager getInstance(Context context){
return TabMangerHolder.sInstance;
}
private static class TabMangerHolder{
private static final TabManager sInstance = new TabManager();
}
public void initTabs(MainActivity mainActivity,Intent intent,TabLayout tabLayout) {
mTabLayout = tabLayout;
mInflater = LayoutInflater.from(AndFastApplication.getContext());
tabLayout.addOnTabSelectedListener(getTabSelectedListener(mainActivity));
MainTab[] mainTabs = MainTab.values();
for (int i = 0; i < mainTabs.length; i++) {
MainTab mainTab = mainTabs[i];
mTabLayout.addTab(mTabLayout.newTab().setCustomView(getTabItemView(i, mainTab)).setTag(new TabInfo(mainTab.getClazz())), false);
}
changeTab(intent);
mTabTextView[mLastIdx].setTextColor(AndFastApplication.getContext().getResources().getColor(R.color.tab_font_red));
}
public void changeTab(Intent intent) { | int tab = intent.getIntExtra(GeneralID.Extra.TAB, 0); | 1 |
spccold/sailfish | sailfish-kernel/src/main/java/sailfish/remoting/channel/EmptyExchangeChannel.java | [
"public class RequestControl {\n\t/**\n\t * response timeout or write timeout if {@code sent} is true\n\t */\n private int timeout = 2000;\n private short opcode;\n private byte serializeType;\n private byte compressType;\n //wait write success or not\n private boolean sent;\n\n /**... | import java.net.SocketAddress;
import java.util.UUID;
import io.netty.channel.Channel;
import sailfish.remoting.RequestControl;
import sailfish.remoting.ResponseCallback;
import sailfish.remoting.Tracer;
import sailfish.remoting.exceptions.SailfishException;
import sailfish.remoting.future.ResponseFuture;
import sailfish.remoting.handler.MsgHandler;
import sailfish.remoting.protocol.Protocol;
import sailfish.remoting.protocol.ResponseProtocol; | /**
*
* Copyright 2016-2016 spccold
*
* 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 sailfish.remoting.channel;
/**
* for test or something else
* @author spccold
* @version $Id: EmptyExchangeChannel.java, v 0.1 2016年11月25日 下午8:37:47 spccold Exp $
*/
public class EmptyExchangeChannel implements ExchangeChannel{
@Override
public UUID id() {
return null;
}
@Override
public boolean isAvailable() {
return false;
}
@Override | public MsgHandler<Protocol> getMsgHander() { | 6 |
Kesshou/Kesshou-Android | app/src/main/java/kesshou/android/daanx/views/regist/SchoolFragment.java | [
"public class ToastUtils {\n\n\tprivate static Toast toast;\n\n\tpublic static void makeTextAndShow(Context context,String text, int duration) {\n\t\tif (toast == null) {\n\t\t\t//如果還沒有用過makeText方法,才使用\n\t\t\ttoast = new Toast(context);\n\t\t\tLayoutInflater inflater = LayoutInflater.from(context);\n\t\t\tView view... | import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.AppCompatButton;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import kesshou.android.daanx.R;
import kesshou.android.daanx.util.component.ToastUtils;
import kesshou.android.daanx.util.network.MyCallBack;
import kesshou.android.daanx.util.network.NetworkingClient;
import kesshou.android.daanx.util.network.api.holder.CheckRegist;
import kesshou.android.daanx.util.network.api.holder.Error;
import kesshou.android.daanx.util.network.api.holder.Register;
import kesshou.android.daanx.util.network.api.holder.StatusResponse;
import kesshou.android.daanx.views.StartActivity;
import retrofit2.Call;
import retrofit2.Response; | package kesshou.android.daanx.views.regist;
/**
* A simple {@link Fragment} subclass.
*/
public class SchoolFragment extends Fragment {
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_school, container, false);
final TextInputLayout tilInputAccount=(TextInputLayout)view.findViewById(R.id.til_input_account);
final TextInputEditText inputAccount=(TextInputEditText)view.findViewById(R.id.input_account);
TextViewCheckEmpty(tilInputAccount,inputAccount);
final TextInputLayout tilInputPassword=(TextInputLayout)view.findViewById(R.id.til_input_password);
final TextInputEditText inputPassword=(TextInputEditText) view.findViewById(R.id.input_password);
TextViewCheckEmpty(tilInputPassword,inputPassword);
| final Register register=((StartActivity) getActivity()).register; | 7 |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/Evaporator.java | [
"public class AMTListAddition extends BaseListAddition {\n private Object amt_recipe = null;\n\n public AMTListAddition(String description, List list, AMTRecipeWrapper recipe) {\n super(description, list, recipe);\n }\n\n @Override\n public void apply() {\n if (amt_recipe == null) {\n ... | import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import minetweaker.api.liquid.ILiquidStack;
import mods.belgabor.amtweaker.mods.amt.util.AMTListAddition;
import mods.belgabor.amtweaker.mods.amt.util.AMTRecipeWrapper;
import mods.belgabor.amtweaker.util.BaseListRemoval;
import mods.defeatedcrow.api.recipe.IEvaporatorRecipe;
import mods.defeatedcrow.api.recipe.RecipeRegisterManager;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqualNull; | package mods.belgabor.amtweaker.mods.amt.handlers;
@ZenClass("mods.amt.Evaporator")
public class Evaporator {
// Adding a new cooking recipe for the iron plate
@ZenMethod
public static void addRecipe(IItemStack output, ILiquidStack secondary, IItemStack input, boolean returnContainer) {
doAddRecipe(output, secondary, input, returnContainer);
}
@ZenMethod
public static void addRecipe(IItemStack output, ILiquidStack secondary, IItemStack input) {
doAddRecipe(output, secondary, input, true);
}
@ZenMethod
public static void addRecipe(IItemStack output, IItemStack input, boolean returnContainer) {
doAddRecipe(output, null, input, returnContainer);
}
@ZenMethod
public static void addRecipe(ILiquidStack secondary, IItemStack input, boolean returnContainer) {
doAddRecipe(null, secondary, input, returnContainer);
}
@ZenMethod
public static void addRecipe(IItemStack output, IItemStack input) {
doAddRecipe(output, null, input, true);
}
@ZenMethod
public static void addRecipe(ILiquidStack secondary, IItemStack input) {
doAddRecipe(null, secondary, input, true);
}
private static void doAddRecipe(IItemStack output, ILiquidStack secondary, IItemStack input, boolean returnContainer) {
if (input == null) {
MineTweakerAPI.getLogger().logError("Evaporator: Input item must not be null!");
return;
}
if ((output == null) && (secondary == null)) {
MineTweakerAPI.getLogger().logError("Evaporator: Primary and secondary output must not both be null!");
return;
}
MineTweakerAPI.apply(new Add(new EvaporatorRecipeWrapper(output, secondary, input, returnContainer)));
}
private static class EvaporatorRecipeWrapper extends AMTRecipeWrapper {
private final ItemStack output;
private final FluidStack secondary;
private final ItemStack input;
private final boolean returnContainer;
public EvaporatorRecipeWrapper(IItemStack output, ILiquidStack secondary, IItemStack input, boolean returnContainer) {
this.output = toStack(output);
this.secondary = toFluid(secondary);
this.input = toStack(input);
this.returnContainer = returnContainer;
}
@Override
public void register() {
RecipeRegisterManager.evaporatorRecipe.addRecipe(output, secondary, input, returnContainer);
}
@Override
public boolean matches(Object o) {
IEvaporatorRecipe r = (IEvaporatorRecipe) o;
return (r.returnContainer() == returnContainer) &&
(areEqualNull(r.getInput(), input)) &&
(areEqualNull(r.getOutput(), output)) &&
(areEqualNull(r.getSecondary(), secondary));
}
@Override
public String getRecipeInfo() {
String s = "";
if (output != null) {
s += output.getDisplayName();
}
if (secondary != null) {
if (output != null) {
s += " + ";
}
s += this.secondary.getLocalizedName();
}
return s;
}
}
//Passes the list to the base list implementation, and adds the recipe | private static class Add extends AMTListAddition { | 0 |
ragnraok/JParserUtil | src/main/java/com/ragnarok/jparseutil/memberparser/TypeParser.java | [
"public class SourceInfo {\n \n public static final String TAG = \"JParserUtil.SourceInfo\";\n \n private String fileName;\n private List<String> importClassNames = new ArrayList<>();\n private String packageName = null;\n \n private List<String> asteriskImports = new ArrayList<>();\n \n ... | import com.github.javaparser.ast.type.ReferenceType;
import com.ragnarok.jparseutil.dataobject.SourceInfo;
import com.ragnarok.jparseutil.dataobject.Type;
import com.ragnarok.jparseutil.util.Log;
import com.ragnarok.jparseutil.util.Primitive;
import com.ragnarok.jparseutil.util.Util;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.tree.JCTree; | package com.ragnarok.jparseutil.memberparser;
/**
* Created by ragnarok on 15/6/28.
* parser for the variable type
*/
public class TypeParser {
public static final String TAG = "JParserUtil.TypeParser";
| public static Type parseType(SourceInfo sourceInfo, com.github.javaparser.ast.type.Type typeElement, String typeName) { | 0 |
njustesen/hero-aicademy | src/ai/NmSearchAI.java | [
"public class GameState {\n\t\n\tpublic static int TURN_LIMIT = 100;\n\tpublic static boolean RANDOMNESS = false;\n\tpublic static int STARTING_AP = 3;\n\tpublic static int ACTION_POINTS = 5;\n\t\n\tprivate static final int ASSAULT_BONUS = 300;\n\tprivate static final double INFERNO_DAMAGE = 350;\n\tprivate static ... | import game.GameState;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import model.Card;
import action.Action;
import action.EndTurnAction;
import ai.evaluation.HeuristicEvaluator;
import ai.evaluation.IStateEvaluator;
import ai.util.AiStatistics;
import ai.util.RAND_METHOD; | package ai;
public class NmSearchAI implements AI {
public boolean p1;
private final AI p1Ai;
private final AI p2Ai;
private List<Action> foundActions;
private final int n;
private final int m;
private IStateEvaluator evaluator;
public NmSearchAI(boolean p1, int n, int m, IStateEvaluator evaluator) {
this.p1 = p1; | p1Ai = new RandomAI(RAND_METHOD.TREE); | 7 |
BFergerson/Chronetic | src/test/java/io/chronetic/data/ChronoSeriesTest.java | [
"public class ChronoRange {\n\n /**\n * Create a ChronoRange for the given ChronoSeries and sequence of ChronoGenes.\n *\n * @param chronoSeries ChronoSeries to create ChronoRange for\n * @param genes ChronoGene sequence containing ChronoPattern(s) to use for creating ChronoRange\n * @return ... | import io.chronetic.data.measure.ChronoRange;
import io.chronetic.data.measure.ChronoScaleUnit;
import io.chronetic.evolution.pool.ChronoGene;
import io.chronetic.evolution.pool.allele.ChronoAllele;
import io.chronetic.evolution.pool.allele.ChronoFrequency;
import io.chronetic.evolution.pool.allele.ChronoPattern;
import org.jenetics.util.ISeq;
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import static org.junit.Assert.assertTrue; | package io.chronetic.data;
public class ChronoSeriesTest {
@Test
public void chronoSeriesTest1() {
ChronoSeries chronoSeries = ChronoSeries.of(
Instant.parse("2011-11-25T08:48:11Z"),
Instant.parse("2012-11-30T09:23:16Z"),
Instant.parse("2013-11-29T09:51:49Z"),
Instant.parse("2014-11-28T08:43:00Z"),
Instant.parse("2015-11-27T08:22:25Z")
);
ISeq<ChronoAllele> alleleSeq = ISeq.of(
new ChronoFrequency(ChronoUnit.YEARS, 0, 1, 1, Instant.now()), | new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.HOURS), 0, 8), | 5 |
andrzejchm/DroidMVP | sample/src/main/java/io/appflate/droidvmp/androidsample/ui/fragments/RepositoriesFragment.java | [
"public enum ApiManager {\n INSTANCE;\n\n private static final String BASE_URL = \"https://api.github.com/\";\n private GithubApi api;\n\n ApiManager() {\n Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL)\n .addConverterFactory(\n ... | import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ViewAnimator;
import butterknife.Bind;
import butterknife.ButterKnife;
import io.appflate.droidvmp.androidsample.R;
import io.appflate.droidvmp.androidsample.domain.ApiManager;
import io.appflate.droidvmp.androidsample.model.Repository;
import io.appflate.droidvmp.androidsample.model.presentation.RepositoriesPresentationModel;
import io.appflate.droidvmp.androidsample.ui.adapters.ReposRecyclerAdapter;
import io.appflate.droidvmp.androidsample.ui.base.BaseFragment;
import io.appflate.droidvmp.androidsample.ui.mvpviews.RepositoriesView;
import io.appflate.droidvmp.androidsample.ui.presenters.RepositoriesPresenter;
import io.appflate.droidvmp.androidsample.utils.Constants;
import java.util.List; | /*
* Copyright (C) 2016 Appflate.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.appflate.droidvmp.androidsample.ui.fragments;
/**
* Created by andrzejchm on 22/06/16.
*/
public class RepositoriesFragment
extends BaseFragment<RepositoriesPresentationModel, RepositoriesView, RepositoriesPresenter>
implements RepositoriesView {
public static final String TAG = RepositoriesFragment.class.getCanonicalName();
private static final int CHILD_PROGRESS_VIEW = 0;
private static final int CHILD_CONTENT_VIEW = 1;
@Bind(R.id.reposRecyclerView) RecyclerView reposRecyclerView;
@Bind(R.id.reposAnimator) ViewAnimator reposAnimator;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@NonNull @Override protected RepositoriesPresenter createPresenter() {
return new RepositoriesPresenter(ApiManager.getInstance().getApiService());
}
@NonNull @Override protected RepositoriesPresentationModel createPresentationModel() {
String username = getArguments().getString(Constants.PARAM_USERNAME);
return new RepositoriesPresentationModel(username);
}
@Nullable @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_repositories, container, false);
}
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
}
@Override public void showTitle(String username) {
getActivity().setTitle(username);
}
@Override public void showLoadingProgress() {
reposAnimator.setDisplayedChild(CHILD_PROGRESS_VIEW);
}
@Override public void showRepositoriesList(List<Repository> repositories) {
reposAnimator.setDisplayedChild(CHILD_CONTENT_VIEW);
reposRecyclerView.setLayoutManager(
new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false)); | reposRecyclerView.setAdapter(new ReposRecyclerAdapter(repositories)); | 3 |
dedyk/JaponskiPomocnik | app/src/main/java/pl/idedyk/android/japaneselearnhelper/test/WordTest.java | [
"public class JapaneseAndroidLearnHelperApplication extends MultiDexApplication {\n\n\tpublic static final ThemeType defaultThemeType = ThemeType.BLACK;\n\t\n\tprivate static JapaneseAndroidLearnHelperApplication singleton;\n\n\tpublic static JapaneseAndroidLearnHelperApplication getInstance() {\n\t\treturn singlet... | import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import pl.idedyk.android.japaneselearnhelper.JapaneseAndroidLearnHelperApplication;
import pl.idedyk.android.japaneselearnhelper.MenuShorterHelper;
import pl.idedyk.android.japaneselearnhelper.R;
import pl.idedyk.android.japaneselearnhelper.config.ConfigManager.WordTestConfig;
import pl.idedyk.android.japaneselearnhelper.context.JapaneseAndroidLearnHelperContext;
import pl.idedyk.android.japaneselearnhelper.context.JapaneseAndroidLearnHelperWordTestContext;
import pl.idedyk.android.japaneselearnhelper.dictionaryscreen.WordDictionaryDetails;
import pl.idedyk.android.japaneselearnhelper.problem.ReportProblem;
import pl.idedyk.android.japaneselearnhelper.utils.EntryOrderList;
import pl.idedyk.android.japaneselearnhelper.utils.ListUtil;
import pl.idedyk.japanese.dictionary.api.dictionary.Utils;
import pl.idedyk.japanese.dictionary.api.dto.Attribute;
import pl.idedyk.japanese.dictionary.api.dto.AttributeType;
import pl.idedyk.japanese.dictionary.api.dto.DictionaryEntry;
import pl.idedyk.japanese.dictionary.api.exception.DictionaryException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; | package pl.idedyk.android.japaneselearnhelper.test;
public class WordTest extends Activity {
private TextViewAndEditText[] textViewAndEditTextForWordAsArray;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, R.id.report_problem_menu_item, Menu.NONE, R.string.report_problem);
MenuShorterHelper.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// report problem
if (item.getItemId() == R.id.report_problem_menu_item) {
final JapaneseAndroidLearnHelperContext context = JapaneseAndroidLearnHelperApplication.getInstance()
.getContext();
final JapaneseAndroidLearnHelperWordTestContext wordTestContext = context.getWordTestContext();
final WordTestConfig wordTestConfig = JapaneseAndroidLearnHelperApplication.getInstance()
.getConfigManager(WordTest.this).getWordTestConfig();
// config
WordTestMode wordTestMode = wordTestConfig.getWordTestMode();
Set<String> chosenWordGroups = wordTestConfig.getChosenWordGroups();
Boolean random = wordTestConfig.getRandom();
Boolean untilSuccess = wordTestConfig.getUntilSuccess();
Integer repeatNumber = wordTestConfig.getRepeatNumber();
Boolean showKanji = wordTestConfig.getShowKanji();
Boolean showKana = wordTestConfig.getShowKana();
Boolean showTranslate = wordTestConfig.getShowTranslate();
Boolean showAdditionalInfo = wordTestConfig.getShowAdditionalInfo();
// context | EntryOrderList<DictionaryEntry> wordsTest = wordTestContext.getWordsTest(); | 7 |
lrtdc/light_drtc | src/main/java/org/light/rtc/admin/AdminNodeRabbitMqRun.java | [
"@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\r\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-03-16\")\r\npublic class TDssService {\r\n\r\n public interface Iface {\r\n\r\n public int addMqinfoToAdminQu(List<String> uLogs) throws org.apache.thrift.TEx... | import java.util.Timer;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.light.rtc.api.TDssService;
import org.light.rtc.base.StreamLogParser;
import org.light.rtc.mq.RabbitMqCollect;
import org.light.rtc.service.RtdcAdminService;
import org.light.rtc.timer.AdminNodeTimer;
import org.light.rtc.util.ConfigProperty;
import org.light.rtc.util.Constants; | package org.light.rtc.admin;
public class AdminNodeRabbitMqRun {
/**
* your self defending function for parsing your data stream logs
* @param slp
*/
public void setSteamParser(StreamLogParser slp){
AdminNodeTimer.setStreamLogParser(slp);
}
private class DataCollect implements Runnable{
@Override
public void run() {
RabbitMqCollect rmc = new RabbitMqCollect();
rmc.run();
}
}
public void run(){
this.adminJobTImer();
new Thread(new DataCollect()).start();
RtdcAdminService rss = new RtdcAdminService();
TDssService.Processor<RtdcAdminService> tp = new TDssService.Processor<RtdcAdminService>(rss);
TServerTransport serverTransport = null;
try {
serverTransport = new TServerSocket(Constants.adminNodePort);
} catch (TTransportException e) {
e.printStackTrace();
}
TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(serverTransport);
tArgs.maxWorkerThreads(1000);
tArgs.minWorkerThreads(10);
tArgs.processor(tp);
TCompactProtocol.Factory portFactory = new TCompactProtocol.Factory();
tArgs.protocolFactory(portFactory);
TServer tServer = new TThreadPoolServer(tArgs); | System.out.println(ConfigProperty.getCurDateTime()+"......轻量级实时计算框架任务管理节点(通过RabbitMq整合CN)服务启动......"); | 5 |
dmillerw/RemoteIO | src/main/java/me/dmillerw/remoteio/core/proxy/ClientProxy.java | [
"@Mod(modid = ModInfo.MOD_ID, name = ModInfo.MOD_NAME, version = ModInfo.MOD_VERSION, dependencies = \"required-after:Forge@[12.18.2.2099,)\")\npublic class RemoteIO {\n\n @Mod.Instance(\"remoteio\")\n public static RemoteIO instance;\n\n @SidedProxy(\n serverSide = ModInfo.CORE_PACKAGE + \".cor... | import me.dmillerw.remoteio.RemoteIO;
import me.dmillerw.remoteio.block.BlockRemoteInterface;
import me.dmillerw.remoteio.block.ModBlocks;
import me.dmillerw.remoteio.client.model.loader.BaseModelLoader;
import me.dmillerw.remoteio.client.render.RenderTileRemoteInterface;
import me.dmillerw.remoteio.lib.property.RenderState;
import me.dmillerw.remoteio.network.packet.client.CActivateBlock;
import me.dmillerw.remoteio.network.player.ClientProxyPlayer;
import me.dmillerw.remoteio.tile.TileRemoteInterface;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.renderer.color.IBlockColor;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import javax.annotation.Nullable; | package me.dmillerw.remoteio.core.proxy;
/**
* Created by dmillerw
*/
public class ClientProxy extends CommonProxy implements IProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
super.preInit(event);
| ModelLoaderRegistry.registerLoader(new BaseModelLoader()); | 3 |
SecUSo/privacy-friendly-weather | app/src/main/java/org/secuso/privacyfriendlyweather/activities/ForecastCityActivity.java | [
"@Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION)\npublic abstract class AppDatabase extends RoomDatabase {\n public static final String DB_NAME = \"PF_WEATHER_DB.db\";\n static final int VERSION = 7;\n static... | import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.TextView;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import org.secuso.privacyfriendlyweather.R;
import org.secuso.privacyfriendlyweather.database.AppDatabase;
import org.secuso.privacyfriendlyweather.database.data.CurrentWeatherData;
import org.secuso.privacyfriendlyweather.database.data.Forecast;
import org.secuso.privacyfriendlyweather.database.data.WeekForecast;
import org.secuso.privacyfriendlyweather.ui.updater.IUpdateableCityUI;
import org.secuso.privacyfriendlyweather.ui.updater.ViewUpdater;
import org.secuso.privacyfriendlyweather.ui.viewPager.WeatherPagerAdapter;
import java.util.List; | package org.secuso.privacyfriendlyweather.activities;
public class ForecastCityActivity extends BaseActivity implements IUpdateableCityUI {
private WeatherPagerAdapter pagerAdapter;
private MenuItem refreshActionButton;
private MenuItem rainviewerButton;
private int cityId = -1;
private ViewPager viewPager;
private TextView noCityText;
public static boolean stopTurning = false;
@Override
protected void onPause() {
super.onPause();
| ViewUpdater.removeSubscriber(this); | 5 |
mruffalo/seal | test/generator/errors/LinearIncreasingErrorGeneratorTest.java | [
"public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator\n{\n\tRandom random = new Random();\n\n\t@Override\n\tpublic CharSequence generateSequence(Options o)\n\t{\n\t\tFragmentErrorGenerator eg = new UniformErrorGenerator(o.characters,\n\t\t\to.repeatErrorProbability);\n\t\tfinal CharSequence re... | import generator.SeqGenSingleSequenceMultipleRepeats;
import generator.SequenceGenerator;
import generator.SequenceGenerator.Options;
import generator.errors.FragmentErrorGenerator;
import generator.errors.LinearIncreasingErrorGenerator;
import org.junit.Test; | package generator.errors;
public class LinearIncreasingErrorGeneratorTest
{
@Test
public void testGenerateErrors()
{ | SeqGenSingleSequenceMultipleRepeats sg = new SeqGenSingleSequenceMultipleRepeats(); | 0 |
Neutrinet/ISP-ng | src/main/java/be/neutrinet/ispng/DNS.java | [
"public class RequestHandler {\n\n static final int FLAG_DNSSECOK = 1;\n static final int FLAG_SIGONLY = 2;\n private Map<Integer, Cache> caches = new HashMap<>();\n\n public Cache getCache(int dclass) {\n Cache c = caches.get(dclass);\n if (c == null) {\n c = new Cache(dclass);... | import be.neutrinet.ispng.dns.RequestHandler;
import be.neutrinet.ispng.dns.TCPServer;
import be.neutrinet.ispng.dns.UDPServer;
import be.neutrinet.ispng.dns.ZoneBuilder;
import be.neutrinet.ispng.util.Zookeeper;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.xbill.DNS.*;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; | package be.neutrinet.ispng;
/**
* Created by wannes on 1/24/15.
*/
public class DNS {
public static Map<String, TSIG> TSIG = new HashMap<>();
public static Map<Name, Zone> zones = new HashMap<>();
public static Properties cfg;
public static void main(String[] args) {
try {
Logger root = Logger.getRootLogger();
root.setLevel(Level.INFO);
root.addAppender(new ConsoleAppender(VPN.LAYOUT));
cfg = new Properties();
cfg.load(new FileInputStream("dns.properties"));
Zookeeper.boot(cfg.getProperty("zookeeper.connectionString"));
String TSIGname = cfg.getProperty("tsig.name").toLowerCase() + ".";
TSIG.put(TSIGname, new TSIG(cfg.getProperty("tsig.algorithm"), TSIGname, cfg.getProperty("tsig.key")));
ZoneBuilder zoneBuilder = new ZoneBuilder();
zoneBuilder.boot(cfg);
zones = zoneBuilder.rebuildZones();
| RequestHandler handler = new RequestHandler(); | 0 |
talklittle/reddit-is-fun | src/com/andrewshu/android/reddit/mail/InboxActivity.java | [
"public abstract class CaptchaCheckRequiredTask extends AsyncTask<Void, Void, Boolean> {\n\t\n\tprivate static final String TAG = \"CaptchaCheckRequiredTask\";\n\t\n\t// Captcha \"iden\"\n private static final Pattern CAPTCHA_IDEN_PATTERN\n \t= Pattern.compile(\"name=\\\"iden\\\" value=\\\"([^\\\"]+)\\\"\");\... | import org.apache.http.client.HttpClient;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.andrewshu.android.reddit.R;
import com.andrewshu.android.reddit.captcha.CaptchaCheckRequiredTask;
import com.andrewshu.android.reddit.captcha.CaptchaDownloadTask;
import com.andrewshu.android.reddit.common.Common;
import com.andrewshu.android.reddit.common.Constants;
import com.andrewshu.android.reddit.common.FormValidation;
import com.andrewshu.android.reddit.common.RedditIsFunHttpClientFactory;
import com.andrewshu.android.reddit.settings.RedditSettings;
import com.andrewshu.android.reddit.things.ThingInfo; | String whichInbox = whichInboxes[getTabHost().getCurrentTab()];
InboxListActivity inboxListActivity = (InboxListActivity) getLocalActivityManager().getActivity(whichInbox);
if (inboxListActivity != null)
inboxListActivity.refresh();
break;
case android.R.id.home:
Common.goHome(this);
break;
}
return true;
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
ProgressDialog pdialog;
AlertDialog.Builder builder;
LayoutInflater inflater;
View layout; // used for inflated views for AlertDialog.Builder.setView()
switch (id) {
case Constants.DIALOG_COMPOSE:
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
builder = new AlertDialog.Builder(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
layout = inflater.inflate(R.layout.compose_dialog, null);
dialog = builder.setView(layout).create();
final Dialog composeDialog = dialog;
Common.setTextColorFromTheme(
mSettings.getTheme(),
getResources(),
(TextView) layout.findViewById(R.id.compose_destination_textview),
(TextView) layout.findViewById(R.id.compose_subject_textview),
(TextView) layout.findViewById(R.id.compose_message_textview),
(TextView) layout.findViewById(R.id.compose_captcha_textview),
(TextView) layout.findViewById(R.id.compose_captcha_loading)
);
final EditText composeDestination = (EditText) layout.findViewById(R.id.compose_destination_input);
final EditText composeSubject = (EditText) layout.findViewById(R.id.compose_subject_input);
final EditText composeText = (EditText) layout.findViewById(R.id.compose_text_input);
final Button composeSendButton = (Button) layout.findViewById(R.id.compose_send_button);
final Button composeCancelButton = (Button) layout.findViewById(R.id.compose_cancel_button);
final EditText composeCaptcha = (EditText) layout.findViewById(R.id.compose_captcha_input);
composeSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ThingInfo thingInfo = new ThingInfo();
if (!FormValidation.validateComposeMessageInputFields(InboxActivity.this, composeDestination, composeSubject, composeText, composeCaptcha))
return;
thingInfo.setDest(composeDestination.getText().toString().trim());
thingInfo.setSubject(composeSubject.getText().toString().trim());
new MyMessageComposeTask(
composeDialog,
thingInfo,
composeCaptcha.getText().toString().trim(),
mCaptchaIden,
mSettings,
mClient,
InboxActivity.this
).execute(composeText.getText().toString().trim());
removeDialog(Constants.DIALOG_COMPOSE);
}
});
composeCancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
removeDialog(Constants.DIALOG_COMPOSE);
}
});
break;
case Constants.DIALOG_COMPOSING:
pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
pdialog.setMessage("Composing message...");
pdialog.setIndeterminate(true);
pdialog.setCancelable(true);
dialog = pdialog;
break;
default:
throw new IllegalArgumentException("Unexpected dialog id "+id);
}
return dialog;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case Constants.DIALOG_COMPOSE:
new MyCaptchaCheckRequiredTask(dialog).execute();
break;
}
}
private class MyMessageComposeTask extends MessageComposeTask {
public MyMessageComposeTask(Dialog dialog,
ThingInfo targetThingInfo, String captcha, String captchaIden,
RedditSettings settings, HttpClient client, Context context) {
super(dialog, targetThingInfo, captcha, captchaIden, settings, client, context);
}
@Override
public void onPreExecute() {
showDialog(Constants.DIALOG_COMPOSING);
}
@Override
public void onPostExecute(Boolean success) {
removeDialog(Constants.DIALOG_COMPOSING);
if (success) {
Toast.makeText(InboxActivity.this, "Message sent.", Toast.LENGTH_SHORT).show();
// TODO: add the reply beneath the original, OR redirect to sent messages page
} else {
Common.showErrorToast(_mUserError, Toast.LENGTH_LONG, InboxActivity.this);
}
}
}
| private class MyCaptchaCheckRequiredTask extends CaptchaCheckRequiredTask { | 0 |
geoparser/geolocator | geo-locator/src/edu/cmu/geoparser/ui/geolocator/GUI/Desktop.java | [
"public class GetReader {\n\n public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException,\n UnsupportedEncodingException {\n File file = new File(filename);\n BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file),\n \"utf... | import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import edu.cmu.geoparser.Disambiguation.ContextDisamb;
import edu.cmu.geoparser.io.GetReader;
import edu.cmu.geoparser.io.GetWriter;
import edu.cmu.geoparser.model.Tweet;
import edu.cmu.geoparser.nlp.languagedetector.LangDetector;
import edu.cmu.geoparser.nlp.ner.FeatureExtractor.FeatureGenerator;
import edu.cmu.geoparser.parser.english.EnglishParser;
import edu.cmu.geoparser.resource.gazindexing.Index;
import edu.cmu.geoparser.resource.gazindexing.CollaborativeIndex.CollaborativeIndex;
import edu.cmu.geoparser.resource.trie.IndexSupportedTrie;
| JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmNew = new JMenuItem("New");
mnFile.add(mntmNew);
JMenuItem mntmOpen = new JMenuItem("Open");
mnFile.add(mntmOpen);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
mnFile.add(mntmExit);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmAbout = new JMenuItem("About");
mnHelp.add(mntmAbout);
mntmAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
About window = new About();
window.frame.setVisible(true);
}
});
frame.getContentPane().setLayout(null);
/**
* Message Box text area.
*/
final JTextArea txtrMessageBox = new JTextArea();
txtrMessageBox
.setText("Welcome to Geo-parser! It's developed by the Language Technology Institute in CMU.");
txtrMessageBox.setEditable(false);
txtrMessageBox.setLineWrap(true);
txtrMessageBox.setBounds(10, 11, 288, 178);
frame.getContentPane().add(txtrMessageBox);
/**
* Output box text area
*/
final JTextArea txtrOutputBox = new JTextArea();
txtrOutputBox.setText("Run the algorithm, and part of the results will be shown here.");
txtrOutputBox.setBounds(10, 217, 288, 178);
txtrOutputBox.setBorder(blackline);
txtrOutputBox.setLineWrap(true);
JScrollPane oscrollPane = new JScrollPane(txtrOutputBox);
oscrollPane.setVisible(true);
frame.getContentPane().add(txtrOutputBox);
/**
* input path, read in inbox content as file name
*/
txtCusers = new JTextField();
txtCusers.setText("Input file");
txtCusers.setToolTipText("Input path");
txtCusers.setBounds(338, 11, 180, 20);
frame.getContentPane().add(txtCusers);
txtCusers.setColumns(10);
/**
* output path, read in output box content as file name
*/
txtCusersoutput = new JTextField();
txtCusersoutput.setText("output file");
txtCusersoutput.setToolTipText("Output path");
txtCusersoutput.setBounds(338, 59, 180, 20);
frame.getContentPane().add(txtCusersoutput);
txtCusersoutput.setColumns(10);
/**
* Input file button clicked
*/
JButton btnNewButton = new JButton("Input File");
btnNewButton.setToolTipText("Select file of toponyms to tag.");
btnNewButton.setBounds(528, 10, 33, 23);
frame.getContentPane().add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// to do: fill out the input text area with selected file path.
}
});
/**
* output file button clicked, output file is ready
*/
JButton btnNewButton_1 = new JButton("Ouput File");
btnNewButton_1.setToolTipText("Select file to store results.");
btnNewButton_1.setBounds(528, 58, 33, 23);
frame.getContentPane().add(btnNewButton_1);
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// to do: fill out the output text area with selected file path.
}
});
JButton btnRun = new JButton("Run");
btnRun.setToolTipText("Run geolocator algorithm on above chosen files.");
btnRun.setBounds(338, 218, 89, 23);
frame.getContentPane().add(btnRun);
btnRun.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
br = GetReader.getUTF8FileReader(txtCusers.getText().trim());
bw = GetWriter.getFileWriter(txtCusersoutput.getText().trim());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sb = new StringBuilder();
| Tweet t;
| 2 |
ISibboI/JBitmessage | src/main/java/sibbo/bitmessage/network/NetworkManager.java | [
"public class Options extends Properties {\n\tprivate static final Logger LOG = Logger.getLogger(Options.class.getName());\n\n\tprivate static final Options defaults = new Options(null);\n\n\tstatic {\n\t\tdefaults.setProperty(\"global.version\", \"0.0.0\");\n\t\tdefaults.setProperty(\"global.name\", \"JBitmessage\... | import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Vector;
import java.util.logging.Logger;
import sibbo.bitmessage.Options;
import sibbo.bitmessage.data.Datastore;
import sibbo.bitmessage.network.protocol.InventoryVectorMessage;
import sibbo.bitmessage.network.protocol.MsgMessage;
import sibbo.bitmessage.network.protocol.NetworkAddressMessage;
import sibbo.bitmessage.network.protocol.POWMessage;
import sibbo.bitmessage.network.protocol.Util; | package sibbo.bitmessage.network;
/**
* Manages the operation of this bitmessage node. It is responsible for all
* communication with other nodes.
*
* @author Sebastian Schmidt
* @version 1.0
*/
public class NetworkManager implements ConnectionListener, Runnable {
private static final Logger LOG = Logger.getLogger(NetworkManager.class.getName());
/**
* Contains all connections managed by this object.<br />
* Thread-safe
*/
private final List<Connection> connections = new Vector<>();
/**
* The objects that listen for network status changes.<br />
* Thread-safe
*/
private final List<NetworkListener> listeners = new Vector<>();
/** The datastore that makes all data persistent. */
private final Datastore datastore;
/** Contains all objects that are currently requested from a node. */
// Note that this is a bad method to ensure that we get all objects but
// don't get anything twice. If someone sends an inv but never responds to a
// getdata and keeps connected, the respective objects will be blocked and
// can only be received if the network manager is restarted.
private final Map<InventoryVectorMessage, Connection> alreadyRequested = new Hashtable<>();
/**
* The parser to parse new objects. This is used to prevent timing attacks
* on the network manager thread.
*/
private final ObjectParser objectParser;
/** If this is true, the network manager stops as fast as possible. */
private volatile boolean stop;
/**
* True if someone connected to us. That means that we are reachable from
* outside.
*/
private boolean activeMode;
/** A random nonce to detect connections to self. */
private final long nonce;
/**
* Creates a new network manager operating on the datastore at the given
* path.
*
* @param datastore
* The name of the datastore.
*/
public NetworkManager(String datastoreName) {
this.datastore = new Datastore(datastoreName);
objectParser = new ObjectParser(datastore.getAddresses());
Random r = new Random();
byte[] nonce = new byte[8];
r.nextBytes(nonce); | this.nonce = Util.getLong(nonce); | 6 |
FlareBot/FlareBot | src/main/java/stream/flarebot/flarebot/ModlogEvents.java | [
"public class RedisController {\n\n private static JedisPool jedisPool;\n\n public static BlockingQueue<RedisSetData> setQueue = new LinkedBlockingQueue<>();\n\n private RedisController() {\n }\n\n public RedisController(JSONConfig config) {\n jedisPool = new JedisPool(\n new Je... | import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.audit.ActionType;
import net.dv8tion.jda.core.audit.AuditLogChange;
import net.dv8tion.jda.core.audit.AuditLogEntry;
import net.dv8tion.jda.core.entities.Channel;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.MessageEmbed;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.Event;
import net.dv8tion.jda.core.events.channel.text.GenericTextChannelEvent;
import net.dv8tion.jda.core.events.channel.text.TextChannelCreateEvent;
import net.dv8tion.jda.core.events.channel.text.TextChannelDeleteEvent;
import net.dv8tion.jda.core.events.channel.voice.GenericVoiceChannelEvent;
import net.dv8tion.jda.core.events.channel.voice.VoiceChannelCreateEvent;
import net.dv8tion.jda.core.events.channel.voice.VoiceChannelDeleteEvent;
import net.dv8tion.jda.core.events.guild.GenericGuildEvent;
import net.dv8tion.jda.core.events.guild.GuildBanEvent;
import net.dv8tion.jda.core.events.guild.member.*;
import net.dv8tion.jda.core.events.guild.update.GenericGuildUpdateEvent;
import net.dv8tion.jda.core.events.guild.update.GuildUpdateExplicitContentLevelEvent;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceJoinEvent;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent;
import net.dv8tion.jda.core.events.message.GenericMessageEvent;
import net.dv8tion.jda.core.events.message.MessageDeleteEvent;
import net.dv8tion.jda.core.events.message.MessageUpdateEvent;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.events.role.GenericRoleEvent;
import net.dv8tion.jda.core.events.role.RoleCreateEvent;
import net.dv8tion.jda.core.events.role.RoleDeleteEvent;
import net.dv8tion.jda.core.events.role.update.GenericRoleUpdateEvent;
import net.dv8tion.jda.core.events.role.update.RoleUpdatePositionEvent;
import net.dv8tion.jda.core.hooks.EventListener;
import stream.flarebot.flarebot.database.RedisController;
import stream.flarebot.flarebot.database.RedisMessage;
import stream.flarebot.flarebot.mod.modlog.ModlogEvent;
import stream.flarebot.flarebot.mod.modlog.ModlogHandler;
import stream.flarebot.flarebot.objects.GuildWrapper;
import stream.flarebot.flarebot.util.MessageUtils;
import stream.flarebot.flarebot.util.general.FormatUtils;
import stream.flarebot.flarebot.util.general.GeneralUtils;
import stream.flarebot.flarebot.util.general.GuildUtils;
import stream.flarebot.flarebot.util.general.VariableUtils;
import java.time.Instant;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull; | package stream.flarebot.flarebot;
public class ModlogEvents implements EventListener {
private long roleResponseNumber = 0;
private long guildResponseNumber = 0;
@Override
public void onEvent(Event event) {
if (!(event instanceof GenericGuildEvent)
&& !(event instanceof GenericRoleEvent)
&& !(event instanceof GenericTextChannelEvent)
&& !(event instanceof GenericVoiceChannelEvent)
&& !(event instanceof GenericMessageEvent))
return;
Guild g = null;
if (event instanceof GenericGuildEvent && ((GenericGuildEvent) event).getGuild() != null)
g = ((GenericGuildEvent) event).getGuild();
else if (event instanceof GenericRoleEvent && ((GenericRoleEvent) event).getGuild() != null)
g = ((GenericRoleEvent) event).getGuild();
else if (event instanceof GenericTextChannelEvent && ((GenericTextChannelEvent) event).getGuild() != null)
g = ((GenericTextChannelEvent) event).getGuild();
else if (event instanceof GenericVoiceChannelEvent && ((GenericVoiceChannelEvent) event).getGuild() != null)
g = ((GenericVoiceChannelEvent) event).getGuild();
else if (event instanceof GenericMessageEvent && ((GenericMessageEvent) event).getGuild() != null)
g = ((GenericMessageEvent) event).getGuild();
if (g == null)
return;
GuildWrapper guildWrapper = FlareBotManager.instance().getGuild(g.getId());
if (guildWrapper == null)
return;
// GUILD
if (event instanceof GuildBanEvent)
onGuildBan((GuildBanEvent) event, guildWrapper);
else if (event instanceof GuildMemberJoinEvent)
onGuildMemberJoin((GuildMemberJoinEvent) event, guildWrapper);
else if (event instanceof GuildMemberLeaveEvent)
onGuildMemberLeave((GuildMemberLeaveEvent) event, guildWrapper);
else if (event instanceof GuildVoiceJoinEvent)
onGuildVoiceJoin((GuildVoiceJoinEvent) event, guildWrapper);
else if (event instanceof GuildVoiceLeaveEvent)
onGuildVoiceLeave((GuildVoiceLeaveEvent) event, guildWrapper);
// ROLES
else if (event instanceof RoleCreateEvent)
onRoleCreate((RoleCreateEvent) event, guildWrapper);
else if (event instanceof RoleDeleteEvent)
onRoleDelete((RoleDeleteEvent) event, guildWrapper);
else if (event instanceof GenericRoleUpdateEvent)
onGenericRoleUpdate((GenericRoleUpdateEvent) event, guildWrapper);
else if (event instanceof GuildMemberRoleAddEvent)
onGuildMemberRoleAdd((GuildMemberRoleAddEvent) event, guildWrapper);
else if (event instanceof GuildMemberRoleRemoveEvent)
onGuildMemberRoleRemove((GuildMemberRoleRemoveEvent) event, guildWrapper);
// CHANNEL
else if (event instanceof TextChannelCreateEvent)
onTextChannelCreate((TextChannelCreateEvent) event, guildWrapper);
else if (event instanceof VoiceChannelCreateEvent)
onVoiceChannelCreate((VoiceChannelCreateEvent) event, guildWrapper);
else if (event instanceof TextChannelDeleteEvent)
onTextChannelDelete((TextChannelDeleteEvent) event, guildWrapper);
else if (event instanceof VoiceChannelDeleteEvent)
onVoiceChannelDelete((VoiceChannelDeleteEvent) event, guildWrapper);
// MESSAGES
/*else if (event instanceof GuildMessageReceivedEvent)
onGuildMessageReceived((GuildMessageReceivedEvent) event, guildWrapper);*/
else if (event instanceof MessageUpdateEvent)
onMessageUpdate((MessageUpdateEvent) event, guildWrapper);
else if (event instanceof MessageDeleteEvent)
onMessageDelete((MessageDeleteEvent) event, guildWrapper);
// GUILD
else if (event instanceof GuildUpdateExplicitContentLevelEvent)
onGuildUpdateExplicitContentLevel((GuildUpdateExplicitContentLevelEvent) event, guildWrapper);
else if (event instanceof GuildMemberNickChangeEvent)
onGuildMemberNickChange((GuildMemberNickChangeEvent) event, guildWrapper);
else if (event instanceof GenericGuildUpdateEvent)
onGenericGuildUpdate((GenericGuildUpdateEvent) event, guildWrapper);
else if (event instanceof GuildVoiceMoveEvent)
onGuildVoiceMove((GuildVoiceMoveEvent) event, guildWrapper);
}
private void onGuildBan(GuildBanEvent event, @Nonnull GuildWrapper wrapper) {
if (cannotHandle(wrapper, ModlogEvent.USER_BANNED)) return;
event.getGuild().getAuditLogs().limit(1).type(ActionType.BAN).queue(auditLogEntries -> {
AuditLogEntry entry = auditLogEntries.get(0);
// We don't want dupes.
if (entry.getUser().getIdLong() == FlareBot.instance().getClient().getSelfUser().getIdLong()) return;
boolean validEntry = entry.getTargetId().equals(event.getUser().getId()); | ModlogHandler.getInstance().postToModlog(wrapper, ModlogEvent.USER_BANNED, event.getUser(), | 3 |
comodoro/FractalZoo | app/src/main/java/com/draabek/fractal/canvas/FractalCpuView.java | [
"public interface FractalViewWrapper {\n void saveBitmap();\n void setVisibility(int visibility);\n boolean isRendering();\n void setRenderListener(RenderListener renderListener);\n void clear();\n}",
"public interface RenderListener {\n void onRenderRequested();\n void onRenderComplete(long ... | import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;
import com.draabek.fractal.fractal.FractalViewWrapper;
import com.draabek.fractal.R;
import com.draabek.fractal.fractal.RenderListener;
import com.draabek.fractal.activity.SaveBitmapActivity;
import com.draabek.fractal.util.Utils;
import com.draabek.fractal.fractal.FractalRegistry;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; | package com.draabek.fractal.canvas;
@SuppressWarnings("SynchronizeOnNonFinalField")
public class FractalCpuView extends SurfaceView implements SurfaceHolder.Callback, FractalViewWrapper
//,GestureDetector.OnDoubleTapListener, GestureDetector.OnGestureListener
{
private static final String LOG_KEY = FractalCpuView.class.getName();
private Bitmap fractalBitmap;
private CpuFractal fractal;
private RectF position;
private RectF oldPosition;
private Paint paint;
private Canvas bufferCanvas = null;
private SurfaceHolder holder;
private SharedPreferences prefs;
private boolean rendering;
private RenderListener renderListener;
public FractalCpuView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public FractalCpuView(Context context) {
super(context);
init(context);
}
private void init(Context context) {
holder = getHolder();
holder.addCallback(this);
this.setOnTouchListener(new MotionTracker());
paint = new Paint();
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
@Override
protected void onDraw(Canvas canvas) {
rendering = true;
if (renderListener != null) {
this.renderListener.onRenderRequested();
}
long start = System.currentTimeMillis();
Log.d(LOG_KEY,"onDraw");
this.holder = getHolder();
synchronized (this.holder) {
if ((fractalBitmap == null) || (fractalBitmap.getHeight() != canvas.getHeight()) ||
(fractalBitmap.getWidth() != canvas.getWidth()) || (bufferCanvas == null)) {
Log.v(LOG_KEY, "Reallocate buffer");
fractalBitmap = Bitmap.createBitmap(getWidth(), getHeight(),
Bitmap.Config.ARGB_8888);
bufferCanvas = new Canvas(fractalBitmap);
}
if (fractal instanceof BitmapDrawFractal) {
Log.v(LOG_KEY, "Start drawing to buffer");
fractalBitmap = ((BitmapDrawFractal)fractal).redrawBitmap(fractalBitmap, position);
} else if (fractal instanceof CanvasFractal) {
Log.v(LOG_KEY, "Draw to canvas");
((CanvasFractal)fractal).draw(bufferCanvas);
} else {
throw new RuntimeException("Wrong fractal type for " + this.getClass().getName());
}
canvas.drawBitmap(fractalBitmap, 0, 0, paint);
}
Log.d(LOG_KEY, "finished onDraw");
rendering = false;
if (renderListener != null) {
renderListener.onRenderComplete(System.currentTimeMillis() - start);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
this.holder = holder;
Log.d(LOG_KEY,"surface changed");
fractal = (CpuFractal) FractalRegistry.getInstance().getCurrent();
invalidate();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
setWillNotDraw(false);
Log.d(LOG_KEY,"surface created");
fractalBitmap = Bitmap.createBitmap(getWidth(), getHeight(),
Bitmap.Config.ARGB_8888);
position = new RectF(1, -2, -1, 1);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(LOG_KEY, "surface destroyed");
bufferCanvas = null;
fractalBitmap = null;
//consider apply instead of commit | prefs.edit().putString(Utils.PREFS_CURRENT_FRACTAL_KEY, FractalRegistry.getInstance().getCurrent().getName()).apply(); | 3 |
schnatterer/nusic | nusic-core-android/src/main/java/info/schnatterer/nusic/core/impl/RemoteMusicDatabaseServiceMusicBrainz.java | [
"public interface RemoteMusicDatabaseService {\n\n /**\n * Finds releases by artist.\n * \n * @param artist\n * the artist to query releases for.\n * @param fromDate\n * the lower boundary of the time range in which release were\n * published\n * @... | import fm.last.musicbrainz.coverart.CoverArt;
import fm.last.musicbrainz.coverart.CoverArtArchiveClient;
import fm.last.musicbrainz.coverart.CoverArtImage;
import fm.last.musicbrainz.coverart.impl.DefaultCoverArtArchiveClient;
import info.schnatterer.nusic.core.RemoteMusicDatabaseService;
import info.schnatterer.nusic.core.ServiceException;
import info.schnatterer.nusic.core.i18n.CoreMessageKey;
import info.schnatterer.nusic.data.DatabaseException;
import info.schnatterer.nusic.data.dao.ArtworkDao;
import info.schnatterer.nusic.data.dao.ArtworkDao.ArtworkType;
import info.schnatterer.nusic.data.model.Artist;
import info.schnatterer.nusic.data.model.Release;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import javax.inject.Inject;
import org.musicbrainz.MBWS2Exception;
import org.musicbrainz.model.ArtistCreditWs2;
import org.musicbrainz.model.NameCreditWs2;
import org.musicbrainz.model.entity.ReleaseWs2;
import org.musicbrainz.model.searchresult.ReleaseResultWs2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.RateLimiter;
import com.google.inject.BindingAnnotation; | /**
* Copyright (C) 2013 Johannes Schnatterer
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This file is part of nusic.
*
* nusic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nusic is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with nusic. If not, see <http://www.gnu.org/licenses/>.
*/
package info.schnatterer.nusic.core.impl;
/**
* {@link RemoteMusicDatabaseService} that queries information from MusicBrainz.
*
* @author schnatterer
*
*/
public class RemoteMusicDatabaseServiceMusicBrainz implements
RemoteMusicDatabaseService {
private static final Logger LOG = LoggerFactory
.getLogger(RemoteMusicDatabaseServiceMusicBrainz.class);
/**
* See http://musicbrainz.org/doc/Development/XML_Web_Service/Version_2#
* Release_Type_and_Status
*/
private static final String SEARCH_BASE = "type:album";
private static final String SEARCH_DATE_BASE = " AND date:[";
private static final String SEARCH_DATE_TO = " TO ";
// 2019/07: "?" seems to no longer work, results in a huge number of results
private static final String SEARCH_DATE_OPEN_END = "9999-12-31";
private static final String SEARCH_DATE_FINAL = "]";
private static final String SEARCH_ARTIST_1 = " AND artist:\"";
private static final String SEARCH_ARTIST_2 = "\"";
/**
* MusicBrainz allows at max 22 requests in 20 seconds. However, we still
* get 503s then. Try 1 request per second.
*/
private static final double PERMITS_PER_SECOND = 1.0;
private final RateLimiter rateLimiter = RateLimiter
.create(PERMITS_PER_SECOND);
private CoverArtArchiveClient client = new DefaultCoverArtArchiveClient();
/** Application name used in user agent string of request. */
private String appName;
/** Application version used in user agent string of request. */
private String appVersion;
/**
* Contact URL or author email used in user agent string of request.
*/
private String appContact;
@Inject
private ArtworkDao artworkDao;
/**
* Creates a service instance for finding releases.
*
* @param appName
* application name used in user agent string of request
*
* @param appVersion
* application version used in user agent string of request
*
* @param appContact
* contact URL or author email used in user agent string of
* request
*/
@Inject
public RemoteMusicDatabaseServiceMusicBrainz(
@ApplicationName String appName,
@ApplicationVersion String appVersion,
@ApplicationContact String appContact) {
this.appName = appName;
this.appVersion = appVersion;
this.appContact = appContact;
}
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
@Override
public Artist findReleases(Artist artist, Date fromDate, Date endDate)
throws ServiceException {
if (artist == null || artist.getArtistName() == null) {
return null;
}
String artistName = artist.getArtistName();
Map<String, Release> releases = new HashMap<String, Release>();
try {
// List<ReleaseResultWs2> releaseResults = findReleases();
org.musicbrainz.controller.Release releaseSearch = createReleaseSearch(
appName, appVersion, appContact);
releaseSearch.search(appendDate(fromDate, endDate,
new StringBuffer(SEARCH_BASE)).append(SEARCH_ARTIST_1)
.append(artistName).append(SEARCH_ARTIST_2).toString());
// Limit request rate to avoid server bans
rateLimiter.acquire();
processReleaseResults(artistName, artist, releases,
releaseSearch.getFirstSearchResultPage());
while (releaseSearch.hasMore()) {
// TODO check if internet connection still there?
// Limit request rate to avoid server bans
rateLimiter.acquire();
processReleaseResults(artistName, artist, releases,
releaseSearch.getNextSearchResultPage());
}
} catch (MBWS2Exception mBWS2Exception) {
throw new AndroidServiceException( | CoreMessageKey.ERROR_QUERYING_MUSIC_BRAINZ, mBWS2Exception, | 2 |
Skyost/SkyDocs | src/main/java/fr/skyost/skydocs/frame/ProjectsFrame.java | [
"public class Constants {\n\t\n\t/**\n\t * ==============\n\t * APP PROPERTIES\n\t * ==============\n\t */\n\t\n\t/**\n\t * App's name.\n\t */\n\t\n\tpublic static final String APP_NAME = \"SkyDocs\";\n\n\t/**\n\t * App's state.\n\t */\n\n\tpublic static final String APP_STATE = \"Beta\";\n\t\n\t/**\n\t * App's ver... | import com.google.common.io.Files;
import fr.skyost.skydocs.Constants;
import fr.skyost.skydocs.DocsRunnable;
import fr.skyost.skydocs.command.BuildCommand;
import fr.skyost.skydocs.command.NewCommand;
import fr.skyost.skydocs.command.ServeCommand;
import fr.skyost.skydocs.utils.GithubUpdater;
import fr.skyost.skydocs.utils.GithubUpdater.GithubUpdaterResultListener;
import fr.skyost.skydocs.utils.Utils;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List; | });
this.pack();
this.setLocationRelativeTo(null);
}
@Override
public final void onRunnableStarted(final DocsRunnable runnable) {
if(runnable instanceof NewCommand) {
createProjectButton.setEnabled(false);
buildProjectButton.setEnabled(false);
serveProjectButton.setEnabled(false);
}
else if(runnable instanceof BuildCommand) {
createProjectButton.setEnabled(false);
buildProjectButton.setText(Constants.GUI_BUTTON_STOP);
serveProjectButton.setEnabled(false);
}
else {
createProjectButton.setEnabled(false);
buildProjectButton.setEnabled(false);
serveProjectButton.setText(Constants.GUI_BUTTON_STOP);
}
removeProjectButton.setEnabled(false);
}
@Override
public final void onRunnableFinished(final DocsRunnable runnable) {
final int index = projectsList.getSelectedIndex();
final boolean enabled = 0 <= index && index < projectsModel.size();
if(runnable instanceof NewCommand) {
newCommand = null;
projectsModel.addElement(((NewCommand)runnable).getArguments().directory);
createProjectButton.setEnabled(true);
buildProjectButton.setEnabled(enabled);
serveProjectButton.setEnabled(enabled);
}
else if(runnable instanceof BuildCommand) {
buildCommand = null;
createProjectButton.setEnabled(true);
buildProjectButton.setText(Constants.GUI_BUTTON_BUILD);
serveProjectButton.setEnabled(enabled);
}
else {
serveCommand = null;
createProjectButton.setEnabled(true);
buildProjectButton.setEnabled(enabled);
serveProjectButton.setText(Constants.GUI_BUTTON_SERVE);
}
removeProjectButton.setEnabled(true);
runnable.blankLine();
logTextArea.setCaretPosition(logTextArea.getText().length());
}
@Override
public final void onRunnableError(final DocsRunnable runnable, final Throwable error) {
JOptionPane.showMessageDialog(this, String.format(Constants.GUI_DIALOG_ERROR_MESSAGE, error.getMessage()), error.getClass().getName(), JOptionPane.ERROR_MESSAGE);
}
@Override
public final void updaterStarted() {}
@Override
public final void updaterException(final Exception ex) {}
@Override
public final void updaterResponse(final String response) {}
@Override
public final void updaterUpdateAvailable(final String localVersion, final String remoteVersion) {
final String link = "https://github.com/" + GithubUpdater.UPDATER_GITHUB_USERNAME + "/" + GithubUpdater.UPDATER_GITHUB_REPO + "/releases/latest";
if(JOptionPane.showConfirmDialog(this, "<html>An update is available : v" + remoteVersion + " !<br/>" + "Would you like to visit " + link + " to download it ?</html>", Constants.APP_NAME, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
try {
if(Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI(link));
}
}
catch(final Exception ex) {
ex.printStackTrace(guiPrintStream);
ex.printStackTrace();
JOptionPane.showMessageDialog(ProjectsFrame.this, String.format(Constants.GUI_DIALOG_ERROR_MESSAGE, ex.getMessage()), ex.getClass().getName(), JOptionPane.ERROR_MESSAGE);
}
}
}
@Override
public final void updaterNoUpdate(final String localVersion, final String remoteVersion) {}
/**
* Builds a list of icons to use with Swing.
*
* @return A list of icons to use with Swing.
*/
private List<Image> buildIconsList() {
final Image icon = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(Constants.RESOURCE_PROJECT_ICON));
return Arrays.asList(
icon.getScaledInstance(16, 16, Image.SCALE_SMOOTH),
icon.getScaledInstance(32, 32, Image.SCALE_SMOOTH),
icon.getScaledInstance(64, 64, Image.SCALE_SMOOTH),
icon.getScaledInstance(128, 128, Image.SCALE_SMOOTH),
icon.getScaledInstance(256, 256, Image.SCALE_SMOOTH),
icon//.getScaledInstance(512, 512, Image.SCALE_SMOOTH) // Already in 512x512.
);
}
/**
* Checks for updates.
*/
public final void checkForUpdates() {
new GithubUpdater(Constants.APP_VERSION.split(" ")[0].substring(1), this).start();
}
/**
* Loads projects from the history.
*/
public final void loadHistory() {
try { | final File history = new File(Utils.getParentFolder(), Constants.FILE_GUI_HISTORY); | 7 |
cvbrandoe/REDEN | src/fr/lip6/reden/ldextractor/per/QueryAuthorBNF.java | [
"public class QuerySource implements QuerySourceInterface {\n\n\t/**\n\t * Prepare the SPARQL statement. Children must implement their own queries.\n\t * \n\t * @param domain\n\t * configuration\n\t * @param firstleter,\n\t * optional filtering for queries\n\t * @return\n\t */\n\tpublic Query ... | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import com.opencsv.CSVWriter;
import fr.lip6.reden.ldextractor.QuerySource;
import fr.lip6.reden.ldextractor.QuerySourceInterface;
import fr.lip6.reden.ldextractor.SpatialExtent;
import fr.lip6.reden.ldextractor.TemporalExtent;
import fr.lip6.reden.ldextractor.TopicExtent; | package fr.lip6.reden.ldextractor.per;
/**
* This class queries the authors catalog in the BnF SPARQL end point.
*
* @author Brando & Frontini
*/
public class QueryAuthorBNF extends QuerySource implements QuerySourceInterface {
private static Logger logger = Logger.getLogger(QueryAuthorBNF.class);
/**
* Mandatory fields
*/
public String SPARQL_END_POINT = "http://data.bnf.fr/sparql";
public Integer TIMEOUT = 200000;
public Boolean LARGE_REPO = true;
public String prefixDictionnaireFile = "authorBNF";
/**
* Default constructor.
*/
public QueryAuthorBNF () {
super();
}
/**
* Formulate a query which is decomposed in several sub-queries because of size of the BnF repo.
*
*/
@Override | public Query formulateSPARQLQuery(List<TopicExtent> domainParams, | 4 |
mosmetro-android/mosmetro-android | app/src/main/java/pw/thedrhax/mosmetro/updater/UpdateChecker.java | [
"public class SafeViewActivity extends Activity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n if (!getIntent().hasExtra(\"data\")) {\n finish(); return;\n }\n\n Uri data = Uri.parse(getIntent().getStringExt... | import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.preference.PreferenceManager;
import android.widget.Toast;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import pw.thedrhax.mosmetro.BuildConfig;
import pw.thedrhax.mosmetro.R;
import pw.thedrhax.mosmetro.activities.SafeViewActivity;
import pw.thedrhax.mosmetro.httpclient.CachedRetriever;
import pw.thedrhax.util.Logger;
import pw.thedrhax.util.UUID;
import pw.thedrhax.util.Version; | /**
* Wi-Fi в метро (pw.thedrhax.mosmetro, Moscow Wi-Fi autologin)
* Copyright © 2015 Dmitry Karikh <the.dr.hax@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pw.thedrhax.mosmetro.updater;
public class UpdateChecker {
// Info from the app
private final Context context;
private final DownloadManager dm;
private final SharedPreferences settings; | private final CachedRetriever retriever; | 1 |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/routing/Router.java | [
"public interface ApiService {\n @GET(\"/v1/planner/\")\n void getPlan(\n @Query(\"from\") PlaceQuery from,\n @Query(\"to\") PlaceQuery to,\n @Query(\"mode\") String mode,\n @Query(\"alternative\") boolean alternative,\n @Query(\"via\") PlaceQuery via,\n ... | import retrofit.RetrofitError;
import retrofit.client.Response;
import androidx.annotation.Nullable;
import android.util.Log;
import com.markupartist.sthlmtraveling.data.api.ApiService;
import com.markupartist.sthlmtraveling.data.api.PlaceQuery;
import com.markupartist.sthlmtraveling.data.api.TravelModeQuery;
import com.markupartist.sthlmtraveling.data.models.Plan;
import com.markupartist.sthlmtraveling.data.models.TravelMode;
import com.markupartist.sthlmtraveling.provider.planner.JourneyQuery;
import com.markupartist.sthlmtraveling.utils.DateTimeUtil;
import com.markupartist.sthlmtraveling.utils.LegUtil;
import java.util.List; | /*
* Copyright (C) 2009-2015 Johan Nilsson <http://markupartist.com>
*
* 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.markupartist.sthlmtraveling.provider.routing;
/**
*
*/
public class Router {
private static final String TAG = "Router";
private final ApiService apiService;
public Router(ApiService apiService) {
this.apiService = apiService;
}
public void plan(final JourneyQuery journeyQuery, final Callback callback) {
if (!journeyQuery.origin.hasLocation() || !journeyQuery.destination.hasLocation()) {
Log.w(TAG, "Origin and or destination is missing location data");
callback.onPlan(null);
return;
}
PlaceQuery from = new PlaceQuery.Builder()
.location(journeyQuery.origin.getName(), journeyQuery.origin.getLocation())
.build();
PlaceQuery to = new PlaceQuery.Builder()
.location(journeyQuery.destination.getName(), journeyQuery.destination.getLocation())
.build();
PlaceQuery via = null;
if (journeyQuery.hasVia() && journeyQuery.via.hasLocation()) {
via = new PlaceQuery.Builder()
.location(journeyQuery.via.getName(), journeyQuery.via.getLocation())
.build();
} else {
Log.i(TAG, "Location data not present on via point");
}
apiService.getPlan(from, to, "foot,bike,car", false, via,
!journeyQuery.isTimeDeparture, null, null, null, null, new retrofit.Callback<Plan>() {
@Override
public void success(Plan plan, Response response) {
callback.onPlan(plan);
}
@Override
public void failure(RetrofitError error) {
Log.w(TAG, "Could not fetch a route for foot, bike and car.");
callback.onPlanError(journeyQuery, null);
}
});
}
public void refreshTransit(final JourneyQuery journeyQuery, final Callback callback) {
planTransit(journeyQuery, callback, journeyQuery.previousIdent, journeyQuery.previousDir);
}
public void planTransit(final JourneyQuery journeyQuery, final Callback callback) {
planTransit(journeyQuery, callback, null);
}
public void planTransit(final JourneyQuery journeyQuery,
final Callback callback,
final @Nullable ScrollDir dir) {
String direction = dir != null ? dir.getDirection() : null;
journeyQuery.previousDir = direction;
journeyQuery.previousIdent = journeyQuery.ident;
planTransit(journeyQuery, callback, journeyQuery.ident, direction);
}
public void planTransit(final JourneyQuery journeyQuery,
final Callback callback,
final String ident,
final @Nullable String dir) {
PlaceQuery from = new PlaceQuery.Builder()
.place(journeyQuery.origin.asPlace())
.build();
PlaceQuery to = new PlaceQuery.Builder()
.place(journeyQuery.destination.asPlace())
.build();
PlaceQuery via = null;
if (journeyQuery.hasVia()) {
via = new PlaceQuery.Builder()
.place(journeyQuery.via.asPlace())
.build();
}
| List<TravelMode> travelModes = LegUtil.transportModesToTravelModes( | 4 |
petitparser/java-petitparser | petitparser-xml/src/test/java/org/petitparser/grammar/xml/XmlParserTest.java | [
"public class XmlAttribute extends XmlNode {\n\n private final XmlName name;\n private final String value;\n\n public XmlAttribute(XmlName name, String value) {\n this.name = name;\n this.value = value;\n }\n\n public XmlName getName() {\n return name;\n }\n\n public String getValue() {\n return ... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.petitparser.grammar.xml.ast.XmlAttribute;
import org.petitparser.grammar.xml.ast.XmlDocument;
import org.petitparser.grammar.xml.ast.XmlElement;
import org.petitparser.grammar.xml.ast.XmlName;
import org.petitparser.grammar.xml.ast.XmlNode;
import org.petitparser.parser.Parser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects; | + " <xsd:element name=\"USPrice\" type=\"xsd:decimal\"/>\n"
+ " <xsd:element ref=\"comment\" minOccurs=\"0\"/>\n"
+ " <xsd:element name=\"shipDate\" type=\"xsd:date\" minOccurs=\"0\"/>\n"
+ " </xsd:sequence>\n"
+ " <xsd:attribute name=\"partNum\" type=\"SKU\" use=\"required\"/>\n"
+ " </xsd:complexType>\n" + " </xsd:element>\n"
+ " </xsd:sequence>\n" + " </xsd:complexType>\n" + "\n"
+ " <!-- Stock Keeping Unit, a code for identifying products -->\n"
+ " <xsd:simpleType name=\"SKU\">\n"
+ " <xsd:restriction base=\"xsd:string\">\n"
+ " <xsd:pattern value=\"\\d{3}-[A-Z]{2}\"/>\n"
+ " </xsd:restriction>\n" + " </xsd:simpleType>\n" + "\n"
+ "</xsd:schema>");
}
@Test
public void testAtom() {
assertParseInvariant("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<app:service>"
+ "<app:workspace>"
+
"<cmisra:repositoryInfo xmlns:ns3=\"http://docs.oasis-open.org/ns/cmis/messaging/200908/\">"
+ "</cmisra:repositoryInfo>"
+ "</app:workspace>"
+ "</app:service>");
}
private void assertParseInvariant(String input) {
XmlNode tree = parser.parse(input).get();
XmlNode other = parser.parse(tree.toXmlString()).get();
assertEquals(tree.toXmlString(), other.toXmlString());
assertEquals(tree, other);
assertInvariants(tree);
}
private void assertInvariants(XmlNode anXmlNode) {
assertEquivalentInvariant(anXmlNode);
assertDocumentInvariant(anXmlNode);
assertParentInvariant(anXmlNode);
assertForwardInvariant(anXmlNode);
assertBackwardInvariant(anXmlNode);
assertNameInvariant(anXmlNode);
assertAttributeInvariant(anXmlNode);
}
private void assertEquivalentInvariant(XmlNode anXmlNode) {
for (XmlNode node : anXmlNode) {
assertEquals(node, node);
assertEquals(node.hashCode(), node.hashCode());
assertFalse(Objects.equals(node, node.getParent()));
for (XmlNode child : node.getChildren()) {
assertFalse(Objects.equals(node, child));
}
for (XmlNode child : node.getAttributes()) {
assertFalse(Objects.equals(node, child));
}
}
}
private void assertDocumentInvariant(XmlNode anXmlNode) {
XmlNode root = anXmlNode.getRoot();
for (XmlNode child : anXmlNode) {
assertSame(child.getRoot(), root);
assertSame(child.getDocument(), root);
}
XmlDocument document = (XmlDocument) anXmlNode;
assertTrue(document.getChildren().contains(document.getRootElement()));
}
private void assertParentInvariant(XmlNode anXmlNode) {
for (XmlNode node : anXmlNode) {
if (node instanceof XmlDocument) {
assertNull(node.getParent());
}
for (XmlNode child : node.getChildren()) {
assertSame(node, child.getParent());
}
for (XmlNode attribute : node.getAttributes()) {
assertSame(node, attribute.getParent());
}
}
}
private void assertForwardInvariant(XmlNode anXmlNode) {
for (XmlNode node : anXmlNode) {
XmlNode current = node.getFirstChild();
List<XmlNode> children = new ArrayList<>(node.getChildren());
while (current != null) {
assertSame(current, children.remove(0));
current = current.getNextSibling();
}
assertTrue(children.isEmpty());
}
}
private void assertBackwardInvariant(XmlNode anXmlNode) {
for (XmlNode node : anXmlNode) {
XmlNode current = node.getLastChild();
List<XmlNode> children = new ArrayList<>(node.getChildren());
while (current != null) {
assertSame(current, children.remove(children.size() - 1));
current = current.getPreviousSibling();
}
assertTrue(children.isEmpty());
}
}
private void assertNameInvariant(XmlNode anXmlNode) {
for (XmlNode node : anXmlNode) {
if (node instanceof XmlElement) {
XmlElement element = (XmlElement) node;
assertNameInvariant(element.getName());
}
if (node instanceof XmlAttribute) {
XmlAttribute attribute = (XmlAttribute) node;
assertNameInvariant(attribute.getName());
}
}
}
| private void assertNameInvariant(XmlName anXmlName) { | 3 |
saiba/OpenBMLParser | test/src/saiba/bml/builder/BehaviourBlockBuilderTest.java | [
"public interface BMLBehaviorAttributeExtension\n{\n /**\n * Decodes the attributes in attrMap. Once decoded, they should be removed from attrMap. The easiest way to do this is using\n * bb.getRequiredAttribute, bb.getOptionalAttribute, etc.\n * \n */\n void decodeAttributes(BehaviourBlock bb,... | import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import hmi.xml.XMLFormatting;
import hmi.xml.XMLStructureAdapter;
import hmi.xml.XMLTokenizer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import lombok.Getter;
import lombok.Setter;
import org.junit.Test;
import saiba.bml.core.BMLBehaviorAttributeExtension;
import saiba.bml.core.BMLBlockComposition;
import saiba.bml.core.BehaviourBlock;
import saiba.bml.core.CoreComposition;
import saiba.bml.core.Mode;
import saiba.bml.core.OffsetDirection;
import saiba.bml.core.SpeechBehaviour;
import saiba.bml.core.ext.FaceFacsBehaviour.Side;
import saiba.bml.parser.BMLParser; | package saiba.bml.builder;
/**
* Unit tests for the BehaviourBlockBuilder
* @author hvanwelbergen
*
*/
public class BehaviourBlockBuilderTest
{
private static final double PARAM_PRECISION = 0.001;
private BehaviourBlockBuilder builder = new BehaviourBlockBuilder();
@Test
public void buildEmptyBlock()
{
BehaviourBlock bb = builder.build();
assertNotNull(bb.id);
assertEquals(CoreComposition.MERGE, bb.getComposition());
}
@Test
public void checkDefaultCompositionOutput()
{
BehaviourBlock bbOut = builder.build();
StringBuilder buf = new StringBuilder();
bbOut.appendXML(buf);
BehaviourBlock bbIn = new BehaviourBlock();
bbIn.readXML(buf.toString()); | BMLParser parser = new BMLParser(); | 8 |
jachness/blockcalls | app/src/androidTest/java/com/jachness/blockcalls/services/ContactCheckerTest.java | [
"public abstract class AndroidTest {\n private Context targetContext;\n private AllComponentTest component;\n private AppPreferences appPreferences;\n private Context context;\n\n protected void setUp() throws Exception {\n targetContext = InstrumentationRegistry.getTargetContext();\n c... | import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.OperationApplicationException;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import com.google.i18n.phonenumbers.NumberParseException;
import com.jachness.blockcalls.AndroidTest;
import com.jachness.blockcalls.db.dao.ContactDAO;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
import com.jachness.blockcalls.stuff.AppPreferences;
import com.jachness.blockcalls.stuff.BlockOrigin;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject; | package com.jachness.blockcalls.services;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class ContactCheckerTest extends AndroidTest {
private static final String TAG = ContactCheckerTest.class.getSimpleName();
@Inject
ContactChecker checker;
@Inject
| ContactDAO contactDAO; | 1 |
domax/gwt-dynamic-plugins | gwt-dynamic-main/gwt-dynamic-host/src/main/java/org/gwt/dynamic/host/client/features/ModuleInfoFeatureConsumer.java | [
"public static native String toStringJSO(JavaScriptObject jso) /*-{\n\treturn JSON.stringify(jso);\n}-*/;",
"public interface FeatureCommonConst {\n\n\tString MODULE_HOST = \"gwt-dynamic-host\";\n\t\n\tString FEATURE_MODULE_READY = \"moduleReady\";\n\tString FEATURE_BUSY = \"busy\";\n\tString FEATURE_NAVIGATOR_IT... | import static org.gwt.dynamic.common.client.util.JsUtils.toStringJSO;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.gwt.dynamic.common.client.features.FeatureCommonConst;
import org.gwt.dynamic.common.client.features.FeatureConsumer;
import org.gwt.dynamic.common.client.jso.ModuleInfo;
import org.gwt.dynamic.common.client.util.BatchRunner;
import org.gwt.dynamic.common.client.util.BatchRunner.CommandSimple;
import org.gwt.dynamic.host.shared.ModuleBean;
import com.google.gwt.user.client.rpc.AsyncCallback; | /*
* Copyright 2014 Maxim Dominichenko
*
* Licensed under The MIT License (MIT) (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* https://github.com/domax/gwt-dynamic-plugins/blob/master/LICENSE
*
* 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.gwt.dynamic.host.client.features;
public class ModuleInfoFeatureConsumer extends FeatureConsumer<Void, ModuleInfo> implements FeatureCommonConst {
private static final Logger LOG = Logger.getLogger(ModuleInfoFeatureConsumer.class.getName());
private final List<ModuleBean> modules;
private final List<ModuleInfo> navigatorItems = new ArrayList<ModuleInfo>();
private String moduleName;
| private class ItemCommand extends CommandSimple { | 5 |
SergioDim3nsions/RealmContactsForAndroid | presentation/src/main/java/sergio/vasco/androidforexample/presentation/sections/main/MainPresenter.java | [
"public interface Bus {\n void post(Object object);\n void postInmediate(Object object);\n void register(Object object);\n void unregister(Object object);\n}",
"public interface InteractorInvoker {\n void execute(Interactor interactor);\n void execute(Interactor interactor, InteractorPriority priority);\n}"... | import java.util.List;
import sergio.vasco.androidforexample.domain.abstractions.Bus;
import sergio.vasco.androidforexample.domain.interactors.InteractorInvoker;
import sergio.vasco.androidforexample.domain.interactors.main.GetContactsFromDataBaseInteractor;
import sergio.vasco.androidforexample.domain.interactors.main.InsertContactsIntoDataBaseInteractor;
import sergio.vasco.androidforexample.domain.interactors.main.events.GetContactsEvent;
import sergio.vasco.androidforexample.domain.model.Contact;
import sergio.vasco.androidforexample.presentation.Presenter;
import sergio.vasco.androidforexample.presentation.mappers.PresentationContactMapper;
import sergio.vasco.androidforexample.presentation.model.PresentationContact; | package sergio.vasco.androidforexample.presentation.sections.main;
/**
* Name: Sergio Vasco
* Date: 14/1/16.
*/
public class MainPresenter extends Presenter {
private MainView view;
private Bus bus;
private InteractorInvoker interactorInvoker;
private InsertContactsIntoDataBaseInteractor insertContactsIntoDataBaseInteractor;
private GetContactsFromDataBaseInteractor getContactsFromDataBaseInteractor;
private PresentationContactMapper presentationContactMapper;
public MainPresenter(MainView view, Bus bus, InteractorInvoker interactorInvoker,
InsertContactsIntoDataBaseInteractor insertContactsIntoDataBaseInteractor,
GetContactsFromDataBaseInteractor getContactsFromDataBaseInteractor, PresentationContactMapper presentationContactMapper) {
this.view = view;
this.bus = bus;
this.interactorInvoker = interactorInvoker;
this.insertContactsIntoDataBaseInteractor = insertContactsIntoDataBaseInteractor;
this.getContactsFromDataBaseInteractor = getContactsFromDataBaseInteractor;
this.presentationContactMapper = presentationContactMapper;
}
public void insertContactIntoDataBase(PresentationContact presentationContact) { | Contact contact = presentationContactMapper.presentationContactToContact(presentationContact); | 5 |
sheimi/SGit | src/main/java/me/sheimi/sgit/activities/delegate/RepoOperationDelegate.java | [
"public class FsUtils {\n\n public static final SimpleDateFormat TIMESTAMP_FORMATTER = new SimpleDateFormat(\n \"yyyyMMdd_HHmmss\", Locale.getDefault());\n public static final String TEMP_DIR = \"temp\";\n private static final String LOGTAG = FsUtils.class.getSimpleName();\n\n private FsUtils... | import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import me.sheimi.android.utils.FsUtils;
import me.sheimi.sgit.activities.RepoDetailActivity;
import me.sheimi.sgit.activities.delegate.actions.AddAllAction;
import me.sheimi.sgit.activities.delegate.actions.AddRemoteAction;
import me.sheimi.sgit.activities.delegate.actions.CherryPickAction;
import me.sheimi.sgit.activities.delegate.actions.CommitAction;
import me.sheimi.sgit.activities.delegate.actions.ConfigAction;
import me.sheimi.sgit.activities.delegate.actions.DeleteAction;
import me.sheimi.sgit.activities.delegate.actions.DiffAction;
import me.sheimi.sgit.activities.delegate.actions.FetchAction;
import me.sheimi.sgit.activities.delegate.actions.MergeAction;
import me.sheimi.sgit.activities.delegate.actions.NewBranchAction;
import me.sheimi.sgit.activities.delegate.actions.NewDirAction;
import me.sheimi.sgit.activities.delegate.actions.NewFileAction;
import me.sheimi.sgit.activities.delegate.actions.PullAction;
import me.sheimi.sgit.activities.delegate.actions.PushAction;
import me.sheimi.sgit.activities.delegate.actions.RawConfigAction;
import me.sheimi.sgit.activities.delegate.actions.RebaseAction;
import me.sheimi.sgit.activities.delegate.actions.RemoveRemoteAction;
import me.sheimi.sgit.activities.delegate.actions.RepoAction;
import me.sheimi.sgit.activities.delegate.actions.ResetAction;
import me.sheimi.sgit.database.models.Repo;
import me.sheimi.sgit.repo.tasks.SheimiAsyncTask.AsyncTaskPostCallback;
import me.sheimi.sgit.repo.tasks.repo.AddToStageTask;
import me.sheimi.sgit.repo.tasks.repo.CheckoutFileTask;
import me.sheimi.sgit.repo.tasks.repo.CheckoutTask;
import me.sheimi.sgit.repo.tasks.repo.DeleteFileFromRepoTask;
import me.sheimi.sgit.repo.tasks.repo.FetchTask;
import me.sheimi.sgit.repo.tasks.repo.MergeTask;
import org.eclipse.jgit.lib.Ref;
import static me.sheimi.sgit.repo.tasks.repo.DeleteFileFromRepoTask.*; | package me.sheimi.sgit.activities.delegate;
public class RepoOperationDelegate {
private Repo mRepo; | private RepoDetailActivity mActivity; | 1 |
schaloner/deadbolt | samples-and-tests/acl/app/controllers/AclDeadboltHandler.java | [
"public interface DeadboltHandler\n{\n /**\n * Invoked immediately before controller or view restrictions are checked. This forms the integration with any\n * authentication actions that may need to occur.\n */\n void beforeRoleCheck();\n\n /**\n * Gets the current {@link RoleHolder}, e.g.... | import controllers.deadbolt.DeadboltHandler;
import controllers.deadbolt.ExternalizedRestrictionsAccessor;
import controllers.deadbolt.RestrictedResourcesHandler;
import model.AclUser;
import models.deadbolt.ExternalizedRestrictions;
import models.deadbolt.RoleHolder;
import play.mvc.Controller; | /*
* Copyright 2010-2011 Steve Chaloner
*
* 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 controllers;
/**
* @author Steve Chaloner (steve@objectify.be)
*/
public class AclDeadboltHandler extends Controller implements DeadboltHandler
{ | private static final RestrictedResourcesHandler RESTRICTED_RESOURCES_HANDLER = new AclRestrictedResourcesHandler(); | 2 |
dariober/ASCIIGenome | src/test/java/tracks/TrackNarrowPeakTest.java | [
"public class Config {\n\t\n\t// C O N S T R U C T O R \n\t\n\tprivate static final Map<ConfigKey, String> config= new HashMap<ConfigKey, String>();\n\n\tpublic Config(String source) throws IOException, InvalidConfigException {\n\t\t\n\t\tnew Xterm256();\n\t\t\n\t\tString RawConfigFile= Config.getConfigFileAsString... | import static org.junit.Assert.*;
import java.io.IOException;
import java.sql.SQLException;
import org.junit.Before;
import org.junit.Test;
import coloring.Config;
import exceptions.InvalidColourException;
import exceptions.InvalidConfigException;
import exceptions.InvalidGenomicCoordsException;
import exceptions.InvalidRecordException;
import samTextViewer.GenomicCoords; | package tracks;
public class TrackNarrowPeakTest {
@Before
public void prepareConfig() throws IOException, InvalidConfigException{
new Config(null);
}
@Test | public void testCanInitNarrorPeakTrack() throws InvalidGenomicCoordsException, IOException, ClassNotFoundException, InvalidRecordException, SQLException, InvalidColourException { | 4 |
jMotif/SAX | src/main/java/net/seninp/jmotif/sax/tinker/MoviePrinter.java | [
"public final class EuclideanDistance {\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public EuclideanDistance() {\r\n super();\r\n }\r\n\r\n /**\r\n * Calculates the Euclidean distance between two points.\r\n * \r\n * @param p1 The first point.\r\n * @param p2 The second point.\r\n * @return The E... | import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.TreeSet;
import javax.imageio.ImageIO;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.seninp.jmotif.distance.EuclideanDistance;
import net.seninp.jmotif.sax.NumerosityReductionStrategy;
import net.seninp.jmotif.sax.SAXProcessor;
import net.seninp.jmotif.sax.TSProcessor;
import net.seninp.util.HeatChart; | package net.seninp.jmotif.sax.tinker;
public class MoviePrinter {
private static final DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
private static DecimalFormat df = new DecimalFormat("0.00000", otherSymbols);
private static EuclideanDistance ed = new EuclideanDistance();
private static final String DAT_FNAME = "src/resources/dataset/depth/0890031.dat";
private static final int SAX_WINDOW_SIZE = 10;
private static int cPoint = SAX_WINDOW_SIZE;
private static final int SAX_PAA_SIZE = 10;
private static final int SAX_ALPHABET_SIZE = 4;
private static final double SAX_NORM_THRESHOLD = 0.001;
private static final NumerosityReductionStrategy SAX_NR_STRATEGY = NumerosityReductionStrategy.NONE;
private static final int SHINGLE_SIZE = 3;
// logging stuff
//
private static Logger LOGGER = LoggerFactory.getLogger(MoviePrinter.class);
// ffmpeg -framerate 5 -i frame%04d.png -s:v 1280x720 -vcodec libx264 -profile:v high -crf 20
// -pix_fmt yuv420p daimler_man.mp4
public static void main(String[] args) throws Exception {
SAXProcessor sp = new SAXProcessor();
// data
//
double[] dat = TSProcessor.readFileColumn(DAT_FNAME, 1, 0);
// TSProcessor tp = new TSProcessor();
// double[] dat = tp.readTS("src/resources/dataset/asys40.txt", 0);
// double[] dat = TSProcessor.readFileColumn(filename, columnIdx,
// sizeLimit)FileColumn(DAT_FNAME, 1, 0);
LOGGER.info("read {} points from {}", dat.length, DAT_FNAME);
String str = "win_width: " + cPoint + "; SAX: W " + SAX_WINDOW_SIZE + ", P " + SAX_PAA_SIZE
+ ", A " + SAX_ALPHABET_SIZE + ", STR " + SAX_NR_STRATEGY.toString();
int frameCounter = 0;
int startOffset = cPoint;
while (cPoint < dat.length - startOffset - 1) {
if (0 == cPoint % 2) {
BufferedImage tsChart = getChart(dat, cPoint);
// bitmap 1
//
double[] win1 = Arrays.copyOfRange(dat, cPoint - startOffset, cPoint);
Map<String, Integer> shingledData1 = sp.ts2Shingles(win1, SAX_WINDOW_SIZE, SAX_PAA_SIZE,
SAX_ALPHABET_SIZE, SAX_NR_STRATEGY, SAX_NORM_THRESHOLD, SHINGLE_SIZE);
BufferedImage pam1 = getHeatMap(shingledData1, "pre-window");
double[] win2 = Arrays.copyOfRange(dat, cPoint, cPoint + startOffset);
Map<String, Integer> shingledData2 = sp.ts2Shingles(win2, SAX_WINDOW_SIZE, SAX_PAA_SIZE,
SAX_ALPHABET_SIZE, SAX_NR_STRATEGY, SAX_NORM_THRESHOLD, SHINGLE_SIZE);
BufferedImage pam2 = getHeatMap(shingledData2, "post-window");
// the assemble
//
BufferedImage target = new BufferedImage(800, 530, BufferedImage.TYPE_INT_ARGB);
Graphics targetGraphics = target.getGraphics();
targetGraphics.setColor(Color.WHITE);
targetGraphics.fillRect(0, 0, 799, 529);
targetGraphics.drawImage(tsChart, 0, 0, null);
targetGraphics.drawImage(pam1, 10, 410, null);// draws the first image onto it
targetGraphics.drawImage(pam2, 120, 410, null);// draws the first image onto it
targetGraphics.setColor(Color.RED);
targetGraphics.setFont(new Font("monospaced", Font.PLAIN, 16));
targetGraphics.drawString(str, 300, 420);
targetGraphics.setColor(Color.BLUE);
targetGraphics.setFont(new Font("monospaced", Font.PLAIN, 24));
double dist = ed.distance(toVector(shingledData1), toVector(shingledData2));
targetGraphics.drawString("ED=" + df.format(dist), 300, 480);
// String fileName = new SimpleDateFormat("yyyyMMddhhmmssSS'.png'").format(new Date());
File outputfile = new File("dframe" + String.format("%04d", frameCounter) + ".png");
ImageIO.write(target, "png", outputfile);
frameCounter++;
}
cPoint++;
}
}
private static double[] toVector(Map<String, Integer> shingledData1) {
TreeSet<String> keys = new TreeSet<String>(shingledData1.keySet());
double[] res = new double[shingledData1.size()];
int counter = 0;
for (String shingle : keys) {
Integer value = shingledData1.get(shingle);
res[counter] = value;
counter++;
}
return res;
}
private static BufferedImage getHeatMap(Map<String, Integer> shingledData1, String title) {
TreeSet<String> keys = new TreeSet<String>(shingledData1.keySet());
double[][] heatmapData = new double[8][8];
int counter = 0;
for (String shingle : keys) {
Integer value = shingledData1.get(shingle);
heatmapData[counter / 8][counter % 8] = value;
counter++;
} | HeatChart chart = new HeatChart(heatmapData); | 4 |
fluxroot/pulse | src/main/java/com/fluxchess/pulse/Search.java | [
"final class MoveList<T extends MoveList.MoveEntry> {\n\n\tprivate static final int MAX_MOVES = 256;\n\n\tfinal T[] entries;\n\tint size = 0;\n\n\tstatic final class MoveVariation {\n\n\t\tfinal int[] moves = new int[MAX_PLY];\n\t\tint size = 0;\n\t}\n\n\tstatic class MoveEntry {\n\n\t\tint move = NOMOVE;\n\t\tint ... | import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import static com.fluxchess.pulse.MoveList.*;
import static com.fluxchess.pulse.model.Color.WHITE;
import static com.fluxchess.pulse.model.Color.opposite;
import static com.fluxchess.pulse.model.Depth.MAX_DEPTH;
import static com.fluxchess.pulse.model.Depth.MAX_PLY;
import static com.fluxchess.pulse.model.Move.NOMOVE;
import static com.fluxchess.pulse.model.Value.*;
import static java.lang.Math.abs;
import static java.lang.Runtime.getRuntime;
import static java.lang.Thread.currentThread;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.TimeUnit.SECONDS; | /*
* Copyright 2013-2021 Phokham Nonava
*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package com.fluxchess.pulse;
final class Search {
private final ExecutorService threadPool = newFixedThreadPool(getRuntime().availableProcessors());
private Optional<Future<?>> future = Optional.empty();
private volatile boolean abort;
private final Protocol protocol;
private Position position;
private final Evaluation evaluation = new Evaluation();
// We will store a MoveGenerator for each ply so we don't have to create them
// in search. (which is expensive)
private final MoveGenerator[] moveGenerators = new MoveGenerator[MAX_PLY];
// Depth search
private int searchDepth;
// Nodes search
private long searchNodes;
// Time & Clock & Ponder search
private long searchTime;
private Timer timer;
private boolean timerStopped;
private boolean doTimeManagement;
// Search parameters | private final MoveList<RootEntry> rootMoves = new MoveList<>(RootEntry.class); | 0 |
apache/incubator-taverna-mobile | app/src/main/java/org/apache/taverna/mobile/ui/favouriteworkflowdetail/FavouriteWorkflowDetailFragment.java | [
"@Singleton\npublic class DataManager {\n\n private BaseApiManager mBaseApiManager;\n\n private DBHelper mDBHelper;\n\n private PreferencesHelper mPreferencesHelper;\n\n @Inject\n public DataManager(BaseApiManager baseApiManager, DBHelper dbHelper, PreferencesHelper\n mPreferencesHelper) {... | import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import org.apache.taverna.mobile.R;
import org.apache.taverna.mobile.data.DataManager;
import org.apache.taverna.mobile.data.model.License;
import org.apache.taverna.mobile.data.model.User;
import org.apache.taverna.mobile.data.model.Workflow;
import org.apache.taverna.mobile.ui.base.BaseActivity;
import org.apache.taverna.mobile.ui.imagezoom.ImageZoomActivity;
import org.apache.taverna.mobile.ui.imagezoom.ImageZoomFragment;
import org.apache.taverna.mobile.ui.workflowrun.WorkflowRunActivity;
import org.apache.taverna.mobile.utils.ConnectionInfo;
import org.apache.taverna.mobile.utils.Constants;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.taverna.mobile.ui.favouriteworkflowdetail;
public class FavouriteWorkflowDetailFragment extends Fragment
implements FavouriteWorkflowDetailMvpView {
private static final String ID = "id";
public final String LOG_TAG = getClass().getSimpleName();
@Inject DataManager dataManager;
@Inject FavouriteWorkflowDetailPresenter mWorkflowDetailPresenter;
@BindView(R.id.ivWorkflowImage)
ImageView workflowImage;
@BindView(R.id.tvTitle)
TextView title;
@BindView(R.id.ivUploader)
ImageView uploaderImage;
@BindView(R.id.tvUploaderName)
TextView uploaderName;
@BindView(R.id.tvDate)
TextView date;
@BindView(R.id.tvType)
TextView type;
@BindView(R.id.tvDescription)
WebView description;
@BindView(R.id.ivFav)
ImageView ivFavourite;
@BindView(R.id.progressBar)
ProgressBar mProgressBar;
@BindView(R.id.scrollView)
ScrollView mScrollView;
@BindView(R.id.rootLayout)
RelativeLayout rootLayout;
@BindView(R.id.fabRun)
FloatingActionButton fabRun;
private AlertDialog alertDialog;
private String id;
private String licenceId = null;
private ProgressDialog dialog;
private ActionBar actionBar;
private Workflow mWorkflow;
public static FavouriteWorkflowDetailFragment newInstance(String id) {
Bundle args = new Bundle();
args.putString(ID, id);
FavouriteWorkflowDetailFragment fragment = new FavouriteWorkflowDetailFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
id = getArguments().getString(ID);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail_workflow, container, false); | ((BaseActivity) getActivity()).getActivityComponent().inject(this); | 2 |
njustesen/hero-aicademy | src/ai/evaluation/MeanEvaluator.java | [
"public class MapLoader {\n\t\n\tprivate static final char P1CRYSTAL = 'c';\n\tprivate static final char P2CRYSTAL = 'C';\n\tstatic Map<Character, SquareType> codes = new HashMap<Character, SquareType>();\n\tstatic {\n\t\tcodes.put('0', SquareType.NONE);\n\t\tcodes.put('d', SquareType.DEPLOY_1);\n\t\tcodes.put('D',... | import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import util.MapLoader;
import ai.util.NormUtil;
import game.GameState;
import libs.UnitClassLib;
import model.Card;
import model.CardType;
import model.DECK_SIZE;
import model.Position; | package ai.evaluation;
public class MeanEvaluator implements IStateEvaluator {
public static double MAX_UNIT_TINY = 0;
public static double MAX_CRYSTAL_TINY = 0;
public static double MAX_UNIT_SMALL = 0;
public static double MAX_CRYSTAL_SMALL = 0;
public static double MAX_UNIT_STANDARD = 0;
public static double MAX_CRYSTAL_STANDARD = 0;
private static Map<Card, Double> values;
static {
values = new HashMap<Card, Double>();
values.put(Card.ARCHER, 1.1);
values.put(Card.CLERIC, 1.2);
values.put(Card.DRAGONSCALE, .4);
values.put(Card.INFERNO, 1.6);
values.put(Card.KNIGHT, 1.0);
values.put(Card.NINJA, 1.5);
values.put(Card.REVIVE_POTION, .9);
values.put(Card.RUNEMETAL, .4);
values.put(Card.SCROLL, .9);
values.put(Card.SHINING_HELM, .4);
values.put(Card.WIZARD, 1.1);
try {
GameState tiny = new GameState(MapLoader.get("a-tiny")); | tiny.init(DECK_SIZE.TINY); | 6 |
TomGrill/gdx-dialogs | ios/src/de/tomgrill/gdxdialogs/ios/IOSGDXDialogs.java | [
"public abstract class GDXDialogs {\n\n\tprotected ArrayMap<String, String> registeredDialogs = new ArrayMap<String, String>();\n\n\tpublic <T> T newDialog(Class<T> cls) {\n\t\tString className = cls.getName();\n\t\tif (registeredDialogs.containsKey(className)) {\n\n\t\t\ttry {\n\t\t\t\tfinal Class<T> dialogClazz =... | import de.tomgrill.gdxdialogs.core.GDXDialogs;
import de.tomgrill.gdxdialogs.core.dialogs.GDXButtonDialog;
import de.tomgrill.gdxdialogs.core.dialogs.GDXProgressDialog;
import de.tomgrill.gdxdialogs.core.dialogs.GDXTextPrompt;
import de.tomgrill.gdxdialogs.ios.dialogs.IOSGDXButtonDialog;
import de.tomgrill.gdxdialogs.ios.dialogs.IOSGDXProgressDialog;
import de.tomgrill.gdxdialogs.ios.dialogs.IOSGDXTextPrompt; | /*******************************************************************************
* Copyright 2015 See AUTHORS file.
*
* 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 de.tomgrill.gdxdialogs.ios;
public class IOSGDXDialogs extends GDXDialogs {
public IOSGDXDialogs() {
registerDialog(GDXButtonDialog.class.getName(), IOSGDXButtonDialog.class.getName());
registerDialog(GDXProgressDialog.class.getName(), IOSGDXProgressDialog.class.getName()); | registerDialog(GDXTextPrompt.class.getName(), IOSGDXTextPrompt.class.getName()); | 6 |
cjdaly/fold | net.locosoft.fold.channel.vitals/src/net/locosoft/fold/channel/vitals/internal/VitalsPostHtml.java | [
"public interface IChannelInternal extends IChannel {\n\n\tIChannelService getChannelService();\n\n\tvoid init(String channelId, IChannelService channelService,\n\t\t\tString channelDescription);\n\n\tvoid init();\n\n\tvoid fini();\n\n\tboolean channelSecurity(HttpServletRequest request,\n\t\t\tHttpServletResponse ... | import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.locosoft.fold.channel.IChannelInternal;
import net.locosoft.fold.channel.vitals.DynamicVitals;
import net.locosoft.fold.channel.vitals.IVitals;
import net.locosoft.fold.sketch.pad.html.AbstractChannelHtmlSketch;
import net.locosoft.fold.sketch.pad.neo4j.ChannelItemNode;
import net.locosoft.fold.sketch.pad.neo4j.HierarchyNode;
import net.locosoft.fold.sketch.pad.neo4j.MultiPropertyAccessNode;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue; | /*****************************************************************************
* Copyright (c) 2015 Chris J Daly (github user cjdaly)
* 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:
* cjdaly - initial API and implementation
****************************************************************************/
package net.locosoft.fold.channel.vitals.internal;
public class VitalsPostHtml extends AbstractChannelHtmlSketch {
public VitalsPostHtml(IChannelInternal channel) {
super(channel);
}
public void postVitals(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JsonObject jsonObject = JsonObject.readFrom(request.getReader());
String vitalsId = jsonObject.getString(IVitals.NODE_PROPERTY_ID, null);
if (vitalsId == null) {
response.getWriter().println(
"POST missing " + IVitals.NODE_PROPERTY_ID);
return;
}
ChannelItemNode vitalsNode = new ChannelItemNode(getChannel(), "Vitals");
long vitalsItemNodeId = vitalsNode.nextOrdinalNodeId();
DynamicVitals vitals = new DynamicVitals(vitalsId);
vitals.saveVitals(vitalsItemNodeId, jsonObject);
response.getWriter().println(
"Posted vitals: "
+ vitalsNode.getOrdinalIndex(vitalsItemNodeId));
}
public void postVitalsDef(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JsonObject jsonObject = JsonObject.readFrom(request.getReader());
String vitalsId = jsonObject.getString(IVitals.NODE_PROPERTY_ID, null);
if (vitalsId == null) {
response.getWriter().println(
"POST missing " + IVitals.NODE_PROPERTY_ID);
return;
}
HierarchyNode channelNode = new HierarchyNode(getChannel()
.getChannelNodeId());
long defsNodeId = channelNode.getSubId("defs", true);
HierarchyNode defsNode = new HierarchyNode(defsNodeId);
long vitalsNodeId = defsNode.getSubId(vitalsId, true);
HierarchyNode vitalsNode = new HierarchyNode(vitalsNodeId);
JsonValue vitalsJsonValue = jsonObject.get("Vitals");
if ((vitalsJsonValue == null) || !vitalsJsonValue.isObject()) {
response.getWriter().println("POST missing Vitals defs");
return;
}
JsonObject vitalsJson = vitalsJsonValue.asObject();
List<String> names = vitalsJson.names();
for (String name : names) {
JsonValue jsonValue = vitalsJson.get(name);
if (!jsonValue.isObject())
continue;
JsonObject vitalDef = jsonValue.asObject();
long subId = vitalsNode.getSubId(name, true); | MultiPropertyAccessNode props = new MultiPropertyAccessNode(subId); | 6 |
engswee/equalize-xpi-modules | com.equalize.xpi.af.modules.ejb/ejbModule/com/equalize/xpi/af/modules/json/XML2JSONConverter.java | [
"public abstract class AbstractModuleConverter {\n\tprotected final Message msg;\n\tprotected final XMLPayload payload;\n\tprotected final AuditLogHelper audit;\n\tprotected final ParameterHelper param;\n\tprotected final DynamicConfigurationHelper dyncfg;\n\tprotected final boolean debug;\n\t\n\tpublic AbstractMod... | import java.util.HashSet;
import com.equalize.xpi.af.modules.util.AbstractModuleConverter;
import com.equalize.xpi.af.modules.util.AuditLogHelper;
import com.equalize.xpi.af.modules.util.DynamicConfigurationHelper;
import com.equalize.xpi.af.modules.util.ParameterHelper;
import com.equalize.xpi.util.converter.ConversionDOMInput;
import com.equalize.xpi.util.converter.ConversionJSONOutput;
import com.equalize.xpi.util.converter.XMLElementContainer;
import com.sap.aii.af.lib.mp.module.ModuleException;
import com.sap.engine.interfaces.messaging.api.Message;
import com.sap.engine.interfaces.messaging.api.auditlog.AuditLogStatus; | package com.equalize.xpi.af.modules.json;
public class XML2JSONConverter extends AbstractModuleConverter {
private ConversionDOMInput domIn;
private ConversionJSONOutput jsonOut;
private XMLElementContainer rootXML;
private int indentFactor;
private boolean skipRootNode;
private boolean forceArrayAll;
private HashSet<String> arrayFields;
| public XML2JSONConverter(Message msg, ParameterHelper param, AuditLogHelper audit, DynamicConfigurationHelper dyncfg, Boolean debug) { | 3 |
alphagov/locate-api | locate-api-service/src/test/uk/gov/gds/locate/api/resources/AddressResourceTest.java | [
"@Provider\n@Produces(MediaType.APPLICATION_JSON)\npublic class LocateExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Throwable> {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(LocateExceptionMapper.class);\n\n protected static final String CONTENT_TYPE = \"application/json; char... | import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.yammer.dropwizard.auth.AuthenticationException;
import com.yammer.dropwizard.auth.Authenticator;
import com.yammer.dropwizard.testing.ResourceTest;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import uk.gov.gds.locate.api.LocateExceptionMapper;
import uk.gov.gds.locate.api.authentication.BearerTokenAuthProvider;
import uk.gov.gds.locate.api.configuration.LocateApiConfiguration;
import uk.gov.gds.locate.api.dao.AddressDao;
import uk.gov.gds.locate.api.dao.UsageDao;
import uk.gov.gds.locate.api.helpers.DetailsBuilder;
import uk.gov.gds.locate.api.helpers.OrderingBuilder;
import uk.gov.gds.locate.api.helpers.PresentationBuilder;
import uk.gov.gds.locate.api.model.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*; | assertThat(result).contains("\"gssCode\":\"gssCode\"");
assertThat(result).contains("\"uprn\":\"uprn\"");
assertThat(result).contains("\"presentation\"");
assertThat(result).contains("\"details\"");
assertThat(result).contains("\"location\"");
assertThat(result).contains("\"property\":\"property-test\"");
assertThat(result).contains("\"street\":\"street-test\"");
assertThat(result).contains("\"locality\":\"locality-test\"");
assertThat(result).contains("\"town\":\"town-test\"");
assertThat(result).contains("\"area\":\"area-test\"");
assertThat(result).contains("\"postcode\":\"postcode-test\"");
}
@Test
public void shouldReturnAListOfAddressesForASuccessfulSearchUsingPresentationFormatAsDefault() {
List<SimpleAddress> result = client().resource("/locate/addresses?postcode=" + validPostcode).header("Authorization", presentationDataFieldsToken).get(new GenericType<List<SimpleAddress>>() {
});
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0).getGssCode()).isEqualTo(address.getGssCode());
assertThat(result.get(0).getUprn()).isEqualTo(address.getUprn());
assertThat(result.get(0).getProperty()).isEqualTo("property-test");
assertThat(result.get(0).getStreet()).isEqualTo("street-test");
assertThat(result.get(0).getLocality()).isEqualTo("locality-test");
assertThat(result.get(0).getArea()).isEqualTo("area-test");
assertThat(result.get(0).getTown()).isEqualTo("town-test");
assertThat(result.get(0).getPostcode()).isEqualTo("postcode-test");
verify(dao, times(1)).findAllForPostcode(validPostcode);
}
@Test
public void shouldReturnAListOfAddressesForASuccessfulSearchWithPresentationFormatQuery() {
List<SimpleAddress> result = client().resource("/locate/addresses?format=presentation&postcode=" + validPostcode).header("Authorization", presentationDataFieldsToken).get(new GenericType<List<SimpleAddress>>() {
});
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0).getGssCode()).isEqualTo(address.getGssCode());
assertThat(result.get(0).getUprn()).isEqualTo(address.getUprn());
assertThat(result.get(0).getProperty()).isEqualTo("property-test");
assertThat(result.get(0).getStreet()).isEqualTo("street-test");
assertThat(result.get(0).getLocality()).isEqualTo("locality-test");
assertThat(result.get(0).getArea()).isEqualTo("area-test");
assertThat(result.get(0).getTown()).isEqualTo("town-test");
assertThat(result.get(0).getPostcode()).isEqualTo("postcode-test");
verify(dao, times(1)).findAllForPostcode(validPostcode);
}
@Test
public void shouldReturnAListOfAddressesAsValidJSONForASuccessfulSearchWithPresentationFormatQuery() {
String result = client().resource("/locate/addresses?format=presentation&postcode=" + validPostcode).header("Authorization", presentationDataFieldsToken).get(String.class);
verify(dao, times(1)).findAllForPostcode(validPostcode);
assertThat(result).contains("\"gssCode\":\"gssCode\"");
assertThat(result).contains("\"uprn\":\"uprn\"");
assertThat(result).doesNotContain("\"presentation\"");
assertThat(result).doesNotContain("\"details\"");
assertThat(result).doesNotContain("\"location\"");
assertThat(result).contains("\"property\":\"property-test\"");
assertThat(result).contains("\"street\":\"street-test\"");
assertThat(result).contains("\"locality\":\"locality-test\"");
assertThat(result).contains("\"town\":\"town-test\"");
assertThat(result).contains("\"area\":\"area-test\"");
assertThat(result).contains("\"postcode\":\"postcode-test\"");
}
@Test
public void shouldReturnAListOfAddressesForASuccessfulSearchWithVCardFormatQuery() {
String result = client().resource("/locate/addresses?format=vcard&postcode=" + validPostcode).header("Authorization", allDataFieldsToken).get(String.class);
verify(dao, times(1)).findAllForPostcode(validPostcode);
assertThat(result).contains("\"x-uprn\":\"uprn\"");
assertThat(result).contains("\"extended-address\":\"property-test\"");
assertThat(result).contains("\"street-address\":\"street-test\"");
assertThat(result).contains("\"locality\":\"town-test\"");
assertThat(result).contains("\"region\":\"area-test\"");
assertThat(result).contains("\"postal-code\":\"postcode-test\"");
assertThat(result).contains("\"vcard\":\"ADR;:;;property-test;street-test;town-test;area-test;postcode-test;country\"");
}
@Test
public void shouldReturnAListOfAddressesWithoutNullFieldsAsValidJSONForASuccessfulSearch() {
Presentation presentation = new Presentation();
Address addressWithMissingFields = new Address("gssCode", "uprn", null, "country", new Date(), presentation, validAddress, new Location(), new Ordering(), "iv");
when(dao.findAllForPostcode(validPostcode)).thenReturn(ImmutableList.of(addressWithMissingFields));
String result = client().resource("/locate/addresses?postcode=" + validPostcode).header("Authorization", allDataFieldsToken).get(String.class);
verify(dao, times(1)).findAllForPostcode(validPostcode);
assertThat(result).contains("\"gssCode\":\"gssCode\"");
assertThat(result).contains("\"uprn\":\"uprn\"");
assertThat(result).doesNotContain("\"property\"");
assertThat(result).doesNotContain("\"street\"");
assertThat(result).doesNotContain("\"locality\"");
assertThat(result).doesNotContain("\"town\"");
assertThat(result).doesNotContain("\"area\"");
assertThat(result).doesNotContain("\"postcode\"");
}
@Test
public void shouldReturnAnEmptyListOfAddressesForAnUnsuccessfulSearch() {
List<SimpleAddress> result = client().resource("/locate/addresses?postcode=" + inValidPostcode).header("Authorization", allDataFieldsToken).get(new GenericType<List<SimpleAddress>>() {
});
assertThat(result.size()).isEqualTo(0);
verify(dao, times(1)).findAllForPostcode(inValidPostcode);
}
@Test
public void shouldReturnAnEmptyListOfAddressesAsValidJSONForAnUnsuccessfulSearch() {
String result = client().resource("/locate/addresses?postcode=" + inValidPostcode).header("Authorization", allDataFieldsToken).get(String.class);
assertThat(result).contains("[]");
verify(dao, times(1)).findAllForPostcode(inValidPostcode);
}
@Test
public void shouldCallDaoWithTidyPostcode() throws UnsupportedEncodingException {
client().resource("/locate/addresses?postcode=" + URLEncoder.encode(" PE1 1eR ", "UTF-8")).header("Authorization", allDataFieldsToken).get(String.class);
verify(dao, times(1)).findAllForPostcode("pe11er");
}
@Override
protected void setUpResources() throws Exception {
addResource(new AddressResource(dao, configuration)); | addProvider(new BearerTokenAuthProvider(configuration, usageDao, new TestAuthenticator())); | 1 |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessToken.java | [
"public interface OAuth2AccessToken\n{\n /**\n * Returns the actual access token String.\n *\n * @return\n *\n * @throws ProtocolException\n */\n public CharSequence accessToken() throws ProtocolException;\n\n /**\n * Returns the access token type.\n *\n * @return\n ... | import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.jems.optional.Optional;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc5545.DateTime;
import org.dmfs.rfc5545.Duration;
import java.util.NoSuchElementException;
import static org.dmfs.oauth2.client.utils.Parameters.ACCESS_TOKEN;
import static org.dmfs.oauth2.client.utils.Parameters.EXPIRES_IN;
import static org.dmfs.oauth2.client.utils.Parameters.SCOPE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE;
import static org.dmfs.oauth2.client.utils.Parameters.TOKEN_TYPE; | /*
* Copyright 2016 dmfs GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dmfs.oauth2.client.tokens;
/**
* Represents an {@link OAuth2AccessToken} received from an Implicit Grant.
*
* @author Marten Gajda
*/
public final class ImplicitGrantAccessToken implements OAuth2AccessToken
{
private final Uri mRedirectUri;
private final ParameterList mRedirectUriParameters;
private final DateTime mIssueDate;
private final OAuth2Scope mScope;
private final Duration mDefaultExpiresIn;
/**
* Represents the {@link OAuth2AccessToken} that's contained in the provided redirect URI.
*
* @param redirectUri
* The URI the user agent was redirected to.
* @param scope
* The scope that has been requested from the server.
* @param state
* The state that was provided to the authorization endpoint.
* @param defaultExpiresIn
* The default expiration duration to assume if no expiration duration was provided with the response.
*
* @throws ProtocolException
* If the state doesn't match the one returned by the server.
*/
public ImplicitGrantAccessToken(Uri redirectUri, OAuth2Scope scope, CharSequence state, Duration defaultExpiresIn) throws ProtocolException
{
mRedirectUri = redirectUri;
mRedirectUriParameters = new XwfueParameterList(redirectUri.fragment().value());
if (!state.toString().equals(new TextParameter(STATE, mRedirectUriParameters).toString()))
{
throw new ProtocolException("State in redirect uri doesn't match the original state!");
}
mIssueDate = DateTime.now();
mScope = scope;
mDefaultExpiresIn = defaultExpiresIn;
}
@Override
public CharSequence accessToken() throws ProtocolException
{ | OptionalParameter<CharSequence> accessToken = new OptionalParameter<>(ACCESS_TOKEN, mRedirectUriParameters); | 2 |
teivah/TIBreview | src/test/java/com/tibco/exchange/tibreview/processor/resourcerule/CProcessorRendezvousResourceCertifiedTest.java | [
"public class TIBResource {\n\tprivate String filePath;\n\tprivate String type;\n\t\n\tprivate static final String REQUEST_GET_TYPE = \"/jndi:namedResource/@type\";\n\t\n\tpublic TIBResource(String filePath) throws Exception {\n\t\tthis.filePath = filePath;\n\t\tthis.type = Util.xpathEval(filePath, Constants.RESOUR... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.tibco.exchange.tibreview.common.TIBResource;
import com.tibco.exchange.tibreview.engine.Context;
import com.tibco.exchange.tibreview.model.pmd.Violation;
import com.tibco.exchange.tibreview.model.rules.Configuration;
import com.tibco.exchange.tibreview.model.rules.Resource;
import com.tibco.exchange.tibreview.model.rules.Tibrules;
import com.tibco.exchange.tibreview.parser.RulesParser;
| package com.tibco.exchange.tibreview.processor.resourcerule;
public class CProcessorRendezvousResourceCertifiedTest {
private static final Logger LOGGER = Logger.getLogger(CProcessorRendezvousResourceCertifiedTest.class);
@Test
public void testCProcessorRendezvousResourceCertifiedTest() {
TIBResource fileresource;
try {
fileresource = new TIBResource("src/test/resources/FileResources/RendezvousResourceCertified.rvResource");
fileresource.toString();
LOGGER.info(fileresource.toString());
assertTrue(fileresource.toString().equals("TIBResource [filePath=src/test/resources/FileResources/RendezvousResourceCertified.rvResource, type=rvsharedresource:RVResource]"));
Tibrules tibrules= RulesParser.getInstance().parseFile("src/test/resources/FileResources/xml/RendezvousResourceCertified.xml");
| Resource resource = tibrules.getResource();
| 4 |
JoshuaKissoon/DOSNA | src/dosna/simulations/performance/large/SimulatedUser.java | [
"public class DOSNA\r\n{\r\n\r\n private DataManager dataManager = null;\r\n private PeriodicNotificationsChecker notificationsChecker;\r\n\r\n public DOSNA()\r\n {\r\n\r\n }\r\n\r\n /**\r\n * Launch the main node for this instance\r\n * Connect to the network\r\n * Launch the main App... | import dosna.DOSNA;
import dosna.content.ContentManager;
import dosna.content.DOSNAContent;
import dosna.core.ContentMetadata;
import dosna.core.DOSNAStatistician;
import dosna.osn.activitystream.ActivityStreamManager;
import dosna.osn.actor.Actor;
import dosna.osn.actor.ActorManager;
import dosna.osn.status.Status;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import kademlia.JKademliaNode;
import kademlia.dht.KademliaStorageEntry;
import kademlia.exceptions.ContentNotFoundException;
import kademlia.node.KademliaId; | package dosna.simulations.performance.large;
/**
* A user used in simulation; this user performs the actions of a user of the system.
*
* @author Joshua Kissoon
* @since 20140508
*/
public class SimulatedUser
{
private Actor actor;
private final DOSNA dosna;
private String password;
public int userNumber;
/* Content Manager to manage the content on the network */
private ContentManager contentManager;
/* DOSNA Statistician */
private final DOSNAStatistician statistician;
/* Set of users in the simulation */
private final SimulatedUser[] users;
/* Whether this user is online or not */
private boolean isOnline;
{
this.dosna = new DOSNA();
statistician = new DOSNAStatistician();
this.isOnline = false;
}
/**
* Setup the simulated user
*
* @param actor The DOSN actor object for this user
* @param userNumber The user number in the simulation
* @param users Set of users in the simulation
*/
public SimulatedUser(final Actor actor, final int userNumber, final SimulatedUser[] users)
{
this.actor = actor;
this.userNumber = userNumber;
this.users = users;
}
/**
* Setup the simulated user
*
* @param actorId The DOSN actor's id for this user
* @param name
* @param password
* @param userNumber The user number in the simulation
* @param users The set of users in the simulation
*/
public SimulatedUser(final String actorId, final String password, final String name, final int userNumber, final SimulatedUser[] users)
{
this.actor = new Actor(actorId);
this.actor.setName(name);
this.actor.setPassword(password);
this.password = password;
this.userNumber = userNumber;
this.users = users;
}
public Actor getActor()
{
return this.actor;
}
public boolean signup()
{
DOSNA.SignupResult res = this.dosna.signupUser(this.actor);
this.contentManager = new ContentManager(this.dosna.getDataManager());
if (res.isSignupSuccessful)
{
this.actor = res.actor;
this.actor.init(this.dosna.getDataManager());
this.dosna.launchNotificationChecker(this.actor);
this.isOnline = true;
}
return res.isSignupSuccessful;
}
public boolean login()
{
DOSNA.LoginResult res = this.dosna.loginUser(this.actor.getId(), this.password);
this.contentManager = new ContentManager(this.dosna.getDataManager());
if (res.isLoginSuccessful)
{
this.actor = res.loggedInActor;
this.actor.init(this.dosna.getDataManager());
this.dosna.launchNotificationChecker(this.actor);
this.isOnline = true;
}
return res.isLoginSuccessful;
}
/**
* Log the user out and shutdown the system
*
* @param saveState Whether to save the Node state or not
*
* @return Whether logout and shutdown was successful or not
*/
public boolean logout(boolean saveState)
{
try
{
this.dosna.shutdown(saveState);
this.isOnline = false;
return true;
}
catch (IOException ex)
{
return false;
}
}
/**
* Creates a new status for this user and places it on the DHT.
*
* @param statusText The status to put
*
* @throws java.io.IOException
*/
public synchronized void setNewStatus(String statusText) throws IOException
{
Status status = Status.createNew(this.getActor(), statusText);
this.getActor().getContentManager().store(status);
}
public Actor loadActor(String uid) throws IOException, ContentNotFoundException
{ | return new ActorManager(this.dosna.getDataManager()).loadActor(uid); | 6 |
DevLeoko/AdvancedBan | bukkit/src/main/java/me/leoko/advancedban/bukkit/BukkitMain.java | [
"public class Universal {\n\n private static Universal instance = null;\n\n public static void setRedis(boolean redis) {\n Universal.redis = redis;\n }\n\n private final Map<String, String> ips = new HashMap<>();\n private MethodInterface mi;\n private LogManager logManager;\n\n private ... | import me.leoko.advancedban.Universal;
import me.leoko.advancedban.bukkit.listener.ChatListener;
import me.leoko.advancedban.bukkit.listener.CommandListener;
import me.leoko.advancedban.bukkit.listener.ConnectionListener;
import me.leoko.advancedban.bukkit.listener.InternalListener;
import org.bukkit.Bukkit;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.plugin.java.JavaPlugin; | package me.leoko.advancedban.bukkit;
public class BukkitMain extends JavaPlugin {
private static BukkitMain instance;
public static BukkitMain get() {
return instance;
}
@Override
public void onEnable() {
instance = this;
Universal.get().setup(new BukkitMethods());
| ConnectionListener connListener = new ConnectionListener(); | 3 |
restsql/restsql | src/org/restsql/core/impl/AbstractSqlResourceMetaData.java | [
"public class Factory extends AbstractFactory {\n\n\t/** Creates request for child row with blank params. Configurable implementation class. */\n\tpublic static Request getChildRequest(final Request parentRequest) {\n\t\tfinal RequestFactory requestFactory = (RequestFactory) getInstance(Config.KEY_REQUEST_FACTORY,\... | import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import org.restsql.core.ColumnMetaData;
import org.restsql.core.Config;
import org.restsql.core.Factory;
import org.restsql.core.InvalidRequestException;
import org.restsql.core.Request;
import org.restsql.core.Request.Type;
import org.restsql.core.SqlBuilder;
import org.restsql.core.SqlResourceException;
import org.restsql.core.SqlResourceMetaData;
import org.restsql.core.TableMetaData;
import org.restsql.core.TableMetaData.TableRole;
import org.restsql.core.sqlresource.Documentation;
import org.restsql.core.sqlresource.SqlResourceDefinition;
import org.restsql.core.sqlresource.SqlResourceDefinitionUtils;
import org.restsql.core.sqlresource.Table; | * @throws InvalidRequestException if main query is invalid
*/
protected String getSqlMainQuery(final SqlResourceDefinition definition, final SqlBuilder sqlBuilder)
throws InvalidRequestException {
final Request request = Factory.getRequest(Type.SELECT, resName, null, null, null, null);
request.setSelectLimit(new Integer(1));
request.setSelectOffset(new Integer(0));
return sqlBuilder.buildSelectSql(this, definition.getQuery().getValue(), request).getStatement();
}
/**
* Retrieves sql for querying primary keys. Hook method for buildPrimaryKeys allows database-specific overrides.
*/
protected abstract String getSqlPkQuery();
/**
* Return whether a column in the given result set is read-only. The default implementation just calls isReadOnly()
* on the result set, database specific implementations can override this behavior. Contributed by <a
* href="https://github.com/rhuitl">rhuitl</a>.
*
* @param resultSetMetaData Result set metadata
* @param colNumber Column number (1..N)
* @throws SQLException if a database access error occurs
*/
protected boolean isColumnReadOnly(final ResultSetMetaData resultSetMetaData, final int colNumber)
throws SQLException {
return resultSetMetaData.isReadOnly(colNumber);
}
/**
* Returns true if db metadata, e.g. database/owner, table and column names are stored as upper case, and therefore
* lookups should be forced to upper. Database specific implementation can override this response.
*/
protected boolean isDbMetaDataUpperCase() {
return false;
}
/**
* Sets sequence metadata for a column with the columns query result set.
*
* @throws SQLException when a database error occurs
*/
protected abstract void setSequenceMetaData(ColumnMetaDataImpl column, ResultSet resultSet)
throws SQLException;
/** Build extended metadata for serialization if first time through. */
private void buildExtendedMetadata() {
if (!extendedMetadataIsBuilt) {
parentTableName = getQualifiedTableName(parentTable);
childTableName = getQualifiedTableName(childTable);
joinTableName = getQualifiedTableName(joinTable);
parentPlusExtTableNames = getQualifiedTableNames(parentPlusExtTables);
childPlusExtTableNames = getQualifiedTableNames(childPlusExtTables);
allReadColumnNames = getQualifiedColumnNames(allReadColumns);
childReadColumnNames = getQualifiedColumnNames(childReadColumns);
parentReadColumnNames = getQualifiedColumnNames(parentReadColumns);
extendedMetadataIsBuilt = true;
}
}
// Private methods
private void buildInvisibleForeignKeys(final Connection connection) throws SQLException {
final PreparedStatement statement = connection.prepareStatement(getSqlColumnsQuery());
ResultSet resultSet = null;
try {
for (final TableMetaData table : tables) {
if (!table.isParent()) {
statement.setString(1, isDbMetaDataUpperCase() ? table.getDatabaseName().toUpperCase()
: table.getDatabaseName());
statement.setString(2, isDbMetaDataUpperCase() ? table.getTableName().toUpperCase()
: table.getTableName());
resultSet = statement.executeQuery();
while (resultSet.next()) {
final String columnName = resultSet.getString(1);
if (!table.getColumns().containsKey(columnName)) {
TableMetaData mainTable;
switch (table.getTableRole()) {
case ChildExtension:
mainTable = childTable;
break;
default: // Child, ParentExtension, Unknown
mainTable = parentTable;
}
// Look for a pk on the main table with the same name
for (final ColumnMetaData pk : mainTable.getPrimaryKeys()) {
if (columnName.equals(pk.getColumnName())) {
final ColumnMetaData fkColumn = Factory.getColumnMetaData();
fkColumn.setAttributes(
table.getDatabaseName(),
table.getQualifiedTableName(),
table.getTableName(),
table.getTableRole(),
columnName,
getQualifiedColumnName(table.getTableName(),
table.getQualifiedTableName(), false, columnName),
pk.getColumnLabel(),
getQualifiedColumnLabel(table.getTableName(),
table.getQualifiedTableName(), false, pk.getColumnLabel()),
resultSet.getString(2));
((TableMetaDataImpl) table).addColumn(fkColumn);
}
}
}
}
}
}
} catch (final SQLException exception) {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
throw exception;
}
}
private void buildJoinTableMetadata(final Connection connection) throws SQLException {
// Join table could have been identified in buildTablesAndColumns(), but not always | final Table joinDef = SqlResourceDefinitionUtils.getTable(definition, TableRole.Join); | 4 |
alexmojaki/boxes | src/main/java/alex/mojaki/boxes/View.java | [
"public class BoxParticipantException extends RuntimeException {\n\n public Box<ParticipationDetails> details = box();\n\n public BoxParticipantException(String message, Exception cause) {\n super(message, cause);\n }\n\n public BoxParticipantException withDetails(ParticipationDetails details) {\... | import alex.mojaki.boxes.exceptions.BoxParticipantException;
import alex.mojaki.boxes.middleware.change.ChangeMiddleware;
import alex.mojaki.boxes.middleware.get.GetMiddleware;
import alex.mojaki.boxes.observers.change.ChangeObserver;
import alex.mojaki.boxes.observers.change.TargetedChangeObserver;
import alex.mojaki.boxes.observers.get.GetObserver; | package alex.mojaki.boxes;
/**
* A {@link PowerBox} whose value is calculated based on the values of other {@code PowerBox}es and knows when those
* boxes change, allowing it to safely cache its own value to save computation and notify {@link ChangeObserver}s
* that the result of its calculation is now different.
* <p>
* Note that views have some base performance overhead and writing your code to use a view for caching wherever
* possible will not necessarily speed up your program - it may even slow it down. You should use views for caching
* only when the computation is slow or expensive.
* <p>
* The {@link PowerBox#set(Object)} method and the use of {@link ChangeMiddleware} are unsupported.
*
* @param <T> the type of the calculated value
*/
public abstract class View<T> extends CommonBox<T> {
private static final TargetedChangeObserver<Object, View> TARGETED_CHANGE_OBSERVER = new TargetedChangeObserver<Object, View>() {
@Override
public void onChange(PowerBox box, Object originalValue, Object finalValue, Object requestedValue, View target) {
target.update();
}
};
private boolean cacheValid = false;
/**
* Construct a view with the given family and whose value depends on the given boxes
*/
public View(BoxFamily family, PowerBox... boxes) {
super(family);
construct(boxes);
}
/**
* Construct a view by looking up a family with the given class and name and whose value depends on the given boxes.
*/
public View(Class<?> clazz, String name, PowerBox... boxes) {
super(clazz, name);
construct(boxes);
}
private void construct(PowerBox[] boxes) {
addBoxes(boxes);
getFamily().getChangeMiddlewares().disable();
}
/**
* Indicate that the value of this view depends on the given boxes in addition to any previously added boxes or
* boxes given in the constructor.
*/
public void addBoxes(PowerBox... boxes) {
for (PowerBox box : boxes) {
//noinspection unchecked
TARGETED_CHANGE_OBSERVER.register(box, this);
}
}
/**
* Indicate that one of the boxes that this view depends on has changed in value, meaning that this view has likely
* changed its value as well. If this view has any {@code ChangeObserver}s they will be notified immediately
* with a new value from the {@link View#calculate()} method.
* Since there is no middleware involved, the last two parameters of
* {@link ChangeObserver#onChange(PowerBox, Object, Object, Object)} will be the same.
* If a new value is successfully calculated, the cache will now be valid. Otherwise it will now be invalid.
*/
private void update() {
if (!getFamily().getChangeObservers().isEmpty()) {
T oldValue = value;
calculateAndCache();
try {
notifyChangeObservers(oldValue, value, value);
} catch (BoxParticipantException e) {
value = oldValue;
cacheValid = false;
throw e;
}
} else {
cacheValid = false;
}
}
// @formatter:off
/**
* Return the value of this view as derived from the boxes it depends on. For the view to function properly, it is
* essential that:
* <ol>
* <li>The result of this method is a deterministic function of the boxes the view depends on, meaning that:
* <ol>
* <li>The method does not depend on any other values of any kind, so add all appropriate boxes in
* the constructor and/or the {@link View#addBoxes(PowerBox[])}
* method and do not rely on any variables not found in boxes.</li>
* <li>Separate calls to this method return the same results if the boxes haven't changed, i.e.
* there is no randomness or internal, invisible state involved.</li>
* </ol></li>
* <li>The values of the boxes cannot change without notifying their {@code ChangeObserver}s
* and thus this view. If the {@code set} method is called on a box its observers will certainly be
* notified, so it remains to ensure that the state of an object cannot change in such a way that
* the result of this method would change without notifying observers. Thus each box must either:
* <ol>
* <li>Contain an immutable type such as {@code Integer} or {@code String}, or</li>
* <li>Intercept any calls that change the value of the box with respect to this method, typically
* by being a {@link WrapperBox}.</li>
* </ol></li>
* </ol>
* <p>
* When {@link PowerBox#get()} is called, {@code calculate()} will be called only if a box has changed its value
* since the previous call to {@code calculate()}. In addition, if the view has any {@code ChangeObserver}s added,
* {@code calculate()} is called every time one of the boxes changes, i.e. the value of view might change.
*/
// @formatter:on
public abstract T calculate();
@Override
protected T rawGet() {
if (cacheValid) {
return value;
}
calculateAndCache();
return value;
}
private void calculateAndCache() {
value = calculate();
cacheValid = true;
}
@Override
public AbstractPowerBox<T> set(T value) {
throw new UnsupportedOperationException("You cannot set a value on a view. It must be calculated.");
}
// Specifying the return type for chaining
@Override | public View<T> addChangeObserver(ChangeObserver... observers) { | 3 |
6thsolution/ApexNLP | english-nlp/src/main/java/com/sixthsolution/apex/nlp/english/DateDetector.java | [
"public class DateDetectionFilter extends ChunkDetectionFilter {\n @Override\n public boolean accept(Label label, TaggedWords taggedWords, int startIndex, int endIndex) {\n switch (label) {\n case FORMAL_DATE:\n case RELAX_DATE:\n case FOREVER_DATE:\n case GL... | import com.nobigsoftware.dfalex.Pattern;
import com.sixthsolution.apex.nlp.english.filter.DateDetectionFilter;
import com.sixthsolution.apex.nlp.ner.Entity;
import com.sixthsolution.apex.nlp.ner.Label;
import com.sixthsolution.apex.nlp.ner.regex.ChunkDetectionFilter;
import com.sixthsolution.apex.nlp.ner.regex.ChunkDetector;
import com.sixthsolution.apex.nlp.util.Pair;
import java.util.Arrays;
import java.util.List;
import static com.nobigsoftware.dfalex.Pattern.*;
import static com.sixthsolution.apex.nlp.dict.Tag.*;
import static com.sixthsolution.apex.nlp.ner.Entity.DATE;
import static com.sixthsolution.apex.nlp.ner.Label.*; | private static Pattern limited_date() {
return match(maybe(DATE_START_RANGE.toString()).then(maybe(anyOf(relax_date(), relative_date(), formal_date()))).then(DATE_RANGE.toString()).then(anyOf(relax_date(), relative_date(), formal_date())));
}
/**
* @return now, this year, today, current year, the year, ...
*/
private static Pattern year_part_current() {
return match(anyOf(match(CURRENT.toString()), match(THE_PREFIX.toString())).then(DATE_SEEKBY.toString()));
}
/**
* @return next year, 2001, the year before 2025, year after next year, year before year 2013, year, ...
*/
private static Pattern year_part() {
return match(anyOf(match(RELATIVE_PREPOSITION.toString()).then(DATE_SEEKBY.toString()), maybe(THE_PREFIX.toString()).thenMaybe(DATE_SEEKBY.toString()).then(NUMBER.toString()),
year_part_relative(), year_part_current(), match(DATE_SEEKBY.toString())));
}
private static Pattern year_part_exact() {
return match(anyOf(match(RELATIVE_PREPOSITION.toString()).thenMaybe(DATE_SEEKBY.toString()), maybe(THE_PREFIX.toString())
.thenMaybe(DATE_SEEKBY.toString()).then(NUMBER.toString()), year_part_current(), match(DATE_SEEKBY.toString())));
}
/**
* @return year after next, after 2001, year before 2025, three years after next year, the year before year 2013, 4 years from today
*/
private static Pattern year_part_relative() {
return match(maybe(anyOf(match(NUMBER.toString()), match(THE_PREFIX.toString()))).then(DATE_SEEKBY.toString())
.then(anyOf(match(GLOBAL_PREPOSITION.toString()), match(DATE_START_RANGE.toString()))).then(year_part_exact()));
}
/**
* @return now, this month, today, current month, the month, ...
*/
private static Pattern month_part_current() {
return match(anyOf(match(CURRENT.toString()), match(THE_PREFIX.toString()).then(DATE_SEEKBY.toString())));
}
private static Pattern month_part_explicit() {
return match(anyOf(match(NUMBER.toString()).then(DATE_SEEKBY.toString()), match(MONTH_NAME.toString())).thenMaybe(match(DATE_PREFIX.toString()).then(year_part())));
}
static Pattern month_part_exact() {
return match(anyOf(month_part_current(), maybe(THE_PREFIX.toString()).then(anyOf(month_part_explicit()))));
}
/**
* @return two months from june(month part), 3rd month after today, 3rd april from now, ...
*/
private static Pattern month_part_relative() {
return match(NUMBER.toString()).then(anyOf(match(DATE_SEEKBY.toString()), match(MONTH_NAME.toString()))
.thenMaybe(anyOf(match(GLOBAL_PREPOSITION.toString()), match(DATE_START_RANGE.toString())).then(month_part_exact())));
}
static Pattern month_part() {
return match(anyOf(match(RELATIVE_PREPOSITION.toString()).then(DATE_SEEKBY.toString()), month_part_current(), maybe(THE_PREFIX.toString()).then(anyOf(month_part_explicit(), month_part_relative()))));
}
/**
* @return now, this week, today, current week, the week, ...
*/
private static Pattern week_part_current() {
return match(anyOf(match(CURRENT.toString()), match(THE_PREFIX.toString()).then(DATE_SEEKBY.toString())));
}
private static Pattern week_part_explicit() {
return match(NUMBER.toString()).then(DATE_SEEKBY.toString()).then(DATE_PREFIX.toString()).then(anyOf(year_part(), month_part()));
}
private static Pattern week_part_exact() {
return maybe(THE_PREFIX.toString()).then(anyOf(week_part_current(), week_part_explicit()));
}
/**
* @return two weeks from first week of next year(week part), 3rd week after today, ...
*/
private static Pattern week_part_relative() {
return match(NUMBER.toString()).then(anyOf(match(GLOBAL_PREPOSITION.toString()), match(DATE_START_RANGE.toString()))).then(week_part_exact());
}
private static Pattern week_part() {
return maybe(THE_PREFIX.toString()).then(anyOf(week_part_current(), week_part_explicit(), week_part_relative()));
}
private static Pattern start_with_number() {
return maybe(THE_PREFIX.toString()).then(NUMBER.toString()).thenMaybe(DATE_SUFFIX.toString()).then(DATE_SEEKBY.toString())
.then(DATE_PREFIX.toString()).then(anyOf(year_part(), month_part(), week_part()));
}
private static Pattern start_with_day_band() {
return match(DATE_BAND.toString()).thenMaybe(anyOf(match(DATE_SEEKBY.toString()), match(WEEK_DAY.toString()), match(MONTH_NAME.toString())))
.then(DATE_PREFIX.toString()).then(anyOf(year_part(), month_part(), week_part()));
}
private static Pattern start_with_day_of_week() {
return match(WEEK_DAY.toString()).then(DATE_PREFIX.toString()).then(anyOf(week_part(), year_part(), month_part()));
}
private static Pattern explicit_relative_date() {
return match(anyOf(start_with_day_band(), start_with_day_of_week(), start_with_number()));
}
@Override
protected List<Pair<Label, Pattern>> getPatterns() {
return Arrays.asList(
newPattern(FORMAL_DATE, formal_date())
, newPattern(RELAX_DATE, relax_date())
, newPattern(RELATIVE_DATE, relative_date())
,newPattern(EXPLICIT_RELATIVE_DATE,explicit_relative_date())
, newPattern(GLOBAL_DATE, global_date())
, newPattern(FOREVER_DATE, forever_date())
, newPattern(LIMITED_DATE, limited_date())
);
}
@Override | protected List<? extends ChunkDetectionFilter> getFilters() { | 3 |
idega/com.idega.documentmanager | src/java/com/idega/documentmanager/component/impl/FormComponentMultiUploadDescriptionImpl.java | [
"public interface ComponentMultiUploadDescription extends Component {\n \n public abstract PropertiesMultiUploadDescription getProperties();\n \n}",
"public interface PropertiesMultiUploadDescription extends PropertiesComponent{\n \n public abstract LocalizedStringBean getRemoveButtonLabel();\n\n ... | import org.w3c.dom.Element;
import com.idega.documentmanager.business.component.ComponentMultiUploadDescription;
import com.idega.documentmanager.business.component.properties.PropertiesMultiUploadDescription;
import com.idega.documentmanager.component.properties.impl.ComponentPropertiesMultiUploadDescription;
import com.idega.documentmanager.component.properties.impl.ConstUpdateType;
import com.idega.documentmanager.manager.XFormsManagerMultiUploadDescription;
import com.idega.documentmanager.util.FormManagerUtil;
import com.idega.util.CoreConstants; | package com.idega.documentmanager.component.impl;
/**
* @author <a href="mailto:arunas@idega.com">Arūnas Vasmanas</a>
* @version $Revision: 1.5 $
*
* Last modified: $Date: 2008/10/26 16:47:10 $ by $Author: anton $
*/
public class FormComponentMultiUploadDescriptionImpl extends FormComponentImpl implements ComponentMultiUploadDescription{
@Override
public XFormsManagerMultiUploadDescription getXFormsManager() {
return getContext().getXformsManagerFactory().getXformsManagerMultiUploadDescription();
}
@Override
public void setReadonly(boolean readonly) {
super.setReadonly(readonly);
Element bindElement = this.getXformsComponentDataBean().getBind().getBindElement();
Element groupElem = this.getXformsComponentDataBean().getElement();
if(readonly) {
bindElement.setAttribute(FormManagerUtil.relevant_att, FormManagerUtil.xpath_false);
groupElem.setAttribute(FormManagerUtil.bind_att, bindElement.getAttribute("id"));
// TODO: needs to transform to link list for downloading files
}else {
if (!CoreConstants.EMPTY.equals(bindElement.getAttribute(FormManagerUtil.relevant_att)))
bindElement.removeAttribute(FormManagerUtil.relevant_att);
groupElem.removeAttribute(FormManagerUtil.bind_att);
}
}
@Override | public PropertiesMultiUploadDescription getProperties(){ | 1 |
ChillingVan/AndroidInstantVideo | app/src/main/java/com/chillingvan/instantvideo/sample/test/publisher/TestCameraPublisherActivity.java | [
"public class CameraPreviewTextureView extends GLMultiTexProducerView {\n\n private H264Encoder.OnDrawListener onDrawListener;\n private IAndroidCanvasHelper drawTextHelper = IAndroidCanvasHelper.Factory.createAndroidCanvasHelper(IAndroidCanvasHelper.MODE.MODE_ASYNC);\n private Paint textPaint;\n\n publ... | import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.chillingvan.canvasgl.ICanvasGL;
import com.chillingvan.canvasgl.glcanvas.BasicTexture;
import com.chillingvan.canvasgl.glview.texture.GLTexture;
import com.chillingvan.canvasgl.textureFilter.BasicTextureFilter;
import com.chillingvan.canvasgl.textureFilter.HueFilter;
import com.chillingvan.canvasgl.textureFilter.TextureFilter;
import com.chillingvan.instantvideo.sample.R;
import com.chillingvan.instantvideo.sample.test.camera.CameraPreviewTextureView;
import com.chillingvan.lib.camera.InstantVideoCamera;
import com.chillingvan.lib.encoder.video.H264Encoder;
import com.chillingvan.lib.muxer.RTMPStreamMuxer;
import com.chillingvan.lib.publisher.CameraStreamPublisher;
import com.chillingvan.lib.publisher.StreamPublisher;
import java.io.IOException;
import java.util.List; | /*
*
* *
* * * Copyright (C) 2017 ChillingVan
* * *
* * * 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.chillingvan.instantvideo.sample.test.publisher;
public class TestCameraPublisherActivity extends AppCompatActivity {
private CameraStreamPublisher streamPublisher;
private CameraPreviewTextureView cameraPreviewTextureView; | private InstantVideoCamera instantVideoCamera; | 1 |
davidmoten/rtree | src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java | [
"public final class CircleDouble implements Circle {\n\n private final double x, y, radius;\n private final Rectangle mbr;\n\n private CircleDouble(double x, double y, double radius) {\n this.x = x;\n this.y = y;\n this.radius = radius;\n this.mbr = RectangleDouble.create(x - ra... | import com.github.davidmoten.guavamini.annotations.VisibleForTesting;
import com.github.davidmoten.rtree.geometry.internal.CircleDouble;
import com.github.davidmoten.rtree.geometry.internal.CircleFloat;
import com.github.davidmoten.rtree.geometry.internal.LineDouble;
import com.github.davidmoten.rtree.geometry.internal.LineFloat;
import com.github.davidmoten.rtree.geometry.internal.PointDouble;
import com.github.davidmoten.rtree.geometry.internal.PointFloat;
import com.github.davidmoten.rtree.geometry.internal.RectangleDouble;
import com.github.davidmoten.rtree.geometry.internal.RectangleFloat; | package com.github.davidmoten.rtree.geometry;
public final class Geometries {
private Geometries() {
// prevent instantiation
}
public static Point point(double x, double y) { | return PointDouble.create(x, y); | 4 |
e-Spirit/basicworkflows | src/main/java/com/espirit/moddev/basicworkflows/release/WorkflowObject.java | [
"public class FsException extends RuntimeException {\n\n private static final long serialVersionUID = -1010220755632543938L;\n\n /**\n * Throws an exception.\n */\n public FsException() {\n super();\n }\n}",
"public class FsLocale {\n\n /**\n * The current locale.\n */\n p... | import com.espirit.moddev.basicworkflows.util.FsException;
import com.espirit.moddev.basicworkflows.util.FsLocale;
import com.espirit.moddev.basicworkflows.util.ReferenceResult;
import com.espirit.moddev.basicworkflows.util.WorkflowConstants;
import com.espirit.moddev.basicworkflows.util.WorkflowSessionHelper;
import de.espirit.common.TypedFilter;
import de.espirit.common.base.Logging;
import de.espirit.common.util.Listable;
import de.espirit.firstspirit.access.BaseContext;
import de.espirit.firstspirit.access.ReferenceEntry;
import de.espirit.firstspirit.access.store.IDProvider;
import de.espirit.firstspirit.access.store.Store;
import de.espirit.firstspirit.access.store.StoreElement;
import de.espirit.firstspirit.access.store.contentstore.Content2;
import de.espirit.firstspirit.access.store.contentstore.ContentFolder;
import de.espirit.firstspirit.access.store.contentstore.ContentStoreRoot;
import de.espirit.firstspirit.access.store.contentstore.ContentWorkflowable;
import de.espirit.firstspirit.access.store.globalstore.GCAFolder;
import de.espirit.firstspirit.access.store.globalstore.GCAPage;
import de.espirit.firstspirit.access.store.globalstore.ProjectProperties;
import de.espirit.firstspirit.access.store.mediastore.Media;
import de.espirit.firstspirit.access.store.mediastore.MediaFolder;
import de.espirit.firstspirit.access.store.pagestore.Content2Section;
import de.espirit.firstspirit.access.store.pagestore.Page;
import de.espirit.firstspirit.access.store.pagestore.PageFolder;
import de.espirit.firstspirit.access.store.pagestore.Section;
import de.espirit.firstspirit.access.store.sitestore.DocumentGroup;
import de.espirit.firstspirit.access.store.sitestore.PageRef;
import de.espirit.firstspirit.access.store.sitestore.PageRefFolder;
import de.espirit.firstspirit.access.store.sitestore.SiteStoreFolder;
import de.espirit.firstspirit.access.store.templatestore.Query;
import de.espirit.firstspirit.access.store.templatestore.TemplateStoreElement;
import de.espirit.firstspirit.access.store.templatestore.WorkflowScriptContext;
import de.espirit.firstspirit.agency.StoreAgent;
import de.espirit.or.schema.Entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set; | /*
* BasicWorkflows Module
* %%
* Copyright (C) 2012 - 2018 e-Spirit AG
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.espirit.moddev.basicworkflows.release;
/**
* This class provides methods to get the references of the workflow object and store them in the session.
*
* @author stephan
* @since 1.0
*/
class WorkflowObject {
/**
* The storeElement to use.
*/
private StoreElement storeElement;
private StoreElement startElement;
/**
* The workflowScriptContext from the workflow.
*/
private WorkflowScriptContext workflowScriptContext;
/**
* The content2 object from the workflow.
*/
private Content2 content2;
/**
* The Entity to use.
*/
private Entity entity;
/**
* The ResourceBundle that contains language specific labels.
*/
private ResourceBundle bundle;
/**
* The logging class to use.
*/
public static final Class<?> LOGGER = WorkflowObject.class;
private boolean releaseRecursively = false;
private final Set<IDProvider> recursiveChildrenList = new HashSet<>();
/**
* Constructor for WorkflowObject.
*
* @param workflowScriptContext The workflowScriptContext from the workflow.
*/
WorkflowObject(final WorkflowScriptContext workflowScriptContext) {
this.workflowScriptContext = workflowScriptContext;
ResourceBundle.clearCache();
bundle = ResourceBundle.getBundle(WorkflowConstants.MESSAGES, new FsLocale(workflowScriptContext).get());
if (workflowScriptContext.getWorkflowable() instanceof ContentWorkflowable) {
content2 = ((ContentWorkflowable) workflowScriptContext.getWorkflowable()).getContent();
entity = ((ContentWorkflowable) workflowScriptContext.getWorkflowable()).getEntity();
} else {
storeElement = (StoreElement) workflowScriptContext.getWorkflowable();
startElement = (StoreElement) workflowScriptContext.getWorkflowable();
}
// get elements from recursive release
final Map<Long, Store.Type>
childrenIdMap =
WorkflowSessionHelper.readObjectFromSession(workflowScriptContext, WorkflowConstants.WF_RECURSIVE_CHILDREN);
if (childrenIdMap != null && !childrenIdMap.isEmpty()) {
final StoreAgent storeAgent = workflowScriptContext.requireSpecialist(StoreAgent.TYPE);
for (final Map.Entry<Long, Store.Type> childrenId : childrenIdMap.entrySet()) {
recursiveChildrenList.add(storeAgent.getStore(childrenId.getValue()).getStoreElement(childrenId.getKey()));
}
}
}
/**
* This method gets the referenced objects from the workflow object (StoreElement) that prevent the release.
*
* @param releaseWithMedia Determines if media references should also be checked
* @return a list of elements that reference the workflow object.
*/
Set<Object> getRefObjectsFromStoreElement(final boolean releaseWithMedia, final boolean recursive) {
return getRefObjectsFromStoreElement(releaseWithMedia, recursive, storeElement);
}
/**
* This method gets the referenced objects from the workflow object (StoreElement) that prevent the release.
*
* @param releaseWithMedia Determines if media references should also be checked
* @return a list of elements that reference the workflow object.
*/
private Set<Object> getRefObjectsFromStoreElement(final boolean releaseWithMedia, final boolean recursive, StoreElement storeElement) {
Set<Object> referencedObjects = new HashSet<>();
if (isPageRef(storeElement)) {
// add outgoing references
referencedObjects.addAll(getReferences(releaseWithMedia, storeElement));
// add outgoing references of referenced page if it is not released
final Page page = ((PageRef) storeElement).getPage();
addOutgoingReferences(page, referencedObjects, releaseWithMedia);
final Set<Object> refObjectsFromSection = getRefObjectsFromSection(page, releaseWithMedia);
referencedObjects.addAll(refObjectsFromSection);
} else if (recursive && storeElement instanceof SiteStoreFolder) {
for (IDProvider idProvider : storeElement.getChildren(IDProvider.class)) {
referencedObjects.addAll(getRefObjectsFromStoreElement(releaseWithMedia, true, idProvider));
}
} else if (isValidStoreElement()) {
// add outgoing references
referencedObjects.addAll(getReferences(releaseWithMedia, storeElement));
if (isPage(storeElement)) {
final Set<Object> refObjectsFromSection = getRefObjectsFromSection(storeElement, releaseWithMedia);
referencedObjects.addAll(refObjectsFromSection);
}
} else if (storeElement instanceof Content2) {
//Element is a content2 object -> aborting" | workflowScriptContext.gotoErrorState(bundle.getString("releaseC2notPossible"), new FsException()); | 0 |
wenerme/bbvm | jbbvm/bbvm-core/src/test/java/me/wener/bbvm/BasmTester.java | [
"public interface ImageManager extends ResourceManager<ImageManager, ImageResource> {\n /**\n * @param file Resource name\n * @param index Resource index start from 0\n */\n ImageResource load(String file, int index);\n\n /**\n * @return Mutable directories to search the resource\n */\... | import com.google.common.base.Throwables;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import me.wener.bbvm.asm.BBAsmParser;
import me.wener.bbvm.asm.ParseException;
import me.wener.bbvm.dev.ImageManager;
import me.wener.bbvm.dev.InputManager;
import me.wener.bbvm.dev.PageManager;
import me.wener.bbvm.dev.swing.Swings;
import me.wener.bbvm.util.Dumper;
import me.wener.bbvm.vm.*;
import me.wener.bbvm.vm.invoke.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.*;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.Scanner;
import static org.junit.Assert.assertNull; | package me.wener.bbvm;
/**
* @author wener
* @since 15/12/13
*/
public class BasmTester {
private final static Logger log = LoggerFactory.getLogger(BasmTester.class);
private static final Config DEFAULT_CONFIG = ConfigFactory.parseString("charset=UTF-8,test-io=true");
private final ByteArrayOutputStream out;
private final InputInvoke in;
private final Charset charset;
// Parse basm
// Compare with bin
// Extract io from basm
// Run
// Compare io
File basmFile;
@Inject
SystemInvokeManager systemInvokeManager;
private Config c;
private PrintStream printStream = System.out;
@Inject
private VM vm;
private String basmContent;
private BBAsmParser parser;
private TestSpec io = new TestSpec();
private Injector injector;
private boolean doTest = true;
public BasmTester() {
this(DEFAULT_CONFIG);
}
public BasmTester(Config config) {
this.c = config;
if (c != DEFAULT_CONFIG) {
c = c.withFallback(DEFAULT_CONFIG);
}
this.charset = Charset.forName(c.getString("charset"));
VMConfig.Builder builder = new VMConfig.Builder()
.withModule(Swings.module())
.charset(charset);
injector = Guice.createInjector(new VirtualMachineModule(builder.build()));
injector.injectMembers(this);
injector.getInstance(ImageManager.class).getResourceDirectory().add("../bbvm-test/image");
out = new ByteArrayOutputStream();
in = new InputInvoke();
// TODO Need a way to make up the input and output
PageManager manager = injector.getInstance(PageManager.class);
if (c.getBoolean("test-io")) {
systemInvokeManager.register(new OutputInvoke((s) -> {
try {
out.write(s.getBytes());
} catch (IOException e) {
Throwables.propagate(e);
}
manager.getScreen().draw(s);
}), in);
} else {
systemInvokeManager.register(new OutputInvoke((s) -> {
manager.getScreen().draw(s);
}), new InputInvoke().setSupplier(() -> injector.getInstance(InputManager.class).readText()));
}
systemInvokeManager.register(GraphInvoke.class, BasicInvoke.class, FileInvoke.class, KeyInvoke.class);
}
public BasmTester setPrintStream(PrintStream printStream) {
this.printStream = printStream;
return this;
}
public BasmTester init(File basm) {
log.info("Init basm tester {}", basm);
basmFile = basm;
try {
basmContent = new String(Files.readAllBytes(basm.toPath()), charset);
} catch (IOException e) {
throw Throwables.propagate(e);
}
parser = new BBAsmParser(new StringReader(basmContent));
parser.setCharset(charset);
io.clear().accept(basmContent);
return this;
}
public void run() {
out.reset();
Scanner scanner = new Scanner(io.output().toString());
in.setSupplier(scanner::nextLine);
try {
parser.Parse();
parser.getAssemblies().stream().forEach(s -> printStream.printf("%02d %s\n", s.getLine(), s.toAssembly()));
} catch (ParseException e) {
Throwables.propagate(e);
}
int length = parser.estimateAddress();
printStream.printf("Estimate length is %s\n", length);
printStream.printf("Expected output \n%s\nWith input\n%s\n", io.output(), io.input());
parser.checkLabel();
ByteBuf buf = Unpooled.buffer(length).order(ByteOrder.LITTLE_ENDIAN);
parser.write(buf);
printStream.println(basmContent); | printStream.println(Dumper.hexDumpReadable(buf)); | 4 |
wtud/tsap | tsap/src/org/tribler/tsap/downloads/DownloadActivity.java | [
"public class Torrent implements Serializable {\n\n\tprivate static final long serialVersionUID = 1619276011406943212L;\n\n\tprivate String name;\n\tprivate String infoHash;\n\tprivate long size;\n\tprivate int seeders;\n\tprivate int leechers;\n\tprivate File thumbnailFile = null;\n\tprivate String category;\n\n\t... | import org.tribler.tsap.R;
import org.tribler.tsap.Torrent;
import org.tribler.tsap.streaming.PlayButtonListener;
import org.tribler.tsap.util.MainThreadPoller;
import org.tribler.tsap.util.Poller.IPollListener;
import org.tribler.tsap.util.ThumbnailUtils;
import org.tribler.tsap.util.Utility;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView; | package org.tribler.tsap.downloads;
/**
* Activity that shows detailed information of a download
*
* @author Dirk Schut & Niels Spruit
*
*/
public class DownloadActivity extends Activity implements IPollListener {
private ActionBar mActionBar;
private Download mDownload;
private Torrent mTorrent;
private View mView; | private MainThreadPoller mPoller; | 2 |
guiguito/AIRShare | shAIRe/src/main/java/com/ggt/airshare/httpserver/ShAIReHttpServer.java | [
"public class UrlShortener {\n\n private static UrlShortener mInstance;\n\n private static AQuery mAQuery;\n\n private static final String ERROR_MESSAGE = \"Url shortening failed\";\n\n private UrlShortener(Context context) {\n if (mAQuery == null) {\n mAQuery = new AQuery(context);\n ... | import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import com.ggt.airshare.R;
import com.ggt.airshare.urlshortener.UrlShortener;
import com.ggt.airshare.urlshortener.UrlShortenerException;
import com.ggt.airshare.urlshortener.UrlShortenerListener;
import com.ggt.airshare.utils.ContactsUtils;
import com.ggt.airshare.utils.HTMLUtils;
import com.ggt.airshare.utils.NetworkUtils;
import com.ggt.airshare.utils.ShAIReConstants;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.android.encode.QRCodeEncoder;
import com.google.zxing.client.result.AddressBookParsedResult;
import com.ipaulpro.afilechooser.utils.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.Random; | package com.ggt.airshare.httpserver;
/**
* Sharing nano server .
*
* @author gduche
*/
public class ShAIReHttpServer extends NanoHTTPD implements UrlShortenerListener {
private String mFilePath;
private String mMimeType;
private String mTextToShare;
private Context mContext;
private String mRealUrl;
private String mRandomString;
private QRCodeEncoder mQrCodeEncoder;
private ShAIReHttpServerListener mShAIReHttpServerListener;
private static final String GET_STRING = "GET";
private static final String URL_BEGIN = "http://";
public ShAIReHttpServer(Context context,
ShAIReHttpServerListener shAIReHttpServerListener, Intent intent)
throws IOException { | super(ShAIReConstants.SERVER_PORT, null); | 5 |
Toberumono/WRF-Runner | src/toberumono/wrf/timing/NamelistTiming.java | [
"public class WRFRunnerComponentFactory<T> {\n\tprivate static final Map<Class<?>, WRFRunnerComponentFactory<?>> factories = new HashMap<>();\n\tprivate final Map<String, BiFunction<ScopedMap, Scope, T>> components;\n\tprivate String defaultComponentType;\n\tprivate BiFunction<ScopedMap, Scope, T> disabledComponent... | import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
import toberumono.namelist.parser.Namelist;
import toberumono.namelist.parser.NamelistSection;
import toberumono.wrf.WRFRunnerComponentFactory;
import toberumono.wrf.scope.AbstractScope;
import toberumono.wrf.scope.Scope;
import toberumono.wrf.timing.clear.Clear;
import toberumono.wrf.timing.duration.Duration;
import toberumono.wrf.timing.duration.NamelistDuration;
import toberumono.wrf.timing.offset.Offset;
import toberumono.wrf.timing.round.Round;
import static toberumono.wrf.SimulationConstants.*; | package toberumono.wrf.timing;
/**
* Implementation of {@link Timing} that uses static data from a {@link Namelist} file instead of computing the timing data at runtime.
*
* @author Toberumono
*/
public class NamelistTiming extends AbstractScope<Scope> implements Timing {
private static final List<String> TIMING_FIELD_SINGULAR_NAMES = TIMING_FIELD_NAMES.stream().map(s -> s.substring(0, s.length() - 1)).collect(Collectors.toList());
private final Calendar base;
private final Calendar start, end; | private final Offset offset; | 6 |
syvaidya/openstego | src/test/java/com/openstego/desktop/plugin/randlsb/RandomLSBOutputStreamTest.java | [
"public class OpenStegoException extends Exception {\n private static final long serialVersionUID = 668241029491685413L;\n\n /**\n * Error Code - Unhandled exception\n */\n static final int UNHANDLED_EXCEPTION = 0;\n\n /**\n * Map to store error code to message key mapping\n */\n priv... | import com.openstego.desktop.OpenStegoException;
import com.openstego.desktop.plugin.lsb.LSBConfig;
import com.openstego.desktop.plugin.lsb.LSBDataHeader;
import com.openstego.desktop.plugin.lsb.LSBErrors;
import com.openstego.desktop.plugin.lsb.LSBPlugin;
import com.openstego.desktop.util.ImageHolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.awt.image.BufferedImage;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*; | /*
* Steganography utility to hide messages into cover files
* Author: Samir Vaidya (mailto:syvaidya@gmail.com)
* Copyright (c) Samir Vaidya
*/
package com.openstego.desktop.plugin.randlsb;
/**
* Unit test class for {@link com.openstego.desktop.plugin.randlsb.RandomLSBOutputStream}
*/
public class RandomLSBOutputStreamTest {
@BeforeEach
public void setup() {
RandomLSBPlugin plugin = new RandomLSBPlugin();
assertNotNull(plugin);
}
@Test
public void testBestCase() throws Exception {
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
ImageHolder holder = new ImageHolder(image, null); | LSBConfig config = new LSBConfig(); | 1 |
RoboTricker/Transport-Pipes | src/main/java/de/robotricker/transportpipes/inventory/CraftingPipeSettingsInventory.java | [
"public class TransportPipes extends JavaPlugin {\n\n private Injector injector;\n\n private SentryService sentry;\n private ThreadService thread;\n private DiskService diskService;\n\n @Override\n public void onEnable() {\n\n if (Bukkit.getVersion().contains(\"1.13\")) {\n Legac... | import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.attribute.Attribute;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.DragType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.RecipeChoice;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.ShapelessRecipe;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.PressurePlate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import de.robotricker.transportpipes.TransportPipes;
import de.robotricker.transportpipes.config.LangConf;
import de.robotricker.transportpipes.duct.pipe.CraftingPipe;
import de.robotricker.transportpipes.duct.pipe.filter.ItemData;
import de.robotricker.transportpipes.location.TPDirection; | package de.robotricker.transportpipes.inventory;
public class CraftingPipeSettingsInventory extends DuctSettingsInventory {
@Override
public void create() {
inv = Bukkit.createInventory(null, 6 * 9, LangConf.Key.DUCT_INVENTORY_TITLE.get(duct.getDuctType().getFormattedTypeName()));
}
@Override
public void closeForAllPlayers(TransportPipes transportPipes) {
save(null);
super.closeForAllPlayers(transportPipes);
}
@Override
public void populate() {
CraftingPipe pipe = (CraftingPipe) duct;
TPDirection outputDir = pipe.getOutputDir();
List<ItemStack> cachedItems = pipe.getCachedItems();
ItemStack glassPane = itemService.createWildcardItem(Material.GRAY_STAINED_GLASS_PANE);
for (int i = 0; i < 9; i++) {
inv.setItem(i, glassPane);
}
ItemStack outputDirectionItem = itemService.changeDisplayNameAndLoreConfig(new ItemStack(Material.TRIPWIRE_HOOK), LangConf.Key.DUCT_INVENTORY_CRAFTINGPIPE_OUTPUTDIRECTION.getLines(outputDir != null ? outputDir.getDisplayName() : LangConf.Key.DIRECTIONS_NONE.get()));
inv.setItem(8, outputDirectionItem);
for (int col = 0; col < 9; col += 4) {
for (int row = 1; row < 4; row++) {
inv.setItem(row * 9 + col, glassPane);
}
}
for (int i = 0; i < 9; i++) { | ItemData id = pipe.getRecipeItems()[i]; | 3 |
mitdbg/AdaptDB | src/main/java/core/adapt/spark/join/SparkJoinQuery.java | [
"public static class PartitionSplit {\n\tprivate int[] partitionIds;\n\tprivate PartitionIterator iterator;\n\n\tpublic PartitionSplit(int[] partitionIds, PartitionIterator iterator) {\n\t\tthis.partitionIds = partitionIds;\n\t\tthis.iterator = iterator;\n\t}\n\n\tpublic int[] getPartitions() {\n\t\treturn this.par... | import core.adapt.AccessMethod.PartitionSplit;
import core.adapt.JoinQuery;
import core.common.globals.Globals;
import core.common.globals.TableInfo;
import core.common.index.MDIndex;
import core.utils.HDFSUtils;
import core.utils.SparkUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import core.utils.ConfUtils;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | package core.adapt.spark.join;
/**
* Created by ylu on 1/6/16.
*/
public class SparkJoinQuery {
public static class Mapper implements PairFunction<Tuple2<LongWritable, Tuple2<Text, Text>>, LongWritable, Text> {
String Delimiter;
String Splitter;
int partitionKey;
public Mapper(String Delimiter, int partitionKey) {
this.Delimiter = Delimiter;
this.partitionKey = partitionKey;
if (Delimiter.equals("|"))
Splitter = "\\|";
else
Splitter = Delimiter;
}
@Override
public Tuple2<LongWritable, Text> call(Tuple2<LongWritable, Tuple2<Text, Text>> x) throws Exception {
String s1 = x._2()._1().toString();
String s2 = x._2()._2().toString();
String value = s1 + Delimiter + s2;
long key = Long.parseLong(value.split(Splitter)[partitionKey]);
return new Tuple2<LongWritable, Text>(new LongWritable(key), new Text(value));
}
}
private SparkJoinQueryConf queryConf;
private JavaSparkContext ctx;
private ConfUtils cfg;
private String Delimiter = "|";
private String joinStrategy = "Heuristic";
public SparkJoinQuery(ConfUtils config) {
this.cfg = config;
SparkConf sconf = SparkUtils.getSparkConf(this.getClass().getName(), config);
try {
sconf.registerKryoClasses(new Class<?>[]{
Class.forName("org.apache.hadoop.io.LongWritable"),
Class.forName("org.apache.hadoop.io.Text")
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ctx = new JavaSparkContext(sconf);
ctx.hadoopConfiguration().setBoolean(
FileInputFormat.INPUT_DIR_RECURSIVE, true);
ctx.hadoopConfiguration().set("fs.hdfs.impl",
org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
queryConf = new SparkJoinQueryConf(ctx.hadoopConfiguration());
queryConf.setHDFSReplicationFactor(cfg.getHDFS_REPLICATION_FACTOR());
queryConf.setHadoopHome(cfg.getHADOOP_HOME());
queryConf.setZookeeperHosts(cfg.getZOOKEEPER_HOSTS());
queryConf.setMaxSplitSize(4L * 1024 * 1024 * 1024); // 4 GB
//queryConf.setMaxSplitSize(400L * 1024 * 1024); // 400 MB
queryConf.setWorkerNum(8);
}
public JavaSparkContext getSparkContext(){
return ctx;
}
public void setBufferSize(long size){
queryConf.setMaxSplitSize(size);
}
public void setDelimiter(String delimiter) {
Delimiter = delimiter;
}
public String getDelimiter() {
return Delimiter;
}
/* SparkJoinQuery */
public JavaPairRDD<LongWritable, Text> createJoinRDD(String hdfsPath) {
queryConf.setReplicaId(0);
return ctx.newAPIHadoopFile(cfg.getHADOOP_NAMENODE() + hdfsPath,
SparkJoinInputFormat.class, LongWritable.class,
Text.class, ctx.hadoopConfiguration());
}
public JavaPairRDD<LongWritable, Text> createJoinRDD(
String dataset1, JoinQuery dataset1_query,
String dataset2, JoinQuery dataset2_query,
int partitionKey) {
// set SparkQuery conf
String hdfsPath = cfg.getHDFS_WORKING_DIR();
queryConf.setWorkingDir(hdfsPath);
queryConf.setJustAccess(false);
Configuration conf = ctx.hadoopConfiguration();
conf.set("DATASET1", dataset1);
conf.set("DATASET2", dataset2);
conf.set("DATASET1_QUERY", dataset1_query.toString());
conf.set("DATASET2_QUERY", dataset2_query.toString());
conf.set("PARTITION_KEY", Integer.toString(partitionKey)) ;
conf.set("JOINALGO", joinStrategy);
conf.set("DELIMITER", Delimiter);
JoinPlanner planner = new JoinPlanner(conf);
String hyperJoinInput = planner.hyperjoin;
System.out.println("hyperJoinInput: " + hyperJoinInput);
conf.set("DATASETINFO",hyperJoinInput);
JavaPairRDD<LongWritable, Text> hyperjoin_rdd = createJoinRDD(hdfsPath);
String input1 = planner.shufflejoin1;
String input2 = planner.shufflejoin2;
System.out.println("shuffleInput1: " + input1);
System.out.println("shuffleInput2: " + input2);
// set conf input;
conf.set("DATASET_QUERY", dataset1_query.toString());
conf.set("DATASETINFO", input1);
conf.set("DATASET", dataset1);
JavaPairRDD<LongWritable, Text> dataset1RDD = createSingleTableRDD(hdfsPath, dataset1_query);
// set conf input;
conf.set("DATASET_QUERY", dataset2_query.toString());
conf.set("DATASETINFO", input2);
conf.set("DATASET", dataset2);
JavaPairRDD<LongWritable, Text> dataset2RDD = createSingleTableRDD(hdfsPath, dataset2_query);
int numPartitions = 2000;
JavaPairRDD<LongWritable, Tuple2<Text,Text> > join_rdd = dataset1RDD.join(dataset2RDD, numPartitions);
JavaPairRDD<LongWritable, Text> shufflejoin_rdd = join_rdd.mapToPair(new Mapper(Delimiter, partitionKey));
return hyperjoin_rdd.union(shufflejoin_rdd);
}
/* SingleTableScan */
public JavaPairRDD<LongWritable, Text> createSingleTableRDD(String hdfsPath,
JoinQuery q) {
queryConf.setWorkingDir(hdfsPath);
queryConf.setJoinQuery(q);
return ctx.newAPIHadoopFile(cfg.getHADOOP_NAMENODE() + hdfsPath + "/" + q.getTable() + "/data",
SparkScanInputFormat.class, LongWritable.class,
Text.class, ctx.hadoopConfiguration());
}
/* for tpch 6 */
public JavaPairRDD<LongWritable, Text> createScanRDD(String dataset, JoinQuery q) {
// set SparkQuery conf
String hdfsPath = cfg.getHDFS_WORKING_DIR();
queryConf.setJustAccess(false);
queryConf.setWorkingDir(hdfsPath);
Configuration conf = ctx.hadoopConfiguration();
conf.set("DATASET", dataset);
conf.set("DATASET_QUERY", q.toString());
conf.set("PARTITION_KEY", "0") ;
conf.set("JOINALGO", joinStrategy);
conf.set("DELIMITER", Delimiter);
FileSystem fs = HDFSUtils.getFSByHadoopHome(queryConf.getHadoopHome());
String workingDir = queryConf.getWorkingDir();
//System.out.println("INFO working dir: " + workingDir);
List<JoinQuery> dataset_queryWindow = JoinPlanner.loadQueries(dataset, queryConf);
dataset_queryWindow.add(q);
JoinPlanner.persistQueryToDisk(q, queryConf);
| Globals.loadTableInfo(dataset, queryConf.getWorkingDir(), fs); | 2 |
DestinyVaultHelper/dvh | app/src/main/java/org/swistowski/vaulthelper/models/Item.java | [
"public class Application extends android.app.Application {\n private Tracker mTracker;\n private ClientWebView mWebView;\n\n @Override\n public void onCreate()\n {\n mWebView = new ClientWebView(getApplicationContext());\n ImageStorage.getInstance().setContext(getApplicationContext());... | import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.swistowski.vaulthelper.Application;
import org.swistowski.vaulthelper.R;
import org.swistowski.vaulthelper.storage.Characters;
import org.swistowski.vaulthelper.storage.ItemMonitor;
import org.swistowski.vaulthelper.storage.Items;
import org.swistowski.vaulthelper.storage.Data;
import org.swistowski.vaulthelper.storage.Labels;
import org.swistowski.vaulthelper.views.ClientWebView;
import org.swistowski.vaulthelper.views.QuantitySelectView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map; |
@Override
public int compareTo(Item another) {
return Ordering.getInstance().doOrder(this, another);
//return orderFunctionMap.get(Preferences.getInstance().getOrdering()).doOrder(this, another);
}
public String[] debugAttrs() {
String[] ret = new String[]{};
return ret;
}
public String toString() {
return mName;
}
public long getItemHash() {
return mItemHash;
}
public int getLocation() {
return mLocation;
}
public String getName() {
return mName;
}
public String getIcon() {
return mIcon;
}
public void setIcon(String icon) {
mIcon = icon;
}
public boolean isVisible() {
if (getStackSize() == 0) {
return false;
}
return true;
}
public String getItemId() {
return mItemInstanceId;
}
public String getDetails() {
return mItemDescription;
}
public void moveTo(String target, int stackSize) {
Items.getInstance().changeOwner(this, target, stackSize);
}
public boolean isEquipped() {
return mIsEquipped;
}
public long getBucketTypeHash() {
return mBucketTypeHash;
}
public void setIsEquipped(boolean isEquipped) {
mIsEquipped = isEquipped;
}
public int getPrimaryStatValue() {
return mPrimaryStatValue;
}
public int getDamageType() {
return mDamageType;
}
public String getDamageTypeName() {
if (mDamageType == DAMAGE_TYPE_SOLAR) {
return "Solar";
} else if (mDamageType == DAMAGE_TYPE_ARC) {
return "Arc";
} else if (mDamageType == DAMAGE_TYPE_VOID) {
return "Void";
}
return "";
}
public int getType() {
return mItemType;
}
public int getStackSize() {
return mStackSize;
}
public String getBucketName() {
return mBucketName;
}
public boolean getIsCompleted() {
return mIsGridComplete;
}
public long getInstanceId() {
return Long.valueOf(mItemInstanceId);
}
public boolean getCanEquip() {
return mCanEquip;
}
public void setCanEquip(boolean canEquip) {
mCanEquip = canEquip;
}
public boolean isMoveable() {
return mLocation == LOCATION_INVENTORY || mLocation == LOCATION_VAULT;
}
private void doMove(final Activity activity, final Item finalItem, final String owner, int stackSize) { | ItemMover.move(((Application) activity.getApplication()).getWebView(), finalItem, owner, stackSize).then( | 0 |
wix/wix-embedded-mysql | wix-embedded-mysql/src/main/java/com/wix/mysql/store/SafeExtractedArtifactStoreBuilder.java | [
"public class DownloadConfig implements AdditionalConfig {\n private final String cacheDir;\n private final String baseUrl;\n private final IProxyFactory proxyFactory;\n\n private DownloadConfig(\n final String cacheDir,\n final String baseUrl,\n final IProxyFactory prox... | import com.wix.mysql.config.DownloadConfig;
import com.wix.mysql.config.DownloadConfigBuilder;
import com.wix.mysql.config.MysqldConfig;
import com.wix.mysql.config.directories.TargetGeneratedFixedPath;
import com.wix.mysql.config.extract.NoopNaming;
import com.wix.mysql.config.extract.PathPrefixingNaming;
import de.flapdoodle.embed.process.extract.DirectoryAndExecutableNaming;
import de.flapdoodle.embed.process.io.directories.FixedPath;
import de.flapdoodle.embed.process.io.directories.IDirectory;
import de.flapdoodle.embed.process.store.Downloader;
import de.flapdoodle.embed.process.store.IArtifactStore;
import java.io.File;
import java.util.UUID; | package com.wix.mysql.store;
public class SafeExtractedArtifactStoreBuilder extends de.flapdoodle.embed.process.store.ExtractedArtifactStoreBuilder {
public SafeExtractedArtifactStoreBuilder defaults(
final MysqldConfig mysqldConfig,
final DownloadConfig downloadConfig) {
String tempExtractDir = String.format("mysql-%s-%s", mysqldConfig.getVersion().getMajorVersion(), UUID.randomUUID());
String combinedPath = new File(mysqldConfig.getTempDir(), tempExtractDir).getPath();
IDirectory preExtractDir = new FixedPath(new File(downloadConfig.getCacheDir(), "extracted").getPath());
executableNaming().setDefault(new PathPrefixingNaming("bin/"));
download().setDefault(new DownloadConfigBuilder().defaults(downloadConfig).build());
downloader().setDefault(new Downloader());
extractDir().setDefault(preExtractDir);
extractExecutableNaming().setDefault(new NoopNaming());
| tempDir().setDefault(new TargetGeneratedFixedPath(combinedPath)); | 3 |
steeleforge/ironsites | core/src/main/java/com/steeleforge/aem/ironsites/wcm/components/LinkUse.java | [
"public enum WCMConstants {\n INSTANCE;\n public static final String HTTP = \"http\";\n public static final String HTTPS = \"https\";\n public static final String PROTOCOL_RELATIVE = \"//\";\n public static final String DELIMITER_QUERY = \"?\";\n public static final String DELIMITER_FRAGMENT = \"#... | import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import com.adobe.cq.sightly.WCMUse;
import com.day.cq.wcm.api.Page;
import com.steeleforge.aem.ironsites.wcm.WCMConstants;
import com.steeleforge.aem.ironsites.wcm.WCMURLBuilder;
import com.steeleforge.aem.ironsites.wcm.WCMUtil;
import com.steeleforge.aem.ironsites.wcm.page.filter.HidePageFilter;
import com.steeleforge.aem.ironsites.wcm.page.filter.InvalidPageFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List; | /**
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org/>
*/
package com.steeleforge.aem.ironsites.wcm.components;
public class LinkUse extends WCMUse {
// statics
public static final String PN_PATH = "path";
public static final String PN_TEXT = "text";
public static final String PN_NAVTITLE = "navTitle";
public static final String PN_HIDEINNAV = "hideInNav";
// local
private String path;
private Link link;
private Page page;
private Boolean navTitle = false;
private Boolean hideInNav = true;
private String id;
private String href;
private String name;
private String styles;
private String target;
private String rel;
private String download;
private String media;
private String hreflang;
private String type;
private Boolean ping;
private String text;
@Override
public void activate() throws Exception {
path = get(PN_PATH, String.class);
if (null == path) path = getProperties().get(PN_PATH, String.class);
page = WCMUtil.getPage(getRequest(), path);
navTitle = get(PN_NAVTITLE, Boolean.class);
navTitle = (null == navTitle)? false : true;
hideInNav = get(PN_HIDEINNAV, Boolean.class);
hideInNav = (null == hideInNav)? true : false;
id = get(Link.PN_ID, String.class);
href = get(Link.PN_HREF, String.class);
name = get(Link.PN_NAME, String.class);
styles = get(Link.PN_STYLES, String.class);
target = get(Link.PN_TARGET, String.class);
rel = get(Link.PN_REL, String.class);
download = get(Link.PN_DOWNLOAD, String.class);
media = get(Link.PN_MEDIA, String.class);
hreflang = get(Link.PN_HREFLANG, String.class);
type = get(Link.PN_TYPE, String.class);
ping = get(Link.PN_PING, Boolean.class);
text = get(Link.PN_TEXT, String.class);
if (null == text) text = getProperties().get(PN_TEXT, String.class);
link = setLink();
}
private Link setLink() {
link = (null != page)? new Link(getRequest(), page) : new Link();
if (null != page) {
link.setPage(page.getPath());
if (getCurrentPage().getPath().equals(page.getPath())) {
link.setCurrent(true);
}
if (StringUtils.startsWith(getCurrentPage().getPath(),
page.getPath() + WCMConstants.DELIMITER_PATH)) {
link.setDescendent(true);
}
if (navTitle) {
text = WCMUtil.getPageNavigationTitle(page);
} else {
text = WCMUtil.getPageTitle(page);
}
} else {
final String[] pathTokens = StringUtils.split(path, WCMConstants.DELIMITER_MULTIFIELD);
if (ArrayUtils.getLength(pathTokens) > 1) {
// <path>|<title>
path = pathTokens[0];
if (StringUtils.isBlank(text)) text = pathTokens[1];
} else {
text = path;
}
}
link.setText(text);
path = new WCMURLBuilder(getRequest()).setPath(path).build();
link.setHref(path);
if (null != id) link.setId(id);
if (null != href) link.setHref(href);
if (null != name) link.setName(name);
if (null != styles) link.setStyles(styles);
if (null != target) link.setTarget(target);
if (null != rel) link.setRel(rel);
if (null != download) link.setDownload(download);
if (null != media) link.setMedia(media);
if (null != hreflang) link.setHreflang(hreflang);
if (null != type) link.setType(type);
if (null != ping) link.setPing(ping);
return link;
}
public Link getLink() {
return link;
}
public List<Link> getLinks() {
if (null != page) {
List<Link> links = new ArrayList<Link>();
Iterator<Page> children = (hideInNav)? | page.listChildren(HidePageFilter.HIDE_IN_NAVIGATION_FILTER) | 3 |
JoeSteven/BiBi | app/src/main/java/com/joe/bibi/activity/DebateActivity.java | [
"public class BBApplication extends Application{\n public static BBApplication mInstance;\n\n public List<BmobChatUser> getContactList() {\n return ContactList;\n }\n\n public void setContactList(List<BmobChatUser> contactList) {\n ContactList = contactList;\n }\n\n public List<BmobC... | import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.github.siyamed.shapeimageview.CircularImageView;
import com.joe.bibi.R;
import com.joe.bibi.application.BBApplication;
import com.joe.bibi.domain.BBUser;
import com.joe.bibi.domain.Comment;
import com.joe.bibi.domain.Debate;
import com.joe.bibi.domain.Follow;
import com.joe.bibi.utils.AnimUtils;
import com.joe.bibi.utils.ConsUtils;
import com.joe.bibi.utils.PrefUtils;
import com.joe.bibi.utils.ToastUtils;
import com.joe.bibi.view.PullUpListView;
import org.xutils.x;
import java.util.ArrayList;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener; | package com.joe.bibi.activity;
public class DebateActivity extends AppCompatActivity {
private static final int SHOW_CURRENT_VS = 0;
private static final int POS_PLUS = 1;
private static final int NEG_PLUS = 2;
private boolean isFabOn;
private FloatingActionButton fabComment;
private FloatingActionButton fabFollow; | private Debate mDebate; | 3 |
jeffprestes/brasilino | android/Brasilino/app/src/main/java/com/paypal/developer/brasilino/broadcast/PaymentOrderReceiver.java | [
"public class PermissionActivity extends ActionBarActivity {\n\n private WebView webContent;\n private ProgressBar progress;\n private Bundle receivedExtras;\n private Token token;\n\n @Override\n protected void onSaveInstanceState(@NonNull Bundle outState) {\n super.onSaveInstanceState(out... | import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationManagerCompat;
import com.paypal.developer.brasilino.PermissionActivity;
import com.paypal.developer.brasilino.application.CarrinhoApplication;
import com.paypal.developer.brasilino.database.CandieSQLiteDataSource;
import com.paypal.developer.brasilino.domain.Token;
import com.paypal.developer.brasilino.service.PaymentService;
import com.paypal.developer.brasilino.util.IntentParameters;
import com.paypal.developer.brasilino.util.Util; | package com.paypal.developer.brasilino.broadcast;
/**
* Created by ricardo on 31/01/2015.
*/
public class PaymentOrderReceiver extends BroadcastReceiver {
public PaymentOrderReceiver() {}
@Override
public void onReceive(Context context, Intent intent) {
NotificationManagerCompat.from(context).cancel(Util.NOTIFICATION_ID);
if(intent != null && intent.hasExtra(IntentParameters.UUID)) {
CandieSQLiteDataSource dataSource = CarrinhoApplication.getDatasource();
if(dataSource != null) { | Token token = dataSource.getToken(); | 3 |
synapticloop/routemaster | src/main/java/synapticloop/nanohttpd/example/servant/ModulesRouteServant.java | [
"public abstract class Routable {\n\t// the route that this routable is bound to\n\tprotected String routeContext = null;\n\t// the map of option key values\n\tprotected Map<String, String> options = new HashMap<String, String>();\n\n\t/**\n\t * Create a new routable class with the bound routing context\n\t *\n\t *... | import java.io.File;
import java.util.Iterator;
import synapticloop.nanohttpd.router.Routable;
import synapticloop.nanohttpd.router.RouteMaster;
import synapticloop.nanohttpd.utils.HttpUtils;
import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import fi.iki.elonen.NanoHTTPD.Response; | package synapticloop.nanohttpd.example.servant;
/*
* Copyright (c) 2013-2020 synapticloop.
*
* All rights reserved.
*
* This source code and any derived binaries are covered by the terms and
* conditions of the Licence agreement ("the Licence"). You may not use this
* source code or any derived binaries except in compliance with the Licence.
* A copy of the Licence is available in the file named LICENCE shipped with
* this source code or binaries.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
public class ModulesRouteServant extends Routable {
public ModulesRouteServant(String routeContext) {
super(routeContext);
}
@Override | public Response serve(File rootDir, IHTTPSession httpSession) { | 4 |
razerdp/FriendCircle | module_main/src/main/java/com/razerdp/github/module/main/ui/TimeLineFragment.java | [
"public abstract class BaseAppFragment extends BaseLibFragment {\n}",
"public class RandomUtil {\n\n private static final String CHAR_LETTERS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n private static final String CHAR_NUMBER = \"0123456789\";\n private static final String CHAR_ALL = CH... | import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.razerdp.github.common.base.BaseAppFragment;
import com.razerdp.github.lib.utils.RandomUtil;
import com.razerdp.github.lib.utils.UIHelper;
import com.razerdp.github.module.main.R;
import com.razerdp.github.module.main.R2;
import com.razerdp.github.uilib.base.adapter.BaseMultiRecyclerViewHolder;
import com.razerdp.github.uilib.base.adapter.MultiRecyclerViewAdapter;
import com.razerdp.github.uilib.base.adapter.SimpleMultiType;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView; | package com.razerdp.github.module.main.ui;
/**
* Created by 大灯泡 on 2019/8/3.
* <p>
* 朋友圈时间线fragment
*/
public class TimeLineFragment extends BaseAppFragment {
@BindView(R2.id.rv_content)
RecyclerView mRvContent;
@Override
public int layoutId() {
return R.layout.fragment_time_line;
}
@Override
protected void onInitView(View rootView) {
List<SimpleMultiType> multiTypes = new ArrayList<>();
int[] types = {1, 2, 3}; | for (int i = 0; i < RandomUtil.randomInt(100, 500); i++) { | 1 |
cesquivias/mumbler | lang/src/main/java/mumbler/truffle/parser/Reader.java | [
"public class BigIntegerSyntax extends Syntax<BigInteger> {\n\tpublic BigIntegerSyntax(BigInteger value, SourceSection source) {\n\t\tsuper(value, source);\n\t}\n}",
"public class BooleanSyntax extends Syntax<Boolean> {\n\tpublic BooleanSyntax(boolean value, SourceSection source) {\n\t\tsuper(value, source);\n\t}... | import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import mumbler.truffle.syntax.BigIntegerSyntax;
import mumbler.truffle.syntax.BooleanSyntax;
import mumbler.truffle.syntax.ListSyntax;
import mumbler.truffle.syntax.LongSyntax;
import mumbler.truffle.syntax.StringSyntax;
import mumbler.truffle.syntax.SymbolSyntax;
import mumbler.truffle.type.MumblerList;
import mumbler.truffle.type.MumblerSymbol;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.source.SourceSection; | package mumbler.truffle.parser;
public class Reader extends MumblerBaseVisitor<Syntax<?>> {
public static ListSyntax read(Source source) throws IOException {
return (ListSyntax) new Reader(source)
.visit(createParseTree(source.getInputStream()));
}
public static Syntax<?> readForm(Source source) throws IOException {
return ((ListSyntax) new Reader(source).visit(
createParseTree(source.getInputStream())))
.getValue()
.car();
}
private static ParseTree createParseTree(InputStream istream)
throws IOException {
ANTLRInputStream input = new ANTLRInputStream(istream);
MumblerLexer lexer = new MumblerLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
MumblerParser parser = new MumblerParser(tokens);
return parser.file();
}
private final Source source;
private Reader(Source source) {
this.source = source;
}
@Override
public ListSyntax visitFile(MumblerParser.FileContext ctx) {
List<Syntax<?>> forms = new ArrayList<>();
for (MumblerParser.FormContext form : ctx.form()) {
forms.add(this.visit(form));
}
return new ListSyntax(MumblerList.list(forms),
createSourceSection(ctx));
}
@Override
public ListSyntax visitList(MumblerParser.ListContext ctx) {
List<Syntax<?>> forms = new ArrayList<>();
for (MumblerParser.FormContext form : ctx.form()) {
forms.add(this.visit(form));
}
return new ListSyntax(MumblerList.list(forms),
createSourceSection(ctx));
}
@Override
public Syntax<?> visitNumber(MumblerParser.NumberContext ctx) {
try {
return new LongSyntax(Long.valueOf(ctx.getText(), 10),
createSourceSection(ctx));
} catch (NumberFormatException e) {
return new BigIntegerSyntax(new BigInteger(ctx.getText()),
createSourceSection(ctx));
}
}
private SourceSection createSourceSection(ParserRuleContext ctx) {
return source.createSection(
ctx.start.getLine(),
ctx.start.getCharPositionInLine() + 1,
ctx.stop.getStopIndex() - ctx.start.getStartIndex());
}
@Override
public BooleanSyntax visitBool(MumblerParser.BoolContext ctx) {
return new BooleanSyntax("#t".equals(ctx.getText()),
createSourceSection(ctx));
}
@Override
public SymbolSyntax visitSymbol(MumblerParser.SymbolContext ctx) {
return new SymbolSyntax(new MumblerSymbol(ctx.getText()),
createSourceSection(ctx));
}
@Override
public ListSyntax visitQuote(MumblerParser.QuoteContext ctx) {
return new ListSyntax(MumblerList.list(
new SymbolSyntax(new MumblerSymbol("quote"), createSourceSection(ctx)),
this.visit(ctx.form())),
createSourceSection(ctx));
}
@Override | public StringSyntax visitString(MumblerParser.StringContext ctx) { | 4 |
la-team/lightadmin-jhipster | src/test/java/org/lightadmin/jhipster/web/rest/AccountResourceTest.java | [
"@ComponentScan\n@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})\npublic class Application {\n\n private final Logger log = LoggerFactory.getLogger(Application.class);\n\n @Inject\n private Environment env;\n\n /**\n * Initializes li... | import org.lightadmin.jhipster.Application;
import org.lightadmin.jhipster.domain.Authority;
import org.lightadmin.jhipster.domain.User;
import org.lightadmin.jhipster.repository.UserRepository;
import org.lightadmin.jhipster.security.AuthoritiesConstants;
import org.lightadmin.jhipster.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.inject.Inject;
import java.util.HashSet;
import java.util.Set;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | package org.lightadmin.jhipster.web.rest;
/**
* Test class for the AccountResource REST controller.
*
* @see UserService
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@ActiveProfiles("dev")
public class AccountResourceTest {
@Inject
private UserRepository userRepository;
@Mock | private UserService userService; | 5 |
zhengjunbase/codehelper.generator | src/main/java/com/ccnode/codegenerator/genCode/GenTestService.java | [
"public class GenCodeResponse extends BaseResponse {\n\n Map<String,String> userConfigMap = Maps.newHashMap();\n\n GenCodeConfig codeConfig;\n\n DirectoryConfig directoryConfig;\n\n List<OnePojoInfo> pojoInfos = Lists.newArrayList();\n\n GenCodeRequest request;\n\n String pathSplitter;\n\n List... | import com.ccnode.codegenerator.pojo.GenCodeResponse;
import com.ccnode.codegenerator.util.LoggerWrapper;
import com.ccnode.codegenerator.pojo.GenCodeResponse;
import com.ccnode.codegenerator.pojo.OnePojoInfo;
import com.ccnode.codegenerator.util.LoggerWrapper;
import org.slf4j.Logger; | package com.ccnode.codegenerator.genCode;
/**
* What always stop you is what you always believe.
* <p>
* Created by zhengjun.du on 2016/08/21 15:54
*/
public class GenTestService {
private final static Logger LOGGER = LoggerWrapper.getLogger(GenTestService.class);
| public static void genTest(GenCodeResponse response) { | 2 |
msoute/vertx-deploy-tools | vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/handler/RestDeployStatusHandler.java | [
"@JsonIgnoreProperties(ignoreUnknown = true)\npublic class DeployRequest {\n private final UUID id = UUID.randomUUID();\n private final List<DeployApplicationRequest> modules;\n private final List<DeployConfigRequest> configs;\n private final List<DeployArtifactRequest> artifacts;\n private final boo... | import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import nl.jpoint.vertx.deploy.agent.request.DeployRequest;
import nl.jpoint.vertx.deploy.agent.request.DeployState;
import nl.jpoint.vertx.deploy.agent.service.AwsService;
import nl.jpoint.vertx.deploy.agent.service.DeployApplicationService;
import nl.jpoint.vertx.deploy.agent.util.ApplicationDeployState;
import nl.jpoint.vertx.deploy.agent.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package nl.jpoint.vertx.deploy.agent.handler;
public class RestDeployStatusHandler implements Handler<RoutingContext> {
private static final Logger LOG = LoggerFactory.getLogger(RestDeployStatusHandler.class);
private final AwsService deployAwsService;
private final DeployApplicationService deployApplicationService;
public RestDeployStatusHandler(AwsService deployAwsService, DeployApplicationService deployApplicationService) {
this.deployAwsService = deployAwsService;
this.deployApplicationService = deployApplicationService;
}
@Override
public void handle(final RoutingContext context) {
DeployRequest deployRequest = deployAwsService.getDeployRequest(context.request().params().get("id"));
DeployState state = deployRequest != null ? deployRequest.getState() : DeployState.UNKNOWN;
if (!deployApplicationService.getDeployedApplicationsFailed().isEmpty()) {
LOG.error("Some services failed to start, failing build");
state = DeployState.FAILED;
deployAwsService.failAllRunningRequests();
}
DeployState deployState = state != null ? state : DeployState.CONTINUE;
LOG.trace("[{}]: Current state : {}", deployRequest != null ? deployRequest.getId() : DeployState.UNKNOWN, deployState.name());
switch (deployState) {
case SUCCESS: | HttpUtils.respondOk(context.request(), createStatusObject(null)); | 5 |
spring-projects/eclipse-integration-tcserver | com.vmware.vfabric.ide.eclipse.tcserver.ui/src/com/vmware/vfabric/ide/eclipse/tcserver/internal/ui/TcServer21WizardFragment.java | [
"public interface ITcRuntime {\n\t\n\tIPath runtimeLocation();\n\t\n\tIPath instanceCreationScript();\n\t\n\tIPath getTomcatLocation();\n\t\n\tIPath getTomcatServersContainer();\n\t\n\tIPath instanceDirectory(String instanceName);\n\t\n\tIPath defaultInstancesDirectory();\n\n}",
"public interface ITcServerConstan... | import java.io.File;
import java.text.MessageFormat;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jst.server.tomcat.core.internal.ITomcatServer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.wst.server.core.IServerWorkingCopy;
import org.eclipse.wst.server.core.TaskModel;
import org.eclipse.wst.server.core.internal.ServerWorkingCopy;
import org.eclipse.wst.server.ui.wizard.IWizardHandle;
import org.eclipse.wst.server.ui.wizard.WizardFragment;
import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.ITcRuntime;
import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.ITcServerConstants;
import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.TcServer;
import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.TcServerCorePlugin;
import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.TcServerUtil; | GridDataFactory.fillDefaults().span(3, 1).applyTo(existingInstanceButton);
serverNameLabel = new Label(composite, SWT.NONE);
serverNameLabel.setText("Instance:");
GridData data = new GridData();
serverNameLabel.setLayoutData(data);
serverNameCombo = new Combo(composite, SWT.BORDER);
data = new GridData(GridData.FILL_HORIZONTAL);
serverNameCombo.setLayoutData(data);
serverNameCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
if (existingInstanceButton.getSelection()) {
updateInstanceNameFromWidget();
}
}
});
serverBrowseButton = new Button(composite, SWT.PUSH);
serverBrowseButton.setText("Browse...");
serverBrowseButton.setLayoutData(new GridData());
serverBrowseButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
handleLocationBrowseButtonPressed();
validate();
}
});
serverNameCombo.setEnabled(false);
serverNameLabel.setEnabled(false);
serverBrowseButton.setEnabled(false);
Label separator = new Label(composite, SWT.NONE);
GridDataFactory.fillDefaults().span(3, 1).applyTo(separator);
descriptionLabel = new Label(composite, SWT.WRAP);
descriptionLabel.setBackground(composite.getBackground());
GridDataFactory.fillDefaults().span(3, 1).grab(true, false).applyTo(descriptionLabel);
return composite;
}
private void updateInstanceNameFromWidget() {
IPath serverPath = new Path(serverNameCombo.getText());
if (!serverPath.isEmpty() && serverPath.isAbsolute()) {
wc.setAttribute(ITomcatServer.PROPERTY_INSTANCE_DIR, serverNameCombo.getText());
wc.setAttribute(TcServer.KEY_SERVER_NAME, (String) null);
}
else {
wc.setAttribute(ITomcatServer.PROPERTY_INSTANCE_DIR, (String) null);
wc.setAttribute(TcServer.KEY_SERVER_NAME, serverNameCombo.getText());
}
validate();
}
private void handleLocationBrowseButtonPressed() {
File path = wc.getRuntime().getLocation().toFile();
DirectoryDialog dialog = new DirectoryDialog(serverBrowseButton.getShell());
dialog.setMessage("Select location");
if (path.exists()) {
dialog.setFilterPath(path.toString());
}
String selectedDirectory = dialog.open();
if (selectedDirectory != null) {
serverNameCombo.add(selectedDirectory, 0);
serverNameCombo.select(0);
}
}
@Override
protected void createChildFragments(List<WizardFragment> list) {
if (newInstanceButton != null && newInstanceButton.getSelection()) {
if (instanceCreationPage == null) {
instanceCreationPage = new TcServer21InstanceCreationFragment();
}
list.add(instanceCreationPage);
}
}
@Override
public void enter() {
this.wc = (IServerWorkingCopy) getTaskModel().getObject(TaskModel.TASK_SERVER);
initialize();
updateChildFragments();
validate();
}
@Override
public void exit() {
if (isDefaultServerName) {
TcServerUtil.setTcServerDefaultName(wc);
}
try {
// load the configuration from the directory based on the selections
// made on the wizard page
((ServerWorkingCopy) wc).importRuntimeConfiguration(wc.getRuntime(), null);
}
catch (CoreException e) {
TcServerCorePlugin.log(
new Status(IStatus.ERROR, TcServerUiPlugin.PLUGIN_ID, "Failed to load runtime configuration", e));
// Trace.trace(Trace.SEVERE, "Failed to load runtime configuration",
// e);
}
}
@Override
public boolean hasComposite() {
return true;
}
private IStatus doValidate() {
if (newInstanceButton != null && newInstanceButton.getSelection()) {
return Status.OK_STATUS;
}
ServerWorkingCopy workingCopy = (ServerWorkingCopy) wc;
if (workingCopy.getAttribute(TcServer.KEY_SERVER_NAME, (String) null) == null
&& workingCopy.getAttribute(ITomcatServer.PROPERTY_INSTANCE_DIR, (String) null) == null) { | return new Status(IStatus.INFO, ITcServerConstants.PLUGIN_ID, SELECT_INSTANCE_MESSAGE); | 1 |
fcrepo4-labs/fcrepo-api-x | fcrepo-api-x-jena/src/main/java/org/fcrepo/apix/jena/impl/LookupOntologyRegistry.java | [
"public static Model parse(final WebResource r, final String base) {\n\n if (r instanceof JenaResource && ((JenaResource) r).model() != null) {\n return ((JenaResource) r).model();\n }\n\n final Model model =\n ModelFactory.createDefaultModel();\n\n final Lang lang = rdfLanguage(r.cont... | import static org.fcrepo.apix.jena.Util.parse;
import static org.fcrepo.apix.jena.Util.rdfLanguage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.util.AbstractMap.SimpleEntry;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import org.fcrepo.apix.model.WebResource;
import org.fcrepo.apix.model.components.Initializer;
import org.fcrepo.apix.model.components.Initializer.Initialization;
import org.fcrepo.apix.model.components.OntologyRegistry;
import org.fcrepo.apix.model.components.Registry;
import org.fcrepo.apix.model.components.Updateable;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Resource;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace 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.fcrepo.apix.jena.impl;
/**
* Allows lookup by ontologyURI as well as location.
* <p>
* For any ontology in underlying registry, will allow retriving that ontology by its location URI, or ontologyIRI
* (which may be different). To do so, it maintains an in-memory map of ontology URIs to location. It is an error to
* have the same ontology IRI in more than one entry in the registry.
* </p>
* <p>
* This indexes all ontologies upon initialization (if {@link #isIndexIRIs()} is {@code true}), and maintains the
* index in response to {@link #put(WebResource)} or {@link #put(WebResource, URI)}.
* </p>
* <p>
* For ontology registries backed by an LDP container in the repository, this class may be used by an asynchronous
* message consumer to update the ontology registry in response to ontologies added/removed manually by clients via
* LDP interactions with the repository.
* </p>
*
* @author apb@jhu.edu
*/
public class LookupOntologyRegistry implements OntologyRegistry, Updateable {
static final String RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
static final String OWL_ONTOLOGY = "http://www.w3.org/2002/07/owl#Ontology";
private final Map<URI, URI> ontologyIRIsToLocation = new ConcurrentHashMap<>();
private Registry registry;
private boolean indexIRIs = true;
private Initializer initializer;
| private Initialization init = Initialization.NONE; | 3 |
mp911de/spinach | src/test/java/biz/paluch/spinach/examples/PeriodicallyUpdatingSocketAddressSupplierFactory.java | [
"@SuppressWarnings(\"serial\")\npublic class DisqueURI implements Serializable {\n\n public static final String URI_SCHEME_DISQUE = \"disque\";\n public static final String URI_SCHEME_DISQUE_SOCKET = \"disque-socket\";\n public static final String URI_SCHEME_DISQUE_SECURE = \"disques\";\n\n /**\n * ... | import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import biz.paluch.spinach.DisqueURI;
import biz.paluch.spinach.api.DisqueConnection;
import biz.paluch.spinach.impl.HelloClusterSocketAddressSupplier;
import biz.paluch.spinach.impl.RoundRobinSocketAddressSupplier;
import biz.paluch.spinach.impl.SocketAddressSupplier;
import biz.paluch.spinach.impl.SocketAddressSupplierFactory;
import io.netty.util.internal.ConcurrentSet; | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package biz.paluch.spinach.examples;
/**
* @author Mark Paluch
*/
public class PeriodicallyUpdatingSocketAddressSupplierFactory implements SocketAddressSupplierFactory {
private final ScheduledExecutorService scheduledExecutorService;
private final Set<ScheduledFuture<?>> futures = new ConcurrentSet<>();
public PeriodicallyUpdatingSocketAddressSupplierFactory(ScheduledExecutorService scheduledExecutorService) {
this.scheduledExecutorService = scheduledExecutorService;
}
@Override | public SocketAddressSupplier newSupplier(DisqueURI disqueURI) { | 0 |
danielflower/app-runner | src/main/java/com/danielflower/apprunner/AppEstate.java | [
"public interface AppDescription {\n String name();\n\n String gitUrl();\n\n void gitUrl(String url) throws URISyntaxException, GitAPIException;\n\n Availability currentAvailability();\n\n BuildStatus lastBuildStatus();\n\n BuildStatus lastSuccessfulBuild();\n\n String latestBuildLog();\n\n ... | import com.danielflower.apprunner.mgmt.AppDescription;
import com.danielflower.apprunner.mgmt.AppManager;
import com.danielflower.apprunner.problems.AppNotFoundException;
import com.danielflower.apprunner.runners.AppRunnerFactoryProvider;
import com.danielflower.apprunner.runners.UnsupportedProjectTypeException;
import com.danielflower.apprunner.web.ProxyMap;
import org.apache.maven.shared.invoker.InvocationOutputHandler;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream; | package com.danielflower.apprunner;
public class AppEstate {
public static final Logger log = LoggerFactory.getLogger(AppEstate.class);
private final List<AppDescription> managers = new ArrayList<>();
private final ProxyMap proxyMap;
private final FileSandbox fileSandbox;
private final List<AppChangedListener> appAddedListeners = new ArrayList<>();
private final List<AppChangedListener> appUpdatedListeners = new ArrayList<>();
private final List<AppChangedListener> appDeletedListeners = new ArrayList<>(); | private final AppRunnerFactoryProvider runnerProvider; | 3 |
xda/XDA-One | android/src/main/java/com/xda/one/auth/RegisterFragment.java | [
"public interface UserClient {\n\n public EventBus getBus();\n\n public void login(final String username, final String password);\n\n void register(final String email, final String username, final String password,\n final String challenge, final String response, final Consumer<Response> success,... | import com.squareup.otto.Subscribe;
import com.xda.one.R;
import com.xda.one.api.inteface.UserClient;
import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.Result;
import com.xda.one.api.retrofit.RetrofitUserClient;
import com.xda.one.constants.XDAConstants;
import com.xda.one.event.user.UserProfileEvent;
import com.xda.one.event.user.UserProfileFailedEvent;
import com.xda.one.ui.listener.MultipleNonEmptyTextViewListener;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import retrofit.client.Response; | package com.xda.one.auth;
public class RegisterFragment extends Fragment {
private UserClient mUserClient;
private EditText mUsername;
private EditText mPassword;
private EditText mEmail;
private EditText mResponse;
private ReCaptcha mReCaptcha;
private ProgressDialog mProgressDialog;
private Object mEventListener;
private ImageView mRecaptchaView;
public static Fragment createInstance() {
return new RegisterFragment();
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
| mUserClient = RetrofitUserClient.getClient(getActivity()); | 3 |
sdadas/fsbrowser | src/main/java/pl/sdadas/fsbrowser/view/locations/StatusBarHelper.java | [
"public final class BeanFactory {\n\n private static Map<Class<?>, Object> beans = new HashMap<>();\n\n private BeanFactory() {\n }\n\n public static FsConnection connection(AppConnection connection) {\n ConnectionConfig config = new ConnectionConfig(connection.getUser(), connection.getProperties... | import com.alee.extended.tab.DocumentData;
import com.alee.laf.menu.WebMenuItem;
import com.alee.laf.menu.WebPopupMenu;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.Path;
import pl.sdadas.fsbrowser.app.BeanFactory;
import pl.sdadas.fsbrowser.app.config.AppConfigProvider;
import pl.sdadas.fsbrowser.app.config.AppConnection;
import pl.sdadas.fsbrowser.app.config.AppLocation;
import pl.sdadas.fsbrowser.fs.connection.HarFsConnection;
import pl.sdadas.fsbrowser.utils.IconFactory;
import pl.sdadas.fsbrowser.utils.ViewUtils;
import pl.sdadas.fsbrowser.view.filesystempanel.FileSystemPanel;
import pl.sdadas.fsbrowser.view.mainwindow.MainPanel;
import java.util.List; | package pl.sdadas.fsbrowser.view.locations;
/**
* @author Sławomir Dadas
*/
public class StatusBarHelper {
private final AppConfigProvider provider;
public StatusBarHelper(AppConfigProvider provider) {
this.provider = provider;
}
| public void addLocation(AppLocation location) { | 3 |
koendeschacht/count-db | src/main/java/be/bagofwords/db/filedb/FileDataInterfaceFactory.java | [
"public interface DataInterface<T extends Object> extends DataIterable<KeyValue<T>> {\n\n T read(long key);\n\n default long readCount(long key) {\n Long result = (Long) read(key);\n if (result == null)\n return 0;\n else\n return result;\n }\n\n default T read... | import be.bagofwords.db.DataInterface;
import be.bagofwords.db.combinator.Combinator;
import be.bagofwords.db.impl.BaseDataInterface;
import be.bagofwords.db.impl.BaseDataInterfaceFactory;
import be.bagofwords.db.methods.ObjectSerializer;
import be.bagofwords.logging.Log;
import be.bagofwords.memory.MemoryManager;
import be.bagofwords.minidepi.ApplicationContext; | package be.bagofwords.db.filedb;
public class FileDataInterfaceFactory extends BaseDataInterfaceFactory {
private final MemoryManager memoryManager;
private final String directory;
public FileDataInterfaceFactory(ApplicationContext context) {
super(context);
this.memoryManager = context.getBean(MemoryManager.class);
this.directory = context.getProperty("data_directory");
}
@Override | protected <T extends Object> BaseDataInterface<T> createBaseDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean isTemporaryDataInterface) { | 2 |
BCA-Team/Buildcraft-Additions | src/main/java/buildcraftAdditions/core/GuiHandler.java | [
"@SideOnly(Side.CLIENT)\npublic class GuiMachineConfigurator extends GuiBase {\n\n\tprivate static final ResourceLocation texture = new ResourceLocation(\"bcadditions:textures/gui/guiMachineConfigurator.png\");\n\tprivate final IConfigurableOutput configurableOutput;\n\tprivate final IUpgradableMachine upgradableMa... | import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.IGuiHandler;
import buildcraftAdditions.api.configurableOutput.IConfigurableOutput;
import buildcraftAdditions.client.gui.GuiBasicCoil;
import buildcraftAdditions.client.gui.GuiChargingStation;
import buildcraftAdditions.client.gui.GuiCoolingTower;
import buildcraftAdditions.client.gui.GuiFluidicCompressor;
import buildcraftAdditions.client.gui.GuiHeatedFurnace;
import buildcraftAdditions.client.gui.GuiItemSorter;
import buildcraftAdditions.client.gui.GuiKEB;
import buildcraftAdditions.client.gui.GuiKineticMultiTool;
import buildcraftAdditions.client.gui.GuiMachineConfigurator;
import buildcraftAdditions.client.gui.GuiPipeColoringTool;
import buildcraftAdditions.client.gui.GuiPortableLaser;
import buildcraftAdditions.client.gui.GuiRefinery;
import buildcraftAdditions.inventories.InventoryKineticMultiTool;
import buildcraftAdditions.inventories.InventoryPortableLaser;
import buildcraftAdditions.inventories.containers.ContainerBasicCoil;
import buildcraftAdditions.inventories.containers.ContainerChargingStation;
import buildcraftAdditions.inventories.containers.ContainerCoolingTower;
import buildcraftAdditions.inventories.containers.ContainerFluidicCompressor;
import buildcraftAdditions.inventories.containers.ContainerHeatedFurnace;
import buildcraftAdditions.inventories.containers.ContainerItemSorter;
import buildcraftAdditions.inventories.containers.ContainerKEB;
import buildcraftAdditions.inventories.containers.ContainerKineticMultiTool;
import buildcraftAdditions.inventories.containers.ContainerMachineConfigurator;
import buildcraftAdditions.inventories.containers.ContainerPipeColoringTool;
import buildcraftAdditions.inventories.containers.ContainerPortableLaser;
import buildcraftAdditions.inventories.containers.ContainerRefinery;
import buildcraftAdditions.items.Tools.ItemKineticMultiTool;
import buildcraftAdditions.items.Tools.ItemPipeColoringTool;
import buildcraftAdditions.items.Tools.ItemPortableLaser;
import buildcraftAdditions.multiBlocks.IMultiBlockTile;
import buildcraftAdditions.reference.Variables;
import buildcraftAdditions.tileEntities.Bases.TileKineticEnergyBufferBase;
import buildcraftAdditions.tileEntities.TileBasicCoil;
import buildcraftAdditions.tileEntities.TileChargingStation;
import buildcraftAdditions.tileEntities.TileCoolingTower;
import buildcraftAdditions.tileEntities.TileFluidicCompressor;
import buildcraftAdditions.tileEntities.TileHeatedFurnace;
import buildcraftAdditions.tileEntities.TileItemSorter;
import buildcraftAdditions.tileEntities.TileRefinery;
import buildcraftAdditions.tileEntities.interfaces.IUpgradableMachine; | package buildcraftAdditions.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Buildcraft Additions is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public final class GuiHandler implements IGuiHandler {
public static final GuiHandler INSTANCE = new GuiHandler();
private GuiHandler() {
}
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity tile = world.getTileEntity(x, y, z);
switch (Variables.Gui.values()[ID]) {
case FLUIDIC_COMPRESSOR:
if (tile instanceof TileFluidicCompressor)
return new ContainerFluidicCompressor(player.inventory, (TileFluidicCompressor) tile);
case CHARGING_STATION:
if (tile instanceof TileChargingStation)
return new ContainerChargingStation(player.inventory, (TileChargingStation) tile);
case KINETIC_MULTI_TOOL:
if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof ItemKineticMultiTool)
return new ContainerKineticMultiTool(player.inventory, new InventoryKineticMultiTool(player.getHeldItem()));
case PORTABLE_LASER:
if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof ItemPortableLaser)
return new ContainerPortableLaser(player.inventory, new InventoryPortableLaser(player.getHeldItem()));
case HEATED_FURNACE:
if (tile instanceof TileHeatedFurnace)
return new ContainerHeatedFurnace(player.inventory, (TileHeatedFurnace) tile);
case BASIC_COIL:
if (tile instanceof TileBasicCoil)
return new ContainerBasicCoil(player.inventory, (TileBasicCoil) tile);
case KEB:
if (tile instanceof TileKineticEnergyBufferBase)
return new ContainerKEB(player, (TileKineticEnergyBufferBase) tile);
case MACHINE_CONFIGURATOR:
return new ContainerMachineConfigurator(player.inventory, tile);
case REFINERY: | return new ContainerRefinery(player.inventory, (TileRefinery) tile); | 3 |
Azure/azure-storage-android | microsoft-azure-storage/src/com/microsoft/azure/storage/table/TableOperation.java | [
"public final class Constants {\n /**\n * Defines constants for ServiceProperties requests.\n */\n public static class AnalyticsConstants {\n\n /**\n * The XML element for the CORS Rule AllowedHeaders\n */\n public static final String ALLOWED_HEADERS_ELEMENT = \"AllowedHe... | import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import com.fasterxml.jackson.core.JsonParseException;
import com.microsoft.azure.storage.Constants;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.StorageExtendedErrorInformation;
import com.microsoft.azure.storage.core.ExecutionEngine;
import com.microsoft.azure.storage.core.SR;
import com.microsoft.azure.storage.core.StorageRequest;
import com.microsoft.azure.storage.core.Utility; | /**
* Copyright Microsoft Corporation
*
* 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.microsoft.azure.storage.table;
/**
* A class which represents a single table operation.
* <p>
* Use the static factory methods to construct {@link TableOperation} instances for operations on tables that insert,
* update, merge, delete, replace or retrieve table entities. To execute a {@link TableOperation} instance, call the
* <code>execute</code> method on a {@link CloudTableClient} instance. A {@link TableOperation} may be executed directly
* or as part of a {@link TableBatchOperation}. If a {@link TableOperation} returns an entity result, it is stored in
* the corresponding {@link TableResult} returned by the <code>execute</code> method.
*
*/
public class TableOperation {
/**
* A static factory method returning a {@link TableOperation} instance to delete the specified entity from Microsoft
* Azure storage. To execute this {@link TableOperation} on a given table, call the
* {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the
*
* @param entity
* The object instance implementing {@link TableEntity} to associate with the operation.
* @return
* A new {@link TableOperation} instance to insert the table entity.
*/
public static TableOperation delete(final TableEntity entity) {
Utility.assertNotNull("entity", entity);
Utility.assertNotNullOrEmpty("entity etag", entity.getEtag());
return new TableOperation(entity, TableOperationType.DELETE);
}
/**
* A static factory method returning a {@link TableOperation} instance to insert the specified entity into
* Microsoft Azure storage. To execute this {@link TableOperation} on a given table, call the
* {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the
*
* @param entity
* The object instance implementing {@link TableEntity} to associate with the operation.
* @return
* A new {@link TableOperation} instance to insert the table entity.
*/
public static TableOperation insert(final TableEntity entity) {
return insert(entity, false);
}
/**
* A static factory method returning a {@link TableOperation} instance to insert the specified entity into
* Microsoft Azure storage. To execute this {@link TableOperation} on a given table, call the
* {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the
*
* @param entity
* The object instance implementing {@link TableEntity} to associate with the operation.
* @param echoContent
* The boolean representing whether the message payload should be returned in the response.
* @return
* A new {@link TableOperation} instance to insert the table entity.
*/
public static TableOperation insert(final TableEntity entity, boolean echoContent) {
Utility.assertNotNull("entity", entity);
return new TableOperation(entity, TableOperationType.INSERT, echoContent);
}
/**
* A static factory method returning a {@link TableOperation} instance to merge the specified entity into
* Microsoft Azure storage, or insert it if it does not exist. To execute this {@link TableOperation} on a given
* table, call
* the {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with
* the table name and the {@link TableOperation} as arguments.
*
* @param entity
* The object instance implementing {@link TableEntity} to associate with the operation.
* @return
* A new {@link TableOperation} instance for inserting or merging the table entity.
*/
public static TableOperation insertOrMerge(final TableEntity entity) {
Utility.assertNotNull("entity", entity);
return new TableOperation(entity, TableOperationType.INSERT_OR_MERGE);
}
/**
* A static factory method returning a {@link TableOperation} instance to replace the specified entity in
* Microsoft Azure storage, or insert it if it does not exist. To execute this {@link TableOperation} on a given
* table, call
* the {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with
* the table name and the {@link TableOperation} as arguments.
*
* @param entity
* The object instance implementing {@link TableEntity} to associate with the operation.
* @return
* A new {@link TableOperation} instance for inserting or replacing the table entity.
*/
public static TableOperation insertOrReplace(final TableEntity entity) {
Utility.assertNotNull("entity", entity);
return new TableOperation(entity, TableOperationType.INSERT_OR_REPLACE);
}
/**
* A static factory method returning a {@link TableOperation} instance to merge the specified table entity into
* Microsoft Azure storage. To execute this {@link TableOperation} on a given table, call the
* {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the
*
* @param entity
* The object instance implementing {@link TableEntity} to associate with the operation.
* @return
* A new {@link TableOperation} instance for merging the table entity.
*/
public static TableOperation merge(final TableEntity entity) {
Utility.assertNotNull("entity", entity);
Utility.assertNotNullOrEmpty("entity etag", entity.getEtag());
return new TableOperation(entity, TableOperationType.MERGE);
}
/**
* A static factory method returning a {@link TableOperation} instance to retrieve the specified table entity and
* return it as the specified type. To execute this {@link TableOperation} on a given table, call the
* {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the
*
* @param partitionKey
* A <code>String</code> which specifies the PartitionKey value for the entity to retrieve.
* @param rowKey
* A <code>String</code> which specifies the RowKey value for the entity to retrieve.
* @param clazzType
* The class type of the table entity object to retrieve.
* @return
* A new {@link TableOperation} instance for retrieving the table entity.
*/
public static TableOperation retrieve(final String partitionKey, final String rowKey,
final Class<? extends TableEntity> clazzType) {
final QueryTableOperation retOp = new QueryTableOperation(partitionKey, rowKey);
retOp.setClazzType(clazzType);
return retOp;
}
/**
* A static factory method returning a {@link TableOperation} instance to retrieve the specified table entity and
* return a projection of it using the specified resolver. To execute this {@link TableOperation} on a given table,
* call the {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance
* with the table name and the {@link TableOperation} as arguments.
*
* @param partitionKey
* A <code>String</code> which specifies the PartitionKey value for the entity to retrieve.
* @param rowKey
* A <code>String</code> which specifies the RowKey value for the entity to retrieve.
* @param resolver
* The implementation of {@link EntityResolver} to use to project the result entity as type T.
* @return
* A new {@link TableOperation} instance for retrieving the table entity.
*/
public static TableOperation retrieve(final String partitionKey, final String rowKey,
final EntityResolver<?> resolver) {
final QueryTableOperation retOp = new QueryTableOperation(partitionKey, rowKey);
retOp.setResolver(resolver);
return retOp;
}
/**
* A static factory method returning a {@link TableOperation} instance to replace the specified table entity. To
* execute this {@link TableOperation} on a given table, call the
* {@link CloudTable#execute(TableOperation)} method.
*
* @param entity
* The object instance implementing {@link TableEntity} to associate with the operation.
* @return
* A new {@link TableOperation} instance for replacing the table entity.
*/
public static TableOperation replace(final TableEntity entity) {
Utility.assertNotNullOrEmpty("entity etag", entity.getEtag());
return new TableOperation(entity, TableOperationType.REPLACE);
}
/**
* The table entity instance associated with the operation.
*/
private TableEntity entity;
/**
* The {@link TableOperationType} enumeration value for the operation type.
*/
private TableOperationType opType = null;
/**
* The value that represents whether the message payload should be returned in the response.
*/
private boolean echoContent;
/**
* Nullary Default Constructor.
*/
protected TableOperation() {
// Empty constructor.
}
/**
* Reserved for internal use. Constructs a {@link TableOperation} with the specified table entity and operation
* type.
*
* @param entity
* The object instance implementing {@link TableEntity} to associate with the operation.
* @param opType
* The {@link TableOperationType} enumeration value for the operation type.
*/
protected TableOperation(final TableEntity entity, final TableOperationType opType) {
this(entity, opType, false);
}
/**
* Reserved for internal use. Constructs a {@link TableOperation} with the specified table entity and operation
* type.
*
* @param entity
* The object instance implementing {@link TableEntity} to associate with the operation.
* @param opType
* The {@link TableOperationType} enumeration value for the operation type.
* @param echoContent
* The boolean representing whether the message payload should be returned in the response.
*/
protected TableOperation(final TableEntity entity, final TableOperationType opType, final boolean echoContent) {
this.entity = entity;
this.opType = opType;
this.echoContent = echoContent;
}
/**
* Reserved for internal use. Performs a delete operation on the specified table, using the specified
* {@link TableRequestOptions} and {@link OperationContext}.
* <p>
* This method will invoke the <a href="http://msdn.microsoft.com/en-us/library/azure/dd135727.aspx">Delete
* Entity</a> REST API to execute this table operation, using the Table service endpoint and storage account
* credentials in the {@link CloudTableClient} object.
*
* @param client
* A {@link CloudTableClient} instance specifying the Table service endpoint, storage account
* credentials, and any additional query parameters.
* @param tableName
* A <code>String</code> which specifies the name of the table.
* @param options
* A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout
* settings for the operation.
* @param opContext
* An {@link OperationContext} object for tracking the current operation.
*
* @return
* A {@link TableResult} which represents the results of executing the operation.
*
* @throws StorageException
* if an error occurs in the storage operation.
*/
private TableResult performDelete(final CloudTableClient client, final String tableName, | final TableRequestOptions options, final OperationContext opContext) throws StorageException { | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.