idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
38,300
|
public static void addDatatablesResourceIfNecessary ( String defaultFilename , String type ) { boolean loadDatatables = shouldLibraryBeLoaded ( P_GET_DATATABLE_FROM_CDN , true ) ; FacesContext context = FacesContext . getCurrentInstance ( ) ; UIViewRoot root = context . getViewRoot ( ) ; String [ ] positions = { "head" , "body" , "form" } ; for ( String position : positions ) { if ( loadDatatables ) { List < UIComponent > availableResources = root . getComponentResources ( context , position ) ; for ( UIComponent ava : availableResources ) { if ( ava . isRendered ( ) ) { String name = ( String ) ava . getAttributes ( ) . get ( "name" ) ; if ( null != name ) { name = name . toLowerCase ( ) ; if ( name . contains ( "datatables" ) && name . endsWith ( "." + type ) ) { loadDatatables = false ; break ; } } } } } } if ( loadDatatables ) { addResourceIfNecessary ( defaultFilename ) ; } }
|
Add the default datatables . net resource if and only if the user doesn t bring their own copy and if they didn t disallow it in the web . xml by setting the context paramter net . bootsfaces . get_datatable_from_cdn to true .
|
38,301
|
public static Class < ? > getValueType ( FacesContext context , UIComponent uiComponent , Collection < Class < ? > > validTypes ) { Class < ? > valueType = getValueType ( context , uiComponent ) ; if ( valueType != null && isValid ( validTypes , valueType ) ) { return valueType ; } else { for ( UIComponent child : uiComponent . getChildren ( ) ) { UIComponent c = ( UIComponent ) child ; ValueExpression expr = c . getValueExpression ( "value" ) ; Object val = expr == null ? null : expr . getValue ( context . getELContext ( ) ) ; if ( val != null ) { valueType = val . getClass ( ) ; if ( valueType . isArray ( ) && isValid ( validTypes , valueType . getComponentType ( ) ) ) { return valueType ; } else if ( val instanceof Collection < ? > ) { valueType = ( ( Collection < ? > ) val ) . iterator ( ) . next ( ) . getClass ( ) ; if ( isValid ( validTypes , valueType ) ) { return valueType ; } } } } } return null ; }
|
Source adapted from Seam s enumConverter . The goal is to get the type to which this component s value is bound . First check if the valueExpression provides the type . For dropdown - like components this may not work so check for SelectItems children .
|
38,302
|
public static Class < ? > getValueType ( FacesContext context , UIComponent comp ) { ValueExpression expr = comp . getValueExpression ( "value" ) ; Class < ? > valueType = expr == null ? null : expr . getType ( context . getELContext ( ) ) ; return valueType ; }
|
return the type for the value attribute of the given component if it exists . Return null otherwise .
|
38,303
|
@ SuppressWarnings ( "rawtypes" ) private void removeMisleadingType ( Slider2 slider ) { try { Method method = getClass ( ) . getMethod ( "getPassThroughAttributes" , ( Class [ ] ) null ) ; if ( null != method ) { Object map = method . invoke ( this , ( Object [ ] ) null ) ; if ( null != map ) { Map attributes = ( Map ) map ; if ( attributes . containsKey ( "type" ) ) attributes . remove ( "type" ) ; } } } catch ( Exception ignoreMe ) { } }
|
remove wrong type information that may have been added by AngularFaces
|
38,304
|
protected SelectItem createSelectItem ( FacesContext context , UISelectItems uiSelectItems , Object value , Object label ) { String var = ( String ) uiSelectItems . getAttributes ( ) . get ( "var" ) ; Map < String , Object > attrs = uiSelectItems . getAttributes ( ) ; Map < String , Object > requestMap = context . getExternalContext ( ) . getRequestMap ( ) ; if ( var != null ) { requestMap . put ( var , value ) ; } Object itemLabelValue = attrs . get ( "itemLabel" ) ; Object itemValue = attrs . get ( "itemValue" ) ; String description = ( String ) attrs . get ( "itemDescription" ) ; Object itemDisabled = attrs . get ( "itemDisabled" ) ; Object itemEscaped = attrs . get ( "itemLabelEscaped" ) ; Object noSelection = attrs . get ( "noSelectionOption" ) ; if ( itemValue == null ) { itemValue = value ; } if ( itemLabelValue == null ) { itemLabelValue = label ; } String itemLabel = itemLabelValue == null ? String . valueOf ( value ) : String . valueOf ( itemLabelValue ) ; boolean disabled = itemDisabled == null ? false : Boolean . valueOf ( itemDisabled . toString ( ) ) ; boolean escaped = itemEscaped == null ? false : Boolean . valueOf ( itemEscaped . toString ( ) ) ; boolean noSelectionOption = noSelection == null ? false : Boolean . valueOf ( noSelection . toString ( ) ) ; if ( var != null ) { requestMap . remove ( var ) ; } return new SelectItem ( itemValue , itemLabel , description , disabled , escaped , noSelectionOption ) ; }
|
Copied from the InputRenderer class of PrimeFaces 5 . 1 .
|
38,305
|
private void add_snake_case_properties ( List < PropertyDescriptor > pdl ) throws IntrospectionException { List < PropertyDescriptor > alternatives = new ArrayList < PropertyDescriptor > ( ) ; for ( PropertyDescriptor descriptor : pdl ) { String camelCase = descriptor . getName ( ) ; if ( camelCase . equals ( "rendererType" ) ) { continue ; } if ( camelCase . equals ( "localValueSet" ) ) { continue ; } if ( camelCase . equals ( "submittedValue" ) ) { continue ; } String snake_case = BsfUtils . camelCaseToSnakeCase ( camelCase ) ; if ( snake_case != camelCase ) { if ( descriptor . getReadMethod ( ) != null && descriptor . getWriteMethod ( ) != null ) { String getter = descriptor . getReadMethod ( ) . getName ( ) ; String setter = descriptor . getWriteMethod ( ) . getName ( ) ; if ( UIComponent . class != descriptor . getReadMethod ( ) . getDeclaringClass ( ) ) { PropertyDescriptor alternative = new PropertyDescriptor ( snake_case , getDecoratedClass ( ) , getter , setter ) ; alternative . setBound ( true ) ; alternatives . add ( alternative ) ; if ( camelCase . equals ( "styleClass" ) ) { alternative = new PropertyDescriptor ( "class" , getDecoratedClass ( ) , getter , setter ) ; alternative . setBound ( true ) ; alternatives . add ( alternative ) ; } } } } } if ( alternatives . size ( ) > 0 ) { pdl . addAll ( alternatives ) ; } }
|
Method that generates dynamically the snake - case methods from the available camelcase properties found inside the bean list .
|
38,306
|
public static void generateJSEventHandlers ( ResponseWriter rw , UIComponent component ) throws IOException { Map < String , Object > attributes = component . getAttributes ( ) ; String [ ] eventHandlers = { "onclick" , "onblur" , "onmouseover" } ; for ( String event : eventHandlers ) { String handler = A . asString ( attributes . get ( event ) ) ; if ( null != handler ) { rw . writeAttribute ( event , handler , event ) ; } } }
|
Generates the standard Javascript event handlers .
|
38,307
|
public Object getConvertedValue ( FacesContext context , Object submittedValue ) throws ConverterException { if ( submittedValue == null ) { return null ; } String val = ( String ) submittedValue ; if ( val . trim ( ) . length ( ) == 0 ) { return null ; } Converter converter = this . getConverter ( ) ; if ( converter != null ) { return converter . getAsObject ( context , this , val ) ; } Locale sloc = BsfUtils . selectLocale ( context . getViewRoot ( ) . getLocale ( ) , this . getLocale ( ) , this ) ; String momentJSFormat = BsfUtils . selectMomentJSDateTimeFormat ( sloc , this . getFormat ( ) , this . isShowDate ( ) , this . isShowTime ( ) ) ; String javaFormat = LocaleUtils . momentToJavaFormat ( momentJSFormat ) ; Calendar cal = Calendar . getInstance ( sloc ) ; SimpleDateFormat format = new SimpleDateFormat ( javaFormat , sloc ) ; format . setTimeZone ( cal . getTimeZone ( ) ) ; try { cal . setTime ( format . parse ( val ) ) ; return cal . getTime ( ) ; } catch ( ParseException e ) { try { cal . setTime ( LocaleUtils . autoParseDateFormat ( val ) ) ; return cal . getTime ( ) ; } catch ( Exception pe ) { this . setValid ( false ) ; throw new ConverterException ( BsfUtils . getMessage ( "javax.faces.converter.DateTimeConverter.DATE" , val , javaFormat , BsfUtils . getLabel ( context , this ) ) ) ; } } }
|
Converts the date from the moment . js format to a java . util . Date .
|
38,308
|
private static Number toNumber ( Object object ) { if ( object instanceof Number ) { return ( Number ) object ; } if ( object instanceof String ) { return Float . valueOf ( ( String ) object ) ; } throw new IllegalArgumentException ( "Use number or string" ) ; }
|
Convert object to number . To be backwards compatible with bound integers to properties where we now also want to accept floats now .
|
38,309
|
public static final void encodeColumn ( ResponseWriter rw , UIComponent c , int span , int cxs , int csm , int clg , int offset , int oxs , int osm , int olg , String style , String sclass ) throws IOException { rw . startElement ( "div" , c ) ; Map < String , Object > componentAttrs = new HashMap < String , Object > ( ) ; if ( c != null ) { rw . writeAttribute ( "id" , c . getClientId ( ) , "id" ) ; Tooltip . generateTooltip ( FacesContext . getCurrentInstance ( ) , c , rw ) ; componentAttrs = c . getAttributes ( ) ; } StringBuilder sb = new StringBuilder ( ) ; if ( span > 0 || offset > 0 ) { if ( span > 0 ) { sb . append ( COLMD ) . append ( span ) ; } if ( offset > 0 ) { if ( span > 0 ) { sb . append ( " " ) ; } sb . append ( OFFSET + offset ) ; } } if ( cxs > 0 ) { sb . append ( " col-xs-" ) . append ( cxs ) ; } if ( componentAttrs . get ( "col-xs" ) != null && cxs == 0 ) { sb . append ( " hidden-xs" ) ; } if ( csm > 0 ) { sb . append ( " col-sm-" ) . append ( csm ) ; } if ( componentAttrs . get ( "col-sm" ) != null && csm == 0 ) { sb . append ( " hidden-sm" ) ; } if ( clg > 0 ) { sb . append ( " col-lg-" ) . append ( clg ) ; } if ( componentAttrs . get ( "col-lg" ) != null && clg == 0 ) { sb . append ( " hidden-lg" ) ; } if ( oxs > 0 ) { sb . append ( " col-xs-offset-" ) . append ( oxs ) ; } if ( osm > 0 ) { sb . append ( " col-sm-offset-" ) . append ( osm ) ; } if ( olg > 0 ) { sb . append ( " col-lg-offset-" ) . append ( olg ) ; } if ( sclass != null ) { sb . append ( " " ) . append ( sclass ) ; } rw . writeAttribute ( "class" , sb . toString ( ) . trim ( ) , "class" ) ; if ( style != null ) { rw . writeAttribute ( "style" , style , "style" ) ; } if ( null != c ) { Tooltip . activateTooltips ( FacesContext . getCurrentInstance ( ) , c ) ; } }
|
Encodes a Column
|
38,310
|
public static void addClass2FacetComponent ( UIComponent f , String cname , String aclass ) { if ( f . getClass ( ) . getName ( ) . endsWith ( cname ) ) { addClass2Component ( f , aclass ) ; } else { if ( f . getChildCount ( ) > 0 ) { for ( UIComponent c : f . getChildren ( ) ) { if ( c . getClass ( ) . getName ( ) . endsWith ( cname ) ) { addClass2Component ( c , aclass ) ; } } } } }
|
Adds a CSS class to a component within a facet .
|
38,311
|
protected static void addClass2Component ( UIComponent c , String aclass ) { Map < String , Object > a = c . getAttributes ( ) ; if ( a . containsKey ( "styleClass" ) ) { a . put ( "styleClass" , a . get ( "styleClass" ) + " " + aclass ) ; } else { a . put ( "styleClass" , aclass ) ; } }
|
Adds a CSS class to a component in the view tree . The class is appended to the styleClass value .
|
38,312
|
public static void decorateFacetComponent ( UIComponent parent , UIComponent comp , FacesContext ctx , ResponseWriter rw ) throws IOException { if ( comp . getChildCount ( ) >= 1 && comp . getClass ( ) . getName ( ) . endsWith ( "Panel" ) ) { for ( UIComponent child : comp . getChildren ( ) ) { decorateComponent ( parent , child , ctx , rw ) ; } } else { decorateComponent ( parent , comp , ctx , rw ) ; } }
|
Decorate the facet children with a class to render bootstrap like prepend and append sections
|
38,313
|
private static void decorateComponent ( UIComponent parent , UIComponent comp , FacesContext ctx , ResponseWriter rw ) throws IOException { if ( comp instanceof Icon ) ( ( Icon ) comp ) . setAddon ( true ) ; String classToApply = "input-group-addon" ; if ( comp . getClass ( ) . getName ( ) . endsWith ( "Button" ) || comp . getChildCount ( ) > 0 ) classToApply = "input-group-btn" ; if ( comp instanceof HtmlOutputText ) { HtmlOutputText out = ( HtmlOutputText ) comp ; String sc = out . getStyleClass ( ) ; if ( sc == null ) sc = classToApply ; else sc = sc + " " + classToApply ; out . setStyleClass ( sc ) ; comp . encodeAll ( ctx ) ; } else { rw . startElement ( "span" , parent ) ; rw . writeAttribute ( "class" , classToApply , "class" ) ; comp . encodeAll ( ctx ) ; rw . endElement ( "span" ) ; } }
|
Add the correct class
|
38,314
|
public static String findComponentFormId ( FacesContext fc , UIComponent c ) { UIComponent parent = c . getParent ( ) ; while ( parent != null ) { if ( parent instanceof UIForm ) { return parent . getClientId ( fc ) ; } parent = parent . getParent ( ) ; } return null ; }
|
Finds the Form Id of a component inside a form .
|
38,315
|
public static void renderChildren ( FacesContext fc , UIComponent component ) throws IOException { for ( Iterator < UIComponent > iterator = component . getChildren ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { UIComponent child = ( UIComponent ) iterator . next ( ) ; renderChild ( fc , child ) ; } }
|
Renders the Childrens of a Component
|
38,316
|
public static void renderChild ( FacesContext fc , UIComponent child ) throws IOException { if ( ! child . isRendered ( ) ) { return ; } child . encodeBegin ( fc ) ; if ( child . getRendersChildren ( ) ) { child . encodeChildren ( fc ) ; } else { renderChildren ( fc , child ) ; } child . encodeEnd ( fc ) ; }
|
Renders the Child of a Component
|
38,317
|
public static MethodExpression evalAsMethodExpression ( String p_expression ) throws PropertyNotFoundException { FacesContext context = FacesContext . getCurrentInstance ( ) ; ExpressionFactory expressionFactory = context . getApplication ( ) . getExpressionFactory ( ) ; ELContext elContext = context . getELContext ( ) ; MethodExpression mex = expressionFactory . createMethodExpression ( elContext , p_expression , Object . class , new Class [ 0 ] ) ; return mex ; }
|
Evaluates an EL expression into an object .
|
38,318
|
private void checkELSyntax ( String el , ELContext context ) { int pos = el . indexOf ( '.' ) ; if ( pos < 0 ) { throw new FacesException ( "The EL expression doesn't contain a method call: " + el ) ; } int end = el . indexOf ( '(' ) ; if ( end < 0 ) end = el . length ( ) ; if ( el . indexOf ( '[' ) >= 0 ) end = Math . min ( end , el . indexOf ( '[' ) ) ; while ( pos < end ) { String object = el . substring ( 0 , pos ) ; ValueExpression vex = evalAsValueExpression ( "#{" + object + "}" ) ; vex . getValue ( context ) ; Object result = vex . getValue ( context ) ; if ( result == null ) { System . out . println ( "Please check your EL expression - intermediate term " + object + " is null" ) ; } pos = el . indexOf ( '.' , pos + 1 ) ; if ( pos < 0 ) break ; } }
|
Evaluate the expression syntax
|
38,319
|
public void decode ( FacesContext context , UIComponent component , List < String > legalValues , String realEventSourceName ) { InputText inputText = ( InputText ) component ; if ( inputText . isDisabled ( ) || inputText . isReadonly ( ) ) { return ; } decodeBehaviors ( context , inputText ) ; String clientId = inputText . getClientId ( context ) ; String name = inputText . getName ( ) ; if ( realEventSourceName == null ) { realEventSourceName = "input_" + clientId ; } if ( null != inputText . getFieldId ( ) ) { realEventSourceName = inputText . getFieldId ( ) ; } if ( null == name ) { name = "input_" + clientId ; } String submittedValue = ( String ) context . getExternalContext ( ) . getRequestParameterMap ( ) . get ( name ) ; if ( inputText instanceof InputSecret ) { if ( ! ( ( InputSecret ) inputText ) . isRenderValue ( ) ) { if ( "*******" . equals ( submittedValue ) ) { submittedValue = null ; } } } if ( null != legalValues && null != submittedValue ) { boolean found = false ; for ( String option : legalValues ) { found |= submittedValue . equals ( option ) ; } if ( ! found ) { submittedValue = "" ; } } if ( submittedValue != null ) { inputText . setSubmittedValue ( submittedValue ) ; } new AJAXRenderer ( ) . decode ( context , component , realEventSourceName ) ; }
|
This method is used by RadioButtons and SelectOneMenus to limit the list of legal values . If another value is sent the input field is considered empty . This comes in useful the the back - end attribute is a primitive type like int which doesn t support null values .
|
38,320
|
private void renderJQueryAfterComponent ( ResponseWriter rw , String clientId , SelectOneMenu menu ) throws IOException { Boolean select2 = menu . isSelect2 ( ) ; if ( select2 != null && select2 ) { rw . startElement ( "script" , menu ) ; rw . writeAttribute ( "type" , "text/javascript" , "script" ) ; StringBuilder buf = new StringBuilder ( "$(document).ready(function(){" ) ; buf . append ( "\n" ) ; buf . append ( " $(\"[id='" ) . append ( clientId ) . append ( "']\")" ) ; buf . append ( ".select2();" ) ; buf . append ( "\n" ) ; buf . append ( "});" ) ; rw . writeText ( buf . toString ( ) , "script" ) ; rw . endElement ( "script" ) ; } }
|
render a jquery javascript block after the component if necessary
|
38,321
|
private SelectItemAndComponent determineSelectedItem ( FacesContext context , SelectOneMenu menu , List < SelectItemAndComponent > items , Converter converter ) { Object submittedValue = menu . getSubmittedValue ( ) ; Object selectedOption ; if ( submittedValue != null ) { selectedOption = submittedValue ; } else { selectedOption = menu . getValue ( ) ; } for ( int index = 0 ; index < items . size ( ) ; index ++ ) { SelectItemAndComponent option = items . get ( index ) ; if ( option . getSelectItem ( ) . isNoSelectionOption ( ) ) continue ; Object itemValue = option . getSelectItem ( ) . getValue ( ) ; String itemValueAsString = getOptionAsString ( context , menu , itemValue , converter ) ; Object optionValue ; if ( submittedValue != null ) { optionValue = itemValueAsString ; } else { optionValue = itemValue ; } if ( itemValue != null ) { if ( isSelected ( context , menu , selectedOption , optionValue , converter ) ) { return option ; } } } return null ; }
|
Compare current selection with items if there is any element selected
|
38,322
|
private String decodeAndEscapeSelectors ( FacesContext context , UIComponent component , String selector ) { selector = ExpressionResolver . getComponentIDs ( context , component , selector ) ; selector = BsfUtils . escapeJQuerySpecialCharsInSelector ( selector ) ; return selector ; }
|
Decode and escape selectors if necessary
|
38,323
|
public static String getErrorSeverityClass ( String clientId ) { String [ ] levels = { "bf-no-message has-success" , "bf-info" , "bf-warning has-warning" , "bf-error has-error" , "bf-fatal has-error" } ; int level = 0 ; Iterator < FacesMessage > messages = FacesContext . getCurrentInstance ( ) . getMessages ( clientId ) ; if ( null != messages ) { if ( ! messages . hasNext ( ) ) { return "" ; } while ( messages . hasNext ( ) ) { FacesMessage message = messages . next ( ) ; if ( message . getSeverity ( ) . equals ( FacesMessage . SEVERITY_INFO ) ) if ( level < 1 ) level = 1 ; if ( message . getSeverity ( ) . equals ( FacesMessage . SEVERITY_WARN ) ) if ( level < 2 ) level = 2 ; if ( message . getSeverity ( ) . equals ( FacesMessage . SEVERITY_ERROR ) ) if ( level < 3 ) level = 3 ; if ( message . getSeverity ( ) . equals ( FacesMessage . SEVERITY_FATAL ) ) if ( level < 4 ) level = 4 ; } return levels [ level ] ; } return "" ; }
|
Returns style matching the severity error .
|
38,324
|
private void saveInitialChildState ( FacesContext facesContext ) { index = - 1 ; initialChildState = new ConcurrentHashMap < String , SavedState > ( ) ; initialClientId = getClientId ( facesContext ) ; if ( getChildCount ( ) > 0 ) { for ( UIComponent child : getChildren ( ) ) { saveInitialChildState ( facesContext , child ) ; } } }
|
Save the initial child state .
|
38,325
|
public static Date autoParseDateFormat ( String dateString ) { for ( Locale locale : DateFormat . getAvailableLocales ( ) ) { for ( int style = DateFormat . FULL ; style <= DateFormat . SHORT ; style ++ ) { DateFormat df = DateFormat . getDateInstance ( style , locale ) ; try { return df . parse ( dateString ) ; } catch ( ParseException ex ) { continue ; } } } String format = determineDateFormat ( dateString ) ; if ( format != null ) { DateFormat df = new SimpleDateFormat ( format ) ; try { return df . parse ( dateString ) ; } catch ( ParseException e ) { return null ; } } return null ; }
|
Try to auto - parse the date format
|
38,326
|
private static String translateFormat ( String formatString , Map < String , String > mapping , String escapeStart , String escapeEnd , String targetEscapeStart , String targetEscapeEnd ) { int beginIndex = 0 ; int i = 0 ; char lastChar = 0 ; char currentChar = 0 ; String resultString = "" ; char esc1 = escapeStart . charAt ( 0 ) ; char esc2 = escapeEnd . charAt ( 0 ) ; for ( ; i < formatString . length ( ) ; i ++ ) { currentChar = formatString . charAt ( i ) ; if ( i > 0 && lastChar != currentChar ) { resultString += mapSubformat ( formatString , mapping , beginIndex , i , escapeStart , escapeEnd , targetEscapeStart , targetEscapeEnd ) ; beginIndex = i ; } lastChar = currentChar ; if ( currentChar == esc1 ) { i ++ ; while ( i < formatString . length ( ) && formatString . charAt ( i ) != esc2 ) { i ++ ; } resultString += targetEscapeStart ; resultString += formatString . substring ( beginIndex + 1 , i ) ; resultString += targetEscapeEnd ; i ++ ; if ( i < formatString . length ( ) ) { lastChar = formatString . charAt ( i ) ; } beginIndex = i ; } } if ( beginIndex < formatString . length ( ) && i <= formatString . length ( ) ) { return resultString + mapSubformat ( formatString , mapping , beginIndex , i , escapeStart , escapeEnd , targetEscapeStart , targetEscapeEnd ) ; } else { return resultString ; } }
|
Internal method to do translations
|
38,327
|
private static String mapSubformat ( String formatString , Map < String , String > mapping , int beginIndex , int currentIndex , String escapeStart , String escapeEnd , String targetEscapeStart , String targetEscapeEnd ) { String subformat = formatString . substring ( beginIndex , currentIndex ) ; if ( subformat . equals ( escapeStart ) || subformat . equals ( escapeEnd ) ) { return targetEscapeStart + "(error: cannot ecape escape characters)" + targetEscapeEnd ; } if ( mapping . containsKey ( subformat ) ) { String result = mapping . get ( subformat ) ; if ( result == null || result . length ( ) == 0 ) { return targetEscapeStart + "(error: " + subformat + " cannot be converted)" + targetEscapeEnd ; } return result ; } return subformat ; }
|
Append the new mapping
|
38,328
|
public Map < String , String > getJQueryEventParameterLists ( ) { Map < String , String > result = new HashMap < String , String > ( ) ; result . put ( "select" , "event, datatable, typeOfSelection, indexes" ) ; result . put ( "deselect" , "event, datatable, typeOfSelection, indexes" ) ; return result ; }
|
Returns the parameter list of jQuery and other non - standard JS callbacks . If there s no parameter list for a certain event the default is simply event .
|
38,329
|
public Map < String , String > getJQueryEventParameterListsForAjax ( ) { Map < String , String > result = new HashMap < String , String > ( ) ; result . put ( "select" , "'typeOfSelection':typeOfSelection,'indexes':indexes" ) ; result . put ( "deselect" , "'typeOfSelection':typeOfSelection,'indexes':indexes" ) ; return result ; }
|
Returns the subset of the parameter list of jQuery and other non - standard JS callbacks which is sent to the server via AJAX . If there s no parameter list for a certain event the default is simply null .
|
38,330
|
private static < T > Observable < Boolean > commitOrRollbackOnNext ( final boolean isCommit , final Database db , Observable < T > source ) { return source . concatMap ( new Func1 < T , Observable < Boolean > > ( ) { public Observable < Boolean > call ( T t ) { if ( isCommit ) return db . commit ( ) ; else return db . rollback ( ) ; } } ) ; }
|
Emits true for commit and false for rollback .
|
38,331
|
public Database asynchronous ( final Scheduler nonTransactionalScheduler ) { return asynchronous ( new Func0 < Scheduler > ( ) { public Scheduler call ( ) { return nonTransactionalScheduler ; } } ) ; }
|
Returns a Database based on the current Database except all non - transactional queries run on the given scheduler .
|
38,332
|
private void connectAndPrepareStatement ( Subscriber < ? super T > subscriber , State state ) throws SQLException { log . debug ( "connectionProvider={}" , query . context ( ) . connectionProvider ( ) ) ; if ( ! subscriber . isUnsubscribed ( ) ) { log . debug ( "getting connection" ) ; state . con = query . context ( ) . connectionProvider ( ) . get ( ) ; log . debug ( "preparing statement,sql={}" , query . sql ( ) ) ; state . ps = state . con . prepareStatement ( query . sql ( ) , ResultSet . TYPE_FORWARD_ONLY , ResultSet . CONCUR_READ_ONLY ) ; if ( query . context ( ) . fetchSize ( ) != null ) { state . ps . setFetchSize ( query . context ( ) . fetchSize ( ) ) ; } log . debug ( "setting parameters" ) ; Util . setParameters ( state . ps , parameters , query . names ( ) ) ; } }
|
Obtains connection creates prepared statement and assigns parameters to the prepared statement .
|
38,333
|
static int parametersCount ( Query query ) { if ( query . names ( ) . isEmpty ( ) ) return countQuestionMarkParameters ( query . sql ( ) ) ; else return query . names ( ) . size ( ) ; }
|
Count the number of JDBC parameters in a sql statement .
|
38,334
|
private static String getTypeInfo ( List < Object > list ) { StringBuilder s = new StringBuilder ( ) ; for ( Object o : list ) { if ( s . length ( ) > 0 ) s . append ( ", " ) ; if ( o == null ) s . append ( "null" ) ; else { s . append ( o . getClass ( ) . getName ( ) ) ; s . append ( "=" ) ; s . append ( o ) ; } } return s . toString ( ) ; }
|
Returns debugging info about the types of a list of objects .
|
38,335
|
private static void setBlob ( PreparedStatement ps , int i , Object o , Class < ? > cls ) throws SQLException { final InputStream is ; if ( o instanceof byte [ ] ) { is = new ByteArrayInputStream ( ( byte [ ] ) o ) ; } }
|
Sets a blob parameter for the prepared statement .
|
38,336
|
private static HikariDataSource createPool ( String url , String username , String password , int minPoolSize , int maxPoolSize , long connectionTimeoutMs ) { HikariDataSource ds = new HikariDataSource ( ) ; ds . setJdbcUrl ( url ) ; ds . setUsername ( username ) ; ds . setPassword ( password ) ; ds . setMinimumIdle ( minPoolSize ) ; ds . setMaximumPoolSize ( maxPoolSize ) ; ds . setConnectionTimeout ( connectionTimeoutMs ) ; return ds ; }
|
Returns a new pooled data source based on jdbc url .
|
38,337
|
static Observable < List < Parameter > > bufferedParameters ( Query query ) { int numParamsPerQuery = numParamsPerQuery ( query ) ; if ( numParamsPerQuery > 0 ) return parametersAfterDependencies ( query ) . concatMap ( FLATTEN_NAMED_MAPS ) . buffer ( numParamsPerQuery ) ; else return singleIntegerAfterDependencies ( query ) . map ( TO_EMPTY_PARAMETER_LIST ) ; }
|
If the number of parameters in a query is > 0 then group the parameters in lists of that number in size but only after the dependencies have been completed . If the number of parameteres is zero then return an observable containing one item being an empty list .
|
38,338
|
public < T > Observable < T > execute ( ResultSetMapper < ? extends T > function ) { return bufferedParameters ( this ) . concatMap ( executeOnce ( function ) ) ; }
|
Returns the results of running a select query with all sets of parameters .
|
38,339
|
private void checkSubscription ( Subscriber < ? super T > subscriber ) { if ( subscriber . isUnsubscribed ( ) ) { keepGoing = false ; log . debug ( "unsubscribing" ) ; } }
|
If subscribe unsubscribed sets keepGoing to false .
|
38,340
|
private void getConnection ( State state ) { state . con = query . context ( ) . connectionProvider ( ) . get ( ) ; debug ( "getting connection" ) ; debug ( "cp={}" , query . context ( ) . connectionProvider ( ) ) ; }
|
Gets the current connection .
|
38,341
|
private void complete ( Subscriber < ? super T > subscriber ) { if ( ! subscriber . isUnsubscribed ( ) ) { debug ( "onCompleted" ) ; subscriber . onCompleted ( ) ; } else debug ( "unsubscribed" ) ; }
|
Notify observer that sequence is complete .
|
38,342
|
private void handleException ( Throwable e , Subscriber < ? super T > subscriber ) { debug ( "onError: " , e . getMessage ( ) ) ; Exceptions . throwOrReport ( e , subscriber ) ; }
|
Notify observer of an error .
|
38,343
|
private void close ( State state ) { if ( state . closed . compareAndSet ( false , true ) ) { Util . closeQuietly ( state . ps ) ; if ( isCommit ( ) || isRollback ( ) ) Util . closeQuietly ( state . con ) ; else Util . closeQuietlyIfAutoCommit ( state . con ) ; } }
|
Cancels a running PreparedStatement closing it and the current Connection but only if auto commit mode .
|
38,344
|
< T > void parameters ( Observable < T > params ) { this . parameters = Observable . concat ( parameters , params . map ( Parameter . TO_PARAMETER ) ) ; }
|
Appends the given parameters to the parameter list for the query . If there are more parameters than required for one execution of the query then more than one execution of the query will occur .
|
38,345
|
void parameter ( Object value ) { if ( value instanceof Observable ) throw new IllegalArgumentException ( "use parameters() method not the parameter() method for an Observable" ) ; parameters ( Observable . just ( value ) ) ; }
|
Appends a parameter to the parameter list for the query . If there are more parameters than required for one execution of the query then more than one execution of the query will occur .
|
38,346
|
@ SuppressLint ( "MissingPermission" ) @ RequiresPermission ( allOf = { ACCESS_COARSE_LOCATION , ACCESS_FINE_LOCATION , CHANGE_WIFI_STATE , ACCESS_WIFI_STATE } ) public static Observable < List < ScanResult > > observeWifiAccessPoints ( final Context context ) { @ SuppressLint ( "WifiManagerPotentialLeak" ) final WifiManager wifiManager = ( WifiManager ) context . getSystemService ( Context . WIFI_SERVICE ) ; if ( wifiManager != null ) { wifiManager . startScan ( ) ; } else { Log . w ( LOG_TAG , "WifiManager was null, so WiFi scan was not started" ) ; } final IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( WifiManager . RSSI_CHANGED_ACTION ) ; filter . addAction ( WifiManager . SCAN_RESULTS_AVAILABLE_ACTION ) ; return Observable . create ( new ObservableOnSubscribe < List < ScanResult > > ( ) { public void subscribe ( final ObservableEmitter < List < ScanResult > > emitter ) throws Exception { final BroadcastReceiver receiver = createWifiScanResultsReceiver ( emitter , wifiManager ) ; if ( wifiManager != null ) { context . registerReceiver ( receiver , filter ) ; } else { emitter . onError ( new RuntimeException ( "WifiManager was null, so BroadcastReceiver for Wifi scan results " + "cannot be registered" ) ) ; } Disposable disposable = disposeInUiThread ( new Action ( ) { public void run ( ) { tryToUnregisterReceiver ( context , receiver ) ; } } ) ; emitter . setDisposable ( disposable ) ; } } ) ; }
|
Observes WiFi Access Points . Returns fresh list of Access Points whenever WiFi signal strength changes .
|
38,347
|
@ RequiresPermission ( ACCESS_WIFI_STATE ) public static Observable < WifiSignalLevel > observeWifiSignalLevel ( final Context context ) { return observeWifiSignalLevel ( context , WifiSignalLevel . getMaxLevel ( ) ) . map ( new Function < Integer , WifiSignalLevel > ( ) { public WifiSignalLevel apply ( Integer level ) throws Exception { return WifiSignalLevel . fromLevel ( level ) ; } } ) ; }
|
Observes WiFi signal level with predefined max num levels . Returns WiFi signal level as enum with information about current level
|
38,348
|
@ RequiresPermission ( ACCESS_WIFI_STATE ) public static Observable < Integer > observeWifiSignalLevel ( final Context context , final int numLevels ) { final WifiManager wifiManager = ( WifiManager ) context . getSystemService ( Context . WIFI_SERVICE ) ; final IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( WifiManager . RSSI_CHANGED_ACTION ) ; return Observable . create ( new ObservableOnSubscribe < Integer > ( ) { public void subscribe ( final ObservableEmitter < Integer > emitter ) throws Exception { final BroadcastReceiver receiver = createSignalLevelReceiver ( emitter , wifiManager , numLevels ) ; if ( wifiManager != null ) { context . registerReceiver ( receiver , filter ) ; } else { emitter . onError ( new RuntimeException ( "WifiManager is null, so BroadcastReceiver for Wifi signal level " + "cannot be registered" ) ) ; } Disposable disposable = disposeInUiThread ( new Action ( ) { public void run ( ) { tryToUnregisterReceiver ( context , receiver ) ; } } ) ; emitter . setDisposable ( disposable ) ; } } ) . defaultIfEmpty ( 0 ) ; }
|
Observes WiFi signal level . Returns WiFi signal level as an integer
|
38,349
|
@ RequiresPermission ( ACCESS_WIFI_STATE ) public static Observable < WifiState > observeWifiStateChange ( final Context context ) { final IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( WifiManager . WIFI_STATE_CHANGED_ACTION ) ; return Observable . create ( new ObservableOnSubscribe < WifiState > ( ) { public void subscribe ( final ObservableEmitter < WifiState > emitter ) throws Exception { final BroadcastReceiver receiver = createWifiStateChangeReceiver ( emitter ) ; context . registerReceiver ( receiver , filter ) ; Disposable disposable = disposeInUiThread ( new Action ( ) { public void run ( ) { tryToUnregisterReceiver ( context , receiver ) ; } } ) ; emitter . setDisposable ( disposable ) ; } } ) ; }
|
Observes WiFi State Change Action Returns wifi state whenever WiFi state changes such like enable disable enabling disabling or Unknown
|
38,350
|
public synchronized DatabaseInfo getDatabaseInfo ( ) { if ( databaseInfo != null ) { return databaseInfo ; } try { _check_mtime ( ) ; boolean hasStructureInfo = false ; byte [ ] delim = new byte [ 3 ] ; file . seek ( file . length ( ) - 3 ) ; for ( int i = 0 ; i < STRUCTURE_INFO_MAX_SIZE ; i ++ ) { int read = file . read ( delim ) ; if ( read == 3 && ( delim [ 0 ] & 0xFF ) == 255 && ( delim [ 1 ] & 0xFF ) == 255 && ( delim [ 2 ] & 0xFF ) == 255 ) { hasStructureInfo = true ; break ; } file . seek ( file . getFilePointer ( ) - 4 ) ; } if ( hasStructureInfo ) { file . seek ( file . getFilePointer ( ) - 6 ) ; } else { file . seek ( file . length ( ) - 3 ) ; } for ( int i = 0 ; i < DATABASE_INFO_MAX_SIZE ; i ++ ) { file . readFully ( delim ) ; if ( delim [ 0 ] == 0 && delim [ 1 ] == 0 && delim [ 2 ] == 0 ) { byte [ ] dbInfo = new byte [ i ] ; file . readFully ( dbInfo ) ; databaseInfo = new DatabaseInfo ( new String ( dbInfo , charset ) ) ; return databaseInfo ; } file . seek ( file . getFilePointer ( ) - 4 ) ; } } catch ( IOException e ) { throw new InvalidDatabaseException ( "Error reading database info" , e ) ; } return new DatabaseInfo ( "" ) ; }
|
Returns information about the database .
|
38,351
|
public Location getLocation ( String str ) { InetAddress addr ; try { addr = InetAddress . getByName ( str ) ; } catch ( UnknownHostException e ) { return null ; } return getLocation ( addr ) ; }
|
for GeoIP City only
|
38,352
|
private synchronized int seekCountryV6 ( InetAddress addr ) { byte [ ] v6vec = addr . getAddress ( ) ; if ( v6vec . length == 4 ) { byte [ ] t = new byte [ 16 ] ; System . arraycopy ( v6vec , 0 , t , 12 , 4 ) ; v6vec = t ; } byte [ ] buf = new byte [ 2 * MAX_RECORD_LENGTH ] ; int [ ] x = new int [ 2 ] ; int offset = 0 ; _check_mtime ( ) ; for ( int depth = 127 ; depth >= 0 ; depth -- ) { readNode ( buf , x , offset ) ; int bnum = 127 - depth ; int idx = bnum >> 3 ; int bMask = 1 << ( bnum & 7 ^ 7 ) ; if ( ( v6vec [ idx ] & bMask ) > 0 ) { if ( x [ 1 ] >= databaseSegments [ 0 ] ) { last_netmask = 128 - depth ; return x [ 1 ] ; } offset = x [ 1 ] ; } else { if ( x [ 0 ] >= databaseSegments [ 0 ] ) { last_netmask = 128 - depth ; return x [ 0 ] ; } offset = x [ 0 ] ; } } throw new InvalidDatabaseException ( "Error seeking country while searching for " + addr . getHostAddress ( ) ) ; }
|
Finds the country index value given an IPv6 address .
|
38,353
|
private synchronized int seekCountry ( long ipAddress ) { byte [ ] buf = new byte [ 2 * MAX_RECORD_LENGTH ] ; int [ ] x = new int [ 2 ] ; int offset = 0 ; _check_mtime ( ) ; for ( int depth = 31 ; depth >= 0 ; depth -- ) { readNode ( buf , x , offset ) ; if ( ( ipAddress & ( 1 << depth ) ) > 0 ) { if ( x [ 1 ] >= databaseSegments [ 0 ] ) { last_netmask = 32 - depth ; return x [ 1 ] ; } offset = x [ 1 ] ; } else { if ( x [ 0 ] >= databaseSegments [ 0 ] ) { last_netmask = 32 - depth ; return x [ 0 ] ; } offset = x [ 0 ] ; } } throw new InvalidDatabaseException ( "Error seeking country while searching for " + ipAddress ) ; }
|
Finds the country index value given an IP address .
|
38,354
|
private static long bytesToLong ( byte [ ] address ) { long ipnum = 0 ; for ( int i = 0 ; i < 4 ; ++ i ) { long y = address [ i ] ; if ( y < 0 ) { y += 256 ; } ipnum += y << ( ( 3 - i ) * 8 ) ; } return ipnum ; }
|
Returns the long version of an IP address given an InetAddress object .
|
38,355
|
public Date getDate ( ) { for ( int i = 0 ; i < info . length ( ) - 9 ; i ++ ) { if ( Character . isWhitespace ( info . charAt ( i ) ) ) { String dateString = info . substring ( i + 1 , i + 9 ) ; try { synchronized ( formatter ) { return formatter . parse ( dateString ) ; } } catch ( ParseException pe ) { } break ; } } return null ; }
|
Returns the date of the database .
|
38,356
|
public void swapElements ( int i , int j ) { if ( i != j ) { double s = get ( i ) ; set ( i , get ( j ) ) ; set ( j , s ) ; } }
|
Swaps the specified elements of this vector .
|
38,357
|
public Vector shuffle ( ) { Vector result = copy ( ) ; Random random = new Random ( ) ; for ( int i = 0 ; i < length ; i ++ ) { int j = random . nextInt ( length - i ) + i ; swapElements ( i , j ) ; } return result ; }
|
Shuffles this vector .
|
38,358
|
public Vector slice ( int from , int until ) { if ( until - from < 0 ) { fail ( "Wrong slice range: [" + from + ".." + until + "]." ) ; } Vector result = blankOfLength ( until - from ) ; for ( int i = from ; i < until ; i ++ ) { result . set ( i - from , get ( i ) ) ; } return result ; }
|
Retrieves the specified sub - vector of this vector . The sub - vector is specified by interval of indices .
|
38,359
|
public Vector select ( int [ ] indices ) { int newLength = indices . length ; if ( newLength == 0 ) { fail ( "No elements selected." ) ; } Vector result = blankOfLength ( newLength ) ; for ( int i = 0 ; i < newLength ; i ++ ) { result . set ( i , get ( indices [ i ] ) ) ; } return result ; }
|
Returns a new vector with the selected elements .
|
38,360
|
public String mkString ( NumberFormat formatter , String delimiter ) { StringBuilder sb = new StringBuilder ( ) ; VectorIterator it = iterator ( ) ; while ( it . hasNext ( ) ) { double x = it . next ( ) ; int i = it . index ( ) ; sb . append ( formatter . format ( x ) ) . append ( ( i < length - 1 ? delimiter : "" ) ) ; } return sb . toString ( ) ; }
|
Converts this vector into the string representation .
|
38,361
|
public VectorIterator iterator ( ) { return new VectorIterator ( length ) { private int i = - 1 ; public int index ( ) { return i ; } public double get ( ) { return Vector . this . get ( i ) ; } public void set ( double value ) { Vector . this . set ( i , value ) ; } public boolean hasNext ( ) { return i + 1 < length ; } public Double next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } i ++ ; return get ( ) ; } } ; }
|
Returns a vector iterator .
|
38,362
|
public static VectorAccumulator asSumAccumulator ( final double neutral ) { return new VectorAccumulator ( ) { private BigDecimal result = BigDecimal . valueOf ( neutral ) ; public void update ( int i , double value ) { result = result . add ( BigDecimal . valueOf ( value ) ) ; } public double accumulate ( ) { double value = result . setScale ( Vectors . ROUND_FACTOR , RoundingMode . CEILING ) . doubleValue ( ) ; result = BigDecimal . valueOf ( neutral ) ; return value ; } } ; }
|
Creates a sum vector accumulator that calculates the sum of all elements in the vector .
|
38,363
|
public static VectorAccumulator mkMinAccumulator ( ) { return new VectorAccumulator ( ) { private double result = Double . POSITIVE_INFINITY ; public void update ( int i , double value ) { result = Math . min ( result , value ) ; } public double accumulate ( ) { double value = result ; result = Double . POSITIVE_INFINITY ; return value ; } } ; }
|
Makes a minimum vector accumulator that accumulates the minimum across vector elements .
|
38,364
|
public static VectorAccumulator mkMaxAccumulator ( ) { return new VectorAccumulator ( ) { private double result = Double . NEGATIVE_INFINITY ; public void update ( int i , double value ) { result = Math . max ( result , value ) ; } public double accumulate ( ) { double value = result ; result = Double . NEGATIVE_INFINITY ; return value ; } } ; }
|
Makes a maximum vector accumulator that accumulates the maximum across vector elements .
|
38,365
|
public static VectorProcedure asAccumulatorProcedure ( final VectorAccumulator accumulator ) { return new VectorProcedure ( ) { public void apply ( int i , double value ) { accumulator . update ( i , value ) ; } } ; }
|
Creates an accumulator procedure that adapts a vector accumulator for procedure interface . This is useful for reusing a single accumulator for multiple fold operations in multiple vectors .
|
38,366
|
public static MatrixAccumulator mkMinAccumulator ( ) { return new MatrixAccumulator ( ) { private double result = Double . POSITIVE_INFINITY ; public void update ( int i , int j , double value ) { result = Math . min ( result , value ) ; } public double accumulate ( ) { double value = result ; result = Double . POSITIVE_INFINITY ; return value ; } } ; }
|
Makes a minimum matrix accumulator that accumulates the minimum of matrix elements .
|
38,367
|
public static MatrixAccumulator mkMaxAccumulator ( ) { return new MatrixAccumulator ( ) { private double result = Double . NEGATIVE_INFINITY ; public void update ( int i , int j , double value ) { result = Math . max ( result , value ) ; } public double accumulate ( ) { double value = result ; result = Double . NEGATIVE_INFINITY ; return value ; } } ; }
|
Makes a maximum matrix accumulator that accumulates the maximum of matrix elements .
|
38,368
|
public static MatrixAccumulator asSumAccumulator ( final double neutral ) { return new MatrixAccumulator ( ) { private BigDecimal result = BigDecimal . valueOf ( neutral ) ; public void update ( int i , int j , double value ) { result = result . add ( BigDecimal . valueOf ( value ) ) ; } public double accumulate ( ) { double value = result . setScale ( Matrices . ROUND_FACTOR , RoundingMode . CEILING ) . doubleValue ( ) ; result = BigDecimal . valueOf ( neutral ) ; return value ; } } ; }
|
Creates a sum matrix accumulator that calculates the sum of all elements in the matrix .
|
38,369
|
public static MatrixProcedure asAccumulatorProcedure ( final MatrixAccumulator accumulator ) { return new MatrixProcedure ( ) { public void apply ( int i , int j , double value ) { accumulator . update ( i , j , value ) ; } } ; }
|
Creates an accumulator procedure that adapts a matrix accumulator for procedure interface . This is useful for reusing a single accumulator for multiple fold operations in multiple matrices .
|
38,370
|
public void swapRows ( int i , int j ) { if ( i != j ) { Vector ii = getRow ( i ) ; Vector jj = getRow ( j ) ; setRow ( i , jj ) ; setRow ( j , ii ) ; } }
|
Swaps the specified rows of this matrix .
|
38,371
|
public void swapColumns ( int i , int j ) { if ( i != j ) { Vector ii = getColumn ( i ) ; Vector jj = getColumn ( j ) ; setColumn ( i , jj ) ; setColumn ( j , ii ) ; } }
|
Swaps the specified columns of this matrix .
|
38,372
|
public Matrix transpose ( ) { Matrix result = blankOfShape ( columns , rows ) ; MatrixIterator it = result . iterator ( ) ; while ( it . hasNext ( ) ) { it . next ( ) ; int i = it . rowIndex ( ) ; int j = it . columnIndex ( ) ; it . set ( get ( j , i ) ) ; } return result ; }
|
Transposes this matrix .
|
38,373
|
public double trace ( ) { double result = 0.0 ; for ( int i = 0 ; i < rows ; i ++ ) { result += get ( i , i ) ; } return result ; }
|
Calculates the trace of this matrix .
|
38,374
|
public double diagonalProduct ( ) { BigDecimal result = BigDecimal . ONE ; for ( int i = 0 ; i < rows ; i ++ ) { result = result . multiply ( BigDecimal . valueOf ( get ( i , i ) ) ) ; } return result . setScale ( Matrices . ROUND_FACTOR , RoundingMode . CEILING ) . doubleValue ( ) ; }
|
Calculates the product of diagonal elements of this matrix .
|
38,375
|
public double determinant ( ) { if ( rows != columns ) { throw new IllegalStateException ( "Can not compute determinant of non-square matrix." ) ; } if ( rows == 0 ) { return 0.0 ; } else if ( rows == 1 ) { return get ( 0 , 0 ) ; } else if ( rows == 2 ) { return get ( 0 , 0 ) * get ( 1 , 1 ) - get ( 0 , 1 ) * get ( 1 , 0 ) ; } else if ( rows == 3 ) { return get ( 0 , 0 ) * get ( 1 , 1 ) * get ( 2 , 2 ) + get ( 0 , 1 ) * get ( 1 , 2 ) * get ( 2 , 0 ) + get ( 0 , 2 ) * get ( 1 , 0 ) * get ( 2 , 1 ) - get ( 0 , 2 ) * get ( 1 , 1 ) * get ( 2 , 0 ) - get ( 0 , 1 ) * get ( 1 , 0 ) * get ( 2 , 2 ) - get ( 0 , 0 ) * get ( 1 , 2 ) * get ( 2 , 1 ) ; } MatrixDecompositor decompositor = withDecompositor ( LinearAlgebra . LU ) ; Matrix [ ] lup = decompositor . decompose ( ) ; Matrix u = lup [ 1 ] ; Matrix p = lup [ 2 ] ; double result = u . diagonalProduct ( ) ; int [ ] permutations = new int [ p . rows ( ) ] ; for ( int i = 0 ; i < p . rows ( ) ; i ++ ) { for ( int j = 0 ; j < p . columns ( ) ; j ++ ) { if ( p . get ( i , j ) > 0.0 ) { permutations [ i ] = j ; break ; } } } int sign = 1 ; for ( int i = 0 ; i < permutations . length ; i ++ ) { for ( int j = i + 1 ; j < permutations . length ; j ++ ) { if ( permutations [ j ] < permutations [ i ] ) { sign *= - 1 ; } } } return sign * result ; }
|
Calculates the determinant of this matrix .
|
38,376
|
public int rank ( ) { if ( rows == 0 || columns == 0 ) { return 0 ; } MatrixDecompositor decompositor = withDecompositor ( LinearAlgebra . SVD ) ; Matrix [ ] usv = decompositor . decompose ( ) ; Matrix s = usv [ 1 ] ; double tolerance = Math . max ( rows , columns ) * s . get ( 0 , 0 ) * Matrices . EPS ; int result = 0 ; for ( int i = 0 ; i < s . rows ( ) ; i ++ ) { if ( s . get ( i , i ) > tolerance ) { result ++ ; } } return result ; }
|
Calculates the rank of this matrix .
|
38,377
|
public Matrix insertRow ( int i , Vector row ) { if ( i > rows || i < 0 ) { throw new IndexOutOfBoundsException ( "Illegal row number, must be 0.." + rows ) ; } Matrix result ; if ( columns == 0 ) { result = blankOfShape ( rows + 1 , row . length ( ) ) ; } else { result = blankOfShape ( rows + 1 , columns ) ; } for ( int ii = 0 ; ii < i ; ii ++ ) { result . setRow ( ii , getRow ( ii ) ) ; } result . setRow ( i , row ) ; for ( int ii = i ; ii < rows ; ii ++ ) { result . setRow ( ii + 1 , getRow ( ii ) ) ; } return result ; }
|
Adds one row to matrix .
|
38,378
|
public Matrix insertColumn ( int j , Vector column ) { if ( j > columns || j < 0 ) { throw new IndexOutOfBoundsException ( "Illegal column number, must be 0.." + columns ) ; } Matrix result ; if ( rows == 0 ) { result = blankOfShape ( column . length ( ) , columns + 1 ) ; } else { result = blankOfShape ( rows , columns + 1 ) ; } for ( int jj = 0 ; jj < j ; jj ++ ) { result . setColumn ( jj , getColumn ( jj ) ) ; } result . setColumn ( j , column ) ; for ( int jj = j ; jj < columns ; jj ++ ) { result . setColumn ( jj + 1 , getColumn ( jj ) ) ; } return result ; }
|
Adds one column to matrix .
|
38,379
|
public Matrix removeRow ( int i ) { if ( i >= rows || i < 0 ) { throw new IndexOutOfBoundsException ( "Illegal row number, must be 0.." + ( rows - 1 ) ) ; } Matrix result = blankOfShape ( rows - 1 , columns ) ; for ( int ii = 0 ; ii < i ; ii ++ ) { result . setRow ( ii , getRow ( ii ) ) ; } for ( int ii = i + 1 ; ii < rows ; ii ++ ) { result . setRow ( ii - 1 , getRow ( ii ) ) ; } return result ; }
|
Removes one row from matrix .
|
38,380
|
public Matrix removeColumn ( int j ) { if ( j >= columns || j < 0 ) { throw new IndexOutOfBoundsException ( "Illegal column number, must be 0.." + ( columns - 1 ) ) ; } Matrix result = blankOfShape ( rows , columns - 1 ) ; for ( int jj = 0 ; jj < j ; jj ++ ) { result . setColumn ( jj , getColumn ( jj ) ) ; } for ( int jj = j + 1 ; jj < columns ; jj ++ ) { result . setColumn ( jj - 1 , getColumn ( jj ) ) ; } return result ; }
|
Removes one column from matrix .
|
38,381
|
public Matrix shuffle ( ) { Matrix result = copy ( ) ; Random random = new Random ( ) ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < columns ; j ++ ) { int ii = random . nextInt ( rows - i ) + i ; int jj = random . nextInt ( columns - j ) + j ; double a = result . get ( ii , jj ) ; result . set ( ii , jj , result . get ( i , j ) ) ; result . set ( i , j , a ) ; } } return result ; }
|
Shuffles this matrix .
|
38,382
|
public Matrix slice ( int fromRow , int fromColumn , int untilRow , int untilColumn ) { ensureIndexArgumentsAreInBounds ( fromRow , fromColumn ) ; ensureIndexArgumentsAreInBounds ( untilRow - 1 , untilColumn - 1 ) ; if ( untilRow - fromRow < 0 || untilColumn - fromColumn < 0 ) { fail ( "Wrong slice range: [" + fromRow + ".." + untilRow + "][" + fromColumn + ".." + untilColumn + "]." ) ; } Matrix result = blankOfShape ( untilRow - fromRow , untilColumn - fromColumn ) ; for ( int i = fromRow ; i < untilRow ; i ++ ) { for ( int j = fromColumn ; j < untilColumn ; j ++ ) { result . set ( i - fromRow , j - fromColumn , get ( i , j ) ) ; } } return result ; }
|
Retrieves the specified sub - matrix of this matrix . The sub - matrix is specified by intervals for row indices and column indices .
|
38,383
|
public RowMajorMatrixIterator rowMajorIterator ( ) { return new RowMajorMatrixIterator ( rows , columns ) { private long limit = ( long ) rows * columns ; private int i = - 1 ; public int rowIndex ( ) { return i / columns ; } public int columnIndex ( ) { return i - rowIndex ( ) * columns ; } public double get ( ) { return Matrix . this . get ( rowIndex ( ) , columnIndex ( ) ) ; } public void set ( double value ) { Matrix . this . set ( rowIndex ( ) , columnIndex ( ) , value ) ; } public boolean hasNext ( ) { return i + 1 < limit ; } public Double next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } i ++ ; return get ( ) ; } } ; }
|
Returns a row - major matrix iterator .
|
38,384
|
public ColumnMajorMatrixIterator columnMajorIterator ( ) { return new ColumnMajorMatrixIterator ( rows , columns ) { private long limit = ( long ) rows * columns ; private int i = - 1 ; public int rowIndex ( ) { return i - columnIndex ( ) * rows ; } public int columnIndex ( ) { return i / rows ; } public double get ( ) { return Matrix . this . get ( rowIndex ( ) , columnIndex ( ) ) ; } public void set ( double value ) { Matrix . this . set ( rowIndex ( ) , columnIndex ( ) , value ) ; } public boolean hasNext ( ) { return i + 1 < limit ; } public Double next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } i ++ ; return get ( ) ; } } ; }
|
Returns a column - major matrix iterator .
|
38,385
|
public RowMajorMatrixIterator nonZeroRowMajorIterator ( ) { return new RowMajorMatrixIterator ( rows , columns ) { private long limit = ( long ) rows * columns ; private long i = - 1 ; public int rowIndex ( ) { return ( int ) ( i / columns ) ; } public int columnIndex ( ) { return ( int ) ( i - ( ( i / columns ) * columns ) ) ; } public double get ( ) { return SparseMatrix . this . get ( rowIndex ( ) , columnIndex ( ) ) ; } public void set ( double value ) { SparseMatrix . this . set ( rowIndex ( ) , columnIndex ( ) , value ) ; } public boolean hasNext ( ) { while ( i + 1 < limit ) { i ++ ; if ( SparseMatrix . this . nonZeroAt ( rowIndex ( ) , columnIndex ( ) ) ) { i -- ; break ; } } return i + 1 < limit ; } public Double next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } i ++ ; return get ( ) ; } } ; }
|
Returns a non - zero row - major matrix iterator .
|
38,386
|
public static ParseException create ( List < ParseError > errors ) { if ( errors . size ( ) == 1 ) { return new ParseException ( errors . get ( 0 ) . getMessage ( ) , errors ) ; } else if ( errors . size ( ) > 1 ) { return new ParseException ( String . format ( "%d errors occured. First: %s" , errors . size ( ) , errors . get ( 0 ) . getMessage ( ) ) , errors ) ; } else { return new ParseException ( "An unknown error occured" , errors ) ; } }
|
Creates a new exception based on the list of errors .
|
38,387
|
public static Token create ( TokenType type , Position pos ) { Token result = new Token ( ) ; result . type = type ; result . line = pos . getLine ( ) ; result . pos = pos . getPos ( ) ; return result ; }
|
Creates a new token with the given type using the given position as location info .
|
38,388
|
public static Token createAndFill ( TokenType type , Char ch ) { Token result = new Token ( ) ; result . type = type ; result . line = ch . getLine ( ) ; result . pos = ch . getPos ( ) ; result . contents = ch . getStringValue ( ) ; result . trigger = ch . getStringValue ( ) ; result . source = ch . toString ( ) ; return result ; }
|
Creates a new token with the given type using the Char a initial trigger and content .
|
38,389
|
@ SuppressWarnings ( "squid:S1698" ) public boolean matches ( TokenType type , String trigger ) { if ( ! is ( type ) ) { return false ; } if ( trigger == null ) { throw new IllegalArgumentException ( "trigger must not be null" ) ; } return getTrigger ( ) == trigger . intern ( ) ; }
|
Determines if this token has the given type and trigger .
|
38,390
|
@ SuppressWarnings ( "squid:S1698" ) public boolean wasTriggeredBy ( String ... triggers ) { if ( triggers . length == 0 ) { return false ; } for ( String aTrigger : triggers ) { if ( aTrigger != null && aTrigger . intern ( ) == getTrigger ( ) ) { return true ; } } return false ; }
|
Determines if this token was triggered by one of the given triggers .
|
38,391
|
public static Expression parse ( String input ) throws ParseException { return new Parser ( new StringReader ( input ) , new Scope ( ) ) . parse ( ) ; }
|
Parses the given input into an expression .
|
38,392
|
protected Expression functionCall ( ) { FunctionCall call = new FunctionCall ( ) ; Token funToken = tokenizer . consume ( ) ; Function fun = functionTable . get ( funToken . getContents ( ) ) ; if ( fun == null ) { errors . add ( ParseError . error ( funToken , String . format ( "Unknown function: '%s'" , funToken . getContents ( ) ) ) ) ; } call . setFunction ( fun ) ; tokenizer . consume ( ) ; while ( ! tokenizer . current ( ) . isSymbol ( ")" ) && tokenizer . current ( ) . isNotEnd ( ) ) { if ( ! call . getParameters ( ) . isEmpty ( ) ) { expect ( Token . TokenType . SYMBOL , "," ) ; } call . addParameter ( expression ( ) ) ; } expect ( Token . TokenType . SYMBOL , ")" ) ; if ( fun == null ) { return Constant . EMPTY ; } if ( call . getParameters ( ) . size ( ) != fun . getNumberOfArguments ( ) && fun . getNumberOfArguments ( ) >= 0 ) { errors . add ( ParseError . error ( funToken , String . format ( "Number of arguments for function '%s' do not match. Expected: %d, Found: %d" , funToken . getContents ( ) , fun . getNumberOfArguments ( ) , call . getParameters ( ) . size ( ) ) ) ) ; return Constant . EMPTY ; } return call ; }
|
Parses a function call .
|
38,393
|
protected boolean canConsumeThisString ( String string , boolean consume ) { if ( string == null ) { return false ; } for ( int i = 0 ; i < string . length ( ) ; i ++ ) { if ( ! input . next ( i ) . is ( string . charAt ( i ) ) ) { return false ; } } if ( consume ) { input . consume ( string . length ( ) ) ; } return true ; }
|
Checks if the next characters starting from the current match the given string .
|
38,394
|
protected void skipBlockComment ( ) { while ( ! input . current ( ) . isEndOfInput ( ) ) { if ( isAtEndOfBlockComment ( ) ) { return ; } input . consume ( ) ; } problemCollector . add ( ParseError . error ( input . current ( ) , "Premature end of block comment" ) ) ; }
|
Checks if we re looking at an end of block comment
|
38,395
|
protected Token fetchString ( ) { char separator = input . current ( ) . getValue ( ) ; char escapeChar = stringDelimiters . get ( input . current ( ) . getValue ( ) ) ; Token result = Token . create ( Token . TokenType . STRING , input . current ( ) ) ; result . addToTrigger ( input . consume ( ) ) ; while ( ! input . current ( ) . isNewLine ( ) && ! input . current ( ) . is ( separator ) && ! input . current ( ) . isEndOfInput ( ) ) { if ( escapeChar != '\0' && input . current ( ) . is ( escapeChar ) ) { result . addToSource ( input . consume ( ) ) ; if ( ! handleStringEscape ( separator , escapeChar , result ) ) { problemCollector . add ( ParseError . error ( input . next ( ) , String . format ( "Cannot use '%s' as escaped character" , input . next ( ) . getStringValue ( ) ) ) ) ; } } else { result . addToContent ( input . consume ( ) ) ; } } if ( input . current ( ) . is ( separator ) ) { result . addToSource ( input . consume ( ) ) ; } else { problemCollector . add ( ParseError . error ( input . current ( ) , "Premature end of string constant" ) ) ; } return result ; }
|
Reads and returns a string constant .
|
38,396
|
protected Token fetchId ( ) { Token result = Token . create ( Token . TokenType . ID , input . current ( ) ) ; result . addToContent ( input . consume ( ) ) ; while ( isIdentifierChar ( input . current ( ) ) ) { result . addToContent ( input . consume ( ) ) ; } if ( ! input . current ( ) . isEndOfInput ( ) && specialIdTerminators . contains ( input . current ( ) . getValue ( ) ) ) { Token specialId = Token . create ( Token . TokenType . SPECIAL_ID , result ) ; specialId . setTrigger ( input . current ( ) . getStringValue ( ) ) ; specialId . setContent ( result . getContents ( ) ) ; specialId . setSource ( result . getContents ( ) ) ; specialId . addToSource ( input . current ( ) ) ; input . consume ( ) ; return handleKeywords ( specialId ) ; } return handleKeywords ( result ) ; }
|
Reads and returns an identifier
|
38,397
|
protected Token handleKeywords ( Token idToken ) { String keyword = keywords . get ( keywordsCaseSensitive ? idToken . getContents ( ) . intern ( ) : idToken . getContents ( ) . toLowerCase ( ) . intern ( ) ) ; if ( keyword != null ) { Token keywordToken = Token . create ( Token . TokenType . KEYWORD , idToken ) ; keywordToken . setTrigger ( keyword ) ; keywordToken . setContent ( idToken . getContents ( ) ) ; keywordToken . setSource ( idToken . getSource ( ) ) ; return keywordToken ; } return idToken ; }
|
Checks if the given identifier is a keyword and returns an appropriate Token
|
38,398
|
protected Token fetchSpecialId ( ) { Token result = Token . create ( Token . TokenType . SPECIAL_ID , input . current ( ) ) ; result . addToTrigger ( input . consume ( ) ) ; while ( isIdentifierChar ( input . current ( ) ) ) { result . addToContent ( input . consume ( ) ) ; } return handleKeywords ( result ) ; }
|
Reads and returns a special id .
|
38,399
|
protected Token fetchNumber ( ) { Token result = Token . create ( Token . TokenType . INTEGER , input . current ( ) ) ; result . addToContent ( input . consume ( ) ) ; while ( input . current ( ) . isDigit ( ) || input . current ( ) . is ( decimalSeparator ) || ( input . current ( ) . is ( groupingSeparator ) && input . next ( ) . isDigit ( ) ) ) { if ( input . current ( ) . is ( groupingSeparator ) ) { result . addToSource ( input . consume ( ) ) ; } else if ( input . current ( ) . is ( decimalSeparator ) ) { if ( result . is ( Token . TokenType . DECIMAL ) ) { problemCollector . add ( ParseError . error ( input . current ( ) , "Unexpected decimal separators" ) ) ; } else { Token decimalToken = Token . create ( Token . TokenType . DECIMAL , result ) ; decimalToken . setContent ( result . getContents ( ) + effectiveDecimalSeparator ) ; decimalToken . setSource ( result . getSource ( ) ) ; result = decimalToken ; } result . addToSource ( input . consume ( ) ) ; } else { result . addToContent ( input . consume ( ) ) ; } } return result ; }
|
Reads and returns a number .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.