idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
3,000
|
public boolean removeExecutedTradeCallback ( final BitfinexExecutedTradeSymbol tradeSymbol , final BiConsumer < BitfinexExecutedTradeSymbol , BitfinexExecutedTrade > callback ) throws BitfinexClientException { return tradesCallbacks . removeCallback ( tradeSymbol , callback ) ; }
|
Remove a executed trade callback
|
3,001
|
public FutureOperation subscribeExecutedTrades ( final BitfinexExecutedTradeSymbol tradeSymbol ) { final FutureOperation future = new FutureOperation ( tradeSymbol ) ; pendingSubscribes . registerFuture ( future ) ; final SubscribeTradesCommand subscribeOrderbookCommand = new SubscribeTradesCommand ( tradeSymbol ) ; client . sendCommand ( subscribeOrderbookCommand ) ; return future ; }
|
Subscribe a executed trade channel
|
3,002
|
public FutureOperation unsubscribeExecutedTrades ( final BitfinexExecutedTradeSymbol tradeSymbol ) { final FutureOperation future = new FutureOperation ( tradeSymbol ) ; pendingUnsubscribes . registerFuture ( future ) ; final UnsubscribeChannelCommand command = new UnsubscribeChannelCommand ( tradeSymbol ) ; client . sendCommand ( command ) ; return future ; }
|
Unsubscribe a executed trades channel
|
3,003
|
public static void registerDefaults ( ) throws BitfinexClientException { try { final URL url = new URL ( SYMBOL_URL ) ; final String symbolJson = Resources . toString ( url , Charsets . UTF_8 ) ; final JSONArray jsonArray = new JSONArray ( symbolJson ) ; for ( int i = 0 ; i < jsonArray . length ( ) ; i ++ ) { final JSONObject currency = jsonArray . getJSONObject ( i ) ; final String pair = currency . getString ( "pair" ) ; if ( pair . length ( ) != 6 ) { throw new BitfinexClientException ( "The currency pair is not 6 chars long: " + pair ) ; } final double minOrderSize = currency . getDouble ( "minimum_order_size" ) ; final String currency1 = pair . substring ( 0 , 3 ) . toUpperCase ( ) ; final String currency2 = pair . substring ( 3 , 6 ) . toUpperCase ( ) ; register ( currency1 , currency2 , minOrderSize ) ; } } catch ( IOException e ) { throw new BitfinexClientException ( e ) ; } }
|
Load and register all known currencies
|
3,004
|
public static BitfinexCurrencyPair register ( final String currency , final String profitCurrency , final double minimalOrderSize ) { final String key = buildCacheKey ( currency , profitCurrency ) ; final BitfinexCurrencyPair newCurrency = new BitfinexCurrencyPair ( currency , profitCurrency , minimalOrderSize ) ; final BitfinexCurrencyPair oldCurrency = instances . putIfAbsent ( key , newCurrency ) ; if ( oldCurrency != null ) { throw new IllegalArgumentException ( "The currency " + key + " is already known" ) ; } return newCurrency ; }
|
Registers currency pair for use within library
|
3,005
|
public static BitfinexCurrencyPair of ( final String currency , final String profitCurrency ) { final String key = buildCacheKey ( currency , profitCurrency ) ; final BitfinexCurrencyPair bcp = instances . get ( key ) ; if ( bcp == null ) { throw new IllegalArgumentException ( "CurrencyPair is not registered: " + currency + " " + profitCurrency ) ; } return bcp ; }
|
Retrieves bitfinex currency pair
|
3,006
|
public static BitfinexCurrencyPair fromSymbolString ( final String symbolString ) { for ( final BitfinexCurrencyPair currency : BitfinexCurrencyPair . values ( ) ) { if ( currency . toBitfinexString ( ) . equalsIgnoreCase ( symbolString ) ) { return currency ; } } throw new IllegalArgumentException ( "Unable to find currency pair for: " + symbolString ) ; }
|
Construct from string
|
3,007
|
public void registerCallback ( final S symbol , final BiConsumer < S , T > callback ) throws BitfinexClientException { final List < BiConsumer < S , T > > callbackList = callbacks . computeIfAbsent ( symbol , ( k ) -> new CopyOnWriteArrayList < > ( ) ) ; callbackList . add ( callback ) ; }
|
Register a new callback
|
3,008
|
public boolean removeCallback ( final S symbol , final BiConsumer < S , T > callback ) throws BitfinexClientException { final List < BiConsumer < S , T > > callbackList = callbacks . get ( symbol ) ; if ( callbackList == null ) { throw new BitfinexClientException ( "Unknown ticker string: " + symbol ) ; } return callbackList . remove ( callback ) ; }
|
Remove the a callback
|
3,009
|
public void handleEventsCollection ( final S symbol , final Collection < T > elements ) { final List < BiConsumer < S , T > > callbackList = callbacks . get ( symbol ) ; if ( callbackList == null ) { return ; } if ( callbackList . isEmpty ( ) ) { return ; } for ( final T element : elements ) { callbackList . forEach ( ( c ) -> { c . accept ( symbol , element ) ; } ) ; } }
|
Process a list with event
|
3,010
|
public static BitfinexInstrument build ( final String symbolString ) { if ( symbolString . startsWith ( "t" ) ) { return BitfinexCurrencyPair . fromSymbolString ( symbolString ) ; } else if ( symbolString . startsWith ( "f" ) ) { return BitfinexFundingCurrency . fromSymbolString ( symbolString ) ; } else { throw new IllegalArgumentException ( "Unable to build currency for symbol string: " + symbolString ) ; } }
|
Build the bitfinex currency from sybol string
|
3,011
|
public void registerOrderbookCallback ( final BitfinexOrderBookSymbol orderbookConfiguration , final BiConsumer < BitfinexOrderBookSymbol , BitfinexOrderBookEntry > callback ) throws BitfinexClientException { channelCallbacks . registerCallback ( orderbookConfiguration , callback ) ; }
|
Register a new trading orderbook callback
|
3,012
|
public void connect ( ) throws DeploymentException , IOException , InterruptedException { final WebSocketContainer container = ContainerProvider . getWebSocketContainer ( ) ; connectLatch = new CountDownLatch ( 1 ) ; this . userSession = container . connectToServer ( this , endpointURI ) ; connectLatch . await ( 15 , TimeUnit . SECONDS ) ; }
|
Open a new connection and wait until connection is ready
|
3,013
|
public void sendMessage ( final String message ) { if ( userSession == null ) { logger . error ( "Unable to send message, user session is null" ) ; return ; } if ( userSession . getAsyncRemote ( ) == null ) { logger . error ( "Unable to send message, async remote is null" ) ; return ; } userSession . getAsyncRemote ( ) . sendText ( message ) ; }
|
Send a new message to the server
|
3,014
|
public void auditPackage ( final JSONArray jsonArray ) { final long channelId = jsonArray . getInt ( 0 ) ; final boolean isHeartbeat = jsonArray . optString ( 1 , "" ) . equals ( "hb" ) ; if ( channelId == 0 ) { if ( isHeartbeat ) { checkPublicSequence ( jsonArray ) ; } else { checkPublicAndPrivateSequence ( jsonArray ) ; } } else { checkPublicSequence ( jsonArray ) ; } }
|
Audit the package
|
3,015
|
private void checkPublicAndPrivateSequence ( final JSONArray jsonArray ) { final long nextPublicSequnceNumber = jsonArray . getLong ( jsonArray . length ( ) - 2 ) ; final long nextPrivateSequnceNumber = jsonArray . getLong ( jsonArray . length ( ) - 1 ) ; auditPublicSequence ( nextPublicSequnceNumber ) ; auditPrivateSequence ( nextPrivateSequnceNumber ) ; }
|
Check the public and the private sequence
|
3,016
|
private void checkPublicSequence ( final JSONArray jsonArray ) { final long nextPublicSequnceNumber = jsonArray . getLong ( jsonArray . length ( ) - 1 ) ; auditPublicSequence ( nextPublicSequnceNumber ) ; }
|
Check the public sequence
|
3,017
|
private void auditPublicSequence ( final long nextPublicSequnceNumber ) { if ( publicSequence == - 1 ) { publicSequence = nextPublicSequnceNumber ; return ; } if ( publicSequence + 1 != nextPublicSequnceNumber ) { final String errorMessage = String . format ( "Got %d as next public sequence number, expected %d", publicSequence + 1 , nextPublicSequnceNumber ) ; handleError ( errorMessage ) ; return ; } publicSequence ++ ; }
|
Audit the public sequence
|
3,018
|
private void auditPrivateSequence ( final long nextPrivateSequnceNumber ) { if ( privateSequence == - 1 ) { privateSequence = nextPrivateSequnceNumber ; return ; } if ( privateSequence + 1 != nextPrivateSequnceNumber ) { final String errorMessage = String . format ( "Got %d as next private sequence number, expected %d", privateSequence + 1 , nextPrivateSequnceNumber ) ; handleError ( errorMessage ) ; return ; } privateSequence ++ ; }
|
Audit the private sequence
|
3,019
|
private void handleError ( final String errorMessage ) { failed = true ; switch ( errorPolicy ) { case LOG_ONLY : logger . error ( errorMessage ) ; break ; case RUNTIME_EXCEPTION : throw new RuntimeException ( errorMessage ) ; default : logger . error ( "Got error {} but unkown error policy {}" , errorMessage , errorPolicy ) ; break ; } }
|
Handle the sequence number error
|
3,020
|
public static BitfinexOrderBookSymbol fromJSON ( final JSONObject jsonObject ) { BitfinexCurrencyPair symbol = BitfinexCurrencyPair . fromSymbolString ( jsonObject . getString ( "symbol" ) ) ; Precision prec = Precision . valueOf ( jsonObject . getString ( "prec" ) ) ; Frequency freq = null ; Integer len = null ; if ( prec != Precision . R0 ) { freq = Frequency . valueOf ( jsonObject . getString ( "freq" ) ) ; len = jsonObject . getInt ( "len" ) ; } return new BitfinexOrderBookSymbol ( symbol , prec , freq , len ) ; }
|
Build from JSON Array
|
3,021
|
public static LocalCall < List < Record > > records ( RecordType type ) { Map < String , Object > args = new LinkedHashMap < > ( ) ; if ( type != null ) { args . put ( "rec_type" , type . getType ( ) ) ; } args . put ( "clean" , false ) ; return new LocalCall < > ( "smbios.records" , Optional . empty ( ) , Optional . of ( args ) , new TypeToken < List < Record > > ( ) { } ) ; }
|
smbios . records
|
3,022
|
public static LocalCall < String > get ( String key ) { return new LocalCall < > ( "config.get" , Optional . of ( Arrays . asList ( key ) ) , Optional . empty ( ) , new TypeToken < String > ( ) { } ) ; }
|
Returns a configuration parameter .
|
3,023
|
public static ParameterizedType parameterizedType ( Type ownerType , Type rawType , Type ... typeArguments ) { return newParameterizedTypeWithOwner ( ownerType , rawType , typeArguments ) ; }
|
Helper for constructing parameterized types .
|
3,024
|
public CompletionStage < WheelAsyncResult < R > > callAsync ( final SaltClient client , AuthMethod auth ) { return client . call ( this , Client . WHEEL_ASYNC , Optional . empty ( ) , Collections . emptyMap ( ) , new TypeToken < Return < List < WheelAsyncResult < R > > > > ( ) { } , auth ) . thenApply ( wrapper -> { WheelAsyncResult < R > result = wrapper . getResult ( ) . get ( 0 ) ; result . setType ( getReturnType ( ) ) ; return result ; } ) ; }
|
Calls a wheel module function on the master asynchronously and returns information about the scheduled job that can be used to query the result . Authentication is done with the token therefore you have to login prior to using this function .
|
3,025
|
public CompletionStage < WheelResult < Result < R > > > callSync ( final SaltClient client , AuthMethod auth ) { Type xor = parameterizedType ( null , Result . class , getReturnType ( ) . getType ( ) ) ; Type wheelResult = parameterizedType ( null , WheelResult . class , xor ) ; Type listType = parameterizedType ( null , List . class , wheelResult ) ; Type wrapperType = parameterizedType ( null , Return . class , listType ) ; @ SuppressWarnings ( "unchecked" ) CompletionStage < WheelResult < Result < R > > > wheelResultCompletionStage = client . call ( this , Client . WHEEL , Optional . empty ( ) , Collections . emptyMap ( ) , ( TypeToken < Return < List < WheelResult < Result < R > > > > > ) TypeToken . get ( wrapperType ) , auth ) . thenApply ( wrapper -> wrapper . getResult ( ) . get ( 0 ) ) ; return wheelResultCompletionStage ; }
|
Calls a wheel module function on the master and synchronously waits for the result . Authentication is done with the token therefore you have to login prior to using this function .
|
3,026
|
public static void mapConfigPropsToArgs ( SaltSSHConfig cfg , Map < String , Object > props ) { cfg . getExtraFilerefs ( ) . ifPresent ( v -> props . put ( "extra_filerefs" , v ) ) ; cfg . getIdentitiesOnly ( ) . ifPresent ( v -> props . put ( "ssh_identities_only" , v ) ) ; cfg . getIgnoreHostKeys ( ) . ifPresent ( v -> props . put ( "ignore_host_keys" , v ) ) ; cfg . getKeyDeploy ( ) . ifPresent ( v -> props . put ( "ssh_key_deploy" , v ) ) ; cfg . getNoHostKeys ( ) . ifPresent ( v -> props . put ( "no_host_keys" , v ) ) ; cfg . getPasswd ( ) . ifPresent ( v -> props . put ( "ssh_passwd" , v ) ) ; cfg . getPriv ( ) . ifPresent ( v -> props . put ( "ssh_priv" , v ) ) ; cfg . getRandomThinDir ( ) . ifPresent ( v -> props . put ( "rand_thin_dir" , v ) ) ; cfg . getRefreshCache ( ) . ifPresent ( v -> props . put ( "refresh_cache" , v ) ) ; cfg . getRemotePortForwards ( ) . ifPresent ( v -> props . put ( "ssh_remote_port_forwards" , v ) ) ; cfg . getRoster ( ) . ifPresent ( v -> props . put ( "roster" , v ) ) ; cfg . getRosterFile ( ) . ifPresent ( v -> props . put ( "roster_file" , v ) ) ; cfg . getScanPorts ( ) . ifPresent ( v -> props . put ( "ssh_scan_ports" , v ) ) ; cfg . getScanTimeout ( ) . ifPresent ( v -> props . put ( "ssh_scan_timeout" , v ) ) ; cfg . getSudo ( ) . ifPresent ( v -> props . put ( "ssh_sudo" , v ) ) ; cfg . getSSHMaxProcs ( ) . ifPresent ( v -> props . put ( "ssh_max_procs" , v ) ) ; cfg . getUser ( ) . ifPresent ( v -> props . put ( "ssh_user" , v ) ) ; cfg . getWipe ( ) . ifPresent ( v -> props . put ( "ssh_wipe" , v ) ) ; }
|
Maps config parameters to salt - ssh rest arguments
|
3,027
|
public void onMessage ( String partialMessage , boolean last ) throws MessageTooBigException { if ( partialMessage . length ( ) > maxMessageLength - messageBuffer . length ( ) ) { throw new MessageTooBigException ( maxMessageLength ) ; } if ( last ) { String message ; if ( messageBuffer . length ( ) == 0 ) { message = partialMessage ; } else { messageBuffer . append ( partialMessage ) ; message = messageBuffer . toString ( ) ; messageBuffer . setLength ( defaultBufferSize ) ; messageBuffer . trimToSize ( ) ; messageBuffer . setLength ( 0 ) ; } if ( ! message . equals ( "server received message" ) ) { Event event = JsonParser . EVENTS . parse ( message . substring ( 6 ) ) ; notifyListeners ( event ) ; } } else { messageBuffer . append ( partialMessage ) ; } }
|
Notify listeners on each event received on the websocket and buffer partial messages .
|
3,028
|
public void onClose ( Session session , CloseReason closeReason ) { this . session = session ; clearListeners ( closeReason . getCloseCode ( ) . getCode ( ) , closeReason . getReasonPhrase ( ) ) ; }
|
On closing the websocket refresh the session and notify all subscribed listeners . Upon exit from this method all subscribed listeners will be removed .
|
3,029
|
private Map < String , Object > readObjectArgument ( JsonReader jsonReader ) throws IOException { Map < String , Object > arg = new LinkedHashMap < > ( ) ; jsonReader . beginObject ( ) ; while ( jsonReader . hasNext ( ) ) { arg . put ( jsonReader . nextName ( ) , JsonParser . GSON . fromJson ( jsonReader , Object . class ) ) ; } jsonReader . endObject ( ) ; return arg ; }
|
Reads a generic object argument from the given JsonReader .
|
3,030
|
public < R > R getData ( TypeToken < R > type ) { return GSON . fromJson ( data , type . getType ( ) ) ; }
|
Return the event data parsed into the given type .
|
3,031
|
public Map < String , Object > getData ( ) { TypeToken < Map < String , Object > > typeToken = new TypeToken < Map < String , Object > > ( ) { } ; return getData ( typeToken ) ; }
|
Return event data as Map
|
3,032
|
public static LocalCall < Result > add ( String name , LocalCall < ? > call , LocalDateTime once , Map < String , ? > metadata ) { LinkedHashMap < String , Object > args = new LinkedHashMap < > ( ) ; Map < String , Object > payload = call . getPayload ( ) ; args . put ( "function" , payload . get ( "fun" ) ) ; args . put ( "job_args" , payload . get ( "arg" ) ) ; args . put ( "job_kwargs" , payload . get ( "kwarg" ) ) ; args . put ( "name" , name ) ; args . put ( "once" , once . format ( DateTimeFormatter . ofPattern ( "yyyy-MM-dd'T'HH:mm:ss" ) ) ) ; args . put ( "metadata" , metadata ) ; return new LocalCall < > ( "schedule.add" , Optional . empty ( ) , Optional . of ( args ) , new TypeToken < Result > ( ) { } ) ; }
|
Schedule a salt call for later execution on the minion
|
3,033
|
private < L , R > TypeAdapter < Xor < L , R > > xorAdapter ( TypeAdapter < L > leftAdapter , TypeAdapter < R > rightAdapter ) { return new TypeAdapter < Xor < L , R > > ( ) { public Xor < L , R > read ( JsonReader in ) throws IOException { JsonElement json = TypeAdapters . JSON_ELEMENT . read ( in ) ; try { R value = rightAdapter . fromJsonTree ( json ) ; return Xor . right ( value ) ; } catch ( Throwable e ) { L value = leftAdapter . fromJsonTree ( json ) ; return Xor . left ( value ) ; } } public void write ( JsonWriter out , Xor < L , R > xor ) throws IOException { throw new JsonParseException ( "Writing Xor is not supported" ) ; } } ; }
|
Creates a generic Xor adapter by combining two other adapters - one for each side of the Xor type . It will first try to parse incoming JSON data as the right type and if that does not succeed it will try again with the left type .
|
3,034
|
private < R > TypeAdapter < Xor < SaltError , R > > errorAdapter ( TypeAdapter < R > innerAdapter ) { return new TypeAdapter < Xor < SaltError , R > > ( ) { public Xor < SaltError , R > read ( JsonReader in ) throws IOException { JsonElement json = TypeAdapters . JSON_ELEMENT . read ( in ) ; try { R value = innerAdapter . fromJsonTree ( json ) ; return Xor . right ( value ) ; } catch ( Throwable e ) { Optional < SaltError > saltError = extractErrorString ( json ) . flatMap ( SaltErrorUtils :: deriveError ) ; return Xor . left ( saltError . orElse ( new JsonParsingError ( json , e ) ) ) ; } } private Optional < String > extractErrorString ( JsonElement json ) { if ( json . isJsonPrimitive ( ) && json . getAsJsonPrimitive ( ) . isString ( ) ) { return Optional . of ( json . getAsJsonPrimitive ( ) . getAsString ( ) ) ; } return Optional . empty ( ) ; } public void write ( JsonWriter out , Xor < SaltError , R > xor ) throws IOException { throw new JsonParseException ( "Writing Xor is not supported" ) ; } } ; }
|
Creates a Xor adapter specifically for the case in which the left side is a SaltError . This is used to catch any Salt - side or JSON parsing errors .
|
3,035
|
private < T > CompletionStage < T > request ( URI uri , Map < String , String > headers , String data , JsonParser < T > parser ) { return executeRequest ( httpClient , prepareRequest ( uri , headers , data ) , parser ) ; }
|
Perform HTTP request and parse the result into a given result type .
|
3,036
|
private < T > HttpUriRequest prepareRequest ( URI uri , Map < String , String > headers , String jsonData ) { HttpUriRequest httpRequest ; if ( jsonData != null ) { HttpPost httpPost = new HttpPost ( uri ) ; httpPost . setEntity ( new StringEntity ( jsonData , ContentType . APPLICATION_JSON ) ) ; httpRequest = httpPost ; } else { httpRequest = new HttpGet ( uri ) ; } httpRequest . addHeader ( HttpHeaders . ACCEPT , "application/json" ) ; headers . forEach ( httpRequest :: addHeader ) ; return httpRequest ; }
|
Prepares the HTTP request object creating a POST or GET request depending on if data is supplied or not .
|
3,037
|
private < T > CompletionStage < T > executeRequest ( HttpAsyncClient httpClient , HttpUriRequest httpRequest , JsonParser < T > parser ) { CompletableFuture < T > future = new CompletableFuture < > ( ) ; httpClient . execute ( httpRequest , new FutureCallback < HttpResponse > ( ) { public void failed ( Exception e ) { future . completeExceptionally ( e ) ; } public void completed ( HttpResponse response ) { int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( statusCode == HttpStatus . SC_OK || statusCode == HttpStatus . SC_ACCEPTED ) { try { T result = parser . parse ( response . getEntity ( ) . getContent ( ) ) ; future . complete ( result ) ; } catch ( Exception e ) { future . completeExceptionally ( e ) ; } } else { future . completeExceptionally ( createSaltException ( statusCode ) ) ; } } public void cancelled ( ) { future . cancel ( false ) ; } } ) ; return future ; }
|
Executes a prepared HTTP request using the given client .
|
3,038
|
public < R > R getData ( TypeToken < R > dataType ) { return GSON . fromJson ( data , dataType . getType ( ) ) ; }
|
Return this event s data .
|
3,039
|
public Map < String , Object > getData ( ) { TypeToken < Map < String , Object > > typeToken = new TypeToken < Map < String , Object > > ( ) { } ; return GSON . fromJson ( data , typeToken . getType ( ) ) ; }
|
Return this event s data as a Map
|
3,040
|
public static LocalCall < String > chown ( String path , String user , String group ) { Map < String , String > args = new LinkedHashMap < > ( ) ; args . put ( "path" , path ) ; args . put ( "user" , user ) ; args . put ( "group" , group ) ; return new LocalCall < > ( "file.chown" , Optional . empty ( ) , Optional . of ( args ) , new TypeToken < String > ( ) { } ) ; }
|
Chown a file
|
3,041
|
public static LocalCall < String > chmod ( String path , String mode ) { return new LocalCall < > ( "file.set_mode" , Optional . of ( Arrays . asList ( path , mode ) ) , Optional . empty ( ) , new TypeToken < String > ( ) { } ) ; }
|
Set the mode of a file
|
3,042
|
public static LocalCall < Boolean > copy ( String src , String dst , boolean recurse , boolean removeExisting ) { Map < String , Object > args = new LinkedHashMap < > ( ) ; args . put ( "src" , src ) ; args . put ( "dst" , dst ) ; args . put ( "recurse" , recurse ) ; args . put ( "remove_existing" , removeExisting ) ; return new LocalCall < > ( "file.copy" , Optional . empty ( ) , Optional . of ( args ) , new TypeToken < Boolean > ( ) { } ) ; }
|
Copy a file or directory from src to dst
|
3,043
|
public static LocalCall < Result > move ( String src , String dst ) { Map < String , Object > args = new LinkedHashMap < > ( ) ; args . put ( "src" , src ) ; args . put ( "dst" , dst ) ; return new LocalCall < > ( "file.move" , Optional . empty ( ) , Optional . of ( args ) , new TypeToken < Result > ( ) { } ) ; }
|
Move a file or directory from src to dst
|
3,044
|
public static LocalCall < String > getHash ( String path , HashType form ) { return getHash ( path , Optional . of ( form ) , Optional . empty ( ) ) ; }
|
Get the hash sum of a file
|
3,045
|
public static LocalCall < String > getUid ( String path , boolean followSymlinks ) { Map < String , Object > args = new LinkedHashMap < > ( ) ; args . put ( "path" , path ) ; args . put ( "follow_symlinks" , followSymlinks ) ; return new LocalCall < > ( "file.get_uid" , Optional . empty ( ) , Optional . of ( args ) , new TypeToken < String > ( ) { } ) ; }
|
Return the id of the user that owns a given file
|
3,046
|
public static LocalCall < List < String > > readdir ( String path ) { return new LocalCall < > ( "file.readdir" , Optional . of ( Collections . singletonList ( path ) ) , Optional . empty ( ) , new TypeToken < List < String > > ( ) { } ) ; }
|
Returns a list containing the contents of a directory
|
3,047
|
public static LocalCall < Map < String , List < Xor < String , Info > > > > listPkgs ( List < String > attributes ) { LinkedHashMap < String , Object > args = new LinkedHashMap < > ( ) ; args . put ( "attr" , attributes ) ; return new LocalCall < > ( "pkg.list_pkgs" , Optional . empty ( ) , Optional . of ( args ) , new TypeToken < Map < String , List < Xor < String , Info > > > > ( ) { } ) ; }
|
Call pkg . list_pkgs
|
3,048
|
public static LocalCall < Map < String , Xor < Info , List < Info > > > > infoInstalledAllVersions ( List < String > attributes , boolean reportErrors , String ... packages ) { LinkedHashMap < String , Object > kwargs = new LinkedHashMap < > ( ) ; kwargs . put ( "attr" , attributes . stream ( ) . collect ( Collectors . joining ( "," ) ) ) ; kwargs . put ( "all_versions" , true ) ; if ( reportErrors ) { kwargs . put ( "errors" , "report" ) ; } return new LocalCall < > ( "pkg.info_installed" , Optional . of ( Arrays . asList ( packages ) ) , Optional . of ( kwargs ) , new TypeToken < Map < String , Xor < Info , List < Info > > > > ( ) { } ) ; }
|
Call pkg . info_installed API .
|
3,049
|
public T parse ( InputStream inputStream ) { Reader inputStreamReader = new InputStreamReader ( inputStream ) ; Reader streamReader = new BufferedReader ( inputStreamReader ) ; return gson . fromJson ( streamReader , type . getType ( ) ) ; }
|
Parses a Json response that has a direct representation as a Java class .
|
3,050
|
public static CloseableHttpAsyncClient defaultClient ( ) { RequestConfig requestConfig = RequestConfig . custom ( ) . setConnectionRequestTimeout ( 0 ) . setConnectTimeout ( 10000 ) . setSocketTimeout ( 20000 ) . setCookieSpec ( CookieSpecs . STANDARD ) . build ( ) ; HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients . custom ( ) ; httpClientBuilder . setDefaultRequestConfig ( requestConfig ) ; CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder . build ( ) ; asyncHttpClient . start ( ) ; return asyncHttpClient ; }
|
Creates a simple default http client
|
3,051
|
public static Optional < SaltVersion > parse ( String versionString ) { Matcher matcher = SALT_VERSION_REGEX . matcher ( versionString ) ; if ( matcher . matches ( ) ) { int year = Integer . parseInt ( matcher . group ( 1 ) ) ; int month = Integer . parseInt ( matcher . group ( 2 ) ) ; int bugfix = Integer . parseInt ( matcher . group ( 3 ) ) ; Optional < Integer > rc = Optional . ofNullable ( matcher . group ( 5 ) ) . map ( Integer :: parseInt ) ; return Optional . of ( new SaltVersion ( year , month , bugfix , rc ) ) ; } else { return Optional . empty ( ) ; } }
|
Parses a salt version string
|
3,052
|
protected void clearListeners ( int code , String phrase ) { listeners . forEach ( listener -> listener . eventStreamClosed ( code , phrase ) ) ; listeners . clear ( ) ; }
|
Removes all listeners .
|
3,053
|
public < R > Change < R > map ( Function < T , R > fn ) { return new Change < > ( fn . apply ( getOldValue ( ) ) , fn . apply ( getNewValue ( ) ) ) ; }
|
Applies a mapping function to both the old and the new value wrapping the result in a new Change .
|
3,054
|
public CompletionStage < Map < String , Result < R > > > callSync ( final SaltClient client , Target < ? > target , AuthMethod auth ) { return callSyncHelperNonBlock ( client , target , auth , Optional . empty ( ) ) . thenApply ( r -> r . get ( 0 ) ) ; }
|
Calls a execution module function on the given target and synchronously waits for the result . Authentication is done with the token therefore you have to login prior to using this function .
|
3,055
|
public CompletionStage < List < Map < String , Result < R > > > > callSync ( final SaltClient client , Target < ? > target , AuthMethod auth , Optional < Batch > batch ) { return callSyncHelperNonBlock ( client , target , auth , batch ) ; }
|
Calls a execution module function on the given target with batching and synchronously waits for the result . Authentication is done with the token therefore you have to login prior to using this function .
|
3,056
|
private List < Map < String , Result < R > > > handleRetcodeBatchingHack ( List < Map < String , Result < R > > > list , Type xor ) { return list . stream ( ) . map ( m -> { return m . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( e -> e . getKey ( ) , e -> { return e . getValue ( ) . fold ( err -> { return err . < Result < R > > fold ( Result :: error , Result :: error , parsingError -> { if ( parsingError . getJson ( ) . isJsonObject ( ) ) { JsonObject jsonObject = parsingError . getJson ( ) . getAsJsonObject ( ) ; if ( jsonObject . has ( "retcode" ) ) { jsonObject . remove ( "retcode" ) ; return JsonParser . GSON . fromJson ( jsonObject , xor ) ; } else { return Result . error ( parsingError ) ; } } else { return Result . error ( parsingError ) ; } } , Result :: error ) ; } , Result :: success ) ; } ) ) ; } ) . collect ( Collectors . toList ( ) ) ; }
|
specific to how a function is dispatched .
|
3,057
|
private CompletionStage < List < Map < String , Result < R > > > > callSyncHelperNonBlock ( final SaltClient client , Target < ? > target , AuthMethod auth , Optional < Batch > batch ) { Map < String , Object > customArgs = new HashMap < > ( ) ; batch . ifPresent ( v -> customArgs . putAll ( v . getParams ( ) ) ) ; Client clientType = batch . isPresent ( ) ? Client . LOCAL_BATCH : Client . LOCAL ; Type xor = parameterizedType ( null , Result . class , getReturnType ( ) . getType ( ) ) ; Type map = parameterizedType ( null , Map . class , String . class , xor ) ; Type listType = parameterizedType ( null , List . class , map ) ; Type wrapperType = parameterizedType ( null , Return . class , listType ) ; TypeToken < Return < List < Map < String , Result < R > > > > > typeToken = ( TypeToken < Return < List < Map < String , Result < R > > > > > ) TypeToken . get ( wrapperType ) ; if ( batch . isPresent ( ) ) { return client . call ( this , clientType , Optional . of ( target ) , customArgs , typeToken , auth ) . thenApply ( Return :: getResult ) . thenApply ( results -> handleRetcodeBatchingHack ( results , xor ) ) ; } else { return client . call ( this , clientType , Optional . of ( target ) , customArgs , typeToken , auth ) . thenApply ( Return :: getResult ) ; } }
|
Helper to call an execution module function on the given target for batched or unbatched while also providing an option to use the given credentials or to use a prior created token . Synchronously waits for the result .
|
3,058
|
public CompletionStage < Map < String , Result < SSHResult < R > > > > callSyncSSH ( final SaltClient client , SSHTarget < ? > target , SaltSSHConfig cfg , AuthMethod auth ) { Map < String , Object > args = new HashMap < > ( ) ; args . putAll ( getPayload ( ) ) ; args . putAll ( target . getProps ( ) ) ; SaltSSHUtils . mapConfigPropsToArgs ( cfg , args ) ; Type xor = parameterizedType ( null , Result . class , parameterizedType ( null , SSHResult . class , getReturnType ( ) . getType ( ) ) ) ; Type map = parameterizedType ( null , Map . class , String . class , xor ) ; Type listType = parameterizedType ( null , List . class , map ) ; Type wrapperType = parameterizedType ( null , Return . class , listType ) ; return client . call ( this , Client . SSH , Optional . of ( target ) , args , ( TypeToken < Return < List < Map < String , Result < SSHResult < R > > > > > > ) TypeToken . get ( wrapperType ) , auth ) . thenApply ( wrapper -> wrapper . getResult ( ) . get ( 0 ) ) ; }
|
Call an execution module function on the given target via salt - ssh and synchronously wait for the result .
|
3,059
|
public long getPolyRefBase ( MeshTile tile ) { if ( tile == null ) { return 0 ; } int it = tile . index ; return encodePolyId ( tile . salt , it , 0 ) ; }
|
Gets the polygon reference for the tile s base polygon .
|
3,060
|
public static long encodePolyId ( int salt , int it , int ip ) { return ( ( ( long ) salt ) << ( DT_POLY_BITS + DT_TILE_BITS ) ) | ( ( long ) it << DT_POLY_BITS ) | ip ; }
|
Derives a standard polygon reference .
|
3,061
|
public int [ ] calcTileLoc ( float [ ] pos ) { int tx = ( int ) Math . floor ( ( pos [ 0 ] - m_orig [ 0 ] ) / m_tileWidth ) ; int ty = ( int ) Math . floor ( ( pos [ 2 ] - m_orig [ 2 ] ) / m_tileHeight ) ; return new int [ ] { tx , ty } ; }
|
Calculates the tile grid location for the specified world position .
|
3,062
|
void baseOffMeshLinks ( MeshTile tile ) { if ( tile == null ) { return ; } long base = getPolyRefBase ( tile ) ; for ( int i = 0 ; i < tile . data . header . offMeshConCount ; ++ i ) { OffMeshConnection con = tile . data . offMeshCons [ i ] ; Poly poly = tile . data . polys [ con . poly ] ; float [ ] ext = new float [ ] { con . rad , tile . data . header . walkableClimb , con . rad } ; FindNearestPolyResult nearestPoly = findNearestPolyInTile ( tile , con . pos , ext ) ; long ref = nearestPoly . getNearestRef ( ) ; if ( ref == 0 ) { continue ; } float [ ] p = con . pos ; float [ ] nearestPt = nearestPoly . getNearestPos ( ) ; if ( sqr ( nearestPt [ 0 ] - p [ 0 ] ) + sqr ( nearestPt [ 2 ] - p [ 2 ] ) > sqr ( con . rad ) ) { continue ; } tile . data . verts [ poly . verts [ 0 ] * 3 ] = nearestPt [ 0 ] ; tile . data . verts [ poly . verts [ 0 ] * 3 + 1 ] = nearestPt [ 1 ] ; tile . data . verts [ poly . verts [ 0 ] * 3 + 2 ] = nearestPt [ 2 ] ; int idx = allocLink ( tile ) ; Link link = tile . links . get ( idx ) ; link . ref = ref ; link . edge = 0 ; link . side = 0xff ; link . bmin = link . bmax = 0 ; link . next = poly . firstLink ; poly . firstLink = idx ; int tidx = allocLink ( tile ) ; int landPolyIdx = decodePolyIdPoly ( ref ) ; Poly landPoly = tile . data . polys [ landPolyIdx ] ; link = tile . links . get ( tidx ) ; link . ref = base | ( con . poly ) ; link . edge = 0xff ; link . side = 0xff ; link . bmin = link . bmax = 0 ; link . next = landPoly . firstLink ; landPoly . firstLink = tidx ; } }
|
Builds internal polygons links for a tile .
|
3,063
|
float [ ] closestPointOnDetailEdges ( MeshTile tile , Poly poly , float [ ] pos , boolean onlyBoundary ) { int ANY_BOUNDARY_EDGE = ( DT_DETAIL_EDGE_BOUNDARY << 0 ) | ( DT_DETAIL_EDGE_BOUNDARY << 2 ) | ( DT_DETAIL_EDGE_BOUNDARY << 4 ) ; int ip = poly . index ; PolyDetail pd = tile . data . detailMeshes [ ip ] ; float dmin = Float . MAX_VALUE ; float tmin = 0 ; float [ ] pmin = null ; float [ ] pmax = null ; for ( int i = 0 ; i < pd . triCount ; i ++ ) { int ti = ( pd . triBase + i ) * 4 ; int [ ] tris = tile . data . detailTris ; if ( onlyBoundary && ( tris [ ti + 3 ] & ANY_BOUNDARY_EDGE ) == 0 ) { continue ; } float [ ] [ ] v = new float [ 3 ] [ ] ; for ( int j = 0 ; j < 3 ; ++ j ) { if ( tris [ ti + j ] < poly . vertCount ) { int index = poly . verts [ tris [ ti + j ] ] * 3 ; v [ j ] = new float [ ] { tile . data . verts [ index ] , tile . data . verts [ index + 1 ] , tile . data . verts [ index + 2 ] } ; } else { int index = ( pd . vertBase + ( tris [ ti + j ] - poly . vertCount ) ) * 3 ; v [ j ] = new float [ ] { tile . data . detailVerts [ index ] , tile . data . detailVerts [ index + 1 ] , tile . data . detailVerts [ index + 2 ] } ; } } for ( int k = 0 , j = 2 ; k < 3 ; j = k ++ ) { if ( ( getDetailTriEdgeFlags ( tris [ 3 ] , j ) & DT_DETAIL_EDGE_BOUNDARY ) == 0 && ( onlyBoundary || tris [ j ] < tris [ k ] ) ) { continue ; } Tupple2 < Float , Float > dt = distancePtSegSqr2D ( pos , v [ j ] , v [ k ] ) ; float d = dt . first ; float t = dt . second ; if ( d < dmin ) { dmin = d ; tmin = t ; pmin = v [ j ] ; pmax = v [ k ] ; } } } return vLerp ( pmin , pmax , tmin ) ; }
|
Returns closest point on polygon .
|
3,064
|
List < Integer > convexhull ( List < Float > pts ) { int npts = pts . size ( ) / 3 ; List < Integer > out = new ArrayList < > ( ) ; int hull = 0 ; for ( int i = 1 ; i < npts ; ++ i ) { float [ ] a = new float [ ] { pts . get ( i * 3 ) , pts . get ( i * 3 + 1 ) , pts . get ( i * 3 + 2 ) } ; float [ ] b = new float [ ] { pts . get ( hull * 3 ) , pts . get ( hull * 3 + 1 ) , pts . get ( hull * 3 + 2 ) } ; if ( cmppt ( a , b ) ) { hull = i ; } } int endpt = 0 ; do { out . add ( hull ) ; endpt = 0 ; for ( int j = 1 ; j < npts ; ++ j ) { float [ ] a = new float [ ] { pts . get ( hull * 3 ) , pts . get ( hull * 3 + 1 ) , pts . get ( hull * 3 + 2 ) } ; float [ ] b = new float [ ] { pts . get ( endpt * 3 ) , pts . get ( endpt * 3 + 1 ) , pts . get ( endpt * 3 + 2 ) } ; float [ ] c = new float [ ] { pts . get ( j * 3 ) , pts . get ( j * 3 + 1 ) , pts . get ( j * 3 + 2 ) } ; if ( hull == endpt || left ( a , b , c ) ) { endpt = j ; } } hull = endpt ; } while ( endpt != out . get ( 0 ) ) ; return out ; }
|
returns number of points on hull .
|
3,065
|
boolean cmppt ( float [ ] a , float [ ] b ) { if ( a [ 0 ] < b [ 0 ] ) { return true ; } if ( a [ 0 ] > b [ 0 ] ) { return false ; } if ( a [ 2 ] < b [ 2 ] ) { return true ; } if ( a [ 2 ] > b [ 2 ] ) { return false ; } return false ; }
|
Returns true if a is more lower - left than b .
|
3,066
|
boolean left ( float [ ] a , float [ ] b , float [ ] c ) { float u1 = b [ 0 ] - a [ 0 ] ; float v1 = b [ 2 ] - a [ 2 ] ; float u2 = c [ 0 ] - a [ 0 ] ; float v2 = c [ 2 ] - a [ 2 ] ; return u1 * v2 - v1 * u2 < 0 ; }
|
Returns true if c is left of line a - b .
|
3,067
|
public void reset ( long ref , float [ ] pos ) { m_path . clear ( ) ; m_path . add ( ref ) ; vCopy ( m_pos , pos ) ; vCopy ( m_target , pos ) ; }
|
Resets the path corridor to the specified position .
|
3,068
|
public void optimizePathVisibility ( float [ ] next , float pathOptimizationRange , NavMeshQuery navquery , QueryFilter filter ) { float dist = vDist2D ( m_pos , next ) ; if ( dist < 0.01f ) { return ; } dist = Math . min ( dist + 0.01f , pathOptimizationRange ) ; float [ ] delta = vSub ( next , m_pos ) ; float [ ] goal = vMad ( m_pos , delta , pathOptimizationRange / dist ) ; Result < RaycastHit > rc = navquery . raycast ( m_path . get ( 0 ) , m_pos , goal , filter , 0 , 0 ) ; if ( rc . succeeded ( ) ) { if ( rc . result . path . size ( ) > 1 && rc . result . t > 0.99f ) { m_path = mergeCorridorStartShortcut ( m_path , rc . result . path ) ; } } }
|
Attempts to optimize the path if the specified point is visible from the current position .
|
3,069
|
public boolean movePosition ( float [ ] npos , NavMeshQuery navquery , QueryFilter filter ) { Result < MoveAlongSurfaceResult > masResult = navquery . moveAlongSurface ( m_path . get ( 0 ) , m_pos , npos , filter ) ; if ( masResult . succeeded ( ) ) { m_path = mergeCorridorStartMoved ( m_path , masResult . result . getVisited ( ) ) ; vCopy ( m_pos , masResult . result . getResultPos ( ) ) ; Result < Float > hr = navquery . getPolyHeight ( m_path . get ( 0 ) , masResult . result . getResultPos ( ) ) ; if ( hr . succeeded ( ) ) { m_pos [ 1 ] = hr . result ; } return true ; } return false ; }
|
Moves the position from the current location to the desired location adjusting the corridor as needed to reflect the change .
|
3,070
|
public void setCorridor ( float [ ] target , List < Long > path ) { vCopy ( m_target , target ) ; m_path = new ArrayList < > ( path ) ; }
|
Loads a new path and target into the corridor . The current corridor position is expected to be within the first polygon in the path . The target is expected to be in the last polygon .
|
3,071
|
public static int findEdge ( Poly node , Poly neighbour , MeshData tile , MeshData neighbourTile ) { for ( int i = 0 ; i < node . vertCount ; i ++ ) { int j = ( i + 1 ) % node . vertCount ; for ( int k = 0 ; k < neighbour . vertCount ; k ++ ) { int l = ( k + 1 ) % neighbour . vertCount ; if ( ( node . verts [ i ] == neighbour . verts [ l ] && node . verts [ j ] == neighbour . verts [ k ] ) || ( node . verts [ i ] == neighbour . verts [ k ] && node . verts [ j ] == neighbour . verts [ l ] ) ) { return i ; } } } for ( int i = 0 ; i < node . vertCount ; i ++ ) { int j = ( i + 1 ) % node . vertCount ; for ( int k = 0 ; k < neighbour . vertCount ; k ++ ) { int l = ( k + 1 ) % neighbour . vertCount ; if ( ( samePosition ( tile . verts , node . verts [ i ] , neighbourTile . verts , neighbour . verts [ l ] ) && samePosition ( tile . verts , node . verts [ j ] , neighbourTile . verts , neighbour . verts [ k ] ) ) || ( samePosition ( tile . verts , node . verts [ i ] , neighbourTile . verts , neighbour . verts [ k ] ) && samePosition ( tile . verts , node . verts [ j ] , neighbourTile . verts , neighbour . verts [ l ] ) ) ) { return i ; } } } return - 1 ; }
|
Find edge shared by 2 polygons within the same tile
|
3,072
|
public static int findEdge ( Poly node , MeshData tile , float value , int comp ) { float error = Float . MAX_VALUE ; int edge = 0 ; for ( int i = 0 ; i < node . vertCount ; i ++ ) { int j = ( i + 1 ) % node . vertCount ; float v1 = tile . verts [ 3 * node . verts [ i ] + comp ] - value ; float v2 = tile . verts [ 3 * node . verts [ j ] + comp ] - value ; float d = v1 * v1 + v2 * v2 ; if ( d < error ) { error = d ; edge = i ; } } return edge ; }
|
Find edge closest to the given coordinate
|
3,073
|
void build ( int nodeOffset , GraphMeshData graphData , List < int [ ] > connections ) { for ( int n = 0 ; n < connections . size ( ) ; n ++ ) { int [ ] nodeConnections = connections . get ( n ) ; MeshData tile = graphData . getTile ( n ) ; Poly node = graphData . getNode ( n ) ; for ( int connection : nodeConnections ) { MeshData neighbourTile = graphData . getTile ( connection - nodeOffset ) ; if ( neighbourTile != tile ) { buildExternalLink ( tile , node , neighbourTile ) ; } else { Poly neighbour = graphData . getNode ( connection - nodeOffset ) ; buildInternalLink ( tile , node , neighbourTile , neighbour ) ; } } } }
|
Process connections and transform them into recast neighbour flags
|
3,074
|
private void buildExternalLink ( MeshData tile , Poly node , MeshData neighbourTile ) { if ( neighbourTile . header . bmin [ 0 ] > tile . header . bmin [ 0 ] ) { node . neis [ PolyUtils . findEdge ( node , tile , neighbourTile . header . bmin [ 0 ] , 0 ) ] = NavMesh . DT_EXT_LINK ; } else if ( neighbourTile . header . bmin [ 0 ] < tile . header . bmin [ 0 ] ) { node . neis [ PolyUtils . findEdge ( node , tile , tile . header . bmin [ 0 ] , 0 ) ] = NavMesh . DT_EXT_LINK | 4 ; } else if ( neighbourTile . header . bmin [ 2 ] > tile . header . bmin [ 2 ] ) { node . neis [ PolyUtils . findEdge ( node , tile , neighbourTile . header . bmin [ 2 ] , 2 ) ] = NavMesh . DT_EXT_LINK | 2 ; } else { node . neis [ PolyUtils . findEdge ( node , tile , tile . header . bmin [ 2 ] , 2 ) ] = NavMesh . DT_EXT_LINK | 6 ; } }
|
In case of external link to other tiles we must find the direction
|
3,075
|
private static int [ ] findLeftMostVertex ( Contour contour ) { int minx = contour . verts [ 0 ] ; int minz = contour . verts [ 2 ] ; int leftmost = 0 ; for ( int i = 1 ; i < contour . nverts ; i ++ ) { int x = contour . verts [ i * 4 + 0 ] ; int z = contour . verts [ i * 4 + 2 ] ; if ( x < minx || ( x == minx && z < minz ) ) { minx = x ; minz = z ; leftmost = i ; } } return new int [ ] { minx , minz , leftmost } ; }
|
Finds the lowest leftmost vertex of a contour .
|
3,076
|
public Result < List < Long > > queryPolygons ( float [ ] center , float [ ] halfExtents , QueryFilter filter ) { if ( Objects . isNull ( center ) || ! vIsFinite ( center ) || Objects . isNull ( halfExtents ) || ! vIsFinite ( halfExtents ) || Objects . isNull ( filter ) ) { } float [ ] bmin = vSub ( center , halfExtents ) ; float [ ] bmax = vAdd ( center , halfExtents ) ; int [ ] minxy = m_nav . calcTileLoc ( bmin ) ; int minx = minxy [ 0 ] ; int miny = minxy [ 1 ] ; int [ ] maxxy = m_nav . calcTileLoc ( bmax ) ; int maxx = maxxy [ 0 ] ; int maxy = maxxy [ 1 ] ; List < Long > polys = new ArrayList < > ( ) ; for ( int y = miny ; y <= maxy ; ++ y ) { for ( int x = minx ; x <= maxx ; ++ x ) { List < MeshTile > neis = m_nav . getTilesAt ( x , y ) ; for ( int j = 0 ; j < neis . size ( ) ; ++ j ) { List < Long > polysInTile = queryPolygonsInTile ( neis . get ( j ) , bmin , bmax , filter ) ; polys . addAll ( polysInTile ) ; } } } return Result . success ( polys ) ; }
|
Finds polygons that overlap the search box .
|
3,077
|
public Status initSlicedFindPath ( long startRef , long endRef , float [ ] startPos , float [ ] endPos , QueryFilter filter , int options ) { m_query = new QueryData ( ) ; m_query . status = Status . FAILURE ; m_query . startRef = startRef ; m_query . endRef = endRef ; vCopy ( m_query . startPos , startPos ) ; vCopy ( m_query . endPos , endPos ) ; m_query . filter = filter ; m_query . options = options ; m_query . raycastLimitSqr = Float . MAX_VALUE ; if ( ! m_nav . isValidPolyRef ( startRef ) || ! m_nav . isValidPolyRef ( endRef ) || Objects . isNull ( startPos ) || ! vIsFinite ( startPos ) || Objects . isNull ( endPos ) || ! vIsFinite ( endPos ) || Objects . isNull ( filter ) ) { return Status . FAILURE_INVALID_PARAM ; } if ( ( options & DT_FINDPATH_ANY_ANGLE ) != 0 ) { MeshTile tile = m_nav . getTileByRef ( startRef ) ; float agentRadius = tile . data . header . walkableRadius ; m_query . raycastLimitSqr = sqr ( agentRadius * NavMesh . DT_RAY_CAST_LIMIT_PROPORTIONS ) ; } if ( startRef == endRef ) { m_query . status = Status . SUCCSESS ; return Status . SUCCSESS ; } m_nodePool . clear ( ) ; m_openList . clear ( ) ; Node startNode = m_nodePool . getNode ( startRef ) ; vCopy ( startNode . pos , startPos ) ; startNode . pidx = 0 ; startNode . cost = 0 ; startNode . total = vDist ( startPos , endPos ) * H_SCALE ; startNode . id = startRef ; startNode . flags = Node . DT_NODE_OPEN ; m_openList . push ( startNode ) ; m_query . status = Status . IN_PROGRESS ; m_query . lastBestNode = startNode ; m_query . lastBestNodeCost = startNode . total ; return m_query . status ; }
|
Intializes a sliced path query .
|
3,078
|
protected Result < float [ ] > getEdgeMidPoint ( long from , long to ) { Result < PortalResult > ppoints = getPortalPoints ( from , to ) ; if ( ppoints . failed ( ) ) { return Result . of ( ppoints . status , ppoints . message ) ; } float [ ] left = ppoints . result . left ; float [ ] right = ppoints . result . right ; float [ ] mid = new float [ 3 ] ; mid [ 0 ] = ( left [ 0 ] + right [ 0 ] ) * 0.5f ; mid [ 1 ] = ( left [ 1 ] + right [ 1 ] ) * 0.5f ; mid [ 2 ] = ( left [ 2 ] + right [ 2 ] ) * 0.5f ; return Result . success ( mid ) ; }
|
Returns edge mid point between two polygons .
|
3,079
|
public Result < List < Long > > getPathFromDijkstraSearch ( long endRef ) { if ( ! m_nav . isValidPolyRef ( endRef ) ) { return Result . invalidParam ( "Invalid end ref" ) ; } List < Node > nodes = m_nodePool . findNodes ( endRef ) ; if ( nodes . size ( ) != 1 ) { return Result . invalidParam ( "Invalid end ref" ) ; } Node endNode = nodes . get ( 0 ) ; if ( ( endNode . flags & DT_NODE_CLOSED ) == 0 ) { return Result . invalidParam ( "Invalid end ref" ) ; } return Result . success ( getPathToNode ( endNode ) ) ; }
|
Gets a path from the explored nodes in the previous search .
|
3,080
|
private List < Long > getPathToNode ( Node endNode ) { List < Long > path = new ArrayList < > ( ) ; Node curNode = endNode ; do { path . add ( 0 , curNode . id ) ; curNode = m_nodePool . getNodeAtIdx ( curNode . pidx ) ; } while ( curNode != null ) ; return path ; }
|
Gets the path leading to the specified end node .
|
3,081
|
public boolean update ( ) { if ( m_update . isEmpty ( ) ) { for ( ObstacleRequest req : m_reqs ) { int idx = decodeObstacleIdObstacle ( req . ref ) ; if ( idx >= m_obstacles . size ( ) ) { continue ; } TileCacheObstacle ob = m_obstacles . get ( idx ) ; int salt = decodeObstacleIdSalt ( req . ref ) ; if ( ob . salt != salt ) { continue ; } if ( req . action == ObstacleRequestAction . REQUEST_ADD ) { float [ ] bmin = new float [ 3 ] ; float [ ] bmax = new float [ 3 ] ; getObstacleBounds ( ob , bmin , bmax ) ; ob . touched = queryTiles ( bmin , bmax ) ; ob . pending . clear ( ) ; for ( long j : ob . touched ) { if ( ! contains ( m_update , j ) ) { m_update . add ( j ) ; } ob . pending . add ( j ) ; } } else if ( req . action == ObstacleRequestAction . REQUEST_REMOVE ) { ob . state = ObstacleState . DT_OBSTACLE_REMOVING ; ob . pending . clear ( ) ; for ( long j : ob . touched ) { if ( ! contains ( m_update , j ) ) { m_update . add ( j ) ; } ob . pending . add ( j ) ; } } } m_reqs . clear ( ) ; } if ( ! m_update . isEmpty ( ) ) { long ref = m_update . remove ( 0 ) ; buildNavMeshTile ( ref ) ; for ( int i = 0 ; i < m_obstacles . size ( ) ; ++ i ) { TileCacheObstacle ob = m_obstacles . get ( i ) ; if ( ob . state == ObstacleState . DT_OBSTACLE_PROCESSING || ob . state == ObstacleState . DT_OBSTACLE_REMOVING ) { ob . pending . remove ( ref ) ; if ( ob . pending . isEmpty ( ) ) { if ( ob . state == ObstacleState . DT_OBSTACLE_PROCESSING ) { ob . state = ObstacleState . DT_OBSTACLE_PROCESSED ; } else if ( ob . state == ObstacleState . DT_OBSTACLE_REMOVING ) { ob . state = ObstacleState . DT_OBSTACLE_EMPTY ; ob . salt = ( ob . salt + 1 ) & ( ( 1 << 16 ) - 1 ) ; if ( ob . salt == 0 ) { ob . salt ++ ; } ob . next = m_nextFreeObstacle ; m_nextFreeObstacle = ob ; } } } } } return m_update . isEmpty ( ) && m_reqs . isEmpty ( ) ; }
|
Updates the tile cache by rebuilding tiles touched by unfinished obstacle requests .
|
3,082
|
static float [ ] randomPointInConvexPoly ( float [ ] pts , int npts , float [ ] areas , float s , float t ) { float areasum = 0.0f ; for ( int i = 2 ; i < npts ; i ++ ) { areas [ i ] = triArea2D ( pts , 0 , ( i - 1 ) * 3 , i * 3 ) ; areasum += Math . max ( 0.001f , areas [ i ] ) ; } float thr = s * areasum ; float acc = 0.0f ; float u = 1.0f ; int tri = npts - 1 ; for ( int i = 2 ; i < npts ; i ++ ) { float dacc = areas [ i ] ; if ( thr >= acc && thr < ( acc + dacc ) ) { u = ( thr - acc ) / dacc ; tri = i ; break ; } acc += dacc ; } float v = ( float ) Math . sqrt ( t ) ; float a = 1 - v ; float b = ( 1 - u ) * v ; float c = u * v ; int pa = 0 ; int pb = ( tri - 1 ) * 3 ; int pc = tri * 3 ; return new float [ ] { a * pts [ pa ] + b * pts [ pb ] + c * pts [ pc ] , a * pts [ pa + 1 ] + b * pts [ pb + 1 ] + c * pts [ pc + 1 ] , a * pts [ pa + 2 ] + b * pts [ pb + 2 ] + c * pts [ pc + 2 ] } ; }
|
Adapted from Graphics Gems article .
|
3,083
|
private static float polyMinExtent ( float [ ] verts , int nverts ) { float minDist = Float . MAX_VALUE ; for ( int i = 0 ; i < nverts ; i ++ ) { int ni = ( i + 1 ) % nverts ; int p1 = i * 3 ; int p2 = ni * 3 ; float maxEdgeDist = 0 ; for ( int j = 0 ; j < nverts ; j ++ ) { if ( j == i || j == ni ) { continue ; } float d = distancePtSeg2d ( verts , j * 3 , verts , p1 , p2 ) ; maxEdgeDist = Math . max ( maxEdgeDist , d ) ; } minDist = Math . min ( minDist , maxEdgeDist ) ; } return ( float ) Math . sqrt ( minDist ) ; }
|
Calculate minimum extend of the polygon .
|
3,084
|
static boolean left ( int [ ] verts , int a , int b , int c ) { return area2 ( verts , a , b , c ) < 0 ; }
|
line through a to b .
|
3,085
|
private static boolean intersectProp ( int [ ] verts , int a , int b , int c , int d ) { if ( collinear ( verts , a , b , c ) || collinear ( verts , a , b , d ) || collinear ( verts , c , d , a ) || collinear ( verts , c , d , b ) ) return false ; return ( left ( verts , a , b , c ) ^ left ( verts , a , b , d ) ) && ( left ( verts , c , d , a ) ^ left ( verts , c , d , b ) ) ; }
|
intersection is ensured by using strict leftness .
|
3,086
|
private static boolean between ( int [ ] verts , int a , int b , int c ) { if ( ! collinear ( verts , a , b , c ) ) return false ; if ( verts [ a + 0 ] != verts [ b + 0 ] ) return ( ( verts [ a + 0 ] <= verts [ c + 0 ] ) && ( verts [ c + 0 ] <= verts [ b + 0 ] ) ) || ( ( verts [ a + 0 ] >= verts [ c + 0 ] ) && ( verts [ c + 0 ] >= verts [ b + 0 ] ) ) ; else return ( ( verts [ a + 2 ] <= verts [ c + 2 ] ) && ( verts [ c + 2 ] <= verts [ b + 2 ] ) ) || ( ( verts [ a + 2 ] >= verts [ c + 2 ] ) && ( verts [ c + 2 ] >= verts [ b + 2 ] ) ) ; }
|
on the closed segement ab .
|
3,087
|
static boolean intersect ( int [ ] verts , int a , int b , int c , int d ) { if ( intersectProp ( verts , a , b , c , d ) ) return true ; else if ( between ( verts , a , b , c ) || between ( verts , a , b , d ) || between ( verts , c , d , a ) || between ( verts , c , d , b ) ) return true ; else return false ; }
|
Returns true iff segments ab and cd intersect properly or improperly .
|
3,088
|
private static boolean inCone ( int i , int j , int n , int [ ] verts , int [ ] indices ) { int pi = ( indices [ i ] & 0x0fffffff ) * 4 ; int pj = ( indices [ j ] & 0x0fffffff ) * 4 ; int pi1 = ( indices [ next ( i , n ) ] & 0x0fffffff ) * 4 ; int pin1 = ( indices [ prev ( i , n ) ] & 0x0fffffff ) * 4 ; if ( leftOn ( verts , pin1 , pi , pi1 ) ) { return left ( verts , pi , pj , pin1 ) && left ( verts , pj , pi , pi1 ) ; } return ! ( leftOn ( verts , pi , pj , pi1 ) && leftOn ( verts , pj , pi , pin1 ) ) ; }
|
polygon P in the neighborhood of the i endpoint .
|
3,089
|
private static boolean diagonal ( int i , int j , int n , int [ ] verts , int [ ] indices ) { return inCone ( i , j , n , verts , indices ) && diagonalie ( i , j , n , verts , indices ) ; }
|
diagonal of P .
|
3,090
|
public static String encrypt ( String c , String key ) { try { SecretKeySpec skeySpec = new SecretKeySpec ( Hex . decodeHex ( key . toCharArray ( ) ) , "AES" ) ; Cipher cipher = Cipher . getInstance ( "AES" ) ; cipher . init ( Cipher . ENCRYPT_MODE , skeySpec ) ; byte [ ] encoded = cipher . doFinal ( c . getBytes ( ) ) ; return new String ( Hex . encodeHex ( encoded ) ) ; } catch ( final Exception e ) { logger . warn ( "Could not encrypt string" , e ) ; return null ; } }
|
Encrypts a string .
|
3,091
|
protected void inject ( Collection < ? extends Expression > objs ) { for ( Object o : objs ) { if ( o == null ) { continue ; } injector . injectMembers ( o ) ; } }
|
Injects dependencies on the given objects .
|
3,092
|
protected String join ( Collection < ? > list , String delimiter ) { return Joiner . on ( delimiter ) . join ( list ) ; }
|
Joins a collection of objects given the delimiter .
|
3,093
|
public String translate ( final When when ) { inject ( when . condition ) ; inject ( when . action ) ; return String . format ( "WHEN %s THEN %s" , when . condition . translate ( ) , when . action . translate ( ) ) ; }
|
Translates When .
|
3,094
|
public String translate ( final Case aCase ) { String elseString = "" ; if ( aCase . getFalseAction ( ) != null ) { inject ( aCase . getFalseAction ( ) ) ; elseString = String . format ( "ELSE %s" , aCase . getFalseAction ( ) . translate ( ) ) ; } final String whens = aCase . whens . stream ( ) . peek ( this :: inject ) . map ( When :: translate ) . collect ( Collectors . joining ( " " ) ) ; return String . format ( "CASE %s %s END" , whens , elseString ) ; }
|
Translates Case .
|
3,095
|
public String translate ( final Values values ) { final ArrayList < Values . Row > rows = new ArrayList < > ( values . getRows ( ) ) ; final String [ ] aliases = values . getAliases ( ) ; if ( aliases == null || aliases . length == 0 ) { throw new DatabaseEngineRuntimeException ( "Values requires aliases to avoid ambiguous columns names." ) ; } else { rows . forEach ( row -> { final List < Expression > expressions = row . getExpressions ( ) ; for ( int i = 0 ; i < expressions . size ( ) && i < aliases . length ; i ++ ) { expressions . get ( i ) . alias ( aliases [ i ] ) ; } } ) ; } final List < Expression > rowsWithSelect = rows . stream ( ) . map ( SqlBuilder :: select ) . collect ( Collectors . toList ( ) ) ; final Union union = rowsToUnion ( rowsWithSelect ) ; if ( values . isEnclosed ( ) ) { union . enclose ( ) ; } return translate ( union ) ; }
|
Translates Values .
|
3,096
|
public String translate ( final Values . Row row ) { inject ( row . getExpressions ( ) ) ; final String translation = row . getExpressions ( ) . stream ( ) . map ( expression -> { final String alias = expression . isAliased ( ) ? " AS " + quotize ( expression . getAlias ( ) ) : "" ; return expression . translate ( ) + alias ; } ) . collect ( Collectors . joining ( ", " ) ) ; return row . isEnclosed ( ) ? "(" + translation + ")" : translation ; }
|
Translates Values . Row .
|
3,097
|
protected Union rowsToUnion ( final List < Expression > rows ) { List < Expression > rowsWithSelect = new ArrayList < > ( rows ) ; while ( rowsWithSelect . size ( ) > 2 ) { final List < Expression > newRowsWithSelect = new ArrayList < > ( ) ; for ( int i = 1 ; i < rowsWithSelect . size ( ) ; i += 2 ) { final Expression left = rowsWithSelect . get ( i - 1 ) ; final Expression right = rowsWithSelect . get ( i ) ; newRowsWithSelect . add ( union ( left , right ) . all ( ) . enclose ( ) ) ; } if ( rowsWithSelect . size ( ) % 2 == 1 ) { newRowsWithSelect . add ( rowsWithSelect . get ( rowsWithSelect . size ( ) - 1 ) ) ; } rowsWithSelect = newRowsWithSelect ; } return union ( rowsWithSelect ) . all ( ) ; }
|
Transform values rows into a union .
|
3,098
|
public Query select ( final Expression ... selectColumns ) { if ( selectColumns == null ) { return this ; } return select ( Arrays . asList ( selectColumns ) ) ; }
|
Adds the SELECT columns .
|
3,099
|
private Expression getParsedOrderByColumn ( final Expression column ) { if ( column instanceof Name ) { final Name columnName = ( Name ) column ; final String environment = columnName . getEnvironment ( ) ; if ( environment != null && ! environment . isEmpty ( ) ) { final Expression parsedColumn = column ( columnName . getName ( ) ) ; inject ( parsedColumn ) ; switch ( column . getOrdering ( ) ) { case "DESC" : parsedColumn . desc ( ) ; break ; default : parsedColumn . asc ( ) ; break ; } return parsedColumn ; } } return column ; }
|
Helper method which removes the environment parameter from a column when it is used inside an order by statement and in a paginated query . This is needed in order to avoid The multi - part identifier could not be bound error which only happens in SQL Server .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.