idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
120,500
private void concatenateExtendsRecursive ( String selector , boolean isReference , String allSelector ) { List < String [ ] > list = exact . get ( selector ) ; if ( list != null ) { for ( String [ ] lessExtend : list ) { for ( String sel : lessExtend ) { boolean needRecursion = selectorList . add ( sel ) ; if ( needRec...
Add to the given selector all possible extends to the internal selectorList . This method is call recursive .
120,501
static String addLessExtendsTo ( FormattableContainer container , LessObject obj , String extendSelector ) { String baseSelectors = null ; do { int idx1 = extendSelector . indexOf ( ":extend(" ) ; int idx2 = extendSelector . indexOf ( ')' , idx1 ) ; int idx3 = extendSelector . lastIndexOf ( ',' , idx1 ) ; String select...
Parse the extendSelector create the needed LessExtend objects and add it to the container .
120,502
String stringValue ( CssFormatter formatter ) { String str ; try { formatter . addOutput ( ) ; appendTo ( formatter ) ; } catch ( Exception ex ) { throw createException ( ex ) ; } finally { str = formatter . releaseOutput ( ) ; } return str ; }
Get the string value
120,503
public Operation listValue ( CssFormatter formatter ) { Expression expr = unpack ( formatter ) ; if ( expr == this ) { throw createException ( "Exprestion is not a list: " + this ) ; } return expr . listValue ( formatter ) ; }
Get the value as a list
120,504
Expression unpack ( CssFormatter formatter ) { Expression unpack = this ; do { if ( unpack . getClass ( ) == FunctionExpression . class && ( ( FunctionExpression ) unpack ) . toString ( ) . isEmpty ( ) ) { unpack = ( ( FunctionExpression ) unpack ) . get ( 0 ) ; continue ; } if ( unpack . getClass ( ) == VariableExpres...
Unpack this expression to return the core expression
120,505
static double getColor ( Expression param , CssFormatter formatter ) throws LessException { switch ( param . getDataType ( formatter ) ) { case Expression . COLOR : case Expression . RGBA : return param . doubleValue ( formatter ) ; } throw new LessException ( "Not a color: " + param ) ; }
Get the color value of the expression or fire an exception if not a color .
120,506
static void dataUri ( CssFormatter formatter , String relativeUrlStr , final String urlString , String type ) throws IOException { String urlStr = removeQuote ( urlString ) ; InputStream input ; try { input = formatter . getReaderFactory ( ) . openStream ( formatter . getBaseURL ( ) , urlStr , relativeUrlStr ) ; } catc...
Implementation of the function data - uri .
120,507
static void dataUri ( CssFormatter formatter , byte [ ] bytes , String urlStr , String type ) { if ( type == null ) { switch ( urlStr . substring ( urlStr . lastIndexOf ( '.' ) + 1 ) ) { case "gif" : type = "image/gif;base64" ; break ; case "png" : type = "image/png;base64" ; break ; case "jpg" : case "jpeg" : type = "...
Write the bytes as inline url .
120,508
private static void appendEncode ( CssFormatter formatter , byte [ ] bytes ) { for ( byte b : bytes ) { if ( ( b >= 'a' && b <= 'z' ) || ( b >= 'A' && b <= 'Z' ) || ( b >= '0' && b <= '9' ) ) { formatter . append ( ( char ) b ) ; } else { switch ( b ) { case '-' : case '_' : case '*' : case '.' : formatter . append ( (...
Append the bytes URL encoded .
120,509
public InputStream openStream ( URL baseURL , String urlStr , String relativeUrlStr ) throws IOException { URL url = new URL ( baseURL , urlStr ) ; try { return openStream ( url ) ; } catch ( Exception e ) { url = new URL ( new URL ( baseURL , relativeUrlStr ) , urlStr ) ; return openStream ( url ) ; } }
Open an InputStream for the given URL . This is used for inlining images via data - uri .
120,510
public Reader create ( URL url ) throws IOException { return new InputStreamReader ( openStream ( url ) , StandardCharsets . UTF_8 ) ; }
Create a Reader for the given URL .
120,511
private void eval ( CssFormatter formatter ) { if ( type != UNKNOWN ) { return ; } try { ScriptEngineManager factory = new ScriptEngineManager ( getClass ( ) . getClassLoader ( ) ) ; ScriptEngine engine = factory . getEngineByName ( "JavaScript" ) ; engine . setContext ( new JavaScriptContext ( formatter , this ) ) ; S...
Execute the JavaScript
120,512
private void evalParam ( int idx , CssFormatter formatter ) { Expression expr = get ( idx ) ; type = expr . getDataType ( formatter ) ; switch ( type ) { case BOOLEAN : booleanValue = expr . booleanValue ( formatter ) ; break ; case STRING : break ; default : doubleValue = expr . doubleValue ( formatter ) ; } }
Evaluate a parameter as this function .
120,513
private void format ( CssFormatter formatter ) { String fmt = get ( 0 ) . stringValue ( formatter ) ; int idx = 1 ; for ( int i = 0 ; i < fmt . length ( ) ; i ++ ) { char ch = fmt . charAt ( i ) ; if ( ch == '%' ) { ch = fmt . charAt ( ++ i ) ; switch ( ch ) { case '%' : formatter . append ( ch ) ; break ; case 'a' : c...
Implements the format function %
120,514
Expression get ( int idx ) { if ( parameters . size ( ) <= idx ) { throw new ParameterOutOfBoundsException ( ) ; } return parameters . get ( idx ) ; }
Get the idx parameter from the parameter list .
120,515
private int getColorDigit ( int idx , CssFormatter formatter ) { Expression expression = get ( idx ) ; double d = expression . doubleValue ( formatter ) ; if ( expression . getDataType ( formatter ) == PERCENT ) { d *= 2.55 ; } return colorDigit ( d ) ; }
Get the idx parameter from the parameter list as color digit .
120,516
private double getColor ( Expression exp , CssFormatter formatter ) { type = exp . getDataType ( formatter ) ; switch ( type ) { case COLOR : case RGBA : return exp . doubleValue ( formatter ) ; } throw new ParameterOutOfBoundsException ( ) ; }
Get a color value from the expression . And set the type variable .
120,517
double getRadians ( CssFormatter formatter ) { final Expression exp = get ( 0 ) ; String unit = exp . unit ( formatter ) ; return exp . doubleValue ( formatter ) * Operation . unitFactor ( unit , "rad" , false ) ; }
Get the value in radians .
120,518
private double getDouble ( int idx , double defaultValue , CssFormatter formatter ) { if ( parameters . size ( ) <= idx ) { return defaultValue ; } return parameters . get ( idx ) . doubleValue ( formatter ) ; }
Get the idx parameter from the parameter list as double .
120,519
private List < Expression > getParamList ( CssFormatter formatter ) { Expression ex0 = get ( 0 ) . unpack ( formatter ) ; if ( ex0 . getDataType ( formatter ) == LIST ) { Operation op = ex0 . listValue ( formatter ) ; List < Expression > operants = op . getOperands ( ) ; if ( operants . size ( ) == 1 ) { Expression ex0...
Get for extract and length the first parameter as parameter list .
120,520
private Expression extract ( CssFormatter formatter ) { List < Expression > exList = getParamList ( formatter ) ; int idx = getInt ( 1 , formatter ) ; if ( idx <= 0 || exList . size ( ) < idx ) { type = STRING ; return null ; } Expression ex = exList . get ( idx - 1 ) ; type = ex . getDataType ( formatter ) ; switch ( ...
Function extract . Change the type and doubleValue
120,521
private Operation range ( CssFormatter formatter ) { type = LIST ; double start = get ( 0 ) . doubleValue ( formatter ) ; double end ; if ( parameters . size ( ) >= 2 ) { end = get ( 1 ) . doubleValue ( formatter ) ; } else { end = start ; start = 1 ; } double step ; if ( parameters . size ( ) >= 3 ) { step = get ( 2 )...
Function range . Generate a list spanning a range of values
120,522
void startBlock ( String [ ] selectors , StringBuilder output ) { this . results . add ( new CssRuleOutput ( selectors , output , isReference ) ) ; }
Start a block inside the media
120,523
static String fastReplace ( String str , String target , String replacement ) { int targetLength = target . length ( ) ; if ( targetLength == 0 ) { return str ; } int idx2 = str . indexOf ( target ) ; if ( idx2 < 0 ) { return str ; } StringBuilder buffer = new StringBuilder ( targetLength > replacement . length ( ) ? s...
Fast string replace which work without regular expressions
120,524
static String replacePlaceHolder ( CssFormatter formatter , String str , LessObject caller ) { int pos = str . startsWith ( "@{" ) ? 0 : str . indexOf ( "@" , 1 ) ; if ( pos >= 0 ) { formatter . addOutput ( ) ; SelectorUtils . appendToWithPlaceHolder ( formatter , str , pos , false , caller ) ; return formatter . relea...
Replace the possible variable place holder .
120,525
void parse ( URL baseURL , Reader input , ReaderFactory readerFactory ) throws MalformedURLException , LessException { this . baseURL = baseURL ; this . readerFactory = readerFactory ; this . relativeURL = new URL ( "file" , null , "" ) ; this . reader = new LessLookAheadReader ( input , null , false , false ) ; parse ...
Main method for parsing of main less file .
120,526
void parseLazy ( CssFormatter formatter ) { if ( lazyImports != null ) { HashMap < String , Expression > vars = variables ; formatter . addVariables ( vars ) ; for ( int i = 0 ; i < lazyImports . size ( ) ; i ++ ) { LazyImport lazyImport = lazyImports . get ( i ) ; String filename = lazyImport . stringValue ( formatter...
If there are some imports with variables then this will parse after a formatter if available .
120,527
private void parse ( FormattableContainer currentRule ) { try { for ( ; ; ) { int ch = reader . nextBlockMarker ( ) ; switch ( ch ) { case - 1 : return ; case ';' : parseSemicolon ( currentRule ) ; break ; case '{' : parseBlock ( currentRule ) ; break ; default : throw createException ( "Unrecognized input: '" + reader...
Parse main and import less files .
120,528
private void parseSemicolon ( FormattableContainer currentRule ) { String selector = null ; Operation params = null ; StringBuilder builder = cachesBuilder ; LOOP : for ( ; ; ) { char ch ; try { ch = read ( ) ; } catch ( Exception e ) { ch = ';' ; } switch ( ch ) { case ':' : if ( isMixin ( builder ) ) { builder . appe...
Parse an expression which ends with a semicolon . This can be a property assignment variable assignment a directive or other .
120,529
private Rule rule ( FormattableContainer parent , String selector , Operation params , Expression guard ) { Rule rule = new Rule ( reader , parent , selector , params , guard ) ; parseRule ( rule ) ; return rule ; }
Create a rule and parse the content of an block .
120,530
private void parseRule ( Rule rule ) { ruleStack . add ( rule ) ; for ( ; ; ) { int ch = reader . nextBlockMarker ( ) ; switch ( ch ) { case - 1 : throw createException ( "Unexpected end of Less data" ) ; case ';' : parseSemicolon ( rule ) ; break ; case '{' : parseBlock ( rule ) ; break ; case '}' : parseSemicolon ( r...
Parse the content of an block .
120,531
private String readQuote ( char quote ) { StringBuilder builder = cachesBuilder ; builder . setLength ( 0 ) ; readQuote ( quote , builder ) ; String str = builder . toString ( ) ; builder . setLength ( 0 ) ; return str ; }
Read a quoted string .
120,532
private void readQuote ( char quote , StringBuilder builder ) { builder . append ( quote ) ; boolean isBackslash = false ; for ( ; ; ) { char ch = read ( ) ; builder . append ( ch ) ; if ( ch == quote && ! isBackslash ) { return ; } isBackslash = ch == '\\' ; } }
Read a quoted string and append it to the builder .
120,533
private Operation parseUrlParam ( ) { StringBuilder builder = cachesBuilder ; builder . setLength ( 0 ) ; Operation op = new Operation ( reader , new ValueExpression ( reader , relativeURL . getPath ( ) ) , ';' ) ; for ( ; ; ) { char ch = read ( ) ; switch ( ch ) { case '"' : case '\'' : String val = builder . toString...
Parse the parameter of an url function which has some curious fallbacks .
120,534
private Expression concat ( Expression left , char operator , Expression right ) { if ( left == null ) { return right ; } Operation op ; if ( left . getClass ( ) == Operation . class && ( ( Operation ) left ) . getOperator ( ) == operator ) { op = ( Operation ) left ; } else if ( right != null && right . getClass ( ) =...
Concatenate 2 expressions to one expression .
120,535
private Expression buildExpression ( String str ) { switch ( str . charAt ( 0 ) ) { case '@' : return new VariableExpression ( reader , str ) ; case '-' : if ( str . startsWith ( "-@" ) ) { return new FunctionExpression ( reader , "-" , new Operation ( reader , buildExpression ( str . substring ( 1 ) ) , ( char ) 0 ) )...
Create an expression from the given atomic string .
120,536
private static String trim ( StringBuilder builder ) { String str = builder . toString ( ) . trim ( ) ; builder . setLength ( 0 ) ; return str ; }
Get a trim string from the builder and clear the builder .
120,537
private static boolean isWhitespace ( StringBuilder builder ) { for ( int i = 0 ; i < builder . length ( ) ; i ++ ) { if ( ! Character . isWhitespace ( builder . charAt ( i ) ) ) { return false ; } } return true ; }
If the builder is empty or contains only whitespaces
120,538
private static boolean isSelector ( StringBuilder builder ) { int length = builder . length ( ) ; if ( length == 0 ) { return false ; } switch ( builder . charAt ( 0 ) ) { case '.' : case '#' : break ; default : return true ; } for ( int i = 1 ; i < length ; i ++ ) { char ch = builder . charAt ( i ) ; switch ( ch ) { c...
If the builder contains a selector and not a mixin .
120,539
private static boolean isVariableName ( StringBuilder builder ) { for ( int i = 1 ; i < builder . length ( ) ; ) { char ch = builder . charAt ( i ++ ) ; switch ( ch ) { case '(' : case '\"' : return false ; } } return true ; }
If the builder contains a valid variable name
120,540
private static char firstNonWhitespace ( StringBuilder builder ) { for ( int i = 0 ; i < builder . length ( ) ; i ++ ) { if ( ! Character . isWhitespace ( builder . charAt ( i ) ) ) { return builder . charAt ( i ) ; } } return ' ' ; }
The first character in the builder that is not a whitespace . Else there are only whitespaces
120,541
private void throwUnrecognizedInputIfAny ( StringBuilder builder , int ch ) { if ( ! isWhitespace ( builder ) ) { throw createException ( "Unrecognized input: '" + trim ( builder ) + ( char ) ch + "'" ) ; } builder . setLength ( 0 ) ; }
Throw an unrecognized input exception if there content in the StringBuilder .
120,542
public static boolean isRserveInstalled ( String Rcmd ) { Process p = doInR ( "is.element(set=installed.packages(lib.loc='" + RserveDaemon . app_dir ( ) + "'),el='Rserve')" , Rcmd , "--vanilla --silent" , false ) ; if ( p == null ) { Log . Err . println ( "Failed to ask if Rserve is installed" ) ; return false ; } try ...
R batch to check Rserve is installed
120,543
public static void main ( String [ ] args ) { File dir = null ; System . out . println ( "checkLocalRserve: " + checkLocalRserve ( ) ) ; try { RConnection c = new RConnection ( ) ; dir = new File ( c . eval ( "getwd()" ) . asString ( ) ) ; System . err . println ( "wd: " + dir ) ; c . eval ( "download.file('https://www...
just a demo main method which starts Rserve and shuts it down again
120,544
public static boolean isPortAvailable ( int p ) { try { ServerSocket test = new ServerSocket ( p ) ; test . close ( ) ; } catch ( BindException e ) { return false ; } catch ( IOException e ) { return false ; } return true ; }
used for windows multi - session emulation . Incremented at each new Rscript instance .
120,545
public static RserverConf newLocalInstance ( Properties p ) { RserverConf server = null ; if ( RserveDaemon . isWindows ( ) || ! UNIX_OPTIMIZE ) { while ( ! isPortAvailable ( RserverPort ) ) { RserverPort ++ ; } server = new RserverConf ( null , RserverPort , null , null , p ) ; } else { server = new RserverConf ( null...
if we want to re - use older sessions . May wrongly fil if older session is already stucked ...
120,546
public static List < String > parse ( String expr ) { List < String > expressions = new ArrayList < > ( ) ; int parenthesis = 0 ; int brackets = 0 ; int brackets2 = 0 ; String [ ] lines = expr . split ( "\n" ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String line : lines ) { line = line . trim ( ) ; if ( line ...
Parse an expression containing multiple lines functions or sub - expressions in a list of inline sub - expressions . This function also cleanup comments .
120,547
public void bindExternalFunction ( String funcName , ExternalFunction func ) throws Exception { ifAsyncWeCant ( "bind an external function" ) ; Assert ( ! externals . containsKey ( funcName ) , "Function '" + funcName + "' has already been bound." ) ; externals . put ( funcName , func ) ; }
Most general form of function binding that returns an Object and takes an array of Object parameters . The only way to bind a function with more than 3 arguments .
120,548
public void chooseChoiceIndex ( int choiceIdx ) throws Exception { List < Choice > choices = getCurrentChoices ( ) ; Assert ( choiceIdx >= 0 && choiceIdx < choices . size ( ) , "choice out of range" ) ; Choice choiceToChoose = choices . get ( choiceIdx ) ; state . getCallStack ( ) . setCurrentThread ( choiceToChoose . ...
Chooses the Choice from the currentChoices list with the given index . Internally this sets the current content path to that pointed to by the Choice ready to continue story evaluation .
120,549
void error ( String message , boolean useEndLineNumber ) throws Exception { StoryException e = new StoryException ( message ) ; e . useEndLineNumber = useEndLineNumber ; throw e ; }
then exits the flow .
120,550
public void observeVariable ( String variableName , VariableObserver observer ) throws StoryException , Exception { ifAsyncWeCant ( "observe a new variable" ) ; if ( variableObservers == null ) variableObservers = new HashMap < String , List < VariableObserver > > ( ) ; if ( ! state . getVariablesState ( ) . globalVari...
When the named global variable changes it s value the observer will be called to notify it of the change . Note that if the value changes multiple times within the ink the observer will only be called once at the end of the ink s evaluation . If during the evaluation it changes and then changes back again to its origin...
120,551
public void observeVariables ( List < String > variableNames , VariableObserver observer ) throws StoryException , Exception { for ( String varName : variableNames ) { observeVariable ( varName , observer ) ; } }
Convenience function to allow multiple variables to be observed with the same observer delegate function . See the singular ObserveVariable for details . The observer will get one call for every variable that has changed .
120,552
public String toJsonString ( ) throws Exception { List < ? > rootContainerJsonList = ( List < ? > ) Json . runtimeObjectToJToken ( mainContentContainer ) ; HashMap < String , Object > rootObject = new HashMap < String , Object > ( ) ; rootObject . put ( "inkVersion" , inkVersionCurrent ) ; rootObject . put ( "root" , r...
The Story itself in JSON representation .
120,553
public void unbindExternalFunction ( String funcName ) throws Exception { ifAsyncWeCant ( "unbind an external a function" ) ; Assert ( externals . containsKey ( funcName ) , "Function '" + funcName + "' has not been bound." ) ; externals . remove ( funcName ) ; }
Remove a binding for a named EXTERNAL ink function .
120,554
void visitContainer ( Container container , boolean atStart ) { if ( ! container . getCountingAtStartOnly ( ) || atStart ) { if ( container . getVisitsShouldBeCounted ( ) ) incrementVisitCountForContainer ( container ) ; if ( container . getTurnIndexShouldBeCounted ( ) ) recordTurnIndexVisitToContainer ( container ) ; ...
Mark a container as having been visited
120,555
public Object evaluateFunction ( String functionName , Object [ ] arguments ) throws Exception { return evaluateFunction ( functionName , null , arguments ) ; }
Evaluates a function defined in ink .
120,556
public Object evaluateFunction ( String functionName , StringBuilder textOutput , Object [ ] arguments ) throws Exception { ifAsyncWeCant ( "evaluate a function" ) ; if ( functionName == null ) { throw new Exception ( "Function is null" ) ; } else if ( functionName . trim ( ) . isEmpty ( ) ) { throw new Exception ( "Fu...
Evaluates a function defined in ink and gathers the possibly multi - line text as generated by the function .
120,557
public long getElapsedTicks ( ) { long elapsed ; if ( running ) { elapsed = ( System . nanoTime ( ) - startTime ) ; } else { elapsed = ( stopTime - startTime ) ; } return elapsed / nsPerTick ; }
Gets the total elapsed time measured by the current instance in nanoseconds . 1 Tick = 100 nanoseconds
120,558
public HashMap < String , Object > getJsonToken ( ) throws Exception { HashMap < String , Object > jRTObject = new HashMap < String , Object > ( ) ; ArrayList < Object > jThreads = new ArrayList < Object > ( ) ; for ( CallStack . Thread thread : threads ) { jThreads . add ( thread . jsonToken ( ) ) ; } jRTObject . put ...
See above for why we can t implement jsonToken
120,559
public RTObject getTemporaryVariableWithName ( String name , int contextIndex ) { if ( contextIndex == - 1 ) contextIndex = getCurrentElementIndex ( ) + 1 ; Element contextElement = getCallStack ( ) . get ( contextIndex - 1 ) ; RTObject varValue = contextElement . temporaryVariables . get ( name ) ; return varValue ; }
Get variable value dereferencing a variable pointer if necessary
120,560
@ SuppressWarnings ( "unchecked" ) public void setJsonToken ( HashMap < String , Object > jRTObject , Story storyContext ) throws Exception { threads . clear ( ) ; List < Object > jThreads = ( List < Object > ) jRTObject . get ( "threads" ) ; for ( Object jThreadTok : jThreads ) { HashMap < String , Object > jThreadObj...
look up RTObjects from paths for currentContainer within elements .
120,561
public Iterable < Entry < String , ProfileNode > > getDescendingOrderedNodes ( ) { if ( nodes == null ) return null ; List < Entry < String , ProfileNode > > averageStepTimes = new LinkedList < Entry < String , ProfileNode > > ( nodes . entrySet ( ) ) ; Collections . sort ( averageStepTimes , new Comparator < Entry < S...
Returns a sorted enumerable of the nodes in descending order of how long they took to run .
120,562
VariablePointerValue resolveVariablePointer ( VariablePointerValue varPointer ) throws Exception { int contextIndex = varPointer . getContextIndex ( ) ; if ( contextIndex == - 1 ) contextIndex = getContextIndexOfVariableNamed ( varPointer . getVariableName ( ) ) ; RTObject valueOfVariablePointedTo = getRawVariableWithN...
or the exact position of a temporary on the callstack .
120,563
StoryState copy ( ) { StoryState copy = new StoryState ( story ) ; copy . getOutputStream ( ) . addAll ( outputStream ) ; outputStreamDirty ( ) ; copy . currentChoices . addAll ( currentChoices ) ; if ( hasError ( ) ) { copy . currentErrors = new ArrayList < String > ( ) ; copy . currentErrors . addAll ( currentErrors ...
I wonder if there s a sensible way to enforce that .. ??
120,564
void trimWhitespaceFromFunctionEnd ( ) { assert ( callStack . getCurrentElement ( ) . type == PushPopType . Function ) ; int functionStartPoint = callStack . getCurrentElement ( ) . functionStartInOuputStream ; if ( functionStartPoint == - 1 ) { functionStartPoint = 0 ; } for ( int i = outputStream . size ( ) - 1 ; i >...
whitespace is trimmed in one go here when we pop the function .
120,565
public HashMap < String , Object > getJsonToken ( ) throws Exception { HashMap < String , Object > obj = new HashMap < String , Object > ( ) ; HashMap < String , Object > choiceThreads = null ; for ( Choice c : currentChoices ) { c . originalThreadIndex = c . getThreadAtGeneration ( ) . threadIndex ; if ( callStack . g...
Object representation of full JSON state . Usually you should use LoadJson and ToJson since they serialise directly to String for you . But it may be useful to get the object representation so that you can integrate it into your own serialisation system .
120,566
void pushToOutputStream ( RTObject obj ) { StringValue text = obj instanceof StringValue ? ( StringValue ) obj : null ; if ( text != null ) { List < StringValue > listText = trySplittingHeadTailWhitespace ( text ) ; if ( listText != null ) { for ( StringValue textObj : listText ) { pushToOutputStreamIndividual ( textOb...
in dealing with them later .
120,567
void removeExistingGlue ( ) { for ( int i = outputStream . size ( ) - 1 ; i >= 0 ; i -- ) { RTObject c = outputStream . get ( i ) ; if ( c instanceof Glue ) { outputStream . remove ( i ) ; } else if ( c instanceof ControlCommand ) { break ; } } outputStreamDirty ( ) ; }
Only called when non - whitespace is appended
120,568
List < StringValue > trySplittingHeadTailWhitespace ( StringValue single ) { String str = single . value ; int headFirstNewlineIdx = - 1 ; int headLastNewlineIdx = - 1 ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; if ( c == '\n' ) { if ( headFirstNewlineIdx == - 1 ) headFirstNewlineI...
- A newline on its own is returned in an list for consistency .
120,569
public String report ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "%d CONTINUES / LINES:\n" , numContinues ) ) ; sb . append ( String . format ( "TOTAL TIME: %s\n" , formatMillisecs ( continueTotal ) ) ) ; sb . append ( String . format ( "SNAPSHOTTING: %s\n" , formatMillisecs ( snapT...
Generate a printable report based on the data recording during profiling .
120,570
public String megalog ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Step type\tDescription\tPath\tTime\n" ) ; for ( StepDetails step : stepDetails ) { sb . append ( step . type ) ; sb . append ( "\t" ) ; sb . append ( step . obj . toString ( ) ) ; sb . append ( "\t" ) ; sb . append ( step . obj . getP...
Create a large log of all the internal instructions that were evaluated while profiling was active . Log is in a tab - separated format for easy loading into a spreadsheet application .
120,571
public void awaitNanos ( final long timeout ) throws InterruptedException { long remaining = timeout ; queueLock . lock ( ) ; try { while ( test ( ) && remaining > 0 ) { remaining = condition . awaitNanos ( remaining ) ; } } finally { queueLock . unlock ( ) ; } }
wake me when the condition is satisfied or timeout
120,572
public void await ( ) throws InterruptedException { queueLock . lock ( ) ; try { while ( test ( ) ) { condition . await ( ) ; } } finally { queueLock . unlock ( ) ; } }
wake if signal is called or wait indefinitely
120,573
public boolean push ( final N n ) { if ( stackTop < size ) { stack [ ( stackTop ++ ) & mask ] = n ; return true ; } return false ; }
add an element to the stack
120,574
public void clear ( ) { for ( int i = 1 ; i <= 2 * m + 3 ; i ++ ) { n [ i ] = i + 1 ; } f [ 1 ] = 0F ; f [ 2 * m + 3 ] = 1F ; for ( int i = 1 ; i <= m ; i ++ ) { f [ 2 * i + 1 ] = quantiles [ i - 1 ] ; } for ( int i = 1 ; i <= m + 1 ; i ++ ) { f [ 2 * i ] = ( f [ 2 * i - 1 ] + f [ 2 * i + 1 ] ) / 2F ; } for ( int i = 1...
clear existing samples
120,575
public void add ( final float x ) { if ( isInitializing ) { q [ ni ++ ] = x ; if ( ni == 2 * m + 3 + 1 ) { Arrays . sort ( q ) ; isInitializing = false ; } } else { addMeasurement ( x ) ; } }
Add a measurement to estimate
120,576
public float [ ] getEstimates ( ) throws InsufficientSamplesException { if ( ! isInitializing ) { for ( int i = 1 ; i <= m ; i ++ ) { e [ i - 1 ] = q [ 2 * i + 1 ] ; } return e ; } else { throw new InsufficientSamplesException ( ) ; } }
get the estimates based on the last sample
120,577
public static void print ( final PrintStream out , final String name , final Percentile p ) { if ( p . isReady ( ) ) { try { final StringBuilder sb = new StringBuilder ( 512 ) ; final float [ ] q = p . getQuantiles ( ) ; final float [ ] e = p . getEstimates ( ) ; final int SCREENWIDTH = 80 ; sb . append ( name ) ; sb ....
print a nice histogram of percentiles
120,578
public final boolean push ( final N n ) { int spin = 0 ; for ( ; ; ) { final long writeLock = seqLock . tryWriteLock ( ) ; if ( writeLock > 0L ) { try { final int stackTop = this . stackTop . get ( ) ; if ( size > stackTop ) { try { stack . set ( stackTop , n ) ; stackNotEmptyCondition . signal ( ) ; return true ; } fi...
add an element to the stack failing if the stack is unable to grow
120,579
public final N peek ( ) { int spin = 0 ; for ( ; ; ) { final long readLock = seqLock . readLock ( ) ; final int stackTop = this . stackTop . get ( ) ; if ( stackTop > 0 ) { final N n = stack . get ( stackTop - 1 ) ; if ( seqLock . readLockHeld ( readLock ) ) { return n ; } } else { return null ; } spin = Condition . pr...
peek at the top of the stack
120,580
public final void clear ( ) { int spin = 0 ; for ( ; ; ) { final long writeLock = seqLock . tryWriteLock ( ) ; if ( writeLock > 0L ) { final int stackTop = this . stackTop . get ( ) ; if ( stackTop > 0 ) { try { for ( int i = 0 ; i < stackTop ; i ++ ) { stack . set ( i , null ) ; } stackNotFullCondition . signal ( ) ; ...
clear the stack - does not null old references
120,581
public static int getCapacity ( int capacity ) { int c = 1 ; if ( capacity >= MAX_POWER2 ) { c = MAX_POWER2 ; } else { while ( c < capacity ) c <<= 1 ; } if ( isPowerOf2 ( c ) ) { return c ; } else { throw new RuntimeException ( "Capacity is not a power of 2." ) ; } }
return the next power of two after
120,582
public static Class < ? > getPrimitiveType ( Class < ? > wrapperType ) { if ( Boolean . class . equals ( wrapperType ) ) { return Boolean . TYPE ; } else if ( Byte . class . equals ( wrapperType ) ) { return Byte . TYPE ; } else if ( Character . class . equals ( wrapperType ) ) { return Character . TYPE ; } else if ( S...
Returns the corresponding primitive type for the given primitive wrapper or null if the type is not a primitive wrapper .
120,583
private static String getEncodingName ( final InputStream is , final byte [ ] start , final int count ) { final int b0 = start [ 0 ] & 0xFF ; final int b1 = start [ 1 ] & 0xFF ; final int b2 = start [ 2 ] & 0xFF ; if ( count > 1 ) { if ( b0 == 0xFE && b1 == 0xFF ) return "UTF-16BE" ; if ( b0 == 0xFF && b1 == 0xFE ) ret...
the detection is done equally to the one in xerces parser
120,584
private int restart ( final boolean basic , final Destination dst , final int eraseCode , final int channel ) throws KNXTimeoutException , KNXRemoteException , KNXLinkClosedException , KNXDisconnectException , InterruptedException { int time = 0 ; if ( basic ) { send ( dst , priority , DataUnitBuilder . createLengthOpt...
for erase codes 1 3 4 the channel should be 0
120,585
List < byte [ ] > readProperty2 ( final Destination dst , final int objIndex , final int propertyId , final int start , final int elements ) throws KNXTimeoutException , KNXRemoteException , KNXDisconnectException , KNXLinkClosedException , InterruptedException { return readProperty ( dst , objIndex , propertyId , star...
as readProperty but collects all responses until response timeout is reached
120,586
private void send ( final Destination d , final Priority p , final byte [ ] apdu , final int response ) throws KNXTimeoutException , KNXDisconnectException , KNXLinkClosedException { svcResponse = response ; if ( d . isConnectionOriented ( ) ) { tl . connect ( d ) ; tl . sendData ( d , p , apdu ) ; } else tl . sendData...
helper which sets the expected svc response and sends in CO or CL mode
120,587
private static byte [ ] extractPropertyElements ( final byte [ ] apdu , final int objIndex , final int propertyId , final int elements ) throws KNXRemoteException { final int oi = apdu [ 2 ] & 0xff ; final int pid = apdu [ 3 ] & 0xff ; if ( oi != objIndex || pid != propertyId ) throw new KNXInvalidResponseException ( S...
returns property read . res element values
120,588
private static Collection < ? extends KNXAddress > ensureDeviceAck ( final KNXMediumSettings settings , final Collection < ? extends KNXAddress > acknowledge ) { if ( settings . getMedium ( ) != KNXMediumSettings . MEDIUM_TP1 ) throw new KNXIllegalArgumentException ( "TP-UART link supports only TP1 medium" ) ; final In...
if possible add this link to the list of addresses to acknowledge
120,589
public void setProperty ( final int objectType , final int objectInstance , final int propertyId , final int start , final int elements , final byte ... data ) throws KNXTimeoutException , KNXRemoteException , KNXPortClosedException , InterruptedException { final CEMIDevMgmt req = new CEMIDevMgmt ( CEMIDevMgmt . MC_PRO...
Sets property value elements of an interface object property .
120,590
public byte [ ] getProperty ( final int objectType , final int objectInstance , final int propertyId , final int start , final int elements ) throws KNXTimeoutException , KNXRemoteException , KNXPortClosedException , InterruptedException { final CEMIDevMgmt req = new CEMIDevMgmt ( CEMIDevMgmt . MC_PROPREAD_REQ , object...
Gets property value elements of an interface object property .
120,591
private Optional < InetAddress > onSameSubnet ( final InetAddress remote ) { try { return Collections . list ( NetworkInterface . getNetworkInterfaces ( ) ) . stream ( ) . flatMap ( ni -> ni . getInterfaceAddresses ( ) . stream ( ) ) . filter ( ia -> ia . getAddress ( ) instanceof Inet4Address ) . peek ( ia -> logger ....
finds a local IPv4 address with its network prefix matching the remote address
120,592
private Destination getOrCreateDestination ( final IndividualAddress device , final boolean keepAlive , final boolean verifyByServer ) { final Destination d = ( ( TransportLayerImpl ) tl ) . getDestination ( device ) ; return d != null ? d : tl . createDestination ( device , true , keepAlive , verifyByServer ) ; }
work around for implementation in TL which unconditionally throws if dst exists
120,593
public void activateBusmonitor ( ) throws IOException { logger . debug ( "activate TP-UART busmonitor" ) ; os . write ( ActivateBusmon ) ; busmonSequence = 0 ; busmon = true ; }
Activate busmonitor mode the TP - UART controller is set completely passive .
120,594
private static byte [ ] cEmiToTP1 ( final byte [ ] frame ) { final int stdMaxApdu = 15 ; final int cEmiPrefix = 10 ; final boolean std = frame . length <= cEmiPrefix + stdMaxApdu ; final byte [ ] tp1 ; if ( std ) { tp1 = new byte [ frame . length - 2 ] ; int i = 0 ; tp1 [ i ++ ] = ( byte ) ( ( frame [ 2 ] & 0xfc ) | St...
returns a TP1 std or ext frame
120,595
public static HidReport createFeatureService ( final BusAccessServerService service , final BusAccessServerFeature feature , final byte [ ] frame ) { return new HidReport ( service , feature , frame ) ; }
Creates a new report for use with the Bus Access Server feature service .
120,596
public static List < HidReport > create ( final KnxTunnelEmi emi , final byte [ ] frame ) { final List < HidReport > l = new ArrayList < > ( ) ; final EnumSet < PacketType > packetType = EnumSet . of ( PacketType . Start ) ; int maxData = maxDataStartPacket ; if ( frame . length > maxData ) packetType . add ( PacketTyp...
Creates a new report containing an EMI frame .
120,597
private byte [ ] unifyLData ( final CEMI ldata , final boolean emptySrc , final List < Integer > types ) { final byte [ ] data ; if ( ldata instanceof CEMILDataEx ) { final CEMILDataEx ext = ( ( CEMILDataEx ) ldata ) ; final List < AddInfo > additionalInfo = ext . additionalInfo ( ) ; synchronized ( additionalInfo ) { ...
additional info . types provides the list of add . info types we want to keep everything else is removed
120,598
public static LibraryAdapter open ( final Logger logger , final String portId , final int baudrate , final int idleTimeout ) throws KNXException { Throwable t = null ; if ( CommConnectionAdapter . isAvailable ( ) ) { logger . debug ( "open Java ME serial port connection (CommConnection) for {}" , portId ) ; try { retur...
Factory method to open a serial connection using one of the available library adapters .
120,599
private void setRepeat ( final boolean repeat ) { final boolean flag = mc == MC_LDATA_IND ? ! repeat : repeat ; if ( flag ) ctrl1 |= 0x20 ; else ctrl1 &= 0xDF ; }
Sets the repeat flag in control field using the message code type for decision .