idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
34,100
@ Procedure ( mode = Mode . WRITE ) @ Description ( "apoc.refactor.rename.nodeProperty(oldName, newName, [nodes]) | rename all node's property from 'oldName' to 'newName'. If 'nodes' is provided renaming is applied to this set only" ) public Stream < BatchAndTotalResultWithInfo > nodeProperty ( @ Name ( "oldName" ) Str...
Rename property of a node by creating a new one and deleting the old .
34,101
@ Description ( "apoc.meta.data({config}) - examines a subset of the graph to provide a tabular meta information" ) public Stream < MetaResult > data ( @ Name ( value = "config" , defaultValue = "{}" ) Map < String , Object > config ) { MetaConfig metaConfig = new MetaConfig ( config ) ; return collectMetaData ( metaC...
todo put index sizes for indexed properties
34,102
private static int [ ] growArray ( int [ ] array , float growFactor ) { int currentSize = array . length ; int newArray [ ] = new int [ ( int ) ( currentSize * growFactor ) ] ; System . arraycopy ( array , 0 , newArray , 0 , currentSize ) ; return newArray ; }
Not doing it right now because of the complications of the interface .
34,103
private Boolean indexExists ( String labelName , List < String > propertyNames ) { Schema schema = db . schema ( ) ; for ( IndexDefinition indexDefinition : Iterables . asList ( schema . getIndexes ( Label . label ( labelName ) ) ) ) { List < String > properties = Iterables . asList ( indexDefinition . getPropertyKeys ...
Checks if an index exists for a given label and a list of properties This method checks for index on nodes
34,104
private Boolean constraintsExists ( String labelName , List < String > propertyNames ) { Schema schema = db . schema ( ) ; for ( ConstraintDefinition constraintDefinition : Iterables . asList ( schema . getConstraints ( Label . label ( labelName ) ) ) ) { List < String > properties = Iterables . asList ( constraintDefi...
Checks if a constraint exists for a given label and a list of properties This method checks for constraints on node
34,105
private Boolean constraintsExistsForRelationship ( String type , List < String > propertyNames ) { Schema schema = db . schema ( ) ; for ( ConstraintDefinition constraintDefinition : Iterables . asList ( schema . getConstraints ( RelationshipType . withName ( type ) ) ) ) { List < String > properties = Iterables . asLi...
Checks if a constraint exists for a given type and a list of properties This method checks for constraints on relationships
34,106
private Stream < ConstraintRelationshipInfo > constraintsForRelationship ( Map < String , Object > config ) { Schema schema = db . schema ( ) ; SchemaConfig schemaConfig = new SchemaConfig ( config ) ; Set < String > includeRelationships = schemaConfig . getRelationships ( ) ; Set < String > excludeRelationships = sche...
Collects constraints for relationships
34,107
private IndexConstraintNodeInfo nodeInfoFromConstraintDescriptor ( ConstraintDescriptor constraintDescriptor , TokenNameLookup tokens ) { String labelName = tokens . labelGetName ( constraintDescriptor . schema ( ) . keyId ( ) ) ; List < String > properties = new ArrayList < > ( ) ; Arrays . stream ( constraintDescript...
ConstraintInfo info from ConstraintDescriptor
34,108
private IndexConstraintNodeInfo nodeInfoFromIndexDefinition ( IndexReference indexReference , SchemaRead schemaRead , TokenNameLookup tokens ) { int [ ] labelIds = indexReference . schema ( ) . getEntityTokenIds ( ) ; if ( labelIds . length != 1 ) throw new IllegalStateException ( "Index with more than one label" ) ; S...
Index info from IndexDefinition
34,109
private ConstraintRelationshipInfo relationshipInfoFromConstraintDefinition ( ConstraintDefinition constraintDefinition ) { return new ConstraintRelationshipInfo ( String . format ( "CONSTRAINT %s" , constraintDefinition . toString ( ) ) , constraintDefinition . getConstraintType ( ) . name ( ) , Iterables . asList ( c...
Constraint info from ConstraintDefinition for relationships
34,110
@ UserFunction ( "apoc.temporal.format" ) @ Description ( "apoc.temporal.format(input, format) | Format a temporal value" ) public String format ( @ Name ( "temporal" ) Object input , @ Name ( value = "format" , defaultValue = "yyyy-MM-dd" ) String format ) { try { DateTimeFormatter formatter = getOrCreate ( format ) ;...
Format a temporal value to a String
34,111
@ UserFunction ( "apoc.temporal.formatDuration" ) @ Description ( "apoc.temporal.formatDuration(input, format) | Format a Duration" ) public String formatDuration ( @ Name ( "input" ) Object input , @ Name ( "format" ) String format ) { try { LocalDateTime midnight = LocalDateTime . of ( 0 , 1 , 1 , 0 , 0 , 0 , 0 ) ; L...
Convert a Duration into a LocalTime and format the value as a String
34,112
protected int getMajorVersion ( ) { return this . cluster . authenticate ( this . passwordAuthenticator ) . clusterManager ( ) . info ( 5 , TimeUnit . SECONDS ) . getMinVersion ( ) . major ( ) ; }
Get the major version of Couchbase server that is 4 . x or 5 . x
34,113
public List < JsonObject > executeStatement ( String statement ) { SimpleN1qlQuery query = N1qlQuery . simple ( statement ) ; return executeQuery ( query ) ; }
Executes a plain un - parameterized N1QL kernelTransaction .
34,114
public List < JsonObject > executeParametrizedStatement ( String statement , List < Object > parameters ) { JsonArray positionalParams = JsonArray . from ( parameters ) ; ParameterizedN1qlQuery query = N1qlQuery . parameterized ( statement , positionalParams ) ; return executeQuery ( query ) ; }
Executes a N1QL kernelTransaction with positional parameters .
34,115
public List < JsonObject > executeParametrizedStatement ( String statement , List < String > parameterNames , List < Object > parameterValues ) { JsonObject namedParams = JsonObject . create ( ) ; for ( int param = 0 ; param < parameterNames . size ( ) ; param ++ ) { namedParams . put ( parameterNames . get ( param ) ,...
Executes a N1QL kernelTransaction with named parameters .
34,116
private List < Pair < Integer , Integer > > doGenerateEdgesWithOmitList ( ) { final int numberOfNodes = getConfiguration ( ) . getNumberOfNodes ( ) ; final int numberOfEdges = getConfiguration ( ) . getNumberOfEdges ( ) ; final long maxEdges = numberOfNodes * ( numberOfNodes - 1 ) / 2 ; final List < Pair < Integer , In...
Improved implementation of Erdos - Renyi generator based on bijection from edge labels to edge realisations . Works very well for large number of nodes but is slow with increasing number of edges . Best for denser networks with a clear giant component .
34,117
private Pair < Integer , Integer > indexToEdgeBijection ( long index ) { long i = ( long ) Math . ceil ( ( Math . sqrt ( 1 + 8 * ( index + 1 ) ) - 1 ) / 2 ) ; long diff = index + 1 - ( i * ( i - 1 ) ) / 2 ; return Pair . of ( ( int ) i , ( int ) diff - 1 ) ; }
Maps an index in a hypothetical list of all edges to the actual edge .
34,118
public static boolean transactionIsTerminated ( TerminationGuard db ) { try { db . check ( ) ; return false ; } catch ( TransactionGuardException | TransactionTerminatedException | NotInTransactionException tge ) { return true ; } }
Given a context related to the procedure invocation this method checks if the transaction is terminated in some way
34,119
private void handleTypeAndAttributes ( Node node , Map < String , Object > elementMap ) { if ( node . getLocalName ( ) != null ) { elementMap . put ( "_type" , node . getLocalName ( ) ) ; } if ( node . getAttributes ( ) != null ) { NamedNodeMap attributeMap = node . getAttributes ( ) ; for ( int i = 0 ; i < attributeMa...
Collects type and attributes for the node
34,120
private void handleTextNode ( Node node , Map < String , Object > elementMap ) { Object text = "" ; int nodeType = node . getNodeType ( ) ; switch ( nodeType ) { case Node . TEXT_NODE : text = normalizeText ( node . getNodeValue ( ) ) ; break ; case Node . CDATA_SECTION_NODE : text = normalizeText ( ( ( CharacterData )...
Handle TEXT nodes and CDATA nodes
34,121
private String normalizeText ( String text ) { String [ ] tokens = StringUtils . split ( text , "\n" ) ; for ( int i = 0 ; i < tokens . length ; i ++ ) { tokens [ i ] = tokens [ i ] . trim ( ) ; } return StringUtils . join ( tokens , " " ) . trim ( ) ; }
Remove trailing whitespaces and new line characters
34,122
public static List < CsvHeaderField > processHeader ( final String header , final char delimiter , final char quotationCharacter ) { final String separatorRegex = Pattern . quote ( String . valueOf ( delimiter ) ) ; final List < String > attributes = Arrays . asList ( header . split ( separatorRegex ) ) ; final List < ...
Processes CSV header . Works for both nodes and relationships .
34,123
public static Evaluator endAndTerminatorNodeEvaluator ( List < Node > endNodes , List < Node > terminatorNodes ) { Evaluator endNodeEvaluator = null ; Evaluator terminatorNodeEvaluator = null ; if ( ! endNodes . isEmpty ( ) ) { Node [ ] nodes = endNodes . toArray ( new Node [ endNodes . size ( ) ] ) ; endNodeEvaluator ...
Returns an evaluator which handles end nodes and terminator nodes Returns null if both lists are empty
34,124
private static int interleaveBits ( int odd , int even ) { int val = 0 ; int max = Math . max ( odd , even ) ; int n = 0 ; while ( max > 0 ) { n ++ ; max >>= 1 ; } for ( int i = 0 ; i < n ; i ++ ) { int bitMask = 1 << i ; int a = ( even & bitMask ) > 0 ? ( 1 << ( 2 * i ) ) : 0 ; int b = ( odd & bitMask ) > 0 ? ( 1 << (...
Interleave the bits from two input integer values
34,125
public CoreGraphAlgorithms init ( String label , String rel ) { TokenRead token = ktx . tokenRead ( ) ; int labelId = token . nodeLabel ( label ) ; int relTypeId = token . relationshipType ( rel ) ; loadNodes ( labelId , relTypeId ) ; loadRels ( labelId , relTypeId ) ; return this ; }
keep threads with open worker - tx for reads
34,126
public Chunks withDefault ( int defaultValue ) { this . defaultValue = defaultValue ; if ( defaultValue != 0 ) { for ( int [ ] chunk : chunks ) { Arrays . fill ( chunk , defaultValue ) ; } } return this ; }
call directly after construction todo move to constructor or static factory
34,127
void set ( int index , int value ) { int chunk = assertSpace ( index ) ; chunks [ chunk ] [ index & mask ] = value ; }
Sets a value an grows chunks dynamically if exceeding size or missing chunk encountered
34,128
private int [ ] newChunk ( ) { if ( defaultValue == 0 ) return new int [ chunkSize ] ; if ( baseChunk == null ) { baseChunk = new int [ chunkSize ] ; Arrays . fill ( baseChunk , defaultValue ) ; } return baseChunk . clone ( ) ; }
todo use pool
34,129
public void sumUp ( ) { int offset = 0 ; int tmp = 0 ; for ( int i = 0 ; i < numChunks ; i ++ ) { int [ ] chunk = chunks [ i ] ; if ( chunk == null ) throw new IllegalStateException ( "Chunks are not continous, null fragement at offset " + i ) ; for ( int j = 0 ; j < chunkSize ; j ++ ) { tmp = chunk [ j ] ; chunk [ j ]...
special operation implemented inline to compute and store sum up until here
34,130
public void add ( Chunks c ) { assert c . chunkBits == chunkBits ; assert c . defaultValue == defaultValue ; int [ ] [ ] oChunks = c . chunks ; if ( c . numChunks > numChunks ) growTo ( c . numChunks - 1 ) ; for ( int i = 0 ; i < oChunks . length ; i ++ ) { int [ ] oChunk = oChunks [ i ] ; if ( oChunk != null ) { if ( ...
adds values from another Chunks to the current one missing chunks are cloned over
34,131
public int [ ] mergeAllChunks ( ) { int [ ] merged = new int [ chunkSize * numChunks ] ; int filledChunks = Math . min ( numChunks , getFilledChunks ( ) + 1 ) ; for ( int i = 0 ; i < filledChunks ; i ++ ) { if ( chunks [ i ] != null ) { System . arraycopy ( chunks [ i ] , 0 , merged , i * chunkSize , chunkSize ) ; } } ...
turn this chunked array into a regular int - array mostly for compatibility also copying unused space at the end filled with default value
34,132
public int [ ] mergeChunks ( ) { int filledChunks = getFilledChunks ( ) ; int [ ] merged = new int [ size ( ) ] ; for ( int i = 0 ; i < filledChunks ; i ++ ) { if ( chunks [ i ] != null ) { System . arraycopy ( chunks [ i ] , 0 , merged , i * chunkSize , chunkSize ) ; } } int remainder = size ( ) % chunkSize ; if ( rem...
turn this chunked array into a regular int - array mostly for compatibility cuts off unused space at the end
34,133
public int randomIndexChoice ( List < Integer > weights ) { int result = 0 , index ; double maxKey = 0.0 ; double u , key ; int weight ; for ( ListIterator < Integer > it = weights . listIterator ( ) ; it . hasNext ( ) ; ) { index = it . nextIndex ( ) ; weight = it . next ( ) ; u = random . nextDouble ( ) ; key = Math ...
Returns an integer at random weighted according to its index
34,134
public static Stream < Relationship > coverNodes ( Collection < Node > nodes ) { return nodes . stream ( ) . flatMap ( n -> StreamSupport . stream ( n . getRelationships ( Direction . OUTGOING ) . spliterator ( ) , false ) . filter ( r -> nodes . contains ( r . getEndNode ( ) ) ) ) ; }
non - parallelized utility method for use by other procedures
34,135
private synchronized Map < String , Map < String , Collection < Index < Node > > > > initIndexConfiguration ( ) { Map < String , Map < String , Collection < Index < Node > > > > indexesByLabelAndProperty = new HashMap < > ( ) ; try ( Transaction tx = graphDatabaseService . beginTx ( ) ) { final IndexManager indexManage...
might be run from a scheduler so we need to make sure we have a transaction
34,136
public synchronized void forceTxRollover ( ) { if ( async ) { try { forceTxRolloverFlag = false ; indexCommandQueue . put ( FORCE_TX_ROLLOVER ) ; while ( ! forceTxRolloverFlag ) { Thread . sleep ( 5 ) ; } } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } }
to be used from unit tests to ensure a tx rollover has happenend
34,137
@ Procedure ( mode = Mode . WRITE ) @ Description ( "apoc.periodic.iterate('statement returning items', 'statement per item', {batchSize:1000,iterateList:true,parallel:false,params:{},concurrency:50,retries:0}) YIELD batches, total - run the second statement for each item returned by the first statement. Returns number...
invoke cypherAction in batched transactions being feeded from cypherIteration running in main thread
34,138
private Map < String , Object > documentToPackableMap ( Map < String , Object > document ) { if ( compatibleValues ) { try { return jsonMapper . readValue ( jsonMapper . writeValueAsBytes ( document ) , new TypeReference < Map < String , Object > > ( ) { } ) ; } catch ( Exception e ) { throw new RuntimeException ( "Can...
It translates a MongoDB document into a Map where the _id field is not an ObjectId but a simple String representation of it
34,139
protected String getQueryUrl ( String hostOrKey , String index , String type , String id , Object query ) { return getElasticSearchUrl ( hostOrKey ) + formatQueryUrl ( index , type , id , query ) ; }
Get the full Elasticsearch url
34,140
private int getDegreeSafe ( Node node , RelationshipType relType , Direction direction ) { if ( relType == null ) { return node . getDegree ( direction ) ; } return node . getDegree ( relType , direction ) ; }
works in cases when relType is null
34,141
static String sanitizeJavadoc ( String documentation ) { documentation = documentation . replaceAll ( "[^\\S\n]+\n" , "\n" ) ; documentation = documentation . replaceAll ( "\\s+$" , "" ) ; documentation = documentation . replaceAll ( "\\*/" , "&#42;/" ) ; documentation = documentation . replaceAll ( "@see (http:" + URL...
A grab - bag of fixes for things that can go wrong when converting to javadoc .
34,142
@ SuppressWarnings ( "unchecked" ) private Object union ( Linker linker , Object a , Object b ) { if ( a instanceof List ) { return union ( ( List < ? > ) a , ( List < ? > ) b ) ; } else if ( a instanceof Map ) { return union ( linker , ( Map < ProtoMember , Object > ) a , ( Map < ProtoMember , Object > ) b ) ; } else ...
Combine values for the same key resolving conflicts based on their type .
34,143
private ProtoFile loadDescriptorProto ( ) throws IOException { InputStream resourceAsStream = SchemaLoader . class . getResourceAsStream ( "/" + DESCRIPTOR_PROTO ) ; try ( BufferedSource buffer = Okio . buffer ( Okio . source ( resourceAsStream ) ) ) { String data = buffer . readUtf8 ( ) ; Location location = Location ...
Returns Google s protobuf descriptor which defines standard options like default deprecated and java_package . If the user has provided their own version of the descriptor proto that is preferred .
34,144
public String readString ( ) { skipWhitespace ( true ) ; char c = peekChar ( ) ; return c == '"' || c == '\'' ? readQuotedString ( ) : readWord ( ) ; }
Reads a quoted or unquoted string and returns it .
34,145
public String readWord ( ) { skipWhitespace ( true ) ; int start = pos ; while ( pos < data . length ) { char c = data [ pos ] ; if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || ( c >= '0' && c <= '9' ) || ( c == '_' ) || ( c == '-' ) || ( c == '.' ) ) { pos ++ ; } else { break ; } } if ( start == pos ) { t...
Reads a non - empty word and returns it .
34,146
private String readComment ( ) { if ( pos == data . length || data [ pos ] != '/' ) throw new AssertionError ( ) ; pos ++ ; int commentType = pos < data . length ? data [ pos ++ ] : - 1 ; if ( commentType == '*' ) { StringBuilder result = new StringBuilder ( ) ; boolean startOfLine = true ; for ( ; pos + 1 < data . len...
Reads a comment and returns its body .
34,147
private String stripDefault ( List < OptionElement > options ) { String result = null ; for ( Iterator < OptionElement > i = options . iterator ( ) ; i . hasNext ( ) ; ) { OptionElement option = i . next ( ) ; if ( option . getName ( ) . equals ( "default" ) ) { i . remove ( ) ; result = String . valueOf ( option . get...
Defaults aren t options . This finds an option named default removes and returns it . Returns null if no default option is present .
34,148
private ReservedElement readReserved ( Location location , String documentation ) { ImmutableList . Builder < Object > valuesBuilder = ImmutableList . builder ( ) ; while ( true ) { char c = reader . peekChar ( ) ; if ( c == '"' || c == '\'' ) { valuesBuilder . add ( reader . readQuotedString ( ) ) ; } else { int tagSt...
Reads a reserved tags and names list like reserved 10 12 to 14 foo ; .
34,149
private EnumConstantElement readEnumConstant ( String documentation , Location location , String label ) { reader . require ( '=' ) ; int tag = reader . readInt ( ) ; List < OptionElement > options = new OptionReader ( reader ) . readOptions ( ) ; reader . require ( ';' ) ; documentation = reader . tryAppendTrailingDoc...
Reads an enum constant like ROCK = 0 ; . The label is the constant name .
34,150
Multimap < Path , String > pathsToAttempt ( Set < Location > protoLocations ) { Multimap < Path , String > result = MultimapBuilder . linkedHashKeys ( ) . linkedHashSetValues ( ) . build ( ) ; for ( Location location : protoLocations ) { pathsToAttempt ( result , location ) ; } return result ; }
Returns a multimap whose keys are base directories and whose values are potential locations of wire profile files .
34,151
boolean mark ( ProtoType type ) { if ( type == null ) throw new NullPointerException ( "type == null" ) ; if ( identifierSet . excludes ( type ) ) return false ; return types . add ( type ) ; }
Marks a type as transitively reachable by the includes set . Returns true if the mark is new the type will be retained and its own dependencies should be traversed .
34,152
boolean mark ( ProtoMember protoMember ) { if ( protoMember == null ) throw new NullPointerException ( "type == null" ) ; if ( identifierSet . excludes ( protoMember ) ) return false ; return members . containsKey ( protoMember . type ( ) ) ? members . put ( protoMember . type ( ) , protoMember ) : types . add ( protoM...
Marks a member as transitively reachable by the includes set . Returns true if the mark is new the member will be retained and its own dependencies should be traversed .
34,153
public String enclosingTypeOrPackage ( ) { int dot = string . lastIndexOf ( '.' ) ; return dot == - 1 ? null : string . substring ( 0 , dot ) ; }
Returns the enclosing type or null if this type is not nested in another type .
34,154
String packageName ( ) { for ( Object context : contextStack ) { if ( context instanceof ProtoFile ) return ( ( ProtoFile ) context ) . packageName ( ) ; } return null ; }
Returns the current package name from the context stack .
34,155
public static XWPFTemplate compile ( InputStream inputStream , Configure config ) { try { XWPFTemplate instance = new XWPFTemplate ( ) ; instance . config = config ; instance . doc = new NiceXWPFDocument ( inputStream ) ; instance . visitor = new TemplateVisitor ( instance . config ) ; instance . eleTemplates = instanc...
template file as InputStream
34,156
private boolean isInvalidEncodedPath ( String path ) { if ( path . contains ( "%" ) ) { try { String decodedPath = URLDecoder . decode ( path , "UTF-8" ) ; if ( isInvalidPath ( decodedPath ) ) { return true ; } decodedPath = processPath ( decodedPath ) ; if ( isInvalidPath ( decodedPath ) ) { return true ; } } catch ( ...
Check whether the given path contains invalid escape sequences .
34,157
public CredentialsProvider createFor ( String uri , String username , String password , String passphrase ) { return createFor ( uri , username , password , passphrase , false ) ; }
Search for a credential provider that will handle the specified URI . If not found and the username or passphrase has text then create a default using the provided username and password or passphrase . Otherwise null .
34,158
public CredentialsProvider createFor ( String uri , String username , String password , String passphrase , boolean skipSslValidation ) { CredentialsProvider provider = null ; if ( awsAvailable ( ) && AwsCodeCommitCredentialProvider . canHandle ( uri ) ) { this . logger . debug ( "Constructing AwsCodeCommitCredentialPr...
Search for a credential provider that will handle the specified URI . If not found and the username or passphrase has text then create a default using the provided username and password or passphrase .
34,159
public String refresh ( String label ) { Git git = null ; try { git = createGitClient ( ) ; if ( shouldPull ( git ) ) { FetchResult fetchStatus = fetch ( git , label ) ; if ( this . deleteUntrackedBranches && fetchStatus != null ) { deleteUntrackedLocalBranches ( fetchStatus . getTrackingRefUpdates ( ) , git ) ; } chec...
Get the working directory ready .
34,160
private void initClonedRepository ( ) throws GitAPIException , IOException { if ( ! getUri ( ) . startsWith ( FILE_URI_PREFIX ) ) { deleteBaseDirIfExists ( ) ; Git git = cloneToBasedir ( ) ; if ( git != null ) { git . close ( ) ; } git = openGitRepository ( ) ; if ( git != null ) { git . close ( ) ; } } }
Clones the remote repository and then opens a connection to it .
34,161
private Collection < String > deleteUntrackedLocalBranches ( Collection < TrackingRefUpdate > trackingRefUpdates , Git git ) { if ( CollectionUtils . isEmpty ( trackingRefUpdates ) ) { return Collections . emptyList ( ) ; } Collection < String > branchesToDelete = new ArrayList < > ( ) ; for ( TrackingRefUpdate trackin...
Deletes local branches if corresponding remote branch was removed .
34,162
private synchronized Git copyRepository ( ) throws IOException , GitAPIException { deleteBaseDirIfExists ( ) ; getBasedir ( ) . mkdirs ( ) ; Assert . state ( getBasedir ( ) . exists ( ) , "Could not create basedir: " + getBasedir ( ) ) ; if ( getUri ( ) . startsWith ( FILE_URI_PREFIX ) ) { return copyFromLocalRepositor...
request ) .
34,163
private static byte [ ] canonicalRequestDigest ( URIish uri ) throws NoSuchAlgorithmException { StringBuilder canonicalRequest = new StringBuilder ( ) ; canonicalRequest . append ( "GIT\n" ) . append ( uri . getPath ( ) ) . append ( "\n" ) . append ( "\n" ) . append ( "host:" ) . append ( uri . getHost ( ) ) . append (...
Creates a message digest .
34,164
public boolean get ( URIish uri , CredentialItem ... items ) throws UnsupportedCredentialItem { String codeCommitPassword ; String awsAccessKey ; String awsSecretKey ; try { AWSCredentials awsCredentials = retrieveAwsCredentials ( ) ; StringBuilder awsKey = new StringBuilder ( ) ; awsKey . append ( awsCredentials . get...
Get the username and password to use for the given uri .
34,165
public boolean get ( URIish uri , CredentialItem ... items ) throws UnsupportedCredentialItem { for ( final CredentialItem item : items ) { if ( item instanceof CredentialItem . StringType && item . getPromptText ( ) . startsWith ( PROMPT ) ) { ( ( CredentialItem . StringType ) item ) . setValue ( this . passphrase ) ;...
Ask for the credential items to be populated with the passphrase .
34,166
boolean isGuarded ( T resource ) { if ( guarded . contains ( resource ) ) { return true ; } Context context = contextStack . peek ( ) ; if ( ! context . safe ) { return false ; } while ( context != null && context . conditional != null ) { registeredGuards . put ( context . conditional , resource ) ; context = context ...
Determines if the given resource is guarded either intrinsically or conditionally . If the former any ancestor conditional nodes are registered as feature - testing the resource .
34,167
private void prioritizeFromEntryNode ( DiGraphNode < Node , Branch > entry ) { PriorityQueue < DiGraphNode < Node , Branch > > worklist = new PriorityQueue < > ( 10 , priorityComparator ) ; worklist . add ( entry ) ; while ( ! worklist . isEmpty ( ) ) { DiGraphNode < Node , Branch > current = worklist . remove ( ) ; if...
Given an entry node find all the nodes reachable from that node and prioritize them .
34,168
static Node computeFallThrough ( Node n ) { switch ( n . getToken ( ) ) { case DO : case FOR : return computeFallThrough ( n . getFirstChild ( ) ) ; case FOR_IN : case FOR_OF : case FOR_AWAIT_OF : return n . getSecondChild ( ) ; case LABEL : return computeFallThrough ( n . getLastChild ( ) ) ; default : return n ; } }
Computes the destination node of n when we want to fallthrough into the subtree of n . We don t always create a CFG edge into n itself because of DOs and FORs .
34,169
private void createEdge ( Node fromNode , ControlFlowGraph . Branch branch , Node toNode ) { cfg . createNode ( fromNode ) ; cfg . createNode ( toNode ) ; cfg . connectIfNotFound ( fromNode , branch , toNode ) ; }
Connects the two nodes in the control flow graph .
34,170
private void connectToPossibleExceptionHandler ( Node cfgNode , Node target ) { if ( mayThrowException ( target ) && ! exceptionHandler . isEmpty ( ) ) { Node lastJump = cfgNode ; for ( Node handler : exceptionHandler ) { if ( handler . isFunction ( ) ) { return ; } checkState ( handler . isTry ( ) ) ; Node catchBlock ...
Connects cfgNode to the proper CATCH block if target subtree might throw an exception . If there are FINALLY blocks reached before a CATCH it will make the corresponding entry in finallyMap .
34,171
public static boolean isBreakTarget ( Node target , String label ) { return isBreakStructure ( target , label != null ) && matchLabel ( target . getParent ( ) , label ) ; }
Checks if target is actually the break target of labeled continue . The label can be null if it is an unlabeled break .
34,172
static boolean isContinueTarget ( Node target , String label ) { return NodeUtil . isLoopStructure ( target ) && matchLabel ( target . getParent ( ) , label ) ; }
Checks if target is actually the continue target of labeled continue . The label can be null if it is an unlabeled continue .
34,173
private static boolean matchLabel ( Node target , String label ) { if ( label == null ) { return true ; } while ( target . isLabel ( ) ) { if ( target . getFirstChild ( ) . getString ( ) . equals ( label ) ) { return true ; } target = target . getParent ( ) ; } return false ; }
Check if label is actually referencing the target control structure . If label is null it always returns true .
34,174
public static boolean mayThrowException ( Node n ) { switch ( n . getToken ( ) ) { case CALL : case TAGGED_TEMPLATELIT : case GETPROP : case GETELEM : case THROW : case NEW : case ASSIGN : case INC : case DEC : case INSTANCEOF : case IN : case YIELD : case AWAIT : return true ; case FUNCTION : return false ; default : ...
Determines if the subtree might throw an exception .
34,175
static boolean isBreakStructure ( Node n , boolean labeled ) { switch ( n . getToken ( ) ) { case FOR : case FOR_IN : case FOR_OF : case FOR_AWAIT_OF : case DO : case WHILE : case SWITCH : return true ; case BLOCK : case ROOT : case IF : case TRY : return labeled ; default : return false ; } }
Determines whether the given node can be terminated with a BREAK node .
34,176
static Node getExceptionHandler ( Node n ) { for ( Node cur = n ; ! cur . isScript ( ) && ! cur . isFunction ( ) ; cur = cur . getParent ( ) ) { Node catchNode = getCatchHandlerForBlock ( cur ) ; if ( catchNode != null ) { return catchNode ; } } return null ; }
Get the TRY block with a CATCH that would be run if n throws an exception .
34,177
static Node getCatchHandlerForBlock ( Node block ) { if ( block . isBlock ( ) && block . getParent ( ) . isTry ( ) && block . getParent ( ) . getFirstChild ( ) == block ) { for ( Node s = block . getNext ( ) ; s != null ; s = s . getNext ( ) ) { if ( NodeUtil . hasCatchHandler ( s ) ) { return s . getFirstChild ( ) ; }...
Locate the catch BLOCK given the first block in a TRY .
34,178
public void visit ( NodeTraversal traversal , Node node , Node parent ) { if ( node . isScript ( ) ) { String fileName = getFileName ( traversal ) ; if ( instrumentationData . get ( fileName ) != null ) { if ( node . hasChildren ( ) && node . getFirstChild ( ) . isModuleBody ( ) ) { node = node . getFirstChild ( ) ; } ...
Instruments the JS code by inserting appropriate nodes into the AST . The instrumentation logic is tuned to collect line coverage data only .
34,179
private void normalizeNodeTypes ( Node n ) { normalizeBlocks ( n ) ; for ( Node child = n . getFirstChild ( ) ; child != null ; child = child . getNext ( ) ) { checkState ( child . getParent ( ) == n ) ; normalizeNodeTypes ( child ) ; } }
Covert EXPR_VOID to EXPR_RESULT to simplify the rest of the code .
34,180
private void normalizeBlocks ( Node n ) { if ( NodeUtil . isControlStructure ( n ) && ! n . isLabel ( ) && ! n . isSwitch ( ) ) { for ( Node c = n . getFirstChild ( ) ; c != null ; c = c . getNext ( ) ) { if ( NodeUtil . isControlStructureCodeBlock ( n , c ) && ! c . isBlock ( ) ) { Node newBlock = IR . block ( ) . src...
Add blocks to IF WHILE DO etc .
34,181
private boolean isInterface ( Node n ) { if ( ! n . isFunction ( ) ) { return false ; } JSDocInfo jsDoc = NodeUtil . getBestJSDocInfo ( n ) ; return jsDoc != null && jsDoc . isInterface ( ) ; }
Whether a function is an interface constructor or a method on an interface .
34,182
private void pullDestructuringOutOfParams ( Node paramList , Node function ) { Node insertSpot = null ; Node body = function . getLastChild ( ) ; int i = 0 ; Node next = null ; for ( Node param = paramList . getFirstChild ( ) ; param != null ; param = next , i ++ ) { next = param . getNext ( ) ; if ( param . isDefaultV...
the parameter list contains a usage of OBJECT_REST .
34,183
private Node replacePatternParamWithTempVar ( Node function , Node insertSpot , Node patternParam , String tempVarName ) { JSType paramType = patternParam . getJSType ( ) ; Node newParam = astFactory . createName ( tempVarName , paramType ) ; newParam . setJSDocInfo ( patternParam . getJSDocInfo ( ) ) ; patternParam . ...
Replace a destructuring pattern parameter with a a temporary parameter name and add a new local variable declaration to the function assigning the temporary parameter to the pattern .
34,184
private void replacePattern ( NodeTraversal t , Node pattern , Node rhs , Node parent , Node nodeToDetach ) { checkArgument ( NodeUtil . isStatement ( nodeToDetach ) , nodeToDetach ) ; switch ( pattern . getToken ( ) ) { case ARRAY_PATTERN : replaceArrayPattern ( t , pattern , rhs , parent , nodeToDetach ) ; break ; ca...
Transpiles a destructuring pattern in a declaration or assignment to ES5
34,185
private Node objectPatternRestRHS ( Node objectPattern , Node rest , String restTempVarName , ArrayList < Node > statedProperties ) { checkArgument ( objectPattern . getLastChild ( ) == rest ) ; Node restTempVarModel = astFactory . createName ( restTempVarName , objectPattern . getJSType ( ) ) ; Node result = restTempV...
Convert rest of object destructuring lhs by making a clone and deleting any properties that were stated in the original object pattern .
34,186
private Node defaultValueHook ( Node getprop , Node defaultValue ) { Node undefined = astFactory . createName ( "undefined" , JSTypeNative . VOID_TYPE ) ; undefined . makeNonIndexable ( ) ; Node getpropClone = getprop . cloneTree ( ) . setJSType ( getprop . getJSType ( ) ) ; return astFactory . createHook ( astFactory ...
Helper for transpiling DEFAULT_VALUE trees .
34,187
public JSDocInfo cloneClassDoc ( ) { JSDocInfo other = new JSDocInfo ( ) ; other . info = this . info == null ? null : this . info . cloneClassDoc ( ) ; other . documentation = this . documentation ; other . visibility = this . visibility ; other . bitset = this . bitset ; other . type = cloneType ( this . type , false...
This is used to get all nodes + the description excluding the param nodes . Used to help in an ES5 to ES6 class converter only .
34,188
public JSDocInfo cloneConstructorDoc ( ) { JSDocInfo other = new JSDocInfo ( ) ; other . info = this . info == null ? null : this . info . cloneConstructorDoc ( ) ; other . documentation = this . documentation == null ? null : this . documentation . cloneConstructorDoc ( ) ; return other ; }
This is used to get only the parameter nodes . Used to help in an ES5 to ES6 converter class only .
34,189
boolean setDeprecationReason ( String reason ) { lazyInitInfo ( ) ; if ( info . deprecated != null ) { return false ; } info . deprecated = reason ; return true ; }
Sets the deprecation reason .
34,190
void addSuppression ( String suppression ) { lazyInitInfo ( ) ; if ( info . suppressions == null ) { info . suppressions = ImmutableSet . of ( suppression ) ; } else { info . suppressions = new ImmutableSet . Builder < String > ( ) . addAll ( info . suppressions ) . add ( suppression ) . build ( ) ; } }
Add a suppressed warning .
34,191
boolean setModifies ( Set < String > modifies ) { lazyInitInfo ( ) ; if ( info . modifies != null ) { return false ; } info . modifies = ImmutableSet . copyOf ( modifies ) ; return true ; }
Sets modifies values .
34,192
boolean documentVersion ( String version ) { if ( ! lazyInitDocumentation ( ) ) { return true ; } if ( documentation . version != null ) { return false ; } documentation . version = version ; return true ; }
Documents the version .
34,193
boolean declareThrows ( JSTypeExpression jsType ) { lazyInitInfo ( ) ; if ( info . thrownTypes == null ) { info . thrownTypes = new ArrayList < > ( ) ; } info . thrownTypes . add ( jsType ) ; return true ; }
Declares that the method throws a given type .
34,194
public JSTypeExpression getParameterType ( String parameter ) { if ( info == null || info . parameters == null ) { return null ; } return info . parameters . get ( parameter ) ; }
Gets the type of a given named parameter .
34,195
public boolean hasParameter ( String parameter ) { if ( info == null || info . parameters == null ) { return false ; } return info . parameters . containsKey ( parameter ) ; }
Returns whether the parameter is defined .
34,196
public Set < String > getParameterNames ( ) { if ( info == null || info . parameters == null ) { return ImmutableSet . of ( ) ; } return ImmutableSet . copyOf ( info . parameters . keySet ( ) ) ; }
Returns the set of names of the defined parameters . The iteration order of the returned set is the order in which parameters are defined in the JSDoc rather than the order in which the function declares them .
34,197
public String getParameterNameAt ( int index ) { if ( info == null || info . parameters == null ) { return null ; } if ( index >= info . parameters . size ( ) ) { return null ; } return Iterables . get ( info . parameters . keySet ( ) , index ) ; }
Returns the nth name in the defined parameters . The iteration order is the order in which parameters are defined in the JSDoc rather than the order in which the function declares them .
34,198
public List < JSTypeExpression > getThrownTypes ( ) { if ( info == null || info . thrownTypes == null ) { return ImmutableList . of ( ) ; } return Collections . unmodifiableList ( info . thrownTypes ) ; }
Returns the list of thrown types .
34,199
public String getThrowsDescriptionForType ( JSTypeExpression type ) { if ( documentation == null || documentation . throwsDescriptions == null ) { return null ; } return documentation . throwsDescriptions . get ( type ) ; }
Get the message for a given thrown type .