TextInput QML Type
Displays an editable line of text More...
| Import Statement: | import QtQuick 2.7 |
| Inherits: |
Properties
- acceptableInput : bool
- activeFocusOnPress : bool
- autoScroll : bool
- bottomPadding : real
- canPaste : bool
- canRedo : bool
- canUndo : bool
- color : color
- contentHeight : real
- contentWidth : real
- cursorDelegate : Component
- cursorPosition : int
- cursorRectangle : rectangle
- cursorVisible : bool
- displayText : string
- echoMode : enumeration
- effectiveHorizontalAlignment : enumeration
- font.bold : bool
- font.capitalization : enumeration
- font.family : string
- font.hintingPreference : enumeration
- font.italic : bool
- font.letterSpacing : real
- font.pixelSize : int
- font.pointSize : real
- font.strikeout : bool
- font.styleName : string
- font.underline : bool
- font.weight : enumeration
- font.wordSpacing : real
- horizontalAlignment : enumeration
- inputMask : string
- inputMethodComposing : bool
- inputMethodHints : enumeration
- leftPadding : real
- length : int
- maximumLength : int
- mouseSelectionMode : enumeration
- overwriteMode : bool
- padding : real
- passwordCharacter : string
- passwordMaskDelay : int
- persistentSelection : bool
- preeditText : string
- readOnly : bool
- renderType : enumeration
- rightPadding : real
- selectByMouse : bool
- selectedText : string
- selectedTextColor : color
- selectionColor : color
- selectionEnd : int
- selectionStart : int
- text : string
- topPadding : real
- validator : Validator
- verticalAlignment : enumeration
- wrapMode : enumeration
Signals
Methods
- clear()
- copy()
- cut()
- deselect()
- ensureVisible(int position)
- string getText(int start, int end)
- insert(int position, string text)
- isRightToLeft(int start, int end)
- moveCursorSelection(int position, SelectionMode mode)
- paste()
- int positionAt(real x, real y, CursorPosition position)
- rect positionToRectangle(int pos)
- redo()
- remove(int start, int end)
- select(int start, int end)
- selectAll()
- selectWord()
- undo()
Detailed Description
The TextInput type displays a single line of editable plain text.
TextInput is used to accept a line of text input. Input constraints can be placed on a TextInput item (for example, through a validator or inputMask), and setting echoMode to an appropriate value enables TextInput to be used for a password input field.
On macOS, the Up/Down key bindings for Home/End are explicitly disabled. If you want such bindings (on any platform), you will need to construct them in QML.
Property Documentation
This property is always true unless a validator or input mask has been set. If a validator or input mask has been set, this property will only be true if the current text is acceptable to the validator or input mask as a final string (not as an intermediate string).
Whether the TextInput should gain active focus on a mouse press. By default this is set to true.
Whether the TextInput should scroll when the text is longer than the width. By default this is set to true.
See also ensureVisible().
These properties hold the padding around the content. This space is reserved in addition to the contentWidth and contentHeight.
This QML property was introduced in Qt 5.6.
Returns true if the TextInput is writable and there are previous operations that can be undone.
Returns the height of the text, including the height past the height that is covered if the text does not fit within the set height.
Returns the width of the text, including the width past the width which is covered due to insufficient wrapping if wrapMode is set.
cursorDelegate : Component |
The delegate for the cursor in the TextInput.
If you set a cursorDelegate for a TextInput, this delegate will be used for drawing the cursor instead of the standard cursor. An instance of the delegate will be created and managed by the TextInput when a cursor is needed, and the x property of the delegate instance will be set so as to be one pixel before the top left of the current character.
Note that the root item of the delegate component must be a QQuickItem or QQuickItem derived item.
The position of the cursor in the TextInput.
The rectangle where the standard text cursor is rendered within the text input. Read only.
The position and height of a custom cursorDelegate are updated to follow the cursorRectangle automatically when it changes. The width of the delegate is unaffected by changes in the cursor rectangle.
Set to true when the TextInput shows a cursor.
This property is set and unset when the TextInput gets active focus, so that other properties can be bound to whether the cursor is currently showing. As it gets set and unset automatically, when you set the value yourself you must keep in mind that your value may be overwritten.
It can be set directly in script, for example if a KeyProxy might forward keys to it and you desire it to look active when this happens (but without actually giving it active focus).
It should not be set directly on the item, like in the below QML, as the specified value will be overridden and lost on focus changes.
TextInput { text: "Text" cursorVisible: false }
In the above snippet the cursor will still become visible when the TextInput gains active focus.
This is the text displayed in the TextInput.
If echoMode is set to TextInput::Normal, this holds the same value as the TextInput::text property. Otherwise, this property holds the text visible to the user, while the text property holds the actual entered text.
Note: Unlike the TextInput::text property, this contains partial text input from an input method.
See also preeditText.
Specifies how the text should be displayed in the TextInput.
- TextInput.Normal - Displays the text as it is. (Default)
- TextInput.Password - Displays platform-dependent password mask characters instead of the actual characters.
- TextInput.NoEcho - Displays nothing.
- TextInput.PasswordEchoOnEdit - Displays characters as they are entered while editing, otherwise identical to
TextInput.Password
.
Sets the horizontal alignment of the text within the TextInput item's width and height. By default, the text alignment follows the natural alignment of the text, for example text that is read from left to right will be aligned to the left.
TextInput does not have vertical alignment, as the natural height is exactly the height of the single line of text. If you set the height manually to something larger, TextInput will always be top aligned vertically. You can use anchors to align it however you want within another item.
The valid values for horizontalAlignment
are TextInput.AlignLeft
, TextInput.AlignRight
and TextInput.AlignHCenter
.
Valid values for verticalAlignment
are TextInput.AlignTop
(default), TextInput.AlignBottom
TextInput.AlignVCenter
.
When using the attached property LayoutMirroring::enabled to mirror application layouts, the horizontal alignment of text will also be mirrored. However, the property horizontalAlignment
will remain unchanged. To query the effective horizontal alignment of TextInput, use the read-only property effectiveHorizontalAlignment
.
Sets the capitalization for the text.
- Font.MixedCase - This is the normal text rendering option where no capitalization change is applied.
- Font.AllUppercase - This alters the text to be rendered in all uppercase type.
- Font.AllLowercase - This alters the text to be rendered in all lowercase type.
- Font.SmallCaps - This alters the text to be rendered in small-caps type.
- Font.Capitalize - This alters the text to be rendered with the first character of each word as an uppercase character.
TextInput { text: "Hello"; font.capitalization: Font.AllLowercase }
Sets the family name of the font.
The family name is case insensitive and may optionally include a foundry name, e.g. "Helvetica [Cronyx]". If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen. If the family isn't available a family will be set using the font matching algorithm.
Sets the preferred hinting on the text. This is a hint to the underlying text rendering system to use a certain level of hinting, and has varying support across platforms. See the table in the documentation for QFont::HintingPreference for more details.
Note: This property only has an effect when used together with render type TextInput.NativeRendering.
Font.PreferDefaultHinting - Use the default hinting level for the target platform.
Font.PreferNoHinting - If possible, render text without hinting the outlines of the glyphs. The text layout will be typographically accurate, using the same metrics as are used e.g. when printing.
Font.PreferVerticalHinting - If possible, render text with no horizontal hinting, but align glyphs to the pixel grid in the vertical direction. The text will appear crisper on displays where the density is too low to give an accurate rendering of the glyphs. But since the horizontal metrics of the glyphs are unhinted, the text's layout will be scalable to higher density devices (such as printers) without impacting details such as line breaks.
Font.PreferFullHinting - If possible, render text with hinting in both horizontal and vertical directions. The text will be altered to optimize legibility on the target device, but since the metrics will depend on the target size of the text, the positions of glyphs, line breaks, and other typographical detail will not scale, meaning that a text layout may look different on devices with different pixel densities.
TextInput { text: "Hello"; renderType: TextInput.NativeRendering; font.hintingPreference: Font.PreferVerticalHinting }
This QML property was introduced in Qt 5.8.
Sets the letter spacing for the font.
Letter spacing changes the default spacing between individual letters in the font. A positive value increases the letter spacing by the corresponding pixels; a negative value decreases the spacing.
Sets the font size in pixels.
Using this function makes the font device dependent. Use pointSize
to set the size of the font in a device independent manner.
Sets the style name of the font.
The style name is case insensitive. If set, the font will be matched against style name instead of the font properties font.weight, font.bold and font.italic.
This QML property was introduced in Qt 5.6.
Sets the font's weight.
The weight can be one of:
- Font.Thin
- Font.Light
- Font.ExtraLight
- Font.Normal - the default
- Font.Medium
- Font.DemiBold
- Font.Bold
- Font.ExtraBold
- Font.Black
TextInput { text: "Hello"; font.weight: Font.DemiBold }
Sets the word spacing for the font.
Word spacing changes the default spacing between individual words.
Sets the horizontal alignment of the text within the TextInput item's width and height. By default, the text alignment follows the natural alignment of the text, for example text that is read from left to right will be aligned to the left.
TextInput does not have vertical alignment, as the natural height is exactly the height of the single line of text. If you set the height manually to something larger, TextInput will always be top aligned vertically. You can use anchors to align it however you want within another item.
The valid values for horizontalAlignment
are TextInput.AlignLeft
, TextInput.AlignRight
and TextInput.AlignHCenter
.
Valid values for verticalAlignment
are TextInput.AlignTop
(default), TextInput.AlignBottom
TextInput.AlignVCenter
.
When using the attached property LayoutMirroring::enabled to mirror application layouts, the horizontal alignment of text will also be mirrored. However, the property horizontalAlignment
will remain unchanged. To query the effective horizontal alignment of TextInput, use the read-only property effectiveHorizontalAlignment
.
Allows you to set an input mask on the TextInput, restricting the allowable text inputs. See QLineEdit::inputMask for further details, as the exact same mask strings are used by TextInput.
See also acceptableInput and validator.
This property holds whether the TextInput has partial text input from an input method.
While it is composing an input method may rely on mouse or key events from the TextInput to edit or commit the partial text. This property can be used to determine when to disable events handlers that may interfere with the correct operation of an input method.
Provides hints to the input method about the expected content of the text input and how it should operate.
The value is a bit-wise combination of flags, or Qt.ImhNone if no hints are set.
Flags that alter behaviour are:
- Qt.ImhHiddenText - Characters should be hidden, as is typically used when entering passwords. This is automatically set when setting echoMode to
TextInput.Password
. - Qt.ImhSensitiveData - Typed text should not be stored by the active input method in any persistent storage like predictive user dictionary.
- Qt.ImhNoAutoUppercase - The input method should not try to automatically switch to upper case when a sentence ends.
- Qt.ImhPreferNumbers - Numbers are preferred (but not required).
- Qt.ImhPreferUppercase - Upper case letters are preferred (but not required).
- Qt.ImhPreferLowercase - Lower case letters are preferred (but not required).
- Qt.ImhNoPredictiveText - Do not use predictive text (i.e. dictionary lookup) while typing.
- Qt.ImhDate - The text editor functions as a date field.
- Qt.ImhTime - The text editor functions as a time field.
- Qt.ImhMultiLine - The text editor doesn't close software input keyboard when Return or Enter key is pressed (since QtQuick 2.4).
Flags that restrict input (exclusive flags) are:
- Qt.ImhDigitsOnly - Only digits are allowed.
- Qt.ImhFormattedNumbersOnly - Only number input is allowed. This includes decimal point and minus sign.
- Qt.ImhUppercaseOnly - Only upper case letter input is allowed.
- Qt.ImhLowercaseOnly - Only lower case letter input is allowed.
- Qt.ImhDialableCharactersOnly - Only characters suitable for phone dialing are allowed.
- Qt.ImhEmailCharactersOnly - Only characters suitable for email addresses are allowed.
- Qt.ImhUrlCharactersOnly - Only characters suitable for URLs are allowed.
Masks:
- Qt.ImhExclusiveInputMask - This mask yields nonzero if any of the exclusive flags are used.
These properties hold the padding around the content. This space is reserved in addition to the contentWidth and contentHeight.
This QML property was introduced in Qt 5.6.
Returns the total number of characters in the TextInput item.
If the TextInput has an inputMask the length will include mask characters and may differ from the length of the string returned by the text property.
This property can be faster than querying the length the text property as it doesn't require any copying or conversion of the TextInput's internal string data.
The maximum permitted length of the text in the TextInput.
If the text is too long, it is truncated at the limit.
By default, this property contains a value of 32767.
Specifies how text should be selected using a mouse.
- TextInput.SelectCharacters - The selection is updated with individual characters. (Default)
- TextInput.SelectWords - The selection is updated with whole words.
This property only applies when selectByMouse is true.
Whether text entered by the user will overwrite existing text.
As with many text editors, the text editor widget can be configured to insert or overwrite existing text with new text entered by the user.
If this property is true
, existing text is overwritten, character-for-character by new text; otherwise, text is inserted at the cursor position, displacing existing text.
By default, this property is false
(new text does not overwrite existing text).
This QML property was introduced in Qt 5.8.
These properties hold the padding around the content. This space is reserved in addition to the contentWidth and contentHeight.
This QML property was introduced in Qt 5.6.
This is the character displayed when echoMode is set to Password or PasswordEchoOnEdit. By default it is the password character used by the platform theme.
If this property is set to a string with more than one character, the first character is used. If the string is empty, the value is ignored and the property is not set.
Sets the delay before visible character is masked with password character, in milliseconds.
The reset method will be called by assigning undefined.
This QML property was introduced in Qt 5.4.
Whether the TextInput should keep its selection when it loses active focus to another item in the scene. By default this is set to false;
This property contains partial text input from an input method.
This QML property was introduced in Qt 5.7.
See also displayText.
Sets whether user input can modify the contents of the TextInput.
If readOnly is set to true, then user input will not affect the text property. Any bindings or attempts to set the text property will still work.
Override the default rendering type for this component.
Supported render types are:
- Text.QtRendering - the default
- Text.NativeRendering
Select Text.NativeRendering if you prefer text to look native on the target platform and do not require advanced features such as transformation of the text. Using such features in combination with the NativeRendering render type will lend poor and sometimes pixelated results.
These properties hold the padding around the content. This space is reserved in addition to the contentWidth and contentHeight.
This QML property was introduced in Qt 5.6.
Defaults to false.
If true, the user can use the mouse to select text in some platform-specific way. Note that for some platforms this may not be an appropriate interaction (it may conflict with how the text needs to behave inside a Flickable, for example).
This read-only property provides the text currently selected in the text input.
It is equivalent to the following snippet, but is faster and easier to use.
myTextInput.text.toString().substring(myTextInput.selectionStart, myTextInput.selectionEnd);
The cursor position after the last character in the current selection.
This property is read-only. To change the selection, use select(start,end), selectAll(), or selectWord().
See also selectionStart, cursorPosition, and selectedText.
The cursor position before the first character in the current selection.
This property is read-only. To change the selection, use select(start,end), selectAll(), or selectWord().
See also selectionEnd, cursorPosition, and selectedText.
These properties hold the padding around the content. This space is reserved in addition to the contentWidth and contentHeight.
This QML property was introduced in Qt 5.6.
Allows you to set a validator on the TextInput. When a validator is set the TextInput will only accept input which leaves the text property in an acceptable or intermediate state. The accepted signal will only be sent if the text is in an acceptable state when enter is pressed.
Currently supported validators are IntValidator, DoubleValidator and RegExpValidator. An example of using validators is shown below, which allows input of integers between 11 and 31 into the text input:
import QtQuick 2.0 TextInput{ validator: IntValidator{bottom: 11; top: 31;} focus: true }
See also acceptableInput and inputMask.
Sets the horizontal alignment of the text within the TextInput item's width and height. By default, the text alignment follows the natural alignment of the text, for example text that is read from left to right will be aligned to the left.
TextInput does not have vertical alignment, as the natural height is exactly the height of the single line of text. If you set the height manually to something larger, TextInput will always be top aligned vertically. You can use anchors to align it however you want within another item.
The valid values for horizontalAlignment
are TextInput.AlignLeft
, TextInput.AlignRight
and TextInput.AlignHCenter
.
Valid values for verticalAlignment
are TextInput.AlignTop
(default), TextInput.AlignBottom
TextInput.AlignVCenter
.
When using the attached property LayoutMirroring::enabled to mirror application layouts, the horizontal alignment of text will also be mirrored. However, the property horizontalAlignment
will remain unchanged. To query the effective horizontal alignment of TextInput, use the read-only property effectiveHorizontalAlignment
.
Set this property to wrap the text to the TextInput item's width. The text will only wrap if an explicit width has been set.
- TextInput.NoWrap - no wrapping will be performed. If the text contains insufficient newlines, then implicitWidth will exceed a set width.
- TextInput.WordWrap - wrapping is done on word boundaries only. If a word is too long, implicitWidth will exceed a set width.
- TextInput.WrapAnywhere - wrapping is done at any point on a line, even if it occurs in the middle of a word.
- TextInput.Wrap - if possible, wrapping occurs at a word boundary; otherwise it will occur at the appropriate point on the line, even in the middle of a word.
The default is TextInput.NoWrap. If you set a width, consider using TextInput.Wrap.
Signal Documentation
This signal is emitted when the Return or Enter key is pressed or the text input loses focus. Note that if there is a validator or inputMask set on the text input and enter/return is pressed, this signal will only be emitted if the input follows the inputMask and the validator returns an acceptable state.
The corresponding handler is onEditingFinished
.
This QML signal was introduced in Qt 5.2.
This signal is emitted whenever the text is edited. Unlike textChanged()
, this signal is not emitted when the text is changed programmatically, for example, by changing the value of the text
property or by calling clear()
.
The corresponding handler is onTextEdited
.
This QML signal was introduced in Qt 5.9.
Method Documentation
Clears the contents of the text input and resets partial text input from an input method.
Use this method instead of setting the text property to an empty string.
This QML method was introduced in Qt 5.7.
See also QInputMethod::reset().
Copies the currently selected text to the system clipboard.
Note: If the echo mode is set to a mode other than Normal then copy will not work. This is to prevent using copy as a method of bypassing password features of the line control.
Moves the currently selected text to the system clipboard.
Note: If the echo mode is set to a mode other than Normal then cut will not work. This is to prevent using cut as a method of bypassing password features of the line control.
Scrolls the contents of the text input so that the specified character position is visible inside the boundaries of the text input.
This QML method was introduced in Qt 5.4.
See also autoScroll.
Inserts text into the TextInput at position.
Returns true if the natural reading direction of the editor text found between positions start and end is right to left.
Moves the cursor to position and updates the selection according to the optional mode parameter. (To only move the cursor, set the cursorPosition property.)
When this method is called it additionally sets either the selectionStart or the selectionEnd (whichever was at the previous cursor position) to the specified position. This allows you to easily extend and contract the selected text range.
The selection mode specifies whether the selection is updated on a per character or a per word basis. If not specified the selection mode will default to TextInput.SelectCharacters.
- TextInput.SelectCharacters - Sets either the selectionStart or selectionEnd (whichever was at the previous cursor position) to the specified position.
- TextInput.SelectWords - Sets the selectionStart and selectionEnd to include all words between the specified position and the previous cursor position. Words partially in the range are included.
For example, take this sequence of calls:
cursorPosition = 5 moveCursorSelection(9, TextInput.SelectCharacters) moveCursorSelection(7, TextInput.SelectCharacters)
This moves the cursor to position 5, extend the selection end from 5 to 9 and then retract the selection end from 9 to 7, leaving the text from position 5 to 7 selected (the 6th and 7th characters).
The same sequence with TextInput.SelectWords will extend the selection start to a word boundary before or on position 5 and extend the selection end to a word boundary on or past position 9.
This function returns the character position at x and y pixels from the top left of the textInput. Position 0 is before the first character, position 1 is after the first character but before the second, and so on until position text.length, which is after all characters.
This means that for all x values before the first character this function returns 0, and for all x values after the last character this function returns text.length. If the y value is above the text the position will be that of the nearest character on the first line and if it is below the text the position of the nearest character on the last line will be returned.
The cursor position type specifies how the cursor position should be resolved.
rect positionToRectangle(int pos) |
This function takes a character position and returns the rectangle that the cursor would occupy, if it was placed at that character position.
This is similar to setting the cursorPosition, and then querying the cursor rectangle, but the cursorPosition is not changed.
Redoes the last operation if redo is available.
Removes the section of text that is between the start and end positions from the TextInput.
Causes the text from start to end to be selected.
If either start or end is out of range, the selection is not changed.
After calling this, selectionStart will become the lesser and selectionEnd will become the greater (regardless of the order passed to this method).
See also selectionStart and selectionEnd.
Undoes the last operation if undo is available. Deselects any current selection, and updates the selection start to the current cursor position.


