id stringlengths 7 14 | text stringlengths 1 106k |
|---|---|
960760_9 | @Override
public void bringToFront(final DrawingObject dob) {
if (threadSafe) {
synchronized (lock) {
insertionOrder.put(dob, ++insertionOrderLargest);
}
} else {
insertionOrder.put(dob, ++insertionOrderLargest);
}
} |
990281_0 | public static SimpleGlobPattern compile(String patternString) {
SimpleGlobPattern pattern = EmptyGlobPattern.INSTANCE;
int endIndexInclusive = patternString.length() - 1;
while ( endIndexInclusive >= 0 ) {
int lastWildcardIndex = patternString.lastIndexOf( WILDCARD_MANY, endIndexInclusive );
if ( lastWildcardIndex < endIndexInclusive ) {
pattern = pattern.prependLiteral( patternString.substring( lastWildcardIndex + 1, endIndexInclusive + 1 ) );
}
if ( 0 <= lastWildcardIndex ) {
pattern = pattern.prependMany();
}
endIndexInclusive = lastWildcardIndex - 1;
}
return pattern;
} |
990281_1 | public boolean matches(String candidate) {
return matches( candidate, 0 );
} |
990281_2 | ; |
990281_3 | public Optional<String> toLiteral() {
return Optional.empty();
} |
990281_4 | @Override
public boolean cancel(boolean mayInterruptIfRunning) {
/*
* Calling future.cancel() may trigger an exception in the operation that may
* end up setting 'this' as completed exceptionally because of the failure...
* Thus we mark 'this' as cancelled *first*, so that any exception in the operation
* from now on will be ignored.
*/
super.cancel( mayInterruptIfRunning );
return future.cancel( mayInterruptIfRunning );
} |
990281_5 | public <E2 extends Exception> Closer<E2> split() {
return new Closer<>( state );
} |
990281_6 | public <E2 extends Exception> Closer<E2> split() {
return new Closer<>( state );
} |
990281_7 | public SuppressingCloser push(AutoCloseable closeable) {
return push( AutoCloseable::close, closeable );
} |
990281_8 | public SuppressingCloser push(AutoCloseable closeable) {
return push( AutoCloseable::close, closeable );
} |
990281_9 | public SuppressingCloser push(AutoCloseable closeable) {
return push( AutoCloseable::close, closeable );
} |
991965_0 | public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType )
{
NotQueryableException.throwIfNotQueryable( resultType );
final ServiceReference<EntityFinder> serviceReference;
try
{
serviceReference = finder.findService( EntityFinder.class );
return new QueryBuilderImpl<T>( serviceReference.get(), resultType, null );
}
catch( IllegalArgumentException e )
{
return new QueryBuilderImpl<T>( null, resultType, null );
}
} |
991965_1 | public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType )
{
NotQueryableException.throwIfNotQueryable( resultType );
final ServiceReference<EntityFinder> serviceReference;
try
{
serviceReference = finder.findService( EntityFinder.class );
return new QueryBuilderImpl<T>( serviceReference.get(), resultType, null );
}
catch( IllegalArgumentException e )
{
return new QueryBuilderImpl<T>( null, resultType, null );
}
} |
991965_2 | public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType )
{
NotQueryableException.throwIfNotQueryable( resultType );
final ServiceReference<EntityFinder> serviceReference;
try
{
serviceReference = finder.findService( EntityFinder.class );
return new QueryBuilderImpl<T>( serviceReference.get(), resultType, null );
}
catch( IllegalArgumentException e )
{
return new QueryBuilderImpl<T>( null, resultType, null );
}
} |
991965_3 | public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType )
{
NotQueryableException.throwIfNotQueryable( resultType );
final ServiceReference<EntityFinder> serviceReference;
try
{
serviceReference = finder.findService( EntityFinder.class );
return new QueryBuilderImpl<T>( serviceReference.get(), resultType, null );
}
catch( IllegalArgumentException e )
{
return new QueryBuilderImpl<T>( null, resultType, null );
}
} |
991965_4 | public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType )
{
NotQueryableException.throwIfNotQueryable( resultType );
final ServiceReference<EntityFinder> serviceReference;
try
{
serviceReference = finder.findService( EntityFinder.class );
return new QueryBuilderImpl<T>( serviceReference.get(), resultType, null );
}
catch( IllegalArgumentException e )
{
return new QueryBuilderImpl<T>( null, resultType, null );
}
} |
991965_5 | public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType )
{
NotQueryableException.throwIfNotQueryable( resultType );
final ServiceReference<EntityFinder> serviceReference;
try
{
serviceReference = finder.findService( EntityFinder.class );
return new QueryBuilderImpl<T>( serviceReference.get(), resultType, null );
}
catch( IllegalArgumentException e )
{
return new QueryBuilderImpl<T>( null, resultType, null );
}
} |
991965_6 | public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType )
{
NotQueryableException.throwIfNotQueryable( resultType );
final ServiceReference<EntityFinder> serviceReference;
try
{
serviceReference = finder.findService( EntityFinder.class );
return new QueryBuilderImpl<T>( serviceReference.get(), resultType, null );
}
catch( IllegalArgumentException e )
{
return new QueryBuilderImpl<T>( null, resultType, null );
}
} |
991965_7 | @Override
public <T> Iterator<T> iterator( Class<T> resultType, Specification<Composite> whereClause, Iterable<OrderBy> orderBySegments, Integer firstResult, Integer maxResults, Map<String, Object> variables )
{
return list(resultType, whereClause, orderBySegments, firstResult, maxResults, variables).iterator();
} |
991965_8 | public List<K> resolveOrder()
throws BindingException
{
if( resolved == null )
{
buildUsageGraph();
resolved = new LinkedList<K>();
for( K item : data )
{
int pos = resolved.size();
for( K entry : resolved )
{
if( transitiveUse( entry, item ) )
{
pos = resolved.indexOf( entry );
break;
}
}
resolved.add( pos, item );
}
}
return resolved;
} |
991965_9 | public boolean transitiveUse( K source, K other ) throws BindingException
{
if( transitive == null )
{
buildUsageGraph();
}
return transitive.containsKey( source ) && transitive.get( source ).contains( other );
} |
992007_0 | public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable
{
try
{
// Get Ruby object for declaring class of the method
Class declaringClass = method.getDeclaringClass();
IRubyObject rubyObject = rubyObjects.get( declaringClass );
// If not yet created, create one
if( rubyObject == null )
{
// Create object instance
try
{
rubyObject = runtime.evalScriptlet( declaringClass.getSimpleName() + ".new()" );
}
catch( RaiseException e )
{
if( e.getException() instanceof RubyNameError )
{
// Initialize Ruby class
String script = getFunction( method );
runtime.evalScriptlet( script );
// Try creating a Ruby instance again
rubyObject = runtime.evalScriptlet( declaringClass.getSimpleName() + ".new()" );
}
else
{
throw e;
}
}
// Set @this variable to Composite
IRubyObject meRuby = JavaEmbedUtils.javaToRuby( runtime, me );
RubyClass rubyClass = meRuby.getMetaClass();
if( !rubyClass.isFrozen() )
{
SetterDynamicMethod setter = new SetterDynamicMethod( runtime.getObjectSpaceModule(), Visibility.PUBLIC, null );
GetterDynamicMethod getter = new GetterDynamicMethod( runtime.getObjectSpaceModule(), Visibility.PUBLIC, null );
Method[] compositeMethods = me.getClass().getInterfaces()[ 0 ].getMethods();
for( Method compositeMethod : compositeMethods )
{
if( Property.class.isAssignableFrom( compositeMethod.getReturnType() ) )
{
rubyClass.addMethod( compositeMethod.getName() + "=", setter );
rubyClass.addMethod( compositeMethod.getName(), getter );
}
}
rubyClass.freeze( ThreadContext.newContext( runtime ) );
}
RubyObjectAdapter rubyObjectAdapter = JavaEmbedUtils.newObjectAdapter();
rubyObjectAdapter.setInstanceVariable( rubyObject, "@this", meRuby );
rubyObjects.put( declaringClass, rubyObject );
}
// Convert method arguments and invoke the method
IRubyObject rubyResult;
if( args != null )
{
IRubyObject[] rubyArgs = new IRubyObject[args.length];
for( int i = 0; i < args.length; i++ )
{
Object arg = args[ i ];
rubyArgs[ i ] = JavaEmbedUtils.javaToRuby( runtime, arg );
}
rubyResult = rubyObject.callMethod( runtime.getCurrentContext(), method.getName(), rubyArgs );
}
else
{
rubyResult = rubyObject.callMethod( runtime.getCurrentContext(), method.getName() );
}
// Convert result to Java
Object result = JavaEmbedUtils.rubyToJava( runtime, rubyResult, method.getReturnType() );
return result;
}
catch( Exception e )
{
e.printStackTrace();
throw e;
}
} |
992007_1 | public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable
{
final FunctionResource groovySource = getFunctionResource( method );
if( groovySource != null )
{
if( groovySource.script )
{
return invokeAsObject( method, args, groovySource.url );
}
return invokeAsScript( method, args, groovySource.url );
}
throw new RuntimeException( "Internal error: Mixin invoked even if it does not apply" );
} |
992007_2 | public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable
{
Context cx = Context.enter();
try
{
Scriptable proxyScope = Context.toObject( proxy, instanceScope );
proxyScope.setPrototype( instanceScope );
proxyScope.put( "compositeBuilderFactory", proxyScope, factory );
proxyScope.put( "This", proxyScope, me );
Function fn = getFunction( cx, proxyScope, method );
Object result = fn.call( cx, instanceScope, proxyScope, args );
if( result instanceof Undefined )
{
return null;
}
else if( result instanceof Wrapper )
{
return ( (Wrapper) result ).unwrap();
}
else
{
return result;
}
}
finally
{
Context.exit();
}
} |
992007_3 | public Object invoke( Object proxy, Method method, Object[] args )
throws Throwable
{
Interpreter runtime;
synchronized( BeanShellMixin.class )
{
runtime = runtimes.get( module );
}
if( runtime == null )
{
runtime = new Interpreter();
BshClassManager.createClassManager( runtime );
Class compositeType = me.getClass().getInterfaces()[ 0 ];
NameSpace namespace = buildNamespace( compositeType, runtime );
runtime.setNameSpace( namespace );
synchronized( BeanShellMixin.class )
{
runtimes.put( module, runtime );
}
runtime.set( "compositeBuilderFactory", compositeBuilderFactory );
runtime.set( "unitOfWorkFactory", uowFactory );
}
if( mixins == null )
{
mixins = extractMixins( runtime.getClassManager() );
}
Object instance = mixins.get( method.getDeclaringClass() );
return method.invoke( instance, args );
} |
992007_4 | public EventRouter route( Specification<DomainEventValue> specification, Receiver<DomainEventValue, T> receiver )
{
routeEvent.put( specification, receiver );
return this;
} |
992007_5 | public static Iterable<DomainEventValue> events( Iterable<UnitOfWorkDomainEventsValue> transactions )
{
return Iterables.flattenIterables( Iterables.map( new Function<UnitOfWorkDomainEventsValue, Iterable<DomainEventValue>>()
{
@Override
public Iterable<DomainEventValue> map( UnitOfWorkDomainEventsValue unitOfWorkDomainEventsValue )
{
return unitOfWorkDomainEventsValue.events().get();
}
}, transactions ) );
} |
992007_6 | public EntityTypeSerializer()
{
// TODO A ton more types need to be added here
dataTypes.put( String.class.getName(), XMLSchema.STRING );
dataTypes.put( Integer.class.getName(), XMLSchema.INT );
dataTypes.put( Boolean.class.getName(), XMLSchema.BOOLEAN );
dataTypes.put( Byte.class.getName(), XMLSchema.BYTE );
dataTypes.put( BigDecimal.class.getName(), XMLSchema.DECIMAL );
dataTypes.put( Double.class.getName(), XMLSchema.DOUBLE );
dataTypes.put( Long.class.getName(), XMLSchema.LONG );
dataTypes.put( Short.class.getName(), XMLSchema.SHORT );
dataTypes.put( Date.class.getName(), XMLSchema.DATETIME );
} |
992007_7 | public static <S, T extends S> ParameterizedType findParameterizedType( Class<T> type, Class<S> searchType )
{
return ParameterizedTypes.findParameterizedType( (Type) type, searchType );
} |
992007_8 | public static <S, T extends S> Type[] findTypeVariables( Class<T> type, Class<S> searchType )
{
return ParameterizedTypes.findParameterizedType( type, searchType ).getActualTypeArguments();
} |
992012_0 | public final void initialize( String schemaUrl, String dataUrl, String dbUrl, Properties connectionProperties )
throws SQLException, IOException
{
Connection connection1 = getSqlConnection( dbUrl, connectionProperties );
runScript( schemaUrl, connection1 );
Connection connection2 = getSqlConnection( dbUrl, connectionProperties );
runScript( dataUrl, connection2 );
} |
992012_1 | public String convertIdentifier( final QualifiedName qualifiedIdentifier )
{
final String name = qualifiedIdentifier.name();
if( name.equalsIgnoreCase( "identity" ) )
{
return "ID";
}
return name.toUpperCase();
} |
992012_2 | public Object getValueFromData( final Map<String, Object> rawData, final QualifiedName qualifiedName )
{
String convertedIdentifier = convertIdentifier( qualifiedName );
if( rawData.containsKey( convertedIdentifier ) )
{
return rawData.remove( convertedIdentifier );
}
return null;
} |
992012_3 | public Object getValueFromData( final Map<String, Object> rawData, final QualifiedName qualifiedName )
{
String convertedIdentifier = convertIdentifier( qualifiedName );
if( rawData.containsKey( convertedIdentifier ) )
{
return rawData.remove( convertedIdentifier );
}
return null;
} |
992012_4 | public Map<String, Object> convertKeys( Map<QualifiedName, Object> rawData )
{
Map<String, Object> result = new HashMap<String, Object>( rawData.size() );
for( Map.Entry<QualifiedName, Object> entry : rawData.entrySet() )
{
final String convertedIdentifier = convertIdentifier( entry.getKey() );
if( result.containsKey( convertedIdentifier ) )
{
throw new IllegalArgumentException( format( "Duplicate Key: %s -> %s", entry.getKey(), convertedIdentifier ) );
}
result.put( convertedIdentifier, entry.getValue() );
}
return result;
} |
992012_5 | public Map<String, Object> convertKeys( Map<QualifiedName, Object> rawData )
{
Map<String, Object> result = new HashMap<String, Object>( rawData.size() );
for( Map.Entry<QualifiedName, Object> entry : rawData.entrySet() )
{
final String convertedIdentifier = convertIdentifier( entry.getKey() );
if( result.containsKey( convertedIdentifier ) )
{
throw new IllegalArgumentException( format( "Duplicate Key: %s -> %s", entry.getKey(), convertedIdentifier ) );
}
result.put( convertedIdentifier, entry.getValue() );
}
return result;
} |
992012_6 | public Map<String, Object> convertKeys( Map<QualifiedName, Object> rawData )
{
Map<String, Object> result = new HashMap<String, Object>( rawData.size() );
for( Map.Entry<QualifiedName, Object> entry : rawData.entrySet() )
{
final String convertedIdentifier = convertIdentifier( entry.getKey() );
if( result.containsKey( convertedIdentifier ) )
{
throw new IllegalArgumentException( format( "Duplicate Key: %s -> %s", entry.getKey(), convertedIdentifier ) );
}
result.put( convertedIdentifier, entry.getValue() );
}
return result;
} |
992971_0 | public Collection<Throwable> getCauseElements() {
return Collections.unmodifiableCollection(this.causes);
} |
993994_0 | public LoadedXml load(final String url, final int timeout) {
try {
final InputStream stream = loadAsStream(url, timeout);
final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
final Document document = builder.parse(stream);
return new LoadedXml(document);
} catch (SocketTimeoutException e) {
return LoadedXml.EMPTY_XML;
} catch (IOException e) {
log.error("Error while processing url: " + url, e); //ignored
} catch (ParserConfigurationException e) {
log.error("Error while processing url: " + url, e); //ignored
} catch (SAXException e) {
log.error("Error while processing url: " + url, e); //ignored
}
return LoadedXml.EMPTY_XML;
} |
993994_1 | public LoadedXml load(final String url, final int timeout) {
try {
final InputStream stream = loadAsStream(url, timeout);
final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
final Document document = builder.parse(stream);
return new LoadedXml(document);
} catch (SocketTimeoutException e) {
return LoadedXml.EMPTY_XML;
} catch (IOException e) {
log.error("Error while processing url: " + url, e); //ignored
} catch (ParserConfigurationException e) {
log.error("Error while processing url: " + url, e); //ignored
} catch (SAXException e) {
log.error("Error while processing url: " + url, e); //ignored
}
return LoadedXml.EMPTY_XML;
} |
993994_2 | public void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath) throws UnsupportedEncodingException, ServletException {
req.setCharacterEncoding(encoding);
res.setCharacterEncoding(encoding);
log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod());
final long startTime = System.currentTimeMillis();
final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath);
final InternalResponse internalResponse = yaletSupport.createResponse(res);
process(internalRequest, internalResponse, new RedirHandler(res));
log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms");
} |
993994_3 | public void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath) throws UnsupportedEncodingException, ServletException {
req.setCharacterEncoding(encoding);
res.setCharacterEncoding(encoding);
log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod());
final long startTime = System.currentTimeMillis();
final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath);
final InternalResponse internalResponse = yaletSupport.createResponse(res);
process(internalRequest, internalResponse, new RedirHandler(res));
log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms");
} |
993994_4 | public void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath) throws UnsupportedEncodingException, ServletException {
req.setCharacterEncoding(encoding);
res.setCharacterEncoding(encoding);
log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod());
final long startTime = System.currentTimeMillis();
final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath);
final InternalResponse internalResponse = yaletSupport.createResponse(res);
process(internalRequest, internalResponse, new RedirHandler(res));
log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms");
} |
993994_5 | public long addUser(final String login, final String fio, final String passwd, final String passwdAdd) throws UserCreationException {
final UserInfo user = getUser(login);
if (user != null) {
throw new UserCreationException(UserCreationException.Type.ALREADY_EXISTS);
}
try {
jdbcTemplate.update(
"insert into auth_user (login, fio, passwd_hash, passwd_add) " +
"values (?,?,?,?)",
login, fio, passwd, passwdAdd
);
return getLastInsertId();
} catch (Exception e) {
throw new UserCreationException(UserCreationException.Type.INTERNAL_ERROR);
}
} |
993994_6 | public UserInfo getUser(final long userId) {
final List<UserInfo> users = jdbcTemplate.query(
"select * from auth_user where user_id = ?", USER_INFO_MAPPER, userId);
if (users.isEmpty()) {
return null;
}
return users.get(0);
} |
993994_7 | public boolean checkUser(final long userId, final String passwd) {
return 0 < jdbcTemplate.queryForInt(
"select count(*) from auth_user where user_id = ? and passwd_hash = ?",
userId, passwd
);
} |
994088_0 | @Override
public void setCacheDir(File dir) {
// comment below as inmemory configuration does not require dir to be exists
// this is relevant when deploy app on readonly file system like heroku and gae
if (!dir.isDirectory() && !dir.mkdir())
throw new IllegalArgumentException("not a dir");
checkInitialize_(false);
cache_ = new FileCache(dir);
} |
1001284_0 | @Override protected boolean okToAdd(Object key, Object value) {
return key != null && value != null;
} |
1001284_1 | @Override protected boolean okToAdd(Object key, Object value) {
return key != null && value != null;
} |
1001284_2 | @Override protected boolean okToAdd(Object key, Object value) {
return key != null && value != null;
} |
1001284_3 | @Override protected boolean okToAdd(Object key, Object value) {
return key != null && value != null;
} |
1001284_4 | public static CodePoints forCharset(Charset c) {
if (ENCODABLES.containsKey(c))
return ENCODABLES.get(c);
CodePoints points = load(c);
ENCODABLES.put(c, points);
return points;
} |
1001284_5 | public int at(int index) {
if (index < 0)
throw new IndexOutOfBoundsException("illegal negative index: " + index);
int min = 0;
int max = ranges.size() - 1;
while (min <= max) {
int midpoint = min + ((max - min) / 2);
CodePointRange current = ranges.get(midpoint);
if (index >= current.previousCount && index < current.previousCount + current.size())
return current.low + index - current.previousCount;
else if (index < current.previousCount)
max = midpoint - 1;
else
min = midpoint + 1;
}
throw new IndexOutOfBoundsException(String.valueOf(index));
} |
1001284_6 | public int at(int index) {
if (index < 0)
throw new IndexOutOfBoundsException("illegal negative index: " + index);
int min = 0;
int max = ranges.size() - 1;
while (min <= max) {
int midpoint = min + ((max - min) / 2);
CodePointRange current = ranges.get(midpoint);
if (index >= current.previousCount && index < current.previousCount + current.size())
return current.low + index - current.previousCount;
else if (index < current.previousCount)
max = midpoint - 1;
else
min = midpoint + 1;
}
throw new IndexOutOfBoundsException(String.valueOf(index));
} |
1001284_7 | public int size() {
if (ranges.isEmpty())
return 0;
CodePointRange last = ranges.get(ranges.size() - 1);
return last.previousCount + last.size();
} |
1001284_8 | @Override public Void generate(SourceOfRandomness random, GenerationStatus status) {
return null;
} |
1001284_9 | public static <T, U> T makeLambda(
Class<T> lambdaType,
Generator<U> returnValueGenerator,
GenerationStatus status) {
if (singleAbstractMethodOf(lambdaType) == null) {
throw new IllegalArgumentException(
lambdaType + " is not a functional interface type");
}
return lambdaType.cast(
newProxyInstance(
lambdaType.getClassLoader(),
new Class<?>[] { lambdaType },
new LambdaInvocationHandler<>(
lambdaType,
returnValueGenerator,
status.attempts())));
} |
1006123_0 | public Wavelet fetchWavelet(WaveId waveId, WaveletId waveletId)
throws ClientWaveException {
return fetchWavelet(waveId, waveletId, null);
} |
1007836_0 | public int parse()
{
String expression = " if(" + _input + "){" +
"returnValue = VALUEA;" +
"}" +
" else { returnValue = VALUEB; }";
expression = expression.replaceAll("0", " false " );
expression = expression.replaceAll("1", " true " );
expression = expression.replaceAll("\\*", " && " );
expression = expression.replaceAll("\\+", " || " );
expression = expression.replace("VALUEA", " \"1\" " );
expression = expression.replace("VALUEB", " \"0\" " );
System.out.println(expression);
ScriptEngineManager manager
= new ScriptEngineManager();
ScriptEngine engine
= manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(expression);
}
catch (ScriptException e)
{
}
return result == null ? 0 :Integer.parseInt(result.toString());
} |
1007836_1 | public int parse()
{
String expression = " if(" + _input + "){" +
"returnValue = VALUEA;" +
"}" +
" else { returnValue = VALUEB; }";
expression = expression.replaceAll("0", " false " );
expression = expression.replaceAll("1", " true " );
expression = expression.replaceAll("\\*", " && " );
expression = expression.replaceAll("\\+", " || " );
expression = expression.replace("VALUEA", " \"1\" " );
expression = expression.replace("VALUEB", " \"0\" " );
System.out.println(expression);
ScriptEngineManager manager
= new ScriptEngineManager();
ScriptEngine engine
= manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(expression);
}
catch (ScriptException e)
{
}
return result == null ? 0 :Integer.parseInt(result.toString());
} |
1007836_2 | public int parse()
{
String expression = " if(" + _input + "){" +
"returnValue = VALUEA;" +
"}" +
" else { returnValue = VALUEB; }";
expression = expression.replaceAll("0", " false " );
expression = expression.replaceAll("1", " true " );
expression = expression.replaceAll("\\*", " && " );
expression = expression.replaceAll("\\+", " || " );
expression = expression.replace("VALUEA", " \"1\" " );
expression = expression.replace("VALUEB", " \"0\" " );
System.out.println(expression);
ScriptEngineManager manager
= new ScriptEngineManager();
ScriptEngine engine
= manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(expression);
}
catch (ScriptException e)
{
}
return result == null ? 0 :Integer.parseInt(result.toString());
} |
1007836_3 | public int parse()
{
String expression = " if(" + _input + "){" +
"returnValue = VALUEA;" +
"}" +
" else { returnValue = VALUEB; }";
expression = expression.replaceAll("0", " false " );
expression = expression.replaceAll("1", " true " );
expression = expression.replaceAll("\\*", " && " );
expression = expression.replaceAll("\\+", " || " );
expression = expression.replace("VALUEA", " \"1\" " );
expression = expression.replace("VALUEB", " \"0\" " );
System.out.println(expression);
ScriptEngineManager manager
= new ScriptEngineManager();
ScriptEngine engine
= manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(expression);
}
catch (ScriptException e)
{
}
return result == null ? 0 :Integer.parseInt(result.toString());
} |
1007836_4 | public int parse()
{
String expression = " if(" + _input + "){" +
"returnValue = VALUEA;" +
"}" +
" else { returnValue = VALUEB; }";
expression = expression.replaceAll("0", " false " );
expression = expression.replaceAll("1", " true " );
expression = expression.replaceAll("\\*", " && " );
expression = expression.replaceAll("\\+", " || " );
expression = expression.replace("VALUEA", " \"1\" " );
expression = expression.replace("VALUEB", " \"0\" " );
System.out.println(expression);
ScriptEngineManager manager
= new ScriptEngineManager();
ScriptEngine engine
= manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(expression);
}
catch (ScriptException e)
{
}
return result == null ? 0 :Integer.parseInt(result.toString());
} |
1007836_5 | public int parse()
{
String expression = " if(" + _input + "){" +
"returnValue = VALUEA;" +
"}" +
" else { returnValue = VALUEB; }";
expression = expression.replaceAll("0", " false " );
expression = expression.replaceAll("1", " true " );
expression = expression.replaceAll("\\*", " && " );
expression = expression.replaceAll("\\+", " || " );
expression = expression.replace("VALUEA", " \"1\" " );
expression = expression.replace("VALUEB", " \"0\" " );
System.out.println(expression);
ScriptEngineManager manager
= new ScriptEngineManager();
ScriptEngine engine
= manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(expression);
}
catch (ScriptException e)
{
}
return result == null ? 0 :Integer.parseInt(result.toString());
} |
1007836_6 | public int parse()
{
String expression = " if(" + _input + "){" +
"returnValue = VALUEA;" +
"}" +
" else { returnValue = VALUEB; }";
expression = expression.replaceAll("0", " false " );
expression = expression.replaceAll("1", " true " );
expression = expression.replaceAll("\\*", " && " );
expression = expression.replaceAll("\\+", " || " );
expression = expression.replace("VALUEA", " \"1\" " );
expression = expression.replace("VALUEB", " \"0\" " );
System.out.println(expression);
ScriptEngineManager manager
= new ScriptEngineManager();
ScriptEngine engine
= manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(expression);
}
catch (ScriptException e)
{
}
return result == null ? 0 :Integer.parseInt(result.toString());
} |
1007836_7 | public int parse()
{
String expression = " if(" + _input + "){" +
"returnValue = VALUEA;" +
"}" +
" else { returnValue = VALUEB; }";
expression = expression.replaceAll("0", " false " );
expression = expression.replaceAll("1", " true " );
expression = expression.replaceAll("\\*", " && " );
expression = expression.replaceAll("\\+", " || " );
expression = expression.replace("VALUEA", " \"1\" " );
expression = expression.replace("VALUEB", " \"0\" " );
System.out.println(expression);
ScriptEngineManager manager
= new ScriptEngineManager();
ScriptEngine engine
= manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(expression);
}
catch (ScriptException e)
{
}
return result == null ? 0 :Integer.parseInt(result.toString());
} |
1007836_8 | public int process()
{
_input = _input.replaceAll(" ", "");
_input = _input.replaceAll("!1", "0");
_input = _input.replaceAll("!0", "1");
Matcher m = p.matcher(_input);
if(m.find())
{
_input = _input.substring(1,_input.length()-1);
}
Matcher m1 = p1.matcher(_input);
Matcher m2 = p2.matcher(_input);
//start with 1+ or end with +1
//short circuit to 1
if(m1.find() || m2.find())
{
return 1;
}
Matcher m4 = p4.matcher(_input);
String foundInnerLogic;
String parsed;
while (m4.find())
{
foundInnerLogic = m4.group();
if(foundInnerLogic != null){
parsed = parseInnerLogic(foundInnerLogic);
String matched = foundInnerLogic;
/*
String matched = foundInnerLogic.replaceAll("\\*","\\\\\\*");
matched = matched.replaceAll("\\(","\\\\\\(");
matched = matched.replaceAll("\\)","\\\\\\)");
*/
_input = _input.replace(matched, parsed);
_input = _input.replace("!0", "1");
_input = _input.replace("!1", "0");
m4 = p4.matcher(_input);
}
}
_input = parseInnerLogic(_input);
return Integer.parseInt(_input);
} |
1007836_9 | public int process()
{
_input = _input.replaceAll(" ", "");
_input = _input.replaceAll("!1", "0");
_input = _input.replaceAll("!0", "1");
Matcher m = p.matcher(_input);
if(m.find())
{
_input = _input.substring(1,_input.length()-1);
}
Matcher m1 = p1.matcher(_input);
Matcher m2 = p2.matcher(_input);
//start with 1+ or end with +1
//short circuit to 1
if(m1.find() || m2.find())
{
return 1;
}
Matcher m4 = p4.matcher(_input);
String foundInnerLogic;
String parsed;
while (m4.find())
{
foundInnerLogic = m4.group();
if(foundInnerLogic != null){
parsed = parseInnerLogic(foundInnerLogic);
String matched = foundInnerLogic;
/*
String matched = foundInnerLogic.replaceAll("\\*","\\\\\\*");
matched = matched.replaceAll("\\(","\\\\\\(");
matched = matched.replaceAll("\\)","\\\\\\)");
*/
_input = _input.replace(matched, parsed);
_input = _input.replace("!0", "1");
_input = _input.replace("!1", "0");
m4 = p4.matcher(_input);
}
}
_input = parseInnerLogic(_input);
return Integer.parseInt(_input);
} |
1014623_0 | @Override
public String phoneticRhymePart(final String word)
{
String withoutPunctuation = removeTwitterChars(removeTrailingPunctuation(word));
// If it is a number, just translate its phonetic part
if (WordUtils.isNumber(withoutPunctuation))
{
withoutPunctuation = SpanishNumber.getBaseSound(withoutPunctuation);
}
String rhymePart = rhymePart(withoutPunctuation);
StringBuilder result = new StringBuilder();
char[] letters = rhymePart.toCharArray();
for (int i = 0; i < letters.length; i++)
{
switch (letters[i])
{
// Vocales
case 225: // a con acento
result.append('a');
break;
case 233: // e con acento
result.append('e');
break;
case 237: // i con acento
result.append('i');
break;
case 243: // o con acento
result.append('o');
break;
case 250: // u con acento
result.append('u');
break;
case 252: // u con dieresis
result.append('u');
break;
// Consonantes
case 'b':
result.append('v');
break;
case 'y':
result.append("ll");
break;
// h => añadirla solo si es una 'ch'
case 'h':
if (i > 0 && letters[i - 1] == 'c')
{
result.append('h');
}
break;
// g => transformarla en 'j' si va antes de 'e' o 'i'
case 'g':
if (i + 1 < letters.length && (letters[i + 1] == 'e' || letters[i + 1] == 'i'))
{
result.append('j');
}
else
{
result.append('g');
}
break;
// Otros
default:
result.append(letters[i]);
break;
}
}
return result.toString();
} |
1014623_1 | public static String capitalize(final String str)
{
if (str == null)
{
return null;
}
switch (str.length())
{
case 0:
return str;
case 1:
return str.toUpperCase();
default:
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
} |
1014623_2 | public static String getLastWord(final String sentence)
{
String word = "";
if (sentence != null)
{
List<String> words = Arrays.asList(sentence.split(" "));
if (words.size() > 0)
{
word = words.get(words.size() - 1);
}
}
return word;
} |
1014623_3 | public static boolean isNumber(String word)
{
if (word == null)
{
return false;
}
String wordToParse = new String(word);
if (wordToParse.startsWith("-"))
{
wordToParse = wordToParse.replaceFirst("-", "");
}
if (wordToParse.length() == 0)
{
return false;
}
for (char c : wordToParse.toCharArray())
{
if (!Character.isDigit(c))
{
return false;
}
}
return true;
} |
1014623_4 | static String getConfigValue(final String propertyName)
{
return getConfiguration().getProperty(propertyName);
} |
1014623_5 | static String getRequiredConfigValue(final String propertyName)
{
String value = getConfiguration().getProperty(propertyName);
if (value == null)
{
throw new ConfigurationException("Te requested property [" + propertyName
+ "] was not set.");
}
return value;
} |
1014623_6 | static String getRequiredConfigValue(final String propertyName)
{
String value = getConfiguration().getProperty(propertyName);
if (value == null)
{
throw new ConfigurationException("Te requested property [" + propertyName
+ "] was not set.");
}
return value;
} |
1014623_7 | public Set<String> findAll() throws IOException
{
Set<String> rhymes = new HashSet<String>();
connect();
try
{
String lastId = getLastId(sentencens);
if (lastId != null)
{
Integer n = Integer.parseInt(getLastId(sentencens));
for (int i = 1; i <= n; i++)
{
String id = sentencens.build(String.valueOf(i)).toString();
if (redis.exists(id) == 1)
{
rhymes.add(URLDecoder.decode(redis.get(id), encoding.displayName()));
}
}
}
}
finally
{
disconnect();
}
return rhymes;
} |
1014623_8 | public String getRhyme(final String sentence) throws IOException
{
String lastWord = WordUtils.getLastWord(sentence);
String rhymepart = wordParser.phoneticRhymePart(lastWord);
StressType type = wordParser.stressType(lastWord);
LOGGER.debug("Finding rhymes for {}", sentence);
Set<String> rhymes = Sets.newHashSet();
connect();
try
{
rhymes.addAll(search(rhymepart, type));
}
finally
{
disconnect();
}
if (rhymes.isEmpty())
{
// If no rhyme is found, return null
return null;
}
else
{
// Otherwise, return a random rhyme
List<String> rhymeList = new ArrayList<String>(rhymes);
Random random = new Random(System.currentTimeMillis());
int index = random.nextInt(rhymeList.size());
return rhymeList.get(index);
}
} |
1014623_9 | public void delete(final String sentence) throws IOException
{
String word = WordUtils.getLastWord(sentence);
if (word.isEmpty())
{
return;
}
String rhyme = normalizeString(wordParser.phoneticRhymePart(word));
StressType type = wordParser.stressType(word);
connect();
try
{
String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence));
if (redis.exists(sentenceKey) == 0)
{
throw new IOException("The element to remove does not exist.");
}
String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type));
String sentenceId = redis.get(sentenceKey);
sentenceId = sentencens.build(sentenceId).toString();
// Remove the index
if (redis.exists(indexKey) == 1)
{
String indexId = redis.get(indexKey);
indexId = indexns.build(indexId).toString();
// Remove the sentence from the index
if (redis.exists(indexId) == 1)
{
redis.srem(indexId, sentenceId);
}
// Remove the index if empty
if (redis.smembers(indexId).isEmpty())
{
redis.del(indexId, indexKey);
}
}
// Remove the key
redis.del(sentenceId, sentenceKey);
LOGGER.info("Deleted rhyme: {}", sentence);
}
finally
{
disconnect();
}
} |
1017889_0 | public boolean containsAncestor(Path path) {
for (Path p : this) {
if (p.isAncestorOf(path)) {
return true;
}
}
return false;
} |
1017889_1 | public boolean containsParent(Path path) {
for (Path p : this) {
if (p.isParentOf(path)) {
return true;
}
}
return false;
} |
1017889_2 | public void removeDescendants(Path path) {
Iterator<Path> i = iterator();
while (i.hasNext()) {
Path p = i.next();
if (p.isDescendantOf(path)) {
i.remove();
}
}
} |
1017889_3 | public boolean removeWithDescendants(Path path) {
boolean ret = remove(path);
removeDescendants(path);
return ret;
} |
1017889_4 | public Path append(Path relative) {
if (relative == null) {
throw new IllegalArgumentException("Argument 'relative' cannot be null");
}
if (relative.isAbsolute()) {
throw new IllegalArgumentException("Cannot append an absolute path");
}
StringBuilder appended = new StringBuilder(path.length() + 1 + relative.path.length());
appended.append(path);
if (!path.endsWith(SEPARATOR)) {
appended.append("/");
}
appended.append(relative.path);
return new Path(appended.toString());
} |
1017889_5 | @Override
public String toString() {
return path;
} |
1017889_6 | public String getName() {
if (path.equals(SEPARATOR)) {
return path;
} else {
int last = path.lastIndexOf(SEPARATOR);
return path.substring(last + 1);
}
} |
1017889_7 | public boolean isAbsolute() {
return path.startsWith("/");
} |
1017889_8 | public boolean isCanonical() {
int offset = 0;
// whether a text segment (not "..") has been found
boolean text = false;
// until empty paths are supported
if (path.equals(".")) {
return true;
}
if (!isRoot() && path.endsWith("/")) {
return false;
}
while (offset < path.length()) {
String sub = path.substring(offset);
if (sub.equals("/") || sub.equals("")) {
break;
}
if (sub.startsWith("./") || sub.equals(".")) {
return false;
}
boolean up = sub.startsWith("../") || sub.equals("..");
if (text && up) {
return false;
}
if (up == false) {
text = true;
}
int next = sub.indexOf("/");
if (next == -1) {
break;
} else if (next == 0 && offset != 0) {
// situation when there are // in the middle of string
return false;
} else {
offset += next + 1;
}
}
return true;
} |
1017889_9 | public boolean isChildOf(Path other) {
return isDescendantOf(other) && size() == other.size() + 1;
} |
1020601_0 | @Override
public Object get(Map<String, Object> source, String memberName) {
return source.get(memberName);
} |
1020601_1 | public Boolean convert(MappingContext<Object, Boolean> context) {
Object source = context.getSource();
if (source == null)
return null;
String stringValue = source.toString().toLowerCase();
if (stringValue.length() == 0)
return null;
for (int i = 0; i < TRUE_STRINGS.length; i++)
if (TRUE_STRINGS[i].equals(stringValue))
return Boolean.TRUE;
for (int i = 0; i < FALSE_STRINGSS.length; i++)
if (FALSE_STRINGSS[i].equals(stringValue))
return Boolean.FALSE;
throw new Errors().errorMapping(context.getSource(), context.getDestinationType())
.toMappingException();
} |
1020601_2 | public Number convert(MappingContext<Object, Number> context) {
Object source = context.getSource();
if (source == null)
return null;
Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType());
if (source instanceof Number)
return numberFor((Number) source, destinationType);
if (source instanceof Boolean)
return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType);
if (source instanceof Date && Long.class.equals(destinationType))
return Long.valueOf(((Date) source).getTime());
if (source instanceof Calendar && Long.class.equals(destinationType))
return Long.valueOf(((Calendar) source).getTime().getTime());
if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType))
return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis();
return numberFor(source.toString(), destinationType);
} |
1020601_3 | public Number convert(MappingContext<Object, Number> context) {
Object source = context.getSource();
if (source == null)
return null;
Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType());
if (source instanceof Number)
return numberFor((Number) source, destinationType);
if (source instanceof Boolean)
return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType);
if (source instanceof Date && Long.class.equals(destinationType))
return Long.valueOf(((Date) source).getTime());
if (source instanceof Calendar && Long.class.equals(destinationType))
return Long.valueOf(((Calendar) source).getTime().getTime());
if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType))
return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis();
return numberFor(source.toString(), destinationType);
} |
1020601_4 | public Number convert(MappingContext<Object, Number> context) {
Object source = context.getSource();
if (source == null)
return null;
Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType());
if (source instanceof Number)
return numberFor((Number) source, destinationType);
if (source instanceof Boolean)
return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType);
if (source instanceof Date && Long.class.equals(destinationType))
return Long.valueOf(((Date) source).getTime());
if (source instanceof Calendar && Long.class.equals(destinationType))
return Long.valueOf(((Calendar) source).getTime().getTime());
if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType))
return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis();
return numberFor(source.toString(), destinationType);
} |
1020601_5 | public Number convert(MappingContext<Object, Number> context) {
Object source = context.getSource();
if (source == null)
return null;
Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType());
if (source instanceof Number)
return numberFor((Number) source, destinationType);
if (source instanceof Boolean)
return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType);
if (source instanceof Date && Long.class.equals(destinationType))
return Long.valueOf(((Date) source).getTime());
if (source instanceof Calendar && Long.class.equals(destinationType))
return Long.valueOf(((Calendar) source).getTime().getTime());
if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType))
return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis();
return numberFor(source.toString(), destinationType);
} |
1020601_6 | public Number convert(MappingContext<Object, Number> context) {
Object source = context.getSource();
if (source == null)
return null;
Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType());
if (source instanceof Number)
return numberFor((Number) source, destinationType);
if (source instanceof Boolean)
return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType);
if (source instanceof Date && Long.class.equals(destinationType))
return Long.valueOf(((Date) source).getTime());
if (source instanceof Calendar && Long.class.equals(destinationType))
return Long.valueOf(((Calendar) source).getTime().getTime());
if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType))
return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis();
return numberFor(source.toString(), destinationType);
} |
1020601_7 | public Number convert(MappingContext<Object, Number> context) {
Object source = context.getSource();
if (source == null)
return null;
Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType());
if (source instanceof Number)
return numberFor((Number) source, destinationType);
if (source instanceof Boolean)
return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType);
if (source instanceof Date && Long.class.equals(destinationType))
return Long.valueOf(((Date) source).getTime());
if (source instanceof Calendar && Long.class.equals(destinationType))
return Long.valueOf(((Calendar) source).getTime().getTime());
if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType))
return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis();
return numberFor(source.toString(), destinationType);
} |
1020601_8 | public Number convert(MappingContext<Object, Number> context) {
Object source = context.getSource();
if (source == null)
return null;
Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType());
if (source instanceof Number)
return numberFor((Number) source, destinationType);
if (source instanceof Boolean)
return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType);
if (source instanceof Date && Long.class.equals(destinationType))
return Long.valueOf(((Date) source).getTime());
if (source instanceof Calendar && Long.class.equals(destinationType))
return Long.valueOf(((Calendar) source).getTime().getTime());
if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType))
return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis();
return numberFor(source.toString(), destinationType);
} |
1020601_9 | public Number convert(MappingContext<Object, Number> context) {
Object source = context.getSource();
if (source == null)
return null;
Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType());
if (source instanceof Number)
return numberFor((Number) source, destinationType);
if (source instanceof Boolean)
return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType);
if (source instanceof Date && Long.class.equals(destinationType))
return Long.valueOf(((Date) source).getTime());
if (source instanceof Calendar && Long.class.equals(destinationType))
return Long.valueOf(((Calendar) source).getTime().getTime());
if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType))
return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis();
return numberFor(source.toString(), destinationType);
} |
1024699_0 | public static void checkUrlIsValid(String url) throws IllegalArgumentException {
logger.debug("Url is : {}",url);
boolean urlIsValid;
Pattern p = Pattern.compile(URL_PATTERN);
Matcher m = p.matcher(url);
if (!m.matches()) {
// not an url ? maybe an ip address
p = Pattern.compile(IP_ADDRESS_PATTERN);
m = p.matcher(url);
urlIsValid = m.matches();
}else{
urlIsValid = true;
}
if(!urlIsValid){
throw new IllegalArgumentException("Url is not valid");
}
//nothing is better than testing for real
URI.create(url);
logger.debug("urlIsValid : {}",urlIsValid);
} |
1024699_1 | public static void checkUrlIsValid(String url) throws IllegalArgumentException {
logger.debug("Url is : {}",url);
boolean urlIsValid;
Pattern p = Pattern.compile(URL_PATTERN);
Matcher m = p.matcher(url);
if (!m.matches()) {
// not an url ? maybe an ip address
p = Pattern.compile(IP_ADDRESS_PATTERN);
m = p.matcher(url);
urlIsValid = m.matches();
}else{
urlIsValid = true;
}
if(!urlIsValid){
throw new IllegalArgumentException("Url is not valid");
}
//nothing is better than testing for real
URI.create(url);
logger.debug("urlIsValid : {}",urlIsValid);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.