id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
2784782_5 | @RequestMapping(value = "/{icon:.+}", method = RequestMethod.GET)
public HttpEntity raw(@PathVariable String icon) throws IOException {
return raw(null, icon);
} |
2791813_183 | @Override
public boolean appliesTo(Character caster, Character target) {
if (target.isDead()) {
return false;
}
return true;
} |
2797978_1 | public boolean emit(String tag, Map<String, Object> record) {
if (record.containsKey("time")) {
return emit0(tag, record);
} else {
return emit(tag, System.currentTimeMillis() / 1000, record);
}
} |
2803695_0 | @Override
public boolean isSupported(OptionalFeature optionalFeature) {
return false;
} |
2804383_31 | public void parseQuery() throws TTXPathException {
// get first token, ignore all white spaces
do {
mToken = mScanner.nextToken();
} while (mToken.getType() == TokenType.SPACE);
// parse the query according to the rules specified in the XPath 2.0 REC
parseExpression();
// after the parsing of the expression no token must be left
if (mToken.getType() != TokenType.END) {
throw new IllegalStateException("The query has not been processed completely.");
}
} |
2818491_3 | public void detect() throws IOException {
detect(new ClassFileIterator());
} |
2845921_1 | public void enter(char c) {
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
state.processDigit(c);
break;
case '.':
state.processDot();
break;
case '+':
case '-':
case '/':
case '*':
state.processOperator(c);
break;
case '=':
state.processEquals();
break;
case 'C':
state = new EnteringFirstOperandState('0');
break;
default:
throw new IllegalArgumentException("Character '" + c + "' is not supported");
}
} |
2851858_9 | public static PropertyEditorProvider getProvider() {
return PROVIDER;
} |
2854377_35 | @Nonnull
@Override
public synchronized List<SObject> retrieve(@Nonnull String sObjectType, @Nonnull List<Id> ids,
@Nonnull List<String> fieldList) throws ApiException {
logger.entry(sObjectType, fieldList, ids);
Retrieve retrieveParam = new Retrieve();
retrieveParam.setFieldList(StringUtils.join(fieldList, ","));
retrieveParam.setSObjectType(sObjectType);
// suppress warning: order is important
@SuppressWarnings("TypeMayBeWeakened") List<String> idStrings = new ArrayList<String>();
for (Id id : ids) {
idStrings.add(id.toString());
}
retrieveParam.getIds().addAll(idStrings);
logger.trace("retrieving fields <{}> for ids <{}>", fieldList, ids);
RetrieveOp op = new RetrieveOp();
RetrieveResponse response = op.execute(retrieveParam);
List<com.palominolabs.crm.sf.soap.jaxwsstub.partner.SObject> stubSObjects = response.getResult();
List<PartnerSObject> facadeSObjects = getSObjectsFromStubs(stubSObjects);
logger.exit(facadeSObjects);
return new ArrayList<SObject>(facadeSObjects);
} |
2856208_18 | @Override
public void printHelp() {
PrintWriter writer = new PrintWriter(System.out);
printHelp(writer);
writer.flush();
} |
2858655_84 | protected Environment getEnvironment(final Properties properties, String... packagesToSearch)
{
final Environment environment = new Environment();
if (properties != null)
{
environment.setProperties(properties);
}
packagesToSearch = ArrayUtils.add(packagesToSearch, getClass().getPackage().getName());
final ServiceProvider serviceProvider = new ServiceProvider(packagesToSearch);
final List<PropertyReader> propertyReaders = Lists.newArrayList(serviceProvider.find(FlipProperty.class,
PropertyReader.class));
Collections.sort(propertyReaders, new FlipPropertiesPriorityComparator());
environment.setPropertyReaders(propertyReaders);
final List<Object> contextProviders = Lists.newArrayList(serviceProvider.find(FlipContext.class));
Collections.sort(contextProviders, new FlipContextsPriorityComparator());
environment.setContextProviders(contextProviders);
return environment;
} |
2874089_0 | public static boolean validate( File f ) {
try {
SAXParser parser = factory.newSAXParser();
parser.setProperty( Constants.XML_SCHEMA_PROPERTY, Constants.XML_SCHEMA_LANGUAGE );
SimpleErrorHandler errorHandler = new SimpleErrorHandler();
SAXReader reader = new SAXReader( parser.getXMLReader() );
reader.setValidation( true );
reader.setErrorHandler( errorHandler );
reader.read( f );
return errorHandler.isValid();
} catch ( ParserConfigurationException e ) {
LOG.error( "ParserConfigurationException: {}", e.getMessage() );
} catch ( SAXException e ) {
LOG.error( "SAXException: {}", e.getMessage() );
} catch ( DocumentException e ) {
LOG.error( "DocumentException: {}", e.getMessage() );
} catch ( NullPointerException e ) {
LOG.warn( "Factory is not initialized. Did you call init()" );
}
return false;
} |
2882681_1 | public static Tracking search(String id) throws EncomendaZException {
return search(id, null, null, null);
} |
2885102_12 | public JSONValue decode() {
char current = reader.current();
if(current == Opener.OBJECT.sign) {
return decodeObject();
} else if(current == Opener.STRING.sign) {
return decodeString();
} else if(current == Opener.ARRAY.sign) {
return decodeArray();
} else if(
Character.isDigit(current) ||
current == Opener.MINUS.sign ||
current == Opener.PLUS.sign ||
current == Opener.DOT.sign) {
return decodeNumber();
} else if(
current == Opener.NULL.sign ||
current == Opener.NULL_UPPER.sign) {
return decodeNull();
} else if(
current == Opener.FALSE.sign ||
current == Opener.FALSE_UPPER.sign) {
return decodeFalse();
} else if(
current == Opener.TRUE.sign ||
current == Opener.TRUE_UPPER.sign) {
return decodeTrue();
}
return null;
} |
2885902_8 | @Override
public ElementType getElementType() {
return reader.getElementType();
} |
2899580_56 | @SuppressWarnings("unchecked")
@Override
protected DomainEventMessage createSnapshot(Class<?> aggregateType,
String aggregateIdentifier,
DomainEventStream eventStream) {
DomainEventMessage firstEvent = eventStream.peek();
AggregateFactory<?> aggregateFactory = getAggregateFactory(aggregateType);
if (aggregateFactory == null) {
throw new IllegalArgumentException(
"Aggregate Type is unknown in this snapshotter: " + aggregateType.getName()
);
}
aggregateModels.computeIfAbsent(aggregateType,
k -> AnnotatedAggregateMetaModelFactory
.inspectAggregate(k, parameterResolverFactory, handlerDefinition));
Object aggregateRoot = aggregateFactory.createAggregateRoot(aggregateIdentifier, firstEvent);
SnapshotAggregate<Object> aggregate = new SnapshotAggregate(aggregateRoot,
aggregateModels.get(aggregateType),
repositoryProvider);
aggregate.initializeState(eventStream);
if (aggregate.isDeleted()) {
return null;
}
return new GenericDomainEventMessage<>(aggregate.type(), aggregate.identifierAsString(), aggregate.version(),
aggregate.getAggregateRoot());
} |
2907398_1 | @Override
public void run() {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Message message = new MimeMessage(session);
try {
if (email.getFromPersonal().equals(EmailBuilder.DEFAULT_PERSONAL)) {
message.setFrom(new InternetAddress(email.getFromAddress()));
} else {
message.setFrom(new InternetAddress(email.getFromAddress(), email.getFromPersonal()));
}
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getTo()));
message.setSubject(email.getSubject());
message.setContent(email.getBody(), CONTENT_TYPE);
if (Strings.isNullOrEmpty(email.getReplyToAddress())) {
message.setReplyTo(new Address[] {
new InternetAddress(email.getReplyToAddress())
});
}
transport.send(message);
} catch (MessagingException e) {
logger.log(Level.WARNING, e.getMessage());
} catch (UnsupportedEncodingException e) {
logger.log(Level.WARNING, e.getMessage());
}
} |
2916790_3 | @Override
public ResultSetCursor getOutgoingRelations(int[] instances)
throws Exception {
final StringBuilder b = new StringBuilder();
for (int i : instances) {
b.append('(');
b.append(i);
b.append(')');
b.append(',');
}
String sql = "SELECT relations.subject, relations.predicate, relations.object FROM relations WHERE (relations.subject IN ("
+ b.substring(0, b.length() - 1) + "))";
try {
PreparedStatement pstmt = connection.prepareStatement(sql);
ResultSet rs = executeQuery(pstmt, sql);
return new ResultSetCursor(rs);
} catch (Exception e) {
log.log(Level.SEVERE, "an error occurred in executing SQL query: "
+ sql, e);
throw e;
}
} |
2928039_24 | @SuppressWarnings("unchecked")
public Object transformRow(Map<String, Object> row, Context context) {
VariableResolver resolver = context.getVariableResolver();
for (Map<String, String> fld : context.getAllEntityFields()) {
String style = resolver.replaceTokens(fld.get(FORMAT_STYLE));
if (style != null) {
String column = fld.get(DataImporter.COLUMN);
String srcCol = fld.get(RegexTransformer.SRC_COL_NAME);
Locale locale = null;
String localeStr = resolver.replaceTokens(fld.get(LOCALE));
if (srcCol == null)
srcCol = column;
if (localeStr != null) {
Matcher matcher = localeRegex.matcher(localeStr);
if (matcher.find() && matcher.groupCount() == 2) {
locale = new Locale(matcher.group(1), matcher.group(2));
} else {
throw new DataImportHandlerException(DataImportHandlerException.SEVERE, "Invalid Locale specified for field: " + fld);
}
} else {
locale = Locale.getDefault();
}
Object val = row.get(srcCol);
String styleSmall = style.toLowerCase();
if (val instanceof List) {
List<String> inputs = (List) val;
List results = new ArrayList();
for (String input : inputs) {
try {
results.add(process(input, styleSmall, locale));
} catch (ParseException e) {
throw new DataImportHandlerException(
DataImportHandlerException.SEVERE,
"Failed to apply NumberFormat on column: " + column, e);
}
}
row.put(column, results);
} else {
if (val == null || val.toString().trim().equals(""))
continue;
try {
row.put(column, process(val.toString(), styleSmall, locale));
} catch (ParseException e) {
throw new DataImportHandlerException(
DataImportHandlerException.SEVERE,
"Failed to apply NumberFormat on column: " + column, e);
}
}
}
}
return row;
} |
2930574_3 | Map<Path, Path> populateTrashCommitPaths(Set<FileStatus> trashSet) {
// find trash paths
Map<Path, Path> trashPaths = new TreeMap<Path, Path>();
Path trash = cluster.getTrashPathWithDateHour();
Iterator<FileStatus> it = trashSet.iterator();
while (it.hasNext()) {
FileStatus src = it.next();
Path target = null;
target = new Path(trash, src.getPath().getParent().getName() + "-"
+ src.getPath().getName());
LOG.debug("Trashing [" + src.getPath() + "] to [" + target + "]");
trashPaths.put(src.getPath(), target);
}
return trashPaths;
} |
2934254_65 | public Iterable<String> formatResults(Iterable<Result> results, final Server server) {
return from(results).transformAndConcat(new Function<Result, List<String>>() {
@Override
public List<String> apply(Result input) {
return formatResult(input, server);
}
}).toList();
} |
2945916_56 | public static AddressListField cc(Address address) {
return addressList0(FieldName.CC, Collections.singleton(address));
} |
2948043_16 | public void inject(Object entity, RESTServiceDiscovery restServiceDiscovery) {
Field injectionField = findInjectionField(entity);
if (injectionField == null) {
return;
}
RESTServiceDiscovery fieldValue = null;
try {
injectionField.setAccessible(true);
fieldValue = (RESTServiceDiscovery) injectionField.get(entity);
} catch (Exception e) {
LogMessages.LOGGER.error(Messages.MESSAGES.failedToReuseServiceDiscovery(entity), e);
}
if (fieldValue == null) {
fieldValue = restServiceDiscovery;
} else {
fieldValue.addAllLinks(restServiceDiscovery);
}
try {
injectionField.set(entity, fieldValue);
injectionField.setAccessible(false);
} catch (Exception e) {
LogMessages.LOGGER.error(Messages.MESSAGES.failedToInjectLinks(entity), e);
}
} |
2964129_9 | public static String encodeJSONMessage(final long messageID, final String endPoint, final String data) {
return SocketIOFrameGenerator.encode(FrameType.JSON, messageID, false, endPoint, data, null);
} |
2974683_0 | @Override
public synchronized int read(long pos, byte[] b, int start, int len)
throws IOException {
this.pos = (int)pos;
return read(b, start, len);
} |
2978404_14 | public void scan(Object object) {
try {
scan(object, "", false, new ArrayList<Object>());
} catch (JMSException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} |
2988101_135 | @OperationMethod(collector = DocumentModelCollector.class)
public DocumentModel run(DocumentModel target) throws OperationException {
resetSchemaProperties(target);
if (saveDocument) {
target = session.saveDocument(target);
if (save) {
session.save();
}
}
return target;
} |
2988709_13 | public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
} |
2988715_4 | public List<NavTreeDescriptor> getTreeDescriptors() {
return registry.getTreeDescriptors(getDirectoryTreeService());
} |
2988721_0 | public PackageBuilder() {
def = new PackageDefinitionImpl();
platforms = new ArrayList<>();
dependencies = new ArrayList<>();
conflicts = new ArrayList<>();
provides = new ArrayList<>();
entries = new LinkedHashMap<>();
installForms = new ArrayList<>();
validationForms = new ArrayList<>();
uninstallForms = new ArrayList<>();
} |
2988725_41 | @Override
public DocumentModelList getEntries() throws DirectoryException {
try {
SearchControls scts = directory.getSearchControls();
if (log.isDebugEnabled()) {
log.debug(String.format(
"LDAPSession.getEntries(): LDAP search base='%s' filter='%s' "
+ " args=* scope=%s [%s]", searchBaseDn,
directory.getBaseFilter(), scts.getSearchScope(), this));
}
NamingEnumeration<SearchResult> results = dirContext.search(
searchBaseDn, directory.getBaseFilter(), scts);
// skip reference fetching
return ldapResultsToDocumentModels(results, false);
} catch (SizeLimitExceededException e) {
throw new org.nuxeo.ecm.directory.SizeLimitExceededException(e);
} catch (NamingException e) {
throw new DirectoryException("getEntries failed", e);
}
} |
2989006_0 | @OperationMethod
public DocumentModel run() {
if (StringUtils.isBlank(path)) {
return session.getRootDocument();
} else {
return session.getDocument(new PathRef(path));
}
} |
2990192_10 | public void write(int b) throws IOException {
if (toSkip > 0) {
toSkip--;
} else {
out.write(b);
}
} |
2992799_3 | @Override
public String toString() {
return "ConditionalAttributeBehavior{" +
"expression=" + expression +
", attribute=" + attribute +
", line=" + line +
", col=" + col +
'}';
} |
2995118_78 | public Map<String, String> createAssociationErrorMap(AssociationReport associationReport) {
Map<String, String> associationErrorMap = new HashMap<>();
//Create map of errors
if (associationReport != null) {
if (associationReport.getSnpError() != null && !associationReport.getSnpError().isEmpty()) {
associationErrorMap.put("SNP Error", associationReport.getSnpError());
}
if (associationReport.getSnpGeneOnDiffChr() != null &&
!associationReport.getSnpGeneOnDiffChr().isEmpty()) {
associationErrorMap.put("Snp Gene On Diff Chr", associationReport.getSnpGeneOnDiffChr());
}
if (associationReport.getNoGeneForSymbol() != null &&
!associationReport.getNoGeneForSymbol().isEmpty()) {
associationErrorMap.put("No Gene For Symbol", associationReport.getNoGeneForSymbol());
}
if (associationReport.getRestServiceError() != null &&
!associationReport.getRestServiceError().isEmpty()) {
associationErrorMap.put("Rest Service Error", associationReport.getRestServiceError());
}
if (associationReport.getSuspectVariationError() != null &&
!associationReport.getSuspectVariationError().isEmpty()) {
associationErrorMap.put("Suspect variation", associationReport.getSuspectVariationError());
}
if (associationReport.getGeneError() != null &&
!associationReport.getGeneError().isEmpty()) {
associationErrorMap.put("Gene Error", associationReport.getGeneError());
}
}
return associationErrorMap;
} |
2997701_136 | public int getCount() {
return curSize;
} |
3010630_0 | public void complete() throws WrongStateException, SystemException {
invoke(Complete.class);
} |
3016145_9 | public LayeredTokenMatcher matcher(LayeredSequence seq)
throws SequenceException {
String encoded = encodeSequence(seq);
Matcher m = encodedPattern.matcher(encoded);
return new LayeredTokenMatcher(m);
} |
3020895_48 | public void start() {
dataProducingThread = new Thread(this);
dataProducingThread.setDaemon(true);
dataProducingThread.start();
} |
3026246_81 | public static void registerProvider() {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null)
Security.addProvider(new BouncyCastleProvider());
} |
3028163_81 | @WriteOperation
public TogglzFeature setFeatureState(@Selector String name, boolean enabled) {
final Feature feature = featureManager.getFeatures().stream()
.filter(f -> f.name().equals(name))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Could not find feature with name " + name));
FeatureState featureState = changeFeatureStatus(feature, enabled);
return new TogglzFeature(feature, featureState);
} |
3040093_3 | public static RunHandler getController(
final RunHandler.Context context,
final RunHandlerConfig config){
final String name = "no.sesat.search.run.handler."
+ config.getClass().getAnnotation(Controller.class).value();
try{
final SiteClassLoaderFactory.Context ctlContext = ContextWrapper.wrap(
SiteClassLoaderFactory.Context.class,
new BaseContext() {
public Spi getSpi() {
return Spi.RUN_HANDLER_CONTROL;
}
},
context
);
final ClassLoader ctlLoader = SiteClassLoaderFactory.instanceOf(ctlContext).getClassLoader();
@SuppressWarnings("unchecked")
final Class<? extends RunHandler> cls = (Class<? extends RunHandler>)ctlLoader.loadClass(name);
final Constructor<? extends RunHandler> constructor = cls.getConstructor(RunHandlerConfig.class);
return constructor.newInstance(config);
} catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(ex);
} catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(ex);
} catch (InvocationTargetException ex) {
throw new IllegalArgumentException(ex);
} catch (InstantiationException ex) {
throw new IllegalArgumentException(ex);
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException(ex);
}
} |
3050780_1 | public String getPublicationId() {
if (this.publicationId == null) {
this.publicationId = extractBeforeSlash(this.url);
}
return this.publicationId;
} |
3061876_8 | public static String maskApiKey(final String key) {
int visibleChars = (int) (0.1 * key.length());
int right = visibleChars / 2;
int left = visibleChars - right; // left >= right
String beginning = key.substring(0, left);
String end = key.substring(key.length() - right);
return beginning + "..." + end;
} |
3069429_0 | protected Map<String, Integer> tokenize(String text) {
Map<String, Integer> tokenMap = newHashMap();
StringTokenizer st = new StringTokenizer(text, "\"{}[]:;|<>?`'.,/~!@#$%^&*()_-+= \t\n\r\f\\");
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.length() < MIN_TOKEN_LENGTH) {
continue;
}
Integer count = tokenMap.containsKey(token) ? tokenMap.get(token) + 1 : 1;
tokenMap.put(token, count);
}
return tokenMap;
} |
3086072_0 | @Background
public void loadProject() {
try {
projectUserRelationDao.delete(projectUserRelationDao.queryForAll());
List<Status> statuses = backlogService.getStatuses();
for (Status status : statuses) {
statusDao.createOrUpdate(status);
Ln.d("put status id:%d", status.id);
}
List<Priority> priorities = backlogService.getPriorities();
for (Priority priority : priorities) {
priorityDao.createOrUpdate(priority);
Ln.d("put priority id:%d", priority.id);
}
List<Resolution> resolutions = backlogService.getResolutions();
for (Resolution resolution : resolutions) {
resolutionDao.createOrUpdate(resolution);
Ln.d("put resolution id:%d", resolution.id);
}
List<Project> projects = backlogService.getProjects();
int projectSize = projects.size();
setProgressMax(projectSize);
for (Project project : projects) {
projectDao.createOrUpdate(project);
Ln.d("put project id:%d", project.id);
List<IssueType> issueTypes = backlogService.getIssueTypes(project.id);
for (IssueType issueType : issueTypes) {
issueTypeDao.createOrUpdate(issueType);
Ln.d("put issueType id:%d name:%s color:%s", issueType.id, issueType.name, issueType.color);
}
List<Component> components = backlogService.getComponents(project.id);
for (Component component : components) {
componentDao.createOrUpdate(component);
Ln.d("put component id:%d", component.id);
}
List<Version> versions = backlogService.getVersions(project.id);
for (Version version : versions) {
versionDao.createOrUpdate(version);
Ln.d("put version id:%d", version.id);
}
List<User> users = backlogService.getUsers(project.id);
for (User user : users) {
userDao.createOrUpdate(user);
ProjectUserRelation rel = new ProjectUserRelation();
rel.project = project;
rel.user = user;
projectUserRelationDao.create(rel);
Ln.d("put user id:%d", user.id);
}
incrementProgress();
}
Ln.d("finish setup");
finishSetup();
} catch (XMLRPCException e) {
failSetup(e);
} catch (SQLException e) {
failSetup(e);
}
} |
3102907_0 | protected String createMSCHAPV2Response(String username, byte[] password, byte ident, byte[] ntResponse, byte[] peerChallenge, byte[] authenticator) {
byte[] authResponse = Authenticator.GenerateAuthenticatorResponse(
password,
ntResponse,
peerChallenge,
authenticator,
username.getBytes()
);
System.err.println("authResponse (" + RadiusUtils.byteArrayToHexString(authResponse) + ")");
String successResponse =
(char)ident
+ "S="
+ RadiusUtils.byteArrayToHexString(authResponse).toUpperCase();
System.err.println("successResponse (" + successResponse + ")");
return successResponse;
} |
3110085_1 | @Compensatable
public void transferMoney(String fromAccount, String toAccount, Double amount) {
accountManager.debitAccount(fromAccount, amount);
accountManager.creditAccount(toAccount, amount);
} |
3113319_1 | @Override
public BigDecimal getPrice(Carrier carrier, Map<Purchasable, Long> items)
{
BigDecimal price = carrier.getPerShipping() != null ? carrier.getPerShipping() : BigDecimal.ZERO;
Long numberOfItems = 0l;
for (Long number : items.values()) {
numberOfItems += number;
}
if (numberOfItems == 0) {
// If the cart is empty, there's no shipping to be paid
return BigDecimal.ZERO;
}
BigDecimal perItem = carrier.getPerItem() != null ? carrier.getPerItem() : BigDecimal.ZERO;
price = price.add(perItem.multiply(BigDecimal.valueOf(numberOfItems)));
return price;
} |
3114475_22 | public String toString(final boolean removeLeadingZero) {
boolean removeZero = removeLeadingZero;
final StringBuilder sb = new StringBuilder("0x");
for (int i = 0; i < INT_ARRAY_SIZE; i++) {
toHex(val[i], removeZero, sb);
if (removeZero && val[i] != 0) {
removeZero = false;
}
}
return sb.toString();
} |
3116751_0 | protected String buildFullMessage(String message, Object... args) {
StringBuilder stringBuilder = new StringBuilder(message.length());
int lastIndex = 0;
int argIndex = 0;
while (true) {
int argPos = message.indexOf(ARGS_PATTERN, lastIndex);
if (argPos == -1) {
break;
}
stringBuilder.append(message.substring(lastIndex, argPos));
lastIndex = argPos + ARGS_PATTERN_LENGTH;
// add the argument, if we still have any
if (argIndex < args.length) {
stringBuilder.append(formatArgument(args[argIndex]));
argIndex++;
}
}
stringBuilder.append(message.substring(lastIndex));
return stringBuilder.toString();
} |
3119164_27 | public SpeculativeGammaConfiguration newWithLocks() {
if (locksDetected) {
return this;
}
return new SpeculativeGammaConfiguration(
true, listenersDetected, commuteDetected, nonRefTypeDetected, orelseDetected, true,
constructedObjectsDetected, richMansConflictScanRequired, abortOnlyDetected, ensureDetected, minimalLength);
} |
3125904_1 | @SuppressWarnings("unchecked")
public <Model> void inject(@NotNull Model model) {
try {
for (Class type = model.getClass(); type != null && type != Object.class && type != Enum.class; type = type.getSuperclass()) {
for (Field field : type.getDeclaredFields()) {
injectField(model, field);
}
}
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
} |
3130403_11 | @Override
public Selection<T_ITEM> getSelection() {
return getSelectionHandler().getSelection();
} |
3139136_1 | public static Map<String, PropertyDescriptor>
getAllProperties(GenericType root)
throws IntrospectionException {
Map<String, PropertyDescriptor> properties =
cPropertiesCache.get(root);
if (properties == null) {
GenericType rootType = root.getRootType();
if (rootType == null) {
rootType = root;
}
properties = Collections.unmodifiableMap
(
createProperties(rootType, root)
);
cPropertiesCache.put(root, properties);
}
return properties;
} |
3149437_2 | @Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
ernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
asSubjectHolder subjectHolder = kerberosClient.login(auth.getName(), auth.getCredentials().toString());
erDetails userDetails = this.userDetailsService.loadUserByUsername(subjectHolder.getUsername());
rberosUsernamePasswordAuthenticationToken output = new KerberosUsernamePasswordAuthenticationToken(
userDetails, auth.getCredentials(), userDetails.getAuthorities(), subjectHolder);
tput.setDetails(authentication.getDetails());
return output;
} |
3149449_52 | protected HostConfiguration getHostConfiguration(URI uri, SAMLMessageContext context) throws MessageEncodingException {
try {
HostConfiguration hc = httpClient.getHostConfiguration();
if (hc != null) {
// Clone configuration from the HTTP Client object
hc = new HostConfiguration(hc);
} else {
// Create brand new configuration when there are no defaults
hc = new HostConfiguration();
}
if (uri.getScheme().equalsIgnoreCase("http")) {
log.debug("Using HTTP configuration");
hc.setHost(uri);
} else {
log.debug("Using HTTPS configuration");
CriteriaSet criteriaSet = new CriteriaSet();
criteriaSet.add(new EntityIDCriteria(context.getPeerEntityId()));
criteriaSet.add(new MetadataCriteria(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
criteriaSet.add(new UsageCriteria(UsageType.UNSPECIFIED));
X509TrustManager trustManager = new X509TrustManager(criteriaSet, context.getLocalSSLTrustEngine());
X509KeyManager manager = new X509KeyManager(context.getLocalSSLCredential());
HostnameVerifier hostnameVerifier = context.getLocalSSLHostnameVerifier();
ProtocolSocketFactory socketFactory = getSSLSocketFactory(context, manager, trustManager, hostnameVerifier);
Protocol protocol = new Protocol("https", socketFactory, 443);
hc.setHost(uri.getHost(), uri.getPort(), protocol);
}
return hc;
} catch (URIException e) {
throw new MessageEncodingException("Error parsing remote location URI", e);
}
} |
3165021_51 | @Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) {
if (!(handler instanceof HandlerMethod)) {
return;
}
SuccessViews successViews = (SuccessViews) ((HandlerMethod) handler).getMethodAnnotation(SuccessViews.class);
SuccessView successView = (SuccessView) ((HandlerMethod) handler).getMethodAnnotation(SuccessView.class);
String viewName = null;
if (successView != null) {
viewName = successView.value();
} else if (successViews != null) {
String[] controllerPaths = RequestUtils.getControllerRequestPaths((HandlerMethod) handler);
viewName = findMatchingTargetUrl(successViews.value(), controllerPaths, request);
}
if (viewName == null) {
return;
}
viewName = RequestUtils.replaceRestPathVariables(viewName, modelAndView.getModel(), request);
modelAndView.setViewName(viewName);
} |
3175956_0 | public String hello(String message) {
return "Hello " + message;
} |
3192456_15 | public void pushTransforms(Matrix4 modelTransform, ShaderProgram shader, Camera camera) {
Matrix3 normalMatrix = new Matrix3(modelTransform).invert().transpose();
//Matrix4 modelViewProjection = modelTransform.multiply(camera.getViewProjectionMatrix());
Matrix4 viewMatrix = camera.getViewMatrix();
Matrix4 modelView = viewMatrix.multiply(modelTransform);
Matrix4 projectionMatrix = camera.getPerspective().getMatrix();
Matrix4 modelViewProjection = projectionMatrix.multiply(modelView);
log.info("model: " + modelTransform);
log.info("projection: " + projectionMatrix);
log.info("modelView: " + modelView);
log.info("modelViewProjection: " + modelViewProjection);
shader.uniform(ShaderUniform.MODEL_VIEW_PROJECTION_MATRIX).setMatrix4(modelViewProjection.toFloatBuffer());
shader.uniform(ShaderUniform.MODEL_VIEW_MATRIX).setMatrix4(modelView.toFloatBuffer());
shader.uniform(ShaderUniform.PROJECTION_MATRIX).setMatrix4(projectionMatrix.toFloatBuffer());
shader.uniform(ShaderUniform.MODEL_MATRIX).setMatrix4(modelTransform.toFloatBuffer());
shader.uniform(ShaderUniform.NORMAL_MATRIX).setMatrix3(normalMatrix.toFloatBuffer());
} |
3192987_254 | @Override
public int hashCode() {
return Objects.hash(id, name, path);
} |
3206489_2 | public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
onResultCanceled(requestCode);
return;
}
if (resultCode != Activity.RESULT_OK) {
onResultNotOk(requestCode);
return;
}
if (data == null) {
onResultNotOk(requestCode);
}
switch (requestCode) {
case CAPTURE_IMAGE:
captureAction.onResult(data);
break;
case PICK_IMAGE:
pickAction.onResult(data);
break;
case CROP_IMAGE: {
cropAction.onResult(data);
break;
}
}
} |
3216014_3 | public static double variance(double[] values) {
double[] squared = new double[values.length];
for (int i = 0; i < values.length; i++) {
squared[i] = values[i] * values[i];
}
double meanVal = mean(values);
return mean(squared) - (meanVal * meanVal);
} |
3224235_1 | public Accuracy train(List<LabeledDatum<F,L>> Data)
{
trainScores = getTrainingResults(Data);
int[] GTLabels = makeLabelVector(Data);
int[] Predictions = trainScores.columnArgmaxs();
TrainAccuracy = new Accuracy(Predictions, GTLabels, CatSize);
return TrainAccuracy;
} |
3242289_6 | @OnClick(R.id.auth_btn_login)
public void login() {
String username = mTxtUsername.getText().toString();
String password = mTxtPassword.getText().toString();
if (username.isEmpty() || password.isEmpty()) {
return;
}
mProgressDisposable = ProgressDialog.create(R.string.authenticating).show(this);
// The following callback can be happening when the app is pushed to the background. We
// update the {@link mLoginResult} observable, s.t. we only react on the change when the app
// is in the foreground.
String accountType = getIntent().getStringExtra(
android.accounts.AccountManager.KEY_ACCOUNT_TYPE);
Account account = new Account(username, accountType);
Disposable unused = mAuthenticator.login(account, password, mCkbRememberPassword.isChecked())
.subscribe(result -> mLoginResult.onNext(new LoginResult(account, result)),
error -> mLoginResult.onNext(new LoginResult(account, error)));
} |
3249257_3 | protected String getBulkData(List<SimpleDataEvent> events) {
StringBuilder builder = new StringBuilder();
for (SimpleDataEvent event : events) {
builder.append(JSONUtils.getElasticSearchBulkHeader(event, this.indexName, this.typeName));
builder.append("\n");
builder.append(JSONUtils.getElasticSearchAddDocument(event.pairs()));
builder.append("\n");
}
return builder.toString();
} |
3250009_0 | public void addCleanUp(ClassLoaderPreMortemCleanUp classLoaderPreMortemCleanUp) {
addConsideringOrder(this.cleanUps, classLoaderPreMortemCleanUp);
} |
3250434_237 | public void remove(String mapId) {
mappedObjects.remove(mapId);
} |
3256677_0 | public void createJobConf(JobConf conf, String[] args) throws IOException {
log.info("Loading paths...");
String line = null;
List<Path> paths = new ArrayList<Path>();
BufferedReader br = new BufferedReader( new FileReader( args[ 0 ] ) );
while( ( line = br.readLine() ) != null ) {
paths.add( new Path( line ) );
}
br.close();
log.info("Setting paths...");
FileInputFormat.setInputPaths( conf, paths.toArray(new Path[] {}) );
log.info("Set "+paths.size()+" InputPaths");
FileOutputFormat.setOutputPath( conf, new Path( args[ 1 ] ) );
//this.setProperties( conf );
conf.setJobName( "NaniteFormatProfiler-"+new File(args[ 0 ]).getName() + "_" + System.currentTimeMillis() );
conf.setInputFormat( ArchiveFileInputFormat.class );
conf.setMapperClass( FormatProfilerMapper.class );
conf.setReducerClass( FormatProfilerReducer.class );
conf.setOutputFormat( TextOutputFormat.class );
conf.set( "map.output.key.field.separator", "" );
conf.setOutputKeyClass( Text.class );
conf.setOutputValueClass( Text.class );
conf.setMapOutputValueClass( Text.class );
// search our classpath first- otherwise we get dependency problems
conf.setUserClassesTakesPrecedence(true);
// Override the task timeout to cope with behaviour when processing malformed archive files
// Value set in MS. Default value is 600,000ms (i.e. 10 mins)
// Set this to 30 minutes
int timeoutMins = 30;
conf.setInt("mapred.task.timeout", timeoutMins*60*1000);
// Override the maxiumum JobConf size so very large lists of files can be processed:
// Default mapred.user.jobconf.limit=5242880 (5M), bump to 100 megabytes = 104857600 bytes.
conf.set("mapred.user.jobconf.limit", "104857600");
// Manually set a large number of reducers:
Config config = ConfigFactory.load();
conf.setNumReduceTasks(config.getInt("warc.hadoop.num_reducers"));
} |
3263787_707 | public void route(String instanceId) throws Exception {
FormSubmission submission = formSubmissionsRepository.findByInstanceId(instanceId);
FormSubmissionHandler handler = handlerMap.get(submission.formName());
if (handler == null) {
logger.warn("Could not find a handler due to unknown form submission: " + submission);
return;
}
logger.info(format("Handling {0} form submission with instance Id: {1} for entity: {2}", submission.formName(),
submission.instanceId(), submission.entityId()));
try {
handler.handle(submission);
formSubmissionReportService.reportFor(submission);
mctsReportService.reportFor(submission);
} catch (Exception e) {
logger.error(format("Handling {0} form submission with instance Id: {1} for entity: {2} failed with exception : {3}",
submission.formName(), submission.instanceId(), submission.entityId(), getFullStackTrace(e)));
throw e;
}
} |
3273720_83 | @Override
public void validate(final InstallServiceValidationContext validationContext) throws RestErrorException {
validateCloudOverridesFileSize(validationContext.getCloudOverridesFile());
} |
3283313_0 | public int createInstance(String gcmadress) {
String vmTemplate = "NAME=vm-4-RoQ\n" + "CONTEXT=[\n"
+ "FILES=\"/nebuladata/scripts/init-RoQ.sh\",\n"
+ "GATEWAY=\"192.168.0.1\",\n" + "HOSTNAME=\"RoQ-VM-$VMID\",\n"
//+ "IP_PUBLIC=$NIC[IP, NETWORK=\"RoQ\"],\n"
+ "TARGET=\"vdb\",\n" + "GCM=\"" + gcmadress + "\"]\n"
+ "CPU=0.2\n" + "DISK=[\n" + "IMAGE=\"RoQ-OpenNebula\",\n"
+ "TARGET=\"vda\" ]\n" + "FEATURES=[\n" + "ACPI=\"yes\" ]\n"
+ "GRAPHICS=[\n" + "KEYMAP=\"fr\",\n" + "LISTEN=\"0.0.0.0\",\n"
+ "TYPE=\"vnc\" ]\n" + "MEMORY=512\n" + "NIC=[\n"
+ "NETWORK=\"RoQ\" ]\n" + "OS=[\n"
+ "ARCH=\"x86_64\",\n" + "BOOT=\"hd\" ]";
logger.info("Trying to allocate the virtual machine... ");
OneResponse rc = VirtualMachine
.allocate(this.oneConnection, vmTemplate);
if (rc.isError()) {
logger.error("Failed to allocate VM !" + rc.getErrorMessage() + "\n" + vmTemplate);
} else {
// The response message is the new VM's ID
int newVMID = Integer.parseInt(rc.getMessage());
logger.info("ok, ID " + newVMID + ".");
VirtualMachine vm = new VirtualMachine(newVMID, oneConnection);
vmAllocated.add(vm);
return newVMID;
}
return -1;
} |
3291848_10 | public static String buildFormPostContent(final WebContext context) {
final String requestedUrl = context.getFullRequestURL();
final Map<String, String[]> parameters = context.getRequestParameters();
final StringBuilder buffer = new StringBuilder();
buffer.append("<html>\n");
buffer.append("<body>\n");
buffer.append("<form action=\"" + escapeHtml(requestedUrl) + "\" name=\"f\" method=\"post\">\n");
if (parameters != null) {
for (final Map.Entry<String, String[]> entry : parameters.entrySet()) {
final String[] values = entry.getValue();
if (values != null && values.length > 0) {
buffer.append("<input type='hidden' name=\"" + escapeHtml(entry.getKey()) + "\" value=\"" + values[0] + "\" />\n");
}
}
}
buffer.append("<input value='POST' type='submit' />\n");
buffer.append("</form>\n");
buffer.append("<script type='text/javascript'>document.forms['f'].submit();</script>\n");
buffer.append("</body>\n");
buffer.append("</html>\n");
return buffer.toString();
} |
3293934_46 | public Flowable<String> messages (String destination) {
return messageReceiver.messages(destination).map(incomingMessage -> incomingMessage.message);
} |
3296177_17 | public static boolean nodeAbsent(Object json, String path, Configuration configuration) {
return nodeAbsent(json, Path.create(path), configuration);
} |
3308294_2 | public String getParameterSummary(String paramName, Element element) {
String comment = elements.getDocComment(element);
if (StringUtils.isBlank(comment)) {
return null;
}
comment = comment.trim();
StringBuilder parameterCommentBuilder = new StringBuilder();
boolean insideParameter = false;
StringTokenizer st = new StringTokenizer(comment, "\n\r");
while (st.hasMoreTokens()) {
String nextToken = st.nextToken().trim();
if (nextToken.startsWith("@param " + paramName + " " ) || nextToken.equals("@param " + paramName)) {
insideParameter = true;
} else if (nextToken.startsWith("@")) {
insideParameter = false;
}
if (insideParameter) {
parameterCommentBuilder.append(nextToken).append(" ");
}
}
int startIndex = 7 + paramName.length() + 1;
if (parameterCommentBuilder.length() < startIndex) {
return null;
}
String parameterComment = parameterCommentBuilder.substring(startIndex);
StringBuilder strippedCommentBuilder = new StringBuilder();
boolean insideTag = false;
for (int i = 0; i < parameterComment.length(); i++) {
if (parameterComment.charAt(i) == '{' &&
parameterComment.charAt(i + 1) == '@') {
insideTag = true;
} else if (parameterComment.charAt(i) == '}') {
insideTag = false;
} else {
if (!insideTag) {
strippedCommentBuilder.append(parameterComment.charAt(i));
}
}
}
String strippedComment = strippedCommentBuilder.toString().trim();
while (strippedComment.length() > 0 && strippedComment.charAt(strippedComment.length() - 1) == '\n') {
strippedComment = StringUtils.chomp(strippedComment);
}
return strippedComment;
} |
3314133_111 | public BGPv4Packet decodeUpdatePacket(ByteBuf buffer) {
UpdatePacket packet = new UpdatePacket();
ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_UPDATE, -1);
if(buffer.readableBytes() < 2)
throw new MalformedAttributeListException();
// handle withdrawn routes
int withdrawnOctets = buffer.readUnsignedShort();
// sanity checking
if(withdrawnOctets > buffer.readableBytes())
throw new MalformedAttributeListException();
ByteBuf withdrawnBuffer = null;
if(withdrawnOctets > 0) {
withdrawnBuffer = buffer.readSlice(withdrawnOctets);
}
// sanity checking
if(buffer.readableBytes() < 2)
throw new MalformedAttributeListException();
// handle path attributes
int pathAttributeOctets = buffer.readUnsignedShort();
// sanity checking
if(pathAttributeOctets > buffer.readableBytes())
throw new MalformedAttributeListException();
ByteBuf pathAttributesBuffer = null;
if(pathAttributeOctets > 0) {
pathAttributesBuffer = buffer.readSlice(pathAttributeOctets);
}
if(withdrawnBuffer != null) {
try {
packet.getWithdrawnRoutes().addAll(decodeWithdrawnRoutes(withdrawnBuffer));
} catch(IndexOutOfBoundsException e) {
throw new MalformedAttributeListException();
}
}
if(pathAttributesBuffer != null) {
try {
packet.getPathAttributes().addAll(decodePathAttributes(pathAttributesBuffer));
} catch (IndexOutOfBoundsException ex) {
throw new MalformedAttributeListException();
}
}
// handle network layer reachability information
if(buffer.readableBytes() > 0) {
try {
while (buffer.isReadable()) {
packet.getNlris().add(NLRICodec.decodeNLRI(buffer));
}
} catch (IndexOutOfBoundsException e) {
throw new InvalidNetworkFieldException();
} catch(IllegalArgumentException e) {
throw new InvalidNetworkFieldException();
}
}
return packet;
} |
3315140_46 | public static void main(String... args) {
loadJDKLoggingConfiguration();
Injector injector = Guice.createInjector(new LoggerModule());
ProvisioningCLI provisioningCLI = injector.getInstance(ProvisioningCLI.class);
new ProvisioningCLI().startCLI(args);
} |
3319591_6 | public Geometry parse(String wkt) {
if (wkt != null) {
tempWkt = wkt;
if (skip(org.geomajas.geometry.Geometry.MULTI_POLYGON.toUpperCase())) {
return parseMultiPolygon();
} else if (skip(org.geomajas.geometry.Geometry.POLYGON.toUpperCase())) {
return parsePolygon();
} else if (skip(org.geomajas.geometry.Geometry.MULTI_LINE_STRING.toUpperCase())) {
return parseMultiLineString();
} else if (skip(org.geomajas.geometry.Geometry.MULTI_POINT.toUpperCase())) {
return parseMultiPoint();
} else if (skip(org.geomajas.geometry.Geometry.LINE_STRING.toUpperCase())) {
return parseLineString();
} else if (skip(org.geomajas.geometry.Geometry.POINT.toUpperCase())) {
return parsePoint();
}
}
return null;
} |
3328338_6 | public boolean verifyResponseEqualsUsername(String duoResponse) {
try {
String duoVerifiedResponse = DuoWeb.verifyResponse(ikey, skey, akey, duoResponse);
boolean usernameMatches = duoVerifiedResponse.equals(username);
if (usernameMatches) {
log.info(username + " successfully Duo two-factor authenticated.");
return true;
} else {
log.info(username + " attempted Duo two-factor authentication but username " + duoVerifiedResponse + " was sent in the Duo response.");
}
} catch (Exception e) {
log.error("An exception occurred while " + username + " attempted Duo two-factor authentication.", e);
}
return false;
} |
3332790_6 | public void writeShort(ByteBuf buffer, short s) {
buffer.writeByte(SHORT);
buffer.writeShort(s);
} |
3333998_352 | @Override
public String digestParams(RestInvocation restInvocation) {
String invocationUrl = restInvocation.getInvocationUrl();
Mac mac = getMac();
mac.update(invocationUrl.getBytes());
return String.format("%0128x", new BigInteger(1, mac.doFinal()));
} |
3337772_506 | public String performTask(String taskParameters) {
EnableStreamingTaskParameters taskParams =
EnableStreamingTaskParameters.deserialize(taskParameters);
String spaceId = taskParams.getSpaceId();
boolean secure = taskParams.isSecure();
List<String> allowedOrigins = taskParams.getAllowedOrigins();
log.info("Performing " + TASK_NAME + " task on space " + spaceId +
". Secure streaming set to " + secure);
// Will throw if bucket does not exist
String bucketName = unwrappedS3Provider.getBucketName(spaceId);
String domainName = null;
String distId = null;
String oaIdentityId = getOriginAccessId();
EnableStreamingTaskResult taskResult = new EnableStreamingTaskResult();
DistributionSummary existingDist = getExistingDistribution(bucketName);
if (existingDist != null) { // There is an existing distribution
// Ensure that this is not an attempt to change the security type
// of this existing distribution
boolean existingSecure =
!existingDist.getDefaultCacheBehavior().getTrustedSigners().getItems().isEmpty();
if ((secure && !existingSecure) || (!secure && existingSecure)) {
throw new UnsupportedTaskException(TASK_NAME,
"The space " + spaceId + " is already configured to stream as " +
(secure ? "OPEN" : "SECURE") +
" and cannot be updated to stream as " +
(secure ? "SECURE" : "OPEN") +
". To do this, you must first execute the " +
StorageTaskConstants.DELETE_HLS_TASK_NAME + " task.");
}
distId = existingDist.getId();
if (!existingDist.isEnabled()) { // Distribution is disabled, enable it
setDistributionState(distId, true);
}
domainName = existingDist.getDomainName();
} else { // No existing distribution, need to create one
// Create S3 Origin
S3OriginConfig s3OriginConfig = new S3OriginConfig()
.withOriginAccessIdentity(S3_ORIGIN_OAI_PREFIX + oaIdentityId);
Origin s3Origin = new Origin().withDomainName(bucketName + S3_ORIGIN_SUFFIX)
.withS3OriginConfig(s3OriginConfig)
.withId("S3-" + bucketName);
// Only include trusted signers on secure distributions
TrustedSigners signers = new TrustedSigners();
if (secure) {
signers.setItems(Collections.singletonList(cfAccountId));
signers.setEnabled(true);
signers.setQuantity(1);
} else {
signers.setEnabled(false);
signers.setQuantity(0);
}
DefaultCacheBehavior defaultCacheBehavior = new DefaultCacheBehavior();
defaultCacheBehavior.setTrustedSigners(signers);
defaultCacheBehavior.setViewerProtocolPolicy(ViewerProtocolPolicy.RedirectToHttps);
// Forwarding headers to support CORS, see:
// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-cors
defaultCacheBehavior.setAllowedMethods(
new AllowedMethods().withItems(Method.GET, Method.HEAD, Method.OPTIONS)
.withQuantity(3));
defaultCacheBehavior.setForwardedValues(
new ForwardedValues()
.withQueryString(false)
.withCookies(new CookiePreference().withForward(ItemSelection.None))
.withHeaders(new Headers().withItems("Origin",
"Access-Control-Request-Headers",
"Access-Control-Request-Method")
.withQuantity(3)));
// Setting other cache behaviors required by the client
defaultCacheBehavior.setMinTTL(0l);
defaultCacheBehavior.setTargetOriginId(s3Origin.getId());
// Create origins list
Origins origins;
CacheBehaviors cacheBehaviors = new CacheBehaviors();
if (secure) {
// Create Origin to allow signed cookies to be set through a CloudFront call
CustomOriginConfig cookiesOriginConfig = new CustomOriginConfig()
.withOriginProtocolPolicy(OriginProtocolPolicy.HttpsOnly)
.withHTTPPort(80)
.withHTTPSPort(443);
String getCookiesPath = "/durastore/aux";
String cookiesOriginId = "Custom origin - " + dcHost + getCookiesPath;
Origin cookiesOrigin = new Origin().withDomainName(dcHost)
.withOriginPath(getCookiesPath)
.withId(cookiesOriginId)
.withCustomOriginConfig(cookiesOriginConfig);
origins = new Origins().withItems(s3Origin, cookiesOrigin).withQuantity(2);
// Create behavior for cookies origin
CookiePreference cookiePreference = new CookiePreference().withForward(ItemSelection.All);
CacheBehavior cookiesCacheBehavior = new CacheBehavior()
.withPathPattern("/cookies")
.withTargetOriginId(cookiesOriginId)
.withViewerProtocolPolicy(ViewerProtocolPolicy.RedirectToHttps)
.withAllowedMethods(new AllowedMethods().withItems(Method.GET, Method.HEAD).withQuantity(2))
.withForwardedValues(new ForwardedValues().withQueryString(true).withCookies(cookiePreference))
.withTrustedSigners(new TrustedSigners().withEnabled(false).withQuantity(0))
.withMinTTL(0l);
cacheBehaviors = cacheBehaviors.withItems(cookiesCacheBehavior).withQuantity(1);
} else {
origins = new Origins().withItems(s3Origin).withQuantity(1);
}
// Build distribution
DistributionConfig distributionConfig = new DistributionConfig()
.withCallerReference("" + System.currentTimeMillis())
.withOrigins(origins)
.withEnabled(true)
.withComment("HLS streaming for space: " + spaceId)
.withDefaultCacheBehavior(defaultCacheBehavior);
if (secure) {
distributionConfig.setCacheBehaviors(cacheBehaviors);
}
Distribution dist = cfClient.createDistribution(
new CreateDistributionRequest(distributionConfig)).getDistribution();
domainName = dist.getDomainName();
}
// Set bucket policy to accept origin access identity
setBucketAccessPolicy(bucketName, oaIdentityId);
// Set CORS policy on bucket
setCorsPolicy(bucketName, allowedOrigins, dcHost);
// Update bucket tags to include streaming host
Map<String, String> spaceProps = s3Provider.getSpaceProperties(spaceId);
spaceProps.put(HLS_STREAMING_HOST_PROP, domainName);
spaceProps.put(HLS_STREAMING_TYPE_PROP,
secure ? STREAMING_TYPE.SECURE.name() : STREAMING_TYPE.OPEN.name());
unwrappedS3Provider.setNewSpaceProperties(spaceId, spaceProps);
taskResult.setResult(TASK_NAME + " task completed successfully");
// Return results
taskResult.setStreamingHost(domainName);
String toReturn = taskResult.serialize();
log.info("Result of " + TASK_NAME + " task: " + toReturn);
return toReturn;
} |
3352045_33 | public ESMClass setSpecificFeature(GSMSpecificFeature specificFeature) {
value = GSMSpecificFeature.compose(value, specificFeature);
return this;
} |
3360581_13 | public static String serializeMsgstr(Message message) {
if (message.isPlural()) {
StringBuilder sb = new StringBuilder();
List<String> plurals = message.getMsgstrPlural();
for (Iterator<String> it=plurals.iterator(); it.hasNext(); ) {
String plural = it.next();
sb.append(plural);
if (it.hasNext()) {
sb.append("\u0000");
}
}
return sb.toString();
} else {
String msgstr = message.getMsgstr();
return msgstr == null ? "" : msgstr;
}
} |
3362935_1 | static Map<String, String> keyValueMapFor(String logLine) {
Map<String, String> keyValueMap = new HashMap<String, String>();
Matcher matcher = KEY_VALUE_HOLDER_PATTERN.matcher(logLine);
if (matcher.find()) {
for (String keyValuePair : matcher.group(1).split(",")) {
int separatorIndex = keyValuePair.indexOf("=");
if (separatorIndex > 0) {
String key = keyValuePair.substring(0, separatorIndex);
String value = keyValuePair.substring(separatorIndex + 1);
keyValueMap.put(key, value);
}
}
}
return keyValueMap;
} |
3370128_31 | public static JdbcCallParseInfo modifyJdbcCall(String jdbcSql, boolean stdStrings,
int serverVersion, int protocolVersion, EscapeSyntaxCallMode escapeSyntaxCallMode) throws SQLException {
// Mini-parser for JDBC function-call syntax (only)
// TODO: Merge with escape processing (and parameter parsing?) so we only parse each query once.
// RE: frequently used statements are cached (see {@link org.postgresql.jdbc.PgConnection#borrowQuery}), so this "merge" is not that important.
String sql = jdbcSql;
boolean isFunction = false;
boolean outParamBeforeFunc = false;
int len = jdbcSql.length();
int state = 1;
boolean inQuotes = false;
boolean inEscape = false;
int startIndex = -1;
int endIndex = -1;
boolean syntaxError = false;
int i = 0;
while (i < len && !syntaxError) {
char ch = jdbcSql.charAt(i);
switch (state) {
case 1: // Looking for { at start of query
if (ch == '{') {
++i;
++state;
} else if (Character.isWhitespace(ch)) {
++i;
} else {
// Not function-call syntax. Skip the rest of the string.
i = len;
}
break;
case 2: // After {, looking for ? or =, skipping whitespace
if (ch == '?') {
outParamBeforeFunc =
isFunction = true; // { ? = call ... } -- function with one out parameter
++i;
++state;
} else if (ch == 'c' || ch == 'C') { // { call ... } -- proc with no out parameters
state += 3; // Don't increase 'i'
} else if (Character.isWhitespace(ch)) {
++i;
} else {
// "{ foo ...", doesn't make sense, complain.
syntaxError = true;
}
break;
case 3: // Looking for = after ?, skipping whitespace
if (ch == '=') {
++i;
++state;
} else if (Character.isWhitespace(ch)) {
++i;
} else {
syntaxError = true;
}
break;
case 4: // Looking for 'call' after '? =' skipping whitespace
if (ch == 'c' || ch == 'C') {
++state; // Don't increase 'i'.
} else if (Character.isWhitespace(ch)) {
++i;
} else {
syntaxError = true;
}
break;
case 5: // Should be at 'call ' either at start of string or after ?=
if ((ch == 'c' || ch == 'C') && i + 4 <= len && jdbcSql.substring(i, i + 4)
.equalsIgnoreCase("call")) {
isFunction = true;
i += 4;
++state;
} else if (Character.isWhitespace(ch)) {
++i;
} else {
syntaxError = true;
}
break;
case 6: // Looking for whitespace char after 'call'
if (Character.isWhitespace(ch)) {
// Ok, we found the start of the real call.
++i;
++state;
startIndex = i;
} else {
syntaxError = true;
}
break;
case 7: // In "body" of the query (after "{ [? =] call ")
if (ch == '\'') {
inQuotes = !inQuotes;
++i;
} else if (inQuotes && ch == '\\' && !stdStrings) {
// Backslash in string constant, skip next character.
i += 2;
} else if (!inQuotes && ch == '{') {
inEscape = !inEscape;
++i;
} else if (!inQuotes && ch == '}') {
if (!inEscape) {
// Should be end of string.
endIndex = i;
++i;
++state;
} else {
inEscape = false;
}
} else if (!inQuotes && ch == ';') {
syntaxError = true;
} else {
// Everything else is ok.
++i;
}
break;
case 8: // At trailing end of query, eating whitespace
if (Character.isWhitespace(ch)) {
++i;
} else {
syntaxError = true;
}
break;
default:
throw new IllegalStateException("somehow got into bad state " + state);
}
}
// We can only legally end in a couple of states here.
if (i == len && !syntaxError) {
if (state == 1) {
// Not an escaped syntax.
// Detect PostgreSQL native CALL.
// (OUT parameter registration, needed for stored procedures with INOUT arguments, will fail without this)
i = 0;
while (i < len && Character.isWhitespace(jdbcSql.charAt(i))) {
i++; // skip any preceding whitespace
}
if (i < len - 5) { // 5 == length of "call" + 1 whitespace
//Check for CALL followed by whitespace
char ch = jdbcSql.charAt(i);
if ((ch == 'c' || ch == 'C') && jdbcSql.substring(i, i + 4).equalsIgnoreCase("call")
&& Character.isWhitespace(jdbcSql.charAt(i + 4))) {
isFunction = true;
}
}
return new JdbcCallParseInfo(sql, isFunction);
}
if (state != 8) {
syntaxError = true; // Ran out of query while still parsing
}
}
if (syntaxError) {
throw new PSQLException(
GT.tr("Malformed function or procedure escape syntax at offset {0}.", i),
PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
}
String prefix;
String suffix;
if (escapeSyntaxCallMode == EscapeSyntaxCallMode.SELECT || serverVersion < 110000
|| (outParamBeforeFunc && escapeSyntaxCallMode == EscapeSyntaxCallMode.CALL_IF_NO_RETURN)) {
prefix = "select * from ";
suffix = " as result";
} else {
prefix = "call ";
suffix = "";
}
String s = jdbcSql.substring(startIndex, endIndex);
int prefixLength = prefix.length();
StringBuilder sb = new StringBuilder(prefixLength + jdbcSql.length() + suffix.length() + 10);
sb.append(prefix);
sb.append(s);
int opening = s.indexOf('(') + 1;
if (opening == 0) {
// here the function call has no parameters declaration eg : "{ ? = call pack_getValue}"
sb.append(outParamBeforeFunc ? "(?)" : "()");
} else if (outParamBeforeFunc) {
// move the single out parameter into the function call
// so that it can be treated like all other parameters
boolean needComma = false;
// the following loop will check if the function call has parameters
// eg "{ ? = call pack_getValue(?) }" vs "{ ? = call pack_getValue() }
for (int j = opening + prefixLength; j < sb.length(); j++) {
char c = sb.charAt(j);
if (c == ')') {
break;
}
if (!Character.isWhitespace(c)) {
needComma = true;
break;
}
}
// insert the return parameter as the first parameter of the function call
if (needComma) {
sb.insert(opening + prefixLength, "?,");
} else {
sb.insert(opening + prefixLength, "?");
}
}
if (!suffix.isEmpty()) {
sql = sb.append(suffix).toString();
} else {
sql = sb.toString();
}
return new JdbcCallParseInfo(sql, isFunction);
} |
3375991_0 | @Override
public Query parseQuery(String expression) {
if (expression == null) {
return null;
}
OqlParser parser = newParser(expression);
try {
parser.oql();
} catch (RecognitionException e) {
e.printStackTrace();
}
return parser.getQuery();
} |
3376848_2 | @Override
@CheckReturnValue
public boolean hasWebDriverStarted() {
WebDriver webDriver = threadWebDriver.get(currentThread().getId());
return webDriver != null;
} |
3382195_492 | public static String getQRCode(String issuer,
String accountName,
String secretKey) throws WriterException, IOException {
if(!StringUtils.hasText(issuer) || issuer.contains(":")) {
throw new IllegalArgumentException("invalid issuer");
}
if(!StringUtils.hasText(accountName) || accountName.contains(":")) {
throw new IllegalArgumentException("invalid account name");
}
QRCodeWriter writer = new QRCodeWriter();
BitMatrix qrBitMatrix = writer.encode(String.format(
OTPAUTH_TOTP_URI,
UriUtils.encode(issuer, STRING_ENCODING),
UriUtils.encode(accountName, STRING_ENCODING),
secretKey,
UriUtils.encode(issuer, STRING_ENCODING)),
BarcodeFormat.QR_CODE, 200, 200);
BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(qrBitMatrix);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(qrImage, "png", os);
return Base64.getEncoder().encodeToString(os.toByteArray());
} |
3398614_3 | protected String constructStatusAndHeaders(AtmosphereResponse response, int contentLength) {
StringBuffer b = new StringBuffer("HTTP/1.1")
.append(" ")
.append(response.getStatus())
.append(" ")
.append(response.getStatusMessage())
.append(CRLF);
Map<String, String> headers = response.headers();
String contentType = response.getContentType();
b.append("Content-Type").append(":").append(headers.get("Content-Type") == null ? contentType : headers.get("Content-Type")).append(CRLF);
if (contentLength != -1) {
b.append("Content-Length").append(":").append(contentLength).append(CRLF);
}
for (String s : headers.keySet()) {
if (!s.equalsIgnoreCase("Content-Type")) {
b.append(s).append(":").append(headers.get(s)).append(CRLF);
}
}
b.append(CRLF);
return b.toString();
} |
3407114_33 | public static Pair<String, String> parseLspciMachineReadable(String line) {
Matcher matcher = LSPCI_MACHINE_READABLE.matcher(line);
if (matcher.matches()) {
return new Pair<>(matcher.group(1), matcher.group(2));
}
return null;
} |
3407162_17 | @Override
public boolean matches(final OSCMessageEvent messageEvent) {
return logicOperator.matches(selector1.matches(messageEvent), selector2.matches(messageEvent));
} |
3409328_0 | @JsonIgnore
public String getId() {
return id;
} |
3411081_27 | @Override
public IOException createException(String message)
{
return new IOException(message);
} |
3415743_0 | public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) {
Provider<EventCasterInternal> eventCasterProvider = null;
for (final Class<?> interfaceClass : listInterfaces(type.getRawType(), new HashSet<Class<?>>())) {
final TypeLiteral<?> interfaceType = type.getSupertype(interfaceClass);
if (bindings.contains(interfaceType))
{
if(eventCasterProvider == null)
{
eventCasterProvider = encounter.getProvider(EventCasterInternal.class);
}
encounter.register(new RegisterInjectedEventListeners<I>(interfaceType, eventCasterProvider));
}
}
} |
3423262_43 | public boolean matches(Class<?> parentEntityType, String propertyName,
Object value) {
if (value == null) {
return _value == null;
} else if (_value == null) {
return false;
}
if (_resolvedValueSet) {
return value.equals(_resolvedValue);
}
Class<?> expectedValueType = value.getClass();
Class<?> actualValueType = _value.getClass();
if (expectedValueType.isAssignableFrom(actualValueType)) {
if (isRegexObj(_value)) {
return regexMatch((String)value, ((String)_value));
}
return value.equals(_value);
}
if (actualValueType == String.class) {
String actualValue = (String) _value;
if (expectedValueType == AgencyAndId.class) {
AgencyAndId expectedId = (AgencyAndId) value;
if (isRegexObj(_value)) {
return regexMatch(expectedId.getId(), actualValue);
}
return expectedId.getId().equals(actualValue);
} else if (IdentityBean.class.isAssignableFrom(expectedValueType)) {
IdentityBean<?> bean = (IdentityBean<?>) value;
Object expectedId = bean.getId();
if (expectedId == null) {
return false;
}
if (expectedId instanceof AgencyAndId) {
AgencyAndId expectedFullId = (AgencyAndId) expectedId;
return expectedFullId.getId().equals(actualValue);
} else if (expectedId instanceof String) {
return expectedId.equals(actualValue);
}
} else {
Converter converter = _support.resolveConverter(parentEntityType,
propertyName, expectedValueType);
if (converter != null) {
_resolvedValue = converter.convert(expectedValueType, _value);
_resolvedValueSet = true;
return value.equals(_resolvedValue);
} else {
throw new IllegalStateException(
"no type conversion from type String to type \""
+ expectedValueType.getName() + "\" for value comparison");
}
}
}
throw new IllegalStateException("no type conversion from type \""
+ actualValueType.getName() + "\" to type \""
+ expectedValueType.getName() + "\" for value comparison");
} |
3424353_158 | @Override
@Transactional(rollbackFor = Throwable.class)
public void delete(Assignment assignment) {
getSession().delete(assignment);
} |
3425475_5 | public void clearPendingSubscription(SiriClientRequest request,
SubscriptionRequest subscriptionRequest) {
_log.info("clear pending subscription: {}", request);
_initiateSubscriptionsManager.clearPendingSubscription(request,
subscriptionRequest);
} |
3429525_9 | protected String renderOpenQuestion(Question question, ArrayList<String> prompts, String sessionKey) {
TwiMLResponse twiml = new TwiMLResponse();
String typeProperty = question.getMediaPropertyValue(MediumType.BROADSOFT, MediaPropertyKey.TYPE);
if (typeProperty != null && typeProperty.equalsIgnoreCase("audio")) {
renderVoiceMailQuestion(question, prompts, sessionKey, twiml);
}
else {
Gather gather = new Gather();
gather.setAction(getAnswerUrl());
gather.setMethod("GET");
String dtmfMaxLength = question.getMediaPropertyValue(MediumType.BROADSOFT,
MediaPropertyKey.ANSWER_INPUT_MAX_LENGTH);
if (dtmfMaxLength != null) {
try {
int digits = Integer.parseInt(dtmfMaxLength);
gather.setNumDigits(digits);
}
catch (NumberFormatException e) {
e.printStackTrace();
}
}
String noAnswerTimeout = question.getMediaPropertyValue(MediumType.BROADSOFT, MediaPropertyKey.TIMEOUT);
//assign a default timeout if one is not specified
noAnswerTimeout = noAnswerTimeout != null ? noAnswerTimeout : "5";
if (noAnswerTimeout.endsWith("s")) {
log.warning("No answer timeout must end with 's'. E.g. 10s. Found: " + noAnswerTimeout);
noAnswerTimeout = noAnswerTimeout.replace("s", "");
}
int timeout = 5;
try {
timeout = Integer.parseInt(noAnswerTimeout);
}
catch (NumberFormatException e) {
e.printStackTrace();
}
gather.setTimeout(timeout);
try {
addPrompts(prompts, gather, ServerUtils.getTTSInfoFromSession(question, sessionKey));
twiml.append(gather);
Redirect redirect = new Redirect(getTimeoutUrl());
redirect.setMethod("GET");
twiml.append(redirect);
}
catch (TwiMLException e) {
e.printStackTrace();
}
}
return twiml.toXML();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.