Playground is very lightweight version of jsreport. It's available for free to try and share any custom report. It also includes collection of examples to quick start with platform. It's great when you are new into jsreport or you want to share some templates or ideas with other developers.


Hurray you are almost there
Stick Bugged Get Stick Bugged Lol GIF
from
Stickbugged GIFs
No
Yes
Rickroll Dance GIF
from
Rickroll GIFs


| 033:051 Khan | : |
You (O Muhammad SAW) can postpone (the turn of) whom you will of them (your wives), and you may receive whom you will. And whomsoever you desire of those whom you have set aside (her turn temporarily), it is no sin on you (to receive her again), that is better; that they may be comforted and not grieved, and may all be pleased with what you give them. Allah knows what is in your hearts. And Allah is Ever All-Knowing, Most Forbearing. |
| 033:051 Maulana | : |
Thou mayest put off whom thou pleasest of them, and take to thee whom thou pleasest. And whom thou desirest of those whom thou hadst separated provisionally, no blame attaches to thee. This is most proper so that their eyes may be cool and they may not grieve, and that they should be pleased, all of them, with what thou givest them. And Allah knows what is in your hearts. And Allah is ever Knowing, Forbearing. |
| 033:051 Pickthal | : |
Thou canst defer whom thou wilt of them and receive unto thee whom thou wilt, and whomsoever thou desirest of those whom thou hast set aside (temporarily), it is no sin for thee (to receive her again); that is better; that they may be comforted and not grieve, and may all be pleased with what thou givest them. Allah knoweth what is in your hearts (O men), and Allah is ever Forgiving, Clement. |
| 033:051 Rashad | : |
You may gently shun any one of them, and you may bring closer to you any one of them.  In this way, they will be pleased, will have no grief, and will be content with what you equitably offer to all of them.  GOD is Omniscient, Clement. |
| 033:051 Sarwar | : |
You may refuse whichever (of the woman who offer themselves to you) as you want and accept whichever of them you wish.  This would be more delightful for them. They should not be grieved but should be happy with whatever you have given to every one of them. God knows what is in your hearts. God is All-knowing and All-forbearing. |
| 033:051 Shakir | : |
You may put off whom you please of them, and you may take to you whom you please, and whom you desire of those whom you had separated provisionally; no blame attaches to you; this is most proper, so that their eyes may be cool and they may not grieve, and that they should be pleased, all of them with what you give them, and Allah knows what is in your hearts; and Allah is Knowing, Forbearing. |
| 033:051 Sherali | : |
Thou mayest put aside any of them that thou pleasest, and keep with thyself whom thou pleasest; and if thou desirest to take back any of those whom thou hast put aside, there is no blame on thee. That is more likely that their eyes may be cooled, and that they may not grieve, and that they may all be pleased with that which thou hast given them. And ALLAH knows what is in your hearts; and ALLAH is All-Knowing, Forbearing. |
| 033:051 Yusufali | : |
Thou mayest defer (the turn of) any of them that thou pleasest, and thou mayest receive any thou pleasest: and there is no blame on thee if thou invite one whose (turn) thou hadst set aside. This were nigher to the cooling of their eyes, the prevention of their grief, and their satisfaction - that of all of them - with that which thou hast to give them: and Allah knows (all) that is in your hearts: and Allah is All-Knowing, Most Forbearing. |
Concepts/Themes Covered: أركان الإسلام > التوحيد > توحيد الله تعالي > صفات الله تعالى > حليماً Pillars of Islam> Islamic> Oneness of Allah> His Glory's Characteristics> Ever Forbearing أركان الإسلام > (محمد (صلى الله عليه وسلم > أخلاقه وصفاته Pillars of Islam> The Blessed Muhammad(PBUH)> His Manners and Attributes أركان الإسلام > (محمد (صلى الله عليه وسلم > مآثره وخصائصه لله Pillars of Islam> The Blessed Muhammad(PBUH)> Memorable Qualities given to Him by Allah الإنسان والعلاقات الاجتماعية > النساء > المرأة Man and The Social Relations>Women>The Woman
This tool uses eight English parallel translations for the Holy Quran imported from Mr. Clay Smith. You can also visit Qurany Concepts for browsing the Quran themes or topics. If you want to search the Holy Quran for keywords, please visit Qurany Keywords.


