id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
12006992_3 | public static TrezorMessage.TxInput newTxInput(Transaction tx, int index) {
Preconditions.checkNotNull(tx, "Transaction must be present");
Preconditions.checkElementIndex(index, tx.getInputs().size(), "TransactionInput not present at index " + index);
// Input index is valid
TransactionInput txInput = tx.getInput(index);
TrezorMessage.TxInput.Builder builder = TrezorMessage.TxInput.newBuilder();
builder.setIndex(index);
// Fill in the input addresses
long prevIndex = txInput.getOutpoint().getIndex();
byte[] prevHash = txInput.getOutpoint().getHash().getBytes();
// In Bitcoinj "nanocoins" are Satoshis
long satoshiAmount = txInput.getConnectedOutput().getValue().longValue();
builder.setAmount(satoshiAmount);
try {
byte[] scriptSig = txInput.getScriptSig().toString().getBytes();
builder.setScriptSig(ByteString.copyFrom(scriptSig));
builder.setPrevIndex((int) prevIndex);
builder.setPrevHash(ByteString.copyFrom(prevHash));
builder.addAddressN(0);
builder.addAddressN(index);
return builder.build();
} catch (ScriptException e) {
throw new IllegalStateException(e);
}
} |
12046384_0 | public Tuple enrichEvent(Tuple event) {
if ("PRODUCT".equals(event.getString("type"))) {
List<String> names = new ArrayList<>(event.getFieldNames());
List<Object> values = new ArrayList(event.getValues());
names.add("category");
values.add(getCategory(event.getString("product")));
return TupleBuilder.tuple().ofNamesAndValues(names, values);
}
else {
return null;
}
} |
12057541_2 | @Override
public final boolean incrementToken() throws IOException {
clearAttributes();
logger.debug("incrementToken");
int length = 0;
int start = -1; // this variable is always initialized
int end = -1;
char[] buffer = termAtt.buffer();
while (true) {
if (bufferIndex >= dataLen) {
offset += dataLen;
charUtils.fill(ioBuffer, input);
if(ioBuffer.getLength() == 0) { // read supplementary char aware with CharacterUtils
dataLen = 0; // so next offset += dataLen won't decrement offset
if (length > 0) {
break;
} else {
finalOffset = correctOffset(offset);
return false;
}
}
dataLen = ioBuffer.getLength();
bufferIndex = 0;
}
// use CharacterUtils here to support < 3.1 UTF-16 code unit behavior if the char based methods are gone
final int c = charUtils.codePointAt(ioBuffer.getBuffer(), bufferIndex, ioBuffer.getBuffer().length);
final int charCount = Character.charCount(c);
bufferIndex += charCount;
if (isTokenChar(c)) { // if it's a token char
//전 문자와 현재 문자를 비교해서 속성이 다르면 분리해낸다.
if (length > 0) {
//이전문자의 속성 set
if(Character.isDigit(preChar)) preCharType = this.DIGIT;
else if(preChar < 127) preCharType = this.ALPHA;
else preCharType = this.KOREAN;
//현재문자의 속성set
if(Character.isDigit(c)) nowCharType = this.DIGIT;
else if(c < 127) nowCharType = this.ALPHA;
else nowCharType = this.KOREAN;
if(preCharType != nowCharType) { //앞뒤 Character가 서로 다른 형식
bufferIndex--;
//여기서 토큰을 하나 끊어야 함
termAtt.setLength(length);
offsetAtt.setOffset(correctOffset(start), correctOffset(start+length));
typeAtt.setType("word");
positionAtt.setPositionIncrement(1);
return true;
}
}
preChar = c;
if (length == 0) { // start of token
assert start == -1;
start = offset + bufferIndex - charCount;
end = start;
} else if (length >= buffer.length-1) { // check if a supplementary could run out of bounds
buffer = termAtt.resizeBuffer(2+length); // make sure a supplementary fits in the buffer
}
end += charCount;
length += Character.toChars(normalize(c), buffer, length); // buffer it, normalized
if (length >= MAX_WORD_LEN) // buffer overflow! make sure to check for >= surrogate pair could break == test
break;
} else if (length > 0) { // at non-Letter w/ chars
break; // return 'em
}
}
termAtt.setLength(length);
assert start != -1;
offsetAtt.setOffset(correctOffset(start), finalOffset = correctOffset(end));
typeAtt.setType("word");
positionAtt.setPositionIncrement(1);
return true;
} |
12058287_0 | public static final <T extends KeyLabel> String contructJson(List<T> list) {
StringWriter writer = new StringWriter();
JsonGenerator g;
try {
g = JsonUtil.jsonFactory.createJsonGenerator(writer);
g.writeStartArray();
if (null != list && !list.isEmpty()) {
for (T model : list) {
g.writeStartObject();
g.writeStringField("key", model.getKey());
g.writeStringField("label", model.getLabel());
g.writeEndObject();
}
}
g.writeEndArray();
g.flush();
g.close();
return writer.toString();
} catch (IOException e) {
e.printStackTrace();
return "[]";
}
} |
12067623_0 | @Override public int calculate(int a, int b) {
return a * b;
} |
12085714_9 | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ActionFlowStepConfig)) {
return false;
}
final ActionFlowStepConfig stepConfig = (ActionFlowStepConfig) o;
if (index != stepConfig.index) {
return false;
}
if ((nextAction != null) ? (!nextAction.equals(stepConfig.nextAction))
: (stepConfig.nextAction != null)) {
return false;
}
if ((prevAction != null) ? (!prevAction.equals(stepConfig.prevAction))
: (stepConfig.prevAction != null)) {
return false;
}
return true;
} |
12117077_49 | public static Style parse(Object css) throws IOException {
Reader reader = Convert.toReader(css).get("Unable to handle input: " + css);
return new CartoParser().parse(reader);
} |
12134164_54 | @SafeVarargs
public static <T> Expression[] literals(T... objects) {
Preconditions.checkNotNull(objects);
Expression[] result = new Expression[objects.length];
for (int i = 0; i < objects.length; i++) {
result[i] = literal(objects[i]);
}
return result;
} |
12151814_1 | @SuppressWarnings("unchecked")
public static <E extends Enum<? extends Style.HasCssName>> E fromStyleName(final String styleName,
final Class<E> enumClass,
final E defaultValue) {
if (styleName == null || enumClass == null) {
return defaultValue;
}
for (final Enum<? extends Style.HasCssName> constant : enumClass.getEnumConstants()) {
final Style.HasCssName anEnum = (Style.HasCssName) constant;
final String cssClass = anEnum.getCssName();
if (cssClass != null && StyleHelper.containsStyle(styleName, cssClass)) {
return (E) anEnum;
}
}
return defaultValue;
} |
12246820_18 | @Override
public long putFile(File sourceFile, ContentReference targetContentReference) throws ContentIOException
{
ContentReferenceHandler delegate = getDelegate(targetContentReference);
return delegate.putFile(sourceFile, targetContentReference);
} |
12250309_0 | public void startServer() throws LDAPException {
logger.info("Starting LDAP Server Configuration.");
File installFile = new File(dataPath);
installDir = installFile.getAbsolutePath();
boolean isFreshInstall;
if (installFile.exists()) {
isFreshInstall = false;
logger.debug("Configuration already exists at {}, not setting up defaults.",
installDir);
} else {
isFreshInstall = true;
logger.debug("No initial configuration found, setting defaults.");
createDirectory(installDir);
logger.info("Storing LDAP configuration at: " + installDir);
logger.info("Copying default files to configuration location.");
copyDefaultFiles();
}
try {
createStorePinFiles();
// General Configuration
DirectoryEnvironmentConfig serverConfig = new DirectoryEnvironmentConfig();
serverConfig.setServerRoot(installFile);
serverConfig.setDisableConnectionHandlers(false);
serverConfig.setMaintainConfigArchive(false);
logger.debug("Starting LDAP Server.");
EmbeddedUtils.startServer(serverConfig);
} catch (InitializationException ie) {
LDAPException le = new LDAPException(
"Could not initialize configuration for LDAP server.", ie);
logger.warn(le.getMessage(), le);
throw le;
} catch (ConfigException ce) {
LDAPException le = new LDAPException("Error while starting embedded server.", ce);
logger.warn(le.getMessage(), le);
throw le;
} catch (IOException e) {
LDAPException le = new LDAPException("Could not create password pin files.", e);
logger.warn(le.getMessage(), le);
throw le;
}
// post start tasks if first time being started
if (isFreshInstall) {
InputStream defaultLDIF = null;
try {
//we use the find because that searches fragments too
Enumeration<URL> entries = context.getBundle()
.findEntries("/", "default-*.ldif", false);
if (entries != null) {
while (entries.hasMoreElements()) {
URL url = entries.nextElement();
defaultLDIF = url.openStream();
logger.debug("Installing default LDIF file: {}", url);
// load into backend
loadLDIF(defaultLDIF);
}
}
} catch (IOException ioe) {
// need to make sure that the server is stopped on error
logger.warn(
"Error encountered during LDIF import, stopping server and cleaning up.");
stopServer();
throw new LDAPException(
"Error encountered during LDIF import, stopping server and cleaning up.",
ioe);
} catch (LDAPException le) {
// need to make sure that the server is stopped on error
logger.warn(
"Error encountered during LDIF import, stopping server and cleaning up.");
stopServer();
throw le;
} finally {
IOUtils.closeQuietly(defaultLDIF);
}
}
logger.info("LDAP server successfully started.");
} |
12255838_2 | public GuiceVerticleFactory setInjector(Injector injector) {
this.injector = injector;
return this;
} |
12299144_16 | @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LOGGER.debug("Loading user by username: {}", username);
User user = repository.findByEmail(username);
LOGGER.debug("Found user: {}", user);
if (user == null) {
throw new UsernameNotFoundException("No user found with username: " + username);
}
ExampleUserDetails principal = ExampleUserDetails.getBuilder()
.firstName(user.getFirstName())
.id(user.getId())
.lastName(user.getLastName())
.password(user.getPassword())
.role(user.getRole())
.socialSignInProvider(user.getSignInProvider())
.username(user.getEmail())
.build();
LOGGER.debug("Returning user details: {}", principal);
return principal;
} |
12299794_3 | public static String combine(final String... parts) {
final StringBuilder sb = new StringBuilder();
for (final String part : parts) {
if (isHttpUrl(part) || isHttpsUrl(part)) {
sb.setLength(0);
} else if (!part.startsWith("/")) {
sb.append("/");
}
final String path = sanitizePath(part);
sb.append(path);
}
return sb.toString();
} |
12304596_1 | @Override
@SuppressWarnings("unchecked")
public void invoke(Context context, Result result) {
Object object = result.getRenderable();
ResponseStreams responseStreams = context.finalizeHeaders(result);
Map map;
// if the object is null we simply render an empty map...
if (object == null) {
map = Maps.newHashMap();
} else if (object instanceof Map) {
map = (Map) object;
} else {
// We are getting an arbitrary Object and put that into
// the root of rythm
// If you are rendering something like Results.ok().render(new
// MyObject())
// Assume MyObject has a public String name field and
// a getter getField()
// You can then access the fields in the template like that:
// @myObject.getField()
// You will need to declare the object in the Template file, for eg:
// @args package.MyObject myObject
String realClassNameLowerCamelCase = CaseFormat.UPPER_CAMEL.to(
CaseFormat.LOWER_CAMEL, object.getClass().getSimpleName());
map = Maps.newHashMap();
map.put(realClassNameLowerCamelCase, object);
}
// set language from framework. You can access
// it in the templates as @lang
Optional<String> language = lang.getLanguage(context,
Optional.of(result));
Map<String, Object> renderArgs = new HashMap<String, Object>();
if (language.isPresent()) {
renderArgs.put("lang", language.get());
}
// put all entries of the session cookie to the map.
// You can access the values by their key in the cookie
// For eg: @session.get("key")
if (!context.getSessionCookie().isEmpty()) {
renderArgs.put("session", context.getSessionCookie().getData());
}
renderArgs.put("contextPath", context.getContextPath());
// /////////////////////////////////////////////////////////////////////
// Convenience method to translate possible flash scope keys.
// !!! If you want to set messages with placeholders please do that
// !!! in your controller. We only can set simple messages.
// Eg. A message like "errorMessage=my name is: {0}" => translate in
// controller and pass directly.
// A message like " errorMessage=An error occurred" => use that as
// errorMessage.
//
// get flash values like @flash.get("key")
// ////////////////////////////////////////////////////////////////////
Map<String, String> flash = new HashMap<String, String>();
for (Entry<String, String> entry : context.getFlashCookie()
.getCurrentFlashCookieData().entrySet()) {
String messageValue = null;
Optional<String> messageValueOptional = messages.get(
entry.getValue(), context, Optional.of(result));
if (!messageValueOptional.isPresent()) {
messageValue = entry.getValue();
} else {
messageValue = messageValueOptional.get();
}
flash.put(entry.getKey(), messageValue);
}
renderArgs.put("flash", flash);
String templateName = rythmHelper.getRythmTemplateForResult(
context.getRoute(), result, FILE_SUFFIX);
// Specify the data source where the template files come from.
// Here I set a file directory for it:
try {
PrintWriter writer = new PrintWriter(responseStreams.getWriter());
if (language.isPresent()) {
// RythmEngine uses ThreadLocal to set the locale, so this
// setting per request is Thread safe.
engine.prepare(new Locale(language.get()));
}
ITemplate t = engine.getTemplate(templateName, map);
t.__setRenderArgs(renderArgs);
String response = t.render();
if (templateName.equals(response)) {
handleServerError(context, new Exception(
"Couldn't locate template " + templateName + " in views."));
} else {
writer.println(response);
writer.flush();
writer.close();
}
} catch (Exception e) {
handleServerError(context, e);
}
} |
12319410_2 | public static XContentBuilder marshall(PoliciesBean bean) throws StorageException {
try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
preMarshall(bean);
builder
.startObject()
.field("organizationId", bean.getOrganizationId())
.field("entityId", bean.getEntityId())
.field("entityVersion", bean.getEntityVersion())
.field("type", bean.getType());
List<PolicyBean> policies = bean.getPolicies();
if (policies != null && !policies.isEmpty()) {
builder.startArray("policies");
for (PolicyBean policy : policies) {
builder.startObject()
.field("id", policy.getId())
.field("name", policy.getName())
.field("configuration", policy.getConfiguration())
.field("createdBy", policy.getCreatedBy())
.field("createdOn", policy.getCreatedOn().getTime())
.field("modifiedBy", policy.getModifiedBy())
.field("modifiedOn", policy.getModifiedOn().getTime())
.field("definitionId", policy.getDefinition().getId())
.field("orderIndex", policy.getOrderIndex())
.endObject();
}
builder.endArray();
}
builder.endObject();
postMarshall(bean);
return builder;
} catch (IOException e) {
throw new StorageException(e);
}
} |
12343833_0 | @SuppressWarnings("unchecked")
public static <T> T transform(Class<T> type, String value) throws IllegalArgumentException {
if (!VALUE_TRANSFORMER.containsKey(type)) {
throw new IllegalArgumentException("unsupported parameter type: " + type);
}
// since VALUE_TRANSFORMER contains the transformer for the given type
// so we can make cast without thinking about ClassCastException
return (T) VALUE_TRANSFORMER.get(type).apply(value);
} |
12356701_0 | private String getProperty(String key) {
return store.get(key);
} |
12414592_26 | @Transactional(Transactional.TxType.NOT_SUPPORTED)
public void notSupported() {
System.out.println(getClass().getName() + "Transactional.TxType.NOT_SUPPORTED");
} |
12473833_38 | public static int myBinarySearch(int[] indices, int key, int begin, int end) {
if (indices.length == 0 || begin == end) {
return -1;
}
end--;
int mid = begin;
while (begin <= end) {
mid = (end + begin) >> 1;
if (indices[mid] < key) {
begin = mid + 1;
}
else if (indices[mid] > key) {
end = mid - 1;
}
else {
return mid;
}
}
if (indices[mid] < key) {
return -mid-2;
}
else {
return -mid-1;
}
} |
12485907_12 | public static String normalizeSubject(String subject) {
String s = subject;
if (s != null) {
s = s.replaceAll("\\[.*?\\][^$]","") // remove any brackets at the beginning except the one having end of line after the "]"
.replaceAll("^\\s*(-*\\s*[a-zA-Z]{2,3}:\\s*)*","") // remove all Re: Fw: Aw: ... etc including leading dash
.replaceAll("\\s+[a-zA-Z]{2,3}:","") // remove any additional Re: having white space prefix
.replaceAll("^\\s*-\\s*","") // remove any left dashes at the beginning
.replaceAll("\\s+"," ") // finally replace multi-white space with one white space
.trim();
}
return s;
} |
12488647_6 | public static String implode(String separator, List<String> elements){
StringBuffer s = new StringBuffer();
for(int i = 0; i < elements.size(); i++){
if(i > 0){
s.append(" ");
}
s.append(elements.get(i));
}
return s.toString();
} |
12497963_1 | @Override
public boolean shouldBreak(IHierarchicalNodeLayout layout) {
if(layout.getDelegate()==null) // TODO : do not point on delegate but on MultiStepLayout.getCounter
return false;
if(layout.getDelegate().getCounter()>maxSteps)
return true;
else
return false;
} |
12506813_0 | public BM25FQuery(
Collection<Query> perFieldQueries,
Map<String, Float> fieldWeights,
Map<String, Float> normFactors) {
super(perFieldQueries, 0.0f);
this.fieldWeights = fieldWeights;
this.normFactors = normFactors;
} |
12508001_17 | @Override
public RenderedFileInfo render(final AbstractAllParams<W> all) throws VCatException {
// Build a Job instance for the parameters.
final String jobId = HashHelper.sha256Hex(all.getCombined());
Object lock;
// Synchronized to jobs, as all code changing it or any of the other Collections storing Jobs.
synchronized (this.jobs) {
if (this.jobs.containsKey(jobId)) {
// If the job is alread queued or running, we need to record that we are also waiting for it to finish.
this.jobs.put(jobId, this.jobs.get(jobId) + 1);
LOGGER.info(() -> String.format(Messages.getString("QueuedVCatRenderer.Info.AlreadyScheduled"), jobId));
// Get lock
lock = jobLocks.get(jobId);
} else {
// If the job is not queued or running yet, it needs to be added to ths list and a new job started.
this.jobs.put(jobId, 1);
// Create new lock
lock = new Object();
this.jobLocks.put(jobId, lock);
this.executorService.execute(() -> runJob(jobId, all));
LOGGER.info(() -> String.format(Messages.getString("QueuedVCatRenderer.Info.Scheduled"), jobId));
}
}
synchronized (lock) {
// Loop while waiting for the thread rendering the Job in the background.
while (!this.jobsFinished.containsKey(jobId)) {
try {
lock.wait();
} catch (InterruptedException e) {
// ignore
}
}
}
// Synchronized to jobs, as all code changing it or any of the other Collections storing Jobs.
synchronized (this.jobs) {
// An Exception might have been thrown. Store it (or null if there was no Exception).
Exception e = this.jobExceptions.get(jobId);
// Get result
RenderedFileInfo renderedFileInfo = this.jobsFinished.get(jobId);
final int waiting = this.jobs.get(jobId);
if (waiting > 1) {
// If more than one is waiting, just record we are no longer waiting.
this.jobs.put(jobId, waiting - 1);
} else {
// If no one else is still waiting, clear the Job.
this.jobs.remove(jobId);
this.jobsFinished.remove(jobId);
this.jobLocks.remove(jobId);
this.jobExceptions.remove(jobId);
}
// Throw exception, if there was one.
if (e != null) {
throw new VCatException(Messages.getString("QueuedVCatRenderer.Exception.Graphviz"), e);
}
// Return result
return renderedFileInfo;
}
} |
12520014_8 | public static Boolean toBoolean(Integer intValue) {
if (intValue == null) {
return null;
}
if (FALSE.equals(intValue)) {
return Boolean.FALSE;
}
return Boolean.TRUE;
} |
12544638_6 | public static ClassPath buildDefaultClassPath (Application app)
{
LinkedHashSet<File> classPathEntries = new LinkedHashSet<File>();
for (Resource resource : app.getActiveCodeResources()) {
classPathEntries.add(resource.getFinalTarget());
}
addClassPathDirectories(app, classPathEntries);
return new ClassPath(classPathEntries);
} |
12554530_5 | protected boolean sample() {
if (curr.increment() >= freq) {
curr.set(0);
target.set(rand.nextInt(freq));
}
return curr.get() == target.get();
} |
12555873_41 | public boolean hasInsituFilter() {
return parameters.getInsitu() != null;
} |
12561697_1 | private void reloadCacheEntry(CacheEntry cacheEntry) throws ExecutionException, InterruptedException {
LoaderCallable<T> loaderCallable = new LoaderCallable<T>(this, cacheProvider, cacheLoader, cacheEntry);
executorService.submit(loaderCallable);
} |
12578911_0 | public static boolean checkNameing(String str)
{
char[] commonArray = new char[str.length()];
int len = 0;
if (str == null || (len = str.length()) == 0)
{
return false;
}
str.getChars(0, len, commonArray, 0);
int index = 0;
char word = commonArray[index++];
//首字母判断 不为数字 , .
if (word >= 46 && word <= 57)
setLog(1, word);
//尾字母判断
else if (commonArray[len - 1] == 46)
setLog(len, 46);
else
while (true)
{
if (word < 36 || word > 122 || chars[word - 36] == 0)
{
setLog(index + 1, word);
return false;
}
if (index == len)
return true;
word = commonArray[index++];
}
return false;
} |
12587918_4 | public static byte[] undo(byte[] target, byte[] diff) {
MemoryDiff md = Serials.deserialize(DefaultSerialization.newInstance(), MemoryDiff.class, diff);
return Diffs.apply(new UndoOpQueue(md.queue()), target);
} |
12590126_3 | @Loggable(Loggable.DEBUG)
public int foo() {
return 1;
} |
12591138_1 | public String notNull(@NotNull final String value) {
return value;
} |
12593159_0 | public Author getAuthorByURL(String link, Author a) throws IOException, SamlibParseException, SamlibInterruptException {
a.setUrl(link);
String str = getURL(mSamLibConfig.getAuthorIndexDate(a), new StringReader());
parseAuthorIndexDateData(a, str);
return a;
} |
12652086_0 | public static Time fromMillis(long timeInMillis) {
int secs = (int) (timeInMillis / 1000);
int nsecs = (int) (timeInMillis % 1000) * 1000000;
return new Time(secs, nsecs);
} |
12652338_12 | public long getPriceWithVAT(LineItem lineItem) {
CalcLineItem calcLineItem = new CalcLineItem(lineItem);
return getCalc().getPriceWithVat(calcLineItem).getCents();
} |
12686435_0 | public FutureTask<ProxyServer> run() {
FutureTask<ProxyServer> future = new FutureTask<>(new Callable<ProxyServer>() {
@Override
public ProxyServer call() throws Exception {
// Configure the server.
bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
FiltersChangeNotifier changeNotifier = filtersChangeNotifier != null ? filtersChangeNotifier : FiltersChangeNotifier.IGNORE;
CommonHttpPipeline pipelineFactory = new CommonHttpPipeline(TIMER);
changeNotifier.addFiltersListener(pipelineFactory);
bootstrap.setPipelineFactory(pipelineFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.connectTimeoutMillis", 2000);
/*bootstrap.setOption("child.writeBufferHighWaterMark", true);
bootstrap.setOption("child.writeBufferLowWaterMark", true);
bootstrap.setOption("child.writeSpinCount", true);*/
bootstrap.setOption("child.receiveBufferSizePredictor", new AdaptiveReceiveBufferSizePredictor());
channel = bootstrap.bind(new InetSocketAddress(port));
LOG.info("server bound to port {}", port);
LOG.info("current handlers registred {}", pipelineFactory.getPipeline().getNames());
return ProxyServer.this;
}
});
final Thread thread = new Thread(future, "Proxy Server");
thread.start();
return future;
} |
12768312_22 | @Override
public boolean hasNext() {
return it != null;
} |
12796207_5 | @NonNull public static Builder emptyBuilder() {
return new Builder(Collections.emptyList());
} |
12796568_15 | public String getKey() {
return key;
} |
12812578_34 | public static boolean hasDependency(final PluginContext context, final EssentialsDependency dependency) {
final TargetPom targetPom = dependency.getDependencyTargetPom();
if (targetPom == TargetPom.INVALID) {
return false;
}
final Model model = ProjectUtils.getPomModel(context, targetPom);
final List<Dependency> dependencies = model.getDependencies();
for (Dependency projectDependency : dependencies) {
final boolean isSameDependency = isSameDependency(dependency, projectDependency);
if (isSameDependency) {
final String ourVersion = dependency.getVersion();
// we don't care about the version:
if (Strings.isNullOrEmpty(ourVersion)) {
return true;
}
//check if versions match: (TODO fix placeholder versions)
final String currentVersion = projectDependency.getVersion();
if (Strings.isNullOrEmpty(currentVersion) || currentVersion.indexOf('$') != -1) {
log.warn("Current version couldn't be resolved {}", currentVersion);
return true;
}
return VersionUtils.compareVersionNumbers(currentVersion, ourVersion) >= 0;
}
}
return false;
} |
12847265_23 | @ExceptionMetered(name = "illegalArgumentExceptionMeteredStaticMethod", cause = IllegalArgumentException.class)
public static void illegalArgumentExceptionMeteredStaticMethod(Runnable runnable) {
runnable.run();
} |
12853082_2 | public void close() throws IOException {
for (StreamingTrack streamingTrack : source) {
writeChunkContainer(createChunkContainer(streamingTrack));
streamingTrack.close();
}
write(sink, createMoov());
} |
12854207_1 | public void initDBTools(String schemaDir) {
DBToolsFiles.copyXsdFileToSchemaDir(schemaDir);
DBToolsFiles.copySampleSchemaFileToSchemaDir(schemaDir);
} |
12903179_22 | public void unregister(Command command) {
registeredCommands.remove(command);
} |
12918104_20 | public static String clone(String URL) throws Exception {
File tempDirectory = new File(Configuration.getTemporaryDirectory() + "/" + Calendar.getInstance().getTime().getTime() + "");
Main.printLine("[Info] Cloning from \"" +URL+ "\"");
ProcessBuilder builder = new ProcessBuilder("git","clone", URL, tempDirectory.getAbsolutePath());
Process process = null;
process = builder.start();
process.waitFor();
int exitValue = process.exitValue();
process.destroy();
if (exitValue == 0) {
Main.printLine("[Info] Cloning succesfull!");
return tempDirectory.getAbsolutePath();
} else {
throw new Exception(exitValue + "");
}
} |
12939200_53 | public void debug(String msg) {
logger.debug(msg);
} |
12953256_122 | public static int unionSize(LongSortedSet a, LongSortedSet b) {
return a.size() + b.size() - intersectSize(a, b);
} |
12959153_0 | @Override
@NonNull
public List<Range> findTokenRanges(CharSequence charSequence, int start, int end) {
ArrayList<Range>result = new ArrayList<>();
if (start == end) {
//Can't have a 0 length token
return result;
}
int tokenStart = Integer.MAX_VALUE;
for (int cursor = start; cursor < end; ++cursor) {
char character = charSequence.charAt(cursor);
//Either this is a terminator, or we contain some content and are at the end of input
if (isTokenTerminator(character)) {
//Is there some token content? Might just be two terminators in a row
if (cursor - 1 > tokenStart) {
result.add(new Range(tokenStart, cursor));
}
//mark that we don't have a candidate token start any more
tokenStart = Integer.MAX_VALUE;
}
//Set tokenStart when we hit a tag prefix
if (tagPrefixes.contains(character)) {
tokenStart = cursor;
}
}
if (end > tokenStart) {
//There was unterminated text after a start of token
result.add(new Range(tokenStart, end));
}
return result;
} |
12960439_18 | public ImmutableList<TransferSegment> createStateList(Layout layout, long trimMark) {
return layout.getSegments()
.stream()
// Keep all the segments after the trim mark, except the open one.
.filter(segment -> segment.getEnd() != NON_ADDRESS && segment.getEnd() > trimMark)
.map(segment -> {
// The transfer segment's start is the layout segment's start or a trim mark,
// whichever is greater.
long segmentStart = Math.max(segment.getStart(), trimMark);
// The transfer segment's end should be inclusive.
// It is the last address to transfer.
long segmentEnd = segment.getEnd() - 1L;
if (segmentContainsServer(segment, getServer())) {
TransferSegmentStatus restored = TransferSegmentStatus
.builder()
.segmentState(RESTORED)
.build();
return TransferSegment
.builder()
.startAddress(segmentStart)
.endAddress(segmentEnd)
.status(restored)
.logUnitServers(ImmutableList.copyOf(segment.getAllLogServers()))
.build();
} else {
TransferSegmentStatus notTransferred = TransferSegmentStatus
.builder()
.segmentState(NOT_TRANSFERRED)
.build();
return TransferSegment
.builder()
.startAddress(segmentStart)
.endAddress(segmentEnd)
.status(notTransferred)
.logUnitServers(ImmutableList.copyOf(segment.getAllLogServers()))
.build();
}
})
.collect(ImmutableList.toImmutableList());
} |
12962336_18 | public static TransactionResult fromJSON(JSONObject json) {
boolean binary;
String metaKey = json.has("meta") ? "meta" : "metaData";
String txKey = json.has("transaction") ? "transaction" :
json.has("tx") ? "tx" :
json.has("tx_blob") ? "tx_blob" : null;
if (txKey == null && !json.has("TransactionType")) {
throw new RuntimeException("This json isn't a transaction " + json);
}
binary = txKey != null && json.get(txKey) instanceof String;
Transaction txn;
if (txKey == null) {
// This should parse the `hash` field
txn = (Transaction) STObject.fromJSONObject(json);
} else {
txn = (Transaction) parseObject(json, txKey, binary);
if (json.has("hash")) {
txn.put(Hash256.hash, Hash256.fromHex(json.getString("hash")));
} else if (binary) {
byte[] decode = B16.decode(json.getString(txKey));
txn.put(Hash256.hash, Index.transactionID(decode));
}
}
TransactionMeta meta = (TransactionMeta) parseObject(json, metaKey, binary);
long ledger_index = json.optLong("ledger_index", 0);
if (ledger_index == 0 && !binary) {
ledger_index = json.getJSONObject(txKey).getLong("ledger_index");
}
TransactionResult tr = new TransactionResult(ledger_index, txn.get(Hash256.hash), txn, meta);
if (json.has("ledger_hash")) {
tr.ledgerHash = Hash256.fromHex(json.getString("ledger_hash"));
}
return tr;
} |
12963511_14 | @Override
public String encode(
String jti, String issuer, String subject, Date currentTime, String method, String path, String contentHashAlgorithm, String contentHash
) throws JWTError {
JwtClaims jwtClaims = new JwtClaims();
jwtClaims.setJwtId(jti);
jwtClaims.setIssuer(issuer);
jwtClaims.setSubject(subject);
jwtClaims.setAudience(apiIdentifier);
NumericDate now = NumericDate.fromMilliseconds(currentTime.getTime());
jwtClaims.setIssuedAt(now);
jwtClaims.setNotBefore(now);
NumericDate exp = NumericDate.fromMilliseconds(currentTime.getTime());
exp.addSeconds((long) requestExpireSeconds);
jwtClaims.setExpirationTime(exp);
Map<String, String> request = new HashMap<>();
//noinspection SpellCheckingInspection
request.put("meth", method);
request.put("path", path);
if (contentHashAlgorithm != null) {
request.put("func", contentHashAlgorithm);
request.put("hash", contentHash);
}
jwtClaims.setClaim("request", request);
JsonWebSignature jws = new JsonWebSignature();
jws.setKeyIdHeaderValue(currentPrivateKeyId);
jws.setKey(privateKeys.get(currentPrivateKeyId));
jws.setPayload(jwtClaims.toJson());
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
String jwt;
try {
jwt = jws.getCompactSerialization();
} catch (JoseException e) {
throw new JWTError("An error occurred encoding the JWT", e);
}
return jwt;
} |
12974177_0 | @NotNull
public static String dumpLocks() {
return LOCK_INVENTORY.dumpLocks();
} |
12983151_0 | public static FS20Command convertHABCommandToFS20Command(Command command) {
if (command instanceof UpDownType) {
return convertUpDownType((UpDownType) command);
} else if (command instanceof OnOffType) {
return convertOnOffType((OnOffType) command);
} else if (command instanceof PercentType) {
return convertPercentType((PercentType) command);
}
return null;
} |
13028147_119 | public void assertOk() {
if (hasErrors()) {
throw new MrrtReportTemplateValidationException(this);
}
} |
13062062_215 | @Override
public void restoreStateFrom(Map<String, String> data) {
field.setText(Optional.ofNullable(data.get("pages")).orElse(EMPTY));
} |
13068300_23 | public static <T> List<T> notNulls(List<T> l, String paramName) {
notNull(l, paramName);
for (T t : l) {
if (t == null) {
throw new IllegalArgumentException(paramName +
" cannot have NULL elements");
}
}
return l;
} |
13073335_8 | public String formatCondition( Operator op, String objectName, String value, boolean parameterized ) {
if ( parameterized ) {
value = "[param:" + value.replaceAll( "[\\{\\}]", "" ) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
} else if ( op == Operator.IN ) {
Matcher m = IN_EVAL_PAT.matcher( value );
StringBuilder sb = new StringBuilder();
while ( m.find() ) {
if ( sb.length() > 0 ) {
sb.append( ";" ); //$NON-NLS-1$
}
sb.append( "\"" ); //$NON-NLS-1$
sb.append( m.group( 1 ) != null ? m.group( 1 ) : m.group( 2 ) );
sb.append( "\"" ); //$NON-NLS-1$
}
if ( sb.length() > 0 ) {
value = sb.toString();
}
} else if ( op.getOperatorType() == 0 || op.getOperatorType() == 2 ) {
value = "\"" + value + "\""; //$NON-NLS-1$ //$NON-NLS-2$
}
String retVal = ""; //$NON-NLS-1$
switch ( op ) {
case EXACTLY_MATCHES:
case EQUAL:
retVal += "EQUALS(" + objectName + ";" + value + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
break;
case CONTAINS:
retVal += "CONTAINS(" + objectName + ";" + value + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
break;
case DOES_NOT_CONTAIN:
retVal += "NOT(CONTAINS(" + objectName + ";" + value + "))"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
break;
case BEGINS_WITH:
retVal += "BEGINSWITH(" + objectName + ";" + value + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
break;
case ENDS_WITH:
retVal += "ENDSWITH(" + objectName + ";" + value + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
break;
case IS_NULL:
retVal += "ISNA(" + objectName + ")"; //$NON-NLS-1$ //$NON-NLS-2$
break;
case IS_NOT_NULL:
retVal += "NOT(ISNA(" + objectName + "))"; //$NON-NLS-1$ //$NON-NLS-2$
break;
case IN:
retVal += "IN(" + objectName + ";" + value + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
break;
default:
retVal = objectName + " " + op.toString(); //$NON-NLS-1$
if ( op.getRequiresValue() ) {
retVal += value;
}
break;
}
return retVal;
} |
13075106_43 | public static void radixSort(int[] input, int n, int[] scratch, int[] countScratch) {
if (countScratch.length != 65536) throw new IllegalArgumentException("countScratch.length must be = 65536");
if (input.length < n) throw new IllegalArgumentException("input.length must be >= n");
if (scratch.length < n) throw new IllegalArgumentException("scratch.length must be >= n");
Arrays.fill(countScratch, 0);
for (int i = 0; i < n; i++) countScratch[input[i]&0xFFFF]++;
int sum = 0;
for (int i = 0; i < countScratch.length; i++) {
int temp = sum;
sum += countScratch[i];
countScratch[i] = temp;
}
for (int i = 0; i < n; i++) {
int temp = input[i]&0xFFFF;
int offset = countScratch[temp]++;
scratch[offset] = input[i];
}
Arrays.fill(countScratch, 0);
for (int i = 0; i < n; i++) countScratch[(scratch[i]>>16)+32768]++;
sum = 0;
for (int i = 0; i < countScratch.length; i++) {
int temp = sum;
sum += countScratch[i];
countScratch[i] = temp;
}
for (int i = 0; i < n; i++) {
int temp = (scratch[i]>>16)+32768;
int offset = countScratch[temp]++;
input[offset] = scratch[i];
}
} |
13075200_44 | protected String[] convertToStringArray(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
// historically, null values are allowed in the result, reasons unknown
return extractNonNullValueFromMapPayload(payload, payloadMapKey, o -> convertToList(o)).stream()
.map(STRING_CONVERTER).toArray(String[]::new);
} |
13077546_22 | @Override
public int size() {
return numElements;
} |
13095397_0 | public void execute( final String[] sql, final ExecutorCallback callback ) throws DataAccessException {
Exception exceptionDuringExecute = null;
DatabaseMeta dbMeta = connectionModel.getDatabaseMeta( );
String url = null;
try {
url = dbMeta.getURL( );
} catch ( KettleDatabaseException e ) {
throw new DataAccessException( "DatabaseMeta problem", e ) {
private static final long serialVersionUID = -3457360074729938909L;
};
}
// create the datasource
SingleConnectionDataSource ds = new SingleConnectionDataSource( url, dbMeta.getUsername( ), dbMeta
.getPassword( ), false );
ds.setDriverClassName( dbMeta.getDriverClass( ) );
// create the jdbc template
final JdbcTemplate jt = new JdbcTemplate( ds );
// create the transaction manager
DataSourceTransactionManager tsMan = new DataSourceTransactionManager( ds );
// create the transaction template
TransactionTemplate txTemplate = new TransactionTemplate( tsMan );
// set behavior
txTemplate.setPropagationBehavior( DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW );
final String[ ] noCommentSql = removeCommentsAndSemicolons( connectionModel.getSchema( ), sql );
try {
// run the code in a transaction
txTemplate.execute( new TransactionCallbackWithoutResult( ) {
public void doInTransactionWithoutResult( TransactionStatus status ) {
jt.batchUpdate( noCommentSql );
}
} );
} catch ( DataAccessException e ) {
if ( logger.isErrorEnabled( ) ) {
logger.error( "data access exception", e );
}
exceptionDuringExecute = e;
}
callback.executionComplete( exceptionDuringExecute );
} |
13105692_5 | public List<Throwable> getErrors() {
final List<Throwable> retval = new ArrayList<Throwable>();
for (final TestInfo testInfo : contractTestMap.listTestInfo()) {
retval.addAll( testInfo.getErrors() );
}
return retval;
} |
13107807_6 | public static String getUrlString( String realHostname, String port ) {
String urlString = "http://" + realHostname + ":" + port + GetStatusServlet.CONTEXT_PATH
+ "?xml=Y";
urlString = Const.replace( urlString, " ", "%20" );
return urlString;
} |
13126412_15 | public int getHunkSize() {
return hunkSize;
} |
13127985_31 | @Override
public String getExtension() {
return delegate.getExtension();
} |
13133836_7 | String[] getSchemas( Database database, DatabaseMeta databaseMeta ) throws KettleDatabaseException {
// This is a hack for PMD-907. A NPE can be thrown on getSchema JDBC's implementations.
String[] schemas = null;
Exception ex = null;
try {
schemas = database.getSchemas();
} catch ( Exception e ) {
// This can happen on shitty implementation of JDBC. We'll try the catalogs.
ex = e;
}
if ( ArrayUtils.isEmpty( schemas ) ) {
// MySQL doesn't report schema names. If we call get Catalogs, we get all the schemas, even those for which the
// current user doesn't have permissions. we'll use the DB name instead, as configured in the JDBC URL.
// Else try the catalogs instead. Some DBs call them catalogs.
schemas =
( databaseMeta.isMySQLVariant() ) ? new String[] { databaseMeta.getDatabaseName() } : database.getCatalogs();
}
if ( ArrayUtils.isEmpty( schemas ) && ex != null ) {
// If we couldn't figure neither the schemas or catalogs and we have cached an exception, throw that.
throw new KettleDatabaseException( ex );
}
return schemas;
} |
13137355_28 | public static Map<String, String> parse(String s) {
final Map<String, String> result = new HashMap<>();
if (s == null)
return result;
// Process each line separated by a newline.
for (String line : s.split("\n")) {
// Parse the line looking for the first equals to get the map key.
final String[] parts = line.split("=", 2);
if (parts.length == 0)
continue;
final String key = parts[0].trim();
if (key.trim().equals(""))
continue;
String value = "";
if (parts.length > 1 && parts[1] != null) {
value = parts[1];
}
if (result.containsKey(key))
log.warn("key {} overwritten due to dupe value", key);
result.put(key, value);
}
return result;
} |
13139604_0 | public static void setValueString(DataType d, String value) throws DataException
{
if (value != null && value.length() > 255)
{
try {
setValue(d, value.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
logger.error(FactoryException.TRACE_EXCEPTION,e);
}
d.setShortData(null);
if(d.getMimeType() == null || d.getMimeType().length() == 0){
d.setMimeType("text/plain");
}
}
else
{
d.setShortData(value);
}
} |
13160719_0 | public Table<String, NewRelicMetric, Boolean> loadTable(@Nonnull InputStream inputStream) throws IOException {
Map<String, Map<NewRelicMetric, Boolean>> m =
objectReader.forType(new TypeReference<Map<String, Map<NewRelicMetric, Boolean>>>() {})
.readValue(inputStream);
return table(m);
} |
13191344_54 | public static boolean matchesModifierLevel(AccessModifier modifierLevelOfElement, AccessModifier modifierLevel) {
return (modifierLevelOfElement.getLevel() >= modifierLevel.getLevel());
} |
13217403_10 | @Override
public void intercept(HttpRequest request) throws IOException {
try {
binding.sign(request, request);
} catch (RequestSigningException e) {
throw new RuntimeException(e);
}
} |
13236207_0 | public static InStream create(String name,
ByteBuffer input,
CompressionCodec codec,
int bufferSize) throws IOException {
if (codec == null) {
return new UncompressedStream(name, input);
} else {
return new CompressedStream(name, input, codec, bufferSize);
}
} |
13240419_2 | public static boolean intersects(GenericSegment seg1, GenericSegment seg2)
{
//System.out.println("seg1: " + seg1 + "\nseg2: " + seg2);
//System.out.println("H: " + horizIntersect(seg1, seg2) + " V: " + vertIntersect(seg1, seg2));
return horizIntersect(seg1, seg2) && vertIntersect(seg1, seg2);
} |
13272929_2 | public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraphs(List<List<SEG>> listOfSegLists,
StyleSpans<S> entireDocumentStyleSpans) {
return addParagraphList(listOfSegLists, entireDocumentStyleSpans, ignore -> null, Function.identity());
} |
13292939_10 | @Override
public List<Value> getValues(String field) {
try {
XPathExpression expr = xpath_map.get(field);
if (expr == null) {
return null;
}
NodeList lst = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
ArrayList<Value> ret = new ArrayList<Value>();
for (int i = 0; i < lst.getLength(); i++) {
String str = lst.item(i).getTextContent().trim();
//Ignore empty lines
if (!"".equals(str)) {
ret.add(new StringValue(str));
}
}
return ret;
} catch(XPathExpressionException e) {
logger.info(e.getStackTrace());
}
return null;
} |
13317929_25 | @Override
public Parser<String> getParser(NonEmpty annotation, Class<?> fieldType) {
return new Parser<String>() {
@Override
public String parse(String text, Locale locale)
throws ParseException {
if (!StringUtils.hasText(text)) {
return null;
} else {
return text;
}
}
};
} |
13325401_358 | public static ValueMap toValueMap(final Map<String, ?> map) {
final Map<String, Object> objectMap = new LinkedHashMap<String, Object>(map.size());
for (final Map.Entry<String, ?> entry : map.entrySet()) {
objectMap.put(entry.getKey(), entry.getValue());
}
return new ValueMapDecorator(objectMap);
} |
13343738_8 | public List<JUGMember> findByExperience(int experience) {
return entityManager.createNamedQuery(
"JUGMember-findByExperience")
.setParameter( 1, experience )
.getResultList();
} |
13348306_1 | public static Properties bind(URI fsURI, Configuration conf) throws
SwiftConfigurationException {
String host = fsURI.getHost();
if (host == null || host.isEmpty()) {
//expect shortnames -> conf names
throw invalidName(host);
}
String container = extractContainerName(host);
String service = extractServiceName(host);
//build filename schema
String prefix = buildSwiftInstancePrefix(service);
if (LOG.isDebugEnabled()) {
LOG.debug("Filesystem " + fsURI
+ " is using configuration keys " + prefix);
}
Properties props = new Properties();
props.setProperty(SWIFT_SERVICE_PROPERTY, service);
props.setProperty(SWIFT_CONTAINER_PROPERTY, container);
copy(conf, prefix + DOT_AUTH_URL, props, SWIFT_AUTH_PROPERTY, true);
copy(conf, prefix + DOT_AUTH_ENDPOINT_PREFIX, props,
SWIFT_AUTH_ENDPOINT_PREFIX, true);
copy(conf, prefix + DOT_USERNAME, props, SWIFT_USERNAME_PROPERTY, true);
copy(conf, prefix + DOT_APIKEY, props, SWIFT_APIKEY_PROPERTY, false);
copy(conf, prefix + DOT_PASSWORD, props, SWIFT_PASSWORD_PROPERTY,
props.contains(SWIFT_APIKEY_PROPERTY) ? true : false);
copy(conf, prefix + DOT_TRUST_ID, props, SWIFT_TRUST_ID_PROPERTY, false);
copy(conf, prefix + DOT_DOMAIN_NAME, props, SWIFT_DOMAIN_NAME_PROPERTY, false);
copy(conf, prefix + DOT_DOMAIN_ID, props, SWIFT_DOMAIN_ID_PROPERTY, false);
copy(conf, prefix + DOT_TENANT, props, SWIFT_TENANT_PROPERTY, false);
copy(conf, prefix + DOT_CONTAINER_TENANT, props, SWIFT_CONTAINER_TENANT_PROPERTY, false);
copy(conf, prefix + DOT_REGION, props, SWIFT_REGION_PROPERTY, false);
copy(conf, prefix + DOT_HTTP_PORT, props, SWIFT_HTTP_PORT_PROPERTY, false);
copy(conf, prefix +
DOT_HTTPS_PORT, props, SWIFT_HTTPS_PORT_PROPERTY, false);
copyBool(conf, prefix + DOT_PUBLIC, props, SWIFT_PUBLIC_PROPERTY, false);
copyBool(conf, prefix + DOT_LOCATION_AWARE, props,
SWIFT_LOCATION_AWARE_PROPERTY, false);
return props;
} |
13349691_13 | public TestPerformances getPerformancesFor(final String msg) {
return map.get(msg);
} |
13363575_17 | @Transactional
@Override
public User updateWithoutPassword(String username, User updatedUser) {
Assert.notNull(updatedUser, "user must not be null");
Assert.notNull(updatedUser.getPassword(), "(old) password must not be null");
preUpdate(username, updatedUser);
return doUpdate(username, updatedUser);
} |
13363729_38 | public List<String> queryXml(String url, String username, String password, String... xpathQueries) throws IOException {
byte[] xmlContent = doGet(url, username, password);
List<String> results = new ArrayList<>();
try {
InputSource is = new InputSource(new ByteArrayInputStream(xmlContent));
Document xmlDocument = documentBuilder.parse(is);
xmlDocument.getDocumentElement().normalize();
//xpathQuery contains the xpath expression to be applied on the retrieved content
for (String xpathQuery : xpathQueries) {
String result = xPath.compile(xpathQuery).evaluate(xmlDocument);
// Notify an empty result to the user
if (result == null || result.isEmpty()) {
LOG.warn("XPath query {} produced no results on content: \n{}", xpathQuery, new String(xmlContent));
result = "";
}
results.add(result);
}
} catch (XPathExpressionException | SAXException | IOException ex) {
throw new IOException("Cannot perform the given xpath query", ex);
}
return results;
} |
13379760_81 | public static String formatAlertMessage(TransactionSeenEvent event) {
// Decode the "transaction seen" event
final Coin amount = event.getAmount();
final Coin modulusAmount;
if (amount.compareTo(Coin.ZERO) >= 0) {
modulusAmount = amount;
} else {
modulusAmount = amount.negate();
}
// Create a suitable representation for inline text (no icon)
final String messageAmount = Formats.formatCoinAsSymbolicText(
modulusAmount,
Configurations.currentConfiguration.getLanguage(),
Configurations.currentConfiguration.getBitcoin()
);
// Construct a suitable alert message
if (amount.compareTo(Coin.ZERO) >= 0) {
// Positive or zero amount, this is a receive
return Languages.safeText(MessageKey.PAYMENT_RECEIVED_ALERT, messageAmount);
} else {
// Negative amount, this is a send (probably from a wallet clone elsewhere)
return Languages.safeText(MessageKey.PAYMENT_SENT_ALERT, messageAmount);
}
} |
13383431_28 | public UndoableEdit delete(PetriNetComponent component) throws PetriNetComponentException {
return deleteComponent(component);
} |
13414290_2 | public Schema getSchema(int version) {
return new Schema(version);
} |
13424587_55 | public static RoundedMoney ofMinor(CurrencyUnit currency, long amountMinor) {
return ofMinor(currency, amountMinor, currency.getDefaultFractionDigits());
} |
13471496_3 | @Override
public String toString() {
StringBuilder builder = new StringBuilder();
boolean firstTime = true;
for (String key : mParams.keySet()) {
builder.append(firstTime ? "?" : "&");
if (firstTime) firstTime = false;
String value = mParams.get(key);
builder.append(key).append("=").append(value);
}
return builder.toString();
} |
13486560_0 | public String guessMimeType(String path) {
int lastDot = path.lastIndexOf('.');
if (lastDot == -1) {
return null;
}
String extension = path.substring(lastDot + 1);
extension = extension.toLowerCase();
String mimeType = extensionToMimeType.get(extension);
return mimeType;
} |
13486910_2 | public void removeAllSpringConfig() {
mSpringConfigMap.clear();
} |
13490595_330 | @Override
public void validate(Sentence sentence) {
invalidOkurigana.stream().forEach(value -> {
int startPosition = sentence.getContent().indexOf(value);
if (startPosition != -1) {
addLocalizedErrorWithPosition(sentence,
startPosition,
startPosition + value.length(),
value);
}
}
);
for (ExpressionRule rule : invalidOkuriganaTokens) {
if (rule.match(sentence.getTokens())) {
addLocalizedError(sentence, rule.toString());
}
}
} |
13498449_0 | double score(double balance, double numTrans, double creditLine) {
ScriptEngine engine = ENGINE.get();
if(engine == null) {
engine = initEngine();
ENGINE.set(engine);
}
double score;
Bindings bindings = engine.getBindings(ENGINE_SCOPE);
bindings.put("balance", balance);
bindings.put("numTrans", numTrans);
bindings.put("creditLine", creditLine);
try {
engine.eval("score <- data.frame(balance=balance,numTrans=numTrans,creditLine=creditLine)");
engine.eval("x <- predict(fraudModel, score)");
DoubleVector x = (DoubleVector) bindings.get("x");
score = x.getElementAsDouble(0);
} catch (ScriptException e) {
throw new RuntimeException("Prediction failed");
}
return score;
} |
13512175_99 | @Override
public EntityUpdateBatch<Id, M, V> updateBatch(Id id) {
return updateBatch(singleton(id));
} |
13521187_28 | public <T> void registerType(Class<T> clazz, TypeSerializer<T> serializer) {
typeSerializers.put(clazz, serializer);
} |
13535208_210 | public String toObject(String value) {
if (StringUtil.isEmpty(value)) {
return null;
}
return ArgumentUtil.decode(value);
} |
13570618_2 | @Override
public synchronized void cleanup()
{
logInfoWithQueueName("purging completed tasks");
// clear all tasks from the finished queue
final List<Future<Void>> completedTasks =
Lists.newArrayListWithExpectedSize(this.completedTasksQueue.size());
this.completedTasksQueue.drainTo(completedTasks);
for (Future<Void> future: completedTasks) {
AppFactoryTask task = FutureStoringThreadPoolExecutor.getOriginal(future);
if (null != task) {
removeTask(task);
} else {
logErrorWithQueueName("Could not find taskId for future {}", future);
}
}
} |
13580866_73 | public char[] readNumber( ) {
try {
ensureBuffer();
char [] results = CharScanner.readNumber( readBuf, index, length);
index += results.length;
if (index >= length && more) {
ensureBuffer();
if (length!=0) {
char results2[] = readNumber();
return Chr.add(results, results2);
} else {
return results;
}
} else {
return results;
}
} catch (Exception ex) {
String str = CharScanner.errorDetails ( "readNumber issue", readBuf, index, ch );
return Exceptions.handle ( char[].class, str, ex );
}
} |
13590591_6 | public void modifyUserProfile(String pid, IUserProfileModification modifier)
throws GetFailedException, PutFailedException, AbortModifyException {
PutQueueEntry entry = new PutQueueEntry(pid);
modifyQueue.add(entry);
synchronized (queueWaiter) {
queueWaiter.notify();
}
UserProfile profile;
try {
profile = entry.getUserProfile();
if (profile == null) {
throw new GetFailedException("User Profile not found");
}
} catch (GetFailedException e) {
// just stop the modification if an error occurs.
if (modifying != null && modifying.getPid().equals(pid)) {
modifying.abort();
}
throw e;
}
boolean retryPut = true;
int forkCounter = 0;
int forkWaitTime = new Random().nextInt(1000) + 500;
while (retryPut) {
// user starts modifying it
modifier.modifyUserProfile(profile);
try {
// put the updated user profile
if (protectionKeys == null) {
protectionKeys = profile.getProtectionKeys();
}
if (modifying != null && modifying.getPid().equals(pid)) {
modifying.setUserProfile(profile);
modifying.readyToPut();
modifying.waitForPut();
// successfully put the user profile
retryPut = false;
} else {
throw new PutFailedException("Not allowed to put anymore");
}
} catch (VersionForkAfterPutException e) {
if (forkCounter++ > FORK_LIMIT) {
logger.warn("Ignoring fork after {} rejects and retries.", forkCounter);
retryPut = false;
} else {
logger.warn("Version fork after put detected. Rejecting and retrying put.");
// exponential back off waiting and retry to update the user profile
try {
Thread.sleep(forkWaitTime);
} catch (InterruptedException e1) {
// ignore
}
forkWaitTime = forkWaitTime * 2;
}
}
}
} |
13601636_0 | public Map<String, Object> deserialize(String data) throws IOException {
try {
Map<String, Object> map = new LinkedHashMap<String, Object>();
JsonParser jp = jsonFactory.createJsonParser(data);
jp.nextToken(); // Object
jp.nextToken(); // key
map.put(KEY, new DataByteArray(jp.getCurrentName().getBytes()));
jp.nextToken(); // object
while (jp.nextToken() != JsonToken.END_OBJECT) {
String field = jp.getCurrentName();
if (DELETEDAT.equals(field.toUpperCase())) {
jp.nextToken();
map.put(DELETEDAT, jp.getLongValue());
} else {
jp.nextToken();
while (jp.nextToken() != JsonToken.END_ARRAY) {
List<Object> cols = new ArrayList<Object>();
jp.nextToken();
String name = jp.getText();
cols.add(name);
jp.nextToken();
cols.add(new DataByteArray(jp.getText().getBytes()));
jp.nextToken();
cols.add(jp.getLongValue());
if (jp.nextToken() != JsonToken.END_ARRAY) {
String status = jp.getText();
cols.add(status);
if ("e".equals(status)) {
jp.nextToken();
cols.add(jp.getLongValue());
jp.nextToken();
cols.add(jp.getLongValue());
} else if ("c".equals(status)) {
jp.nextToken();
cols.add(jp.getLongValue());
}
jp.nextToken();
}
map.put(name, cols);
}
}
}
return map;
} catch (IOException e) {
LOG.error(data);
throw e;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.