_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q169700 | Launcher.extractLauncherArgs | validation | private static String[] extractLauncherArgs(String[] args, int commandIndex) {
String[] launcherArgs = new String[commandIndex];
System.arraycopy(args, 0, launcherArgs, 0, commandIndex);
return launcherArgs;
} | java | {
"resource": ""
} |
q169701 | Launcher.extractCommandArgs | validation | private static String[] extractCommandArgs(String[] args, int commandIndex) {
String[] commandArgs = new String[args.length - commandIndex - 1];
System.arraycopy(args, commandIndex + 1, commandArgs, 0, args.length - commandIndex - 1);
return commandArgs;
} | java | {
"resource": ""
} |
q169702 | Launcher.main | validation | public static void main(String[] args) {
try {
int commandIndex = findCommandIndex(args);
if (commandIndex < 0) {
printHelp();
}
String[] launcherArgs = extractLauncherArgs(args, commandIndex);
String[] commandArgs = extractCommandArgs(args, commandIndex);
parseCommandLineArguments(launcherArgs);
debug("Launcher#main(): args = " + Arrays.asList(args));
debug("Launcher#main(): launcherArgs = " + Arrays.asList(launcherArgs));
debug("Launcher#main(): commandArgs = " + Arrays.asList(commandArgs));
String commandName = args[commandIndex];
Executable tool = Command.getUtil(commandName);
if (tool != null) {
tool.execute(commandArgs, debugEnabled, quiet);
} else {
debug("Launcher#main(): Command \"" + commandName + "\" not found");
printHelp();
}
} catch (Throwable t) {
debug("Launcher#main(): Throwable caught with message = " + t.getMessage(), t);
Utils.exitWithFailure("Unexpected throwable", t);
}
} | java | {
"resource": ""
} |
q169703 | Launcher.debug | validation | private static void debug(String message, Throwable t) {
if (debugEnabled) {
System.err.println("0 [Launcher] " + message);
if (t != null) {
t.printStackTrace(System.err);
}
}
} | java | {
"resource": ""
} |
q169704 | MonitorTool.start | validation | private void start() {
try {
timer.schedule(new IsAliveTimerTask(), 0, period);
} catch (Throwable t) {
Utils.exitWithFailure("Throwable caught during the startup", t);
}
} | java | {
"resource": ""
} |
q169705 | PeerCacheService.createRegions | validation | public Set<Region<?, ?>> createRegions(Map<String, String> regionNames) {
Set<Region<?, ?>> regions = new HashSet<Region<?, ?>>();
proxyRegionFactory = cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
for (String regionPath : regionNames.keySet()) {
Region region = createRegion(regionPath, regionNames.get(regionPath));
regions.add(region);
}
return regions;
} | java | {
"resource": ""
} |
q169706 | ExpirationController.process | validation | public long process(Region<?, ?> region, ExpirationPolicy policy) {
long destroyedEntriesNumber = 0;
try {
if (region == null) {
throw new IllegalStateException("The Region cannot be null");
}
if (policy == null) {
throw new IllegalArgumentException(
"The ExpirationPolicy cannot be null");
}
logger
.info("Running ExpirationController process with parameters region = "
+ region
+ ", policy = "
+ policy
+ ", packetSize = "
+ packetSize + ", packetDelay = " + packetDelay);
DestroyedEntriesCountCollector collector = (DestroyedEntriesCountCollector) FunctionService
.onRegion(region)
.withArgs(
new ExpirationFunctionArguments(packetSize, packetDelay))
.withCollector(new DestroyedEntriesCountCollector())
.execute(new ExpirationFunction(policy));
Object result = collector.getResult();
if (result instanceof Long) {
destroyedEntriesNumber = (Long) result;
}
logger
.info("ExpirationController process with parameters region = "
+ region + ", policy = " + policy + ", packetSize = "
+ packetSize + ", packetDelay = " + packetDelay
+ " has destroyed " + destroyedEntriesNumber + " entries");
} catch (RuntimeException re) {
logger.error("RuntimeException during processing", re);
throw re;
}
return destroyedEntriesNumber;
} | java | {
"resource": ""
} |
q169707 | RenderConfiguration.setIndentationToken | validation | public final void setIndentationToken(final String indentationToken) {
// Check sanity
if (indentationToken == null || indentationToken.isEmpty()) {
throw new IllegalArgumentException("Cannot handle null or empty 'indentationToken' argument.");
}
// Assign internal state
this.indentationToken = indentationToken;
} | java | {
"resource": ""
} |
q169708 | JavaPackageExtractor.getPackage | validation | @Override
public String getPackage(final File sourceFile) {
String aLine = getPackage(sourceFile, PACKAGE_STATEMENT);
if (aLine != null) return aLine;
// No package statement found.
// Return default package.
return "";
} | java | {
"resource": ""
} |
q169709 | LifecycleInvestigationDoclet.start | validation | public static boolean start(final RootDoc root) {
// Perform some reflective investigation of the RootDoc
final boolean toReturn = Standard.start(root);
eventSequence.add("start (root): " + toReturn);
// We should emit the eventSequence here.
for(int i = 0; i < eventSequence.size(); i++) {
System.out.println(" event [" + i + " / " + eventSequence.size() + "]: " + eventSequence.get(i));
}
// All Done.
return toReturn;
} | java | {
"resource": ""
} |
q169710 | NodesController.extractPortsSet | validation | private Set<Integer> extractPortsSet(SystemMember member)
throws AdminException {
Set<Integer> portsSet = new HashSet<Integer>();
SystemMemberCache cache = member.getCache();
if (cache != null) {
SystemMemberCacheServer[] cacheServers = cache.getCacheServers();
if (cacheServers != null) {
for (SystemMemberCacheServer cacheServer : cacheServers) {
portsSet.add(cacheServer.getPort());
}
}
}
return portsSet;
} | java | {
"resource": ""
} |
q169711 | NodesController.findOrCreatePool | validation | private Pool findOrCreatePool(String host, int port) {
String poolName = Utils.toKey(host, port);
Pool pool = PoolManager.find(poolName);
if (pool == null) {
poolFactory.reset();
poolFactory.addServer(host, port);
pool = poolFactory.create(poolName);
}
return pool;
} | java | {
"resource": ""
} |
q169712 | RuleUtil.getName | validation | public static String getName(String eventSrcName) {
if (eventSrcName == null) {
return null;
}
if (eventSrcName.endsWith("Check")) {
eventSrcName = eventSrcName.substring(0, eventSrcName.length() - 5);
}
return eventSrcName.substring(eventSrcName.lastIndexOf('.') + 1);
} | java | {
"resource": ""
} |
q169713 | RuleUtil.getCategory | validation | public static String getCategory(String eventSrcName) {
if (eventSrcName == null) {
return null;
}
int end = eventSrcName.lastIndexOf('.');
eventSrcName = eventSrcName.substring(0, end);
if (CHECKSTYLE_PACKAGE.equals(eventSrcName)) {
return "misc";
} else if (!eventSrcName.startsWith(CHECKSTYLE_PACKAGE)) {
return "extension";
}
return eventSrcName.substring(eventSrcName.lastIndexOf('.') + 1);
} | java | {
"resource": ""
} |
q169714 | MethodFrameCounter.enterFrame | validation | public static void enterFrame(String className) {
int counter = local.get().incrementAndGet();
classNames.get().add(className);
if (counter == MAX_STACK_DEPTH) {
throw new RuntimeException(STACK_OVERFLOW_MSG + getClassNames());
}
} | java | {
"resource": ""
} |
q169715 | MethodFrameCounter.exitFrame | validation | public static void exitFrame(String className) {
int counter = local.get().decrementAndGet();
if (counter < 0) {
String errorMessage = "Method frame counter is less then 0. Some programming error: count(exitFrame) > count(enterFrame)."
+ getClassNames();
clearCounter();
throw new RuntimeException(errorMessage);
}
String frameToExit = classNames.get().remove(classNames.get().size() - 1);
if (!className.equals(frameToExit)) {
throw new RuntimeException("Method frame counter try to exit from the class '" + className
+ "' but must exit from the class '" + frameToExit + "' first." + getClassNames());
}
} | java | {
"resource": ""
} |
q169716 | MethodFrameCounter.getClassNames | validation | private static String getClassNames() {
StringBuilder result = new StringBuilder("\nMethod frame counter enter to the following classes:\n");
for (String className : classNames.get()) {
result.append(className).append("\n");
}
return result.toString();
} | java | {
"resource": ""
} |
q169717 | CorrectPackagingRule.setPackageExtractors | validation | public final void setPackageExtractors(final String packageExtractorImplementations)
throws IllegalArgumentException {
// Check sanity
if(packageExtractorImplementations == null) {
throw new NullPointerException("Cannot handle empty packageExtractorImplementations argument.");
}
// Instantiate the PackageExtractor instances.
List<PackageExtractor> extractors = new ArrayList<PackageExtractor>();
for (String current : splice(packageExtractorImplementations)) {
try {
// Load the current PackageExtractor implementation class
final Class<?> aClass = getClass().getClassLoader().loadClass(current);
// The PackageExtractor implementation must have a default constructor.
// Fire, and handle any exceptions.
extractors.add((PackageExtractor) aClass.newInstance());
} catch (Exception e) {
throw new IllegalArgumentException("Could not instantiate PackageExtractor from class ["
+ current + "]. Validate that implementation has a default constructor, and implements the"
+ PackageExtractor.class.getSimpleName() + " interface.");
}
}
// Assign if non-null.
if (extractors.size() > 0) {
this.packageExtractors = extractors;
}
} | java | {
"resource": ""
} |
q169718 | CorrectPackagingRule.addPackages | validation | private void addPackages(final File fileOrDirectory,
final SortedMap<String, SortedSet<String>> package2FileNamesMap) {
for (PackageExtractor current : packageExtractors) {
final FileFilter sourceFileDefinitionFilter = current.getSourceFileFilter();
if (fileOrDirectory.isFile() && sourceFileDefinitionFilter.accept(fileOrDirectory)) {
// Single source file to add.
final String thePackage = current.getPackage(fileOrDirectory);
SortedSet<String> sourceFileNames = package2FileNamesMap.get(thePackage);
if (sourceFileNames == null) {
sourceFileNames = new TreeSet<String>();
package2FileNamesMap.put(thePackage, sourceFileNames);
}
// Done.
sourceFileNames.add(fileOrDirectory.getName());
} else if (fileOrDirectory.isDirectory()) {
// Add the immediate source files
for (File currentChild : fileOrDirectory.listFiles(sourceFileDefinitionFilter)) {
addPackages(currentChild, package2FileNamesMap);
}
// Recurse into subdirectories
for (File currentSubdirectory : fileOrDirectory.listFiles(DIRECTORY_FILTER)) {
addPackages(currentSubdirectory, package2FileNamesMap);
}
}
}
} | java | {
"resource": ""
} |
q169719 | LanguageImage.updateImageData | validation | @PrePersist
@PreUpdate
private void updateImageData() throws CustomConstraintViolationException {
thumbnail = createImage(true);
imageFile.validate();
if (imageData != null) {
imageContentHash = HashUtilities.generateSHA256(imageData).toCharArray();
}
} | java | {
"resource": ""
} |
q169720 | LanguageImage.setUiOriginalFileName | validation | public void setUiOriginalFileName(final String uiOriginalFileName) {
this.uiOriginalFileName = uiOriginalFileName;
if (this.uiOriginalFileName != null && !this.uiOriginalFileName.isEmpty()) originalFileName = this.uiOriginalFileName;
} | java | {
"resource": ""
} |
q169721 | BucketOrientedQueryService.extractLimit | validation | private static int extractLimit(String queryString) {
int limitIndex = queryString.lastIndexOf("limit");
if (limitIndex == -1) {
limitIndex = queryString.lastIndexOf("LIMIT");
}
if (limitIndex == -1) {
return limitIndex;
}
String limitValue = queryString.substring(limitIndex + 5);
return Integer.parseInt(limitValue.trim());
} | java | {
"resource": ""
} |
q169722 | BucketOrientedQueryService.formatSelectResults | validation | @SuppressWarnings({ "unchecked" })
private static SelectResults<Object> formatSelectResults(List<List<Object>> queryResults, int limit) {
List<Object> list = new ArrayList<Object>();
ObjectType baseElementType = null;
for (List<Object> queryResult : queryResults) {
ObjectType elementType = (ObjectType) queryResult.remove(queryResult.size() - 1);
if (baseElementType == null) {
baseElementType = elementType;
} else if (!baseElementType.equals(elementType)) {
throw new IllegalStateException("Collection types for query result are different.");
}
list.addAll(queryResult);
if (limit != -1 && list.size() >= limit) {
break;
}
}
return limit == -1 ? new ResultsCollectionWrapper(baseElementType, list) : new ResultsCollectionWrapper(
baseElementType, list, limit);
} | java | {
"resource": ""
} |
q169723 | RTSupport.checkAllowedInRealTime0 | validation | private static void checkAllowedInRealTime0(Object obj, int depth) throws InvalidClassException {
if (depth >= MethodFrameCounter.MAX_STACK_DEPTH) { //todo: correct >? or >=?
throw new RuntimeException();
}
Class<?> clazz = obj.getClass();
if (clazz.getName().startsWith("java.") || clazz.getName().startsWith("javax.")) {
checkAllowedInCompileTimeJdkType(clazz);
} else {
checkAllowedInCompileTimeCustomType(clazz);
}
// array
if (clazz.isArray()) {
final int length = Array.getLength(obj);
for (int k = 0; k < length; k++) {
Object elem = Array.get(obj, k);
checkAllowedInRealTime0(elem, depth + 1);
}
}
// Collection
if (Collection.class.isAssignableFrom(clazz)) {
for (Object elem : ((Collection) obj)) {
checkAllowedInRealTime0(elem, depth + 1);
}
}
// Map
if (Map.class.isAssignableFrom(clazz)) {
for (Map.Entry<Object, Object> elem : ((Map<Object, Object>) obj).entrySet()) {
checkAllowedInRealTime0(elem.getKey(), depth + 1);
checkAllowedInRealTime0(elem.getValue(), depth + 1);
}
}
} | java | {
"resource": ""
} |
q169724 | JavaProcessLauncher.runWithConfirmation | validation | public Process runWithConfirmation(String id, Class<?> klass,
String[] javaArguments, String[] processArguments)
throws IOException, InterruptedException {
Process process = startProcess(id, klass, javaArguments, processArguments,
true);
waitConfirmation(klass.getSimpleName(), process);
new StreamRedirector(process.getInputStream(), klass.getSimpleName()
+ PROCESS_STDOUT_STREAM_PREFIX,
redirectProcessInputStreamToParentProcessStdOut).start();
return process;
} | java | {
"resource": ""
} |
q169725 | JavaProcessLauncher.runWithStartupDelay | validation | public Process runWithStartupDelay(Class<?> klass, String[] javaArguments,
String[] processArguments) throws IOException,
InterruptedException, TimeoutException {
return runWithStartupDelay(klass, javaArguments, processArguments,
DEFAULT_PROCESS_STARTUP_SHUTDOWN_TIME);
} | java | {
"resource": ""
} |
q169726 | JavaProcessLauncher.runWithStartupDelay | validation | public Process runWithStartupDelay(Class<?> klass, String[] javaArguments,
String[] processArguments, long processStartupTime)
throws IOException, InterruptedException, TimeoutException {
Process process = runWithConfirmation("", klass, javaArguments,
processArguments);
if (processStartupTime > 0) {
Thread.sleep(processStartupTime);
}
return process;
} | java | {
"resource": ""
} |
q169727 | JavaProcessLauncher.stopBySendingNewLineIntoProcess | validation | public void stopBySendingNewLineIntoProcess(Process process)
throws IOException, InterruptedException {
if (process != null) {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
process.getOutputStream()));
writer.newLine();
writer.flush();
process.waitFor();
}
} | java | {
"resource": ""
} |
q169728 | JavaProcessLauncher.startProcess | validation | private Process startProcess(String id, Class<?> klass, String[] javaArguments,
String[] processArguments, boolean withConfirmation)
throws IOException, InterruptedException {
List<String> arguments = createCommandLineForProcess(klass,
javaArguments, processArguments);
Process process = new ProcessBuilder(arguments).start();
redirectProcessStreams(id, klass, process, !withConfirmation);
return process;
} | java | {
"resource": ""
} |
q169729 | JavaProcessLauncher.redirectProcessStreams | validation | private void redirectProcessStreams(String id, Class<?> klass, Process process,
boolean redirectProcessStdOut) {
String errorStreamType = (printType ? klass.getSimpleName() + id
+ PROCESS_ERROR_STREAM_PREFIX : "");
new StreamRedirector(process.getErrorStream(), errorStreamType,
redirectProcessErrorStreamToParentProcessStdOut, System.err)
.start();
if (redirectProcessStdOut) {
String outputStreamType = (printType ? klass.getSimpleName() + id
+ PROCESS_STDOUT_STREAM_PREFIX : "");
new StreamRedirector(process.getInputStream(), outputStreamType,
redirectProcessInputStreamToParentProcessStdOut, System.out)
.start();
}
} | java | {
"resource": ""
} |
q169730 | JavaProcessLauncher.waitConfirmation | validation | private void waitConfirmation(String className, Process process)
throws IOException, InterruptedException {
System.out
.println("Waiting startup complete confirmation for a process ("
+ className + ")...");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.equals(PROCESS_STARTUP_COMPLETED)) {
System.out.println("The process (" + className
+ ") has been started successfully");
return;
} else if (redirectProcessInputStreamToParentProcessStdOut) {
System.out.println(className + PROCESS_STDOUT_STREAM_PREFIX
+ line);
}
}
throw new InterruptedException(
"Process ("
+ className
+ ") "
+ "has been already finished without startup complete confirmation");
} | java | {
"resource": ""
} |
q169731 | VelocityTemplate.generate | validation | public void generate( String outputFilename, String template, Context context )
throws VelocityException, MojoExecutionException, IOException
{
Writer writer = null;
try
{
File f = new File( outputFilename );
if ( !f.getParentFile().exists() )
{
f.getParentFile().mkdirs();
}
writer = new FileWriter( f );
getVelocity().getEngine().mergeTemplate( templateDirectory + "/" + template, context, writer );
}
catch ( ResourceNotFoundException e )
{
throw new ResourceNotFoundException( "Template not found: " + templateDirectory + "/" + template, e );
}
catch ( VelocityException | IOException e )
{
throw e; // to get past generic catch for Exception.
}
catch ( Exception e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
finally
{
if ( writer != null )
{
writer.flush();
writer.close();
getLog().debug( "File " + outputFilename + " created..." );
}
}
} | java | {
"resource": ""
} |
q169732 | ReplicationProcessor.process | validation | public int process() throws IOException, InterruptedException {
debug("ReplicationProcessor#process(): Processing start");
Properties gemfireProperties = PropertiesHelper.filterProperties(
System.getProperties(), "gemfire.");
String[] vmOptions = PropertiesHelper
.propertiesToVMOptions(gemfireProperties);
debug("ReplicationProcessor#process(): vmOptions = "
+ Arrays.asList(vmOptions));
List<Process> processesList = new ArrayList<Process>();
for (Object keyObject : clustersProperties.keySet()) {
String cluster = (String) keyObject;
String clustersPropertiesString = PropertiesHelper
.propertiesToString(clustersProperties);
debug("ReplicationProcessor#process(): Starting GuestNode with parameters: cluster = "
+ cluster
+ ", clustersPropertiesString = "
+ clustersPropertiesString
+ ", timeout = "
+ timeout
+ ", regionName = " + regionName);
Process process = javaProcessLauncher.runWithoutConfirmation(
"",
GuestNode.class,
vmOptions, new String[] { cluster, clustersPropertiesString,
String.valueOf(timeout), regionName,
String.valueOf(debugEnabled), String.valueOf(quiet),
String.valueOf(processingStartedAt) });
debug("ReplicationProcessor#process(): Adding GuestNode to processList");
processesList.add(process);
}
debug("ReplicationProcessor#process(): Waiting for processes finish");
int mainExitCode = 0;
int processNumber = 0;
for (Process process : processesList) {
debug("ReplicationProcessor#process(): Waiting for process #"
+ processNumber);
int exitCode = process.waitFor();
if (exitCode != 0) {
mainExitCode = 1;
}
debug("ReplicationProcessor#process(): Process #" + processNumber
+ " finished with exitCode = " + exitCode);
processNumber++;
}
debug("ReplicationProcessor#process(): Processing finished with mainExitCode = "
+ mainExitCode);
return mainExitCode;
} | java | {
"resource": ""
} |
q169733 | Types.isA | validation | public static boolean isA(Class clazz, ParameterizedType pType) {
return clazz.isAssignableFrom((Class) pType.getRawType());
} | java | {
"resource": ""
} |
q169734 | Types.isCompatible | validation | public static boolean isCompatible(Method method, Method intfMethod) {
if (method == intfMethod)
return true;
if (!method.getName().equals(intfMethod.getName()))
return false;
if (method.getParameterTypes().length != intfMethod.getParameterTypes().length)
return false;
for (int i = 0; i < method.getParameterTypes().length; i++) {
Class rootParam = method.getParameterTypes()[i];
Class intfParam = intfMethod.getParameterTypes()[i];
if (!intfParam.isAssignableFrom(rootParam))
return false;
}
return true;
} | java | {
"resource": ""
} |
q169735 | Types.getImplementingMethod | validation | public static Method getImplementingMethod(Class clazz, Method intfMethod) {
Class<?> declaringClass = intfMethod.getDeclaringClass();
if (declaringClass.equals(clazz))
return intfMethod;
Class[] paramTypes = intfMethod.getParameterTypes();
if (declaringClass.getTypeParameters().length > 0 && paramTypes.length > 0) {
Type[] intfTypes = findParameterizedTypes(clazz, declaringClass);
Map<String, Type> typeVarMap = new HashMap<String, Type>();
TypeVariable<? extends Class<?>>[] vars = declaringClass.getTypeParameters();
for (int i = 0; i < vars.length; i++) {
if (intfTypes != null && i < intfTypes.length) {
typeVarMap.put(vars[i].getName(), intfTypes[i]);
} else {
// Interface type parameters may not have been filled out
typeVarMap.put(vars[i].getName(), vars[i].getGenericDeclaration());
}
}
Type[] paramGenericTypes = intfMethod.getGenericParameterTypes();
paramTypes = new Class[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
if (paramGenericTypes[i] instanceof TypeVariable) {
TypeVariable tv = (TypeVariable) paramGenericTypes[i];
Type t = typeVarMap.get(tv.getName());
if (t == null) {
throw new RuntimeException("Unable to resolve type variable");
}
paramTypes[i] = getRawType(t);
} else {
paramTypes[i] = getRawType(paramGenericTypes[i]);
}
}
}
try {
return clazz.getMethod(intfMethod.getName(), paramTypes);
} catch (NoSuchMethodException e) {
}
try {
Method tmp = clazz.getMethod(intfMethod.getName(), intfMethod.getParameterTypes());
return tmp;
} catch (NoSuchMethodException e) {
}
return intfMethod;
} | java | {
"resource": ""
} |
q169736 | Types.getTypeArgument | validation | public static Class<?> getTypeArgument(Type genericType) {
if (!(genericType instanceof ParameterizedType))
return null;
ParameterizedType parameterizedType = (ParameterizedType) genericType;
Class<?> typeArg = (Class<?>) parameterizedType.getActualTypeArguments()[0];
return typeArg;
} | java | {
"resource": ""
} |
q169737 | Types.resolveTypeVariable | validation | public static Type resolveTypeVariable(Class<?> root, TypeVariable<?> typeVariable) {
if (typeVariable.getGenericDeclaration() instanceof Class<?>) {
Class<?> classDeclaringTypeVariable = (Class<?>) typeVariable.getGenericDeclaration();
Type[] types = findParameterizedTypes(root, classDeclaringTypeVariable);
if (types == null)
return null;
for (int i = 0; i < types.length; i++) {
TypeVariable<?> tv = classDeclaringTypeVariable.getTypeParameters()[i];
if (tv.equals(typeVariable)) {
return types[i];
}
}
}
return null;
} | java | {
"resource": ""
} |
q169738 | Types.getActualTypeArgumentsOfAnInterface | validation | public static Type[] getActualTypeArgumentsOfAnInterface(Class<?> classToSearch, Class<?> interfaceToFind) {
Type[] types = findParameterizedTypes(classToSearch, interfaceToFind);
if (types == null)
throw new RuntimeException("Unable to find type arguments of " + interfaceToFind);
return types;
} | java | {
"resource": ""
} |
q169739 | AutoPopulateGenericObjectPool.populate | validation | private void populate() throws Exception {
List<T> initializer = new ArrayList<T>(this.getMinIdle());
for (int idx = 0; idx < this.getMinIdle() && (this.getMaxIdle() == DISABLED || idx < this.getMaxIdle()) && (this.getMaxActive() == DISABLED || idx < this.getMaxActive()); idx++) {
initializer.add(this.borrowObject());
}
for (int idx = 0; idx < this.getMinIdle() && (this.getMaxIdle() == DISABLED || idx < this.getMaxIdle()) && (this.getMaxActive() == DISABLED || idx < this.getMaxActive()); idx++) {
this.returnObject(initializer.get(idx));
}
} | java | {
"resource": ""
} |
q169740 | SEIProcessor.addReturnOptionDescription | validation | private void addReturnOptionDescription(Method method, Return.ReturnBuilder returnBuilder) {
DocReturn returnAnno = getNonExceptionDocReturn(method);
String returnOptionDesc = (returnAnno == null) ? null : returnAnno.description();
returnBuilder.description(StringUtils.isEmpty(returnOptionDesc) ? null : returnAnno.description());
} | java | {
"resource": ""
} |
q169741 | WekaThreadSafeScorerPool.returnObject | validation | private void returnObject(ObjectPool<Classifier> pool, Classifier object) {
try {
pool.returnObject(object);
} catch (Exception e) {
logger.error("Could not return object to pool", e);
}
} | java | {
"resource": ""
} |
q169742 | JmsService.getDestination | validation | private Destination getDestination(final String destinationName) {
if (!destinations.containsKey(destinationName)) {
Destination destination = destinationSupplier.apply(destinationName);
destinations.put(destinationName, destination);
}
return destinations.get(destinationName);
} | java | {
"resource": ""
} |
q169743 | JmsService.getConsumer | validation | private MessageConsumer getConsumer(final String destinationName) {
if (!consumers.containsKey(destinationName)) {
Session session = getSession();
Destination destination = getDestination(destinationName);
try {
MessageConsumer consumer = session.createConsumer(destination);
consumers.put(destinationName, consumer);
} catch (JMSException e) {
throw new JmsException("Unable to create consumer for destination "
+ destinationName, e);
}
}
return consumers.get(destinationName);
} | java | {
"resource": ""
} |
q169744 | JmsService.getProducer | validation | private MessageProducer getProducer(final String destinationName) {
if (!producers.containsKey(destinationName)) {
Session session = getSession();
Destination destination = getDestination(destinationName);
MessageProducer producer;
try {
producer = session.createProducer(destination);
} catch (JMSException e) {
throw new JmsException("Unable to create producer for destination "
+ destinationName, e);
}
producers.put(destinationName, producer);
}
return producers.get(destinationName);
} | java | {
"resource": ""
} |
q169745 | JmsService.getSession | validation | private Session getSession() {
if (!sessionOption.isPresent()) {
try {
sessionOption = Optional.of(getConnection().createSession(transacted, acknowledgeMode));
} catch (JMSException e) {
throw new JmsException("Unable to get JMS session", e);
}
}
return sessionOption.get();
} | java | {
"resource": ""
} |
q169746 | JmsService.getConnection | validation | private Connection getConnection() {
if (!connectionOption.isPresent()) {
final Connection connection = connectionSupplier.get();
if (connection instanceof ActiveMQConnection) {
((ActiveMQConnection) connection).addTransportListener(new TransportListener() {
@Override
public void onCommand(Object command) {
}
@Override
public void onException(IOException error) {
}
@Override
public void transportInterupted() {
connected.set(false);
}
@Override
public void transportResumed() {
connected.set(true);
}
});
}
connected.set(true);
if (startConnection) {
try {
connection.start();
} catch (JMSException e) {
throw new JmsException("Unable to start JMS connection", e);
}
}
connectionOption = Optional.of(connection);
}
return connectionOption.get();
} | java | {
"resource": ""
} |
q169747 | JmsService.sendTextMessageWithDestination | validation | public void sendTextMessageWithDestination(final String destinationName, final String messageContent) {
if (!this.isConnected()) {
throw new JmsNotConnectedException("JMS connection is down " + destinationName);
}
final Session session = getSession();
final MessageProducer producer = getProducer(destinationName);
try {
TextMessage message = session.createTextMessage(messageContent);
producer.send(message);
} catch (JMSException e) {
throw new JmsException("Unable to send message to " + destinationName, e);
}
} | java | {
"resource": ""
} |
q169748 | JmsService.listenTextMessagesWithDestination | validation | public void listenTextMessagesWithDestination(final String destinationName,
final Consumer<String> messageListener) {
final MessageConsumer consumer = getConsumer(destinationName);
try {
consumer.setMessageListener(message -> {
try {
messageListener.accept(
((TextMessage) message).getText()
);
if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
message.acknowledge();
}
} catch (JMSException e) {
throw new JmsException("Unable to register get text from message in listener " + destinationName, e);
} catch (Exception ex) {
throw new IllegalStateException("Unable handle JMS Consumer " + destinationName, ex);
}
});
} catch (JMSException e) {
throw new JmsException("Unable to register message listener " + destinationName, e);
}
} | java | {
"resource": ""
} |
q169749 | JmsService.receiveTextMessageFromDestinationWithTimeout | validation | public String receiveTextMessageFromDestinationWithTimeout(final String destinationName, final int timeout) {
if (!this.isConnected()) {
throw new JmsNotConnectedException("Not connected");
}
MessageConsumer consumer = getConsumer(destinationName);
TextMessage message;
try {
if (timeout == 0) {
message = (TextMessage) consumer.receiveNoWait();
} else {
message = (TextMessage) consumer.receive(timeout);
}
if (message != null) {
if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
message.acknowledge();
}
return message.getText();
} else {
return null;
}
} catch (JMSException e) {
throw new JmsException("Unable to receive message from " + destinationName, e);
}
} | java | {
"resource": ""
} |
q169750 | JmsService.stop | validation | @Override
public void stop() {
if (connectionOption.isPresent()) {
try {
if (startConnection)
connectionOption.get().close();
} catch (JMSException e) {
throw new JmsException("Unable to stop ", e);
}
connectionOption = Optional.empty();
sessionOption = Optional.empty();
producers.clear();
consumers.clear();
destinations.clear();
}
} | java | {
"resource": ""
} |
q169751 | RecommendationService.handleLoadFromUserDataService | validation | private void handleLoadFromUserDataService(final User loadedUser,
final Callback<List<Recommendation>> recommendationsCallback) {
/** Add a runnable to the callbacks list. */
callbacks.add(() -> {
List<Recommendation> recommendations = runRulesEngineAgainstUser(loadedUser);
recommendationsCallback.accept(recommendations);
});
// callbacks.add(new Runnable() {
// @Override
// public void run() {
// List<Recommendation> recommendations = runRulesEngineAgainstUser(loadedUser);
// recommendationsCallback.accept(recommendations);
// }
// });
} | java | {
"resource": ""
} |
q169752 | WekaModelConfig.getPoolConfiguration | validation | @NotNull
public Map<Object, Object> getPoolConfiguration() {
return ConfigurationConverter.getMap(configuration.subset(GenericObjectPoolConfig.class.getName()));
} | java | {
"resource": ""
} |
q169753 | WekaModelConfig.setId | validation | public void setId(UUID id) {
this.dirty = true;
this.id = id;
this.modelConfig.setProperty(ID, id.toString());
} | java | {
"resource": ""
} |
q169754 | WekaModelConfig.setModel | validation | public void setModel(File model) {
this.dirty = true;
this.model = model;
this.modelConfig.setProperty(MODEL_FILE, model.getAbsolutePath());
} | java | {
"resource": ""
} |
q169755 | WekaScorer.addOrUpdate | validation | public void addOrUpdate(WekaModelConfig wekaModelConfig) throws FOSException {
checkNotNull(wekaModelConfig, "Model config cannot be null");
WekaThreadSafeScorer newWekaThreadSafeScorer = new WekaThreadSafeScorerPool(wekaModelConfig, wekaManagerConfig);
WekaThreadSafeScorer oldWekaThreadSafeScorer = quickSwitch(wekaModelConfig.getId(), newWekaThreadSafeScorer);
WekaUtils.closeSilently(oldWekaThreadSafeScorer);
} | java | {
"resource": ""
} |
q169756 | WekaScorer.removeModel | validation | public void removeModel(UUID modelId) {
WekaThreadSafeScorer newWekaThreadSafeScorer = null;
WekaThreadSafeScorer oldWekaThreadSafeScorer = quickSwitch(modelId, newWekaThreadSafeScorer);
WekaUtils.closeSilently(oldWekaThreadSafeScorer);
} | java | {
"resource": ""
} |
q169757 | ClusterConfiguration.clusteredEventManagerServiceQueue | validation | @Bean
public ServiceQueue clusteredEventManagerServiceQueue(final @Qualifier("eventBusCluster")
EventBusCluster eventBusCluster) {
if (eventBusCluster == null) {
return null;
}
return eventBusCluster.eventServiceQueue();
} | java | {
"resource": ""
} |
q169758 | ClusterConfiguration.clusteredEventManagerImpl | validation | @Bean
public EventManager clusteredEventManagerImpl(final EventConnectorHub eventConnectorHub) {
return EventManagerBuilder.eventManagerBuilder()
.setEventConnector(eventConnectorHub)
.setName("CLUSTERED_EVENT_MANAGER").build();
} | java | {
"resource": ""
} |
q169759 | Encode.encodeNonCodes | validation | public static String encodeNonCodes(String string) {
Matcher matcher = nonCodes.matcher(string);
StringBuffer buf = new StringBuffer();
// FYI: we do not use the no-arg matcher.find()
// coupled with matcher.appendReplacement()
// because the matched text may contain
// a second % and we must make sure we
// encode it (if necessary).
int idx = 0;
while (matcher.find(idx)) {
int start = matcher.start();
buf.append(string.substring(idx, start));
buf.append("%25");
idx = start + 1;
}
buf.append(string.substring(idx));
return buf.toString();
} | java | {
"resource": ""
} |
q169760 | Encode.decode | validation | public static MultivaluedMap<String, String> decode(MultivaluedMap<String, String> map) {
MultivaluedMapImpl<String, String> decoded = new MultivaluedMapImpl<String, String>();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> values = entry.getValue();
for (String value : values) {
try {
decoded.add(URLDecoder.decode(entry.getKey(), UTF_8), URLDecoder.decode(value, UTF_8));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
return decoded;
} | java | {
"resource": ""
} |
q169761 | ResourceClassProcessor.createServiceGroup | validation | public ServiceGroup createServiceGroup(Set<ResourceClass> resourceClasses, ServiceGroup.ServiceGroupBuilder serviceGroupBuilder) {
for (ResourceClass resourceClass : resourceClasses) {
Logger.info("{0} processing started", resourceClass.getClazz().getCanonicalName());
Service service = createResource(resourceClass);
serviceGroupBuilder.service(service);
Logger.info("{0} processing finished", resourceClass.getClazz().getCanonicalName());
}
return serviceGroupBuilder.build();
} | java | {
"resource": ""
} |
q169762 | WekaManager.close | validation | @Override
public synchronized void close() throws FOSException {
acceptThreadRunning = false;
if (scorerHandler != null) {
scorerHandler.close();
}
IOUtils.closeQuietly(serverSocket);
saveConfiguration();
} | java | {
"resource": ""
} |
q169763 | EventRemoteReplicatorService.forwardEvent | validation | @Override
public void forwardEvent(final EventTransferObject<Object> event) {
eventConnector.forwardEvent(new EventTransferObject<Object>() {
@Override
public String channel() {
return event.channel();
}
@Override
public long id() {
return event.id();
}
@Override
public Object body() {
return event.body();
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public MultiMap<String, String> params() {
return event.params();
}
@Override
public MultiMap<String, String> headers() {
return event.headers();
}
/* Save a map lookup or building a header map. */
@Override
public boolean wasReplicated() {
return true;
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object obj) {
//noinspection EqualsBetweenInconvertibleTypes
return event.equals(obj);
}
@Override
public int hashCode() {
return event.hashCode();
}
});
} | java | {
"resource": ""
} |
q169764 | FindAnnotation.getResourcesAnnotations | validation | public static Annotation[] getResourcesAnnotations(Method method) {
Map<Class<?>, Annotation> annotations = new HashMap<Class<?>, Annotation>();
for (Annotation annotation : method.getDeclaringClass().getAnnotations()) {
annotations.put(annotation.getClass(), annotation);
}
for (Annotation annotation : method.getAnnotations()) {
annotations.put(annotation.getClass(), annotation);
}
return annotations.values().toArray(new Annotation[annotations.size()]);
} | java | {
"resource": ""
} |
q169765 | FindAnnotation.findAnnotation | validation | public static <T extends Annotation> T findAnnotation(Class<?> type, Annotation[] annotations, Class<T> annotation) {
T config = FindAnnotation.findAnnotation(annotations, annotation);
if (config == null) {
config = type.getAnnotation(annotation);
}
return config;
} | java | {
"resource": ""
} |
q169766 | ResourceBuilder.constructor | validation | public static ResourceConstructor constructor(Class<?> annotatedResourceClass) {
Constructor constructor = PickConstructor.pickPerRequestConstructor(annotatedResourceClass);
if (constructor == null) {
throw new RuntimeException("Could not find constructor for class: " + annotatedResourceClass.getName());
}
ResourceConstructorBuilder builder = rootResource(annotatedResourceClass).constructor(constructor);
if (constructor.getParameterTypes() != null) {
for (int i = 0; i < constructor.getParameterTypes().length; i++)
builder.param(i).fromAnnotations();
}
return builder.buildConstructor().buildClass().getConstructor();
} | java | {
"resource": ""
} |
q169767 | ResourceBuilder.rootResourceFromAnnotations | validation | public static ResourceClass rootResourceFromAnnotations(Class<?> clazz) {
ResourceClass resourceClass = fromAnnotations(false, clazz);
return resourceClass;
} | java | {
"resource": ""
} |
q169768 | RandomForestUtils.setupBaggingClassifiers | validation | public static void setupBaggingClassifiers(IteratedSingleClassifierEnhancer bagging) throws Exception {
bagging.m_Classifiers = Classifier.makeCopies(bagging.m_Classifier, bagging.m_NumIterations);
} | java | {
"resource": ""
} |
q169769 | Cloner.get | validation | @NotNull
public T get() throws IOException, ClassNotFoundException {
/* cannot be pre-instantiated to enable thread concurrency*/
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
byteArrayInputStream = new ByteArrayInputStream(this.serializedObject);
objectInputStream = new ObjectInputStream(byteArrayInputStream);
return (T) objectInputStream.readObject();
} finally {
IOUtils.closeQuietly(byteArrayInputStream);
IOUtils.closeQuietly(objectInputStream);
}
} | java | {
"resource": ""
} |
q169770 | Cloner.getSerialized | validation | @NotNull
public byte[] getSerialized() {
byte[] result = new byte[serializedObject.length];
System.arraycopy(serializedObject, 0, result, 0, serializedObject.length);
return result;
} | java | {
"resource": ""
} |
q169771 | Cloner.write | validation | public void write(File file) throws IOException {
checkNotNull(file, "Output file cannot be null");
FileUtils.writeByteArrayToFile(file, serializedObject);
} | java | {
"resource": ""
} |
q169772 | PMMLConversionCommons.leafScoreFromDistribution | validation | public static String leafScoreFromDistribution(double[] classDistribution, Instances instances) {
double sum = 0, maxCount = 0;
int maxIndex = 0;
if (classDistribution != null) {
sum = Utils.sum(classDistribution);
maxIndex = Utils.maxIndex(classDistribution);
maxCount = classDistribution[maxIndex];
}
return instances.classAttribute().value(maxIndex);
} | java | {
"resource": ""
} |
q169773 | JmsServiceBuilder.getProviderURL | validation | public String getProviderURL() {
if (providerURL == null) {
providerURL = getProviderURLPattern().replace("#host#", getHost())
.replace("#port#", Integer.toString(getPort()));
}
return providerURL;
} | java | {
"resource": ""
} |
q169774 | JmsServiceBuilder.getContext | validation | public Context getContext() {
if (context == null) {
try {
context = new InitialContext(createProperties());
} catch (NamingException e) {
throw new IllegalStateException("Unable to create context", e);
}
}
return context;
} | java | {
"resource": ""
} |
q169775 | JmsServiceBuilder.getConnectionSupplier | validation | public Supplier<Connection> getConnectionSupplier() {
final boolean startConnection = isStartConnection();
if (connectionSupplier == null) {
if (getUserName() == null) {
connectionSupplier = () -> {
try {
final Connection connection = getConnectionFactory().createConnection();
if (startConnection) {
connection.start();
}
return connection;
} catch (JMSException e) {
throw new JmsNotConnectedException("Unable to create context", e);
}
};
} else {
final String userName = getUserName();
final String password = getPassword();
connectionSupplier = () -> {
try {
final Connection connection = getConnectionFactory().createConnection(userName, password);
if (startConnection) {
connection.start();
}
return connection;
} catch (JMSException e) {
throw new JmsNotConnectedException("Unable to create context for user " + userName, e);
}
};
}
}
return connectionSupplier;
} | java | {
"resource": ""
} |
q169776 | JmsServiceBuilder.build | validation | public JmsService build() {
return new JmsService(
getConnectionSupplier(), getDestinationSupplier(), isTransacted(),
getAcknowledgeMode(), isStartConnection(), getDefaultDestination(), getDefaultTimeout());
} | java | {
"resource": ""
} |
q169777 | JacksonToJrapidocProcessor.getType | validation | public Type getType(SimpleType jacksonType) {
try {
String signature = JacksonSignature.createSignature(jacksonType);
CustomType type = new CustomType(jacksonType.getRawClass().getName(), signature, jacksonType.getRawClass());
if (cache.containsKey(signature)) {
return cache.get(signature);
}
cache.put(signature, type);
ObjectWriter objectWriter = objectMapper.writerFor(jacksonType);
Field prefetchField = objectWriter.getClass().getDeclaredField("_prefetch");
prefetchField.setAccessible(true);
ObjectWriter.Prefetch prefetch = (ObjectWriter.Prefetch) prefetchField.get(objectWriter);
doIntrospection(prefetch.valueSerializer, type);
return type;
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
} | java | {
"resource": ""
} |
q169778 | JacksonToJrapidocProcessor.getType | validation | public Type getType(JavaType type) {
if (type instanceof SimpleType) {
return getType((SimpleType) type);
} else if (type instanceof CollectionType) {
return getType((CollectionLikeType) type);
} else if (type instanceof ArrayType) {
return getType((ArrayType) type);
} else if (type instanceof MapLikeType) {
return getType((MapLikeType) type);
}
throw new RuntimeException("Unimplemented Jackson type: " + type);
} | java | {
"resource": ""
} |
q169779 | JacksonToJrapidocProcessor.doIntrospection | validation | private void doIntrospection(JsonSerializer serializer, Type type) {
if (serializer == null) {
return;
}
if (EnumSerializer.class.isAssignableFrom(serializer.getClass())) {
introspectSerializer((EnumSerializer) serializer, (CustomType) type);
} else if (BeanSerializerBase.class.isAssignableFrom(serializer.getClass())) {
introspectSerializer((BeanSerializerBase) serializer, (CustomType) type);
} else if (StdScalarSerializer.class.isAssignableFrom(serializer.getClass())) {
introspectSerializer((StdScalarSerializer) serializer, (CustomType) type);
} else if (AsArraySerializerBase.class.isAssignableFrom(serializer.getClass())) {
introspectSerializer((AsArraySerializerBase) serializer, (CollectionTypeJrapidoc) type);
} else if (MapSerializer.class.isAssignableFrom(serializer.getClass())) {
introspectSerializer((MapSerializer) serializer, (MapTypeJrapidoc) type);
}
} | java | {
"resource": ""
} |
q169780 | JacksonToJrapidocProcessor.introspectSerializer | validation | private void introspectSerializer(BeanSerializerBase beanSerializer, CustomType type) {
try {
Field propsField = beanSerializer.getClass().getSuperclass().getDeclaredField("_props");
propsField.setAccessible(true);
BeanPropertyWriter[] props = (BeanPropertyWriter[]) propsField.get(beanSerializer);
for (BeanPropertyWriter prop : props) {
JavaType propType = prop.getType();
getType(propType);
String signature = JacksonSignature.createSignature(propType);
type.addBeanProperty(new BeanProperty(prop.getName(), signature, prop.getPropertyType(), prop.getMetadata().getDescription(), prop
.getMetadata().isRequired()));
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q169781 | JacksonToJrapidocProcessor.introspectSerializer | validation | private void introspectSerializer(EnumSerializer enumSerializer, CustomType type) {
for (SerializableString value : enumSerializer.getEnumValues().values()) {
type.addEnumeration(value.getValue());
}
} | java | {
"resource": ""
} |
q169782 | JacksonToJrapidocProcessor.introspectSerializer | validation | private void introspectSerializer(MapSerializer mapSerializer, MapTypeJrapidoc type) {
try {
Field keyTypeField = mapSerializer.getClass().getDeclaredField("_keyType");
keyTypeField.setAccessible(true);
JavaType keyType = (JavaType) keyTypeField.get(mapSerializer);
JavaType valueType = mapSerializer.getContentType();
getType(keyType);
getType(valueType);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q169783 | TradeOrderProc.frame1 | validation | private void frame1() {
// SELECT acct_name = ca_name, broker_id = ca_b_id,
// cust_id = ca_c_id, tax_status = ca_tax_st FROM
// customer_account WHERE ca_id = acct_id
String sql = "SELECT ca_name, ca_b_id, ca_c_id, ca_tax_st FROM customer_account"
+ " WHERE ca_id = " + paramHelper.getAcctId();
Scan s = executeQuery(sql);
acctName = (String) s.getVal("ca_name").asJavaVal();
brokerId = (Long) s.getVal("ca_b_id").asJavaVal();
custId = (Long) s.getVal("ca_c_id").asJavaVal();
taxStatus = (Integer) s.getVal("ca_tax_st").asJavaVal();
// TODO: Add this
// num_found = row_count
// SELECT cust_f_name = c_f_name, cust_l_name = c_l_name,
// cust_tier = c_tier, tax_id = c_tax_id FROM
// customer WHERE c_id = cust_id
sql = "SELECT c_f_name, c_l_name, c_tier, c_tax_id FROM customer"
+ " WHERE c_id = " + custId;
s = executeQuery(sql);
custFName = (String) s.getVal("c_f_name").asJavaVal();
custLName = (String) s.getVal("c_l_name").asJavaVal();
custTier = (Integer) s.getVal("c_tier").asJavaVal();
taxId = (String) s.getVal("c_tax_id").asJavaVal();
// SELECT broker_name = b_name FROM broker WHERE b_id = broker_id
sql = "SELECT b_name FROM broker WHERE b_id = " + brokerId;
s = executeQuery(sql);
brokerName = (String) s.getVal("b_name").asJavaVal();
} | java | {
"resource": ""
} |
q169784 | TradeOrderProc.frame3 | validation | private void frame3() {
// ===== Simplified Version =====
// SELECT co_id = s_co_id, exch_id = s_ex_id, s_name = s_name
// FROM security WHERE s_symb = symbol
String sql = "SELECT s_co_id, s_ex_id, s_name FROM security WHERE "
+ "s_symb = " + paramHelper.getSymbol();
Scan s = executeQuery(sql);
coId = (Long) s.getVal("s_co_id").asJavaVal();
exchId = (String) s.getVal("s_ex_id").asJavaVal();
sName = (String) s.getVal("s_name").asJavaVal();
// SELECT market_price = lt_price FROM last_trade
// WHERE lt_s_symb = symbol
sql = "SELECT lt_price FROM last_trade WHERE "
+ "lt_s_symb = " + paramHelper.getSymbol();
s = executeQuery(sql);
marketPrice = (Double) s.getVal("lt_price").asJavaVal();
// SELECT type_is_market = tt_is_mrkt, type_is_sell = tt_is_sell
// FROM trade_type WHERE tt_id = trade_type_id
sql = "SELECT tt_is_mrkt, tt_is_sell FROM trade_type WHERE "
+ "tt_id = " + paramHelper.getTradeTypeId();
s = executeQuery(sql);
typeIsMarket = (Integer) s.getVal("tt_is_mrkt").asJavaVal();
typeIsSell = (Integer) s.getVal("tt_is_sell").asJavaVal();
if (typeIsMarket == 1) {
statusId = "A";
} else {
statusId = "B";
}
// TODO: Implement this version
// ===== Full Version =====
// Get information on the security
if (true) {
// SELECT co_id = co_id FROM company WHERE co_name = co_name
// SELECT exch_id = s_ex_id, s_name = s_name, symbol = s_symb
// FROM security WHERE s_co_id = co_id AND s_issue = issue
} else {
// SELECT co_id = s_co_id, exch_id = s_ex_id, s_name = s_name
// FROM security WHERE s_symb = symbol
// SELECT co_name = co_name FROM company WHERE co_id = co_id
}
// Get current pricing information for the security
// SELECT market_price = lt_price FROM last_trade
// WHERE lt_s_symb = symbol
// Set trade characteristics based on the type of trade
// SELECT type_is_market = tt_is_mrkt, type_is_sell = tt_is_sell
// FROM trade_type WHERE tt_id = trade_type_id
// If this is a limit-order, then the requested_price was passed in to the frame,
// but if this a market-order, then the requested_price needs to be set to the
// current market price.
// if( type_is_market ) then {
// requested_price = market_price
// }
// TODO: Estimation
} | java | {
"resource": ""
} |
q169785 | TradeOrderProc.frame4 | validation | private void frame4() {
long currentTime = System.currentTimeMillis();
// XXX: Lots of dummy value
// Record trade information in TRADE table.
// INSERT INTO trade (t_id, t_dts, t_st_id, t_tt_id, t_is_cash,
// t_s_symb, t_qty, t_bid_price, t_ca_id, t_exec_name, t_trade_price,
// t_chrg, t_comm, t_tax, t_lifo) VALUES (...)
String sql = String.format("INSERT INTO trade (t_id, t_dts, t_st_id, t_tt_id, "
+ "t_is_cash, t_s_symb, t_qty, t_bid_price, t_ca_id, t_exec_name, "
+ "t_trade_price, t_chrg, t_comm, t_tax, t_lifo) VALUES (%d, %d, '%s', "
+ "'%s', %d, '%s', %d, %f, %d, '%s', %f, %f, %f, %f, %d)",
paramHelper.getTradeId(), currentTime, statusId,
paramHelper.getTradeTypeId(), 1, paramHelper.getSymbol(),
paramHelper.getTradeQty(), marketPrice, paramHelper.getAcctId(), "exec_name",
paramHelper.getTradePrice(), 0.0, 0.0, 0.0, 1);
executeUpdate(sql);
// TODO: Implement this (not in the simplified version)
// Record pending trade information in TRADE_REQUEST table
// if this trade is a limit trade
// INSERT INTO trade_request (tr_t_id, tr_tt_id, tr_s_symb, tr_qty,
// tr_bid_price, tr_b_id) VALUES (...)
// Record trade information in TRADE_HISTORY table
// INSERT INTO trade_history (th_t_id, th_dts, th_st_id) VALUES (...)
sql = String.format("INSERT INTO trade_history (th_t_id, th_dts, th_st_id) VALUES "
+ "(%d, %d, '%s')", paramHelper.getTradeId(), currentTime, statusId);
executeUpdate(sql);
} | java | {
"resource": ""
} |
q169786 | RandomPermutationGenerator.next | validation | public void next() {
for (int k = a.length - 1; k > 0; k--) {
int w = (int) Math.floor(Math.random() * (k + 1));
int temp = a[w];
a[w] = a[k];
a[k] = temp;
}
} | java | {
"resource": ""
} |
q169787 | RandomNonRepeatGenerator.next | validation | public int next() {
// int rndIndex = (int) ((array.length - 1 - curIndex) * rg.nextDouble())
// + curIndex;
// int tmp = array[rndIndex];
// array[rndIndex] = array[curIndex];
// array[curIndex] = tmp;
// curIndex++;
//
// return tmp;
int number;
do{
number = rg.nextInt(size) + 1;
} while(!numberSet.add(number));
return number;
} | java | {
"resource": ""
} |
q169788 | MicrobenchmarkParamGen.main | validation | public static void main(String[] args) {
MicrobenchmarkParamGen executor = new MicrobenchmarkParamGen();
System.out.println("Parameters:");
System.out.println("Read Write Tx Rate: " + RW_TX_RATE);
System.out.println("Long Read Tx Rate: " + LONG_READ_TX_RATE);
System.out.println("Total Read Count: " + TOTAL_READ_COUNT);
System.out.println("Local Hot Count: " + LOCAL_HOT_COUNT);
System.out.println("Write Ratio in RW Tx: " + WRITE_RATIO_IN_RW_TX);
System.out.println("Hot Conflict Rate: " + HOT_CONFLICT_RATE);
System.out.println("# of items: " + DATA_SIZE);
System.out.println("# of hot items: " + HOT_DATA_SIZE);
System.out.println("# of cold items: " + COLD_DATA_SIZE);
System.out.println();
for (int i = 0; i < 1000; i++) {
Object[] params = executor.generateParameter();
System.out.println(Arrays.toString(params));
}
} | java | {
"resource": ""
} |
q169789 | TpccValueGenerator.makeLastName | validation | public String makeLastName(int number) {
if (number < 0 && number > TpccConstants.NUM_DISTINCT_CLAST - 1)
throw new IllegalArgumentException();
int indicies[] = { number / 100, (number / 10) % 10, number % 10 };
StringBuffer sb = new StringBuffer();
for (int i = 0; i < indicies.length; ++i) {
sb.append(TOKENS[indicies[i]]);
}
return sb.toString();
} | java | {
"resource": ""
} |
q169790 | RandomValueGenerator.randomChooseFromDistribution | validation | public int randomChooseFromDistribution(double... probs) {
int result = -1;
int[] range = new int[probs.length];
double accuracy = 1000;
int total = 0;
for (int i = 0; i < probs.length; i++) {
range[i] = (int) (probs[i] * accuracy);
total += range[i];
}
int randNum = (int) (rng.nextDouble() * total);
for (int i = 0; i < range.length; i++) {
randNum -= range[i];
if (randNum <= 0) {
result = i;
break;
}
}
return result;
} | java | {
"resource": ""
} |
q169791 | GitFileSystemObject.getRelativePath | validation | public static File getRelativePath(File in, File repositoryPath) throws JavaGitException {
String path = in.getPath();
String absolutePath = in.getAbsolutePath();
//check if the path is relative or absolute
if(path.equals(absolutePath)) {
//if absolute, make sure it belongs to working tree
String workingTreePath = repositoryPath.getAbsolutePath();
if(!path.startsWith(workingTreePath)) {
throw new JavaGitException(999, "Invalid path :" + path
+ ". Does not belong to the git working tree/ repository: " + workingTreePath);
}
//make path relative
if(!path.equals(workingTreePath)) {
path = path.substring(workingTreePath.length()+1);
}
}
return new File(path);
} | java | {
"resource": ""
} |
q169792 | GitFileSystemObject.add | validation | public GitAddResponse add() throws IOException, JavaGitException {
GitAdd gitAdd = new GitAdd();
// create a list of filenames and add yourself to it
List<File> list = new ArrayList<File>();
File relativeFilePath;
if(relativePath.isDirectory()){
for(File f : relativePath.listFiles()){
if(!f.isHidden() && !f.getName().startsWith(".")){
relativeFilePath = this.getRelativePath(f, this.getWorkingTree().getPath());
list.add(relativeFilePath );
}
}
}
else{
list.add(relativePath);
}
// run git-add command
return gitAdd.add(workingTree.getPath(), null, list);
} | java | {
"resource": ""
} |
q169793 | GitFileSystemObject.commit | validation | public GitCommitResponse commit(String comment) throws IOException, JavaGitException {
// first add the file
add();
// create a list of filenames and add yourself to it
List<File> list = new ArrayList<File>();
list.add(relativePath);
GitCommit gitCommit = new GitCommit();
return gitCommit.commitOnly(workingTree.getPath(), comment, list);
} | java | {
"resource": ""
} |
q169794 | GitFileSystemObject.mv | validation | public GitMvResponse mv(File dest) throws IOException, JavaGitException {
// source; current location (relative)
File source = relativePath;
//get relative path for destination
File relativeDest = getRelativePath(dest, workingTree.getPath());
// perform git-mv
GitMv gitMv = new GitMv();
GitMvResponse response = gitMv.mv(workingTree.getPath(), source, relativeDest);
// file has changed; update
file = dest;
relativePath = relativeDest;
return response;
} | java | {
"resource": ""
} |
q169795 | GitFileSystemObject.rm | validation | public GitRmResponse rm() throws IOException, JavaGitException {
GitRm gitRm = new GitRm();
// run git rm command
return gitRm.rm(workingTree.getPath(), relativePath);
} | java | {
"resource": ""
} |
q169796 | CheckUtilities.checkFileValidity | validation | public static void checkFileValidity(File file) throws IOException {
if (!file.exists()) {
throw new IOException(ExceptionMessageMap.getMessage("020001") + " { filename=["
+ file.getName() + "] }");
}
} | java | {
"resource": ""
} |
q169797 | CheckUtilities.checkUnorderedListsEqual | validation | public static boolean checkUnorderedListsEqual(List<?> l1, List<?> l2) {
if (null == l1 && null != l2) {
return false;
}
if (null != l1 && null == l2) {
return false;
}
if (l1.size() != l2.size()) {
return false;
}
for (Object o : l1) {
if (!l2.contains(o)) {
return false;
}
}
for (Object o : l2) {
if (!l1.contains(o)) {
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q169798 | CheckUtilities.checkIntInRange | validation | public static void checkIntInRange(int index, int start, int end) {
if (index < start) {
throw new IndexOutOfBoundsException(ExceptionMessageMap.getMessage("000006") + " { index=["
+ index + "], start=[" + start + "], end=[" + end + "] }");
}
if (index >= end) {
throw new IndexOutOfBoundsException(ExceptionMessageMap.getMessage("000006") + " { index=["
+ index + "], start=[" + start + "], end=[" + end + "] }");
}
} | java | {
"resource": ""
} |
q169799 | ClientManager.getClientInstance | validation | public IClient getClientInstance(ClientType clientType) {
IClient clientInstance = clientImpls.get(clientType);
if (null == clientInstance) {
if (ClientType.CLI == clientType) {
clientInstance = new CliClient();
}
if (null != clientInstance) {
clientImpls.put(clientType, clientInstance);
}
}
return clientInstance;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.