hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
29aae679af86deee5ac595754c7465bb7c62b6cd | 1,988 | package io.joyrpc.protocol.grpc;
/*-
* #%L
* joyrpc
* %%
* Copyright (C) 2019 joyrpc.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.
* #L%
*/
import io.grpc.Status;
import io.grpc.internal.GrpcUtil;
import io.joyrpc.transport.http2.DefaultHttp2Headers;
import io.joyrpc.transport.http2.Http2Headers;
import static io.joyrpc.constants.Constants.GRPC_MESSAGE_KEY;
import static io.joyrpc.constants.Constants.GRPC_STATUS_KEY;
/**
* 头构建器
*/
public abstract class Headers {
/**
* 设置结束头
*
* @param end 是否结束
* @return 头
*/
public static Http2Headers build(final boolean end) {
Http2Headers headers = new DefaultHttp2Headers();
headers.status("200");
headers.set(GrpcUtil.CONTENT_TYPE_KEY.name(), GrpcUtil.CONTENT_TYPE_GRPC);
if (end) {
headers.set(GRPC_STATUS_KEY, Status.Code.OK.value());
}
return headers;
}
/**
* 设置异常结束头
*
* @param throwable 异常
* @return 头
*/
public static Http2Headers build(final Throwable throwable) {
String errorMsg = throwable.getClass().getName() + ":" + throwable.getMessage();
Http2Headers headers = new DefaultHttp2Headers();
headers.status("200");
headers.set(GrpcUtil.CONTENT_TYPE_KEY.name(), GrpcUtil.CONTENT_TYPE_GRPC);
headers.set(GRPC_STATUS_KEY, Status.Code.INTERNAL.value());
headers.set(GRPC_MESSAGE_KEY, errorMsg);
return headers;
}
}
| 29.235294 | 88 | 0.676559 |
a7f168af9e0f2977c125e25d51e2d2fff6d5fd4e | 1,861 | /*
* 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.shindig.common.servlet;
import com.google.inject.Injector;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
/**
* A Filter that can use Guice for injecting. Complements InjectedServlet.
*/
public abstract class InjectedFilter implements Filter {
protected Injector injector;
public void init(FilterConfig config) throws ServletException {
ServletContext context = config.getServletContext();
injector = (Injector) context.getAttribute(GuiceServletContextListener.INJECTOR_ATTRIBUTE);
if (injector == null) {
injector = (Injector)
context.getAttribute(GuiceServletContextListener.INJECTOR_NAME);
if (injector == null) {
throw new UnavailableException(
"Guice Injector not found! Make sure you registered " +
GuiceServletContextListener.class.getName() + " as a listener");
}
}
injector.injectMembers(this);
}
}
| 37.22 | 95 | 0.74691 |
a2ae592b72fcd3810cae715213d1d7c4420b1a0d | 262 | package restful.context;
/**
* @author André Schmer
*
*/
public class RestfulContext {
private static String token;
public static void setToken(final String logintoken) {
token = logintoken;
}
public static String getToken() {
return token;
}
}
| 13.1 | 55 | 0.70229 |
31e8222809bca12f21a774409a6a65338ed86707 | 153 | package io.gunmetal.sandbox.testmocks;
import javax.inject.Inject;
/**
* @author rees.byars
*/
public class Z {
@Inject
public Z() {
}
}
| 11.769231 | 38 | 0.627451 |
8ec336d865695ac83a72da7ba49f5365dd322e99 | 2,233 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.patching.runner;
import java.io.IOException;
import org.jboss.as.patching.metadata.ContentModification;
import org.jboss.as.patching.metadata.ModificationType;
import org.jboss.as.patching.metadata.ModuleItem;
/**
* Task used to find the active modules and record them as part of the invalidation roots.
*
* @author Emanuel Muckenhuber
*/
class ModuleRollbackTask extends AbstractModuleTask {
public ModuleRollbackTask(PatchingTaskDescription description) {
super(description);
}
@Override
protected byte[] notFound(ModuleItem contentItem) throws IOException {
// Maybe just don't record the original ADD as part of the history?
if (description.getModificationType() == ModificationType.REMOVE) {
return contentItem.getContentHash();
}
return super.notFound(contentItem);
}
@Override
byte[] apply(final PatchingTaskContext context, final PatchContentLoader loader) throws IOException {
return getContentItem().getContentHash();
}
@Override
ContentModification createRollbackEntry(ContentModification original, byte[] targetHash, byte[] itemHash) {
return null;
}
}
| 36.606557 | 111 | 0.737573 |
41a329716a5992b702a96fbafe77d0d1ada55c10 | 11,529 | package markpeng.kaggle.mmc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.util.Version;
public class TrainingFileGenerator implements Runnable {
private static final int BUFFER_LENGTH = 1000;
private static final String newLine = System.getProperty("line.separator");
private static final int MAX_NGRAM = 2;
private static final int MIN_DF = 2;
private static final double MAX_DF_PERCENT = 0.85;
String mode;
String trainLabelFile;
String trainFolder;
String outputCsv;
String fileType;
boolean filtered;
String[] featureFiles;
public TrainingFileGenerator() {
}
public TrainingFileGenerator(String mode, String trainLabelFile,
String trainFolder, String outputCsv, String fileType,
boolean filtered, String... featureFiles) {
this.mode = mode;
this.trainLabelFile = trainLabelFile;
this.trainFolder = trainFolder;
this.outputCsv = outputCsv;
this.fileType = fileType;
this.filtered = filtered;
}
@Override
public void run() {
try {
if (mode.equals("csv"))
generatCSV(trainLabelFile, trainFolder, outputCsv, fileType,
filtered, featureFiles);
else if (mode.equals("libsvm"))
generateLibsvm(trainLabelFile, trainFolder, outputCsv,
fileType, filtered, featureFiles);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Hashtable<String, List<String>> readTrainLabel(String trainLabelFile)
throws Exception {
// <label, list<doc_ids>>
Hashtable<String, List<String>> output = new Hashtable<String, List<String>>();
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(trainLabelFile), "UTF-8"));
try {
String aLine = null;
// skip header line
in.readLine();
while ((aLine = in.readLine()) != null) {
String[] sp = aLine.split(",");
if (sp != null && sp.length > 0) {
String fileName = sp[0].replaceAll("\"", "");
String label = sp[1];
// System.out.println(fileName + ", " + label);
if (output.get(label) == null) {
List<String> tmp = new ArrayList<String>();
tmp.add(fileName);
output.put(label, tmp);
} else {
List<String> tmp = output.get(label);
tmp.add(fileName);
output.put(label, tmp);
}
}
}
} finally {
in.close();
}
return output;
}
public List<String> readFeature(String... featureFiles) throws Exception {
List<String> features = new ArrayList<String>();
for (String featureFile : featureFiles) {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(featureFile), "UTF-8"));
try {
String aLine = null;
while ((aLine = in.readLine()) != null) {
String tmp = aLine.toLowerCase().trim();
if (tmp.length() > 0 && !features.contains(tmp))
features.add(tmp);
}
} finally {
in.close();
}
}
// extra features
if (!features.contains("db"))
features.add("db");
if (!features.contains("dd"))
features.add("dd");
return features;
}
public void generatCSV(String trainLabelFile, String trainFolder,
String outputCsv, String fileType, boolean filtered,
String... featureFiles) throws Exception {
List<String> features = readFeature(featureFiles);
Hashtable<String, List<String>> labels = readTrainLabel(trainLabelFile);
StringBuffer resultStr = new StringBuffer();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputCsv, false), "UTF-8"));
try {
// add header line
int featureIndex = 0;
resultStr.append("fileName,");
for (String feature : features) {
if (featureIndex < features.size() - 1)
resultStr.append(feature + ",");
else
resultStr.append(feature + ",classLabel" + newLine);
featureIndex++;
}
for (String label : labels.keySet()) {
String folderName = trainFolder + "/" + label;
List<String> fileList = labels.get(label);
for (String file : fileList) {
File f = null;
if (filtered)
f = new File(folderName + "/" + file + "." + fileType
+ "_filtered");
else
f = new File(folderName + "/" + file + "." + fileType);
System.out.println("Loading " + f.getAbsolutePath());
if (f.exists()) {
// add fileName
resultStr.append(file + ",");
StringBuffer fileContent = new StringBuffer();
String aLine = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(
f.getAbsolutePath()), "UTF-8"));
while ((aLine = in.readLine()) != null) {
String tmp = aLine.toLowerCase().trim();
String[] sp = tmp.split("\\t{2,}\\s{2,}");
List<String> tokens = Arrays.asList(sp);
int index = 0;
for (String token : tokens) {
if (index > 0 && token.length() > 1) {
fileContent.append(token + " ");
}
index++;
}
fileContent.append(newLine);
}
in.close();
String content = fileContent.toString();
fileContent.setLength(0);
// get term frequency
Hashtable<String, Integer> tfMap = getTermFreqByLucene(content);
// check if each feature exists
for (String feature : features) {
// int termFreq = countTermFreqByRegEx(feature,
// content);
int termFreq = 0;
if (tfMap.containsKey(feature))
termFreq = tfMap.get(feature);
resultStr.append(termFreq + ",");
} // end of feature loop
// add label
resultStr.append(label + newLine);
if (resultStr.length() >= BUFFER_LENGTH) {
out.write(resultStr.toString());
out.flush();
resultStr.setLength(0);
}
System.out.println("Completed filtering file: " + file);
}
} // end of label file loop
} // end of label loop
System.out.println("Total # of features: " + features.size());
} finally {
out.write(resultStr.toString());
out.flush();
out.close();
resultStr.setLength(0);
}
}
public void generateLibsvm(String trainLabelFile, String trainFolder,
String outputCsv, String fileType, boolean filtered,
String... featureFiles) throws Exception {
List<String> features = readFeature(featureFiles);
Hashtable<String, List<String>> labels = readTrainLabel(trainLabelFile);
StringBuffer resultStr = new StringBuffer();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputCsv, false), "UTF-8"));
try {
for (String label : labels.keySet()) {
String folderName = trainFolder + "/" + label;
List<String> fileList = labels.get(label);
for (String file : fileList) {
File f = null;
if (filtered)
f = new File(folderName + "/" + file + "." + fileType
+ "_filtered");
else
f = new File(folderName + "/" + file + "." + fileType);
System.out.println("Loading " + f.getAbsolutePath());
if (f.exists()) {
StringBuffer fileContent = new StringBuffer();
String aLine = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(
f.getAbsolutePath()), "UTF-8"));
while ((aLine = in.readLine()) != null) {
String tmp = aLine.toLowerCase().trim();
String[] sp = tmp.split("\\t{2,}\\s{2,}");
List<String> tokens = Arrays.asList(sp);
int index = 0;
for (String token : tokens) {
if (index > 0 && token.length() > 1) {
fileContent.append(token + " ");
}
index++;
}
fileContent.append(newLine);
}
in.close();
String content = fileContent.toString();
fileContent.setLength(0);
// get term frequency
Hashtable<String, Integer> tfMap = getTermFreqByLucene(content);
// add label
resultStr.append(label + " ");
// check if each feature exists
int index = 1;
for (String feature : features) {
// int termFreq = countTermFreqByRegEx(feature,
// content);
int termFreq = 0;
if (tfMap.containsKey(feature)) {
termFreq = tfMap.get(feature);
resultStr.append(index + ":" + termFreq + " ");
}
index++;
} // end of feature loop
resultStr.append(newLine);
if (resultStr.length() >= BUFFER_LENGTH) {
out.write(resultStr.toString());
out.flush();
resultStr.setLength(0);
}
System.out.println("Completed filtering file: " + file);
}
} // end of label file loop
} // end of label loop
System.out.println("Total # of features: " + features.size());
} finally {
out.write(resultStr.toString());
out.flush();
out.close();
resultStr.setLength(0);
}
}
private Hashtable<String, Integer> getTermFreqByLucene(String text)
throws IOException {
Hashtable<String, Integer> result = new Hashtable<String, Integer>();
TokenStream ts = new StandardTokenizer(Version.LUCENE_46,
new StringReader(text));
try {
CharTermAttribute termAtt = ts
.addAttribute(CharTermAttribute.class);
ts.reset();
int wordCount = 0;
while (ts.incrementToken()) {
if (termAtt.length() > 0) {
String word = termAtt.toString();
if (result.get(word) == null)
result.put(word, 1);
else {
result.put(word, result.get(word) + 1);
}
wordCount++;
}
}
} finally {
// Fixed error : close ts:TokenStream
ts.end();
ts.close();
}
return result;
}
public static void main(String[] args) throws Exception {
// args = new String[7];
// args[0] = "csv";
// args[1] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/dataSample";
// args[2] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/trainLabels.csv";
// args[3] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/ireullin/newFeatures20150318.txt|"
// +
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/ireullin/rf_nonzero_features.txt";
// args[4] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/dataSample/submission.csv";
// args[5] = "asm";
// args[6] = "false";
if (args.length < 6) {
System.out
.println("Arguments: [model{csv|libsvm}] [train folder] [train label file] [feature files] [output csv] [file type] [filtered]");
return;
}
String mode = args[0];
String trainFolder = args[1];
String trainLabelFile = args[2];
String[] featureFiles = args[3].split("\\|");
String outputCsv = args[4];
String fileType = args[5];
boolean filterred = Boolean.parseBoolean(args[5]);
TrainingFileGenerator worker = new TrainingFileGenerator();
if (mode.equals("csv"))
worker.generatCSV(trainLabelFile, trainFolder, outputCsv, fileType,
filterred, featureFiles);
else if (mode.equals("libsvm"))
worker.generateLibsvm(trainLabelFile, trainFolder, outputCsv,
fileType, filterred, featureFiles);
}
}
| 28.257353 | 134 | 0.644028 |
1c556bd34a29e0d81fe26f4d47a4af9c3b058fde | 1,477 | /* file: LeafNodeDescriptor.java */
/*******************************************************************************
* Copyright 2014-2021 Intel 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.
*******************************************************************************/
/**
* @ingroup regression
* @{
*/
package com.intel.daal.algorithms.tree_utils.regression;
import com.intel.daal.algorithms.tree_utils.NodeDescriptor;
/**
* <a name="DAAL-CLASS-ALGORITHMS-TREE_UTILS-REGRESSION__NODEDESCRIPTOR"></a>
* @brief Struct containing description of leaf node in regression descision tree
*/
public final class LeafNodeDescriptor extends NodeDescriptor {
public double response;
public LeafNodeDescriptor(long level_, double response_, double impurity_, long nNodeSampleCount_)
{
super.level = level_;
response = response_;
super.impurity = impurity_;
super.nNodeSampleCount = nNodeSampleCount_;
}
}
/** @} */
| 34.348837 | 102 | 0.659445 |
8732d5901ba5784247f7f62753feecfd703546c7 | 92 | /**
* Support for the {@code adapter:} JNDI scheme
*/
package com.adaptris.naming.adapter; | 23 | 47 | 0.706522 |
4e9d743c43514391a34b5461f67f0e89c89b0af2 | 2,540 |
package org.s3s3l.yggdrasil.starter.datasource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.s3s3l.yggdrasil.annotation.apollo.ApolloConfiguration;
import org.s3s3l.yggdrasil.bean.time.JsonTimestampDateTimeDeserializer;
import org.s3s3l.yggdrasil.bean.time.JsonTimestampDateTimeSerializer;
import org.s3s3l.yggdrasil.configuration.datasource.SwitchableDatasourceConfiguration;
import org.s3s3l.yggdrasil.configuration.mybatis.MybatisConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import io.shardingsphere.core.yaml.sharding.YamlShardingRuleConfiguration;
import lombok.Data;
/**
* <p>
* </p>
* ClassName:DefaultRedisClientConfiguration <br>
* Date: Sep 10, 2018 8:53:45 PM <br>
*
* @author kehw_zwei
* @version 1.0.0
* @since JDK 1.8
*/
@Data
@ApolloConfiguration
@ConfigurationProperties(prefix = MultiDatasourceConfiguration.PREFIX)
public class MultiDatasourceConfiguration {
public static final String PREFIX = "yggdrasil.datasource";
private Map<String, SwitchableDatasourceConfiguration> dbs = new HashMap<>();
private Map<String, ShardingDatasourceConfiguration> sharding = new HashMap<>();
private Map<String, AutoSwitchDatasourceConfiguration> autoSwitchDbs = new HashMap<>();
private MybatisConfiguration mybatis;
private List<String> requiredInstances;
private boolean enable;
private String[] tableDefinePackages = new String[] {};
@Data
public static class ShardingDatasourceConfiguration {
private YamlShardingRuleConfiguration rule;
private Map<String, Object> configMap = new LinkedHashMap<>();
private Properties props = new Properties();
private Map<String, SwitchableDatasourceConfiguration> dbs;
}
@Data
public static class AutoSwitchDatasourceConfiguration {
private DatasourceName current;
private DatasourceName next;
@JsonDeserialize(using = JsonTimestampDateTimeDeserializer.class)
@JsonSerialize(using = JsonTimestampDateTimeSerializer.class)
private Timestamp switchTime;
}
@Data
public static class DatasourceName {
private String name;
private DataSourceType type;
}
public enum DataSourceType {
COMMON, SHARDING
}
}
| 32.987013 | 91 | 0.767323 |
6344318fdfcf80dcf6909db564a4f6c83ee57cbb | 1,818 | package com.reactnativecommunity.webview;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.ReactApplicationContext;
import java.util.List;
import kotlin.Metadata;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.internal.Intrinsics;
@Metadata(mo40251bv = {1, 0, 3}, mo40252d1 = {"\u0000\"\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010 \n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\u0018\u00002\u00020\u0001B\u0005¢\u0006\u0002\u0010\u0002J\u0016\u0010\u0003\u001a\b\u0012\u0004\u0012\u00020\u00050\u00042\u0006\u0010\u0006\u001a\u00020\u0007H\u0016J\u0016\u0010\b\u001a\b\u0012\u0004\u0012\u00020\t0\u00042\u0006\u0010\u0006\u001a\u00020\u0007H\u0016¨\u0006\n"}, mo40253d2 = {"Lcom/reactnativecommunity/webview/RNCWebViewPackage;", "Lcom/facebook/react/ReactPackage;", "()V", "createNativeModules", "", "Lcom/reactnativecommunity/webview/RNCWebViewModule;", "reactContext", "Lcom/facebook/react/bridge/ReactApplicationContext;", "createViewManagers", "Lcom/reactnativecommunity/webview/RNCWebViewManager;", "react-native-webview_release"}, mo40254k = 1, mo40255mv = {1, 4, 2})
/* compiled from: RNCWebViewPackage.kt */
public final class RNCWebViewPackage implements ReactPackage {
public List<RNCWebViewModule> createNativeModules(ReactApplicationContext reactApplicationContext) {
Intrinsics.checkNotNullParameter(reactApplicationContext, "reactContext");
return CollectionsKt.listOf(new RNCWebViewModule(reactApplicationContext));
}
public List<RNCWebViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) {
Intrinsics.checkNotNullParameter(reactApplicationContext, "reactContext");
return CollectionsKt.listOf(new RNCWebViewManager());
}
}
| 79.043478 | 906 | 0.79758 |
0cee380df4c7e73e43511d78769847fd0059921b | 1,130 | package uk.org.grant.getkanban;
public class WipLimitAdjustment {
private final int expedite;
private final int selected;
private final int analysis;
private final int development;
private final int test;
private final int day;
public WipLimitAdjustment(int day, int expedite, int selected, int analysis, int development, int test) {
this.day = day;
this.expedite = expedite;
this.selected = selected;
this.analysis = analysis;
this.development = development;
this.test = test;
}
public int getDay() {
return this.day;
}
public int getExpedite() {
return this.expedite;
}
public int getSelected() {
return this.selected;
}
public int getAnalysis() {
return this.analysis;
}
public int getDevelopment() {
return this.development;
}
public int getTest() {
return this.test;
}
public String toString() {
return "[EXP=" + expedite + "; SEL=" + selected + "; ANA=" + analysis + "; DEV=" + development + "; TST=" + test + "]";
}
}
| 23.541667 | 127 | 0.597345 |
ed8b983bfd562adea4dd2ec8e9de8fe3cee305d7 | 10,144 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.struts.election_manager;
import com.myapp.struts.hbm.ElectionManagerDAO;
import com.myapp.struts.utility.AppPath;
import com.myapp.struts.utility.UserLog;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.io.*;
import jxl.*;
import java.util.*;
import jxl.Workbook;
import jxl.write.*;
import org.apache.log4j.Logger;
import java.util.List;
import javax.servlet.http.HttpSession;
/**
*
* @author edrp01
*/
public class XLSExportAction extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private static final String SUCCESS = "success";
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session=request.getSession();
String login=(String)session.getAttribute("user_id");
String login_role=(String)session.getAttribute("login_role");
String institute_id=(String)session.getAttribute("institute_id");
String election_id=request.getParameter("election");
String export=request.getParameter("export");
ArrayList columns=new ArrayList();
ElectionManagerDAO dao=new ElectionManagerDAO();
String path=AppPath.getProjectExportPath();
if(login.indexOf(".")>0)
login=login.substring(0,login.indexOf("."))+election_id;
try
{
String filename=path+login+".xls";
if (export!=null)
{
filename=path+login+".txt";
columns.add(0, "Institute_Name");
columns.add(1, "Election_Id");
columns.add(2, "Enrollment");
columns.add(3, "Email");
columns.add(4, "VoterName");
columns.add(5, "Status");
columns.add(6, "MobileNo");
columns.add(7, "Nomination Start Date");
columns.add(8, "Nomination End Date");
columns.add(9, "Election Start Date");
columns.add(10, "Election End Date");
columns.add(11, "Position Name");
StringBuffer line=new StringBuffer();
for (int k = 0; k < columns.size(); k++)
{
line.append(columns.get(k).toString());
line.append("|");
}
line.deleteCharAt(line.length()-1);
line.append("\n");
// List<Export> lst = (ArrayList<Export>)daoobj.ViewAllTable(tableName,library_id,sublibrary_id) ;
List<CandidateReg1> lst=dao.VotedVoterListXML(institute_id,election_id);
for (int row = 0; row < lst.size(); row++)
{
CandidateReg1 rowdata=(CandidateReg1)lst.get(row);
line.append(rowdata.getI_institute_name());
line.append("|");
line.append(rowdata.getE_election_name()==null?"NA":rowdata.getE_election_name());
line.append("|");
line.append(rowdata.getV_enrollment()==null?"NA":rowdata.getV_enrollment());
line.append("|");
line.append(rowdata.getV_email()==null?"NA":rowdata.getV_email());
line.append("|");
line.append(rowdata.getV_voter_name()==null?"NA":rowdata.getV_voter_name());
line.append("|");
line.append(rowdata.getStatus()==null?"NA":rowdata.getStatus());
line.append("|");
line.append(rowdata.getV_mobile_number()==null?"NA":rowdata.getV_mobile_number());
line.append("|");
line.append(rowdata.getE_nomistart()==null?"NA":rowdata.getE_nomistart());
line.append("|");
line.append(rowdata.getE_nomiend()==null?"NA":rowdata.getE_nomiend());
line.append("|");
line.append(rowdata.getE_start()==null?"NA":rowdata.getE_start());
line.append("|");
line.append(rowdata.getE_end()==null?"NA":rowdata.getE_end());
line.append("|");
line.append(rowdata.getP_position_name()==null?"NA":rowdata.getP_position_name());
line.append("|");
line.append("\n");
}
//write data in the file
boolean res=UserLog.WriteTextFile(line.toString(), filename);
if(res==false){
request.setAttribute("msg1", "Export in Flat file has error");
}else{
session.setAttribute("type", "text");
request.setAttribute("msgxls", "The Data has been successfully exported and saved");
//session.setAttribute("file", tableName+user_id+".txt");
session.setAttribute("filename", login+".txt");
}
return mapping.findForward("success");
}
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook =
Workbook.createWorkbook(new File(filename), ws);
WritableSheet s = workbook.createSheet("Sheet1", 0);
writeDataSheet1(s, election_id,institute_id);
workbook.write();
workbook.close();
request.setAttribute("msgxls", "The Data has been successfully exported and saved");
session.setAttribute("filename", login+".xls");
// log4j.error("Write:"+filename);
return mapping.findForward("success");
}
catch (IOException e)
{
e.printStackTrace();
//log4j.error(e.getMessage());
request.setAttribute("msg1", "Unable to read Data from Database11"+e);
return mapping.findForward("success");
} }
private void writeDataSheet1(WritableSheet s, String election_id,String institute_id)
throws WriteException
{
ElectionManagerDAO dao=new ElectionManagerDAO();
WritableFont wf = new WritableFont(WritableFont.TIMES,
10, WritableFont.NO_BOLD);
WritableCellFormat cf = new WritableCellFormat(wf);
cf.setWrap(true);
WritableFont wf1 = new WritableFont(WritableFont.ARIAL,
10, WritableFont.BOLD);
WritableCellFormat cf1 = new WritableCellFormat(wf1);
cf.setWrap(true);
Label l;
ArrayList columns=new ArrayList();
columns.add(0, "Institute_Name");
columns.add(1, "Election_Id");
columns.add(2, "Enrollment");
columns.add(3, "Email");
columns.add(4, "VoterName");
columns.add(5, "Status");
columns.add(6, "MobileNo");
columns.add(7, "Nomination Start Date");
columns.add(8, "Nomination End Date");
columns.add(9, "Election Start Date");
columns.add(10, "Election End Date");
columns.add(11, "Position Name");
for (int k = 0; k < columns.size(); k++)
{
l = new Label(k, 0, columns.get(k).toString(), cf1);
s.addCell(l);
System.out.println("this is table columns ::::::::::::::::" + columns.get(k).toString());
}
List<CandidateReg1> lst=dao.VotedVoterListXML(institute_id,election_id);
for (int row = 0; row < lst.size(); row++)
{
CandidateReg1 rowdata = (CandidateReg1) lst.get(row);
l = new Label(0, row +1, String.valueOf(rowdata.getI_institute_name()), cf);
s.addCell(l);
l = new Label(1, row +1, String.valueOf(rowdata.getE_election_name()==null?"NA":rowdata.getE_election_name()), cf);
s.addCell(l);
l = new Label(2, row +1, String.valueOf(rowdata.getV_enrollment()==null?"NA":rowdata.getV_enrollment()), cf);
s.addCell(l);
l = new Label(3, row +1, String.valueOf(rowdata.getV_email()==null?"NA":rowdata.getV_email()), cf);
s.addCell(l);
l = new Label(4, row +1, String.valueOf(rowdata.getV_voter_name()==null?"NA":rowdata.getV_voter_name()), cf);
s.addCell(l);
l = new Label(5, row +1, String.valueOf(rowdata.getStatus()==null?"NA":rowdata.getStatus()), cf);
s.addCell(l);
l = new Label(6, row +1, String.valueOf(rowdata.getV_mobile_number()==null?"NA":rowdata.getV_mobile_number()), cf);
s.addCell(l);
l = new Label(7, row +1, String.valueOf(rowdata.getE_nomistart()==null?"NA":rowdata.getE_nomistart()), cf);
s.addCell(l);
l = new Label(8, row +1, String.valueOf(rowdata.getE_nomiend()==null?"NA":rowdata.getE_nomiend()), cf);
s.addCell(l);
l = new Label(9, row +1, String.valueOf(rowdata.getE_start()==null?"NA":rowdata.getE_start()), cf);
s.addCell(l);
l = new Label(10, row +1, String.valueOf(rowdata.getE_end()==null?"NA":rowdata.getE_end()), cf);
s.addCell(l);
l = new Label(11, row +1, String.valueOf(rowdata.getP_position_name()==null?"NA":rowdata.getP_position_name()), cf);
s.addCell(l);
}
}
}
| 39.625 | 131 | 0.568218 |
1a07203056b2afa7a15dc8b3cc6877bc3ed08fdd | 3,339 | package org.codelogger.utils;
public class PrintUtils {
private PrintUtils() {
}
/****************
* For boolean. *
***************/
public static void print(final boolean[] arg0) {
print(ObjectUtils.toString(arg0));
}
public static void println(final boolean[] arg0) {
print(arg0);
println();
}
/*************
* For byte. *
*************/
public static void print(final byte[] arg0) {
print(ObjectUtils.toString(arg0));
}
public static void println(final byte[] arg0) {
print(arg0);
println();
}
/**************
* For short. *
*************/
public static void print(final short[] arg0) {
print(ObjectUtils.toString(arg0));
}
public static void println(final short[] arg0) {
print(arg0);
println();
}
/*************
* For char. *
*************/
public static void print(final char[] arg0) {
print(ObjectUtils.toString(arg0));
}
public static void println(char[] arg0) {
print(arg0);
println();
}
/************
* For int. *
************/
public static void print(final int[] arg0) {
print(ObjectUtils.toString(arg0));
}
public static void println(final int[] arg0) {
print(arg0);
println();
}
/**************
* For float. *
**************/
public static void print(final float[] arg0) {
print(ObjectUtils.toString(arg0));
}
public static void println(final float[] arg0) {
print(arg0);
println();
}
/*************
* For long. *
*************/
public static void print(final long[] arg0) {
print(ObjectUtils.toString(arg0));
}
public static void println(final long[] arg0) {
print(arg0);
println();
}
/***************
* For double. *
***************/
public static void print(final double[] arg0) {
print(ObjectUtils.toString(arg0));
}
public static void println(final double[] arg0) {
print(arg0);
println();
}
/**************
* for Object *
**************/
public static void print(String format, Object... args) {
Object[] stringArgs = new Object[args.length];
for (int i = 0; i < args.length; i++) {
stringArgs[i] = ObjectUtils.toString(args[i]);
}
print(String.format(format, stringArgs));
}
public static void println(String format, Object... args) {
print(format, args);
println();
}
public static void print(Object[] arg0) {
print(ObjectUtils.toString(arg0));
}
public static void println(Object[] arg0) {
print(arg0);
println();
}
/**********
* format *
**********/
public static void print(Object arg0) {
System.out.print(ObjectUtils.toString(arg0));
}
public static void println(Object arg0) {
System.out.println(arg0);
}
public static void println() {
System.out.println();
}
} | 19.757396 | 64 | 0.467206 |
1068160fb78bd01e827d3b3bbdd2a6f28f1cdae9 | 785 | package com.privatekit.server.filter;
import org.springframework.util.AntPathMatcher;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class CaptchaFilterPathMatcherElement {
public static CaptchaFilterPathMatcherElement from(String pattern, String... methods) {
return new CaptchaFilterPathMatcherElement(pattern, new HashSet<>(Arrays.asList(methods)));
}
private final String pattern;
private final Set<String> methods;
public CaptchaFilterPathMatcherElement(String pattern, Set<String> methods) {
this.pattern = pattern;
this.methods = methods;
}
public boolean match(String path, String method) {
return new AntPathMatcher().match(pattern, path) && methods.contains(method);
}
}
| 29.074074 | 99 | 0.736306 |
3a4e54854b63c5a13ee18a0c129968d5093a7f2b | 337 | package com.gjyl.appserver.service;
import com.gjyl.appserver.pojo.Collect;
import java.util.List;
public interface CollectService {
Boolean collectCycl(Collect collect);
Boolean cancleCollect(String userId, String cyclId);
Boolean isCollected(String userId, String cyclId);
List<Collect> getCollectByUserId(String userId);
}
| 19.823529 | 53 | 0.79822 |
b4326a687674582018005207d0a2d2469cc0f2a3 | 5,961 | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.jasig.ssp.dao.reference;
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 java.util.Collection;
import java.util.List;
import java.util.UUID;
import org.jasig.ssp.model.ObjectStatus;
import org.jasig.ssp.model.Person;
import org.jasig.ssp.model.reference.Challenge;
import org.jasig.ssp.service.ObjectNotFoundException;
import org.jasig.ssp.service.impl.SecurityServiceInTestEnvironment;
import org.jasig.ssp.util.sort.PagingWrapper;
import org.jasig.ssp.util.sort.SortingAndPaging;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("../dao-testConfig.xml")
@TransactionConfiguration(defaultRollback = false)
@Transactional
public class ChallengeDaoTest {
private static final Logger LOGGER = LoggerFactory
.getLogger(ChallengeDaoTest.class);
private static final UUID CONFIDENTIALITYLEVEL_ID = UUID
.fromString("afe3e3e6-87fa-11e1-91b2-0026b9e7ff4c");
private static final String CONFIDENTIALITYLEVEL_NAME = "Test Confidentiality Level";
@Autowired
transient private ChallengeDao dao;
@Autowired
transient private ConfidentialityLevelDao confidentialityLevelDao;
@Autowired
transient private SecurityServiceInTestEnvironment securityService;
@Before
public void setUp() {
securityService.setCurrent(new Person(Person.SYSTEM_ADMINISTRATOR_ID));
}
@Test
public void testSaveNew() throws ObjectNotFoundException {
UUID saved;
Challenge obj = new Challenge();
obj.setName("new name");
obj.setObjectStatus(ObjectStatus.ACTIVE);
obj.setShowInSelfHelpSearch(false);
obj.setShowInStudentIntake(false);
obj.setDefaultConfidentialityLevel(confidentialityLevelDao
.load(CONFIDENTIALITYLEVEL_ID));
dao.save(obj);
assertNotNull("obj.id should not have been null.", obj.getId());
saved = obj.getId();
LOGGER.debug(obj.toString());
obj = dao.get(saved);
assertNotNull("Saved should not have been null.", obj);
assertNotNull("Saved ID should not have been null.", obj.getId());
assertNotNull("Saved name should not have been null.", obj.getName());
assertEquals("Confidentiality level name did not match.",
CONFIDENTIALITYLEVEL_NAME, obj.getDefaultConfidentialityLevel()
.getName());
final Collection<Challenge> all = dao.getAll(ObjectStatus.ACTIVE)
.getRows();
assertFalse("GetAll() list should not be empty.", all.isEmpty());
assertList(all);
dao.delete(obj);
}
@Test(expected = ObjectNotFoundException.class)
public void testNull() throws ObjectNotFoundException {
final UUID id = UUID.randomUUID();
final Challenge challenge = dao.get(id);
assertNull("Challenge should not have been null.", challenge);
}
private void assertList(final Collection<Challenge> objects) {
for (final Challenge object : objects) {
assertNotNull("List item should not have been null.",
object.getId());
}
}
@Test
public void uuidGeneration() {
final Challenge obj = new Challenge();
obj.setName("new name");
obj.setObjectStatus(ObjectStatus.ACTIVE);
dao.save(obj);
final Challenge obj2 = new Challenge();
obj2.setName("new name");
obj2.setObjectStatus(ObjectStatus.ACTIVE);
dao.save(obj2);
assertNotNull("obj1 should not have been null.", obj);
assertNotNull("obj2 should not have been null.", obj);
dao.delete(obj);
dao.delete(obj2);
}
@Test
public void searchByQuery() {
final List<Challenge> challenges = dao.searchByQuery("issue", false);
assertList(challenges);
assertFalse("Search list should have returned some items.",
challenges.isEmpty());
LOGGER.debug(Integer.toString(challenges.size()));
}
@Test
public void getAllInStudentIntake() {
final Collection<Challenge> challenges = dao
.getAllInStudentIntake(
new SortingAndPaging(ObjectStatus.ACTIVE)).getRows();
assertList(challenges);
assertFalse("GetAll() result should not have been empty.",
challenges.isEmpty());
}
@Test
public void selectAffirmativeBySelfHelpGuideResponseId() {
final List<Challenge> challenges = dao
.selectAffirmativeBySelfHelpGuideResponseId(UUID.randomUUID());
assertList(challenges);
}
@Test
public void getAllForCategory() {
final PagingWrapper<Challenge> challenges = dao.getAllForCategory(
UUID.randomUUID(), new SortingAndPaging(ObjectStatus.ACTIVE));
assertList(challenges.getRows());
}
@Test
public void getAllForPerson() {
final PagingWrapper<Challenge> challenges = dao.getAllForPerson(
UUID.fromString("252de4a0-7c06-4254-b7d8-4ffc02fe81ff"),
new SortingAndPaging(ObjectStatus.ACTIVE));
assertList(challenges.getRows());
}
}
| 32.048387 | 86 | 0.768495 |
e3a27d60494411f058c05c676b3b163c34c829b1 | 7,709 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.repository.manager;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.Assert;
import org.junit.Test;
import org.olat.basesecurity.GroupRoles;
import org.olat.core.commons.persistence.DB;
import org.olat.core.commons.services.notifications.NotificationsManager;
import org.olat.core.commons.services.notifications.Publisher;
import org.olat.core.commons.services.notifications.PublisherData;
import org.olat.core.commons.services.notifications.SubscriptionContext;
import org.olat.core.id.Identity;
import org.olat.core.util.mail.MailPackage;
import org.olat.group.BusinessGroup;
import org.olat.group.manager.BusinessGroupDAO;
import org.olat.group.manager.BusinessGroupRelationDAO;
import org.olat.repository.RepositoryEntry;
import org.olat.repository.RepositoryManager;
import org.olat.test.JunitTestHelper;
import org.olat.test.OlatTestCase;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* Initial date: 10.02.2015<br>
* @author srosse, [email protected], http://www.frentix.com
*
*/
public class RepositoryEntryMembershipProcessorTest extends OlatTestCase {
@Autowired
private DB dbInstance;
@Autowired
private BusinessGroupDAO businessGroupDao;
@Autowired
private NotificationsManager notificationManager;
@Autowired
private BusinessGroupRelationDAO businessGroupRelationDao;
@Autowired
private RepositoryManager repositoryManager;
@Autowired
private RepositoryEntryRelationDAO repositoryEntryRelationDao;
@Test
public void testRemoveParticipant() {
RepositoryEntry re = JunitTestHelper.createAndPersistRepositoryEntry();
//create a group with members
Identity owner = JunitTestHelper.createAndPersistIdentityAsRndUser("remp-proc-1");
Identity member = JunitTestHelper.createAndPersistIdentityAsRndUser("remp-proc-2");
Identity participant = JunitTestHelper.createAndPersistIdentityAsRndUser("mbr-proc-3");
repositoryEntryRelationDao.addRole(owner, re, GroupRoles.owner.name());
repositoryEntryRelationDao.addRole(member, re, GroupRoles.coach.name());
repositoryEntryRelationDao.addRole(member, re, GroupRoles.participant.name());
repositoryEntryRelationDao.addRole(participant, re, GroupRoles.participant.name());
//create a publisher
SubscriptionContext context = new SubscriptionContext(re.getOlatResource(), "");
PublisherData publisherData = new PublisherData("testGroupPublishers", "e.g. something", null);
Publisher publisher = notificationManager.getOrCreatePublisher(context, publisherData);
Assert.assertNotNull(publisher);
dbInstance.commitAndCloseSession();
//subscribe
notificationManager.subscribe(owner, context, publisherData);
notificationManager.subscribe(member, context, publisherData);
notificationManager.subscribe(participant, context, publisherData);
dbInstance.commitAndCloseSession();
//remove member and participant as participant of the repo entry
List<Identity> removeIdentities = new ArrayList<>(2);
removeIdentities.add(member);
removeIdentities.add(participant);
MailPackage mailing = new MailPackage(false);
repositoryManager.removeParticipants(owner, removeIdentities, re, mailing, false);
//wait for the remove of subscription
waitForCondition(new CheckUnsubscription(participant, context, dbInstance, notificationManager), 5000);
sleep(1000);
//check that subscription of id1 was deleted but not the ones of id2 and coach
boolean subscribedPart = notificationManager.isSubscribed(participant, context);
Assert.assertFalse(subscribedPart);
boolean subscribedMember = notificationManager.isSubscribed(member, context);
Assert.assertTrue(subscribedMember);
boolean subscribedOwner = notificationManager.isSubscribed(owner, context);
Assert.assertTrue(subscribedOwner);
}
@Test
public void testRemoveCoach_withBusinessGroups() {
RepositoryEntry re = JunitTestHelper.createAndPersistRepositoryEntry();
//create a group with members
Identity owner = JunitTestHelper.createAndPersistIdentityAsRndUser("remp-proc-1");
Identity member = JunitTestHelper.createAndPersistIdentityAsRndUser("remp-proc-2");
Identity coach = JunitTestHelper.createAndPersistIdentityAsRndUser("mbr-proc-3");
repositoryEntryRelationDao.addRole(owner, re, GroupRoles.owner.name());
repositoryEntryRelationDao.addRole(member, re, GroupRoles.coach.name());
repositoryEntryRelationDao.addRole(coach, re, GroupRoles.coach.name());
BusinessGroup businessGroup = businessGroupDao.createAndPersist(coach, "mbr-proc-1", "mbr-proc-desc", BusinessGroup.BUSINESS_TYPE,
-1, -1, false, false, false, false, false);
businessGroupRelationDao.addRelationToResource(businessGroup, re);
//create a publisher
SubscriptionContext context = new SubscriptionContext(re.getOlatResource(), "");
PublisherData publisherData = new PublisherData("testGroupPublishers", "e.g. something", null);
Publisher publisher = notificationManager.getOrCreatePublisher(context, publisherData);
Assert.assertNotNull(publisher);
dbInstance.commitAndCloseSession();
//subscribe
notificationManager.subscribe(owner, context, publisherData);
notificationManager.subscribe(member, context, publisherData);
notificationManager.subscribe(coach, context, publisherData);
dbInstance.commitAndCloseSession();
//remove member and coach as coach of the repo entry
List<Identity> removeIdentities = new ArrayList<>(2);
removeIdentities.add(member);
removeIdentities.add(coach);
repositoryManager.removeTutors(owner, removeIdentities, re, new MailPackage(false));
//wait for the remove of subscription
waitForCondition(new CheckUnsubscription(member, context, dbInstance, notificationManager), 5000);
sleep(1000);
//check that subscription of id1 was deleted but not the ones of id2 and coach
boolean subscribedMember = notificationManager.isSubscribed(member, context);
Assert.assertFalse(subscribedMember);
boolean subscribedCoach = notificationManager.isSubscribed(coach, context);
Assert.assertTrue(subscribedCoach);
boolean subscribedOwner = notificationManager.isSubscribed(owner, context);
Assert.assertTrue(subscribedOwner);
}
private static class CheckUnsubscription implements Callable<Boolean> {
private final DB db;
private final NotificationsManager notificationMgr;
private final Identity identity;
private final SubscriptionContext context;
public CheckUnsubscription(Identity identity, SubscriptionContext context, DB db, NotificationsManager notificationMgr) {
this.identity = identity;
this.context = context;
this.db = db;
this.notificationMgr = notificationMgr;
}
@Override
public Boolean call() throws Exception {
boolean subscribed = notificationMgr.isSubscribed(identity, context);
db.commitAndCloseSession();
return !subscribed;
}
}
}
| 41.67027 | 132 | 0.792191 |
3bf950b688afb0eaf7458d382827b7a1bbd71024 | 15,118 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|security
operator|.
name|authorization
operator|.
name|restriction
package|;
end_package
begin_import
import|import static
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|security
operator|.
name|RegistrationConstants
operator|.
name|OAK_SECURITY_NAME
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Set
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|security
operator|.
name|AccessControlException
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|collect
operator|.
name|ImmutableMap
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|api
operator|.
name|PropertyState
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|api
operator|.
name|Tree
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|api
operator|.
name|Type
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|security
operator|.
name|authorization
operator|.
name|restriction
operator|.
name|AbstractRestrictionProvider
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|security
operator|.
name|authorization
operator|.
name|restriction
operator|.
name|CompositePattern
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|security
operator|.
name|authorization
operator|.
name|restriction
operator|.
name|Restriction
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|security
operator|.
name|authorization
operator|.
name|restriction
operator|.
name|RestrictionDefinition
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|security
operator|.
name|authorization
operator|.
name|restriction
operator|.
name|RestrictionDefinitionImpl
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|security
operator|.
name|authorization
operator|.
name|restriction
operator|.
name|RestrictionPattern
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|security
operator|.
name|authorization
operator|.
name|restriction
operator|.
name|RestrictionProvider
import|;
end_import
begin_import
import|import
name|org
operator|.
name|jetbrains
operator|.
name|annotations
operator|.
name|NotNull
import|;
end_import
begin_import
import|import
name|org
operator|.
name|jetbrains
operator|.
name|annotations
operator|.
name|Nullable
import|;
end_import
begin_import
import|import
name|org
operator|.
name|osgi
operator|.
name|service
operator|.
name|component
operator|.
name|annotations
operator|.
name|Component
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_comment
comment|/** * Default restriction provider implementation that supports the following * restrictions: * *<ul> *<li>{@link #REP_GLOB}: A simple paths matching pattern. See {@link GlobPattern} * for details.</li> *<li>{@link #REP_NT_NAMES}: A restriction that allows to limit the effect * of a given access control entries to JCR nodes of any of the specified * primary node type. In case of a JCR property the primary type of the * parent node is taken into consideration when evaluating the permissions.</li> *<li>{@link #REP_PREFIXES}: A multivalued access control restriction * which matches by name space prefix. The corresponding restriction type * is {@link org.apache.jackrabbit.oak.api.Type#STRINGS}.</li> *</ul> */
end_comment
begin_class
annotation|@
name|Component
argument_list|(
name|service
operator|=
name|RestrictionProvider
operator|.
name|class
argument_list|,
name|property
operator|=
name|OAK_SECURITY_NAME
operator|+
literal|"=org.apache.jackrabbit.oak.security.authorization.restriction.RestrictionProviderImpl"
argument_list|)
specifier|public
class|class
name|RestrictionProviderImpl
extends|extends
name|AbstractRestrictionProvider
block|{
specifier|private
specifier|static
specifier|final
name|Logger
name|log
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|RestrictionProviderImpl
operator|.
name|class
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|int
name|NUMBER_OF_DEFINITIONS
init|=
literal|3
decl_stmt|;
specifier|public
name|RestrictionProviderImpl
parameter_list|()
block|{
name|super
argument_list|(
name|supportedRestrictions
argument_list|()
argument_list|)
expr_stmt|;
block|}
specifier|private
specifier|static
name|Map
argument_list|<
name|String
argument_list|,
name|RestrictionDefinition
argument_list|>
name|supportedRestrictions
parameter_list|()
block|{
name|RestrictionDefinition
name|glob
init|=
operator|new
name|RestrictionDefinitionImpl
argument_list|(
name|REP_GLOB
argument_list|,
name|Type
operator|.
name|STRING
argument_list|,
literal|false
argument_list|)
decl_stmt|;
name|RestrictionDefinition
name|nts
init|=
operator|new
name|RestrictionDefinitionImpl
argument_list|(
name|REP_NT_NAMES
argument_list|,
name|Type
operator|.
name|NAMES
argument_list|,
literal|false
argument_list|)
decl_stmt|;
name|RestrictionDefinition
name|pfxs
init|=
operator|new
name|RestrictionDefinitionImpl
argument_list|(
name|REP_PREFIXES
argument_list|,
name|Type
operator|.
name|STRINGS
argument_list|,
literal|false
argument_list|)
decl_stmt|;
name|RestrictionDefinition
name|names
init|=
operator|new
name|RestrictionDefinitionImpl
argument_list|(
name|REP_ITEM_NAMES
argument_list|,
name|Type
operator|.
name|NAMES
argument_list|,
literal|false
argument_list|)
decl_stmt|;
return|return
name|ImmutableMap
operator|.
name|of
argument_list|(
name|glob
operator|.
name|getName
argument_list|()
argument_list|,
name|glob
argument_list|,
name|nts
operator|.
name|getName
argument_list|()
argument_list|,
name|nts
argument_list|,
name|pfxs
operator|.
name|getName
argument_list|()
argument_list|,
name|pfxs
argument_list|,
name|names
operator|.
name|getName
argument_list|()
argument_list|,
name|names
argument_list|)
return|;
block|}
comment|//------------------------------------------------< RestrictionProvider>---
annotation|@
name|NotNull
annotation|@
name|Override
specifier|public
name|RestrictionPattern
name|getPattern
parameter_list|(
name|String
name|oakPath
parameter_list|,
annotation|@
name|NotNull
name|Tree
name|tree
parameter_list|)
block|{
if|if
condition|(
name|oakPath
operator|==
literal|null
condition|)
block|{
return|return
name|RestrictionPattern
operator|.
name|EMPTY
return|;
block|}
else|else
block|{
name|List
argument_list|<
name|RestrictionPattern
argument_list|>
name|patterns
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|(
name|NUMBER_OF_DEFINITIONS
argument_list|)
decl_stmt|;
name|PropertyState
name|glob
init|=
name|tree
operator|.
name|getProperty
argument_list|(
name|REP_GLOB
argument_list|)
decl_stmt|;
if|if
condition|(
name|glob
operator|!=
literal|null
condition|)
block|{
name|patterns
operator|.
name|add
argument_list|(
name|GlobPattern
operator|.
name|create
argument_list|(
name|oakPath
argument_list|,
name|glob
operator|.
name|getValue
argument_list|(
name|Type
operator|.
name|STRING
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|PropertyState
name|ntNames
init|=
name|tree
operator|.
name|getProperty
argument_list|(
name|REP_NT_NAMES
argument_list|)
decl_stmt|;
if|if
condition|(
name|ntNames
operator|!=
literal|null
condition|)
block|{
name|patterns
operator|.
name|add
argument_list|(
operator|new
name|NodeTypePattern
argument_list|(
name|ntNames
operator|.
name|getValue
argument_list|(
name|Type
operator|.
name|NAMES
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|PropertyState
name|prefixes
init|=
name|tree
operator|.
name|getProperty
argument_list|(
name|REP_PREFIXES
argument_list|)
decl_stmt|;
if|if
condition|(
name|prefixes
operator|!=
literal|null
condition|)
block|{
name|patterns
operator|.
name|add
argument_list|(
operator|new
name|PrefixPattern
argument_list|(
name|prefixes
operator|.
name|getValue
argument_list|(
name|Type
operator|.
name|STRINGS
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|PropertyState
name|itemNames
init|=
name|tree
operator|.
name|getProperty
argument_list|(
name|REP_ITEM_NAMES
argument_list|)
decl_stmt|;
if|if
condition|(
name|itemNames
operator|!=
literal|null
condition|)
block|{
name|patterns
operator|.
name|add
argument_list|(
operator|new
name|ItemNamePattern
argument_list|(
name|itemNames
operator|.
name|getValue
argument_list|(
name|Type
operator|.
name|NAMES
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
return|return
name|CompositePattern
operator|.
name|create
argument_list|(
name|patterns
argument_list|)
return|;
block|}
block|}
annotation|@
name|NotNull
annotation|@
name|Override
specifier|public
name|RestrictionPattern
name|getPattern
parameter_list|(
annotation|@
name|Nullable
name|String
name|oakPath
parameter_list|,
annotation|@
name|NotNull
name|Set
argument_list|<
name|Restriction
argument_list|>
name|restrictions
parameter_list|)
block|{
if|if
condition|(
name|oakPath
operator|==
literal|null
operator|||
name|restrictions
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
return|return
name|RestrictionPattern
operator|.
name|EMPTY
return|;
block|}
else|else
block|{
name|List
argument_list|<
name|RestrictionPattern
argument_list|>
name|patterns
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|(
name|NUMBER_OF_DEFINITIONS
argument_list|)
decl_stmt|;
for|for
control|(
name|Restriction
name|r
range|:
name|restrictions
control|)
block|{
name|String
name|name
init|=
name|r
operator|.
name|getDefinition
argument_list|()
operator|.
name|getName
argument_list|()
decl_stmt|;
if|if
condition|(
name|REP_GLOB
operator|.
name|equals
argument_list|(
name|name
argument_list|)
condition|)
block|{
name|patterns
operator|.
name|add
argument_list|(
name|GlobPattern
operator|.
name|create
argument_list|(
name|oakPath
argument_list|,
name|r
operator|.
name|getProperty
argument_list|()
operator|.
name|getValue
argument_list|(
name|Type
operator|.
name|STRING
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
elseif|else
if|if
condition|(
name|REP_NT_NAMES
operator|.
name|equals
argument_list|(
name|name
argument_list|)
condition|)
block|{
name|patterns
operator|.
name|add
argument_list|(
operator|new
name|NodeTypePattern
argument_list|(
name|r
operator|.
name|getProperty
argument_list|()
operator|.
name|getValue
argument_list|(
name|Type
operator|.
name|NAMES
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
elseif|else
if|if
condition|(
name|REP_PREFIXES
operator|.
name|equals
argument_list|(
name|name
argument_list|)
condition|)
block|{
name|patterns
operator|.
name|add
argument_list|(
operator|new
name|PrefixPattern
argument_list|(
name|r
operator|.
name|getProperty
argument_list|()
operator|.
name|getValue
argument_list|(
name|Type
operator|.
name|STRINGS
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
elseif|else
if|if
condition|(
name|REP_ITEM_NAMES
operator|.
name|equals
argument_list|(
name|name
argument_list|)
condition|)
block|{
name|patterns
operator|.
name|add
argument_list|(
operator|new
name|ItemNamePattern
argument_list|(
name|r
operator|.
name|getProperty
argument_list|()
operator|.
name|getValue
argument_list|(
name|Type
operator|.
name|NAMES
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|log
operator|.
name|debug
argument_list|(
literal|"Ignoring unsupported restriction {}"
argument_list|,
name|name
argument_list|)
expr_stmt|;
block|}
block|}
return|return
name|CompositePattern
operator|.
name|create
argument_list|(
name|patterns
argument_list|)
return|;
block|}
block|}
annotation|@
name|Override
specifier|public
name|void
name|validateRestrictions
parameter_list|(
name|String
name|oakPath
parameter_list|,
annotation|@
name|NotNull
name|Tree
name|aceTree
parameter_list|)
throws|throws
name|AccessControlException
block|{
name|super
operator|.
name|validateRestrictions
argument_list|(
name|oakPath
argument_list|,
name|aceTree
argument_list|)
expr_stmt|;
name|Tree
name|restrictionsTree
init|=
name|getRestrictionsTree
argument_list|(
name|aceTree
argument_list|)
decl_stmt|;
name|PropertyState
name|glob
init|=
name|restrictionsTree
operator|.
name|getProperty
argument_list|(
name|REP_GLOB
argument_list|)
decl_stmt|;
if|if
condition|(
name|glob
operator|!=
literal|null
condition|)
block|{
name|GlobPattern
operator|.
name|validate
argument_list|(
name|glob
operator|.
name|getValue
argument_list|(
name|Type
operator|.
name|STRING
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
| 14.480843 | 810 | 0.800833 |
963a6a676083a5a1c3b15f982215d0bce11e11df | 89 | package com.mark.design.chain_of_responsibility;
public class Level {
// 定义一个请求和处理等级
}
| 14.833333 | 48 | 0.786517 |
5e8723ab01d84429fab14b78dbfe85b7dc3e3197 | 1,090 | package com.vitreoussoftware.bioinformatics.sequence;
import lombok.val;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.nullValue;
/**
* Created by John on 12/4/2016.
*/
public class InvalidDnaFormatExceptionTest {
@Test
public void testErrorMessage() {
val exception = new InvalidDnaFormatException("foo");
assertThat(exception.getMessage(), is("foo"));
assertThat(exception.getCause(), is(nullValue()));
}
@Test
public void testErrorMessageWithCause() {
val exception = new InvalidDnaFormatException("foo", null);
assertThat(exception.getMessage(), is("foo"));
assertThat(exception.getCause(), is(nullValue()));
}
@Test
public void testGetCause() {
val cause = new InvalidDnaFormatException("bar");
val exception = new InvalidDnaFormatException("foo", cause);
assertThat(exception.getMessage(), is("foo"));
assertThat(exception.getCause(), is(cause));
}
} | 28.684211 | 68 | 0.684404 |
806e0a8c1f879c4dbf65c6211d648e9316bc16fa | 2,576 | package com.citelic.game.entity.npc.impl.others;
import com.citelic.game.engine.Engine;
import com.citelic.game.engine.task.EngineTask;
import com.citelic.game.engine.task.EngineTaskManager;
import com.citelic.game.entity.Animation;
import com.citelic.game.entity.Entity;
import com.citelic.game.entity.npc.NPC;
import com.citelic.game.entity.npc.combat.NPCCombatDefinitions;
import com.citelic.game.entity.player.Player;
import com.citelic.game.entity.player.content.controllers.impl.distractions.WarriorsGuild;
import com.citelic.game.entity.player.item.Item;
import com.citelic.game.map.tile.Tile;
import com.citelic.utility.Utilities;
@SuppressWarnings("serial")
public class AnimatedArmor extends NPC {
private transient Player player;
public AnimatedArmor(Player player, int id, Tile tile, int mapAreaNameHash,
boolean canBeAttackFromOutOfArea) {
super(id, tile, mapAreaNameHash, canBeAttackFromOutOfArea);
this.player = player;
}
@Override
public void processNPC() {
super.processNPC();
if (!getCombat().underCombat())
finish();
}
@Override
public void sendDeath(final Entity source) {
final NPCCombatDefinitions defs = getCombatDefinitions();
resetWalkSteps();
getCombat().removeTarget();
setNextAnimation(null);
EngineTaskManager.schedule(new EngineTask() {
int loop;
@Override
public void run() {
if (loop == 0) {
setNextAnimation(new Animation(defs.getDeathEmote()));
} else if (loop >= defs.getDeathDelay()) {
if (source instanceof Player) {
Player player = (Player) source;
for (Integer items : getDroppedItems()) {
if (items == -1)
continue;
Engine.addGroundItem(new Item(items), new Tile(
getCoordFaceX(getSize()),
getCoordFaceY(getSize()), getZ()), player,
true, 60, true);
}
player.setWarriorPoints(3,
WarriorsGuild.ARMOR_POINTS[getId() - 4278]);
}
finish();
stop();
}
loop++;
}
}, 0, 1);
}
public int[] getDroppedItems() {
int index = getId() - 4278;
int[] droppedItems = WarriorsGuild.ARMOUR_SETS[index];
if (Utilities.getRandom(15) == 0) // 1/15 chance of losing
droppedItems[Utilities.random(0, 2)] = -1;
return droppedItems;
}
@Override
public void finish() {
if (hasFinished())
return;
super.finish();
if (player != null) {
player.getTemporaryAttributtes().remove("animator_spawned");
if (!isDead()) {
for (int item : getDroppedItems()) {
if (item == -1)
continue;
player.getInventory().addItem(item, 1);
}
}
}
}
}
| 27.404255 | 90 | 0.688276 |
2980b624e00702c000499c48c39be4c4880e0c20 | 1,367 | package com.vann.kanxue.api;
import android.content.Context;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONObject;
/**
* @Author: wenlong.bian 2016-01-04
* @E-mail: [email protected]
*/
public abstract class VolleyInterface {
public Context mContext;
public static Response.Listener mListener;
public static Response.ErrorListener mErrorListener;
public abstract void success(JSONObject result);
public abstract void error(VolleyError volleyError);
public VolleyInterface(Context context, Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
this.mContext = context;
this.mListener = listener;
this.mErrorListener = errorListener;
}
public Response.Listener<JSONObject> loadListener(){
mListener = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject o) {
success(o);
}
};
return mListener;
}
public Response.ErrorListener errorListener(){
mErrorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
error(volleyError);
}
};
return mErrorListener;
}
}
| 27.34 | 83 | 0.651061 |
bc6413c55393d486cf9a820575237a0ab9606fc6 | 1,847 | package xyz.rexlin600.jaxb.util;
import lombok.SneakyThrows;
import org.junit.Test;
import xyz.rexlin600.jaxb.entity.dynamic.simple.Biscuit;
import xyz.rexlin600.jaxb.entity.dynamic.simple.Cake;
import xyz.rexlin600.jaxb.entity.dynamic.simple.Order;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.util.Arrays;
public class JaxbUtilDynamicTest {
private final static Order ORDER = new Order(1L, "产品1", Arrays.asList(
new Cake("蛋糕"),
new Biscuit("饼干")
));
private final static String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<PRODUCT>\n" +
" <ID>1</ID>\n" +
" <NAME>产品1</NAME>\n" +
" <PRODUCT>\n" +
" <CAKE>\n" +
" <NAME>蛋糕</NAME>\n" +
" </CAKE>\n" +
" <BISCUIT>\n" +
" <NAME>饼干</NAME>\n" +
" </BISCUIT>\n" +
" </PRODUCT>\n" +
"</PRODUCT>";
@SneakyThrows
@Test
public void java2Xml() {
JAXBContext jaxbContext = JAXBContext.newInstance(Order.class, Cake.class, Biscuit.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(ORDER, System.out);
}
@SneakyThrows
@Test
public void xml2Java() {
JAXBContext jaxbContext = JAXBContext.newInstance(Order.class, Cake.class, Biscuit.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader stringReader = new StringReader(xml);
Order result = (Order) unmarshaller.unmarshal(new StreamSource(stringReader));
stringReader.close();
// 注意:这里的特定对象转 Object 为 null
System.out.println(result.toString());
}
} | 31.305085 | 105 | 0.663238 |
51e9958473d634bf9c71e19640dee118e8b7fce9 | 5,487 | package org.activiti.cloud.services.audit.mongo.events;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.querydsl.core.annotations.QueryEntity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "eventType",
visible = true,
defaultImpl = IgnoredProcessEngineEvent.class)
@JsonSubTypes({
@JsonSubTypes.Type(value = ActivityStartedEventDocument.class, name = ActivityStartedEventDocument.ACTIVITY_STARTED_EVENT),
@JsonSubTypes.Type(value = ActivityCompletedEventDocument.class, name = ActivityCompletedEventDocument.ACTIVITY_COMPLETED_EVENT),
@JsonSubTypes.Type(value = ActivityCancelledEventDocument.class, name = ActivityCancelledEventDocument.ACTIVITY_CANCELLED_EVENT),
@JsonSubTypes.Type(value = ProcessStartedEventDocument.class, name = ProcessStartedEventDocument.PROCESS_STARTED_EVENT),
@JsonSubTypes.Type(value = ProcessCompletedEventDocument.class, name = ProcessCompletedEventDocument.PROCESS_COMPLETED_EVENT),
@JsonSubTypes.Type(value = ProcessCancelledEventDocument.class, name = ProcessCancelledEventDocument.PROCESS_CANCELLED_EVENT),
@JsonSubTypes.Type(value = TaskCreatedEventDocument.class, name = TaskCreatedEventDocument.TASK_CREATED_EVENT),
@JsonSubTypes.Type(value = TaskAssignedEventDocument.class, name = TaskAssignedEventDocument.TASK_ASSIGNED_EVENT),
@JsonSubTypes.Type(value = TaskCompletedEventDocument.class, name = TaskCompletedEventDocument.TASK_COMPLETED_EVENT),
@JsonSubTypes.Type(value = VariableCreatedEventDocument.class, name = VariableCreatedEventDocument.VARIABLE_CREATED_EVENT),
@JsonSubTypes.Type(value = VariableUpdatedEventDocument.class, name = VariableUpdatedEventDocument.VARIABLE_UPDATED_EVENT),
@JsonSubTypes.Type(value = VariableDeletedEventDocument.class, name = VariableDeletedEventDocument.VARIABLE_DELETED_EVENT),
@JsonSubTypes.Type(value = SequenceFlowTakenEventDocument.class, name = SequenceFlowTakenEventDocument.SEQUENCE_FLOW_TAKEN_EVENT),
@JsonSubTypes.Type(value = IntegrationRequestSentEventDocument.class, name = IntegrationRequestSentEventDocument.INTEGRATION_REQUEST_SENT_EVENT),
@JsonSubTypes.Type(value = IntegrationResultReceivedEventDocument.class, name = IntegrationResultReceivedEventDocument.INTEGRATION_RESULT_RECEIVED_EVENT)
})
@QueryEntity
@Document(collection = "act_evt_log")
public class ProcessEngineEventDocument {
@Id
private String id;
private Long timestamp;
private String eventType;
private String executionId;
private String processDefinitionId;
private String processInstanceId;
private String appName;
private String appVersion;
private String serviceName;
private String serviceFullName;
private String serviceType;
private String serviceVersion;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppVersion() {
return appVersion;
}
public void setAppVersion(String appVersion) {
this.appVersion = appVersion;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getServiceFullName() {
return serviceFullName;
}
public void setServiceFullName(String serviceFullName) {
this.serviceFullName = serviceFullName;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public String getServiceVersion() {
return serviceVersion;
}
public void setServiceVersion(String serviceVersion) {
this.serviceVersion = serviceVersion;
}
@JsonIgnore
public boolean isIgnored() {
return false;
}
}
| 34.949045 | 161 | 0.740477 |
d2195e1633b207d059415a239760b8aa5c209209 | 4,214 | package focusedCrawler.target;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import focusedCrawler.target.repository.ElasticSearchRestTargetRepository;
import focusedCrawler.target.repository.FileSystemTargetRepository;
import focusedCrawler.target.repository.FilesTargetRepository;
import focusedCrawler.target.repository.MultipleTargetRepositories;
import focusedCrawler.target.repository.RocksDBTargetRepository;
import focusedCrawler.target.repository.TargetRepository;
import focusedCrawler.target.repository.WarcTargetRepository;
import focusedCrawler.target.repository.FileSystemTargetRepository.DataFormat;
import focusedCrawler.target.repository.elasticsearch.ElasticSearchConfig;
import focusedCrawler.target.repository.kafka.KafkaTargetRepository;
public class TargetRepositoryFactory {
public static final Logger logger = LoggerFactory.getLogger(TargetRepositoryFactory.class);
public static TargetRepository create(String dataPath, String esIndexName,
String esTypeName, TargetStorageConfig config) throws IOException {
List<String> dataFormats = config.getDataFormats();
List<TargetRepository> repositories = new ArrayList<>();
for (String dataFormat : dataFormats) {
TargetRepository targetRepository =
createRepository(dataFormat, dataPath, esIndexName, esTypeName, config);
repositories.add(targetRepository);
}
TargetRepository targetRepository = null;
if (repositories.size() == 1) {
targetRepository = repositories.get(0);
} else if (repositories.size() > 1) {
// create pool of repositories
targetRepository = new MultipleTargetRepositories(repositories);
} else {
throw new IllegalArgumentException("No valid data formats configured.");
}
return targetRepository;
}
private static TargetRepository createRepository(String dataFormat, String dataPath,
String esIndexName, String esTypeName, TargetStorageConfig config) throws IOException {
Path targetDirectory = Paths.get(dataPath, config.getTargetStorageDirectory());
boolean compressData = config.getCompressData();
boolean hashFilename = config.getHashFileName();
logger.info("Loading repository with data_format={} from {}",
dataFormat, targetDirectory.toString());
switch (dataFormat) {
case "ROCKSDB":
return new RocksDBTargetRepository(targetDirectory);
case "FILES":
return new FilesTargetRepository(targetDirectory, config.getMaxFileSize());
case "FILESYSTEM_JSON":
return new FileSystemTargetRepository(targetDirectory, DataFormat.JSON,
hashFilename, compressData);
case "FILESYSTEM_CBOR":
return new FileSystemTargetRepository(targetDirectory, DataFormat.CBOR,
hashFilename, compressData);
case "FILESYSTEM_HTML":
return new FileSystemTargetRepository(targetDirectory, DataFormat.HTML,
hashFilename, compressData);
case "WARC":
return new WarcTargetRepository(targetDirectory, config.getWarcMaxFileSize(),
config.getCompressWarc());
case "KAFKA":
return new KafkaTargetRepository(config.getKafkaConfig());
case "ELASTICSEARCH":
ElasticSearchConfig esconfig = config.getElasticSearchConfig();
if (esIndexName != null && !esIndexName.isEmpty()) {
esconfig.setIndexName(esIndexName);
}
if (esTypeName != null && !esTypeName.isEmpty()) {
esconfig.setTypeName(esTypeName);
}
return new ElasticSearchRestTargetRepository(esconfig);
default:
throw new IllegalArgumentException("Invalid data format provided: " + dataFormat);
}
}
}
| 44.357895 | 99 | 0.682487 |
aa16d36a61df43de8ecbff808c71853f1b606f0c | 469 | package org.proteored.miapeapi.exceptions;
public class MiapeSecurityException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public MiapeSecurityException() {
super();
}
public MiapeSecurityException(String message, Throwable throwable) {
super(message, throwable);
}
public MiapeSecurityException(String message) {
super(message);
}
public MiapeSecurityException(Throwable throwable) {
super(throwable);
}
}
| 18.76 | 69 | 0.750533 |
e1d3d2deb1856a0c359724f146b1ecc1b8a3bb6c | 1,175 | package org.xman.trainings.dates;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateFormatTest {
private static final String GMT_PATTERN_X = "yyyy-MM-dd'T'HH:mm:ssXXX";
private static final String GMT_PATTERN_Z = "yyyy-MM-dd'T'HH:mm:ssZ";
private static final String T_PM_PATTERN = "HH:mm:ss aaa";
@Test
public void testGmtPatternX() {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(GMT_PATTERN_X);
// 加上时区校正
// sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(now));
// 输出示例:2016-08-01T12:44:12+08:00
}
@Test
public void testGmtPatternZ() {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(GMT_PATTERN_Z);
System.out.println(sdf.format(now));
// 输出示例:2016-08-01T12:46:45+0800
}
@Test
public void testPmDate() {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(T_PM_PATTERN, Locale.US);
System.out.println(sdf.format(now));
// 输出示例:12:56:05 PM
}
}
| 26.111111 | 77 | 0.646809 |
9ab1212cfee91b2e50e5d8ab23af650011a1a4c3 | 3,952 | /*
* 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 opennlp.tools.ml.model;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.zip.GZIPOutputStream;
import opennlp.tools.ml.maxent.io.BinaryGISModelWriter;
import opennlp.tools.ml.maxent.io.BinaryQNModelWriter;
import opennlp.tools.ml.maxent.io.PlainTextGISModelWriter;
import opennlp.tools.ml.model.AbstractModel.ModelType;
import opennlp.tools.ml.naivebayes.BinaryNaiveBayesModelWriter;
import opennlp.tools.ml.naivebayes.PlainTextNaiveBayesModelWriter;
import opennlp.tools.ml.perceptron.BinaryPerceptronModelWriter;
import opennlp.tools.ml.perceptron.PlainTextPerceptronModelWriter;
public class GenericModelWriter extends AbstractModelWriter {
private AbstractModelWriter delegateWriter;
public GenericModelWriter(AbstractModel model, File file) throws IOException {
String filename = file.getName();
OutputStream os;
// handle the zipped/not zipped distinction
if (filename.endsWith(".gz")) {
os = new GZIPOutputStream(new FileOutputStream(file));
filename = filename.substring(0, filename.length() - 3);
} else {
os = new FileOutputStream(file);
}
// handle the different formats
if (filename.endsWith(".bin")) {
init(model, new DataOutputStream(os));
} else { // filename ends with ".txt"
init(model, new BufferedWriter(new OutputStreamWriter(os)));
}
}
public GenericModelWriter(AbstractModel model, DataOutputStream dos) {
init(model, dos);
}
private void init(AbstractModel model, DataOutputStream dos) {
if (model.getModelType() == ModelType.Perceptron) {
delegateWriter = new BinaryPerceptronModelWriter(model, dos);
} else if (model.getModelType() == ModelType.Maxent) {
delegateWriter = new BinaryGISModelWriter(model, dos);
} else if (model.getModelType() == ModelType.MaxentQn) {
delegateWriter = new BinaryQNModelWriter(model, dos);
}
if (model.getModelType() == ModelType.NaiveBayes) {
delegateWriter = new BinaryNaiveBayesModelWriter(model, dos);
}
}
private void init(AbstractModel model, BufferedWriter bw) {
if (model.getModelType() == ModelType.Perceptron) {
delegateWriter = new PlainTextPerceptronModelWriter(model, bw);
} else if (model.getModelType() == ModelType.Maxent) {
delegateWriter = new PlainTextGISModelWriter(model, bw);
}
if (model.getModelType() == ModelType.NaiveBayes) {
delegateWriter = new PlainTextNaiveBayesModelWriter(model, bw);
}
}
@Override
public void close() throws IOException {
delegateWriter.close();
}
@Override
public void persist() throws IOException {
delegateWriter.persist();
}
@Override
public void writeDouble(double d) throws IOException {
delegateWriter.writeDouble(d);
}
@Override
public void writeInt(int i) throws IOException {
delegateWriter.writeInt(i);
}
@Override
public void writeUTF(String s) throws IOException {
delegateWriter.writeUTF(s);
}
} | 34.365217 | 80 | 0.738866 |
1a8b75296aa22b04c96a0d021811e47e67123875 | 1,264 | // Generated source.
// Generator: org.chromium.sdk.internal.wip.tools.protocolgenerator.Generator
// Origin: http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/inspector/Inspector.json@96703
package org.chromium.sdk.internal.wip.protocol.output.dom;
/**
Enters the 'inspect' mode. In this mode, elements that user is hovering over are highlighted. Backend then generates 'inspect' command upon element selection.
*/
public class SetInspectModeEnabledParams extends org.chromium.sdk.internal.wip.protocol.output.WipParams {
/**
@param enabled True to enable inspection mode, false to disable it.
@param highlightConfigOpt A descriptor for the highlight appearance of hovered-over nodes. May be omitted if <code>enabled == false</code>.
*/
public SetInspectModeEnabledParams(boolean enabled, org.chromium.sdk.internal.wip.protocol.output.dom.HighlightConfigParam highlightConfigOpt) {
this.put("enabled", enabled);
if (highlightConfigOpt != null) {
this.put("highlightConfig", highlightConfigOpt);
}
}
public static final String METHOD_NAME = org.chromium.sdk.internal.wip.protocol.BasicConstants.Domain.DOM + ".setInspectModeEnabled";
@Override protected String getRequestName() {
return METHOD_NAME;
}
}
| 43.586207 | 158 | 0.771361 |
a5d32e2093de5e61cf8ba79ddb53018588aa582e | 583 | package com.es.agriculturafamiliar.dto.response;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
@AllArgsConstructor
@NoArgsConstructor
@Data
public class CadastroConsumidorResponse {
private String nome;
private String email;
private String telefone;
private String cpf;
private UserResponse user;
private List<EnderecoConsumidorResponse> endereco;
}
| 20.821429 | 61 | 0.80446 |
6a9de8ddb22a3c8afad46360383291195989b279 | 1,152 | package org.nd4j.linalg.jcublas.ops.executioner.kernels.args.impl;
import jcuda.Pointer;
import org.nd4j.linalg.api.ops.Op;
import org.nd4j.linalg.jcublas.ops.executioner.kernels.args.BaseKernelCallPointerArgs;
/**
* Post process kernel call device pointers
*
* @author Adam Gibson
*/
public class PostProcessKernelCallPointerArgs extends BaseKernelCallPointerArgs {
/**
* @param op
* @param extraArgs
*/
public PostProcessKernelCallPointerArgs(Op op, Object[] extraArgs) {
super(op, extraArgs);
}
@Override
protected void initPointers(Op op, Object[] extraArgs) {
/**
* args = new Object[] {
op.x().tensorAlongDimension(0, dimension).length(),
op.x().offset(),
(Pointer) this.originalArgs[resultIndex],
op.x().tensorAlongDimension(0, dimension).elementWiseStride(),
(Pointer) this.originalArgs[extraParamsIndex],
(Pointer) this.originalArgs[resultIndex],
};
*/
this.x = (Pointer) extraArgs[2];
this.extraArgsPointer = (Pointer) extraArgs[4];
this.z = (Pointer) extraArgs[5];
}
}
| 30.315789 | 86 | 0.649306 |
0dddb6465cf6f5f1ba8e4cdcb7b43e7fc135ce0c | 1,707 | package com.kxj.task;
import org.apache.tomcat.jni.Local;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.sql.SQLOutput;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Random;
/**
* @author xiangjin.kong
* @date 2020/9/9 13:47
*/
public abstract class TaskService {
private static Random random = new Random();
public void oneTask() throws InterruptedException {
System.out.println("任务一:start......");
LocalDateTime startTime = LocalDateTime.now();
Thread.sleep(random.nextInt(10000));
LocalDateTime endTime = LocalDateTime.now();
System.out.println("任务一:end.......");
long millis = Duration.between(startTime, endTime).toMillis();
System.out.println("任务一耗时:" + millis);
}
public void twoTask() throws InterruptedException {
System.out.println("任务二:start......");
LocalDateTime startTime = LocalDateTime.now();
Thread.sleep(random.nextInt(10000));
LocalDateTime endTime = LocalDateTime.now();
System.out.println("任务二:end.......");
long millis = Duration.between(startTime, endTime).toMillis();
System.out.println("任务二耗时:" + millis);
}
public void threeTask() throws InterruptedException {
System.out.println("任务三:start......");
LocalDateTime startTime = LocalDateTime.now();
Thread.sleep(random.nextInt(10000));
LocalDateTime endTime = LocalDateTime.now();
System.out.println("任务三:end.......");
long millis = Duration.between(startTime, endTime).toMillis();
System.out.println("任务三耗时:" + millis);
}
}
| 32.826923 | 70 | 0.662566 |
b41db58902c7ed776d07e8479d6931ee60f4f631 | 9,457 | /*
* Copyright (c) 2010-2021 Haifeng Li. All rights reserved.
*
* Smile 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.
*
* Smile 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 Smile. If not, see <https://www.gnu.org/licenses/>.
*/
package smile.feature.extraction;
import java.io.Serializable;
import java.util.Properties;
import smile.math.DifferentiableFunction;
import smile.math.MathEx;
import smile.math.matrix.Matrix;
import smile.feature.extraction.ica.Exp;
import smile.feature.extraction.ica.LogCosh;
import smile.stat.distribution.GaussianDistribution;
/**
* Independent Component Analysis (ICA) is a computational method for separating
* a multivariate signal into additive components. FastICA is an efficient
* algorithm for ICA invented by Aapo Hyvärinen.
* <p>
* Like most ICA algorithms, FastICA seeks an orthogonal rotation of prewhitened
* data, through a fixed-point iteration scheme, that maximizes a measure of
* non-Gaussianity of the rotated components. Non-gaussianity serves as a proxy
* for statistical independence, which is a very strong condition and requires
* infinite data to verify. To measure non-Gaussianity, FastICA relies on a
* non-quadratic nonlinear function f(u), its first derivative g(u),
* and its second derivative g2(u).
* <p>
* A simple application of ICA is the cocktail party problem, where the
* underlying speech signals are separated from a sample data consisting
* of people talking simultaneously in a room. Usually the problem is
* simplified by assuming no time delays or echoes.
* <p>
* An important note to consider is that if N sources are present,
* at least N observations (e.g. microphones if the observed signal
* is audio) are needed to recover the original signals.
*
* <h2>References</h2>
* <ol>
* <li>Aapo Hyvärinen: Fast and robust fixed-point algorithms for independent component analysis, 1999</li>
* <li>Aapo Hyvärinen, Erkki Oja: Independent component analysis: Algorithms and applications, 2000</li>
* </ol>
*
* @author Haifeng Li
*/
public class ICA implements Serializable {
private static final long serialVersionUID = 2L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ICA.class);
/**
* The independent components (row-wise).
*/
public final double[][] components;
/**
* Constructor.
* @param components each row is an independent component.
*/
public ICA(double[][] components) {
this.components = components;
}
/**
* Fits independent component analysis.
*
* @param data training data. The number of columns corresponding with the
* number of samples of mixed signals and the number of rows
* corresponding with the number of independent source signals.
* @param p the number of independent components.
* @return the model.
*/
public static ICA fit(double[][] data, int p) {
return fit(data, p, new Properties());
}
/**
* Fits independent component analysis.
*
* @param data training data. The number of columns corresponding with the
* number of samples of mixed signals and the number of rows
* corresponding with the number of independent source signals.
* @param p the number of independent components.
* @param params the hyper-parameters.
* @return the model.
*/
public static ICA fit(double[][] data, int p, Properties params) {
DifferentiableFunction f;
String contrast = params.getProperty("smile.ica.contrast", "LogCosh");
switch (contrast) {
case "LogCosh":
f = new LogCosh();
break;
case "Gaussian":
f = new Exp();
break;
default:
throw new IllegalArgumentException("Unsupported contrast function: " + contrast);
}
double tol = Double.parseDouble(params.getProperty("smile.ica.tolerance", "1E-4"));
int maxIter = Integer.parseInt(params.getProperty("smile.ica.iterations", "100"));
return fit(data, p, f, tol, maxIter);
}
/**
* Fits independent component analysis.
*
* @param data training data.
* @param p the number of independent components.
* @param contrast the contrast function which is capable of separating or
* extracting independent sources from a linear mixture.
* It must be a non-quadratic non-linear function that
* has second-order derivative.
* @param tol the tolerance of convergence test.
* @param maxIter the maximum number of iterations.
* @return the model.
*/
public static ICA fit(double[][] data, int p, DifferentiableFunction contrast, double tol, int maxIter) {
if (tol <= 0.0) {
throw new IllegalArgumentException("Invalid tolerance: " + tol);
}
if (maxIter <= 0) {
throw new IllegalArgumentException("Invalid maximum number of iterations: " + maxIter);
}
int n = data.length;
int m = data[0].length;
if (p < 1 || p > m) {
throw new IllegalArgumentException("Invalid dimension of feature space: " + p);
}
GaussianDistribution g = new GaussianDistribution(0, 1);
double[][] W = new double[p][n];
for (int i = 0; i < p; i++) {
for (int j = 0; j < n; j++) {
W[i][j] = g.rand();
}
MathEx.unitize(W[i]);
}
Matrix X = whiten(data);
double[] wold = new double[n];
double[] wdif = new double[n];
double[] gwX = new double[m];
double[] g2w = new double[n];
for (int i = 0; i < p; i++) {
double[] w = W[i];
double diff = Double.MAX_VALUE;
for (int iter = 0; iter < maxIter && diff > tol; iter++) {
System.arraycopy(w, 0, wold, 0, n);
// Calculate derivative of projection
double[] wX = new double[m];
X.tv(w, wX);
double g2 = 0.0;
for (int j = 0; j < m; j++) {
gwX[j] = contrast.g(wX[j]);
g2 += contrast.g2(wX[j]);
}
for (int j = 0; j < n; j++) {
g2w[j] = w[j] * g2;
}
X.mv(gwX, w);
for (int j = 0; j < n; j++) {
w[j] = (w[j] - g2w[j]) / m;
}
// Orthogonalization of independent components
for (int k = 0; k < i; k++) {
double[] wk = W[k];
double wkw = MathEx.dot(W[k], w);
for (int j = 0; j < n; j++) {
w[j] -= wkw * wk[j];
}
}
// normalize
MathEx.unitize2(w);
// Test for termination condition. Note that the algorithm has
// converged if the direction of w and wOld is the same, this
// is why we test the two cases.check if convergence
for (int j = 0; j < n; j++) {
wdif[j] = (w[j] - wold[j]);
}
double n1 = MathEx.norm(wdif);
for (int j = 0; j < n; j++) {
wdif[j] = (w[j] + wold[j]);
}
double n2 = MathEx.norm(wdif);
diff = Math.min(n1, n2);
}
if (diff > tol) {
logger.warn(String.format("Component %d did not converge in %d iterations.", i, maxIter));
}
}
return new ICA(W);
}
/**
* The input data matrix must be prewhitened, or centered and whitened,
* before applying the FastICA algorithm to it.
*
* @param data the raw data.
* @return the whitened data
*/
private static Matrix whiten(double[][] data) {
// covariance matrix on centered data.
double[] mean = MathEx.rowMeans(data);
Matrix X = Matrix.of(data);
int n = X.nrow();
int m = X.ncol();
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
X.sub(i, j, mean[i]);
}
}
Matrix XXt = X.aat();
Matrix.EVD eigen = XXt.eigen(false, true, true);
Matrix E = eigen.Vr;
Matrix Y = E.tm(X);
double[] d = eigen.wr;
for (int i = 0; i < d.length; i++) {
if (d[i] < 1E-8) {
throw new IllegalArgumentException(String.format("Covariance matrix (column %d) is close to singular.", i));
}
d[i] = 1 / Math.sqrt(d[i]);
}
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
Y.mul(i, j, d[i]);
}
}
return Y;
}
} | 35.82197 | 124 | 0.56445 |
c5bc2345fbc28383022e9514b47087acd97a75cc | 4,022 | package ballModel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.Timer;
/**
* MVC model for the system
*/
public class BallModel {
private int _timeSlice = 50; // update every 50 milliseconds
// The model adapter is initialized to a no-op to insure that system always has well-defined behavior
private IModel2ViewAdapter _model2ViewAdpt = IModel2ViewAdapter.NULL_OBJECT;
//The timer "ticks" by calling this method every _timeslice milliseconds
private Timer _timer = new Timer(_timeSlice, (e) -> _model2ViewAdpt.update());
private Dispatcher myDispatcher = new Dispatcher(); //centralize and distribute
private static Rectangle bounds; //the bounds of the canvas
private Point startLoc = new Point(10, 20); //start location of the ball
private int startRadius = 10; //start radius of the ball
private Point startVel = new Point(10, 10); //start velocity of the ball
private Color startColor = Color.BLACK; //start color of the ball
private Randomizer random = new Randomizer(); //set up a randomizer to random location, radius, velocity and color
/**
* Constructor is supplied with an instance of the view adapter.
* @param model2ViewAdpt
*/
public BallModel(IModel2ViewAdapter model2ViewAdpt) {
_model2ViewAdpt = model2ViewAdpt;
}
/**
* get the bounds from the view
* @param bounds
*/
public void getBounds(Rectangle bounds) {
BallModel.bounds = bounds;
}
/**
* let the ABall class know the bounds of the canvas
* @return bounds
*/
public static Rectangle returnBounds() {
return bounds;
}
/**
* The following method returns an instance of an ABall, given a fully qualified class name (package.classname) of a subclass of ABall.
* The method assumes that there is only one constructor for the supplied class that has the same *number* of
* input parameters as specified in the args array and that it conforms to a specific
* signature, i.e. specific order and types of input parameters in the args array.
* @param classname A string that is the fully qualified class name of the desired object
* @param startLoc
* @param startRadius
* @param startVel
* @param startColor
* @return An instance of the supplied class.
*/
private ABall loadBall(String classname, Point startLoc, int startRadius, Point startVel, Color startColor) {
try {
Object[] args = new Object[] { startLoc, startRadius, startVel, startColor };
java.lang.reflect.Constructor<?> cs[] = Class.forName(classname).getConstructors();
java.lang.reflect.Constructor<?> c = null;
for (int i = 0; i < cs.length; i++) {
if (args.length == (cs[i]).getParameterTypes().length) {
c = cs[i];
break;
}
}
return (ABall) c.newInstance(args); // Call the constructor. Will throw a null ptr exception if no constructor with the right number of input parameters was found.
} catch (Exception ex) {
System.err.println("Class " + classname + " failed to load. \nException = \n" + ex);
ex.printStackTrace();
return null;
}
}
/**
* add the balls with the given type name, randomize the initial location, radius, velocity and color
* add the balls into dispatcher, so right now it can be notified
* @param temp
*/
public void make_ball(String typename) {
int radius = random.randomInt(10, 50);
startLoc = random.randomLoc(returnBounds(), radius);
startRadius = radius;
startVel = random.randomVel();
startColor = random.randomColor();
typename = "ballModel." + typename;
ABall a = loadBall(typename, startLoc, startRadius, startVel, startColor);
myDispatcher.addObserver(a);
}
/**
* clean all observers from dispatcher, so it could clean the canvas
*/
public void clean() {
myDispatcher.deleteObservers();
}
/**
* start the model and make the timer start
*/
public void start() {
_timer.start();
}
/**
* notify all observers to update
* @param g
*/
public void update(Graphics g) {
myDispatcher.notifyAll(g);
}
}
| 33.516667 | 168 | 0.715813 |
2e82b347db0da7278adcd0079c330975797d0280 | 14,946 | /*
* 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 samples.cloudrun.GCESample.cmd;
import samples.cloudrun.GCESample.model.DefaultValues;
import samples.cloudrun.GCESample.model.GCEInstance;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.ComputeScopes;
import com.google.api.services.compute.model.AccessConfig;
import com.google.api.services.compute.model.AttachedDisk;
import com.google.api.services.compute.model.AttachedDiskInitializeParams;
import com.google.api.services.compute.model.Instance;
import com.google.api.services.compute.model.InstanceList;
import com.google.api.services.compute.model.Metadata;
import com.google.api.services.compute.model.NetworkInterface;
import com.google.api.services.compute.model.Operation;
import com.google.api.services.compute.model.ServiceAccount;
import com.google.api.services.compute.model.Zone;
import com.google.api.services.compute.model.ZoneList;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.lang.RuntimeException;
import java.util.logging.Logger;
import java.util.logging.Level;
public class GCEComputeCmd {
private static final Logger LOGGER = Logger.getLogger(GCEComputeCmd.class.getName());
private static HttpTransport httpTransport = null;
private static JsonFactory jsonFactoryInstance = null;
private static Compute compute = null;
private static final String APPLICATION_NAME = "";
private static final long OPERATION_TIMEOUT_MILLIS = 60 * 1000;
public GCEComputeCmd() {
try {
init();
} catch(Exception e) {
}
}
// Method to initialise the class
private void init()
throws IOException {
try {
// Initialise the class...
if (httpTransport != null && jsonFactoryInstance != null &&
compute != null) {
return;
}
if (jsonFactoryInstance == null) {
jsonFactoryInstance = JacksonFactory.getDefaultInstance();
}
if (httpTransport == null) {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
}
if (compute == null) {
// Authenticate using Google Application Default Credentials.
GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
if (credential.createScopedRequired()) {
List<String> scopes = new ArrayList<>();
// Set Google Cloud Storage scope to Full Control.
scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
// Set Google Compute Engine scope to Read-write.
scopes.add(ComputeScopes.COMPUTE);
credential = credential.createScoped(scopes);
}
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
// Create Compute Engine object for listing instances.
compute = new Compute.Builder(httpTransport, jsonFactoryInstance, requestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
}
} catch(Exception e) {
LOGGER.severe("init() :"+e.getMessage());
httpTransport = null;
jsonFactoryInstance = null;
compute = null;
throw new IOException(e.getMessage());
}
return;
}
private static Operation.Error blockUntilComplete(
final String projectId,
Compute compute,
Operation operation,
long timeout)
throws Exception {
long start = System.currentTimeMillis();
final long pollInterval = 5 * 1000;
String zone = operation.getZone(); // null for global/regional operations
if (zone != null) {
String[] bits = zone.split("/");
zone = bits[bits.length - 1];
}
String status = operation.getStatus();
String opId = operation.getName();
while (operation != null && !status.equals("DONE")) {
Thread.sleep(pollInterval);
long elapsed = System.currentTimeMillis() - start;
if (elapsed >= timeout) {
throw new InterruptedException("Timed out waiting for operation to complete");
}
if (zone != null) {
Compute.ZoneOperations.Get get = compute.zoneOperations().get(projectId, zone, opId);
operation = get.execute();
} else {
Compute.GlobalOperations.Get get = compute.globalOperations().get(projectId, opId);
operation = get.execute();
}
if (operation != null) {
status = operation.getStatus();
}
}
return operation == null ? null : operation.getError();
}
// Create an instance implementation
private static Operation create(final String projectId, GCEInstance gceInstance)
throws RuntimeException {
try {
Instance instance = new Instance();
instance.setName(gceInstance.getInstanceName());
instance.setMachineType(
String.format(
"https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/%s",
projectId, gceInstance.getZone(), gceInstance.getMachineType()));
// Add Network Interface to be used by VM Instance.
LOGGER.info("create() "+instance.getMachineType());
NetworkInterface ifc = new NetworkInterface();
ifc.setNetwork(
String.format(
"https://www.googleapis.com/compute/v1/projects/%s/global/networks/default",
projectId));
List<AccessConfig> configs = new ArrayList<>();
AccessConfig config = new AccessConfig();
config.setType(gceInstance.getNetworkInterface());
config.setName(gceInstance.getNetworkConfig());
configs.add(config);
ifc.setAccessConfigs(configs);
instance.setNetworkInterfaces(Collections.singletonList(ifc));
// Add attached Persistent Disk to be used by VM Instance.
AttachedDisk disk = new AttachedDisk();
disk.setBoot(true);
disk.setAutoDelete(true);
disk.setType("PERSISTENT");
AttachedDiskInitializeParams params = new AttachedDiskInitializeParams();
// Assign the Persistent Disk the same name as the VM Instance.
params.setDiskName(gceInstance.getInstanceName());
// Specify the source operating system machine image to be used by the VM Instance.
params.setSourceImage(DefaultValues.SOURCE_IMAGE_PREFIX + gceInstance.getImageName());
// Specify the disk type as Standard Persistent Disk
params.setDiskType(
String.format(
"https://www.googleapis.com/compute/v1/projects/%s/zones/%s/diskTypes/pd-standard",
projectId, gceInstance.getZone()));
disk.setInitializeParams(params);
instance.setDisks(Collections.singletonList(disk));
// Initialize the service account to be used by the VM Instance and set the API access scopes.
ServiceAccount account = new ServiceAccount();
account.setEmail("default");
List<String> scopes = new ArrayList<>();
scopes.add("https://www.googleapis.com/auth/devstorage.full_control");
scopes.add("https://www.googleapis.com/auth/compute");
account.setScopes(scopes);
instance.setServiceAccounts(Collections.singletonList(account));
// Optional - Add a startup script to be used by the VM Instance.
// Metadata meta = new Metadata();
// Metadata.Items item = new Metadata.Items();
// item.setKey("startup-script-url");
// If you put a script called "vm-startup.sh" in this Google Cloud Storage
// bucket, it will execute on VM startup. This assumes you've created a
// bucket named the same as your PROJECT_ID.
// For info on creating buckets see:
// https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets
// item.setValue(String.format("gs://%s/vm-startup.sh", PROJECT_ID));
// meta.setItems(Collections.singletonList(item));
// instance.setMetadata(meta);
Compute.Instances.Insert insert = compute.instances().insert(projectId,
gceInstance.getZone(),
instance);
return insert.execute();
} catch(Exception e) {
LOGGER.severe("create() :"+e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
// Delete an instance implementation
private static Operation delete(final String projectId, GCEInstance gceInstance)
throws RuntimeException {
try {
Compute.Instances.Delete delete =
compute.instances().delete(projectId, gceInstance.getZone(),
gceInstance.getInstanceName());
return delete.execute();
} catch(Exception e) {
LOGGER.severe("delete() :"+e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
// Get instance
private Instance getInstance(final String projectId, final String region, final String instanceName) {
try {
Compute.Instances.List instances = compute.instances().list(projectId, region);
InstanceList list = instances.execute();
if (list.getItems() == null) {
return null;
} else {
for (Instance instance : list.getItems()) {
if (instance.getName().equals(instanceName)) {
return instance;
}
}
}
return null;
} catch(Exception e) {
LOGGER.severe("getInstance() :"+e.getMessage());
return null;
}
}
// Get instance
private Map<String,List<Object>> list(final String projectId) {
try {
Compute.Zones.List zones = compute.zones().list(projectId);
ZoneList list = zones.execute();
if (list.getItems() == null) {
return null;
} else {
Map<String,List<Object>> mmap = new HashMap<String,List<Object>>();
for (Zone zone : list.getItems()) {
List<Object> insList = list(projectId,zone.getName());
if (insList != null) {
mmap.put(zone.getName(),insList);
}
}
return mmap;
}
} catch(Exception e) {
LOGGER.severe("list() :"+e.getMessage());
return null;
}
}
// Get instance
private List<Object> list(final String projectId, final String region) {
try {
Compute.Instances.List instances = compute.instances().list(projectId, region);
InstanceList list = instances.execute();
if (list.getItems() == null) {
return null;
} else {
List<Object> listInst = new ArrayList<Object>(list.getItems());
return listInst;
}
} catch(Exception e) {
LOGGER.severe("list() :"+e.getMessage());
return null;
}
}
// List all instances
public List<Object> listInstances(final String projectId, final String region) {
return(list(projectId,region));
}
// List all instances
public Map<String,List<Object>> listInstances(final String projectId) {
return(list(projectId));
}
// Describe instance
public Instance describeInstance(final String projectId, final String region, final String instanceName) {
return(getInstance(projectId,region,instanceName));
}
// Create an instance
public boolean createInstance(final String projectId, GCEInstance gceInstance)
throws RuntimeException {
try {
init();
Operation op = create(projectId,gceInstance);
Operation.Error error = blockUntilComplete(projectId, compute,
op, OPERATION_TIMEOUT_MILLIS);
if (error != null) {
throw new RuntimeException(error.toPrettyString());
}
Instance gce = getInstance(projectId,gceInstance.getZone(),gceInstance.getInstanceName());
if (gce == null) {
return false;
}
LOGGER.info("createInstance() :"+gce.toPrettyString());
return true;
} catch(Exception e) {
LOGGER.severe("createInstance() :"+e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
// Delete an instance
public boolean deleteInstance(final String projectId, GCEInstance gceInstance)
throws RuntimeException {
try {
init();
Operation op = delete(projectId,gceInstance);
Operation.Error error = blockUntilComplete(projectId, compute,
op, OPERATION_TIMEOUT_MILLIS);
return (error == null);
} catch(Exception e) {
LOGGER.severe("deleteInstance() :"+e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
}
| 41.06044 | 110 | 0.598287 |
2dedea1d9a3e7ec7ab0e20015fc11bb85ed5d195 | 2,698 | package restaurant.layoutGUI;
import java.awt.*;
import restaurant.layoutGUI.Restaurant;
import restaurant.layoutGUI.Table;
import restaurant.layoutGUI.Waiter;
import restaurant.layoutGUI.Customer;
import restaurant.layoutGUI.Food;
public class AppWindow
{
public static void main(String args[])
{
Restaurant restaurant = new Restaurant("Welcome to My Restaurant", 20, 15, true);
Waiter waiter1 = new Waiter("W1", new Color(255, 0, 0), restaurant);
Waiter waiter2 = new Waiter("W2", new Color(255, 0, 0), restaurant);
Waiter waiter3 = new Waiter("W3", new Color(255, 0, 0), restaurant);
Customer customer1 = new Customer("C1", new Color(0, 255, 0), restaurant);
Customer customer2 = new Customer("C2", new Color(0, 255, 0), restaurant);
Customer customer3 = new Customer("C3", new Color(0, 255, 0), restaurant);
Food food1 = new Food("F1", new Color(0, 0, 255), restaurant);
Food food2 = new Food("F2", new Color(0, 0, 255), restaurant);
Food food3 = new Food("F3", new Color(0, 0, 255), restaurant);
Table table1 = new Table("T1", 5, 3, 3, restaurant);
Table table2 = new Table("T2", 5, 8, 3, restaurant);
Table table3 = new Table("T3", 10, 3, 3, restaurant);
Table table4 = new Table("T4", 10, 9, 3, restaurant);
restaurant.setAnimDelay(250);
restaurant.addWaitArea(2, 2, 5);
restaurant.addCounter(17, 2, 4);
restaurant.addGrill(19, 3, 10);
restaurant.displayRestaurant();
customer1.appearInWaitingQueue();
customer2.appearInWaitingQueue();
customer3.appearInWaitingQueue();
food1.cookFood();
food2.cookFood();
food1.placeOnCounter();
food3.cookFood();
waiter1.move(2, 1);
waiter1.move(3, 1);
waiter1.move(3, 2);
waiter1.pickUpCustomer(customer1);
waiter1.move(4, 2);
waiter1.move(5, 2);
waiter1.seatCustomer(table1);
for (int i = 6; i <= 16; i++)
waiter1.move(i, 2);
waiter1.pickUpFood(food1);
for (int i = 16; i >= 7; i--)
waiter1.move(i, 2);
waiter1.serveFood(table1);
for (int i = 6; i >= 3; i--)
waiter1.move(i, 2);
waiter1.move(3, 3);
food1.remove();
customer1.leave();
food2.placeOnCounter();
}
}
| 36.958904 | 94 | 0.531134 |
b05836bc444b9637e09ac2df61ce2448a0764da6 | 6,230 | /*
* This Java source file was generated by the Gradle 'init' task.
*/
package pop3.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Properties;
import java.util.Scanner;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Store;
public class App {
// Mailtrap.io configurations
private static String host;
private static String username;
private static String password;
public String getGreeting() {
return "[POP3 Client] Welcome to POP3 Client.";
}
/**
* Retrieve properties from config.properties
*
* @param propertiesPath
* @return
* @throws IOException
*/
public Properties getEmailProperties(String propertiesPath) throws IOException {
InputStream inPropertiesStream = getClass().getResourceAsStream(propertiesPath);
Properties props = new Properties();
InputStreamReader inputStreamReader = new InputStreamReader(inPropertiesStream, "UTF-8");
props.load(inputStreamReader);
return props;
}
/**
* Build console prompt
*
* @return
*/
public String buildPrompt() {
String prompt = "\n";
prompt += "[POP3 Client] Info:\n";
prompt += " Host: " + host + "\n";
prompt += " Mailtrap username: " + username + "\n";
prompt += " Mailtrap password: " + maskPassword(password) + "\n";
return prompt;
}
/**
* Mask password with *
*
* @param password
* @return
*/
public String maskPassword(String password) {
StringBuilder maskedPassword = new StringBuilder(password);
maskedPassword.replace(1, password.length() - 1, "*".repeat(password.length() - 2));
return maskedPassword.toString();
}
/**
* Fetch email list from server
*/
public void fetchMail() {
// Start loading animation
LoadingIndicator loadingIndicator = new LoadingIndicator();
loadingIndicator.start();
// Format email date
SimpleDateFormat dateFormat = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss z", Locale.US);
Properties properties = System.getProperties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "1100");
properties.put("mail.pop3.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties);
try {
// Create POP3 store object and connect with POP3 server
Store store = session.getStore("pop3");
store.connect(host, username, password);
// Create folder object and open read only mode
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
// Get messages from inbox
Message[] messages = folder.getMessages();
// Stop loading indicator animation
loadingIndicator.setLoading(false);
System.out.println("");
if (messages.length == 0) {
System.out.println("[POP3 Client] Inbox empty.");
} else {
System.out.println("[POP3 Client] Inbox:");
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("-----------------------------------------------");
System.out.println(" [No." + (i + 1) + "]");
System.out.println(" Date: " + dateFormat.format(message.getSentDate()));
System.out.println(" Subject: " + message.getSubject());
System.out.println(" Sender: " + message.getFrom()[0].toString());
System.out.println(" Receiver: " + message.getRecipients(RecipientType.TO)[0].toString());
System.out.println(" Content: " + message.getContent().toString().trim());
}
System.out.println("-----------------------------------------------");
System.out.println("[POP3 Client] Messages loaded.");
}
// Close resources
folder.close(false);
store.close();
} catch (Exception e) {
loadingIndicator.setLoading(false);
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
App app = new App();
System.out.println(app.getGreeting());
// Init email properties
Properties props = app.getEmailProperties("/config.properties");
host = props.getProperty("pop3client.host");
username = props.getProperty("pop3client.mailtrap.username");
password = props.getProperty("pop3client.mailtrap.password");
System.out.println(app.buildPrompt());
System.out.println("[POP3 Client] Type \"help\" to see a list of commands available.");
// Deal with commands
String command = "";
Scanner scanner = new Scanner(System.in);
while (!command.equals("bye")) {
System.out.print("> ");
command = scanner.nextLine();
switch (command) {
case "fetch":
app.fetchMail();
break;
case "info":
System.out.println(app.buildPrompt());
break;
case "help":
System.out.println("\n[POP3 Client] Commands:");
System.out.println(" fetch - Fetch inbox.");
System.out.println(" info - Print current user info.");
System.out.println(" help - Print this help message.");
System.out.println(" bye - Exit POP3 Client.");
break;
case "bye":
System.out.println("\n[POP3 Client] Bye!");
break;
default:
System.out.println("\n[POP3 Client] Invalid command.");
break;
}
}
scanner.close();
}
}
| 34.804469 | 113 | 0.560514 |
0c420b78fa0f61b84c2a4ffbeff66fd7e231ce8a | 1,055 | /*
* Created on Jul 22, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package backend.h2PNodes;
import backend.h2PFoundation.AcceptReturnType;
import backend.h2PVisitors.aVisitor;
/**
* @author karli
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class JoinNode extends aNode {
protected String fromID = "";
protected String toID = "";
/**
* @param theID
*/
public JoinNode(String theID, String theFromID, String theToID) {
super(theID, "JoinNode");
// TODO Auto-generated constructor stub
fromID = theFromID;
toID = theToID;
}
public String getFromID() {
return fromID;
}
public String getToID () {
return toID;
}
public AcceptReturnType accept(aVisitor v) {
return v.visitJoinNode(this);
}
}
| 22.446809 | 70 | 0.611374 |
22700a3ea5b5004352673b2b9bea67bc21bc1b94 | 1,895 | package java_oc_simple_server;
import org.iotivity.*;
import org.iotivity.oc.*;
public class PostLight implements OCRequestHandler {
private Light light;
public PostLight(Light light) {
this.light = light;
}
@Override
public void handler(OCRequest request, int interfaces) {
System.out.println("Inside the PostLight RequestHandler");
System.out.println("POST LIGHT:");
OCRepresentation rep = request.getRequestPayload();
while (rep != null) {
System.out.println("-----------------------------------------------------");
System.out.println("Key: " + rep.getName());
System.out.println("Type: " + rep.getType());
switch (rep.getType()) {
case OC_REP_BOOL:
light.setState(rep.getValue().getBool());
System.out.println("value: " + light.getState());
break;
case OC_REP_INT:
light.setPower(rep.getValue().getInteger());
System.out.println("value: " + light.getPower());
break;
case OC_REP_STRING:
light.setName(rep.getValue().getString());
System.out.println("value: " + light.getName());
break;
default:
System.out.println("NOT YET HANDLED VALUE");
OcUtils.sendResponse(request, OCStatus.OC_STATUS_BAD_REQUEST);
}
System.out.println("-----------------------------------------------------");
rep = rep.getNext();
}
OcCborEncoder root = OcCborEncoder.createOcCborEncoder(OcCborEncoder.EncoderType.ROOT);
root.setBoolean("value", light.getState());
root.setLong("dimmingSetting", light.getPower());
root.done();
OcUtils.sendResponse(request, OCStatus.OC_STATUS_CHANGED);
}
}
| 36.442308 | 95 | 0.543008 |
d514e3c3dcfd95307f6726b3fe9a15a70edbda3a | 1,162 | /**
* Package for calculate task.
*
* @author Ruslan Halmatov (mailto:[email protected])
* @version $Id$
* @since 25.09.2017
*/
package ru.job4j.calculator;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
*Класс {@code CalculatorTest} тестирует класс {@code Calculator}.
*/
public class CalculatorTest {
/**
*Метод {@code whenAddOnePlusOneThenTwo} создает объект класса {@code Calculator}.
*и тестирует арифметические функции и сверяет результат с ожидаемым.
*/
@Test
public void whenAddOnePlusOneThenTwo() {
Calculator calc = new Calculator();
calc.add(1, 1);
double result = calc.getResult();
double expected = 2;
assertThat(result, is(expected));
calc.subtract(1, 1);
result = calc.getResult();
expected = 0;
assertThat(result, is(expected));
calc.div(2, 1);
result = calc.getResult();
expected = 2;
assertThat(result, is(expected));
calc.multiple(2, 2);
result = calc.getResult();
expected = 4;
assertThat(result, is(expected));
}
} | 27.666667 | 84 | 0.635972 |
7aebd3f60448d6262708094cc3a5b31394299f47 | 20,717 | package org.deeplearning4j.examples.rnn.beer;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Random;
import org.deeplearning4j.examples.rnn.beer.utils.EpochScoreTracker;
import org.deeplearning4j.examples.utils.Utils;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.BackpropType;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.layers.GravesLSTM;
import org.deeplearning4j.nn.conf.layers.RnnOutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.api.IterationListener;
import org.deeplearning4j.optimize.listeners.CollectScoresIterationListener;
import org.deeplearning4j.optimize.listeners.ParamAndGradientIterationListener;
import org.deeplearning4j.optimize.listeners.PerformanceListener;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LSTMBeerReviewModelingExample {
private static Logger log = LoggerFactory.getLogger(LSTMBeerReviewModelingExample.class);
public static void main(String[] args) throws Exception {
log.info("ARGS: " + args.length);
final int LAGER = 2;
int lstmLayerSize = Integer.parseInt(args[0]); //Number of units in each GravesLSTM layer
int miniBatchSize = Integer.parseInt(args[1]); //Size of mini batch to use when training
int maxExamplesPerEpoch = 0; //maximum # examples to train on (for debugging)
int maxExampleLength = Integer.parseInt(args[2]); //If >0 we truncate longer sequences, exclude shorter sequences
int tbpttLength = Integer.parseInt(args[3]); //Truncated backprop through time, i.e., do parameter updates ever 50 characters
int numEpochs = Integer.parseInt(args[4]); //Total number of training + sample generation epochs
int nSamplesToGenerate = 5; //Number of samples to generate after each training epoch
double temperature = Double.parseDouble(args[5]);
boolean loadPrevModel = true;
String generationInitialization = "~"; //Optional character initialization; a random character is used if null
// Above is Used to 'prime' the LSTM with a character sequence to continue/complete.
// Initialization characters must all be in CharacterIterator.getMinimalCharacterSet() by default
int rngSeed = 12345;
Random rng = new Random(rngSeed);
String SEP = FileSystems.getDefault().getSeparator();
String dataPath = System.getenv("BEER_REVIEW_PATH");
File tempFile = new File(dataPath);
assert(tempFile.exists() && !tempFile.isDirectory());
String beerIdDataPath = dataPath + SEP + "beers_all.json";
String reviewTrainingDataPath = dataPath + SEP + "reviews_top-train.json";
String reviewTestDataPath = dataPath + SEP + "reviews_top-test.json";
EpochScoreTracker tracker = new EpochScoreTracker();
tracker.setTargetLossScore(10.0);
ArrayList<String> extraLogLines = new ArrayList<>();
char[] validCharacters = BeerReviewCharacterIterator.getDefaultCharacterSet();
BeerReviewCharacterIterator trainData = new BeerReviewCharacterIterator(reviewTrainingDataPath, beerIdDataPath,
Charset.forName("UTF-8"), miniBatchSize, maxExampleLength,
maxExamplesPerEpoch, validCharacters, rng);
BeerReviewCharacterIterator testData = new BeerReviewCharacterIterator(reviewTestDataPath, beerIdDataPath,
Charset.forName("UTF-8"), miniBatchSize, maxExampleLength,
maxExamplesPerEpoch, validCharacters, rng);
BeerReviewCharacterIterator partTestData = new BeerReviewCharacterIterator(reviewTestDataPath, beerIdDataPath,
Charset.forName("UTF-8"), miniBatchSize, maxExampleLength,
miniBatchSize, validCharacters, rng);
int everyNEpochs = 10; //trainData.totalExamples() / miniBatchSize / 50;
String baseModelPath = System.getenv("MODEL_SAVE_PATH");
ModelSaver saver = new ModelSaver(baseModelPath, everyNEpochs);
String modelSavePath = saver.getModelSavePath();
int totalExamples = trainData.totalExamples();
if (maxExamplesPerEpoch <= 0 || maxExamplesPerEpoch > totalExamples)
maxExamplesPerEpoch = totalExamples;
int nIn = trainData.inputColumns();
int nOut = trainData.totalOutcomes();
//Set up network configuration:
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT).iterations(1)
.learningRate(0.1)
.rmsDecay(0.95)
.seed(rngSeed)
.regularization(true)
.l2(0.001)
.weightInit(WeightInit.XAVIER)
.updater(Updater.RMSPROP)
.list()
.layer(0, new GravesLSTM.Builder()
.nIn(nIn)
.nOut(lstmLayerSize)
.activation("tanh").build())
.layer(1, new GravesLSTM.Builder()
.nOut(lstmLayerSize)
.activation("tanh").build())
.layer(2, new RnnOutputLayer.Builder(LossFunction.MCXENT)
.activation("softmax")
.nOut(nOut)
.build())
.backpropType(BackpropType.TruncatedBPTT)
.tBPTTForwardLength(tbpttLength)
.tBPTTBackwardLength(tbpttLength)
.pretrain(false)
.backprop(true)
.build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
INDArray params = null;
if (loadPrevModel) {
log.info("Attempting to continue training from " + modelSavePath);
try {
MultiLayerNetwork oldNet = ModelSerializer.restoreMultiLayerNetwork(modelSavePath);
params = oldNet.params();
log.info("Success!");
} catch (Exception e) {
log.info("Failed to load model from " + modelSavePath);
loadPrevModel = false;
log.info("Starting with a new model...");
}
}
net.init(params, false);
ArrayList<IterationListener> listeners = new ArrayList<>();
listeners.add(saver);
// listeners.add(new HistogramIterationListener(1));
// listeners.add(new FlowIterationListener(1));
listeners.add(new CollectScoresIterationListener(10));
listeners.add(new PerformanceListener(everyNEpochs, true));
// listeners.add(new ScoreIterationListener(1));
listeners.add(new HeldoutScoreIterationListener(partTestData, 2*miniBatchSize, 2));
File gradientFile = new File(baseModelPath + FileSystems.getDefault().getSeparator() + "gradients.tsv");
listeners.add(new ParamAndGradientIterationListener(everyNEpochs, true, false, false, true, false, true, true,
gradientFile, "\t"));
listeners.add(new SampleGeneratorListener(net, trainData, rng, temperature, maxExampleLength, LAGER, everyNEpochs));
net.setListeners(listeners);
//Print the number of parameters in the network (and for each layer)
Layer[] layers = net.getLayers();
int totalNumParams = 0;
for(int i=0; i<layers.length; i++){
int nParams = layers[i].numParams();
log.info("Number of parameters in layer " + i + ": " + nParams);
totalNumParams += nParams;
}
log.info("Total number of network parameters: " + totalNumParams);
long totalExamplesAcrossEpochs = 0;
long start;
long totalTrainingTimeMS = 0;
log.info("----- Generating Initial Lager Beer Review Sample -----");
String[] initialSample = SampleGeneratorListener.sampleBeerRatingFromNetwork(net, trainData, rng, temperature,
maxExampleLength > 0 ? maxExampleLength : 1000, 1, LAGER);
log.info("SAMPLE 00: " + initialSample[0]);
//Do training, and then generate and print samples from network
String evalStr = "Test set evaluation at epoch %d: Accuracy = %.2f, F1 = %.2f";
for(int i=0; i<numEpochs; i++){
log.info("EPOCH " + i);
start = System.currentTimeMillis();
net.fit(trainData);
long end = System.currentTimeMillis();
long epochSeconds = Math.abs(end - start) / 1000; // se
long epochMin = epochSeconds / 60; // se
totalTrainingTimeMS += Math.abs(end - start);
totalExamplesAcrossEpochs += maxExamplesPerEpoch;
log.info("--------------------");
log.info("Completed epoch " + i);
log.info("Epoch Loss Score: " + net.score());
tracker.addScore(net.score());
log.info("Time for Epoch Training " + Math.abs(end - start) + " ms, (" + epochSeconds + " seconds) (" + (epochMin) + " minutes)");
log.info("Total Training Time so Far: " + (totalTrainingTimeMS / 1000 / 60) + " minutes");
ModelSaver.saveModel(net, saver.getModelSavePath(), i);
log.info("Evaluate model....");
// int ct = testData.totalExamples();
double cost = 0;
double count = 0;
while(testData.hasNext()) {
DataSet minibatch = testData.next();
cost += net.scoreExamples(testData, false).sumNumber().doubleValue();
count += minibatch.getLabelsMaskArray().sumNumber().doubleValue();
}
log.info(String.format("Epoch %4d test set average cost: %.4f", i, cost / count));
// testData.reset();
// Evaluation evaluation = net.evaluate(testData);;
// log.info(String.format(evalStr, i, ));
// log.info(String.format(evalStr, i, evaluation.accuracy(), evaluation.f1()));
log.info("****************Example finished********************");
// float rating_overall = 4.0f;
// float rating_taste = 5.0f;
// float rating_appearance = 4.0f;
// float rating_palate = 5.0f;
// float rating_aroma = 5.0f;
// int styleIndex = 2; // Lager
// String[] samples = sampleBeerRatingFromNetwork(generationInitialization, net, iter, rng, nCharactersToSample, nSamplesToGenerate, rating_overall, rating_taste, rating_appearance, rating_palate, rating_aroma, styleIndex);
// for(int j=0; j<samples.length; j++){
// log.info("----- Generating Lager Beer Review Sample [" + j + "] -----");
// log.info(samples[j]);
// }
trainData.reset();
testData.reset();
for (String s : SampleGeneratorListener.sampleBeerRatingFromNetwork(net, trainData, rng, temperature,
maxExampleLength, 5, 2))
log.info("SAMPLE: " + s);
int a = 1;
}
log.info("Training Final Report: ");
long totalTrainingTimeMinutesFinal = (totalTrainingTimeMS / 1000 / 60);
log.info("Total Training Time: " + totalTrainingTimeMinutesFinal + " minutes");
log.info("Training First Loss Score: " + tracker.firstScore);
log.info("Training Average Loss Score: " + tracker.avgScore());
log.info("Training Loss Score Improvement: " + tracker.scoreChangeOverWindow());
extraLogLines.add("Mini-Batch Size: " + miniBatchSize);
extraLogLines.add("LSTM Layer Size: " + lstmLayerSize);
extraLogLines.add("Training Dataset: " + dataPath);
extraLogLines.add("Total Epochs: " + numEpochs);
extraLogLines.add("Training Time: " + totalTrainingTimeMinutesFinal);
long avgTrainingTimePerEpochInMin = totalTrainingTimeMinutesFinal / numEpochs;
extraLogLines.add("Avg Training Time per Epoch: " + avgTrainingTimePerEpochInMin);
extraLogLines.add("Records in epoch: " + maxExamplesPerEpoch);
extraLogLines.add("Records in dataset: " + trainData.numExamples());
extraLogLines.add("Records Seen Across Epochs: " + totalExamplesAcrossEpochs);
extraLogLines.add("Training First Loss Score: " + tracker.firstScore);
extraLogLines.add("Training Average Loss Score: " + tracker.avgScore());
extraLogLines.add("Training Total Loss Score Improvement: " + tracker.scoreChangeOverWindow());
extraLogLines.add("Training Average Loss Score Improvement per Epoch: " + tracker.averageLossImprovementPerEpoch());
extraLogLines.add("Targeted Loss Score: " + tracker.targetLossScore);
double remainingEpochs = tracker.computeProjectedEpochsRemainingToTargetLossScore();
extraLogLines.add("Projected Remaining Epochs to Loss Target: " + remainingEpochs);
extraLogLines.add("Projected Remaining Minutes to Loss Target: " + avgTrainingTimePerEpochInMin * remainingEpochs);
Utils.writeLinesToLocalDisk(saver.getExtraLogLinesPath(), extraLogLines);
log.info("Example complete");
}
//
// private static String[] sampleBeerRatingFromNetwork(MultiLayerNetwork net, BeerReviewCharacterIterator iter,
// Random rng, int charactersToSample, int numSamples,
// float[] rating_overall, float[] rating_taste, float[] rating_appearance,
// float[] rating_palate, float[] rating_aroma, int styleIndex){
//
// String initialization = "the";
//
// //Create input for initialization
// INDArray initializationInput = Nd4j.zeros(numSamples, iter.inputColumns(), initialization.length());
// char[] init = initialization.toCharArray();
//
// // for each timestep we want to generate a character
// for(int charTimestep = 0; charTimestep < init.length; charTimestep++){
//
// // get the column index for the current character
// int col_idx = iter.convertCharacterToIndex(init[ charTimestep ]);
//
// // for each sample
// for(int sampleIndex = 0; sampleIndex < numSamples; sampleIndex++){
//
// initializationInput.putScalar(new int[]{ sampleIndex, col_idx, charTimestep }, 1.0f);
//
// // TODO: here is where we need to add in ratings for generation hints
//
// int staticColumnBaseOffset = iter.numCharacterColumns();
//
// initializationInput.putScalar(new int[]{ sampleIndex, staticColumnBaseOffset, charTimestep }, rating_appearance);
// initializationInput.putScalar(new int[]{ sampleIndex, staticColumnBaseOffset + 1, charTimestep }, rating_aroma);
// initializationInput.putScalar(new int[]{ sampleIndex, staticColumnBaseOffset + 2, charTimestep }, rating_overall);
// initializationInput.putScalar(new int[]{ sampleIndex, staticColumnBaseOffset + 3, charTimestep }, rating_palate);
// initializationInput.putScalar(new int[]{ sampleIndex, staticColumnBaseOffset + 4, charTimestep }, rating_taste);
//
//
// // SETUP STYLE INDEX
// int styleColumnBaseOffset = staticColumnBaseOffset + 5;
// int styleIndexColumn = styleColumnBaseOffset + styleIndex; // add the base to the index
//
// //log.info("style index base: " + styleColumnBaseOffset + ", offset: " + styleIndexColumn);
//
// initializationInput.putScalar(new int[]{ sampleIndex, styleIndexColumn, charTimestep }, 1.0);
//
//
// }
//
// }
//
//
//
//
//
// // TODO: end ratings hints in input array
//
//
// StringBuilder[] sb = new StringBuilder[numSamples];
//
// for (int i = 0; i < numSamples; i++) {
//
// sb[ i ] = new StringBuilder(initialization);
//
// }
//
// //Sample from network (and feed samples back into input) one character at a time (for all samples)
// //Sampling is done in parallel here
// net.rnnClearPreviousState();
// INDArray output = net.rnnTimeStep(initializationInput);
// output = output.tensorAlongDimension(output.size(2)-1,1,0); //Gets the last time step output
//
// for(int i=0; i<charactersToSample; i++){
// //Set up next input (single time step) by sampling from previous output
// INDArray nextInput = Nd4j.zeros(numSamples,iter.inputColumns());
// //Output is a probability distribution. Sample from this for each example we want to generate, and add it to the new input
// for(int s=0; s<numSamples; s++){
// double[] outputProbDistribution = new double[iter.totalOutcomes()];
// for(int j=0; j<outputProbDistribution.length; j++) outputProbDistribution[j] = output.getDouble(s,j);
// int sampledCharacterIdx = sampleFromDistribution(outputProbDistribution,rng);
//
// nextInput.putScalar(new int[]{s,sampledCharacterIdx}, 1.0f); //Prepare next time step input
// sb[s].append(iter.convertIndexToCharacter(sampledCharacterIdx)); //Add sampled character to StringBuilder (human readable output)
// }
//
// output = net.rnnTimeStep(nextInput); //Do one time step of forward pass
// }
//
// String[] out = new String[numSamples];
// for(int i=0; i<numSamples; i++) out[i] = sb[i].toString();
// return out;
// }
//
//
// /** Generate a sample from the network, given an (optional, possibly null) initialization. Initialization
// * can be used to 'prime' the RNN with a sequence you want to extend/continue.<br>
// * Note that the initalization is used for all samples
// * @param initialization String, may be null. If null, select a random character as initialization for all samples
// * @param charactersToSample Number of characters to sample from network (excluding initialization)
// * @param net MultiLayerNetwork with one or more GravesLSTM/RNN layers and a softmax output layer
// * @param iter CharacterIterator. Used for going from indexes back to characters
// */
// private static String[] sampleCharactersFromNetwork(String initialization, MultiLayerNetwork net,
// BeerReviewCharacterIterator iter, Random rng, int charactersToSample, int numSamples){
// //Set up initialization. If no initialization: use a random character
// if(initialization == null){
// initialization = String.valueOf(iter.getRandomCharacter());
// }
//
// //Create input for initialization
// INDArray initializationInput = Nd4j.zeros(numSamples, iter.inputColumns(), initialization.length());
// char[] init = initialization.toCharArray();
// for(int i=0; i<init.length; i++){
// int idx = iter.convertCharacterToIndex(init[i]);
// for(int j=0; j<numSamples; j++){
// initializationInput.putScalar(new int[]{j,idx,i}, 1.0f);
// }
// }
//
// StringBuilder[] sb = new StringBuilder[numSamples];
// for(int i=0; i<numSamples; i++) sb[i] = new StringBuilder(initialization);
//
// //Sample from network (and feed samples back into input) one character at a time (for all samples)
// //Sampling is done in parallel here
// net.rnnClearPreviousState();
// INDArray output = net.rnnTimeStep(initializationInput);
// output = output.tensorAlongDimension(output.size(2)-1,1,0); //Gets the last time step output
//
// for(int i=0; i<charactersToSample; i++){
// //Set up next input (single time step) by sampling from previous output
// INDArray nextInput = Nd4j.zeros(numSamples,iter.inputColumns());
// //Output is a probability distribution. Sample from this for each example we want to generate, and add it to the new input
// for(int s=0; s<numSamples; s++){
// double[] outputProbDistribution = new double[iter.totalOutcomes()];
// for(int j=0; j<outputProbDistribution.length; j++) outputProbDistribution[j] = output.getDouble(s,j);
// int sampledCharacterIdx = sampleFromDistribution(outputProbDistribution,rng);
//
// nextInput.putScalar(new int[]{s,sampledCharacterIdx}, 1.0f); //Prepare next time step input
// sb[s].append(iter.convertIndexToCharacter(sampledCharacterIdx)); //Add sampled character to StringBuilder (human readable output)
// }
//
// output = net.rnnTimeStep(nextInput); //Do one time step of forward pass
// }
//
// String[] out = new String[numSamples];
// for(int i=0; i<numSamples; i++) out[i] = sb[i].toString();
// return out;
// }
//
// /** Given a probability distribution over discrete classes, sample from the distribution
// * and return the generated class index.
// * @param distribution Probability distribution over classes. Must sum to 1.0
// */
// private static int sampleFromDistribution(double[] distribution, Random rng){
// double d = rng.nextDouble();
// double sum = 0.0;
// for(int i=0; i<distribution.length; i++){
// sum += distribution[i];
// if(d <= sum) return i;
// }
// //Should never happen if distribution is a valid probability distribution
// throw new IllegalArgumentException("Distribution is invalid? d="+d+", sum="+sum);
// }
}
| 50.162228 | 227 | 0.683497 |
678f98b464c473b8bde24e80d036beb15746448f | 6,257 | /**
* 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.metron.dataloads.nonbulk.taxii;
import com.google.common.base.Joiner;
import org.apache.metron.dataloads.extractor.stix.types.ObjectTypeHandlers;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class TaxiiConnectionConfig {
final static ObjectMapper _mapper = new ObjectMapper();
private URL endpoint;
private int port = 443;
private URL proxy;
private String username;
private String password;
private ConnectionType type;
private String collection = "default";
private String subscriptionId = null;
private Date beginTime;
private String table;
private String columnFamily;
private Set<String> allowedIndicatorTypes = new HashSet<String>();
public TaxiiConnectionConfig withAllowedIndicatorTypes(List<String> indicatorTypes) {
allowedIndicatorTypes = new HashSet(indicatorTypes);
return this;
}
public TaxiiConnectionConfig withTable(String table) {
this.table = table;
return this;
}
public TaxiiConnectionConfig withColumnFamily(String cf) {
this.columnFamily = cf;
return this;
}
public TaxiiConnectionConfig withBeginTime(Date time) {
this.beginTime = time;
return this;
}
public TaxiiConnectionConfig withSubscriptionId(String subId) {
this.subscriptionId = subId;
return this;
}
public TaxiiConnectionConfig withCollection(String collection) {
this.collection = collection;
return this;
}
public TaxiiConnectionConfig withPort(int port) {
this.port = port;
return this;
}
public TaxiiConnectionConfig withEndpoint(URL endpoint) {
this.endpoint = endpoint;
return this;
}
public TaxiiConnectionConfig withProxy(URL proxy) {
this.proxy = proxy;
return this;
}
public TaxiiConnectionConfig withUsername(String username) {
this.username = username;
return this;
}
public TaxiiConnectionConfig withPassword(String password) {
this.password = password;
return this;
}
public TaxiiConnectionConfig withConnectionType(ConnectionType type) {
this.type= type;
return this;
}
public void setEndpoint(String endpoint) throws MalformedURLException {
this.endpoint = new URL(endpoint);
}
public void setPort(int port) {
this.port = port;
}
public void setProxy(String proxy) throws MalformedURLException {
this.proxy = new URL(proxy);
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setType(ConnectionType type) {
this.type = type;
}
public void setCollection(String collection) {
this.collection = collection;
}
public void setSubscriptionId(String subscriptionId) {
this.subscriptionId = subscriptionId;
}
public void setBeginTime(String beginTime) throws ParseException {
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.MEDIUM);
this.beginTime = sdf.parse(beginTime);
}
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public String getColumnFamily() {
return columnFamily;
}
public void setColumnFamily(String columnFamily) {
this.columnFamily = columnFamily;
}
public Date getBeginTime() {
return beginTime;
}
public int getPort() {
return port;
}
public URL getEndpoint() {
return endpoint;
}
public URL getProxy() {
return proxy;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public ConnectionType getType() {
return type;
}
public String getCollection() {
return collection;
}
public String getSubscriptionId() {
return subscriptionId;
}
public void setAllowedIndicatorTypes(List<String> allowedIndicatorTypes) {
withAllowedIndicatorTypes(allowedIndicatorTypes);
}
public Set<String> getAllowedIndicatorTypes() {
return allowedIndicatorTypes;
}
public static synchronized TaxiiConnectionConfig load(InputStream is) throws IOException {
TaxiiConnectionConfig ret = _mapper.readValue(is, TaxiiConnectionConfig.class);
return ret;
}
public static synchronized TaxiiConnectionConfig load(String s, Charset c) throws IOException {
return load( new ByteArrayInputStream(s.getBytes(c)));
}
public static synchronized TaxiiConnectionConfig load(String s) throws IOException {
return load( s, Charset.defaultCharset());
}
@Override
public String toString() {
return "TaxiiConnectionConfig{" +
"endpoint=" + endpoint +
", port=" + port +
", proxy=" + proxy +
", username='" + username + '\'' +
", password=" + (password == null?"null" : "'******'") +
", type=" + type +
", allowedIndicatorTypes=" + Joiner.on(',').join(allowedIndicatorTypes)+
", collection='" + collection + '\'' +
", subscriptionId='" + subscriptionId + '\'' +
", beginTime=" + beginTime +
", table=" + table + ":" + columnFamily+
'}';
}
}
| 28.058296 | 97 | 0.707368 |
33580552d3c4f2c1589acf2785c3d8af91f74b5e | 5,398 | /*
* 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.gora.pig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.gora.mapreduce.GoraRecordWriter;
import org.apache.gora.persistency.impl.PersistentBase;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.pig.ResourceSchema;
import org.apache.pig.ResourceSchema.ResourceFieldSchema;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Storage to delete rows by key.
*
* Given a relation with schema (key:chararray) rows, the following will delete
* all rows with that keys:
*
* <pre>
* STORE webpages INTO '.' USING org.apache.gora.pig.GoraDeleteStorage('{
* "persistentClass": "admin.WebPage",
* "goraProperties": "gora.datastore.default=org.apache.gora.hbase.store.HBaseStore\\ngora.datastore.autocreateschema=true\\ngora.hbasestore.scanner.caching=4",
* "mapping": {@code<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>\\n<gora-odm>\\n<table name=\\"webpage\\">\\n<family name=\\"f\\" maxVersions=\\"1\\"/>\\n</table>\\n<class table=\\"webpage\\" keyClass=\\"java.lang.String\\" name=\\"admin.WebPage\\">\\n<field name=\\"baseUrl\\" family=\\"f\\" qualifier=\\"bas\\"/>\\n<field name=\\"status\\" family=\\"f\\" qualifier=\\"st\\"/>\\n<field name=\\"content\\" family=\\"f\\" qualifier=\\"cnt\\"/>\\n</class>\\n</gora-odm>},
* "configuration": {
* "hbase.zookeeper.quorum": "hdp4,hdp1,hdp3",
* "zookeeper.znode.parent": "/hbase-unsecure"
* }
* }') ;
* </pre>
*
* @see GoraStorage
*
*/
public class GoraDeleteStorage extends GoraStorage {
public static final Logger LOG = LoggerFactory.getLogger(GoraDeleteStorage.class);
public GoraDeleteStorage(String storageConfigurationString) throws InstantiationException, IllegalAccessException, JsonParseException, JsonMappingException, IOException {
super(storageConfigurationString);
}
@Override
/**
* Checks that the Pig schema has at least the field "key" with schema chararray.
*
* Sets UDFContext property GORA_STORE_SCHEMA with the schema to send it to the backend.
*/
public void checkSchema(ResourceSchema pigSchema) throws IOException {
List<String> pigFieldSchemasNames = new ArrayList<String>(Arrays.asList(pigSchema.fieldNames())) ;
if ( !pigFieldSchemasNames.contains("key") ) {
throw new IOException("Expected a field called \"key\" but not found.") ;
}
for (ResourceFieldSchema fieldSchema: pigSchema.getFields()) {
if (fieldSchema.getName().equals("key") &&
fieldSchema.getType() != DataType.CHARARRAY )
{
throw new IOException("Expected field \"key\" with schema chararray, but found schema " + DataType.findTypeName(fieldSchema.getType()) + ".") ;
}
}
// Save the schema to UDFContext to use it on backend when writing data
this.getUDFProperties().setProperty(GoraStorage.GORA_STORE_PIG_SCHEMA, pigSchema.toString()) ;
}
/**
* If delete type = ROWS : deletes all the rows with the given keys
* If delete type = VALUES : for all fields with a name related to avro map, deletes the elements
*/
@SuppressWarnings("unchecked")
@Override
public void putNext(Tuple pigTuple) throws IOException {
String key = (String) pigTuple.get(this.pigFieldKeyIndex) ;
((GoraRecordWriter<Object,PersistentBase>) this.writer).delete(key) ;
}
/**
* Disabled method since it is used to load data with LOAD command
*/
@Override
public ResourceSchema getSchema(String location, Job job) throws IOException {
throw new IOException(this.getClass().getName() + " can not be used to load data.") ;
}
@Override
public void setLocation(String location, Job job) throws IOException {
throw new IOException(this.getClass().getName() + " can not be used to load data.") ;
}
@SuppressWarnings("rawtypes")
@Override
public void prepareToRead(RecordReader reader, PigSplit split) throws IOException {
throw new IOException(this.getClass().getName() + " can not be used to load data.") ;
}
@Override
public void setUDFContextSignature(String signature) {
throw new RuntimeException(this.getClass().getName() + " can not be used to load data.") ;
}
}
| 41.844961 | 477 | 0.709707 |
c9a1e89b23302297ca7dad52e1a3821c0d1cc436 | 390 | /**
* Start klasse
* @author Dwight Van der Velpen
*/
public class Main {
/**
* het beginpunt van deze oefening
* @param args Console argumenten
* @see Console
*/
public static void main(String[] args) {
// Console toepassing
// Console c = new Console();
// c.Start();
// Gui toepssing
GUI.main(null);
}
}
| 18.571429 | 44 | 0.530769 |
2f3a40050a84b6933506ca6dd9d98fbfbd81cc85 | 289 | package de.gg.game.events;
/**
* Is posted when the local player enters a house.
*/
public class HouseEnterEvent {
private short id;
public HouseEnterEvent(short id) {
this.id = id;
}
/**
* @return the id of the entered house.
*/
public short getId() {
return id;
}
}
| 13.136364 | 50 | 0.647059 |
b9f9ef96d24f7a3dfd27943bcfb6144790d467fa | 10,819 | package de.flingelli.weblate;
import org.mockserver.integration.ClientAndServer;
import org.testng.Assert;
import org.testng.annotations.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Set;
import static org.mockserver.model.HttpClassCallback.callback;
import static org.mockserver.model.HttpRequest.request;
public class WeblateConnectorTest {
private static final String PREFIX_URL = "http://localhost:50080/";
private ClientAndServer server;
@BeforeClass
public void startServer() throws IOException {
server = ClientAndServer.startClientAndServer(50080);
registerResponses();
}
private void registerResponses() throws IOException {
String root = new File("src/test/resources").getAbsolutePath();
Files.walk(Paths.get("src/test/resources/api")).filter(Files::isDirectory).forEach(path -> {
server.when(request().withPath(path.toFile().getAbsolutePath().substring(root.length()))).callback(callback().withCallbackClass(CommonCallback.class.getCanonicalName()));
});
}
@AfterClass
public void stopServer() {
server.stop();
}
@Test
public void getApiProjects() {
Assert.assertEquals(getConnector().getApi().getProjects(), PREFIX_URL + "api/projects/");
}
private WeblateConnector getConnector() {
return new WeblateConnector("http://localhost:50080", "password");
}
@Test
public void getApiChanges() {
Assert.assertEquals(getConnector().getApi().getChanges(), PREFIX_URL + "api/changes/");
}
@Test
public void getApiComponents() {
Assert.assertEquals(getConnector().getApi().getComponents(), PREFIX_URL + "api/components/");
}
@Test
public void getApiLanguages() {
Assert.assertEquals(getConnector().getApi().getLanguages(), PREFIX_URL + "api/languages/");
}
@Test
public void getApiScreenshots() {
Assert.assertEquals(getConnector().getApi().getScreenshots(), PREFIX_URL + "api/screenshots/");
}
@Test
public void getApiSources() {
Assert.assertEquals(getConnector().getApi().getSources(), PREFIX_URL + "api/sources/");
}
@Test
public void getApiTranslations() {
Assert.assertEquals(getConnector().getApi().getTranslations(), PREFIX_URL + "api/translations/");
}
@Test
public void getApiUnits() {
Assert.assertEquals(getConnector().getApi().getUnits(), PREFIX_URL + "api/units/");
}
@Test
public void getProjects() {
Projects projects = getConnector().getProjects();
Assert.assertEquals(projects.getCount(), 2);
}
@Test
public void getPreviousProjects() {
WeblateConnector connector = getConnector();
Projects projects = connector.getProjects();
Projects nextProjects = connector.getNextProjects(projects);
Assert.assertEquals(connector.getPreviousProjects(nextProjects), projects);
}
@Test
public void getProject() {
WeblateConnector connector = getConnector();
Project project = connector.getProject("project");
Assert.assertEquals(project.getRepository_url(), "http://127.0.0.1:8000/api/projects/hello/repository/");
}
@Test
public void getComponents() {
Components components = getConnector().getComponents();
Assert.assertEquals(components.getCount(), 2);
}
@Test
public void getPreviousComponents() {
WeblateConnector connector = getConnector();
Components nextComponents = connector.getNextComponents(connector.getComponents());
Assert.assertNull(connector.getPreviousComponents(nextComponents).getPrevious());
}
@Test
public void getComponentsOfProject() {
WeblateConnector connector = getConnector();
Components components = connector.getComponents("project");
Assert.assertEquals(components.getCount(), 1);
}
@Test
public void getComponent() {
WeblateConnector connector = getConnector();
Component component = connector.getComponent("project", "component");
Assert.assertEquals(component.getBranch(), "master");
}
@Test
public void getUnits() {
WeblateConnector connector = getConnector();
Units units = connector.getUnits();
Assert.assertEquals(units.getCount(), 1);
}
@Test
public void getPreviousUnits() {
WeblateConnector connector = getConnector();
Units nextUnits = connector.getNextUnits(connector.getUnits());
Assert.assertNull(connector.getPreviousUnits(nextUnits).getPrevious());
}
@Test
public void getLanguages() {
WeblateConnector connector = getConnector();
Languages languages = connector.getLanguages();
Assert.assertEquals(languages.getCount(), 47);
}
@Test
public void getPreviousLanguages() {
WeblateConnector connector = getConnector();
Languages languages = connector.getLanguages();
Languages nextLanguages = connector.getNextLanguages(languages);
Assert.assertEquals(connector.getPreviousLanguages(nextLanguages), languages);
}
@Test
public void getChanges() {
WeblateConnector connector = getConnector();
Changes changes = connector.getChanges();
Assert.assertEquals(changes.getCount(), 2);
}
@Test
public void getPreviousChanges() {
WeblateConnector connector = getConnector();
Changes nextChanges = connector.getNextChanges(connector.getChanges());
Assert.assertNull(connector.getPreviousChanges(nextChanges).getPrevious());
}
@Test
public void getChangesOfProject() {
WeblateConnector connector = getConnector();
Changes changes = connector.getChanges("project");
Assert.assertEquals(changes.getCount(), 2);
}
@Test
public void getChangesOfComponent() {
WeblateConnector connector = getConnector();
Changes changes = connector.getChanges("project", "component");
Assert.assertEquals(changes.getCount(), 2);
}
@Test
public void getChangesOfComponentAndLanguage() {
WeblateConnector connector = getConnector();
Changes changes = connector.getChanges("project", "component", "fr");
Assert.assertEquals(changes.getCount(), 2);
}
@Test
public void getTranslations() {
Translations translations = getConnector().getTranslations();
Assert.assertEquals(translations.getCount(), 1);
}
@Test
public void getPreviousTranslations() {
WeblateConnector connector = getConnector();
Translations nextTranslations = connector.getNextTranslations(connector.getTranslations());
Assert.assertNull(connector.getPreviousTranslations(nextTranslations).getPrevious());
}
@Test
public void getTranslationsOfComponent() {
WeblateConnector connector = getConnector();
Translations translations = connector.getTranslations("project", "component");
Assert.assertEquals(translations.getCount(), 3);
}
@Test
public void getTranslation() {
WeblateConnector connector = getConnector();
Translation translation = connector.getTranslation("project", "component", "fr");
Assert.assertEquals(translation.getFilename(), "component-translation/src/main/resources/component-gui_fr.properties");
}
@Test
public void getSources() {
WeblateConnector connector = getConnector();
Sources sources = connector.getSources();
Assert.assertEquals(sources.getCount(), 2);
}
@Test
public void getPreviousSources() {
WeblateConnector connector = getConnector();
Sources sources = connector.getSources();
Sources nextSources = connector.getNextSources(sources);
Assert.assertNull(connector.getPreviousSources(nextSources).getPrevious());
}
@Test
public void getScreenshots() {
WeblateConnector connector = getConnector();
Screenshots screenshots = connector.getScreenshots();
Assert.assertEquals(screenshots.getCount(), 0);
}
@Test
public void getPreviousScreenshots() {
WeblateConnector connector = getConnector();
Screenshots screenshots = connector.getScreenshots();
Screenshots nextScreenshots = connector.getNextScreenshots(screenshots);
Assert.assertEquals(connector.getPreviousScreenshots(nextScreenshots), screenshots);
}
@Test
public void getRepository() {
WeblateConnector connector = getConnector();
Repository repository = connector.getRepository("project", "component");
Assert.assertEquals(repository.getStatus(),
"On branch master\nYour branch is ahead of 'origin/master' by 1 commit.\n " +
"(use \"git push\" to publish your local commits)\nnothing to commit, working directory clean\n");
}
@Test
public void getLanguage() {
WeblateConnector connector = getConnector();
Language language = connector.getLanguage("fr");
Assert.assertEquals(language.getCode(), "fr");
}
@Test
public void getLock() {
WeblateConnector connector = getConnector();
Lock lock = connector.getLock("project", "component");
Assert.assertFalse(lock.isLock());
}
@Test
public void getStatistics() {
WeblateConnector connector = getConnector();
Statistics statistics = connector.getStatistics("project", "component");
Assert.assertEquals(statistics.getResults().get(0).getLast_author(), "Markus");
}
@Test
public void getPreviousStatistics() {
WeblateConnector connector = getConnector();
Statistics statistics = connector.getStatistics("project", "component");
Statistics nextStatistcs = connector.getNextStatistics(statistics);
Assert.assertEquals(connector.getPreviousStatistics(nextStatistcs), statistics);
}
@Test
public void getComponentsChangedAfter() throws ParseException {
WeblateConnector connector = getConnector();
Set<String> components = connector.getComponentsChangedAfter("project", new SimpleDateFormat("dd-MM-yyyy").parse("01-06-2017"));
Assert.assertFalse(components.isEmpty());
}
@Test
public void getComponentsLanguageChangedAfter() throws ParseException {
WeblateConnector connector = getConnector();
Set<String> components = connector.getComponentsChangedAfter("project", "fr", new SimpleDateFormat("dd-MM-yyyy").parse("01-06-2017"));
Assert.assertFalse(components.isEmpty());
}
}
| 35.356209 | 182 | 0.682688 |
928ff912ed336dda2b91e8b69348ea12b8e7ebcc | 15,662 | package org.ff4j.cassandra.store;
/*
* #%L
* ff4j-store-cassandra
* %%
* Copyright (C) 2013 - 2020 FF4J
* %%
* 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.
* #L%
*/
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.literal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.ff4j.cassandra.FF4jCassandraSchema;
import org.ff4j.core.Feature;
import org.ff4j.core.FeatureStore;
import org.ff4j.core.FlippingStrategy;
import org.ff4j.exception.FeatureNotFoundException;
import org.ff4j.property.Property;
import org.ff4j.property.util.PropertyFactory;
import org.ff4j.store.AbstractFeatureStore;
import org.ff4j.utils.MappingUtil;
import org.ff4j.utils.Util;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.BatchStatement;
import com.datastax.oss.driver.api.core.cql.BatchStatementBuilder;
import com.datastax.oss.driver.api.core.cql.BatchType;
import com.datastax.oss.driver.api.core.cql.BoundStatement;
import com.datastax.oss.driver.api.core.cql.PreparedStatement;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.data.UdtValue;
import com.datastax.oss.driver.api.core.type.UserDefinedType;
import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
import com.datastax.oss.driver.shaded.guava.common.base.Functions;
/**
* Implementation of {@link FeatureStore} to work with Cassandra Storage.
*
* Minimize the Number of Writes :
* Writes in Cassandra aren’t free, but they’re awfully cheap. Cassandra is optimized for high write throughput,
* and almost all writes are equally efficient [1]. If you can perform extra writes to improve the efficiency of
* your read queries, it’s almost always a good tradeoff. Reads tend to be more expensive and are much more
* difficult to tune.
*
* Minimize Data Duplication
* Denormalization and duplication of data is a fact of life with Cassandra. Don’t be afraid of it. Disk space
* is generally the cheapest resource (compared to CPU, memory, disk IOPs, or network), and Cassandra is
* architected around that fact. In order to get the most efficient reads, you often need to duplicate data.
*
* @author Cedrick Lunven (@clunven)
*/
public class FeatureStoreCassandra extends AbstractFeatureStore implements FF4jCassandraSchema {
/** Driver Session. */
private CqlSession cqlSession;
/** udt. */
private UserDefinedType udtStrategy;
private UserDefinedType udtProperty;
/** Statements. */
private PreparedStatement psExistFeature;
private PreparedStatement psToggleFeature;
private PreparedStatement psInsertFeature;
private PreparedStatement psDeleteFeature;
private PreparedStatement psReadFeature;
private PreparedStatement psReadGroup;
private PreparedStatement psAddToGroup;
private PreparedStatement psRmvFromGroup;
private PreparedStatement psListGroups;
/**
* Default constructor.
*/
public FeatureStoreCassandra() {}
/**
* Connector with running session
*/
public FeatureStoreCassandra(CqlSession cqlSession) {
this.cqlSession = cqlSession;
}
/** {@inheritDoc} */
@Override
public void createSchema() {
cqlSession.execute(STMT_CREATE_UDT_STRATEGY);
cqlSession.execute(STMT_CREATE_UDT_PROPERTY);
cqlSession.execute(STMT_CREATE_TABLE_FEATURE);
cqlSession.execute(STMT_CREATE_INDEX_FEATUREGROUP);
}
/** {@inheritDoc} */
@Override
public boolean exist(String uid) {
Util.assertHasLength(uid);
return getCqlSession().execute(psExistFeature.bind(uid))
.getAvailableWithoutFetching() > 0;
}
/** {@inheritDoc} */
@Override
public void enable(String uid) {
assertFeatureExist(uid);
getCqlSession().execute(psToggleFeature.bind(true, uid));
}
/** {@inheritDoc} */
@Override
public void disable(String uid) {
assertFeatureExist(uid);
getCqlSession().execute(psToggleFeature.bind(false, uid));
}
/** {@inheritDoc} */
@Override
public void create(Feature fp) {
assertFeatureNotNull(fp);
assertFeatureNotExist(fp.getUid());
BoundStatement bsInsertFeature = psInsertFeature.bind();
bsInsertFeature = bsInsertFeature.setString(FEATURES_ATT_UID, fp.getUid());
bsInsertFeature = bsInsertFeature.setBoolean(FEATURES_ATT_ENABLED, fp.isEnable());
bsInsertFeature = bsInsertFeature.setString(FEATURES_ATT_DESCRIPTION, fp.getDescription());
if (Util.hasLength(fp.getGroup())) {
bsInsertFeature = bsInsertFeature.setString(FEATURES_ATT_GROUPNAME, fp.getGroup());
}
if (null != fp.getPermissions()) {
bsInsertFeature = bsInsertFeature.setSet(FEATURES_ATT_ROLES, fp.getPermissions(), String.class);
}
if (null != fp.getFlippingStrategy()) {
UdtValue newUdtStrategy = udtStrategy.newValue();
FlippingStrategy fStrategy = fp.getFlippingStrategy();
newUdtStrategy.setString(UDT_STRATEGY_CLASS, fStrategy.getClass().getName());
newUdtStrategy.setMap(UDT_STRATEGY_PARAMS, fStrategy.getInitParams(), String.class, String.class);
bsInsertFeature = bsInsertFeature.setUdtValue(FEATURES_ATT_STRATEGY, newUdtStrategy);
}
if (null != fp.getCustomProperties()) {
Map<String, UdtValue> properties = new HashMap<>();
for (Property<?> prop : fp.getCustomProperties().values()) {
UdtValue currentUdtProp = udtProperty.newValue();
currentUdtProp.setString(UDT_PROPERTY_UID, prop.getName());
currentUdtProp.setString(UDT_PROPERTY_CLASS, prop.getClass().getName());
currentUdtProp.setString(UDT_PROPERTY_DESCRIPTION, prop.getDescription());
currentUdtProp.setString(UDT_PROPERTY_VALUE, prop.asString());
Set <String> fixedValues = new HashSet<>();
if (!Util.isEmpty(prop.getFixedValues())) {
for (Object fv : prop.getFixedValues()) {
fixedValues.add(fv.toString());
}
}
currentUdtProp.setSet(UDT_PROPERTY_FIXEDVALUES, fixedValues, String.class);
properties.put(prop.getName(), currentUdtProp);
}
bsInsertFeature = bsInsertFeature.setMap(FEATURES_ATT_PROPERTIES, properties, String.class, UdtValue.class);
}
getCqlSession().execute(bsInsertFeature);
}
/** {@inheritDoc} */
@Override
public void delete(String uid) {
assertFeatureExist(uid);
getCqlSession().execute(psDeleteFeature.bind(uid));
}
/** {@inheritDoc} */
@Override
public Feature read(String uid) {
Util.assertHasLength(uid);
ResultSet rs = cqlSession.execute(psReadFeature.bind(uid));
Row row = rs.one();
if (null == row) {
throw new FeatureNotFoundException(uid);
}
return mapFeatureRow(row);
}
/** {@inheritDoc} */
@Override
public Map<String, Feature> readAll() {
Map < String, Feature> features = new HashMap<String, Feature>();
ResultSet rs = cqlSession.execute(STMT_FEATURE_READ_ALL);
for (Row row : rs.all()) {
features.put(row.getString(FEATURES_ATT_UID), mapFeatureRow(row));
}
return features;
}
/** {@inheritDoc} */
@Override
public void update(Feature fp) {
assertFeatureNotNull(fp);
assertFeatureExist(fp.getUid());
delete(fp.getUid());
create(fp);
}
/** {@inheritDoc} */
@Override
public void grantRoleOnFeature(String uid, String roleName) {
assertFeatureExist(uid);
Util.assertHasLength(roleName);
getCqlSession().execute(QueryBuilder.update(FEATURES_TABLE)
.appendSetElement(FEATURES_ATT_ROLES, literal(roleName))
.whereColumn(FEATURES_ATT_UID).isEqualTo(literal(uid))
.build());
}
/** {@inheritDoc} */
@Override
public void removeRoleFromFeature(String uid, String roleName) {
assertFeatureExist(uid);
Util.assertHasLength(roleName);
getCqlSession().execute(QueryBuilder.update(FEATURES_TABLE)
.removeSetElement(FEATURES_ATT_ROLES, literal(roleName))
.whereColumn(FEATURES_ATT_UID).isEqualTo(literal(uid))
.build());
}
/*
* Unfortunately no way to apply update on multiple features in 1 call.
* We go N+1 select, we can still group in a batch statement.
*/
@Override
public void enableGroup(String groupName) {
assertGroupExist(groupName);
BatchStatementBuilder stmtBatch = BatchStatement.builder(BatchType.LOGGED);
readGroup(groupName).values()
.stream().map(Feature::getUid)
.forEach(uid -> stmtBatch.addStatement(psToggleFeature.bind(true, uid)));
getCqlSession().execute(stmtBatch.build());
}
/** {@inheritDoc} */
@Override
public void disableGroup(String groupName) {
assertGroupExist(groupName);
BatchStatementBuilder stmtBatch = BatchStatement.builder(BatchType.LOGGED);
readGroup(groupName).values().stream()
.map(Feature::getUid)
.forEach(uid -> stmtBatch.addStatement(psToggleFeature.bind(false, uid)));
getCqlSession().execute(stmtBatch.build());
}
/** {@inheritDoc} */
@Override
public boolean existGroup(String groupName) {
Util.assertHasLength(groupName);
return getCqlSession().execute(psReadGroup.bind(groupName))
.getAvailableWithoutFetching() > 0;
}
/** {@inheritDoc} */
@Override
public Map<String, Feature> readGroup(String groupName) {
assertGroupExist(groupName);
return getCqlSession().execute(psReadGroup.bind(groupName))
.all().stream().map(this::mapFeatureRow)
.collect(Collectors.toMap(Feature::getUid, Functions.identity()));
}
/** {@inheritDoc} */
@Override
public void addToGroup(String uid, String groupName) {
assertFeatureExist(uid);
Util.assertHasLength(groupName);
getCqlSession().execute(psAddToGroup.bind(groupName, uid));
}
/** {@inheritDoc} */
@Override
public void removeFromGroup(String uid, String groupName) {
assertFeatureExist(uid);
assertGroupExist(groupName);
Feature feat = read(uid);
if (feat.getGroup() != null && !feat.getGroup().equals(groupName)) {
throw new IllegalArgumentException("'" + uid + "' is not in group '" + groupName + "'");
}
getCqlSession().execute(psRmvFromGroup.bind(uid));
}
/** {@inheritDoc} */
@Override
public Set<String> readAllGroups() {
List < Row> rows = cqlSession.execute(psListGroups.bind()).all();
Set<String> groupNames = new HashSet<>();
if (null != rows) {
rows.stream()
.map(r -> r.getString(FEATURES_ATT_GROUPNAME))
.forEach(groupNames::add);
}
groupNames.remove(null);
groupNames.remove("");
return groupNames;
}
/** {@inheritDoc} */
@Override
public void clear() {
getCqlSession().execute(QueryBuilder.truncate(FEATURES_TABLE).build());
}
/**
* Prepared once, run many.
*/
protected void prepareStatements() {
// udt
udtStrategy = cqlSession.getMetadata()
.getKeyspace(cqlSession.getKeyspace().get())
.flatMap(ks -> ks.getUserDefinedType(UDT_STRATEGY))
.orElseThrow(() -> new IllegalArgumentException("Missing UDT '" + UDT_STRATEGY + "'"));
udtProperty = cqlSession.getMetadata()
.getKeyspace(cqlSession.getKeyspace().get())
.flatMap(ks -> ks.getUserDefinedType(UDT_PROPERTY))
.orElseThrow(() -> new IllegalArgumentException("Missing UDT '" + UDT_PROPERTY + "'"));
// Prepared Statements
psReadFeature = cqlSession.prepare(STMT_FEATURE_READ);
psExistFeature = cqlSession.prepare(STMT_FEATURE_EXIST);
psToggleFeature = cqlSession.prepare(STMT_FEATURE_TOGGLE);
psInsertFeature = cqlSession.prepare(STMT_FEATURE_INSERT);
psDeleteFeature = cqlSession.prepare(STMT_FEATURE_DELETE);
psReadGroup = cqlSession.prepare(STMT_FEATUREGROUP_READ);
psAddToGroup = cqlSession.prepare(STMT_FEATURE_ADDTOGROUP);
psRmvFromGroup = cqlSession.prepare(STMT_FEATURE_REMOVEGROUP);
psListGroups = cqlSession.prepare(STMT_FEATUREGROUP_LIST);
}
protected Feature mapFeatureRow(Row row) {
Feature f = new Feature(row.getString(FEATURES_ATT_UID));
f.setDescription(row.getString(FEATURES_ATT_DESCRIPTION));
f.setEnable(row.getBoolean(FEATURES_ATT_ENABLED));
f.setGroup(row.getString(FEATURES_ATT_GROUPNAME));
f.setPermissions(row.getSet(FEATURES_ATT_ROLES, String.class));
// Flipping Strategy
UdtValue udtStrat = row.getUdtValue(FEATURES_ATT_STRATEGY);
if (null != udtStrat) {
String className = udtStrat.getString(UDT_STRATEGY_CLASS);
Map <String, String > initparams = udtStrat.getMap(UDT_STRATEGY_PARAMS,String.class, String.class);
f.setFlippingStrategy(MappingUtil.instanceFlippingStrategy(f.getUid(), className, initparams));
}
// Custom Properties
Map <String, UdtValue> mapOfProperties = row.getMap(FEATURES_ATT_PROPERTIES, String.class, UdtValue.class);
if (mapOfProperties != null) {
Map < String, Property<?>> customProperties = new HashMap<String, Property<?>>();
for(UdtValue udt : mapOfProperties.values()) {
String propName = udt.getString(UDT_PROPERTY_UID);
String propClass = udt.getString(UDT_PROPERTY_CLASS);
String propDesc = udt.getString(UDT_PROPERTY_DESCRIPTION);
String propVal = udt.getString(UDT_PROPERTY_VALUE);
Set<String> fixV = udt.getSet(UDT_PROPERTY_FIXEDVALUES, String.class);
Property<?> p = PropertyFactory.createProperty(propName, propClass, propVal, propDesc, fixV);
customProperties.put(p.getName(), p);
}
f.setCustomProperties(customProperties);
}
return f;
}
/**
* Prepared statements on first call.
*/
private synchronized CqlSession getCqlSession() {
if (null == psExistFeature) {
prepareStatements();
}
return cqlSession;
}
}
| 39.954082 | 120 | 0.655408 |
6b14d427912e88a24e67f0be1911b55621aed0e6 | 8,560 | package Model;
import configuration.GetPropertyValues;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Rodrigo Araujo
*
* Purpose: A class that extends the abstract simulation
* class and implements the rules to create the Rock,
* Paper, Scissors simulation.
*
* Assumptions: Typically, negative values would cause
* the simulation method to fail; however, we catch
* negative values and print out an error. Besides that,
* inputting the wrong values would cause the simulation
* class to fail.
*
* Dependencies: This subclass is dependent on the abstract
* simulation class.
*
* Example:
*
* RPSSIM exSim = new RPSSIM(30, 30, params);
*
*/
public class RPSSim extends Simulation{
private GetPropertyValues properties = new GetPropertyValues();
private double percentRock;
private double percentScissors;
private int defaultThreshold;
// private String boundary = properties.getPropValues("boundary");
private RPSCell[][] rpsGrid;
/**
* Purpose: RPSSim constructor that defines variables
* to be used.
*
* Assumptions: Inputting the wrong values would cause it
* to fail.
*
* Return: N/A
*/
public RPSSim(int width, int height, HashMap<String, Double> params) {
super((int)(params.get("grid_height")*10)/10,(int)(params.get("grid_width")*10/10), width,height, params);
initParams();
createGrid(getRows(), getCols());
setUpHashMap();
setName("rps");
}
/**
* Purpose: RPSSim constructor that defines variables
* to be used and allows user to load a past simulation.
*
* Assumptions: Inputting the wrong values would cause it
* to fail.
*
* Return: N/A
*/
public RPSSim(int width, int height, HashMap<String,Double> params, Simulation sim){
super((int)(params.get("grid_height")*10)/10,(int)(params.get("grid_width")*10/10), width,height, params);
initParams();
createGridFromAnotherSim(sim);
initRPSGridFromFile(getRows(),getCols());
setUpHashMap();
setName("rps");
}
/**
* Purpose: Method to set the starting configuration values
* for the simulation.
*
* Assumptions: Calling this method on an object that is not
* of the subclass simulation would cause it to fail.
*
* Return: N/A
*/
public void initParams() {
defaultThreshold = (int) (getParams().get("threshold") * 10) / 10;
percentRock = getParams().get("percentRock");
percentScissors = getParams().get("percentScissors");
initAddToAgentNumberMap("rock");
initAddToAgentNumberMap("paper");
initAddToAgentNumberMap("scissor");
}
/**
* Purpose: Method to create 2D array of cell objects grid by using
* setCell to set the values by cell location.
*
* Assumptions: Inputting the wrong values would cause it
* to fail.
*
* Return: N/A
*/
public void createGrid(int rows, int cols) {
rpsGrid = new RPSCell[rows][cols];
for (int i = 0; i < getRows(); i++) {
for (int j = 0; j < getCols(); j++) {
double choice = Math.random();
if (choice <= percentRock) {
rpsGrid[i][j] = new RPSCell(i, j, "rock", defaultThreshold);
rpsGrid[i][j].setNextState(rpsGrid[i][j]);
setCell(i, j, "rock");
}
else if (choice <= percentRock + percentScissors) {
rpsGrid[i][j] = new RPSCell(i, j, "scissor", defaultThreshold);
rpsGrid[i][j].setNextState(rpsGrid[i][j]);
setCell(i, j, "scissor");
}
else {
rpsGrid[i][j] = new RPSCell(i, j, "paper", defaultThreshold);
rpsGrid[i][j].setNextState(rpsGrid[i][j]);
setCell(i, j, "paper");
}
}
}
}
private void initRPSGridFromFile(int rows, int cols) {
rpsGrid = new RPSCell[rows][cols];
for (int i = 0; i < getRows(); i++) {
for (int j = 0; j < getCols(); j++) {
if (getCell(i,j).equals("rock")) {
rpsGrid[i][j] = new RPSCell(i, j, "rock", defaultThreshold);
rpsGrid[i][j].setNextState(rpsGrid[i][j]);
}
else if (getCell(i,j).equals("scissor")) {
rpsGrid[i][j] = new RPSCell(i, j, "scissor", defaultThreshold);
rpsGrid[i][j].setNextState(rpsGrid[i][j]);
}
else {
rpsGrid[i][j] = new RPSCell(i, j, "paper", defaultThreshold);
rpsGrid[i][j].setNextState(rpsGrid[i][j]);
}
}
}
}
/**
* Purpose: Method to update the individual cells in the
* 2D array of cell objects grid by using updateCell, which contains
* the game rules, to set the string value by cell location.
*
* Assumptions: Calling this method on an object that is not
* of the subclass simulation would cause it to fail.
*
* Return: N/A
*/
public void updateGrid() {
resetAgentNumbers();
for (int i = 0; i < getRows(); i++) {
for (int j = 0; j < getCols(); j++) {
rpsGrid[i][j] = rpsGrid[i][j].getNextState();
rpsGrid[i][j].setNextState(null);
}
}
for (int i = 0; i < getRows(); i++) {
for (int j = 0; j < getCols(); j++) {
updateCell(rpsGrid[i][j]);
}
}
updateStringArray();
countAgentNumbers();
}
/**
* Purpose: Method that contains the rules to
* update the cells by.
*
* Assumptions: Inputting the wrong values would cause it
* to fail or calling this method on an object that is not
* of the subclass simulation would cause it to fail.
*
* Return: N/A
*/
public void updateCell(RPSCell input) {
if (input.getName().equals("rock")) {
updateRock(input);
}
else if (input.getName().equals("scissor")) {
updateScissor(input);
}
else {
updatePaper(input);
}
}
private void updateRock(RPSCell input) {
int paper = neighborFilter(input, "paper");
if (paper >= defaultThreshold) {
input.setNextState(new RPSCell(input.x, input.y, "paper", defaultThreshold));
}
else {
input.setNextState(new RPSCell(input.x, input.y, "rock", defaultThreshold));
}
}
private void updateScissor(RPSCell input) {
int rock = neighborFilter(input, "rock");
if (rock >= defaultThreshold) {
input.setNextState(new RPSCell(input.x, input.y, "rock", defaultThreshold));
}
else {
input.setNextState(new RPSCell(input.x, input.y, "scissor", defaultThreshold));
}
}
private void updatePaper(RPSCell input) {
int scissor = neighborFilter(input, "scissor");
if (scissor >= defaultThreshold) {
input.setNextState(new RPSCell(input.x, input.y, "scissor", defaultThreshold));
}
else {
input.setNextState(new RPSCell(input.x, input.y, "paper", defaultThreshold));
}
}
private int neighborFilter(RPSCell input, String name) {
int result = 0;
ArrayList<RPSCell> neighbors = new ArrayList<>();
neighbors = input.get8NeighborsFinite(input.x, input.y, rpsGrid, neighbors);
for (RPSCell n : neighbors) {
if (n.getName().equals(name)) {
result++;
}
}
return result;
}
/**
* Purpose: Method that updates the updates the color scheme
* for different cell names.
*
* Assumptions: Calling this method on an object that is not
* of the subclass simulation would cause it to fail.
*
* Return: N/A
*/
public void setUpHashMap() {
createColorMap(new HashMap<>());
addToColorMap("rock", "red");
addToColorMap("paper", "blue");
addToColorMap("scissor", "yellow");
}
private void updateStringArray() {
for (int i = 0; i < getRows(); i++) {
for (int j = 0; j < getCols(); j++) {
setCell(i, j, rpsGrid[i][j].getName());
}
}
}
}
| 32.059925 | 114 | 0.556659 |
bdfdfbe0fd83157a5fc92f47a86ec1c7c8f1ccd5 | 1,689 | package org.mockserver.model;
import org.junit.Test;
import org.mockserver.collections.CaseInsensitiveRegexHashMap;
import java.util.Arrays;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockserver.model.NottableString.not;
import static org.mockserver.model.NottableString.string;
public class KeyAndValueTest {
@Test
public void shouldConvertToHashMap() {
// given
Cookie cookie = new Cookie("name", "value");
// when
CaseInsensitiveRegexHashMap hashMap = KeyAndValue.toHashMap(cookie);
// then
assertThat(hashMap.get(string("name")), is(string("value")));
}
@Test
public void shouldConvertNottedCookieToHashMap() {
// given
Cookie nottedCookie = new Cookie(not("name"), not("value"));
// when
CaseInsensitiveRegexHashMap hashMap = KeyAndValue.toHashMap(nottedCookie);
// then
assertThat(hashMap.get(not("name")), is(not("value")));
}
@Test
public void shouldConvertListOfNottableCookiesToHashMap() {
// given
Cookie firstNottedCookie = new Cookie(not("name_one"), not("value_one"));
Cookie secondCookie = new Cookie(string("name_two"), string("value_two"));
// when
CaseInsensitiveRegexHashMap hashMap = KeyAndValue.toHashMap(
Arrays.asList(
firstNottedCookie,
secondCookie
)
);
// then
assertThat(hashMap.get(not("name_one")), is(not("value_one")));
assertThat(hashMap.get(string("name_two")), is(string("value_two")));
}
} | 29.12069 | 82 | 0.639432 |
2e51d54e2f60466f2fadfebde0c4cc100cfe98e4 | 2,314 | package com.zup.mercadolivre.product.controller;
import com.zup.mercadolivre.mailing.Mailing;
import com.zup.mercadolivre.product.controller.request.ProductQuestionRequest;
import com.zup.mercadolivre.product.controller.response.ProductQuestionResponse;
import com.zup.mercadolivre.product.model.Product;
import com.zup.mercadolivre.product.model.ProductQuestion;
import com.zup.mercadolivre.user.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/product/{id}/question")
public class ProductQuestionController {
@PersistenceContext
private EntityManager manager;
@Autowired
private Mailing mailing;
@PostMapping
@Transactional
public ResponseEntity<List<ProductQuestionResponse>> create(@PathVariable("id") Long idProduct,
@RequestBody @Valid ProductQuestionRequest request,
@AuthenticationPrincipal UserDetails loggedUser) {
User user = (User) loggedUser;
Product product = manager.find(Product.class, idProduct);
if (product == null) {
return ResponseEntity.notFound().build();
}
ProductQuestion productQuestion = request.toModel(product,user);
manager.persist(productQuestion);
mailing.send("Dúvida sobre produto", productQuestion.getCustomer(), product.getOwnerEmail(), productQuestion.getTitle());
List<ProductQuestionResponse> questions = manager.createQuery("select q from ProductQuestion q where q.product = :product", ProductQuestion.class)
.setParameter("product", product)
.getResultList()
.stream()
.map(ProductQuestionResponse::new)
.collect(Collectors.toList());
return ResponseEntity.ok(questions);
}
}
| 37.934426 | 154 | 0.73293 |
041e73638a8b8f131c900b0150811142b9221622 | 2,616 | package dev.xdark.ssvm.natives;
import dev.xdark.ssvm.VirtualMachine;
import dev.xdark.ssvm.api.VMInterface;
import dev.xdark.ssvm.execution.Result;
import dev.xdark.ssvm.mirror.InstanceJavaClass;
import dev.xdark.ssvm.util.VMHelper;
import dev.xdark.ssvm.value.Value;
import lombok.experimental.UtilityClass;
/**
* Initializes java/security/AccessController.
*
* @author xDark
*/
@UtilityClass
public class AccessControllerNatives {
/**
* @param vm VM instance.
*/
public void init(VirtualMachine vm) {
VMInterface vmi = vm.getInterface();
InstanceJavaClass accController = (InstanceJavaClass) vm.findBootstrapClass("java/security/AccessController");
vmi.setInvoker(accController, "getStackAccessControlContext", "()Ljava/security/AccessControlContext;", ctx -> {
// TODO implement?
ctx.setResult(vm.getMemoryManager().nullValue());
return Result.ABORT;
});
vmi.setInvoker(accController, "doPrivileged", "(Ljava/security/PrivilegedAction;)Ljava/lang/Object;", ctx -> {
Value action = ctx.getLocals().load(0);
VMHelper helper = vm.getHelper();
helper.checkNotNull(action);
Value result = helper.invokeVirtual("run", "()Ljava/lang/Object;", new Value[0], new Value[]{
action
}).getResult();
ctx.setResult(result);
return Result.ABORT;
});
vmi.setInvoker(accController, "doPrivileged", "(Ljava/security/PrivilegedExceptionAction;)Ljava/lang/Object;", ctx -> {
Value action = ctx.getLocals().load(0);
VMHelper helper = vm.getHelper();
helper.checkNotNull(action);
Value result = helper.invokeVirtual("run", "()Ljava/lang/Object;", new Value[0], new Value[]{
action
}).getResult();
ctx.setResult(result);
return Result.ABORT;
});
vmi.setInvoker(accController, "doPrivileged", "(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;", ctx -> {
Value action = ctx.getLocals().load(0);
VMHelper helper = vm.getHelper();
helper.checkNotNull(action);
Value result = helper.invokeVirtual("run", "()Ljava/lang/Object;", new Value[0], new Value[]{
action
}).getResult();
ctx.setResult(result);
return Result.ABORT;
});
vmi.setInvoker(accController, "doPrivileged", "(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;", ctx -> {
Value action = ctx.getLocals().load(0);
VMHelper helper = vm.getHelper();
helper.checkNotNull(action);
Value result = helper.invokeVirtual("run", "()Ljava/lang/Object;", new Value[0], new Value[]{
action
}).getResult();
ctx.setResult(result);
return Result.ABORT;
});
}
}
| 36.333333 | 157 | 0.716743 |
51f9f858f49c68c3228171e6a1ddba07aea554d0 | 495 | package net.onrc.onos.core.util.distributed.sharedlog;
import com.google.common.annotations.Beta;
/**
* Listener interface for SharedLogObject consumer.
*/
@Beta
public interface LogEventListener {
// TODO Whether to expose logValue is TBD
// if exposed, one may manually apply logValue without going through runtime
/**
* Notification for .
*
* @param seq updated log entry sequence number
*/
public void logAdded(SeqNum seq/*, ByteValue logValue*/);
}
| 24.75 | 80 | 0.707071 |
b643fc2f5503fe5a12d69c6bd4cd2bc27631e957 | 8,185 | package com.haoji.haoji.video.record.weight;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import com.haoji.haoji.video.HeyhouPlayerRender;
import com.haoji.haoji.video.HeyhouPlayerService;
import com.haoji.haoji.video.VideoPlayListener;
import com.haoji.haoji.video.VideoTimeType;
/**
* Created by lky on 2017/6/26.
*/
public class SpecialEffectsPlayView extends GLSurfaceView implements VideoPlayListener {
private Handler mHandler;
private SurfaceHolder mSurfaceHolder;
private HeyhouPlayerService mService;
private boolean isPause = false;
private String mVideoPath;
private boolean isLooping;
private boolean isNeedCallBackFinish;
private SpecialEffectsPlayViewListener mSpecialEffectsPlayViewListener;
private boolean isResetNeedPlay = true;
private HeyhouPlayerRender mHeyhouPlayerRender;
public SpecialEffectsPlayView(Context context) {
this(context,null);
}
public SpecialEffectsPlayView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
setEGLContextClientVersion(2);
mSurfaceHolder = getHolder();
mService = HeyhouPlayerService.instance;
mHeyhouPlayerRender = new HeyhouPlayerRender(context,this);
// mHeyhouPlayerRender.setRotation(Rotation.ROTATION_90);
setRenderer(mHeyhouPlayerRender);
// mSurfaceHolder.addCallback(this);
mHandler = new Handler();
}
public void setSpecialEffectsPlayViewListener(SpecialEffectsPlayViewListener specialEffectsPlayViewListener) {
mSpecialEffectsPlayViewListener = specialEffectsPlayViewListener;
}
public void setNeedCallBackFinish(boolean needCallBackFinish) {
isNeedCallBackFinish = needCallBackFinish;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
super.surfaceCreated(holder);
//m.attachSurface(holder.getSurface());
mService.attachRender(mHeyhouPlayerRender);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
super.surfaceChanged(holder,format,width,height);
// Log.d(TAG,"surface changed +++++++++++");
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
super.surfaceDestroyed(holder);
// Log.d(TAG,"surface destroyed +++++++++++");
//m.detachSurface();
// mService.detachRender();
if(mHeyhouPlayerRender != null){
mService.detachRender();
}
}
// @Override
// public void surfaceCreated(SurfaceHolder holder) {
//// mService.attachSurface(holder.getSurface());
//// mService.attachRender(new r);
// }
//
// @Override
// public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
//
// }
//
// @Override
// public void surfaceDestroyed(SurfaceHolder holder) {
// mService.detachSurface();
// }
public void setLooping(boolean looping) {
isLooping = looping;
}
public void stop(){
isPause = false;
mService.stopM();
}
public void destroyRender(){
if(mHeyhouPlayerRender != null){
mHeyhouPlayerRender.destroy();
mHeyhouPlayerRender = null;
mService.detachRender();
}
}
public void setFilter(int filter){
mService.setFilter(filter);
}
public void pause(){
if(mService.isPlaying()){
mService.pause();
isPause = true;
}
}
public void play(){
if(isPause && !mService.isPlaying()){
mService.resumeM();
}else if(!TextUtils.isEmpty(mVideoPath)){
mService.prepareM(mVideoPath);
}
}
public void changeState(){
if(mService.isPlaying()){
pause();
}else{
play();
}
}
public void setVideoPath(String videoPath){
isResetNeedPlay = true;
isPause = false;
mVideoPath = videoPath;
play();
}
public void setVideoPathNotPlay(String videoPath){
isResetNeedPlay = false;
mVideoPath = videoPath;
mService.prepareM(mVideoPath);
}
public void setSpeed(VideoTimeType videoTimeType){
mService.setSpeed(videoTimeType.getValue());
}
public long getDuration(){
return mService.getDuration();
}
public void seekTo(long position){
mService.setPosition(position);
}
@Override
public void onBufferingEvent(float percentage) {
}
@Override
public void onPrepareEvent() {
mService.playM();
if(!isResetNeedPlay){
isResetNeedPlay = true;
mService.pauseM();
mService.setPosition(0);
isPause = true;
}
mHandler.post(new Runnable() {
@Override
public void run() {
if(mSpecialEffectsPlayViewListener != null){
mSpecialEffectsPlayViewListener.onPrepare(mService.getDuration()/1000);
}
}
});
}
@Override
public void onPlayEvent() {
mHandler.post(new Runnable() {
@Override
public void run() {
if(mSpecialEffectsPlayViewListener != null){
mSpecialEffectsPlayViewListener.onPlay();
}
}
});
}
@Override
public void onPauseEvent() {
mHandler.post(new Runnable() {
@Override
public void run() {
if(mSpecialEffectsPlayViewListener != null){
mSpecialEffectsPlayViewListener.onPause();
}
}
});
}
@Override
public void onResumeEvent() {
mHandler.post(new Runnable() {
@Override
public void run() {
if(mSpecialEffectsPlayViewListener != null){
mSpecialEffectsPlayViewListener.onPlay();
}
}
});
}
@Override
public void onStopEvent() {
mHandler.post(new Runnable() {
@Override
public void run() {
if(mSpecialEffectsPlayViewListener != null){
mSpecialEffectsPlayViewListener.onStop();
}
}
});
}
@Override
public void onEndEvent() {
mHandler.post(new Runnable() {
@Override
public void run() {
if(isLooping && !TextUtils.isEmpty(mVideoPath)){
mService.prepareM(mVideoPath);
if(isNeedCallBackFinish){
if(mSpecialEffectsPlayViewListener != null){
mSpecialEffectsPlayViewListener.onFinish();
}
}
}else{
if(mSpecialEffectsPlayViewListener != null){
mSpecialEffectsPlayViewListener.onFinish();
}
}
}
});
}
@Override
public void onErrorEvent(String msg) {
mHandler.post(new Runnable() {
@Override
public void run() {
// ToastTool.showShort(AppUtil.getApplicationContext(), R.string.tidal_pat_upload_play_error);
}
});
}
@Override
public void onPlayTimeEvent(final long time) {
mHandler.post(new Runnable() {
@Override
public void run() {
if(mSpecialEffectsPlayViewListener != null){
mSpecialEffectsPlayViewListener.onPlayTime(time/1000);
}
}
});
}
public interface SpecialEffectsPlayViewListener{
void onPrepare(long timeDuration);
void onPlayTime(long time);
void onPause();
void onPlay();
void onStop();
void onFinish();
}
}
| 25.738994 | 114 | 0.58595 |
3313125a5b57fe83599d219394a7b763c309fd43 | 56 | /**
* 枚举类
*/
package com.baomidou.hibernateplus.enums; | 14 | 41 | 0.696429 |
7ca5fa5b7c028ac452bfc8faa72ae9af42ff3087 | 6,699 | public enum Op
{
SuccessfullyRegistered, // Registrazione avvenuta con successo
SuccessfullyLoggedIn, // Login avvenuto con successo
SuccessfullyLoggedOut, // Logout avvenuto con successo
SuccessfullyCreated, // Creazione documento avvenuta con successo
SuccessfullyShared, // Condivisione documento avvenuta con successo
SuccessfullyShown, // Visualizzazione avvenuta con successo
SuccessfullyRemovedSession, // Sessione rimossa con successo
SuccessfullyReceivedSections,// Tutte le sezioni richieste sono state ricevute
// con successo
SuccessfullyReceivedList, // Lista ricevuta con successo
SuccessfullyListed, // Lista visualizzata con successo
SuccessfullyStartedEditing, // Inizio editing sezione avvenuto con successo
SuccessfullyEndedEditing, // Fine editing sezione avvenuto con successo
SuccessfullySentSection, // Invio sezione avvenuta con successo
SuccessfullySentMessage, // Invio messaggio avvenuto con successo
SuccessfullyReceivedMessage,// Ricezione messaggio avvenuta con successo
SuccessfullyShownHelp, // Messaggio di Help visualizzato con successo
SuccessfullyPrintedEditing, // Messaggio di sezione modificata attualmente
// visualizzato con successo
WrongPassword, // Password non corretta
UserDoesNotExists, // L'utente non esiste
NicknameAlreadyExists, // Esiste già l'utente
DocumentAlreadyExists, // Esiste già il documento
DirectoryAlreadyExists, // Esiste già la cartella
NotDocumentCreator, // L'utente non è il creatore del documento
NotDocumentCreatorNorCollaborator, // L'utente non è né il creatore del
// documento, né un collaboratore
SectionUnderModification, // La sezione è attualmente sotto modifica
Login, // Operazione di Login TCP
Logout, // Operazione di Logout TCP
Create, // Operazione di creazione di un documento
Share, // Operazione di condivisione di un documento
Show, // Operazione di visualizzazione di una sezione
// o dell'intero documento
List, // Operazione di visualizzazione lista documenti
// con relativi creatori e collaboratori
Edit, // Operazione di richiesta modifica di una sezione
EndEdit, // Operazione di richiesta fine modifica di una
// sezione
Error, // Errore non ben specificato
UsageError, // Passaggio parametri sbagliato
ClosedConnection, // Il server non È più raggiungibile
UnknownSession, // Sessione inesistente
AlreadyLoggedIn, // L'utente è già loggato
CannotLogout, // L'utente è nello stato Started o Editing
SuccessfullySent, // Richiesta inviata con successo
MustBeInStartedState, // Bisogna essere nello stato Started per eseguire
// il comando
MustBeInLoggedState, // Bisogna essere nello stato Logged per eseguire
// il comando
MustBeInEditingState, // Bisogna essere nello stato Editing per eseguire
// il comando
DocumentDoesNotExists, // Il documento non esiste
SectionDoesNotExists, // La sezione non esiste
AlreadyCollaborates, // L'utente già collabora alla modifica del
// documento
CreatorCannotBeCollaborator,// Il creatore del documento non può essere
// collaboratore
NotEditingThisSection, // Non si sta attualmente editando questa sezione
newNotification; // Nuova notifica
static void printErr(Object o)
{
System.err.println("[Error] " + o);
}
static void print(Op op)
{
switch(op)
{
case WrongPassword :
printErr("Password non corretta");
break;
case UserDoesNotExists :
printErr("L'utente specificato non esiste");
break;
case NicknameAlreadyExists :
printErr("Esiste gia' un utente con questo nickname");
break;
case DocumentAlreadyExists :
printErr("Esiste gia' un documento con questo nome");
break;
case DirectoryAlreadyExists :
printErr("Esiste gia' una directory con questo nome");
break;
case NotDocumentCreator :
printErr("Privilegi insufficienti: non si e' creatori del documento");
break;
case NotDocumentCreatorNorCollaborator :
printErr("Privilegi insufficienti: non si e' creatori ne' collaboratori" +
" del documento");
break;
case SectionUnderModification :
printErr("La sezione e' attualmente sotto modifica");
break;
case Error :
printErr("Errore non ben specificato");
break;
case UsageError :
printErr("Errore di utilizzo del comando");
break;
case ClosedConnection :
printErr("host non piu' raggiungibile");
break;
case UnknownSession :
printErr("Sessione inesistente");
break;
case AlreadyLoggedIn :
printErr("Login gia' effettuato");
break;
case CannotLogout :
printErr("Impossibile effettuare il logout (non si e' nello stato " +
" Started o Editing)");
break;
case MustBeInStartedState :
printErr("Bisogna essere nello stato Started per eseguire il comando");
break;
case MustBeInLoggedState :
printErr("Bisogna essere nello stato Logged per eseguire il comando");
break;
case MustBeInEditingState :
printErr("Bisogna essere nello stato Editing per eseguire il comando");
break;
case DocumentDoesNotExists :
printErr("Il documento specificato non esiste");
break;
case SectionDoesNotExists :
printErr("La sezione specificata non esiste ");
break;
case AlreadyCollaborates :
printErr("L'utente specificato collabora gia' alla modifica del" +
" documento");
break;
case CreatorCannotBeCollaborator :
printErr("Un creatore non puo' essere anche collaboratore");
break;
case NotEditingThisSection :
printErr("Non si sta attualmente modificando questa sezione");
break;
default:
printErr("Errore non codificato");
break;
}
}
}
| 44.959732 | 82 | 0.629945 |
bb98922be00516de74283c1d7e7977a972898e80 | 271 | package unalcol.evolution.haea;
import unalcol.descriptors.Descriptors;
public class HaeaStepDescriptors<T> extends Descriptors<HaeaStep<T>> {
@Override
public double[] descriptors(HaeaStep<T> step) {
return Descriptors.obtain(step.operators());
}
} | 27.1 | 70 | 0.738007 |
a9bc3264015adb28405ebca53947817daa76366a | 8,013 | /*
* Copyright 2002-2010 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 org.grails.plugins.elasticsearch.mapping;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.springframework.util.ClassUtils;
/**
* Build ElasticSearch class mapping based on attributes provided by closure.
*/
public class ElasticSearchMappingFactory {
private static final Set<String> SUPPORTED_FORMAT = new HashSet<String>(Arrays.asList(
"string", "integer", "long", "float", "double", "boolean", "null", "date"));
private static final Logger LOG = Logger.getLogger(ElasticSearchMappingFactory.class);
private static Class<?> JODA_TIME_BASE;
static {
try {
JODA_TIME_BASE = Class.forName("org.joda.time.ReadableInstant");
} catch (ClassNotFoundException e) { }
}
@SuppressWarnings("unchecked")
public static Map<String, Object> getElasticMapping(SearchableClassMapping scm) {
Map<String, Object> elasticTypeMappingProperties = new LinkedHashMap<String, Object>();
String parentType = null;
if (!scm.isAll()) {
// "_all" : {"enabled" : true}
elasticTypeMappingProperties.put("_all",
Collections.singletonMap("enabled", false));
}
// Map each domain properties in supported format, or object for complex type
for(SearchableClassPropertyMapping scpm : scm.getPropertiesMapping()) {
// Does it have custom mapping?
GrailsDomainClassProperty property = scpm.getGrailsProperty();
String propType = property.getTypePropertyName();
Map<String, Object> propOptions = new LinkedHashMap<String, Object>();
// Add the custom mapping (searchable static property in domain model)
propOptions.putAll(scpm.getAttributes());
if (!(SUPPORTED_FORMAT.contains(propType))) {
LOG.debug("propType not supported: " + propType + " name: " + property.getName());
if (scpm.isGeoPoint()) {
propType = "geo_point";
}
else if (property.isBasicCollectionType()) {
// Handle embedded persistent collections, ie List<String> listOfThings
String basicType = ClassUtils.getShortName(property.getReferencedPropertyType()).toLowerCase(Locale.ENGLISH);
if (SUPPORTED_FORMAT.contains(basicType)) {
propType = basicType;
}
// Handle arrays
} else if (property.getReferencedPropertyType().isArray()) {
String basicType = ClassUtils.getShortName(property.getReferencedPropertyType().getComponentType()).toLowerCase(Locale.ENGLISH);
if (SUPPORTED_FORMAT.contains(basicType)) {
propType = basicType;
}
} else if (isDateType(property.getReferencedPropertyType())) {
propType = "date";
} else if (GrailsClassUtils.isJdk5Enum(property.getReferencedPropertyType())) {
propType = "string";
} else if (scpm.getConverter() != null) {
// Use 'string' type for properties with custom converter.
// Arrays are automatically resolved by ElasticSearch, so no worries.
propType = "string";
} else if (java.math.BigDecimal.class.isAssignableFrom(property.getReferencedPropertyType())) {
propType = "double";
} else {
// todo should this be string??
propType = "object";
}
if (scpm.getReference() != null) {
propType = "object"; // fixme: think about composite ids.
} else if (scpm.isComponent()) {
// Proceed with nested mapping.
// todo limit depth to avoid endless recursion?
propType = "object";
//noinspection unchecked
propOptions.putAll((Map<String, Object>)
(getElasticMapping(scpm.getComponentPropertyMapping()).values().iterator().next()));
}
// Once it is an object, we need to add id & class mappings, otherwise
// ES will fail with NullPointer.
if (scpm.isComponent() || scpm.getReference() != null) {
Map<String, Object> props = (Map<String, Object>) propOptions.get("properties");
if (props == null) {
props = new LinkedHashMap<String, Object>();
propOptions.put("properties", props);
}
props.put("id", defaultDescriptor("long", "not_analyzed", true));
props.put("class", defaultDescriptor("string", "no", true));
props.put("ref", defaultDescriptor("string", "no", true));
}
if (scpm.isParentKey()) {
parentType = property.getTypePropertyName();
scm.setParent(scpm);
}
}
else if (scpm.isGeoPoint()) {
propType = "geo_point";
}
propOptions.put("type", propType);
// See http://www.elasticsearch.com/docs/elasticsearch/mapping/all_field/
if (!propType.equals("object") && scm.isAll()) {
// does it make sense to include objects into _all?
if (scpm.shouldExcludeFromAll()) {
propOptions.put("include_in_all", false);
} else {
propOptions.put("include_in_all", true);
}
}
// todo only enable this through configuration...
if (propType.equals("string") && scpm.isAnalyzed()) {
propOptions.put("term_vector", "with_positions_offsets");
}
elasticTypeMappingProperties.put(scpm.getPropertyName(), propOptions);
}
Map<String, Object> mapping = new LinkedHashMap<String, Object>();
Map<String, Object> objectMapping = new LinkedHashMap<String, Object>();
if (parentType != null) {
objectMapping.put("_parent", Collections.singletonMap("type", parentType));
}
objectMapping.put("properties", elasticTypeMappingProperties);
mapping.put(scm.getElasticTypeName(), objectMapping);
return mapping;
}
private static boolean isDateType(Class<?> type) {
return (JODA_TIME_BASE != null && JODA_TIME_BASE.isAssignableFrom(type)) || java.util.Date.class.isAssignableFrom(type);
}
private static Map<String, Object> defaultDescriptor(String type, String index, boolean excludeFromAll) {
Map<String, Object> props = new LinkedHashMap<String, Object>();
props.put("type", type);
props.put("index", index);
props.put("include_in_all", !excludeFromAll);
return props;
}
}
| 44.765363 | 148 | 0.590166 |
9e37092f2926ccfce4437e972a87a3c4761d0eba | 6,477 | /*
* Copyright 2006-2011 The Virtual Laboratory for e-Science (VL-e)
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* For details, see the LICENCE.txt file location in the root directory of this
* distribution or obtain the Apache Licence at the following location:
* 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.
*
* See: http://www.vl-e.nl/
* See: LICENCE.txt (located in the root folder of this distribution).
* ---
* $Id: CertPanel.java,v 1.4 2011-05-18 13:03:29 ptdeboer Exp $
* $Date: 2011-05-18 13:03:29 $
*/
// source:
package nl.uva.vlet.gui.viewers.x509viewer;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.BevelBorder;
public class CertPanel extends JPanel
{
private static final long serialVersionUID = -392090763524848492L;
public static final int CANCEL = -1;
public static final int OK = 0;
public static final int TEMPORARY = 1;
public static final int NO = 2;
private JLabel certInfoLabel;
private JPanel topBorderPanel;
private JPanel topPanel;
private JTextArea upperText;
private JPanel buttonPanel;
private JScrollPane scrollPane;
private JButton cancelButton;
private JButton importButton;
private JPanel borderPanel;
private JTextArea middleText;
private int value=CANCEL;
private CertPanelListener certPanelListener;
private boolean viewOnly;
public CertPanel()
{
super();
initGUI();
}
public void exit(int val)
{
this.value=val;
//this.setVisible(false);
certPanelListener.optionSelected();
}
public void setCertPanelListener(CertPanelListener listener){
this.certPanelListener = listener;
}
private void initGUI()
{
try
{
BorderLayout thisLayout = new BorderLayout();
setLayout(thisLayout);
{
topPanel = new JPanel();
BorderLayout topPanelLayout = new BorderLayout();
topPanel.setLayout(topPanelLayout);
add(topPanel, BorderLayout.NORTH);
topPanel.setPreferredSize(new java.awt.Dimension(478, 84));
topPanel.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
{
topBorderPanel = new JPanel();
BorderLayout topBorderPanelLayout = new BorderLayout();
topBorderPanel.setLayout(topBorderPanelLayout);
topPanel.add(topBorderPanel, BorderLayout.CENTER);
topBorderPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
{
upperText = new JTextArea();
topBorderPanel.add(upperText, BorderLayout.CENTER);
upperText.setText("text");
upperText.setBorder(BorderFactory
.createEtchedBorder(BevelBorder.LOWERED));
upperText.setFont(new java.awt.Font("Dialog",1,14));
upperText.setEditable(false);
}
}
}
{
borderPanel = new JPanel();
BorderLayout borderPanelLayout = new BorderLayout();
borderPanel.setLayout(borderPanelLayout);
add(borderPanel, BorderLayout.CENTER);
borderPanel.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
{
scrollPane = new JScrollPane();
borderPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
{
middleText = new JTextArea();
scrollPane.setViewportView(middleText);
middleText.setText("Certificate Text");
middleText.setPreferredSize(new java.awt.Dimension(454, 53));
middleText.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
middleText.setFont(new java.awt.Font("DialogInput",0,11));
middleText.setEditable(false);
}
}
{
buttonPanel = new JPanel();
borderPanel.add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.setBorder(BorderFactory
.createEtchedBorder(BevelBorder.LOWERED));
{
importButton = new JButton();
buttonPanel.add(importButton);
importButton.setText("Import");
importButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt)
{
exit(OK);
}
});
}
{
cancelButton = new JButton();
buttonPanel.add(cancelButton);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt)
{
exit(CANCEL);
}
});
}
}
{
certInfoLabel = new JLabel();
borderPanel.add(certInfoLabel, BorderLayout.NORTH);
certInfoLabel.setText("Certificate Information");
certInfoLabel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
}
}
this.setSize(578, 322);
} catch (Exception e) {
e.printStackTrace();
}
}
void setMessageText(String text)
{
this.middleText.setText(text);
}
/**
* Auto-generated main method to display this JDialog
*/
public static void main(String[] args)
{
JFrame frame = new JFrame();
CertPanel inst = new CertPanel();
frame.add(inst);
frame.pack();
frame.setVisible(true);
}
// public static int showDialog(String text, String chainMessage)
// {
// JFrame frame = new JFrame();
// CertPanel inst = new CertPanel();
// frame.add(inst);
//
// inst.setQuestion(text);
// inst.setMessageText(chainMessage);
//// frame.setModal(true);
// frame.setVisible(true);
//
// return inst.value;
// }
void setQuestion(String text)
{
this.upperText.setText(text);
}
public int getOption()
{
return value;
}
public void setViewOnly(boolean viewOnly)
{
this.viewOnly=viewOnly;
boolean add=(viewOnly==false);
this.importButton.setEnabled(add);
this.importButton.setVisible(add);
if (viewOnly)
this.cancelButton.setText("OK");
else
this.cancelButton.setText("Cancel");
}
}
| 28.038961 | 82 | 0.689054 |
2cc9ff7bb94d9e58331d536d4e513eeca088d788 | 9,631 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.dmn.client.editors.expressions;
import java.util.Optional;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import org.jboss.errai.common.client.dom.HTMLElement;
import org.kie.workbench.common.dmn.api.definition.HasExpression;
import org.kie.workbench.common.dmn.api.definition.HasName;
import org.kie.workbench.common.stunner.client.widgets.presenters.session.SessionPresenter;
import org.kie.workbench.common.stunner.client.widgets.toolbar.ToolbarCommand;
import org.kie.workbench.common.stunner.client.widgets.toolbar.impl.EditorToolbar;
import org.kie.workbench.common.stunner.core.client.session.impl.AbstractClientFullSession;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.uberfire.mvp.Command;
@Dependent
public class ExpressionEditor implements ExpressionEditorView.Presenter {
private ExpressionEditorView view;
private Optional<Command> exitCommand;
private ToolbarCommandStateHandler toolbarCommandStateHandler;
public ExpressionEditor() {
//CDI proxy
}
@Inject
@SuppressWarnings("unchecked")
public ExpressionEditor(final ExpressionEditorView view) {
this.view = view;
this.view.init(this);
}
@Override
public HTMLElement getElement() {
return view.getElement();
}
@Override
public ExpressionEditorView getView() {
return view;
}
@Override
public void init(final SessionPresenter<AbstractClientFullSession, ?, Diagram> presenter) {
this.toolbarCommandStateHandler = new ToolbarCommandStateHandler((EditorToolbar) presenter.getToolbar());
}
@Override
public void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName) {
view.setExpression(nodeUUID,
hasExpression,
hasName);
toolbarCommandStateHandler.enter();
}
@Override
public void setExitCommand(final Command exitCommand) {
this.exitCommand = Optional.ofNullable(exitCommand);
}
@Override
public void exit() {
exitCommand.ifPresent(c -> {
toolbarCommandStateHandler.exit();
c.execute();
});
}
//Package-protected for Unit Tests
ToolbarCommandStateHandler getToolbarCommandStateHandler() {
return toolbarCommandStateHandler;
}
@SuppressWarnings("unchecked")
static class ToolbarCommandStateHandler {
private EditorToolbar toolbar;
//Package-protected for Unit Tests
boolean visitGraphToolbarCommandEnabled = false;
boolean clearToolbarCommandEnabled = false;
boolean clearStatesToolbarCommandEnabled = false;
boolean deleteSelectionToolbarCommandEnabled = false;
boolean switchGridToolbarCommandEnabled = false;
boolean undoToolbarCommandEnabled = false;
boolean redoToolbarCommandEnabled = false;
boolean validateToolbarCommandEnabled = false;
boolean exportToPngToolbarCommandEnabled = false;
boolean exportToJpgToolbarCommandEnabled = false;
boolean exportToPdfToolbarCommandEnabled = false;
boolean copyCommandEnabled = false;
boolean cutCommandEnabled = false;
boolean pasteCommandEnabled = false;
private ToolbarCommandStateHandler(final EditorToolbar toolbar) {
this.toolbar = toolbar;
}
private void enter() {
this.visitGraphToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getVisitGraphToolbarCommand());
this.clearToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getClearToolbarCommand());
this.clearStatesToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getClearStatesToolbarCommand());
this.deleteSelectionToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getDeleteSelectionToolbarCommand());
this.switchGridToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getSwitchGridToolbarCommand());
this.undoToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getUndoToolbarCommand());
this.redoToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getRedoToolbarCommand());
this.validateToolbarCommandEnabled = toolbar.isEnabled(toolbar.getValidateToolbarCommand());
this.exportToPngToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getExportToPngToolbarCommand());
this.exportToJpgToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getExportToJpgToolbarCommand());
this.exportToPdfToolbarCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getExportToPdfToolbarCommand());
this.copyCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getCopyToolbarCommand());
this.cutCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getCutToolbarCommand());
this.pasteCommandEnabled = toolbar.isEnabled((ToolbarCommand) toolbar.getPasteToolbarCommand());
enableToolbarCommand(toolbar.getVisitGraphToolbarCommand(),
false);
enableToolbarCommand(toolbar.getClearToolbarCommand(),
false);
enableToolbarCommand(toolbar.getClearStatesToolbarCommand(),
false);
enableToolbarCommand(toolbar.getDeleteSelectionToolbarCommand(),
false);
enableToolbarCommand(toolbar.getSwitchGridToolbarCommand(),
false);
enableToolbarCommand(toolbar.getUndoToolbarCommand(),
false);
enableToolbarCommand(toolbar.getRedoToolbarCommand(),
false);
enableToolbarCommand(toolbar.getValidateToolbarCommand(),
false);
enableToolbarCommand(toolbar.getExportToPngToolbarCommand(),
false);
enableToolbarCommand(toolbar.getExportToJpgToolbarCommand(),
false);
enableToolbarCommand(toolbar.getExportToPdfToolbarCommand(),
false);
enableToolbarCommand(toolbar.getCopyToolbarCommand(),
false);
enableToolbarCommand(toolbar.getCutToolbarCommand(),
false);
enableToolbarCommand(toolbar.getPasteToolbarCommand(),
false);
}
private void exit() {
enableToolbarCommand(toolbar.getVisitGraphToolbarCommand(),
visitGraphToolbarCommandEnabled);
enableToolbarCommand(toolbar.getClearToolbarCommand(),
clearToolbarCommandEnabled);
enableToolbarCommand(toolbar.getClearStatesToolbarCommand(),
clearStatesToolbarCommandEnabled);
enableToolbarCommand(toolbar.getDeleteSelectionToolbarCommand(),
deleteSelectionToolbarCommandEnabled);
enableToolbarCommand(toolbar.getSwitchGridToolbarCommand(),
switchGridToolbarCommandEnabled);
enableToolbarCommand(toolbar.getUndoToolbarCommand(),
undoToolbarCommandEnabled);
enableToolbarCommand(toolbar.getRedoToolbarCommand(),
redoToolbarCommandEnabled);
enableToolbarCommand(toolbar.getValidateToolbarCommand(),
validateToolbarCommandEnabled);
enableToolbarCommand(toolbar.getExportToPngToolbarCommand(),
exportToPngToolbarCommandEnabled);
enableToolbarCommand(toolbar.getExportToJpgToolbarCommand(),
exportToJpgToolbarCommandEnabled);
enableToolbarCommand(toolbar.getExportToPdfToolbarCommand(),
exportToPdfToolbarCommandEnabled);
enableToolbarCommand(toolbar.getCopyToolbarCommand(),
copyCommandEnabled);
enableToolbarCommand(toolbar.getCutToolbarCommand(),
cutCommandEnabled);
enableToolbarCommand(toolbar.getPasteToolbarCommand(),
pasteCommandEnabled);
}
private void enableToolbarCommand(final ToolbarCommand command,
final boolean enabled) {
if (enabled) {
toolbar.enable(command);
} else {
toolbar.disable(command);
}
}
}
}
| 46.08134 | 135 | 0.657564 |
06d4d09c7230c928ce3d362ee3a8dc22a498e979 | 4,098 | /*-
* Copyright (C) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
*
* This file was distributed by Oracle as part of a version of Oracle Berkeley
* DB Java Edition made available at:
*
* http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html
*
* Please see the LICENSE file included in the top-level directory of the
* appropriate version of Oracle Berkeley DB Java Edition for a copy of the
* license and additional information.
*/
package com.sleepycat.je.dbi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import com.sleepycat.je.DbInternal;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.config.EnvironmentParams;
import com.sleepycat.je.util.TestUtils;
import com.sleepycat.je.utilint.JVMSystemUtils;
import com.sleepycat.util.test.SharedTestUtils;
import com.sleepycat.util.test.TestBase;
import org.junit.Test;
public class MemoryBudgetTest extends TestBase {
private final File envHome;
public MemoryBudgetTest() {
envHome = SharedTestUtils.getTestDir();
}
@Test
public void testDefaults()
throws Exception {
EnvironmentConfig envConfig = TestUtils.initEnvConfig();
envConfig.setAllowCreate(true);
Environment env = new Environment(envHome, envConfig);
EnvironmentImpl envImpl = DbInternal.getNonNullEnvImpl(env);
MemoryBudget testBudget = envImpl.getMemoryBudget();
/*
System.out.println("max= " + testBudget.getMaxMemory());
System.out.println("log= " + testBudget.getLogBufferBudget());
System.out.println("thresh= " + testBudget.getEvictorCheckThreshold());
*/
assertTrue(testBudget.getMaxMemory() > 0);
assertTrue(testBudget.getLogBufferBudget() > 0);
assertTrue(testBudget.getMaxMemory() <=
JVMSystemUtils.getRuntimeMaxMemory());
env.close();
}
/* Verify that the proportionally based setting works. */
@Test
public void testCacheSizing()
throws Exception {
long jvmMemory = JVMSystemUtils.getRuntimeMaxMemory();
/*
* Runtime.maxMemory() may return Long.MAX_VALUE if there is no
* inherent limit.
*/
if (jvmMemory == Long.MAX_VALUE) {
jvmMemory = 1 << 26;
}
/* The default cache size ought to be percentage based. */
EnvironmentConfig envConfig = TestUtils.initEnvConfig();
envConfig.setAllowCreate(true);
Environment env = new Environment(envHome, envConfig);
EnvironmentImpl envImpl = DbInternal.getNonNullEnvImpl(env);
long percentConfig = envImpl.getConfigManager().
getInt(EnvironmentParams.MAX_MEMORY_PERCENT);
EnvironmentConfig c = env.getConfig();
long expectedMem = (jvmMemory * percentConfig) / 100;
assertEquals(expectedMem, c.getCacheSize());
assertEquals(expectedMem, envImpl.getMemoryBudget().getMaxMemory());
env.close();
/* Try setting the percentage.*/
expectedMem = (jvmMemory * 30) / 100;
envConfig = TestUtils.initEnvConfig();
envConfig.setCachePercent(30);
env = new Environment(envHome, envConfig);
envImpl = DbInternal.getNonNullEnvImpl(env);
c = env.getConfig();
assertEquals(expectedMem, c.getCacheSize());
assertEquals(expectedMem, envImpl.getMemoryBudget().getMaxMemory());
env.close();
/* Try overriding */
envConfig = TestUtils.initEnvConfig();
envConfig.setCacheSize(MemoryBudget.MIN_MAX_MEMORY_SIZE + 10);
env = new Environment(envHome, envConfig);
envImpl = DbInternal.getNonNullEnvImpl(env);
c = env.getConfig();
assertEquals(MemoryBudget.MIN_MAX_MEMORY_SIZE + 10, c.getCacheSize());
assertEquals(MemoryBudget.MIN_MAX_MEMORY_SIZE + 10,
envImpl.getMemoryBudget().getMaxMemory());
env.close();
}
}
| 35.327586 | 99 | 0.67838 |
4784b58c3b7ecff7137b043a6af7ba8af701d89e | 7,564 | package application.Model;
import application.Controller.MainframeController;
import com.google.zxing.WriterException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import java.io.IOException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class Monitor {
private ArrayList<Event> events;
private ArrayList<Venue> venues;
private ArrayList<eQRCode> codes;
public Monitor() {
events = Event.loadEvents();
Collections.sort(events, Comparator.comparing(Event::getID));
venues = Venue.loadVenues();
Collections.sort(venues, Comparator.comparing(Venue::getID));
codes = new ArrayList<>();
}
public String scanIn(File file, Event event, Venue venue) throws IOException, WriterException, GEMSException {
try {
eQRCode person = eQRCode.getQRCode(file);
System.out.println(person.toString());
if(!contains(person)) codes.add(person);
else {
for(eQRCode code: codes) {
if(code.toString().equals(person.toString())) { person = code; System.out.println("found"); break; }
}
}
if(venue.contains(person)) {
return person.getName()+" already in "+venue.getName();
}
if(person.isInside()) {
return person.getName()+" already somewhere else";
}
if(person.getEvent().equals(event)) {
venue.add(person);
person.enter(venue);
if (venue.getCurr_capacity() == venue.getMax_capacity()) return "Full Capacity";
else return "Scan Successful: "+person.getName()+" has entered";
} else return person.getName()+ " should be at " + person.getEvent().getName();
} catch (GEMSException e) {
if(e.getMessage().equals("Illegal .png")) throw new GEMSException("Illegal .png");
return e.getMessage();
}
}
public String scanOut(File file, Event event, Venue venue) throws IOException, WriterException {
try {
eQRCode person = eQRCode.getQRCode(file);
if(!venue.contains(person)) {
return person.getName()+" is not here";
}
person = venue.getByID(person.geteQRCodeID());
if(person.isInside()) person.exit();
if(!contains(person)) add(person);
if(person.getEvent().equals(event)) {
venue.remove(person);
LocalDateTime[] arr = person.exit();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
File visit = new File(System.getProperty("user.dir") + "\\visit.csv", 'a');
visit.out.println(
String.join(",",
person.getName(),
person.getContact_no(),
event.getID(),
venue.getID(),
DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss").format(arr[0]),
DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss").format(arr[1])
)
);
visit.close();
return "Checkout Successful: "+person.getName()+" has left";
} else return person.getName()+ " is not at the right event";
} catch(GEMSException e) {
return e.getMessage();
}
}
public void massCheckOut(Event selEvent, Venue selVenue, Button massOut) {
if(selVenue != null) {
massOut.setDisable(true);
File visit = new File(System.getProperty("user.dir")+"\\visit.csv", 'a');
while(selVenue.getCurr_capacity() != 0) {
eQRCode person = selVenue.getVisitors().get(0);
try {
selVenue.remove(person);
LocalDateTime[] arr = person.exit();
visit.out.println(
String.join(",",
person.getName(),
person.getContact_no(),
selEvent.getID(),
selVenue.getID(),
DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss").format(arr[0]),
DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss").format(arr[1])
)
);
} catch (GEMSException ex) {}
}
visit.close();
massOut.setDisable(false);
}
}
public Event[] getEvents() {
return events.toArray(new Event[events.size()]);
}
public Venue[] getVenues() {
return venues.toArray(new Venue[venues.size()]);
}
public eQRCode[] getCodes() {
return codes.toArray(new eQRCode[codes.size()]);
}
public String[] getEventNames() {
String[] arr = new String[events.size()];
for(int i = 0; i < events.size(); i++) {
arr[i] = events.get(i).getName();
}
Arrays.sort(arr);
return arr;
}
public String[] getVenueNames() {
String[] arr = new String[venues.size()];
for(int i = 0; i < venues.size(); i++) {
arr[i] = venues.get(i).getName() + " " + venues.get(i).getRoom_no();
}
Arrays.sort(arr);
return arr;
}
public Event getEventByName(String name) {
for(Event event: events) {
if(event.getName().equals(name)) return event;
}
return null;
}
public Event getEventByID(String ID) {
for(Event event: events) {
if(event.getID().equals(ID)) return event;
}
return null;
}
public Venue getVenueByName(String name) {
for(Venue venue: venues) {
if(name.equals(venue.getName()+" "+venue.getRoom_no())) return venue;
}
return null;
}
public void add(Event event) {
events.add(event);
Collections.sort(events, Comparator.comparing(Event::getID));
}
public void remove(Event event) {
ArrayList<Event> arr = new ArrayList<>();
for(Event ev: events) {
if(!ev.getID().equals(event.getID())) arr.add(ev);
}
events = arr;
event.delete();
}
public void add(Venue venue) {
venues.add(venue);
Collections.sort(venues, Comparator.comparing(Venue::getID));
}
public void remove(Venue venue) {
ArrayList<Venue> arr = new ArrayList<>();
for(Venue v: venues) {
if(!v.getID().equals(venue.getID())) arr.add(v);
}
venues = arr;
for(Event event: events) {
if(event.contains(venue)) event.remove(venue);
}
venue.delete();
}
public void add(eQRCode code) {
codes.add(code);
Collections.sort(codes, Comparator.comparing(eQRCode::geteQRCodeID));
}
public boolean contains(eQRCode code) {
for(eQRCode qrCode: codes) {
if(qrCode.geteQRCodeID().equals(code.geteQRCodeID())) return true;
}
return false;
}
}
| 35.018519 | 120 | 0.535828 |
237759f5faa3b1eff7147fae77a06126770f5fb4 | 1,094 | package com.networknt.spring.servlet;
import com.networknt.handler.Handler;
import com.networknt.handler.OrchestrationHandler;
import io.undertow.servlet.api.DeploymentInfo;
import org.springframework.boot.web.embedded.undertow.UndertowDeploymentInfoCustomizer;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LightConfig {
@Bean
UndertowServletWebServerFactory embeddedServletWebFactory() {
UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
factory.addDeploymentInfoCustomizers(new UndertowDeploymentInfoCustomizer() {
@Override
public void customize(DeploymentInfo deploymentInfo) {
Handler.init();
deploymentInfo.addInitialHandlerChainWrapper(handler -> {
return new OrchestrationHandler(handler);
});
}
});
return factory;
}
}
| 36.466667 | 88 | 0.73766 |
aa6e7f660fbe4567218400035635e8939a6fe056 | 2,263 | package it.av.youeat.web.page.manager;
import it.av.youeat.ocm.model.Eater;
import it.av.youeat.ocm.model.Ristorante;
import it.av.youeat.service.EaterService;
import it.av.youeat.service.RistoranteService;
import java.util.ArrayList;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
/**
* Provides some actions to manage the current restaurant
*
* @author Alessandro Vincelli
*
*/
public class RistoActionColumn extends Panel {
@SpringBean
private RistoranteService ristoranteService;
@SpringBean
private EaterService eaterService;
/**
* @param id component id
* @param model model for ristorante
*/
public RistoActionColumn(String id, final IModel<Ristorante> model) {
super(id, model);
Injector.get().inject(this);
Link<Ristorante> link = new Link<Ristorante>("remove", model) {
@Override
public void onClick() {
ristoranteService.remove(model.getObject());
setResponsePage(getApplication().getHomePage());
//TODO 1.5
//setRedirect(true);
}
};
add(link);
Form<String> form = new Form<String>("setRestaurateurForm", new CompoundPropertyModel(model));
form.setOutputMarkupId(true);
add(form);
ArrayList<Eater> eaters = new ArrayList<Eater>(eaterService.getAll());
eaters.add(null);
DropDownChoice<Eater> restaurateur = new DropDownChoice<Eater>("restaurateur", eaters);
restaurateur.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
ristoranteService.updateNoRevision(model.getObject());
}
});
form.add(restaurateur);
}
} | 33.776119 | 102 | 0.690234 |
cd72c81053106c0b15479f8b0377174eefc23907 | 266 | package com.example.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.System;
/**
* <p>
* 系统配置表格 Mapper 接口
* </p>
*
* @author MrWen
* @since 2021-11-28
*/
public interface SystemMapper extends BaseMapper<System> {
}
| 15.647059 | 58 | 0.710526 |
f70eb54d15bb4e9b83d473e2fb982e2b73dd4d0d | 4,041 | package net.gupt.community.exception;
import lombok.extern.slf4j.Slf4j;
import net.gupt.community.entity.CodeMsg;
import net.gupt.community.entity.Result;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* <h3>gupt-community</h3>
* <p>全局异常处理类</p>
*
* @author : Cui
* @date : 2019-08-03 16:40
**/
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class SpringExceptionHandle {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
e.printStackTrace();
if (e instanceof GlobalException) {
GlobalException globalException = (GlobalException) e;
return Result.error(globalException.getCode(), globalException.getMessage());
} else {
return Result.error(CodeMsg.SYSTEM_ERROR);
}
}
/**
* List索引越界异常
*
* @param e 异常信息
* @return Result
*/
@ExceptionHandler(value = IndexOutOfBoundsException.class)
@ResponseBody
public Result indexOut(Exception e) {
if (e instanceof IndexOutOfBoundsException) {
return Result.error(CodeMsg.MISSING_RECORD);
} else {
GlobalException globalException = (GlobalException) e;
return Result.error(globalException.getCode(), globalException.getMessage());
}
}
/**
* 重复绑定异常
*
* @param e 异常信息
* @return Result
*/
@ExceptionHandler(value = DuplicateKeyException.class)
@ResponseBody
public Result duplicateKey(Exception e) {
final String exceptionInfo = "tbl_student";
if (e instanceof DuplicateKeyException && e.getCause().toString().contains(exceptionInfo)) {
return Result.error(CodeMsg.REPEAT_BINDING);
} else if (e instanceof DuplicateKeyException) {
return Result.error(CodeMsg.UNIQUE_INDEX);
} else {
return Result.error(CodeMsg.SYSTEM_ERROR);
}
}
/**
* 请求参数丢失异常
*
* @param e 异常对象
* @return Result
*/
@ExceptionHandler(value = MissingServletRequestParameterException.class)
@ResponseBody
public Result missingServletRequestParameter(Exception e) {
if (e instanceof MissingServletRequestParameterException) {
return Result.error(CodeMsg.MISSING_PARAMETER);
} else {
GlobalException globalException = (GlobalException) e;
return Result.error(globalException.getCode(), globalException.getMessage());
}
}
/**
* 非法请求异常
*
* @param e 异常信息
* @return Result
*/
@ExceptionHandler(value = IllegalRequestException.class)
@ResponseBody
public Result illegalRequest(Exception e) {
switch (e.getMessage()) {
case "游客无权限访问":
return Result.error(CodeMsg.VISITOR_FORBIDDEN);
case "请求频繁":
return Result.error(CodeMsg.REQUEST_FREQUENT);
default:
return Result.error(CodeMsg.SYSTEM_ERROR);
}
}
/**
* 数据完整性异常
*
* @param e 异常
* @return result
*/
@ExceptionHandler(value = DataIntegrityViolationException.class)
@ResponseBody
public Result dataIntegrityViolation(Exception e) {
if (e instanceof DataIntegrityViolationException) {
return Result.error(CodeMsg.DATA_EXCEPTION);
} else {
GlobalException globalException = (GlobalException) e;
return Result.error(globalException.getCode(), globalException.getMessage());
}
}
}
| 31.818898 | 100 | 0.662955 |
9f615ec5756d131fceafbc63b90e6fdba3863cf5 | 1,193 | package io.github.vaa25.excel;
import com.poiji.option.PoijiOptions;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestExcelFile {
String DEFAULT_EXCEL_OPTIONS_BEAN_NAME = "defaultExcelOptions";
/**
* Alias for {@link #name}.
*/
@AliasFor("name")
String value() default "";
/**
* The name of the part in the {@code "multipart/form-data"} request to bind to.
* @since 4.2
*/
@AliasFor("value")
String name() default "";
/**
* Whether the part is required.
* <p>Defaults to {@code true}, leading to an exception being thrown
* if the part is missing in the request. Switch this to
* {@code false} if you prefer a {@code null} value if the part is
* not present in the request.
*/
boolean required() default true;
/**
* Options bean name. Options bean type must be {@link PoijiOptions}
*/
String optionsBean() default "";
}
| 27.744186 | 84 | 0.678122 |
6ba4668a9ebac6f89df232fda6c3d4b08e03f392 | 961 | package pl.ostrowski.account.assembler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import pl.ostrowski.account.dto.UserDto;
import pl.ostrowski.account.model.User;
import pl.ostrowski.util.Assembler;
/** Created by Jedras-PC on 25.01.2018. */
@Component
public class UserAssembler extends Assembler<User, UserDto> {
private final PasswordEncoder passwordEncoder;
@Autowired
public UserAssembler(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
public UserDto convertToBusiness(User user) {
return null;
}
@Override
public User convertToDomain(UserDto userDto) {
return User.builder()
.username(userDto.getUsername())
.email(userDto.getEmail())
.password(passwordEncoder.encode(userDto.getPassword()))
.build();
}
}
| 27.457143 | 68 | 0.758585 |
d18cb2413573a5ea55d25222ca3caf29c3da6fc5 | 824 | package org.rspeekenbrink.deathmatch.events;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.rspeekenbrink.deathmatch.managers.MessageManager;
/**
* PlayerBedEnter Event will avoid spawn altering or time altering trough sleeping
* It is registered upon plugin load in the Startup class.
* @see https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/player/PlayerBedEnterEvent.html
*
* @author Remco Speekenbrink
* @version 1.0
* @since 1.0
*/
public class PlayerBedEnter implements Listener {
MessageManager msg = MessageManager.getInstance();
@EventHandler
public void onPlayerBedEnterEvent(PlayerBedEnterEvent e) {
msg.sendErrorMessage("You can't sleep now!", e.getPlayer());
e.setCancelled(true);
}
}
| 31.692308 | 97 | 0.775485 |
55e2aa283e8bcb28a1056cd1da36d639d91ae267 | 121 | package deviseworks;
public enum ExecutableContentsEnum {
install,
uninstall,
setting,
help,
exit
}
| 12.1 | 36 | 0.669421 |
ce709caeb275322394aa7bbb92a376328c52521b | 3,037 | // Copyright (c) YugaByte, Inc.
package com.yugabyte.yw.commissioner.tasks.subtasks;
import com.yugabyte.yw.commissioner.BaseTaskDependencies;
import com.yugabyte.yw.commissioner.tasks.UniverseTaskBase;
import com.yugabyte.yw.common.CertificateHelper;
import com.yugabyte.yw.forms.UniverseDefinitionTaskParams;
import com.yugabyte.yw.forms.UniverseTaskParams;
import com.yugabyte.yw.models.Universe;
import java.util.UUID;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class UniverseSetTlsParams extends UniverseTaskBase {
@Inject
protected UniverseSetTlsParams(BaseTaskDependencies baseTaskDependencies) {
super(baseTaskDependencies);
}
public static class Params extends UniverseTaskParams {
public boolean enableNodeToNodeEncrypt;
public boolean enableClientToNodeEncrypt;
public boolean rootAndClientRootCASame;
public boolean allowInsecure;
public UUID rootCA;
public UUID clientRootCA;
}
protected UniverseSetTlsParams.Params taskParams() {
return (UniverseSetTlsParams.Params) taskParams;
}
@Override
public String getName() {
return super.getName();
}
@Override
public void run() {
try {
log.info("Running {}", getName());
// Create the update lambda.
Universe.UniverseUpdater updater =
universe -> {
// If this universe is not being edited, fail the request.
UniverseDefinitionTaskParams universeDetails = universe.getUniverseDetails();
if (!universeDetails.updateInProgress) {
String errMsg = "UserUniverse " + taskParams().universeUUID + " is not being edited.";
log.error(errMsg);
throw new RuntimeException(errMsg);
}
UniverseDefinitionTaskParams.UserIntent userIntent =
universeDetails.getPrimaryCluster().userIntent;
userIntent.enableNodeToNodeEncrypt = taskParams().enableNodeToNodeEncrypt;
userIntent.enableClientToNodeEncrypt = taskParams().enableClientToNodeEncrypt;
universeDetails.allowInsecure = taskParams().allowInsecure;
universeDetails.rootCA = null;
universeDetails.clientRootCA = null;
universeDetails.rootAndClientRootCASame = taskParams().rootAndClientRootCASame;
if (CertificateHelper.isRootCARequired(taskParams())) {
universeDetails.rootCA = taskParams().rootCA;
}
if (taskParams().enableClientToNodeEncrypt) {
universeDetails.clientRootCA = taskParams().clientRootCA;
}
universe.setUniverseDetails(universeDetails);
};
// Perform the update. If unsuccessful, this will throw a runtime
// exception which we do not catch as we want to fail.
saveUniverseDetails(updater);
} catch (Exception e) {
String msg = getName() + " failed with exception " + e.getMessage();
log.warn(msg, e.getMessage());
throw new RuntimeException(msg, e);
}
}
}
| 36.154762 | 100 | 0.69674 |
b77a91d8f707a92feaa585bc1e3ecc3939cd5cca | 8,190 | package st.gravel.support.compiler.ast;
/*
This file is automatically generated from typed smalltalk source. Do not edit by hand.
(C) AG5.com
*/
import java.math.BigInteger;
import st.gravel.support.jvm.NonLocalReturn;
import st.gravel.support.compiler.ast.MessageNode;
import st.gravel.support.compiler.ast.MessageNode.MessageNode_Factory;
import st.gravel.support.compiler.ast.Expression;
import st.gravel.support.compiler.ast.NodeVisitor;
import st.gravel.support.compiler.ast.Node;
import st.gravel.support.compiler.ast.SourcePrinter;
import st.gravel.support.compiler.ast.SourcePosition;
public class BinaryMessageNode extends MessageNode implements Cloneable {
public static BinaryMessageNode_Factory factory = new BinaryMessageNode_Factory();
Expression _argument;
public static class BinaryMessageNode_Factory extends MessageNode_Factory {
public BinaryMessageNode basicNew() {
BinaryMessageNode newInstance = new BinaryMessageNode();
newInstance.initialize();
return newInstance;
}
@Override
public BinaryMessageNode receiver_selector_(final Expression _aNode, final String _aString) {
return ((BinaryMessageNode) this.basicNew().initializeReceiver_selector_(_aNode, _aString));
}
public BinaryMessageNode receiver_selector_arguments_(final Expression _aNode, final String _aString, final Expression[] _anArray) {
st.gravel.support.jvm.ObjectExtensions.assert_(this, st.gravel.support.jvm.IntegerExtensions.equals_(_anArray.length, 1));
return ((BinaryMessageNode) this.receiver_selector_argument_(_aNode, _aString, _anArray[0]));
}
public BinaryMessageNode receiver_selector_argument_(final Expression _anIntegerLiteralNode, final String _aString, final Expression _anIntegerLiteralNode2) {
return ((BinaryMessageNode) this.basicNew().initializeReceiver_selector_argument_(_anIntegerLiteralNode, _aString, _anIntegerLiteralNode2));
}
}
static public BinaryMessageNode _receiver_selector_(Object receiver, final Expression _aNode, final String _aString) {
return factory.receiver_selector_(_aNode, _aString);
}
static public BinaryMessageNode _receiver_selector_arguments_(Object receiver, final Expression _aNode, final String _aString, final Expression[] _anArray) {
return factory.receiver_selector_arguments_(_aNode, _aString, _anArray);
}
static public BinaryMessageNode _receiver_selector_argument_(Object receiver, final Expression _anIntegerLiteralNode, final String _aString, final Expression _anIntegerLiteralNode2) {
return factory.receiver_selector_argument_(_anIntegerLiteralNode, _aString, _anIntegerLiteralNode2);
}
@Override
public <X> X accept_(final NodeVisitor<X> _visitor) {
return _visitor.visitBinaryMessageNode_(this);
}
@Override
public BinaryMessageNode allNodesDo_(final st.gravel.support.jvm.Block1<Object, Node> _aBlock) {
this.nodesDo_(new st.gravel.support.jvm.Block1<Object, Node>() {
@Override
public Object value_(final Node _each) {
return _each.withAllNodesDo_(_aBlock);
}
});
return this;
}
@Override
public BinaryMessageNode allNodesDo_pruneWhere_(final st.gravel.support.jvm.Block1<Object, Node> _aBlock, final st.gravel.support.jvm.Block1<Boolean, Node> _pruneBlock) {
this.nodesDo_(new st.gravel.support.jvm.Block1<Object, Node>() {
@Override
public Object value_(final Node _each) {
if (!_pruneBlock.value_(_each)) {
return _each.withAllNodesDo_pruneWhere_(_aBlock, _pruneBlock);
}
return BinaryMessageNode.this;
}
});
return this;
}
@Override
public Expression argument() {
return _argument;
}
@Override
public Expression[] arguments() {
return st.gravel.support.jvm.ArrayFactory.with_(_argument);
}
public BinaryMessageNode copy() {
try {
BinaryMessageNode _temp1 = (BinaryMessageNode) this.clone();
_temp1.postCopy();
return _temp1;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean equals(final Object _anObject) {
if (!super.equals(_anObject)) {
return false;
}
if (this._argument == null) {
if (!(((BinaryMessageNode) _anObject)._argument == null)) {
return false;
}
} else {
if (!st.gravel.support.jvm.ObjectExtensions.equals_(this._argument, ((BinaryMessageNode) _anObject)._argument)) {
return false;
}
}
return true;
}
public BinaryMessageNode_Factory factory() {
return factory;
}
@Override
public int hashCode() {
return (super.hashCode() ^ (_argument == null ? 0 : _argument.hashCode()));
}
@Override
public BinaryMessageNode initializeReceiver_selector_(final Expression _anIntegerLiteralNode, final String _aString) {
_receiver = _anIntegerLiteralNode;
_selector = _aString;
this.initialize();
return this;
}
public BinaryMessageNode initializeReceiver_selector_argument_(final Expression _anIntegerLiteralNode, final String _aString, final Expression _anIntegerLiteralNode2) {
_receiver = _anIntegerLiteralNode;
_selector = _aString;
_argument = _anIntegerLiteralNode2;
this.initialize();
return this;
}
@Override
public BinaryMessageNode innerSourceOn_(final StringBuilder _aStream) {
_receiver.sourceOn_(_aStream);
this.sourceSendOn_(_aStream);
return this;
}
@Override
public BinaryMessageNode innerSourceSendOn_(final StringBuilder _aStream) {
_aStream.append(_selector);
_aStream.append(' ');
_argument.sourceOn_(_aStream);
return this;
}
@Override
public BinaryMessageNode localVarNamesDo_(final st.gravel.support.jvm.Block1<Object, String> _aBlock) {
return this;
}
@Override
public BinaryMessageNode nodesDo_(final st.gravel.support.jvm.Block1<Object, Node> _aBlock) {
_aBlock.value_(_receiver);
_aBlock.value_(_argument);
return this;
}
@Override
public int numArgs() {
return 1;
}
@Override
public int precedence() {
return 2;
}
@Override
public BinaryMessageNode prettySourceOn_(final StringBuilder _aStream) {
SourcePrinter.factory.on_(_aStream).visit_(this);
return this;
}
@Override
public BinaryMessageNode printOn_(final StringBuilder _aStream) {
final String _title;
_title = this.factory().toString();
_aStream.append(st.gravel.support.jvm.CharacterExtensions.isVowel(_title.charAt(0)) ? "an " : "a ");
_aStream.append(_title);
_aStream.append('[');
this.sourceOn_(_aStream);
_aStream.append(']');
return this;
}
public BinaryMessageNode pvtSetArgument_(final Expression _anExpression) {
_argument = _anExpression;
return this;
}
@Override
public BinaryMessageNode pvtSetSourcePosition_(final SourcePosition _aSourcePosition) {
_sourcePosition = _aSourcePosition;
return this;
}
@Override
public BinaryMessageNode sourceOn_(final StringBuilder _aStream) {
if (!this.needsBrackets()) {
return BinaryMessageNode.this.innerSourceOn_(_aStream);
}
_aStream.append('(');
this.innerSourceOn_(_aStream);
_aStream.append(')');
return this;
}
@Override
public BinaryMessageNode sourceSendOn_(final StringBuilder _aStream) {
_aStream.append(' ');
this.innerSourceSendOn_(_aStream);
return this;
}
@Override
public BinaryMessageNode withAllNodesDo_(final st.gravel.support.jvm.Block1<Object, Node> _aBlock) {
_aBlock.value_(this);
this.allNodesDo_(_aBlock);
return this;
}
@Override
public BinaryMessageNode withAllNodesDo_pruneWhere_(final st.gravel.support.jvm.Block1<Object, Node> _aBlock, final st.gravel.support.jvm.Block1<Boolean, Node> _pruneBlock) {
_aBlock.value_(this);
this.allNodesDo_pruneWhere_(_aBlock, _pruneBlock);
return this;
}
@Override
public BinaryMessageNode withArguments_(final Expression[] _anArray) {
st.gravel.support.jvm.ObjectExtensions.assert_(this, st.gravel.support.jvm.IntegerExtensions.equals_(_anArray.length, 1));
return this.withArgument_(_anArray[0]);
}
public BinaryMessageNode withArgument_(final Expression _anExpression) {
return this.copy().pvtSetArgument_(_anExpression);
}
@Override
public BinaryMessageNode withSourcePosition_(final SourcePosition _aSourcePosition) {
if (_sourcePosition == _aSourcePosition) {
return BinaryMessageNode.this;
}
return this.copy().pvtSetSourcePosition_(_aSourcePosition);
}
}
| 30.446097 | 184 | 0.773138 |
54d53a3812aabb3df2bfd9fdfb05463bab0b4500 | 1,526 | package org.docksidestage.bizfw.debug;
/**
* @author zaya
*/
public class Language {
public String name;
public String description = "";
public int countries = 0;
public int rank;
public Language(String name) {
this.name = name;
}
public Language(String name, String description) {
this.name = name;
this.description = description;
}
public Language(String name, String description, int countries) {
this.name = name;
this.description = description;
this.countries = countries;
}
public Language(String name, int countries, int rank) {
this.name = name;
this.rank = rank;
this.countries = countries;
}
public Language(String name, String description, int countries, int rank) {
this.name = name;
this.description = description;
this.countries = countries;
this.rank = rank;
}
public String getDescription() {
return description;
}
public void setCountries(int countries) {
this.countries = countries;
}
public String getName() {
return name;
}
public void setDescription(String description) {
this.description = description;
}
public int getRank() {
return rank;
}
public void setName(String name) {
this.name = name;
}
public int getCountries() {
return countries;
}
public void setRank(int rank) {
this.rank = rank;
}
}
| 21.194444 | 79 | 0.598952 |
6e4415b050710f48a059ae012402e59f96ba153e | 6,126 |
package com.faizal.OtpVerify;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
// import android.support.annotation.NonNull;
import androidx.annotation.NonNull;
import android.util.Log;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.credentials.Credential;
import com.google.android.gms.auth.api.credentials.HintRequest;
import com.google.android.gms.auth.api.phone.SmsRetriever;
import com.google.android.gms.auth.api.phone.SmsRetrieverClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import java.util.ArrayList;
public class RNOtpVerifyModule extends ReactContextBaseJavaModule implements LifecycleEventListener, ActivityEventListener {
private static final String TAG = RNOtpVerifyModule.class.getSimpleName();
private static final int RESOLVE_HINT = 10001;
private GoogleApiClient apiClient;
private Promise requestHintCallback;
private final ReactApplicationContext reactContext;
private BroadcastReceiver mReceiver;
private boolean isReceiverRegistered = false;
public RNOtpVerifyModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
mReceiver = new OtpBroadcastReceiver(reactContext);
getReactApplicationContext().addLifecycleEventListener(this);
registerReceiverIfNecessary(mReceiver);
reactContext.addActivityEventListener(this);
apiClient = new GoogleApiClient.Builder(reactContext)
.addApi(Auth.CREDENTIALS_API)
.build();
}
@Override
public String getName() {
return "RNOtpVerify";
}
@ReactMethod
public void requestHint(Promise promise) {
Activity currentActivity = getCurrentActivity();
requestHintCallback = promise;
if (currentActivity == null) {
requestHintCallback.reject("No Activity Found", "Current Activity Null.");
return;
}
try {
HintRequest hintRequest = new HintRequest.Builder().setPhoneNumberIdentifierSupported(true).build();
PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(apiClient, hintRequest);
currentActivity.startIntentSenderForResult(intent.getIntentSender(), RESOLVE_HINT, null, 0, 0, 0);
} catch (Exception e) {
requestHintCallback.reject(e);
}
}
@ReactMethod
public void getOtp(Promise promise) {
requestOtp(promise);
}
@ReactMethod
public void getHash(Promise promise) {
try {
AppSignatureHelper helper = new AppSignatureHelper(reactContext);
ArrayList<String> signatures = helper.getAppSignatures();
WritableArray arr = Arguments.createArray();
for (String s : signatures) {
arr.pushString(s);
}
promise.resolve(arr);
} catch (Exception e) {
promise.reject(e);
}
}
private void registerReceiverIfNecessary(BroadcastReceiver receiver) {
if (getCurrentActivity() == null) return;
try {
getCurrentActivity().registerReceiver(
receiver,
new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
);
Log.d(TAG, "Receiver Registered");
isReceiverRegistered = true;
} catch (Exception e) {
e.printStackTrace();
}
}
private void requestOtp(final Promise promise) {
SmsRetrieverClient client = SmsRetriever.getClient(reactContext);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.e(TAG, "started sms listener");
promise.resolve(true);
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Could not start sms listener", e);
promise.reject(e);
}
});
}
private void unregisterReceiver(BroadcastReceiver receiver) {
if (isReceiverRegistered && getCurrentActivity() != null && receiver != null) {
try {
getCurrentActivity().unregisterReceiver(receiver);
Log.d(TAG, "Receiver UnRegistered");
isReceiverRegistered = false;
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onHostResume() {
registerReceiverIfNecessary(mReceiver);
}
@Override
public void onHostPause() {
unregisterReceiver(mReceiver);
}
@Override
public void onHostDestroy() {
unregisterReceiver(mReceiver);
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
if (requestCode == RESOLVE_HINT) {
if (resultCode == Activity.RESULT_OK) {
Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
// credential.getId(); <-- will need to process phone number string
requestHintCallback.resolve(credential.getId());
}
}
}
@Override
public void onNewIntent(Intent intent) {
}
}
| 34.033333 | 124 | 0.665687 |
abb43d7880d863db29c6fac26cea8913b0b35cf9 | 3,076 | package com.revature.controllers;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.revature.models.Approvals;
import com.revature.models.Event;
import com.revature.services.ApprovalService;
public class ApprovalController {
public static ApprovalService as = new ApprovalService();
public static Gson gson = new Gson();
public static void getApprovalById(HttpServletRequest request, HttpServletResponse response) throws IOException {
String input = request.getParameter("id");
int id;
try {
id = Integer.parseInt(input);
} catch(NumberFormatException e) {
e.printStackTrace();
response.sendError(400, "ID parameter incorrectly formatted");
return;
}
Approvals a = as.getApprovalById(id);
response.getWriter().append((a != null) ? gson.toJson(a) : "{}");
}
public static void createApproval(HttpServletRequest request, HttpServletResponse response) throws JsonSyntaxException, JsonIOException, IOException {
Approvals a = gson.fromJson(request.getReader(), Approvals.class);
int approvalId = as.createApproval(a);
a.setApprovalId(approvalId);
response.getWriter().append((approvalId > 0) ? gson.toJson(a) : "{}");
}
// public List<Approvals> getAllApprovals() {
// return ar.getAllApprovals();
// }
// Update
public static void updateSupervisorApprovals(HttpServletRequest request, HttpServletResponse response) throws JsonSyntaxException, JsonIOException, IOException {
Approvals a = gson.fromJson(request.getReader(), Approvals.class);
as.updateSupervisorApprovals(a.getApprovalId(), a.getSupervisorApproval());
boolean success = a.getSupervisorApproval() > 0;
response.getWriter().append((success) ? gson.toJson(a) : "{}");
}
public static void updateDepartmentHeadApprovals(HttpServletRequest request, HttpServletResponse response) throws JsonSyntaxException, JsonIOException, IOException {
Approvals a = gson.fromJson(request.getReader(), Approvals.class);
as.updateDepartmentHeadApprovals(a.getApprovalId(), a.getDepartmentHeadApproval());
boolean success = a.getDepartmentHeadApproval() > 0;
response.getWriter().append((success) ? gson.toJson(a) : "{}");
}
public static void updateBenCoApprovals(HttpServletRequest request, HttpServletResponse response) throws JsonSyntaxException, JsonIOException, IOException {
Approvals a = gson.fromJson(request.getReader(), Approvals.class);
as.updateBenCoApprovals(a.getApprovalId(), a.getBenCoApproval());
boolean success = a.getBenCoApproval() > 0;
response.getWriter().append((success) ? gson.toJson(a) : "{}");
}
public static void deleteApproval(HttpServletRequest request, HttpServletResponse response) throws JsonSyntaxException, JsonIOException, IOException {
}
}
| 31.387755 | 167 | 0.736671 |
af784748a40d6fab4b17fde1ec4fc326b14b392f | 1,940 | /*
* Copyright 2014 - 2021 Blazebit.
*
* 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.blazebit.persistence.examples.itsm.model.ticket.entity;
import com.blazebit.persistence.examples.itsm.model.article.entity.LocalizedEntity;
import com.blazebit.persistence.examples.itsm.model.article.entity.LocalizedEntity_;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* @author Giovanni Lovato
* @since 1.4.0
*/
@Entity
public class TicketStatus extends LocalizedEntity
implements Comparable<TicketStatus> {
private boolean initial;
private boolean active;
private boolean assigneeRequired;
private boolean activityRequired;
private boolean scheduledActivityRequired;
private boolean publicCommentRequired;
private boolean appliedChangeRequired;
private boolean incidentReportRequired;
private String theme;
@OrderBy(LocalizedEntity_.NAME)
@ManyToMany
private SortedSet<TicketStatus> next = new TreeSet<>();
public TicketStatus(String name) {
this.setName(name);
}
public SortedSet<TicketStatus> getNext() {
return this.next;
}
@Override
public int compareTo(TicketStatus o) {
return Comparator.comparing(TicketStatus::getName).compare(this, o);
}
}
| 26.575342 | 84 | 0.743814 |
dbc6695404c46659f2101627d8876f70bb977c3e | 413 | package org.schema.api.model.thing.action.assessAction.chooseAction;
import org.schema.api.model.thing.action.assessAction.AssessAction;
public class ChooseAction extends AssessAction
{
private String actionOption;//Notes - Allowed types- [Text, Thing]
public String getActionOption()
{
return actionOption;
}
public void setActionOption(String actionOption)
{
this.actionOption = actionOption;
}
} | 22.944444 | 68 | 0.789346 |
fbcd907f02388be58eeba97df6b9d3e246fabc65 | 4,313 | package ru.unatco.rss.activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.volley.toolbox.Volley;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import ru.unatco.rss.R;
import ru.unatco.rss.adapters.FeedAdapter;
import ru.unatco.rss.data.local.RssDataStore;
import ru.unatco.rss.data.local.RssDatabaseHelper;
import ru.unatco.rss.model.Item;
import ru.unatco.rss.model.Subscription;
import ru.unatco.rss.presenters.FeedPresenter;
public class FeedActivity extends AppCompatActivity implements FeedPresenter.FeedListener {
public static final String ARG_SUB = "ru.unatco.rss.Subscription";
private static FeedPresenter mPresenter;
@Bind(R.id.toolbar)
Toolbar mToolbar;
@Bind(android.R.id.list)
ListView mListView;
@Bind(android.R.id.progress)
ProgressBar mProgressBar;
@Bind(R.id.error_message)
TextView mErrorMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Item item = (Item) adapterView.getAdapter().getItem(i);
Intent intent = new Intent(FeedActivity.this, ItemActivity.class);
intent.putExtra(ItemActivity.ARG_ITEM, item);
startActivity(intent);
}
});
mListView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
if (mPresenter == null) {
Context appContext = getApplicationContext();
mPresenter = new FeedPresenter(new RssDataStore(new RssDatabaseHelper(appContext)), Volley.newRequestQueue(appContext));
}
}
@Override
protected void onResume() {
super.onResume();
mPresenter.setListener(this);
Subscription sub = getIntent().getParcelableExtra(ARG_SUB);
if (sub != null) {
getSupportActionBar().setTitle(sub.getmTitle());
mPresenter.setSubscription(sub);
} else {
getSupportActionBar().setTitle(mPresenter.getSubscription().getmTitle());
}
mPresenter.fetchItems();
}
@Override
protected void onPause() {
super.onPause();
mPresenter.clearListener();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_feed, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onFetchSuccess(List<Item> items) {
mListView.setAdapter(new FeedAdapter(LayoutInflater.from(getApplicationContext()), items));
mListView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mErrorMessage.setVisibility(View.GONE);
}
@Override
public void onFetchError(Throwable error) {
mListView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
mErrorMessage.setVisibility(View.VISIBLE);
}
}
| 32.923664 | 132 | 0.69163 |
37a8466fcded64c5848871dc4f2622d754a20c7b | 1,883 | package org.telegram.api.message.media;
import org.telegram.api.photo.TLAbsPhoto;
import org.telegram.tl.StreamingUtils;
import org.telegram.tl.TLContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The type TL message media photo.
*/
public class TLMessageMediaPhoto extends TLAbsMessageMedia {
/**
* The constant CLASS_ID.
*/
public static final int CLASS_ID = 0x3d8ce53d;
private TLAbsPhoto photo;
private String caption;
/**
* Instantiates a new TL message media photo.
*/
public TLMessageMediaPhoto() {
super();
}
@Override
public int getClassId() {
return CLASS_ID;
}
/**
* Gets photo.
*
* @return the photo
*/
public TLAbsPhoto getPhoto() {
return this.photo;
}
/**
* Sets photo.
*
* @param photo the photo
*/
public void setPhoto(TLAbsPhoto photo) {
this.photo = photo;
}
/**
* Gets caption.
*
* @return the caption
*/
public String getCaption() {
return this.caption;
}
/**
* Sets caption.
*
* @param caption the caption
*/
public void setCaption(String caption) {
this.caption = caption;
}
@Override
public void serializeBody(OutputStream stream)
throws IOException {
StreamingUtils.writeTLObject(this.photo, stream);
StreamingUtils.writeTLString(this.caption, stream);
}
@Override
public void deserializeBody(InputStream stream, TLContext context)
throws IOException {
this.photo = ((TLAbsPhoto) StreamingUtils.readTLObject(stream, context));
this.caption = StreamingUtils.readTLString(stream);
}
@Override
public String toString() {
return "messageMediaPhoto#3d8ce53d";
}
} | 21.157303 | 81 | 0.618694 |
0bfa0cc1df25ae9da7353243b28c9f7fa6813996 | 3,381 | package org.example;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* 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.
*/
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import java.io.*;
/**
* @author ironman
*/
@Mojo(name = "touch", defaultPhase = LifecyclePhase.COMPILE)
public class MyMojo extends AbstractMojo {
@Parameter(name = "output", defaultValue = "${project.build.directory}")
private File output;
public void execute() throws MojoExecutionException {
File f = output;
if (!f.exists()) {
f.mkdirs();
}
try {
printFileName(f);
} catch (Exception e) {
throw new MojoExecutionException("instrument error", e);
}
File touch = new File(f, "touch.txt");
FileWriter w = null;
try {
w = new FileWriter(touch);
w.write("touch.txt");
} catch (IOException e) {
throw new MojoExecutionException("Error creating file " + touch, e);
} finally {
if (w != null) {
try {
w.close();
} catch (IOException e) {
// ignore
}
}
}
}
private void printFileName(File root) throws IOException {
if (root.isDirectory()) {
for (File file : root.listFiles()) {
printFileName(file);
}
}
if (root.getName().endsWith(".class")) {
System.out.println(root.getName());
FileOutputStream fos = null;
try {
final byte[] instrumentBytes = instrument(root);
fos = new FileOutputStream(root);
fos.write(instrumentBytes);
fos.flush();
} catch (MojoExecutionException e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}
}
private byte[] instrument(File clsFile) throws MojoExecutionException {
try {
ClassReader cr = new ClassReader(new FileInputStream(clsFile));
ClassWriter cw = new ClassWriter(cr, ClassReader.SKIP_DEBUG);
final ClassVisitor cv = new MethodCoverageClassVisitor(cw);
cr.accept(cv, ClassReader.SKIP_DEBUG);
return cw.toByteArray();
} catch (Exception e) {
throw new MojoExecutionException("instrument error", e);
}
}
}
| 31.305556 | 80 | 0.589766 |
64d48f03fcc977acc2eadfe72d28f4bbb9f2f827 | 2,183 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.eventgrid.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for VerifiedPartnerProvisioningState. */
public final class VerifiedPartnerProvisioningState extends ExpandableStringEnum<VerifiedPartnerProvisioningState> {
/** Static value Creating for VerifiedPartnerProvisioningState. */
public static final VerifiedPartnerProvisioningState CREATING = fromString("Creating");
/** Static value Updating for VerifiedPartnerProvisioningState. */
public static final VerifiedPartnerProvisioningState UPDATING = fromString("Updating");
/** Static value Deleting for VerifiedPartnerProvisioningState. */
public static final VerifiedPartnerProvisioningState DELETING = fromString("Deleting");
/** Static value Succeeded for VerifiedPartnerProvisioningState. */
public static final VerifiedPartnerProvisioningState SUCCEEDED = fromString("Succeeded");
/** Static value Canceled for VerifiedPartnerProvisioningState. */
public static final VerifiedPartnerProvisioningState CANCELED = fromString("Canceled");
/** Static value Failed for VerifiedPartnerProvisioningState. */
public static final VerifiedPartnerProvisioningState FAILED = fromString("Failed");
/**
* Creates or finds a VerifiedPartnerProvisioningState from its string representation.
*
* @param name a name to look for.
* @return the corresponding VerifiedPartnerProvisioningState.
*/
@JsonCreator
public static VerifiedPartnerProvisioningState fromString(String name) {
return fromString(name, VerifiedPartnerProvisioningState.class);
}
/**
* Gets known VerifiedPartnerProvisioningState values.
*
* @return known VerifiedPartnerProvisioningState values.
*/
public static Collection<VerifiedPartnerProvisioningState> values() {
return values(VerifiedPartnerProvisioningState.class);
}
}
| 42.803922 | 116 | 0.774164 |
0726eb4a85562fddbb0dff44b5e2b88e044a9da5 | 1,618 | package com.evolveum.midpoint.studio.impl.client;
import com.evolveum.midpoint.common.LocalizationService;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.util.LocalizableMessage;
import com.evolveum.midpoint.util.exception.CommonException;
import java.util.Locale;
/**
* Created by Viliam Repan (lazyman).
*/
public class LocalizationServiceImpl implements LocalizationService {
@Override
public String translate(LocalizableMessage msg, Locale locale, String defaultMessage) {
String translated = translate(msg, locale);
return translated != null ? translated : defaultMessage;
}
@Override
public String translate(PolyString polyString, Locale locale, boolean allowOrig) {
String def = allowOrig ? polyString.getOrig() : null;
return translate(polyString.getOrig(), new Object[]{}, locale, def);
}
@Override
public Locale getDefaultLocale() {
return Locale.getDefault();
}
@Override
public String translate(String key, Object[] params, Locale locale) {
return translate(key, params, locale, null);
}
@Override
public String translate(String key, Object[] params, Locale locale, String defaultMessage) {
if (defaultMessage != null) {
return defaultMessage;
}
return key;
}
@Override
public String translate(LocalizableMessage msg, Locale locale) {
return msg != null ? msg.getFallbackMessage() : null;
}
@Override
public <T extends CommonException> T translate(T e) {
return e;
}
}
| 28.892857 | 96 | 0.691595 |
f7a1a9afa597753fedfed0fc078b30d23be3ef38 | 3,879 | package com.infodart.peerhuntr.jpa.dao.impl;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.infodart.peerhuntr.jpa.dao.PersonalityTestDao;
import com.infodart.peerhuntr.jpa.dao.impl.basedao.AbstractGenericDao;
import com.infodart.peerhuntr.jpa.entity.personalityTest.PersonalityMaster;
import com.infodart.peerhuntr.jpa.entity.personalityTest.QuestionSectionQualityMapping;
import com.infodart.peerhuntr.jpa.entity.personalityTest.SectionMaster;
import com.infodart.peerhuntr.jpa.entity.personalityTest.SectionQualityMapping;
import com.infodart.peerhuntr.jpa.entity.personalityTest.UserQuestionAnswer;
import com.infodart.peerhuntr.jpa.entity.user.User;
@Repository
public class PersonalityTestDaoImpl extends AbstractGenericDao<UserQuestionAnswer> implements PersonalityTestDao{
@Autowired
private SessionFactory sessionFactory;
@Override
public List<Object> getTest() {
List<Object> questions = new ArrayList<Object>();
/*questions = sessionFactory.getCurrentSession() .createQuery("from QuestionMaster q,AnswerMaster a "
+ " where a.questionMaster.questionId=q.questionId and q.status = ? order by q.questionNumberId,q.sectionMaster.sectionId,a.answerId")
.setParameter(0, (byte)1).list();*/
questions = getSession().createQuery("from QuestionMaster where status = ? order by questionNumberId,sectionMaster.sectionId")
.setParameter(0, (byte)1).list();
return questions;
}
@Override
public boolean updatePersonalityType(int personalityId,int userId) {
Query query= getSession().createQuery("update User set personalityMaster.personalityId=?,status=? where userId=?")
.setParameter(0, personalityId)
.setParameter(1, (byte)1)
.setParameter(2, userId);
int a= query.executeUpdate();
if(a==1)
return true;
else
return false;
}
@Override
public boolean updateUserLoginStatus(int userLoginId) {
Query query= getSession().createQuery("update UserLogin set status=? where userLoginId=?")
.setParameter(0, (byte)1)
.setParameter(1, userLoginId);
int a= query.executeUpdate();
if(a==1)
return true;
else
return false;
}
@Override
public int getUserLoginId(int userId) {
List<User> test = getSession().createQuery("from User where userId=?")
.setParameter(0, userId).list();
return test.get(0).getUserLogin().getUserLoginId();
}
@Override
public boolean testGivenByUser(int userId) {
List<Object> test = getSession().createQuery("from UserQuestionAnswer where user.userId=?")
.setParameter(0, userId).list();
if(test.size()>0)
return true;
else
return false;
}
@Override
public void deleteTest(int userId) {
try {
Query query= getSession().createQuery("delete from UserQuestionAnswer u where user.userId=:userId")
.setParameter("userId", userId);
int a= query.executeUpdate();
System.out.println(a);
}catch(Exception e) {
e.printStackTrace();
}
}
@Override
public List<SectionQualityMapping> getAllSectionQualities() {
Query query = getSession().getNamedQuery("SectionQualityMapping.findAll");
return query.list();
}
@Override
public List<PersonalityMaster> getAllPersonalities() {
Query query = getSession().getNamedQuery("PersonalityMaster.findAll");
return query.list();
}
public List<QuestionSectionQualityMapping> getAllQuestionQualities(){
Query query = getSession().getNamedQuery("QuestionSectionQualityMapping.findAll");
return query.list();
}
}
| 29.165414 | 139 | 0.712813 |
91b403be73d33a6735c623361fa8da1e0f51033d | 589 | package ua.training.service;
import ua.training.controller.exception.OrderCheckException;
import ua.training.controller.exception.OrderNotFoundException;
import ua.training.dto.BankCardDto;
import ua.training.dto.OrderCheckDto;
import java.util.List;
public interface OrderCheckService {
List<OrderCheckDto> showAllChecks();
OrderCheckDto showCheckById(Long checkId) throws OrderCheckException;
List<OrderCheckDto> showChecksByUser(Long userId);
OrderCheckDto createCheckDto(Long orderDtoId, BankCardDto bankCardDtoId, Long userId) throws OrderNotFoundException;
}
| 28.047619 | 120 | 0.82343 |
21a5249617a9b408966825d96efda4b40ce38cf7 | 5,089 | /*
* Copyright (C) 2015 Jorge Castillo Pérez
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jorgecastilloprz.corleone;
import com.github.jorgecastilloprz.corleone.annotations.Execution;
import com.github.jorgecastilloprz.corleone.annotations.Job;
import com.github.jorgecastilloprz.corleone.annotations.Param;
import com.github.jorgecastilloprz.corleone.annotations.Rule;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.MirroredTypeException;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
/**
* Data model for classes flagged with @Job annotation. This entity will be used to wrap all the
* parsing logic and will not be used along the whole AP. It will be mapped to a JobEntity
* later on.
*
* @author Jorge Castillo Pérez
*/
class JobAnnotatedClass {
private TypeElement annotatedClassElement;
private List<VariableElement> paramElements;
private ExecutableElement executionMethod;
private LinkedList<RuleDataModel> rules;
private Elements elementUtils;
public JobAnnotatedClass(TypeElement classElement, Elements elementUtils) {
this.annotatedClassElement = classElement;
this.elementUtils = elementUtils;
this.rules = new LinkedList<>();
parseRules();
parseParamFields(elementUtils);
parseExecutionMethod(elementUtils);
}
/**
* While parsing rules we are going to access previousJob classes to get their canonical names.
* Since annotation processing runs before compiling java sources, needed classes could
* not be compiled yet. We need to catch MirroredTypeException to reach the TypeMirror of the
* class and be able to get the name. The "try" case would happen if there is a compiled .class
* with a @Job annotation into a third party jar.
*/
private void parseRules() {
Job jobAnnotation = annotatedClassElement.getAnnotation(Job.class);
Rule[] ruleAnnotations = jobAnnotation.value();
for (Rule rule : ruleAnnotations) {
try {
rules.add(new RuleDataModel(rule.context(), rule.previousJob().getCanonicalName()));
} catch (MirroredTypeException exception) {
DeclaredType classTypeMirror = (DeclaredType) exception.getTypeMirror();
TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
rules.add(
new RuleDataModel(rule.context(), classTypeElement.getQualifiedName().toString()));
}
}
}
private void parseParamFields(Elements elementUtils) {
paramElements = new ArrayList<>();
List<? extends Element> elementMembers = elementUtils.getAllMembers(annotatedClassElement);
List<VariableElement> fieldElements = ElementFilter.fieldsIn(elementMembers);
for (VariableElement fieldElement : fieldElements) {
if (fieldElement.getAnnotation(Param.class) != null) {
paramElements.add(fieldElement);
}
}
}
private void parseExecutionMethod(Elements elementUtils) {
List<? extends Element> elementMembers = elementUtils.getAllMembers(annotatedClassElement);
List<ExecutableElement> elementMethods = ElementFilter.methodsIn(elementMembers);
for (ExecutableElement methodElement : elementMethods) {
if (methodElement.getAnnotation(Execution.class) != null) {
executionMethod = methodElement;
return;
}
}
}
public List<VariableElement> getParamElements() {
return paramElements;
}
public String getExecutionMethodName() {
return executionMethod.getSimpleName().toString();
}
public List<RuleDataModel> getRules() {
return rules;
}
public String getPreviousJobForContext(String context) {
for (RuleDataModel currentRule : rules) {
if (currentRule.getContext().equals(context)) {
return currentRule.getPreviousJobQualifiedName();
}
}
return "";
}
public String getPackageName() {
return elementUtils.getPackageOf(annotatedClassElement).getQualifiedName().toString();
}
public String getClassName() {
return annotatedClassElement.getSimpleName().toString();
}
public String getQualifiedName() {
return annotatedClassElement.getQualifiedName().toString();
}
public TypeMirror getClassType() {
return annotatedClassElement.asType();
}
}
| 36.092199 | 97 | 0.747495 |
08a6f0ed997c30da996b852af1fbf5a90ffededf | 4,509 | /*
Copyright 2017 Digital Learning Sciences (DLS) at the
University Corporation for Atmospheric Research (UCAR),
P.O. Box 3000, Boulder, CO 80307
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.dlese.dpc.schemedit.sif;
import org.dlese.dpc.schemedit.SchemEditUtils;
import org.dlese.dpc.xml.Dom4jUtils;
import org.dlese.dpc.xml.XMLFileFilter;
import java.util.*;
import java.io.File;
import org.dom4j.*;
/**
* Manages configurations of SIF fields that take references to other SIF
* objects.
*
* @author Jonathan Ostwald
*/
public class SIFRefIdManager {
private static boolean debug = true;
private File sourceDir = null;
private Map map = null;
private static SIFRefIdManager instance = null;
private static String path = null;
/**
* Gets singleton SIFRefIdManager instance.
*
* @return The instance value
*/
public static SIFRefIdManager getInstance() {
if (instance == null) {
try {
instance = new SIFRefIdManager();
} catch (Exception e) {
if (path == null) {
// not configured, fail silently
}
else {
prtln("getInstance error: " + e.getMessage());
}
}
}
return instance;
}
/**
* Constructor for the SIFRefIdManager object
*
* @param path directory containing configuration files.
* @exception Exception NOT YET DOCUMENTED
*/
private SIFRefIdManager() throws Exception, Exception {
if (path == null)
throw new Exception("path does not have a value");
this.sourceDir = new File(path);
if (!sourceDir.exists() || !sourceDir.isDirectory())
throw new Exception("directory does not exist or is not a directory at " + path);
this.init();
}
/**
* Sets the path attribute of the SIFRefIdManager class
*
* @param sourceDir The new path value
*/
public static void setPath(String sourceDir) {
path = sourceDir;
}
public static void reinit() {
instance = null;
}
/**
* Read configuration files for SIF frameworks and populate a map which stores
* the configurations keyed by xmlFormat.
*/
private void init() {
prtln ("init");
this.map = new HashMap();
File[] files = sourceDir.listFiles(new XMLFileFilter());
for (int i = 0; i < files.length; i++) {
try {
SIFRefIdMap refIdMap = new SIFRefIdMap(files[i]);
refIdMap.report();
this.map.put(refIdMap.getXmlFormat(), refIdMap);
} catch (Exception e) {
prtln("could not instantiage RefIdMap for " + files[i] + ": " + e.getMessage());
}
}
}
/**
* Gets the refIdMap for the specified SIF Framework.
*
* @param xmlFormat NOT YET DOCUMENTED
* @return The refIdMap value
*/
public SIFRefIdMap getRefIdMap(String xmlFormat) {
return (SIFRefIdMap) map.get(xmlFormat);
}
/**
* Returns list of supported SIF xmlFormats.
*
* @return The xmlFormats value
*/
public List getXmlFormats() {
List formats = new ArrayList();
for (Iterator i = this.map.keySet().iterator(); i.hasNext(); )
formats.add((String) i.next());
return formats;
}
/**
* Returns true of specified xmlFormat is configured.
*
* @param xmlFormat NOT YET DOCUMENTED
* @return NOT YET DOCUMENTED
*/
public boolean hasXmlFormat(String xmlFormat) {
return this.map.containsKey(xmlFormat);
}
/**
* The main program for the SIFRefIdManager class
*
* @param args The command line arguments
* @exception Exception NOT YET DOCUMENTED
*/
public static void main(String[] args) throws Exception {
String path = "C:/Documents and Settings/ostwald/devel/SIF/dcs_config/sifTypePaths";
SIFRefIdManager.setPath(path);
SIFRefIdManager refIdMgr = SIFRefIdManager.getInstance();
prtln("refIdMgr instantiated");
for (Iterator i = refIdMgr.map.values().iterator(); i.hasNext(); ) {
((SIFRefIdMap) i.next()).report();
}
}
/**
* NOT YET DOCUMENTED
*
* @param s NOT YET DOCUMENTED
*/
protected static void prtln(String s) {
if (debug) {
SchemEditUtils.prtln(s, "SIFRefIdManager");
}
}
}
| 25.05 | 86 | 0.681969 |
60c5bef72b73c0fcb4808d1ae0ce5fe010b18c7a | 6,746 | package com.multilevel.treelist;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* @param
*/
public abstract class TreeListViewAdapter extends BaseAdapter
{
protected Context mContext;
/**
* 存储所有可见的Node
*/
protected List<Node> mNodes = new ArrayList<>();
protected LayoutInflater mInflater;
/**
* 存储所有的Node
*/
protected List<Node> mAllNodes = new ArrayList<>();
/**
* 点击的回调接口
*/
private OnTreeNodeClickListener onTreeNodeClickListener;
/**
* 默认不展开
*/
private int defaultExpandLevel = 0;
/** 展开与关闭的图片*/
private int iconExpand = -1,iconNoExpand = -1;
public void setOnTreeNodeClickListener(
OnTreeNodeClickListener onTreeNodeClickListener) {
this.onTreeNodeClickListener = onTreeNodeClickListener;
}
public TreeListViewAdapter(ListView mTree, Context context, List<Node> datas,
int defaultExpandLevel, int iconExpand, int iconNoExpand) {
this.iconExpand = iconExpand;
this.iconNoExpand = iconNoExpand;
for (Node node:datas){
node.getChildren().clear();
node.iconExpand = iconExpand;
node.iconNoExpand = iconNoExpand;
}
this.defaultExpandLevel = defaultExpandLevel;
mContext = context;
/**
* 对所有的Node进行排序
*/
mAllNodes = TreeHelper.getSortedNodes(datas, defaultExpandLevel);
/**
* 过滤出可见的Node
*/
mNodes = TreeHelper.filterVisibleNode(mAllNodes);
mInflater = LayoutInflater.from(context);
/**
* 设置节点点击时,可以展开以及关闭;并且将ItemClick事件继续往外公布
*/
mTree.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
expandOrCollapse(position);
if (onTreeNodeClickListener != null) {
onTreeNodeClickListener.onClick(mNodes.get(position),
position);
}
}
});
}
/**
*
* @param mTree
* @param context
* @param datas
* @param defaultExpandLevel
* 默认展开几级树
*/
public TreeListViewAdapter(ListView mTree, Context context, List<Node> datas,
int defaultExpandLevel) {
this(mTree,context,datas,defaultExpandLevel,-1,-1);
}
/**
* 清除掉之前数据并刷新 重新添加
* @param mlists
* @param defaultExpandLevel 默认展开几级列表
*/
public void addDataAll(List<Node> mlists,int defaultExpandLevel){
mAllNodes.clear();
addData(-1,mlists,defaultExpandLevel);
}
/**
* 在指定位置添加数据并刷新 可指定刷新后显示层级
* @param index
* @param mlists
* @param defaultExpandLevel 默认展开几级列表
*/
public void addData(int index,List<Node> mlists,int defaultExpandLevel){
this.defaultExpandLevel = defaultExpandLevel;
notifyData(index,mlists);
}
/**
* 在指定位置添加数据并刷新
* @param index
* @param mlists
*/
public void addData(int index,List<Node> mlists){
notifyData(index,mlists);
}
/**
* 添加数据并刷新
* @param mlists
*/
public void addData(List<Node> mlists){
addData(mlists,defaultExpandLevel);
}
/**
* 添加数据并刷新 可指定刷新后显示层级
* @param mlists
* @param defaultExpandLevel
*/
public void addData(List<Node> mlists,int defaultExpandLevel){
this.defaultExpandLevel = defaultExpandLevel;
notifyData(-1,mlists);
}
/**
* 添加数据并刷新
* @param node
*/
public void addData(Node node){
addData(node,defaultExpandLevel);
}
/**
* 添加数据并刷新 可指定刷新后显示层级
* @param node
* @param defaultExpandLevel
*/
public void addData(Node node,int defaultExpandLevel){
List<Node> nodes = new ArrayList<>();
nodes.add(node);
this.defaultExpandLevel = defaultExpandLevel;
notifyData(-1,nodes);
}
/**
* 刷新数据
* @param index
* @param mListNodes
*/
private void notifyData(int index,List<Node> mListNodes){
for (int i = 0; i < mListNodes.size(); i++) {
Node node = mListNodes.get(i);
node.getChildren().clear();
node.iconExpand = iconExpand;
node.iconNoExpand = iconNoExpand;
}
for (int i = 0; i < mAllNodes.size(); i++) {
Node node = mAllNodes.get(i);
node.getChildren().clear();
node.isNewAdd = false;
}
if (index != -1){
mAllNodes.addAll(index,mListNodes);
}else {
mAllNodes.addAll(mListNodes);
}
/**
* 对所有的Node进行排序
*/
mAllNodes = TreeHelper.getSortedNodes(mAllNodes, defaultExpandLevel);
/**
* 过滤出可见的Node
*/
mNodes = TreeHelper.filterVisibleNode(mAllNodes);
//刷新数据
notifyDataSetChanged();
}
/**
* 获取排序后所有节点
* @return
*/
public List<Node> getAllNodes(){
if(mAllNodes == null)
mAllNodes = new ArrayList<Node>();
return mAllNodes;
}
/**
* 相应ListView的点击事件 展开或关闭某节点
*
* @param position
*/
public void expandOrCollapse(int position) {
Node n = mNodes.get(position);
if (n != null) {// 排除传入参数错误异常
if (!n.isLeaf()) {
n.setExpand(!n.isExpand());
mNodes = TreeHelper.filterVisibleNode(mAllNodes);
notifyDataSetChanged();// 刷新视图
}
}
}
@Override
public int getCount()
{
return mNodes.size();
}
@Override
public Object getItem(int position)
{
return mNodes.get(position);
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Node node = mNodes.get(position);
convertView = getConvertView(node, position, convertView, parent);
// 设置内边距
convertView.setPadding(node.getLevel() * 30, 3, 3, 3);
return convertView;
}
/**
* 设置多选
* @param node
* @param checked
*/
protected void setChecked(final Node node, boolean checked) {
node.setChecked(checked);
setChildChecked(node, checked);
if(node.getParent()!=null)
setNodeParentChecked(node.getParent(), checked);
notifyDataSetChanged();
}
/**
* 设置是否选中
* @param node
* @param checked
*/
public <T,B>void setChildChecked(Node<T,B> node,boolean checked){
if(!node.isLeaf()){
node.setChecked(checked);
for (Node childrenNode : node.getChildren()) {
setChildChecked(childrenNode, checked);
}
}else{
node.setChecked(checked);
}
}
private void setNodeParentChecked(Node node,boolean checked){
if(checked){
node.setChecked(checked);
if(node.getParent()!=null)
setNodeParentChecked(node.getParent(), checked);
}else{
List<Node> childrens = node.getChildren();
boolean isChecked = false;
for (Node children : childrens) {
if(children.isChecked()){
isChecked = true;
}
}
//如果所有自节点都没有被选中 父节点也不选中
if(!isChecked){
node.setChecked(checked);
}
if(node.getParent()!=null)
setNodeParentChecked(node.getParent(), checked);
}
}
public abstract View getConvertView(Node node, int position,
View convertView, ViewGroup parent);
}
| 21.484076 | 78 | 0.683368 |
c080a2d3633525c5ad2096befaf7ce361555e8fb | 4,415 | package wae.thesis.indiv.app.restapi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import wae.thesis.indiv.api.util.ApiMessages;
import wae.thesis.indiv.api.behavior.ServiceBehavior;
import wae.thesis.indiv.api.exception.CoreException;
import wae.thesis.indiv.api.exception.DataInvalidException;
import wae.thesis.indiv.api.item.ErrorCode;
import wae.thesis.indiv.api.item.UserRole;
import wae.thesis.indiv.api.model.ServiceInfo;
import wae.thesis.indiv.core.plugins.PluginManager;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import static org.springframework.web.bind.annotation.RequestMethod.*;
/**
* Created by Nguyen Tan Dat.
*/
@RestController
@RequestMapping("/api")
@Slf4j
public class AppApi {
private final PluginManager pluginManager;
@Autowired
public AppApi(PluginManager pluginManager) {
this.pluginManager = pluginManager;
}
@RequestMapping(path = "/{serviceId}", method = {GET, POST, PUT, DELETE})
public Object getServiceData(@PathVariable String serviceId,
@RequestParam Map<String, String> params,
HttpServletRequest httpServletRequest) {
return getServiceData(serviceId, null, null, params, httpServletRequest);
}
@RequestMapping(path = "/{serviceId}/{subServiceId}", method = {GET, POST, PUT, DELETE})
public Object getServiceData(@PathVariable String serviceId,
@PathVariable String subServiceId,
@RequestParam Map<String, String> params,
HttpServletRequest httpServletRequest) {
return getServiceData(serviceId, subServiceId, null, params, httpServletRequest);
}
@RequestMapping(path = "/{serviceId}/{subServiceId}/{functionId}", method = {GET, POST, PUT, DELETE})
public Object getServiceData(@PathVariable String serviceId,
@PathVariable String subServiceId,
@PathVariable String functionId,
@RequestParam Map<String, String> params,
HttpServletRequest httpServletRequest) {
ServiceBehavior serviceBehavior = (ServiceBehavior) pluginManager.getService(ServiceBehavior.class);
String path = serviceBehavior.buildPath(serviceId, subServiceId, functionId);
ServiceInfo serviceInfo = getServiceInfo(path, params, httpServletRequest);
return serviceBehavior.handlerAction(UserRole.GUEST, serviceInfo);
}
private ServiceInfo getServiceInfo(String path, Map<String, String> params, HttpServletRequest httpServletRequest) {
ServiceInfo serviceInfo = null;
String requestMethod = httpServletRequest.getMethod();
switch (requestMethod) {
case "GET":
serviceInfo = ServiceInfo.fromGETRequest(path, params);
break;
case "POST":
serviceInfo = ServiceInfo.fromPOSTRequest(path, getDataBody(httpServletRequest), params);
break;
case "PUT":
serviceInfo = ServiceInfo.fromPUTRequest(path, getDataBody(httpServletRequest), params);
break;
case "DELETE":
serviceInfo = ServiceInfo.fromDELETERequest(path, params);
break;
default:
break;
}
if (serviceInfo == null) {
throw new CoreException(
ApiMessages.unsupportedRequestMethod(requestMethod),
ErrorCode.CORE_EXCEPTION);
}
return serviceInfo;
}
private String getDataBody(HttpServletRequest request) {
try {
return request.getReader().lines()
.reduce("", (accumulator, actual) -> accumulator + actual);
} catch (IOException e) {
throw new DataInvalidException(
ApiMessages.couldNotReadDataFromRequest(),
ErrorCode.CORE_EXCEPTION);
}
}
}
| 36.487603 | 120 | 0.653454 |
650410cefee446fe54d053db47717a6db6152b20 | 4,828 | /*
* ===============================LICENSE_START======================================
* dcae-analytics
* ================================================================================
* Copyright © 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================LICENSE_END===========================================
*/
package org.onap.dcae.apod.analytics.cdap.tca.utils;
import com.google.common.base.Function;
import org.onap.dcae.apod.analytics.cdap.tca.settings.TCAAppPreferences;
import org.onap.dcae.apod.analytics.dmaap.domain.config.DMaaPMRSubscriberConfig;
import javax.annotation.Nonnull;
import static org.onap.dcae.apod.analytics.cdap.common.utils.ValidationUtils.isPresent;
/**
* Function which translates {@link TCAAppPreferences} to {@link DMaaPMRSubscriberConfig}
*
* @author Rajiv Singla . Creation Date: 11/17/2016.
*/
public class AppPreferencesToSubscriberConfigMapper implements Function<TCAAppPreferences, DMaaPMRSubscriberConfig> {
/**
* Factory Method to converts {@link TCAAppPreferences} to {@link DMaaPMRSubscriberConfig} object
*
* @param tcaAppPreferences tca app preferences
* @return DMaaP Subscriber Config
*/
public static DMaaPMRSubscriberConfig map(final TCAAppPreferences tcaAppPreferences) {
return new AppPreferencesToSubscriberConfigMapper().apply(tcaAppPreferences);
}
/**
* Implementation to convert {@link TCAAppPreferences} to {@link DMaaPMRSubscriberConfig} object
*
* @param tcaAppPreferences tca app preferences
*
* @return DMaaP Subscriber Config
*/
@Nonnull
@Override
public DMaaPMRSubscriberConfig apply(@Nonnull TCAAppPreferences tcaAppPreferences) {
// Create a new subscriber settings builder
final DMaaPMRSubscriberConfig.Builder subscriberConfigBuilder = new DMaaPMRSubscriberConfig.Builder(
tcaAppPreferences.getSubscriberHostName(), tcaAppPreferences.getSubscriberTopicName());
// Setup up any optional subscriber parameters if they are present
final Integer subscriberHostPortNumber = tcaAppPreferences.getSubscriberHostPort();
if (subscriberHostPortNumber != null) {
subscriberConfigBuilder.setPortNumber(subscriberHostPortNumber);
}
final String subscriberProtocol = tcaAppPreferences.getSubscriberProtocol();
if (isPresent(subscriberProtocol)) {
subscriberConfigBuilder.setProtocol(subscriberProtocol);
}
final String subscriberUserName = tcaAppPreferences.getSubscriberUserName();
if (isPresent(subscriberUserName)) {
subscriberConfigBuilder.setUserName(subscriberUserName);
}
final String subscriberUserPassword = tcaAppPreferences.getSubscriberUserPassword();
if (isPresent(subscriberUserPassword)) {
subscriberConfigBuilder.setUserPassword(subscriberUserPassword);
}
final String subscriberContentType = tcaAppPreferences.getSubscriberContentType();
if (isPresent(subscriberContentType)) {
subscriberConfigBuilder.setContentType(subscriberContentType);
}
final String subscriberConsumerId = tcaAppPreferences.getSubscriberConsumerId();
if (isPresent(subscriberConsumerId)) {
subscriberConfigBuilder.setConsumerId(subscriberConsumerId);
}
final String subscriberConsumerGroup = tcaAppPreferences.getSubscriberConsumerGroup();
if (isPresent(subscriberConsumerGroup)) {
subscriberConfigBuilder.setConsumerGroup(subscriberConsumerGroup);
}
final Integer subscriberTimeoutMS = tcaAppPreferences.getSubscriberTimeoutMS();
if (subscriberTimeoutMS != null) {
subscriberConfigBuilder.setTimeoutMS(subscriberTimeoutMS);
}
final Integer subscriberMessageLimit = tcaAppPreferences.getSubscriberMessageLimit();
if (subscriberMessageLimit != null) {
subscriberConfigBuilder.setMessageLimit(subscriberMessageLimit);
}
// return Subscriber settings
return subscriberConfigBuilder.build();
}
}
| 42.350877 | 117 | 0.685584 |
920c322aa8bc55e01fe369b57c01e1cd66a95e5f | 4,184 | package com.krista.apirouter.core;
import com.krista.apirouter.bean.ApiEntity;
import com.krista.apirouter.exception.ApiException;
import com.krista.apirouter.request.ApiParam;
import com.krista.apirouter.request.Head;
import com.krista.apirouter.response.ApiResponseCode;
import com.krista.apirouter.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
/**
* Api路由,Web模式启动
*
* @author krista
*/
public class ApiRouter implements ApplicationContextAware {
private static Logger logger = LoggerFactory.getLogger(ApiRouter.class);
/**
* Spring容器
*/
private ApplicationContext applicationContext;
/**
* Api上下文
*/
private ApiContext apiContext;
/**
* ApplicationContextAware接口实现
*
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 启动ApiRouter
*/
public void startup() throws ApiException {
if (logger.isInfoEnabled()) {
logger.info(">>>>>开始启动ApiRouter...");
}
Assert.notNull(this.applicationContext, "Spring上下文不能为空");
apiContext = new ApiContext();
long start = System.currentTimeMillis();
apiContext.loadApi(applicationContext);
long end = System.currentTimeMillis();
if (logger.isInfoEnabled()) {
logger.info(">>>>>ApiRouter启动成功!api个数:{},耗时(ms):{}",
apiContext.getApiCount(), (end - start));
}
}
/**
* 执行api服务
*
* @param requestData
* @throws ApiException
*/
public ApiParam executeApi(String requestData) throws ApiException {
// 请求的时候,参数为"",这里接收到的数据为"\"\"",因此不为空
logger.info("请求的数据:{}", requestData);
// 参数为空
if (StringUtils.isEmpty(requestData)) {
throw new ApiException(ApiResponseCode.RequestDataIsEmpty);
}
// Url decode
if (requestData.contains("%")) {
try {
requestData = URLDecoder.decode(requestData, "utf-8");
} catch (UnsupportedEncodingException e) {
logger.info("url解码时遇到未知编码方式");
}
}
// 解析出ApiParam
ApiParam apiParam = null;
try {
apiParam = JsonUtil.toObject(requestData, ApiParam.class);
} catch (Exception e) {
logger.error("对象序列化失败", e);
}
return this.executeApi(apiParam);
}
/**
* 执行api服务
*
* @param apiParam
* @throws ApiException
*/
public ApiParam executeApi(ApiParam apiParam) throws ApiException {
// 参数格式错误
if (apiParam == null) {
logger.info("请求数据为空");
throw new ApiException(ApiResponseCode.RequestDataFormatError);
}
// 验证参数头
Head head = apiParam.getHead();
if (head == null) {
logger.info("请求头为空");
throw new ApiException(ApiResponseCode.RequestHeadIsEmpty);
}
String module = head.getModule();
String apiNo = head.getApiNo();
if (!apiContext.isValidApi(module, apiNo)) {
throw new ApiException(ApiResponseCode.ApiNoNotExist);
}
String version = head.getVersion();
if (!apiContext.isValidVersion(module, apiNo, version)) {
throw new ApiException(ApiResponseCode.VersionIsNotAvailable);
}
// 获取Api信息,并执行Api
ApiEntity apiEntity = apiContext.getApiEntity(module, apiNo, version);
if (apiEntity == null) {
throw new ApiException(ApiResponseCode.ApiNoNotExist);
}
ApiService apiService = (ApiService) apiEntity.getApiInfo();
return apiService.execute(apiParam);
}
} | 28.657534 | 100 | 0.631453 |
63af5e8a8f1bd5b3f7d4d9a692363196b7d562ea | 1,641 | package packageName.web;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.List;
public abstract class AbstractCrudController<S extends IService<T>, T, K extends Serializable> {
protected final S service;
public AbstractCrudController(S service) {
this.service = service;
}
@GetMapping("/{id}")
public T get(@PathVariable K id) {
return service.getById(id);
}
@GetMapping
public List<T> listAll(QueryWrapper<T> filtering) {
return service.list(filtering);
}
@GetMapping("/filtering")
public IPage<T> page(IPage<T> page, QueryWrapper<T> filtering) {
return service.page(page, filtering);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public T save(@RequestBody T t) {
service.save(t);
return t;
}
@PatchMapping
public T update(@RequestBody T t) {
service.updateById(t);
return t;
}
@PostMapping("/batch")
@ResponseStatus(HttpStatus.CREATED)
public void saveBatch(@RequestBody List<T> t) {
service.saveBatch(t);
}
@PatchMapping("/batch")
public void update(@RequestBody List<T> t) {
service.updateBatchById(t);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable K id) {
service.removeById(id);
}
}
| 24.863636 | 96 | 0.67337 |
8d9dd537c58cae490b91b469978f3ff68f52d9b5 | 3,443 | package edu.cs.scu.dao.impl;
import com.alibaba.fastjson.JSON;
import edu.cs.scu.bean.UserBean;
import edu.cs.scu.common.constants.TableConstants;
import edu.cs.scu.conf.JedisPoolManager;
import edu.cs.scu.dao.BaseDao;
import edu.cs.scu.javautils.DateUtil;
import redis.clients.jedis.ShardedJedis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 用户信息数据库接口
* <p>
* Created by Wang Han on 2017/6/19 13:58.
* E-mail address is [email protected].
* Copyright © 2017 Wang Han. SCU. All Rights Reserved.
*/
public class UserDaoImpl extends BaseDao {
@Override
public void add(List<Object> objectList) {
ShardedJedis jedis = JedisPoolManager.getResource();
Map<String, String> userTableMap = new HashMap<>();
for (Object o : objectList) {
UserBean userBean = (UserBean) o;
String Key = String.valueOf(userBean.getShopId()) + "||" + userBean.getMac();
String value = JSON.toJSONString(userBean);
userTableMap.put(Key, value);
}
jedis.hmset(TableConstants.TABLE_USER, userTableMap);
jedis.close();
}
@Override
public Object get(String key) {
ShardedJedis jedis = JedisPoolManager.getResource();
List<String> userList = jedis.hmget(TableConstants.TABLE_USER, key);
UserBean user = JSON.parseObject(userList.get(0), UserBean.class);
jedis.close();
return user;
}
@Override
public List<Object> get(List<String> keys) {
ShardedJedis jedis = JedisPoolManager.getResource();
List<String> userList = jedis.hmget(TableConstants.TABLE_USER, keys.toArray(new String[0]));
List<Object> userBeanList = new ArrayList<>();
for (String user : userList) {
userBeanList.add(JSON.parseObject(user, UserBean.class));
}
jedis.close();
return userBeanList;
}
//更新所有驻留时长
public void updateStayTime() {
ShardedJedis jedis = JedisPoolManager.getResource();
Map<String, String> map = jedis.hgetAll(TableConstants.TABLE_USER);
if(map.size() > 0) {
List<Object> userBeanList = new ArrayList<>();
for (Map.Entry<String, String> user : map.entrySet()) {
UserBean userBean = JSON.parseObject(user.getValue(), UserBean.class);
String firstVisitTime = jedis.lindex(user.getKey(), 0);
userBean.setFirst_time(DateUtil.stampToDate(firstVisitTime));
Long len = jedis.llen(user.getKey());
String LastVisitTime = "";
Long stayTime = 0L;
if (len > 1) {
LastVisitTime = jedis.lindex(user.getKey(), len - 1);
stayTime = Long.valueOf(LastVisitTime) - Long.valueOf(firstVisitTime) + 3;
userBean.setRecent_time(DateUtil.stampToDate(LastVisitTime));
} else {
stayTime = 3000L;
userBean.setRecent_time("-");
}
Long visitCycle = 0L;
userBean.setStayTime(stayTime);
userBean.setVisitCycle(visitCycle);
userBeanList.add(userBean);
}
System.out.println("insert ....");
this.add(userBeanList);
}
System.out.println("nothing insert ....");
jedis.close();
}
}
| 36.242105 | 100 | 0.607029 |
0ff6ad98ea6ec5e2936fe177e757f22f025a120d | 678 | public class Bank2Ans5to10Test {
static final int EVEN = 0;
static final int ODD = 1;
public static void main(String[] args) {
SequenceGenerator sg = new SequenceGenerator(1, 100);
sg.createSequence();
sg.printCondition(EVEN);
sg.printCondition(ODD);
System.out.printf("1 ~ 100까지 4의 배수 합: %d\n", sg.findAndSum(4));
sg.printRandomCondition(2, 10);
// 일단 1 ~ 100을 순회함
// 2 ~ 10사이의 랜덤값을 매번 변경함
// 랜덤한 숫자만큼 이동을 함
sg.printRandomTravel(2, 10);
// 일단 1 ~ 100을 순회함
// 2 ~ 10사이의 랜덤값을 매번 변경함
// 랜덤 뽑은 근저리의 배수를 출력해야함
sg.printRandomTimesTravel(2, 10);
}
}
| 25.111111 | 71 | 0.567847 |
d3d90f086f4fcb10c1df4ec67e7903a0372bff34 | 1,703 | package br.com.mybooks.store.controllers;
import br.com.mybooks.store.daos.BookDao;
import br.com.mybooks.store.models.Book;
import br.com.mybooks.store.models.Cart;
import br.com.mybooks.store.models.CartItem;
import br.com.mybooks.store.models.PriceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
@Controller
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
@RequestMapping("/cart")
public class CartController {
@Autowired
private BookDao bookDao;
@Autowired
private Cart cart;
@RequestMapping("/add")
public ModelAndView add(Integer bookId, PriceType priceType) {
ModelAndView modelAndView = new ModelAndView("redirect:/cart");
CartItem cartItem = createItem(bookId, priceType);
cart.add(cartItem);
return modelAndView;
}
@RequestMapping(method = RequestMethod.GET)
public ModelAndView items() {
return new ModelAndView("carts/items");
}
@RequestMapping("/remove")
public ModelAndView remove(Integer bookId, PriceType priceType) {
cart.remove(bookId, priceType);
return new ModelAndView("redirect:/cart");
}
private CartItem createItem(Integer bookId, PriceType priceType) {
Book book = bookDao.find(bookId);
CartItem cartItem = new CartItem(book, priceType);
return cartItem;
}
}
| 30.963636 | 71 | 0.744568 |
31d899821e1228b43dad56a19291ce0ef6243f02 | 1,849 | /* Programmer: Jack Donato
Alterations: Marcus Ross */
package lab03;
import lab03.*;
public class List {
private Element[] data;
private int size;
private int index;
public List() { }
public List(int size) {
create(size);
}
public void create(int size) {
data = new Element[size];
this.size = 0;
index = 0;
}
public void destroy() {
for(Element elemCur:data)
elemCur = null;
size = -1;
index = -1;
}
public boolean isFull() {
boolean result;
result = size == data.length;
return result;
}
public boolean search(String searchStr) {
boolean result = false;
reset();
while(!atEnd() && !searchStr.equals(data[index].getKey()))
getNext();
if(!atEnd())
result = true;
else
result = false;
return result;
}
public boolean delete(String searchStr) {
boolean result;
result = search(searchStr);
if(result) {
while(index < size)
data[index] = data[++index];
size--;
}
return result;
}
public boolean add(Element element) {
boolean result;
if(isFull())
result = false;
else {
result = true;
data[size++] = element.clone();
}
return result;
}
public Element retrieve() {
Element element;
if(isEmpty() || atEnd())
return null;
element = data[index].clone();
return element;
}
public void reset() {
index = 0;
}
public boolean getNext() {
boolean result;
if(atEnd() || isEmpty())
result = false;
else {
result = true;
index++;
}
return result;
}
public boolean atEnd() {
boolean result;
if(index == size)
result = true;
else
result = false;
return result;
}
public boolean isEmpty() {
boolean result;
if(size == 0)
result = true;
else
result = false;
return result;
}
}
| 16.362832 | 61 | 0.585181 |
a4e8036e3daed373fbf6a89f225b1df2049fec2d | 2,804 | package cohadar.assembler.gui.menus;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import cohadar.assembler.gui.AsmFrame;
public class AsmHelpMenu extends JMenu implements ActionListener {
private final AsmFrame asmFrame;
private final JMenuItem about;
private final JMenuItem instructions;
private final JMenuItem functions;
public AsmHelpMenu(AsmFrame asmFrame) {
super("Help");
this.asmFrame = asmFrame;
this.setMnemonic(KeyEvent.VK_H);
instructions = new JMenuItem("Instructions");
instructions.addActionListener(this);
instructions.setMnemonic(KeyEvent.VK_I);
this.add(instructions);
functions = new JMenuItem("Functions");
functions.addActionListener(this);
functions.setMnemonic(KeyEvent.VK_F);
this.add(functions);
about = new JMenuItem("About");
about.addActionListener(this);
about.setMnemonic(KeyEvent.VK_A);
this.add(about);
}
@Override
public void actionPerformed(ActionEvent e) {
asmFrame.clearAndSelectConsole();
if (e.getSource() == about) {
this.about();
} else if (e.getSource() == functions) {
this.listFunctions();
} else if (e.getSource() == instructions) {
this.listInstructions();
}
}
private void listFunctions() {
System.out.println("%MATH_ABS");
System.out.println("%MATH_SIN");
System.out.println("%MATH_COS");
System.out.println("%MATH_ARCTAN");
System.out.println("%MATH_LN");
System.out.println("%MATH_EXP");
System.out.println("%MATH_SQR");
System.out.println("%MATH_SQRT");
System.out.println("%MATH_TRUNC");
System.out.println("%MATH_ROUND");
System.out.println("%MATH_IRAND");
System.out.println("%MATH_RRAND");
System.out.println("%PRINT_BOOLEAN ");
System.out.println("%PRINT_CREF");
System.out.println("%PRINT_NL");
System.out.println("%PRINT_REAL");
System.out.println("%PROC_SLEEP");
System.out.println("%SEM_INIT");
System.out.println("%SEM_WAIT");
System.out.println("%SEM_SIGNAL");
}
private void about() {
asmFrame.about();
}
private void listInstructions() {
System.out.println("ARITHMETIC: add sub mul div mod inc dec neg");
System.out.println("F-ARITHMETIC: fadd fsub fmul fdiv fmod finc fdec fneg i2f");
System.out.println("COMPARISON: eq neq lt lte gt gte");
System.out.println("F-COMPARISON: feq fneq flt flte fgt fgte");
System.out.println("LOGIC: and or xor not");
System.out.println("STACK: const dis dup nop swap");
System.out.println("PROGRAM FLOW: br brz brnz call ret fork join exit syscall");
System.out.println("MEMORY: addr load store aload astore bload bstore index range");
}
}
| 30.813187 | 93 | 0.697218 |
92108852c8143948a1b23325fc72040987c57a1c | 3,200 | package com.vincent.workflow;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import com.vincent.bean.CalculateUnit;
import com.vincent.bean.Condition;
import com.vincent.bean.Coupon;
import com.vincent.bean.Product;
public class WorkFlow {
private List<CalculateUnit> calculateUnits;
List<WorkStep> workSteps;
public static void main(String[] args) {
List<Coupon> couponList = DataFactory.getCoupons();
if (couponList == null)
return;
List<Product> productList = DataFactory.getProducts();
WorkFlow workFlow = new WorkFlow();
workFlow.createCalculateUnits(productList);
workFlow.createWorkSteps(couponList, workFlow.getCalculateUnits());
workFlow.start();
workFlow.showResult();
}
public void showResult() {
BigDecimal totalCurrentValue = this.calculateUnits.stream().map(CalculateUnit::getCurrentValue)
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println("最终结果:" + totalCurrentValue.toString());
this.calculateUnits.forEach(System.out::println);
}
public void start() {
this.getWorkSteps().get(0).run();
}
public void createWorkSteps(List<Coupon> couponList, List<CalculateUnit> calculateUnits) {
List<WorkStep> steps = couponList.stream().map(coupon -> {
WorkStep step = new WorkStep();
if (calculateUnits == null || coupon == null || coupon.getFilterRule() == null) {
System.out.println();
}
// 要根据规则过滤
step.setCalculateUnits(calculateUnits.stream().filter(coupon.getFilterRule()).collect(Collectors.toList()));
if (coupon.getFullElement() != null) {
Condition condition = new Condition();
condition.setFullElement(coupon.getFullElement());
condition.setQrCode(coupon.getCode());
List<CalculateUnit> calculateUnitList = calculateUnits.stream().filter(coupon.getFilterRule())
.collect(Collectors.toList());
CalculateUnit newUnit = new CalculateUnit();
newUnit.setCalculateUnits(calculateUnitList);
newUnit.setMin(coupon.getFullElement());
// 这里整合成一个 AB而不是A+B
condition.setCalculateUnit(newUnit);
step.setCondition(condition);
}
step.setCoupon(coupon);
return step;
}).collect(Collectors.toList());
WorkStep previous = null;
int i = 1;
for (WorkStep step : steps) {
step.setName("step" + i++);
if (previous == null) {
previous = step;
continue;
}
step.setPreviousStep(previous);
previous.setNextStep(step);
previous = step;
}
this.setWorkSteps(steps);
}
public List<CalculateUnit> createCalculateUnits(List<Product> productList) {
List<CalculateUnit> list = productList.stream().map(product -> {
CalculateUnit unit = new CalculateUnit();
unit.setMax(product.getPrice());
unit.setProductCode(product.getCode());
return unit;
}).collect(Collectors.toList());
this.setCalculateUnits(list);
return list;
}
public List<CalculateUnit> getCalculateUnits() {
return calculateUnits;
}
public void setCalculateUnits(List<CalculateUnit> calculateUnits) {
this.calculateUnits = calculateUnits;
}
public List<WorkStep> getWorkSteps() {
return workSteps;
}
public void setWorkSteps(List<WorkStep> workSteps) {
this.workSteps = workSteps;
}
}
| 27.350427 | 111 | 0.725313 |
d39a2505f7bc6348443f52415e1f82b128f41908 | 6,267 | package com.dbkynd.vdaccess.discord;
import com.dbkynd.vdaccess.VDAccess;
import com.dbkynd.vdaccess.config.Config;
import com.dbkynd.vdaccess.http.ImageDownloader;
import com.dbkynd.vdaccess.http.WebRequest;
import com.dbkynd.vdaccess.mojang.MojangJSON;
import com.dbkynd.vdaccess.sql.MySQLService;
import com.dbkynd.vdaccess.sql.UserRecord;
import com.moandjiezana.toml.Toml;
import com.velocitypowered.api.proxy.Player;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class AddCommandHandler {
private static final Logger logger = VDAccess.logger;
private static final WebRequest request = new WebRequest();
private static final Toml config = new Config().read();
private static final MySQLService sql = MySQLService.getInstance();
static String addCommand = config.getString("Discord.addCommandName");
static String embedMessageAdded = config.getString("Discord.Messages.embedMessageAdded");
static String embedMessageUpdated = config.getString("Discord.Messages.embedMessageUpdated");
static List<String> allowedChannels = new ArrayList<>(config.getList("Discord.allowedChannelIds"));
public static void action(SlashCommandEvent event, String ign) {
event.deferReply().queue();
InteractionHook hook = event.getHook();
String channel = event.getChannel().getName() + " (" + event.getChannel().getId() + ")";
String user = event.getUser().getAsTag() + " (" + event.getUser().getId() + ")";
logger.info("/" + event.getName() + " " + ign + " issued by: " + user + " in channel: " + channel);
// Make sure the command was run from a channel we allow
// If no channels are set allow all
if (allowedChannels.size() > 0) {
if (!allowedChannels.contains(event.getChannel().getId())) {
logger.info("Commands from channel: " + channel + " are not allowed.");
hook.sendMessage("The /" + addCommand + " command is not allowed from this channel.\nPlease talk to your server admin to find out what the proper channel(s) are.").setEphemeral(true).queue();
return;
}
}
// Get the user data from the Mojang API
MojangJSON mojang = request.getMojangData(ign);
// Tell the discord member we cannot find any data for the username they submitted
if (mojang == null || mojang.getId() == null) {
hook.sendMessage("Unable to get Mojang data for username **" + ign + "**. PLease double check the spelling.").queue();
return;
}
// Try to download the user's avatar image so that it's in crafatar's cache for when Discord asks for it to embed.
// I think when discord tries to embed the image it doesn't wait for it to be generated by crafatar like it would for a web client.
// And therefore, even though the url is valid, Discord was not showing the thumbnail reliably.
String thumbnail = "https://crafatar.com/renders/body/" + mojang.getId();
ImageDownloader.main(thumbnail);
String discordId = event.getUser().getId();
String embedMessage;
// Save to database
try {
if (sql.itemExists("discord_id", discordId)) {
// Kick the member if they are currently joined and are updating the database
// Had a past player exploit this to get his friend on by staying logged in and running the Discord command, adding their friend
UserRecord userRecord = sql.getRegisteredPlayer("discord_id", discordId);
Collection<Player> connectedPlayers = VDAccess.server.getAllPlayers();
List<Player> playerNames = connectedPlayers.stream().filter(player -> Objects.equals(player.getUniqueId().toString(), userRecord.getUUID())).collect(Collectors.toList());
if (playerNames.size() > 0) {
// Kick user
for (Player player : playerNames) {
player.disconnect(Component.text("You were disconnected for trying to update the allow list database while connected.").color(NamedTextColor.RED));
}
// Don't update the database if they were connected.
hook.sendMessage("Unable to update the allow list database while you account is currently joined. Please disconnect from the server and try again.").queue();
return;
}
// Update the database
sql.setMinecraftName(discordId, mojang.getName().toLowerCase());
sql.setUUID(discordId, mojang.getUUID().toString());
sql.updateTimestamp(discordId);
embedMessage = embedMessageUpdated;
logger.info("Updated entry for discord user: " + user);
} else {
sql.addNewPlayer(discordId, mojang.getName().toLowerCase(), mojang.getUUID().toString());
embedMessage = embedMessageAdded;
logger.info("Added new entry for discord user: " + user);
}
} catch (Exception e) {
e.printStackTrace();
hook.sendMessage("There was an error updating the Minecraft user database with username **" + mojang.getName() + "**.").queue();
return;
}
// Tell the Discord member that everything worked as expected!
EmbedBuilder builder = new EmbedBuilder();
builder.setDescription("```" + mojang.getName() + "```\n" + embedMessage);
builder.setThumbnail(thumbnail);
builder.setColor(0x5a9a30);
MessageEmbed embed = builder.build();
hook.sendMessageEmbeds(embed).queue();
}
}
| 52.663866 | 208 | 0.644647 |
e8000086bdc748c6c34c53529344d7f8c27a63ee | 1,752 | package ar.edu.unq.dapp.c2a.model.order.invoice;
import ar.edu.unq.dapp.c2a.model.client.Client;
import ar.edu.unq.dapp.c2a.model.order.Order;
import ar.edu.unq.dapp.c2a.persistence.money.MonetaryAmountConverter;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Transient;
@Entity
public class OrderInvoice extends Invoice {
private String description;
@Convert(converter = MonetaryAmountConverter.class)
private MonetaryAmount menuTotal = Monetary.getDefaultAmountFactory().setCurrency("ARS").setNumber(0).create();
@Convert(converter = MonetaryAmountConverter.class)
private MonetaryAmount deliveryTotal = Monetary.getDefaultAmountFactory().setCurrency("ARS").setNumber(0).create();
public OrderInvoice() {
}
public OrderInvoice(Order order) {
this.menuTotal = order.getPrice();
this.deliveryTotal = order.getDeliveryPrice();
this.description = order.getMenu().getName();
this.client=order.getClient();
}
@Override
@Transient
public MonetaryAmount getTotal() {
return menuTotal.add(deliveryTotal);
}
@Override
public String getDescription() {
return this.description;
}
void setDescription(String description) {
this.description = description;
}
MonetaryAmount getMenuTotal() {
return menuTotal;
}
public void setMenuTotal(MonetaryAmount menuTotal) {
this.menuTotal = menuTotal;
}
MonetaryAmount getDeliveryTotal() {
return deliveryTotal;
}
void setDeliveryTotal(MonetaryAmount deliveryTotal) {
this.deliveryTotal = deliveryTotal;
}
}
| 26.545455 | 119 | 0.71347 |
833d07922fe6fa88893ac53b932ab4d137e7c554 | 3,370 | /*
* 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.flexunit.ant.launcher.contexts;
import java.io.IOException;
import org.apache.tools.ant.Project;
import org.flexunit.ant.LoggingUtil;
import org.flexunit.ant.launcher.commands.headless.XvncException;
import org.flexunit.ant.launcher.commands.headless.XvncStartCommand;
import org.flexunit.ant.launcher.commands.headless.XvncStopCommand;
import org.flexunit.ant.launcher.commands.player.PlayerCommand;
/**
* Context used to wrap a call to the player command in a start and stop of a vncserver.
* All vncserver commands are blocking.
*/
public class HeadlessContext implements ExecutionContext
{
private PlayerCommand playerCommand;
private int startDisplay;
private int finalDisplay;
private Project project;
public HeadlessContext(int display)
{
this.startDisplay = display;
}
public void setProject(Project project)
{
this.project = project;
}
public void setCommand(PlayerCommand command)
{
this.playerCommand = command;
}
public void start() throws IOException
{
// setup vncserver on the provided display
XvncStartCommand xvncStart = new XvncStartCommand(startDisplay);
xvncStart.setProject(project);
LoggingUtil.log("Starting xvnc", true);
// execute the maximum number of cycle times before throwing an exception
while (xvncStart.execute() != 0)
{
LoggingUtil.log("Cannot start xnvc on :" + xvncStart.getCurrentDisplay() + ", cycling ...");
try
{
xvncStart.cycle();
}
catch (XvncException xe) {
throw new IOException(xe);
}
}
finalDisplay = xvncStart.getCurrentDisplay();
//setup player command to use the right display in its env when launching
playerCommand.setEnvironment(new String[]{ "DISPLAY=:" + finalDisplay });
LoggingUtil.log("Setting DISPLAY=:" + finalDisplay);
//prep anything the command needs to run
playerCommand.prepare();
}
public void stop(Process playerProcess) throws IOException
{
// destroy the process related to the player if it exists
if(playerProcess != null)
{
playerProcess.destroy();
}
// Now stop the vncserver that the player has been destroyed
XvncStopCommand xvncStop = new XvncStopCommand(finalDisplay);
xvncStop.setProject(project);
xvncStop.execute();
}
}
| 33.7 | 102 | 0.676261 |
1e23156e86f825d72914cb8986d81b5c7f2a0231 | 5,091 | /**
* Copyright @ 2018 Quan Nguyen
*
* 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 net.sourceforge.vietocr;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.Stage;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.vietocr.controls.OuputFormatCheckBoxActionListener;
public class OptionsDialogController implements Initializable {
@FXML
private Button btnOK;
@FXML
private Button btnCancel;
@FXML
private MenuButton mbOutputFormat;
@FXML
private CheckBox chbEnable;
@FXML
private CheckBox chbPostProcessing;
@FXML
private CheckBox chbCorrectLetterCases;
@FXML
private CheckBox chbRemoveLineBreaks;
@FXML
private CheckBox chbDeskew;
@FXML
private CheckBox chbRemoveLines;
@FXML
private CheckBox chbReplaceHyphens;
@FXML
private CheckBox chbRemoveHyphens;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
for (ITesseract.RenderedFormat value : ITesseract.RenderedFormat.values()) {
CheckBox chb = new CheckBox(value.name());
chb.setOnAction(new OuputFormatCheckBoxActionListener(mbOutputFormat));
CustomMenuItem menuItem = new CustomMenuItem(chb);
// keep the menu open during selection
menuItem.setHideOnClick(false);
mbOutputFormat.getItems().add(menuItem);
}
}
@FXML
private void handleAction(ActionEvent event) {
if (event.getSource() == btnOK) {
((Stage) btnOK.getScene().getWindow()).close();
} else if (event.getSource() == btnCancel) {
((Stage) btnCancel.getScene().getWindow()).close();
}
}
/**
* @return the selectedFormats
*/
public String getSelectedOutputFormats() {
List<String> list = new ArrayList<>();
for (MenuItem mi : mbOutputFormat.getItems()) {
if (mi instanceof CustomMenuItem cmi) {
CheckBox item = (CheckBox) cmi.getContent();
if (item.isSelected()) {
list.add(item.getText());
}
}
}
return list.stream().map(n -> String.valueOf(n)).collect(Collectors.joining(","));
}
/**
* @param selectedFormats the selectedFormats to set
*/
public void setSelectedOutputFormats(String selectedFormats) {
List<String> list = Arrays.asList(selectedFormats.split(","));
for (MenuItem mi : mbOutputFormat.getItems()) {
if (mi instanceof CustomMenuItem cmi) {
CheckBox item = (CheckBox) cmi.getContent();
if (list.contains(item.getText())) {
item.setSelected(true);
}
}
}
}
/**
* @return the processingOptions
*/
public ProcessingOptions getProcessingOptions() {
ProcessingOptions processingOptions = new ProcessingOptions();
processingOptions.setDeskew(this.chbDeskew.isSelected());
processingOptions.setPostProcessing(this.chbPostProcessing.isSelected());
processingOptions.setRemoveLines(this.chbRemoveLines.isSelected());
processingOptions.setRemoveLineBreaks(this.chbRemoveLineBreaks.isSelected());
processingOptions.setCorrectLetterCases(this.chbCorrectLetterCases.isSelected());
processingOptions.setRemoveHyphens(this.chbRemoveHyphens.isSelected());
processingOptions.setReplaceHyphens(this.chbReplaceHyphens.isSelected());
return processingOptions;
}
/**
* @param processingOptions the processingOptions to set
*/
public void setProcessingOptions(ProcessingOptions processingOptions) {
this.chbDeskew.setSelected(processingOptions.isDeskew());
this.chbPostProcessing.setSelected(processingOptions.isPostProcessing());
this.chbRemoveLines.setSelected(processingOptions.isRemoveLines());
this.chbRemoveLineBreaks.setSelected(processingOptions.isRemoveLineBreaks());
this.chbCorrectLetterCases.setSelected(processingOptions.isCorrectLetterCases());
this.chbRemoveHyphens.setSelected(processingOptions.isRemoveHyphens());
this.chbReplaceHyphens.setSelected(processingOptions.isReplaceHyphens());
}
}
| 35.601399 | 90 | 0.683363 |
Subsets and Splits