OK, OK, nothing to see here. Just to be clear, the Sun isn't a planet! It's the star at the center of our whole solar system, though. It's also big enough to fit about 333,060 Earths inside! With a surface temperature of 5500 degrees Celsius, I don't think we should even consider living here, don't you?


Any re-ordering or permutation of the integers i.n is called a permutation vector of order n. If p is a permutation vector, then p&{ is the corresponding permutation function. For example:
p=: 4 5 2 1 0 3 text=: 'ABCDEF' p { text EFCBAD p&{ text EFCBAD
The phrase k=: A. p gives the index of the permutation vector p in the ordered list of !n permutation vectors of order n, and the function k&A. is the corresponding permutation function. For example:
]k=: A. p 590 k A. text EFCBAD (i.!3) A. i. 3 0 1 2 0 2 1 1 0 2 1 2 0 2 0 1 2 1 0
The phrase c=: C. p gives the (boxed) cycle representation of p, and either p&C. or c&C. provide the corresponding permutation function. For example:
]c=: C. p +-+---+-----+ |2|4 0|5 3 1| +-+---+-----+ c C. text EFCBAD
In the phrases p C. x and c C. x, the order of the permutation is determined by the number of items in x, and abbreviated vectors p and c may therefore be used unambiguously:
3 1 C. text NB. Move items to tail ACEFDB (<3 1) C. text NB. Interchange items ADCBEF (<3 1 4) C. text NB. Rotate items AECBDF
The application of C. to any abbreviated representation produces the standard form, and two applications of C. therefore provide the standard form for any representation. For example:
C. 3 1 +-+-----+ |0|3 1 2| +-+-----+ C. C. 3 1 0 2 3 1 C. C. <3 1 +-+-+---+ |0|2|3 1| +-+-+---+ C. C. <3 1 4 +-+-+-----+ |0|2|4 3 1| +-+-+-----+
| m0 =: /: | Inverse permutation vector |
| m1 =: /:&.C. | Inverse cycle |
| m2 =: (-: >) :: 0: | Not-a-box test |
| m3 =: m1`m0 @. m2 | Inverse permutation |
| m4 =: C.^:2 | Put permutation into standard form |
| m5 =: (<0 _1)&C. | Interchange first and last items |
| m6 =: _1&A. | Reverse |
| m7 =: 3&A. | Rotate last three to the left |
| m8 =: 4&A. | Rotate last three right |
| d9 =: ([: +/[:![:}.[:i.[) A. ] | Rotate last x to the left |
| d10=: (!@[ - !@<:@[) A. ] | Rotate last x to the right |
| m11 =: /:~ | Sort up |
| m12 =: \:~ | Sort down |
| m13 =: ?~ | Random permutation of order y |
| m14=: /:@:?@$~ | Random permutation of order y |
| m15=: ?@! A. i. | Random permutation of order y |
| d16=: A. i. | x-th permutation of order y |
| m17=: all=: i.@! A. i. | All permutations of order y |
| m18=: ,:@i.`([: ,/ 0&,.@ ($:&.<:){"2 1 \:"1@=@i.)@.(1&<) | All permutations of order y (recursive definition) |
| m19=: pow=: {^:(]`(i.@#@[)) | Permutation x to the power y |
| m20=: [: {/ ] $ ,:@[ | Permutation x to the power y |
| m21=: i.@#@[C.~(#&>@C.@[| ])#C.@[ | Permutation x to the power y |
| m22=: pow 2&^ | Permutation x to the power 2^y |
| m23=: 3 : (':'; '{~^:y x') | Permutation x to the power 2^y |
| m24=: {~@]^:(]`[) | Permutation x to the power 2^y |
| m25=: ord=: *./@(#&>"_)@C. | The order of a permutation |
| m26=: sg=: pow i.@ord | Subgroup generated by permutation y |
| m27=: [: {/\ ord $ ,: | " |
| m28=: ~.@(,/)@({"1/~)^:_@(i.@{:@$ ,: ]) | " § 4.4 Hui [4] |
| d29=: \:@[{] | Move items located by x to front of y |
| m30=: 1: |. ] | Rotate y by 1 to the left (or up) |
| d31=: !@[ * ! | Number of perms of y objects x at a time |
| m32=: (] {~ [: /: ] = ' '"_)"1 | Move all blanks to end of row |
| d33=: /:@[ { ] | Move items located by x to end of y |
| m34=: _1: |. ] | Rotate y by 1 to the right (or down) |
| m35=: ~.@(,/)@({"1/~)^:_@(i.@{:@$,]) | Subgroup generated by a matrix of permutations |
| m36=: {"1/~ | The group table of a matrix of permutations |
| m37=: ugt=: ~.@(,/)@({"1/~) | The unique elements of the permutation group |
| m38=: pbi=: i.@{:@$ , ] | Preface a matrix of permutations by the identity |
| m39=: ugt^:_ @ pbi | The subgroup generated by a matrix of permutations (same as m35) |


How to Create a Custom Authentication System with Guard¶
Whether you need to build a traditional login form, an API token authentication system or you need to integrate with some proprietary single-sign-on system, the Guard component can make it easy… and fun!
In this example, you’ll build an API token authentication system and learn how to work with Guard.
Step 1) Create the Authenticator Class¶
Suppose you have an API where your clients will send an X-AUTH-TOKEN
header on each request. This token is composed of the username followed
by a password, separated by a colon (e.g. X-AUTH-TOKEN: coolguy:awesomepassword
).
Your job is to read this, find the associated user (if any) and check
the password.
To create a custom authentication system, just create a class and make it implement GuardAuthenticatorInterface. Or, extend the simpler AbstractGuardAuthenticator. This requires you to implement six methods:
<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
class TokenAuthenticator extends AbstractGuardAuthenticator
{
private $encoderFactory;
public function __construct(EncoderFactoryInterface $encoderFactory)
{
$this->encoderFactory = $encoderFactory;
}
public function getCredentials(Request $request)
{
// Checks if the credential header is provided
if (!$token = $request->headers->get('X-AUTH-TOKEN')) {
return;
}
// Parse the header or ignore it if the format is incorrect.
if (false === strpos($token, ':')) {
return;
}
list($username, $secret) = explode(':', $token, 2);
return array(
'username' => $username,
'secret' => $secret,
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
return $userProvider->loadUserByUsername($credentials['username']);
}
public function checkCredentials($credentials, UserInterface $user)
{
// check credentials - e.g. make sure the password is valid
// return true to cause authentication success
$encoder = $this->encoderFactory->getEncoder($user);
return $encoder->isPasswordValid(
$user->getPassword(),
$credentials['secret'],
$user->getSalt()
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
// on success, let the request continue
return;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
// or to translate this message
// $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, 403);
}
/**
* Called when authentication is needed, but it's not sent
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
// you might translate this message
'message' => 'Authentication Required',
);
return new JsonResponse($data, 401);
}
public function supportsRememberMe()
{
return false;
}
}
Step 2) Configure the Authenticator¶
To finish this, register the class as a service:
$app['app.token_authenticator'] = function ($app) {
return new App\Security\TokenAuthenticator($app['security.encoder_factory']);
};
Finally, configure your security.firewalls key to use this authenticator:
$app['security.firewalls'] = array(
'main' => array(
'guard' => array(
'authenticators' => array(
'app.token_authenticator'
),
// Using more than 1 authenticator, you must specify
// which one is used as entry point.
// 'entry_point' => 'app.token_authenticator',
),
// configure where your users come from. Hardcode them, or load them from somewhere
// https://PrestoPHP.symfony.com/doc/providers/security.html#defining-a-custom-user-provider
'users' => array(
//raw password = foo
'victoria' => array('ROLE_USER', '$2y$10$3i9/lVd8UOFIJ6PAMFt8gu3/r5g0qeCJvoSlLCsvMTythye19F77a'),
),
// 'anonymous' => true
),
);
Note
You can use many authenticators, they are executed by the order they are configured.
You did it! You now have a fully-working API token authentication system. If your homepage required ROLE_USER, then you could test it under different conditions:
# test with no token
curl http://localhost:8000/
# {"message":"Authentication Required"}
# test with a bad token
curl -H "X-AUTH-TOKEN: alan" http://localhost:8000/
# {"message":"Username could not be found."}
# test with a working token
curl -H "X-AUTH-TOKEN: victoria:foo" http://localhost:8000/
# the homepage controller is executed: the page loads normally
For more details read the Symfony cookbook entry on How to Create a Custom Authentication System with Guard.


Enter your name and choose the number of players (1 to 3)
Score:{{ hand.score() }}?
BUST! Dealer Wins
BUST! Hand WinsDealer Wins


Women techmakers Madrid 2016
Today I went to the Women Techmakers Madrid and it was an overdose of Iocain for me, in a possitive way, of course. Iocain? To understand the meaning, you should have watched Teresa de la Torre’s talk, but I will explain a little bit later :)
The organization was fantastic, thanks to Tech & Ladies and Google Campus Madrid! The speakers were awesome, funny and very professional. I learn a lot from different technologies and subjects and I have some ideas to carry out thanks to those talks:
-
Introduction to web technologies with Python (Yamila Moreno): I used to code in groovy with Grails framework and this talk reminded me of those days. You should choose the framework that fits most with the project or even don’t use it and do it with the language itself. She spoke about Brython for Frontend, so maybe I can start with Python and don’t give up Frontend at the same time!
-
Hi, my name is Teresa and I am Iocain addict (Teresa de la Torre): This was a very motivational talk, about leaving your comfort zone and not die trying. You can start learning a new thing by going to a meetup, reading manuals, starting with simple talks.
-
Geb + Spock: long and prosperous life to your functional tests (Esther Lozano): I have worked with Geb in the past and I should work with it again, very reusable, easy to use and with the same syntaxis as JQuery. Esther explained how to use it very well.
-
Creating web elements with Polymer (Gloria Bueno): When I hear about Polymer and Web Components I always want to learn more about it. I should watch this talk when I learn it, because you need to have a knowledge in Polymer to take advantage of the talk.
-
Gamification, ¿do you want to play with me? (Laura Muñoz): I used Gamification when I work for a project for BBVA and it is true that people like gamification very much, sometimes too much and someone has to set limits… But it can be very useful for a business to engage their clients.
-
10 gold rules in software development (Esther Sanz): She spoke about not having different departments for each role. It should be designers, frontend, backend developers…in the same department. It was very inspirational talk too.
-
Arduino and IoT (Internet of Tricks) (Isabel Cabeza and Carmen Checa): This was the funniest talk today. They did a magic trick and then they explained how they did it with Arduino.
-
TDD and hexagonal architecture (Laura Morillo): I have never used TDD but I should try it. You have to do the test first, then the code to make the test works and then refactor the code to make it clean and usable.
-
YouTuber, woman and 9 years old, what can end bad? (Adriana Luengo): A 9 year old girl in Women Techmakers? Yes, she explained how she makes the videos about handicrafts in her Youtube channel and the importance of speaking with her subscribers. She writes her ideas to have enough material each week and every Saturday morning she recordes the videos, it can last 3 or 4 hours sometimes to finish them! She was very sweet and an example for all of us.
-
Project and team management (Rita Madariaga): She spoke about how to manage the issues with the clients in a project and how to manage a team in a non agile development.
-
Predictive Analytics and be early to your client wishes (Laila El Qadi): Big data can help a business to be closer to its clients, give them what they need, even before they know it.
-
Good practices in Angular 1.x and the road for Angular 2 (Ana Belén Medina): I work with AngularJS but I didn’t learn it in a proper way. This talk can help me to use it better (use ‘Controller as’ instead of $scope, avoid $watch and use ng-change instead, use angular.copy, structure folders by functionality). She explains also a little about Angular 2 and the use of Components instead of directives.
-
War of the Worlds: designers and developers (Laura Andina and Josefina Pérez): A very funny talk, but very true. I am a developer, but I want to learn about UX, so I would like to be in both worlds, will I fight with myself? They spoke about the importante of the communications between designers and developers in every step of the process (you have to clarify what are the interactions in the design, how the design changes with real text…). Both designers and developers should know more about the work of the other (UX is research, analysis, design, prototype and user testing, not only an inspirational draw). A designer should know the technology where his/her design will end. After coding, a developer should do a demo to the UX to confirm that the implementation is correct, they should be on the same page from the beginning. They also spoke about the tool Zeplin to collaborate between designers and developers, I have to check it out.
So, as you can see, women have a lot of knowledge to spread and this kind of events are very useful to make women more visible. Now it is time to follow their example!


{% extends 'polyana/base.html' %} {% block content %}
{{m.currency.currency_type}}: {{m.amount}}
{% endfor %}Played battles: {{ player.played_battles }}
Battles won: {{ player.battles_won }}
Winrate: {{ player.winrate | floatformat:3 }}
| Nickname | Winrate | Played battles |
|---|---|---|
| {{ leader.nickname }} | {{ leader.winrate | floatformat:3}} | {{ leader.played_battles }} |


1. Procedural thinking: Break solutions down into steps.
2. Abstract Thinking
1+1=2
3. Systematic Debugging
4. Technological Empathy
Understanding how a computer sees things.
5. Systems thinking
Breaking larger ideas down into smaller component steps.
 When a person goes to a web page like www.google.com, their computer sends an HTTP Request to a server.
The server finds the appropriate HTML document and sends it back to the user's computer where a web browser interprets the page and displays it on the user's screen. This video does a good job of explaining.
HTML
HTML stands for Hypertext Markup Language.
HTML documents form the majority of the content on the web.
HTML documents contain text content which describes "what you see"
and markup which describes "how it looks". This video gives a
good overview.
Tags and Elements
HTML documents are made of HTML elements.
When writing HTML, we tell browsers the type of each
element by using HTML tags. This video explains the
distinction well.

This makes them very unforgiving since a small mistake by a
programmer can cause huge problems in a program.
Inline vs Block Elements
HTML elements are either inline or block.
Block elements form an "invisible box" around the content
inside of them.


piln
What follows now is the list of objects that were paid for here and preserved with their notes:
no censorship permitted
The Earth Plane By Eric Dubay
Reseach about Eric Dubay
mountain
encryption key HBLbLPwFeFB1hLmuZRQ2dqkLD5Xtvf2LJZn
meghaA
lightning network paper
ln


{% extends "store/base.html" %} {% block content %} {% include 'store/header2.html' %} Email Verification {% if verified %} Your account has been verified! Click here to Sign In {% else %} An error occured when we tried to verify your account. Please try again or contact us if the issue persists. {% endif %} {% endblock %}
Email Verification
{% if verified %} Your account has been verified! Click here to Sign In {% else %} An error occured when we tried to verify your account. Please try again or contact us if the issue persists. {% endif %}


{{fileBeingPreviewed.content}}
file path: {{fileBeingPreviewed.path}}
Date last updated: {{fileBeingPreviewed.date}}


Post-Deployment Package Options¶
When the OKD software has been deployed the orchestrator allows you to conveniently run additional Ansible playbooks that are designed to install extra software.
A built-in post-OKD playbook exists, called acme-controller
. Ths
creates an OKD project and installs a utility to automatically
provision certificates using ACME protocol and manage their lifecycle.
Running post-OKD playbooks¶
To execute a post-OKD installation playbook you simply need to name it in
your configuration 1. Essentially, you just need to add the name of the
playbook in the post_okd
list:
okd:
post_okd:
- play: acme-controller
Adding new playbooks¶
Pre-defined Variables¶
Special variables are passed to post-OKD playbooks, so adding your own
OKD applications that can operate the master API after the OKD software is
installed is easy. The playbooks are provided with the following variables by
the create
utility: -
okd_api_hostname
. Essentially the https location of the master’s API.okd_admin_password
. The OKD administration user password. (the user isadmin
)okd_deployment
. The name of deployment.
If a developer password has been supplied the following variable is defined: -
okd_developer_password
. The OKD developer user password (the user isdeveloper
)
If a template project has been created you also get: -
template_namespace
. The project/namespace of the template project
Adding plays¶
To add an ansible playbook you need to: -
Create a directory for your playbook in the orchestrator’s
ansible/post-okd
directoryYour playbook must have a
deploy.yaml
. It is this playbook that thecreate
utility will call. The deploy playbook will be provided with the variables described above.
If you’ve added a my-play/deploy.yaml
playbook you can add it the the list
of post-OKD plays that are run at the end of your deployment by adding it to
the post_okd
list in your configuration:
okd:
post_okd:
- play: acme-controller
- play: my-play
You can organise your playbook into roles and add a directory to
ansible/post-okd/roles
if you wish, or just provide a playbook.
Regardless, you have to define a deploy.yaml
to act as the entry
point of your playbook.
Footnotes
- 1
For up-to-date instructions refer to the built-in
compact-aws-frankfurt-3-11
configuration, which contains significant embedded documentation


:: com :: sun :: star :: form :: component ::
|
| service CommandButton |
- Description
- specifies the control model for a clickable button which is part of a form
component hierarchy.
- See also
- ImageButton
|
| Properties' Summary |
::com::sun::star::form::FormButtonType
ButtonType |
describes the action to be executed by the button when pressed.
|
string
TargetFrame |
describes the frame, where to open the document specified by the TargetURL.
|
string
TargetURL |
specifies the URL, which should be opened if the button was clicked.
|
boolean
DefaultState |
[ OPTIONAL ]
specifies the default toggle state for the button, used when it is reset.
|
| Exported Interfaces - Details |
::com::sun::star::form::XImageProducerSupplier
- Description
- supplies the image producer when the button is to display an image.
If the ::com::sun::star::awt::UnoControlButtonModel::ImageURL points to the location of an
image to be displayed on the button, this interface can be used to retrieve an image
producer, which itself will supply the image.
Usually, a control belonging to the model will use this interface to obtain the
image to be painted
|
|
::com::sun::star::form::XReset
- Usage Restrictions
- optional
- Description
- allows resetting the button
This property is meaningful only when ::com::sun::star::awt::UnoControlButtonModel::Toggle
is true. In this case, the DefaultState controls to which State the button will
be reset, when ::com::sun::star::form::XReset::reset is invoked.
For a given implementation of the interface, if this (optional) interface is present, then also the optional
property DefaultState must be present.
|
|
| Properties' Details |
ButtonType
::com::sun::star::form::FormButtonType ButtonType;
- Description
- describes the action to be executed by the button when pressed.
|
|
TargetFrame
string TargetFrame;
- Description
- describes the frame, where to open the document specified by the TargetURL.
This property is evaluated if the button is of type URL.
As always, there is a number of target names which have a special meaning, and force
a special ::com::sun::star::frame::Frame to be used.
|
|
TargetURL
string TargetURL;
- Description
- specifies the URL, which should be opened if the button was clicked.
This property is evaluated if the button is of type URL.
- See also
- ::com::sun::star::form::FormButtonType
|
|
DefaultState
boolean DefaultState;
- Usage Restrictions
- optional
- Description
- specifies the default toggle state for the button, used when it is reset.
This property is meaningful only when ::com::sun::star::awt::UnoControlButtonModel::Toggle
is true. In this case, the DefaultState controls to which State the button will
be reset.
For a given implementation of the interface, if this (optional) property is present, then also the optional
interface ::com::sun::star::form::XReset must be present.
|
|
Top of Page
Copyright © 2013, The Apache Software Foundation, Licensed under the Apache License, Version 2.0. Apache, the Apache feather logo, Apache OpenOffice and OpenOffice.org are trademarks of The Apache Software Foundation. Other names may be trademarks of their respective owners.


This is link 5439deda-d2c7-4ab9-8194-352a6e3464ae
This is link 33d20ae0-4562-4186-a35b-d44b00ae43bd This is link 47817d21-4f5c-4d7f-8ccc-876bfd669143
This is text a8d5af7d-ab4c-447c-a3ca-3967f51aac8a This is link c2cfa0da-02e1-45eb-bbc2-6db2dc951943
This is link e37b408d-4ca5-4c33-befe-dd7b66c71cea This is link 8434e8a8-6758-4720-8486-a9188e1d2165
This is text afafa0ab-7dcb-4007-9c4b-7dd33d806420 This is link 00a2c563-1ceb-4458-88b7-d759ae08369c
This is text eb4826c5-2086-4098-9893-51eb847a20a1 This is text 12416abb-3046-47a1-b9e0-f4824aaf9fe4 This is text 0112e26b-f508-44f9-82ae-f2f1e02960e8
This is text a26e7e57-c5d6-47a6-bf4f-7bcef04fa985 This is link dec6f05b-e01a-4126-a8a7-5fbf3433e554 This is text cb2f971f-14ac-4bc7-be30-d624e5eac845
This is text 04514143-41de-4352-a0c2-172b7b4b6e92 This is link 62544d9e-c271-483b-90b2-5ef86570f387 This is text 44f271a9-f924-49b6-b95b-0ace13090ff8
This is text 51400de5-85ef-4087-8723-79882b57a6f9 This is link 3a50bc7a-0133-4f57-bfb4-1b66bfd363a4 This is link d23273b3-4600-44ef-89bd-3087ac076e2e


Indicate the potential ability of an individual to develop a disease or a medical condition, who currently does not have a clinically evident disease or a disorder. For instance, the C-reactive protein (CRP) level may be used as a susceptibility/risk biomarker to identify the risk of COVID-19 aggravation. Pre-existing conditions and biological age of an individual are being identified as susceptibility/risk biomarkers.
Identify or confirm the existence of a disease or condition of interest, or to recognize individuals with the disease subtype. For example, Severe Acute Respiratory Syndrome Coronavirus 2 (SARS-CoV-2) nucleic acid is the leading diagnostic marker for COVID-19. This biomarker is being tested by Real-Time PCR or Rapid immunochromatography tests (antigen-based detection / antibody-based detection) or Serological tests in the blood (IgM and IgG).
Access the status of the disease or medical condition on the exposure of or effect of a medical substance or an environmental agent. In the case of COVID-19, various markers levels such as IL-6, procalcitonin (PCT), Ferritin, KL-6, cardiac troponin values (hs-cTnI), B-type natriuretic peptide (BNP) and N-terminal pro-b-type natriuretic peptide (NT-proBNP) are often seen to be dysregulated in COVID-19 patients.
Identify the probability of a clinical occurrence, recurrence of disease, or worsening in patients with an unusual illness or medical condition. For instance, CD8+ T lymphocyte counts, and D-dimer are independent prognostic markers of disease severity in COVID-19 patients.
Classify individuals who are more likely to experience a favorable or unfavorable effect from exposure to a medicinal product or an environmental agent than similar individuals without the biomarker. In the case of COVID-19, ICU admission may be predicted by elevations in leukocyte count and levels of alanine aminotransferase, aspartate transaminase, and LDH.
Demonstrate that a biological response has occurred in an individual exposed to a medicinal product or to an environmental agent. For example, CYP450 and CYP3A4-mediated drug interactions are being examined as pharmacodynamic biomarkers.
measure the probability, occurrence, or degree of an adverse effect of toxicity on exposure to a medicinal product or an environmental agent. For instance, Chloroquines used to treat COVID-19 patients show clinically apparent liver injury and increase levels of serum aminotransferases.


legendary-sniffle
A project to help students know their gear
Project created by Emma Walker, Matthew Greenhalgh, Rainer Leit, Conor Hegarty and James Gardner
Project created by Emma Walker, Matthew Greenhalgh, Rainer Leit, Conor Hegarty and James Gardner


JavaScript Example
Weather Forecast
°C
°F
°K
Cloudy
20° C
August 16
Monday
Sunny
37° C
August 17
Tuesday
Rainy
7° C
August 18
Wednesday
Snowy
-10° C
August 19
Thursday


{% extends 'core/base.html' %} {% load static %} {% load i18n %} {% load add_export_elements_classes from directory_components %} {% block head_css %} {{ block.super }} {% endblock %} {% block head_title %} {{ page.seo_title|default:"Foreign Direct Investment Opportunities - great.gov.uk" }} {% endblock %} {% block head_sharing_metadata %} {{ block.super }} {% endblock %} {% block content %} Contact us about foreign direct investment opportunities Got a question about one of our foreign direct investment opportunities? Get in touch and give as much information as you can. {% csrf_token %} {% include 'directory_components/form_widgets/form_field.html' with field=form.given_name %} {% include 'directory_components/form_widgets/form_field.html' with field=form.family_name %} {% include 'directory_components/form_widgets/form_field.html' with field=form.job_title %} {% include 'directory_components/form_widgets/form_field.html' with field=form.email_address %} {% include 'directory_components/form_widgets/form_field.html' with field=form.phone_number %} {% include 'directory_components/form_widgets/form_field.html' with field=form.company_name %} {% include 'directory_components/form_widgets/form_field.html' with field=form.website_url %} {% include 'directory_components/form_widgets/form_field.html' with field=form.company_address %} {% include 'directory_components/form_widgets/form_field.html' with field=form.country %} {% include 'directory_components/form_widgets/form_field.html' with field=form.industry %} {% include 'directory_components/form_widgets/form_field.html' with field=form.opportunities %} {% include 'directory_components/form_widgets/form_field.html' with field=form.how_can_we_help %} {% include 'directory_components/form_widgets/form_field.html' with field=form.your_plans %} {% include 'directory_components/form_widgets/form_field.html' with field=form.how_did_you_hear %} {% include 'core/includes/form_consent_hpo.html' with form=form %} {% include 'directory_components/form_widgets/form_field.html' with field=form.captcha %} {% trans "Submit" %} {% endblock %} {% block body_js %} {{ block.super }} {% endblock %}
Got a question about one of our foreign direct investment opportunities? Get in touch and give as much information as you can.


Tag it! ~ Tag editor and suggestions
After looking for a jQuery plugin for handling a 'tag suggestion' form field, in much the same way ZenDesk.com does, I ended up developing a customization of jQuery UI that does the same interaction.
Built with jQuery and jQueryUI.
By Levy Carneiro Jr


--- layout: post title: Python geoprocessing with .csv and field types date: 2011-06-24 16:31:26.000000000 -05:00 type: post published: true status: publish categories: - Geoprocessing with Python tags: [] meta: _edit_last: '15714693' _wpas_done_twitter: '1' _wpas_skip_fb: '1' author: login: broberts65 email<EMAIL_ADDRESS>display_name: Bob Roberts first_name: '' last_name: '' ---
A while back I showed how to import a .csv to create a shapefile. The script that I had written for a client went unused for quite sometime and after trying out the resulting shapefile it was determined that the fields from the .csv were being formatted incorrectly in the resulting shapefile.
Last night I set out to fix this. The idea was to create a blank database table with the proper field formats and then copy the values from the .csv to the database table. What I thought was going to take 30 minutes to complete, turned into a long adventure. About 6 hours later I finally figured it out. Interestingly enough, I found almost NO info on what I was trying to do. Finally I found a partial reference in a forum thread from 2006 and wasn't sure if it would even work.
[sourcecode language="Python"]
# import required modules
import sys, os, glob
import arcgisscripting
# Create the geoprocessor object
gp = arcgisscripting.create()
# I was having issues with a table view not deleting so I added the overwrite
gp.overwriteoutput = 1
## System arguments
# Input .csv
File_in = sys.argv[1]
# Output shapefile
File_out = sys.argv[2]
# Input table_template
tabletemp = sys.argv[3]
# Set the workspace for the processing files
gp.workspace = os.path.dirname(sys.argv[1])
# Convert the .csv to .dbf in the directory from sys.argv[3]
gp.AddMessage("\nCreating processing .dbf from .csv...")
gp.TableToDbase_conversion(File_in, os.path.dirname(sys.argv[3]))
## Make copies so that processing doesn't take place on the originals.
gp.AddMessage("\nCreating processing file...")
gp.Copy_management(File_in[:-4]+".dbf", "tempfile.dbf")
gp.Copy_management(tabletemp, "temptable.dbf")
# Need to use a search cursor to read the values from the input file
# and then use a insert cursor to write to the new table.
# The part I could not figure out is the SetValue function. By using a
# while statement we can read thru each of the records in the input .csv
# and then write them out using SetValue.
# The SetValue takes two parameters; the first is the field name in the new
# table and the second is the field name in the read file. Quite similiar
# to Field Mapping actually. The input field name must not match the output
# field name, however the formats do need to match.
gp.AddMessage("\nSearch cursor process...")
intable = "tempfile.dbf"
outtable = "temptable.dbf"
table = gp.SearchCursor(intable)
run = table.Next()
outRows = gp.InsertCursor(outtable)
while run:
outRow = outRows.NewRow()
outRow.SetValue("FieldName1", run.FieldName1)
outRow.SetValue("FieldName2", run.FieldName2)
outRow.SetValue("FieldName3", run.FieldName3)
outRow.SetValue("FieldName4", run.FieldName4)
run = table.Next()
del outRows
# From here you can do whatever you wish with the new table "temptable.dbf"
# If you want to make a points shapefile you will need to use the MakeEventLayer
# as shown below.
gp.AddMessage("Creating the output points file...")
# Make a point shapefile based on the X,Y in the table
gp.MakeXYEventLayer_management("temptable.dbf", "X", "Y", "Table_output")
gp.CopyFeatures_management("Table_output", "temp.shp")
# Create a prj file for temp.shp
coordsys = "Coordinate Systems/Geographic Coordinate Systems/World/WGS 1984.prj"
gp.defineprojection("temp.shp", coordsys)
gp.AddMessage("Creating final output file...")
# Create the output files based on the user's input
gp.Rename_management("temp.shp", File_out)
gp.AddMessage("Cleanup...")
# Delete "process" files
for file in glob.glob(gp.workspace+"/temp*"):
os.remove(file)
for file in glob.glob(gp.workspace+"/*xml"):
os.remove(file)
gp.AddMessage("\nImport Successful.\n")
[/sourcecode]
Hope this helps!
BR


This section helps you budget
Some sources might be:
Don't include transportation costs. Examples of expenses:
Estimating your budget etc...


Here you can find the projects:
You can find the shown image here and the source on GitHub.
Thanks to neocities for hosting. Made by rugk.


{% extends "base.html" %} {% block title %}Basic Formset with Admin Widget{% endblock %} {% block extrahead %} {{ formset.media }} {% endblock %} {% block content %}
Here's another example that uses the "added" callback, based on a comment submitted by lfborjas.
I apologize for not styling the calendar popup properly -- didn't really have much time. Sure, it'd have made the demo prettier, but I think you'll still get the idea, ugly calendar or no.
{% endblock %}


YAFFH is a free file host that stores your files forever.
The permalinks returned by YAFFH will never expire and will still work even if we go out of business trying to host your files.
Currently, only Mozilla Firefox supports the YAFFH uploading interface but the permalinks work in all standards-compliant browsers.
FAQ
What file formats are supported?
All of them and then some.
Is there a maximum file size limit?
No. You may upload files of any file size.
What are the shortcuts?
+
Add a new file.
-
Remove last file.
p
Skip to a specified permalink.
f
Skip to a specified file.
How are the files instantly uploaded with Ajax?
Advanced Instajax™ technology developed by Elijah Grey hacks your browser and pre-uploads files that are determined to be most likely to be uploaded by you. It determines this based on your most recently modified files.
How are the files instantly downloaded by my browser?
YAFFH hacks your browser to download and cache the files before they are even requested.


Ethereum Dapp DEMO
Guess the secret number in the Ethereum contract and you will receive double your stake.
Each guess costs
1
ETH.
Money in the bank:
Wei (=
ETH)
You have
Wei (=
ETH)
Your ETH address:


In this part of the tutorial, we will investigate how to speed up certain functions operating on pandas DataFrames using three different techniques: Cython, Numba and pandas.eval(). We will see a speed improvement of ~200 when we use Cython and Numba on a test function operating row-wise on the DataFrame. Using pandas.eval() we will speed up a sum by an order of ~2.
DataFrames
pandas.eval()
DataFrame
For many use cases writing pandas in pure Python and NumPy is sufficient. In some computationally heavy applications however, it can be possible to achieve sizable speed-ups by offloading work to cython.
This tutorial assumes you have refactored as much as possible in Python, for example by trying to remove for-loops and making use of NumPy vectorization. It’s always worth optimising in Python first.
This tutorial walks through a “typical” process of cythonizing a slow computation. We use an example from the Cython documentation but in the context of pandas. Our final cythonized solution is around 100 times faster than the pure Python solution.
We have a DataFrame to which we want to apply a function row-wise.
In [1]: df = pd.DataFrame({'a': np.random.randn(1000), ...: 'b': np.random.randn(1000), ...: 'N': np.random.randint(100, 1000, (1000)), ...: 'x': 'x'}) ...: In [2]: df Out[2]: a b N x 0 0.469112 -0.218470 585 x 1 -0.282863 -0.061645 841 x 2 -1.509059 -0.723780 251 x 3 -1.135632 0.551225 972 x 4 1.212112 -0.497767 181 x .. ... ... ... .. 995 -1.512743 0.874737 374 x 996 0.933753 1.120790 246 x 997 -0.308013 0.198768 157 x 998 -0.079915 1.757555 977 x 999 -1.010589 -1.115680 770 x [1000 rows x 4 columns]
Here’s the function in pure Python:
In [3]: def f(x): ...: return x * (x - 1) ...: In [4]: def integrate_f(a, b, N): ...: s = 0 ...: dx = (b - a) / N ...: for i in range(N): ...: s += f(a + i * dx) ...: return s * dx ...:
We achieve our result by using apply (row-wise):
apply
In [7]: %timeit df.apply(lambda x: integrate_f(x['a'], x['b'], x['N']), axis=1) 10 loops, best of 3: 174 ms per loop
But clearly this isn’t fast enough for us. Let’s take a look and see where the time is spent during this operation (limited to the most time consuming four calls) using the prun ipython magic function:
In [5]: %prun -l 4 df.apply(lambda x: integrate_f(x['a'], x['b'], x['N']), axis=1) # noqa E999 782222 function calls (779196 primitive calls) in 0.264 seconds Ordered by: internal time List reduced from 230 to 4 due to restriction <4> ncalls tottime percall cumtime percall filename:lineno(function) 1000 0.095 0.000 0.141 0.000 <ipython-input-4-c2a74e076cf0>:1(integrate_f) 552423 0.046 0.000 0.046 0.000 <ipython-input-3-c138bdd570e3>:1(f) 3000 0.008 0.000 0.108 0.000 base.py:4621(get_value) 3000 0.008 0.000 0.054 0.000 base.py:684(array)
By far the majority of time is spend inside either integrate_f or f, hence we’ll concentrate our efforts cythonizing these two functions.
integrate_f
f
Note
In Python 2 replacing the range with its generator counterpart (xrange) would mean the range line would vanish. In Python 3 range is already a generator.
range
xrange
First we’re going to need to import the Cython magic function to ipython:
In [6]: %load_ext Cython
Now, let’s simply copy our functions over to Cython as is (the suffix is here to distinguish between function versions):
In [7]: %%cython ...: def f_plain(x): ...: return x * (x - 1) ...: def integrate_f_plain(a, b, N): ...: s = 0 ...: dx = (b - a) / N ...: for i in range(N): ...: s += f_plain(a + i * dx) ...: return s * dx ...:
If you’re having trouble pasting the above into your ipython, you may need to be using bleeding edge ipython for paste to play well with cell magics.
In [4]: %timeit df.apply(lambda x: integrate_f_plain(x['a'], x['b'], x['N']), axis=1) 10 loops, best of 3: 85.5 ms per loop
Already this has shaved a third off, not too bad for a simple copy and paste.
We get another huge improvement simply by providing type information:
In [8]: %%cython ...: cdef double f_typed(double x) except? -2: ...: return x * (x - 1) ...: cpdef double integrate_f_typed(double a, double b, int N): ...: cdef int i ...: cdef double s, dx ...: s = 0 ...: dx = (b - a) / N ...: for i in range(N): ...: s += f_typed(a + i * dx) ...: return s * dx ...:
In [4]: %timeit df.apply(lambda x: integrate_f_typed(x['a'], x['b'], x['N']), axis=1) 10 loops, best of 3: 20.3 ms per loop
Now, we’re talking! It’s now over ten times faster than the original python implementation, and we haven’t really modified the code. Let’s have another look at what’s eating up time:
In [9]: %prun -l 4 df.apply(lambda x: integrate_f_typed(x['a'], x['b'], x['N']), axis=1) 229795 function calls (226769 primitive calls) in 0.101 seconds Ordered by: internal time List reduced from 225 to 4 due to restriction <4> ncalls tottime percall cumtime percall filename:lineno(function) 3000 0.007 0.000 0.088 0.000 base.py:4621(get_value) 3000 0.007 0.000 0.044 0.000 base.py:684(array) 33354 0.006 0.000 0.011 0.000 {built-in method builtins.isinstance} 3000 0.006 0.000 0.015 0.000 numpy_.py:43(__init__)
It’s calling series… a lot! It’s creating a Series from each row, and get-ting from both the index and the series (three times for each row). Function calls are expensive in Python, so maybe we could minimize these by cythonizing the apply part.
We are now passing ndarrays into the Cython function, fortunately Cython plays very nicely with NumPy.
In [10]: %%cython ....: cimport numpy as np ....: import numpy as np ....: cdef double f_typed(double x) except? -2: ....: return x * (x - 1) ....: cpdef double integrate_f_typed(double a, double b, int N): ....: cdef int i ....: cdef double s, dx ....: s = 0 ....: dx = (b - a) / N ....: for i in range(N): ....: s += f_typed(a + i * dx) ....: return s * dx ....: cpdef np.ndarray[double] apply_integrate_f(np.ndarray col_a, np.ndarray col_b, ....: np.ndarray col_N): ....: assert (col_a.dtype == np.float ....: and col_b.dtype == np.float and col_N.dtype == np.int) ....: cdef Py_ssize_t i, n = len(col_N) ....: assert (len(col_a) == len(col_b) == n) ....: cdef np.ndarray[double] res = np.empty(n) ....: for i in range(len(col_a)): ....: res[i] = integrate_f_typed(col_a[i], col_b[i], col_N[i]) ....: return res ....:
The implementation is simple, it creates an array of zeros and loops over the rows, applying our integrate_f_typed, and putting this in the zeros array.
integrate_f_typed
Warning
You can not pass a Series directly as a ndarray typed parameter to a Cython function. Instead pass the actual ndarray using the Series.to_numpy(). The reason is that the Cython definition is specific to an ndarray and not the passed Series.
Series
ndarray
Series.to_numpy()
So, do not do this:
apply_integrate_f(df['a'], df['b'], df['N'])
But rather, use Series.to_numpy() to get the underlying ndarray:
apply_integrate_f(df['a'].to_numpy(), df['b'].to_numpy(), df['N'].to_numpy())
Loops like this would be extremely slow in Python, but in Cython looping over NumPy arrays is fast.
In [4]: %timeit apply_integrate_f(df['a'].to_numpy(), df['b'].to_numpy(), df['N'].to_numpy()) 1000 loops, best of 3: 1.25 ms per loop
We’ve gotten another big improvement. Let’s check again where the time is spent:
In [11]: %%prun -l 4 apply_integrate_f(df['a'].to_numpy(), ....: df['b'].to_numpy(), ....: df['N'].to_numpy()) ....: 260 function calls in 0.001 seconds Ordered by: internal time List reduced from 65 to 4 due to restriction <4> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.001 0.001 0.001 0.001 {built-in method _cython_magic_a87ed6057fd15f22198299d71d154f60.apply_integrate_f} 1 0.000 0.000 0.001 0.001 {built-in method builtins.exec} 3 0.000 0.000 0.000 0.000 frame.py:2767(__getitem__) 3 0.000 0.000 0.000 0.000 managers.py:950(iget)
As one might expect, the majority of the time is now spent in apply_integrate_f, so if we wanted to make anymore efficiencies we must continue to concentrate our efforts here.
apply_integrate_f
There is still hope for improvement. Here’s an example of using some more advanced Cython techniques:
In [12]: %%cython ....: cimport cython ....: cimport numpy as np ....: import numpy as np ....: cdef double f_typed(double x) except? -2: ....: return x * (x - 1) ....: cpdef double integrate_f_typed(double a, double b, int N): ....: cdef int i ....: cdef double s, dx ....: s = 0 ....: dx = (b - a) / N ....: for i in range(N): ....: s += f_typed(a + i * dx) ....: return s * dx ....: @cython.boundscheck(False) ....: @cython.wraparound(False) ....: cpdef np.ndarray[double] apply_integrate_f_wrap(np.ndarray[double] col_a, ....: np.ndarray[double] col_b, ....: np.ndarray[int] col_N): ....: cdef int i, n = len(col_N) ....: assert len(col_a) == len(col_b) == n ....: cdef np.ndarray[double] res = np.empty(n) ....: for i in range(n): ....: res[i] = integrate_f_typed(col_a[i], col_b[i], col_N[i]) ....: return res ....:
In [4]: %timeit apply_integrate_f_wrap(df['a'].to_numpy(), df['b'].to_numpy(), df['N'].to_numpy()) 1000 loops, best of 3: 987 us per loop
Even faster, with the caveat that a bug in our Cython code (an off-by-one error, for example) might cause a segfault because memory access isn’t checked. For more about boundscheck and wraparound, see the Cython docs on compiler directives.
boundscheck
wraparound
A recent alternative to statically compiling Cython code, is to use a dynamic jit-compiler, Numba.
Numba gives you the power to speed up your applications with high performance functions written directly in Python. With a few annotations, array-oriented and math-heavy Python code can be just-in-time compiled to native machine instructions, similar in performance to C, C++ and Fortran, without having to switch languages or Python interpreters.
Numba works by generating optimized machine code using the LLVM compiler infrastructure at import time, runtime, or statically (using the included pycc tool). Numba supports compilation of Python to run on either CPU or GPU hardware, and is designed to integrate with the Python scientific software stack.
You will need to install Numba. This is easy with conda, by using: conda install numba, see installing using miniconda.
conda
conda install numba
As of Numba version 0.20, pandas objects cannot be passed directly to Numba-compiled functions. Instead, one must pass the NumPy array underlying the pandas object to the Numba-compiled function as demonstrated below.
We demonstrate how to use Numba to just-in-time compile our code. We simply take the plain Python code from above and annotate with the @jit decorator.
@jit
import numba @numba.jit def f_plain(x): return x * (x - 1) @numba.jit def integrate_f_numba(a, b, N): s = 0 dx = (b - a) / N for i in range(N): s += f_plain(a + i * dx) return s * dx @numba.jit def apply_integrate_f_numba(col_a, col_b, col_N): n = len(col_N) result = np.empty(n, dtype='float64') assert len(col_a) == len(col_b) == n for i in range(n): result[i] = integrate_f_numba(col_a[i], col_b[i], col_N[i]) return result def compute_numba(df): result = apply_integrate_f_numba(df['a'].to_numpy(), df['b'].to_numpy(), df['N'].to_numpy()) return pd.Series(result, index=df.index, name='result')
Note that we directly pass NumPy arrays to the Numba function. compute_numba is just a wrapper that provides a nicer interface by passing/returning pandas objects.
compute_numba
In [4]: %timeit compute_numba(df) 1000 loops, best of 3: 798 us per loop
In this example, using Numba was faster than Cython.
Numba can also be used to write vectorized functions that do not require the user to explicitly loop over the observations of a vector; a vectorized function will be applied to each row automatically. Consider the following toy example of doubling each observation:
import numba def double_every_value_nonumba(x): return x * 2 @numba.vectorize def double_every_value_withnumba(x): # noqa E501 return x * 2
# Custom function without numba In [5]: %timeit df['col1_doubled'] = df['a'].apply(double_every_value_nonumba) # noqa E501 1000 loops, best of 3: 797 us per loop # Standard implementation (faster than a custom function) In [6]: %timeit df['col1_doubled'] = df['a'] * 2 1000 loops, best of 3: 233 us per loop # Custom function with numba In [7]: %timeit (df['col1_doubled'] = double_every_value_withnumba(df['a'].to_numpy()) 1000 loops, best of 3: 145 us per loop
Numba will execute on any function, but can only accelerate certain classes of functions.
Numba is best at accelerating functions that apply numerical functions to NumPy arrays. When passed a function that only uses operations it knows how to accelerate, it will execute in nopython mode.
nopython
If Numba is passed a function that includes something it doesn’t know how to work with – a category that currently includes sets, lists, dictionaries, or string functions – it will revert to object mode. In object mode, Numba will execute but your code will not speed up significantly. If you would prefer that Numba throw an error if it cannot compile a function in a way that speeds up your code, pass Numba the argument nopython=True (e.g. @numba.jit(nopython=True)). For more on troubleshooting Numba modes, see the Numba troubleshooting page.
object mode
nopython=True
@numba.jit(nopython=True)
Read more in the Numba docs.
eval()
The top-level function pandas.eval() implements expression evaluation of Series and DataFrame objects.
To benefit from using eval() you need to install numexpr. See the recommended dependencies section for more details.
numexpr
The point of using eval() for expression evaluation rather than plain Python is two-fold: 1) large DataFrame objects are evaluated more efficiently and 2) large arithmetic and boolean expressions are evaluated all at once by the underlying engine (by default numexpr is used for evaluation).
You should not use eval() for simple expressions or for expressions involving small DataFrames. In fact, eval() is many orders of magnitude slower for smaller expressions/objects than plain ol’ Python. A good rule of thumb is to only use eval() when you have a DataFrame with more than 10,000 rows.
eval() supports all arithmetic expressions supported by the engine in addition to some extensions available only in pandas.
The larger the frame and the larger the expression the more speedup you will see from using eval().
These operations are supported by pandas.eval():
Arithmetic operations except for the left shift (<<) and right shift (>>) operators, e.g., df + 2 * pi / s ** 4 % 42 - the_golden_ratio
<<
>>
df + 2 * pi / s ** 4 % 42 - the_golden_ratio
Comparison operations, including chained comparisons, e.g., 2 < df < df2
2 < df < df2
Boolean operations, e.g., df < df2 and df3 < df4 or not df_bool
df < df2 and df3 < df4 or not df_bool
list and tuple literals, e.g., [1, 2] or (1, 2)
list
tuple
[1, 2]
(1, 2)
Attribute access, e.g., df.a
df.a
Subscript expressions, e.g., df[0]
df[0]
Simple variable evaluation, e.g., pd.eval('df') (this is not very useful)
pd.eval('df')
Math functions: sin, cos, exp, log, expm1, log1p, sqrt, sinh, cosh, tanh, arcsin, arccos, arctan, arccosh, arcsinh, arctanh, abs, arctan2 and log10.
This Python syntax is not allowed:
Expressions
Function calls other than math functions. is/is not operations if expressions lambda expressions list/set/dict comprehensions Literal dict and set expressions yield expressions Generator expressions Boolean expressions consisting of only scalar values
Function calls other than math functions.
is/is not operations
is
is not
if expressions
if
lambda expressions
lambda
list/set/dict comprehensions
set
dict
Literal dict and set expressions
yield expressions
yield
Generator expressions
Boolean expressions consisting of only scalar values
Statements
Neither simple nor compound statements are allowed. This includes things like for, while, and if.
for
while
pandas.eval() works well with expressions containing large arrays.
First let’s create a few decent-sized arrays to play with:
In [13]: nrows, ncols = 20000, 100 In [14]: df1, df2, df3, df4 = [pd.DataFrame(np.random.randn(nrows, ncols)) for _ in range(4)]
Now let’s compare adding them together using plain ol’ Python versus eval():
In [15]: %timeit df1 + df2 + df3 + df4 20.9 ms +- 68.8 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
In [16]: %timeit pd.eval('df1 + df2 + df3 + df4') 8.36 ms +- 73.7 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
Now let’s do the same thing but with comparisons:
In [17]: %timeit (df1 > 0) & (df2 > 0) & (df3 > 0) & (df4 > 0) 91 ms +- 491 us per loop (mean +- std. dev. of 7 runs, 10 loops each)
In [18]: %timeit pd.eval('(df1 > 0) & (df2 > 0) & (df3 > 0) & (df4 > 0)') 12.4 ms +- 530 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
eval() also works with unaligned pandas objects:
In [19]: s = pd.Series(np.random.randn(50)) In [20]: %timeit df1 + df2 + df3 + df4 + s 72.9 ms +- 701 us per loop (mean +- std. dev. of 7 runs, 10 loops each)
In [21]: %timeit pd.eval('df1 + df2 + df3 + df4 + s') 9.28 ms +- 84.3 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
Operations such as
1 and 2 # would parse to 1 & 2, but should evaluate to 2 3 or 4 # would parse to 3 | 4, but should evaluate to 3 ~1 # this is okay, but slower when using eval
should be performed in Python. An exception will be raised if you try to perform any boolean/bitwise operations with scalar operands that are not of type bool or np.bool_. Again, you should perform these kinds of operations in plain Python.
bool
np.bool_
DataFrame.eval
In addition to the top level pandas.eval() function you can also evaluate an expression in the “context” of a DataFrame.
In [22]: df = pd.DataFrame(np.random.randn(5, 2), columns=['a', 'b']) In [23]: df.eval('a + b') Out[23]: 0 -0.246747 1 0.867786 2 -1.626063 3 -1.134978 4 -1.027798 dtype: float64
Any expression that is a valid pandas.eval() expression is also a valid DataFrame.eval() expression, with the added benefit that you don’t have to prefix the name of the DataFrame to the column(s) you’re interested in evaluating.
DataFrame.eval()
In addition, you can perform assignment of columns within an expression. This allows for formulaic evaluation. The assignment target can be a new column name or an existing column name, and it must be a valid Python identifier.
The inplace keyword determines whether this assignment will performed on the original DataFrame or return a copy with the new column.
inplace
For backwards compatibility, inplace defaults to True if not specified. This will change in a future version of pandas - if your code depends on an inplace assignment you should update to explicitly set inplace=True.
True
inplace=True
In [24]: df = pd.DataFrame(dict(a=range(5), b=range(5, 10))) In [25]: df.eval('c = a + b', inplace=True) In [26]: df.eval('d = a + b + c', inplace=True) In [27]: df.eval('a = 1', inplace=True) In [28]: df Out[28]: a b c d 0 1 5 5 10 1 1 6 7 14 2 1 7 9 18 3 1 8 11 22 4 1 9 13 26
When inplace is set to False, a copy of the DataFrame with the new or modified columns is returned and the original frame is unchanged.
False
In [29]: df Out[29]: a b c d 0 1 5 5 10 1 1 6 7 14 2 1 7 9 18 3 1 8 11 22 4 1 9 13 26 In [30]: df.eval('e = a - c', inplace=False) Out[30]: a b c d e 0 1 5 5 10 -4 1 1 6 7 14 -6 2 1 7 9 18 -8 3 1 8 11 22 -10 4 1 9 13 26 -12 In [31]: df Out[31]: a b c d 0 1 5 5 10 1 1 6 7 14 2 1 7 9 18 3 1 8 11 22 4 1 9 13 26
As a convenience, multiple assignments can be performed by using a multi-line string.
In [32]: df.eval(""" ....: c = a + b ....: d = a + b + c ....: a = 1""", inplace=False) ....: Out[32]: a b c d 0 1 5 6 12 1 1 6 7 14 2 1 7 8 16 3 1 8 9 18 4 1 9 10 20
The equivalent in standard Python would be
In [33]: df = pd.DataFrame(dict(a=range(5), b=range(5, 10))) In [34]: df['c'] = df['a'] + df['b'] In [35]: df['d'] = df['a'] + df['b'] + df['c'] In [36]: df['a'] = 1 In [37]: df Out[37]: a b c d 0 1 5 5 10 1 1 6 7 14 2 1 7 9 18 3 1 8 11 22 4 1 9 13 26
The query method has a inplace keyword which determines whether the query modifies the original frame.
query
In [38]: df = pd.DataFrame(dict(a=range(5), b=range(5, 10))) In [39]: df.query('a > 2') Out[39]: a b 3 3 8 4 4 9 In [40]: df.query('a > 2', inplace=True) In [41]: df Out[41]: a b 3 3 8 4 4 9
Unlike with eval, the default value for inplace for query is False. This is consistent with prior versions of pandas.
eval
You must explicitly reference any local variable that you want to use in an expression by placing the @ character in front of the name. For example,
@
In [42]: df = pd.DataFrame(np.random.randn(5, 2), columns=list('ab')) In [43]: newcol = np.random.randn(len(df)) In [44]: df.eval('b + @newcol') Out[44]: 0 -0.173926 1 2.493083 2 -0.881831 3 -0.691045 4 1.334703 dtype: float64 In [45]: df.query('b < @newcol') Out[45]: a b 0 0.863987 -0.115998 2 -2.621419 -1.297879
If you don’t prefix the local variable with @, pandas will raise an exception telling you the variable is undefined.
When using DataFrame.eval() and DataFrame.query(), this allows you to have a local variable and a DataFrame column with the same name in an expression.
DataFrame.query()
In [46]: a = np.random.randn() In [47]: df.query('@a < a') Out[47]: a b 0 0.863987 -0.115998 In [48]: df.loc[a < df['a']] # same as the previous expression Out[48]: a b 0 0.863987 -0.115998
With pandas.eval() you cannot use the @ prefix at all, because it isn’t defined in that context. pandas will let you know this if you try to use @ in a top-level call to pandas.eval(). For example,
pandas
In [49]: a, b = 1, 2 In [50]: pd.eval('@a + b') Traceback (most recent call last): File "/home/stijnvh/miniconda3/envs/pandas-dev/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3319, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-50-af17947a194f>", line 1, in <module> pd.eval('@a + b') File "/home/stijnvh/Documents/repositories/pandas/pandas/core/computation/eval.py", line 321, in eval _check_for_locals(expr, level, parser) File "/home/stijnvh/Documents/repositories/pandas/pandas/core/computation/eval.py", line 167, in _check_for_locals raise SyntaxError(msg) File "<string>", line unknown SyntaxError: The '@' prefix is not allowed in top-level eval calls, please refer to your variables by name without the '@' prefix
In this case, you should simply refer to the variables like you would in standard Python.
In [51]: pd.eval('a + b') Out[51]: 3
There are two different parsers and two different engines you can use as the backend.
The default 'pandas' parser allows a more intuitive syntax for expressing query-like operations (comparisons, conjunctions and disjunctions). In particular, the precedence of the & and | operators is made equal to the precedence of the corresponding boolean operations and and or.
'pandas'
&
|
and
or
For example, the above conjunction can be written without parentheses. Alternatively, you can use the 'python' parser to enforce strict Python semantics.
'python'
In [52]: expr = '(df1 > 0) & (df2 > 0) & (df3 > 0) & (df4 > 0)' In [53]: x = pd.eval(expr, parser='python') In [54]: expr_no_parens = 'df1 > 0 & df2 > 0 & df3 > 0 & df4 > 0' In [55]: y = pd.eval(expr_no_parens, parser='pandas') In [56]: np.all(x == y) Out[56]: True
The same expression can be “anded” together with the word and as well:
In [57]: expr = '(df1 > 0) & (df2 > 0) & (df3 > 0) & (df4 > 0)' In [58]: x = pd.eval(expr, parser='python') In [59]: expr_with_ands = 'df1 > 0 and df2 > 0 and df3 > 0 and df4 > 0' In [60]: y = pd.eval(expr_with_ands, parser='pandas') In [61]: np.all(x == y) Out[61]: True
The and and or operators here have the same precedence that they would in vanilla Python.
There’s also the option to make eval() operate identical to plain ol’ Python.
Using the 'python' engine is generally not useful, except for testing other evaluation engines against it. You will achieve no performance benefits using eval() with engine='python' and in fact may incur a performance hit.
engine='python'
You can see this by using pandas.eval() with the 'python' engine. It is a bit slower (not by much) than evaluating the same expression in Python
In [62]: %timeit df1 + df2 + df3 + df4 20.8 ms +- 157 us per loop (mean +- std. dev. of 7 runs, 10 loops each)
In [63]: %timeit pd.eval('df1 + df2 + df3 + df4', engine='python') 22.2 ms +- 74.4 us per loop (mean +- std. dev. of 7 runs, 10 loops each)
eval() is intended to speed up certain kinds of operations. In particular, those operations involving complex expressions with large DataFrame/Series objects should see a significant performance benefit. Here is a plot showing the running time of pandas.eval() as function of the size of the frame involved in the computation. The two lines are two different engines.
Operations with smallish objects (around 15k-20k rows) are faster using plain Python:
This plot was created using a DataFrame with 3 columns each containing floating point values generated using numpy.random.randn().
numpy.random.randn()
Expressions that would result in an object dtype or involve datetime operations (because of NaT) must be evaluated in Python space. The main reason for this behavior is to maintain backwards compatibility with versions of NumPy < 1.7. In those versions of NumPy a call to ndarray.astype(str) will truncate any strings that are more than 60 characters in length. Second, we can’t pass object arrays to numexpr thus string comparisons must be evaluated in Python space.
NaT
ndarray.astype(str)
object
The upshot is that this only applies to object-dtype expressions. So, if you have an expression–for example
In [64]: df = pd.DataFrame({'strings': np.repeat(list('cba'), 3), ....: 'nums': np.repeat(range(3), 3)}) ....: In [65]: df Out[65]: strings nums 0 c 0 1 c 0 2 c 0 3 b 1 4 b 1 5 b 1 6 a 2 7 a 2 8 a 2 In [66]: df.query('strings == "a" and nums == 1') Out[66]: Empty DataFrame Columns: [strings, nums] Index: []
the numeric part of the comparison (nums == 1) will be evaluated by numexpr.
nums == 1
In general, DataFrame.query()/pandas.eval() will evaluate the subexpressions that can be evaluated by numexpr and those that must be evaluated in Python space transparently to the user. This is done by inferring the result type of an expression from its arguments and operators.


An example of using <graphite-metrics>:
<graphite-metrics>
Note that this demo doesn't really work as it requires a valid Graphite server and target.


{% extends 'vespawatch/base.html' %} {% load i18n %} {% block content %} {% csrf_token %} {% trans 'The following individuals as well as their related objects will be deleted. Are you sure?' %} {{ object }} {% endblock %}