file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
paragraph.tsx | import { Editor, EditorState, RichUtils } from "draft-js"
import { debounce } from "lodash"
import React, { Component } from "react"
import ReactDOM from "react-dom"
import styled from "styled-components"
import { TextInputUrl } from "../components/text_input_url"
import { TextNav } from "../components/text_nav"
import { decorators } from "../shared/decorators"
import { confirmLink, linkDataFromSelection, removeLink } from "../shared/links"
import {
handleReturn,
insertPastedState,
styleMapFromNodes,
styleNamesFromMap,
} from "../shared/shared"
import { AllowedStyles, StyleMap, StyleNamesParagraph } from "../typings"
import { convertDraftToHtml, convertHtmlToDraft } from "./utils/convert"
import {
allowedStylesParagraph,
blockRenderMap,
keyBindingFn,
} from "./utils/utils"
interface Props {
allowedStyles?: AllowedStyles
allowEmptyLines?: boolean // Users can insert br tags
html?: string
hasLinks: boolean
onChange: (html: string) => void
placeholder?: string
stripLinebreaks: boolean // Return a single p block
isDark?: boolean
isReadOnly?: boolean
}
interface State {
editorPosition: ClientRect | null
editorState: EditorState
html: string
showNav: boolean
showUrlInput: boolean
urlValue: string
}
/**
* Supports HTML with bold and italic styles in <p> blocks.
* Allowed styles can be limited by passing allowedStyles.
* Optionally supports links, and linebreak stripping.
*/
export class Paragraph extends Component<Props, State> {
private editor
private allowedStyles: StyleMap
private debouncedOnChange
static defaultProps = {
allowEmptyLines: false,
hasLinks: false,
stripLinebreaks: false,
}
constructor(props: Props) {
super(props)
this.allowedStyles = styleMapFromNodes(
props.allowedStyles || allowedStylesParagraph
)
this.state = {
editorPosition: null,
editorState: this.setEditorState(),
html: props.html || "",
showNav: false,
showUrlInput: false,
urlValue: "",
}
this.debouncedOnChange = debounce((html: string) => {
props.onChange(html)
}, 250)
}
setEditorState = () => {
const { hasLinks, html } = this.props
if (html) {
return this.editorStateFromHTML(html)
} else {
return EditorState.createEmpty(decorators(hasLinks))
}
}
editorStateToHTML = (editorState: EditorState) => {
const { allowEmptyLines, stripLinebreaks } = this.props
const currentContent = editorState.getCurrentContent()
return convertDraftToHtml(
currentContent,
this.allowedStyles,
stripLinebreaks,
allowEmptyLines
)
}
editorStateFromHTML = (html: string) => {
const { hasLinks, allowEmptyLines } = this.props
const contentBlocks = convertHtmlToDraft(
html,
hasLinks,
this.allowedStyles,
allowEmptyLines
)
return EditorState.createWithContent(contentBlocks, decorators(hasLinks))
}
onChange = (editorState: EditorState) => {
const html = this.editorStateToHTML(editorState)
this.setState({ editorState, html })
if (html !== this.props.html) {
// Return html if changed
this.debouncedOnChange(html)
}
}
focus = () => {
this.editor.focus()
this.checkSelection()
}
handleReturn = e => {
const { editorState } = this.state
const { stripLinebreaks, allowEmptyLines } = this.props
if (stripLinebreaks) {
// Do nothing if linebreaks are disallowed
return "handled"
} else if (allowEmptyLines) {
return "not-handled"
} else {
// Maybe split-block, but don't create empty paragraphs
return handleReturn(e, editorState)
}
}
handleKeyCommand = (command: string) => {
const { hasLinks } = this.props
switch (command) {
case "link-prompt": {
if (hasLinks) {
// Open link input if links are supported
return this.promptForLink()
}
break
}
case "bold":
case "italic": {
return this.keyCommandInlineStyle(command)
}
}
// let draft defaults or browser handle
return "not-handled"
}
keyCommandInlineStyle = (command: "italic" | "bold") => {
// Handle style changes from key command
const { editorState } = this.state
const styles = styleNamesFromMap(this.allowedStyles)
if (styles.includes(command.toUpperCase())) {
const newState = RichUtils.handleKeyCommand(editorState, command)
// If an updated state is returned, command is handled
if (newState) {
this.onChange(newState)
return "handled"
}
} else {
return "not-handled"
}
}
toggleInlineStyle = (command: StyleNamesParagraph) => {
// Handle style changes from menu click
const { editorState } = this.state
const styles = styleNamesFromMap(this.allowedStyles)
let newEditorState
if (styles.includes(command)) {
newEditorState = RichUtils.toggleInlineStyle(editorState, command)
}
if (newEditorState) {
this.onChange(newEditorState)
}
}
handlePastedText = (text: string, html?: string) => {
const { editorState } = this.state
if (!html) {
// Wrap pasted plain text in html
html = "<p>" + text + "</p>"
}
const stateFromPastedFragment = this.editorStateFromHTML(html)
const stateWithPastedText = insertPastedState(
stateFromPastedFragment,
editorState
)
this.onChange(stateWithPastedText)
return true
}
promptForLink = () => {
// Opens a popup link input populated with selection data if link is selected
const { editorState } = this.state
const linkData = linkDataFromSelection(editorState)
const urlValue = linkData ? linkData.url : ""
const editor = ReactDOM.findDOMNode(this.editor) as Element
const editorPosition: ClientRect = editor.getBoundingClientRect()
this.setState({
editorPosition,
showUrlInput: true,
showNav: false,
urlValue,
})
return "handled"
}
confirmLink = (url: string) => {
const { editorState } = this.state
const newEditorState = confirmLink(url, editorState)
this.setState({
editorPosition: null,
showNav: false,
showUrlInput: false,
urlValue: "",
})
this.onChange(newEditorState)
}
removeLink = () => {
const editorState = removeLink(this.state.editorState)
if (editorState) {
this.setState({
editorPosition: null,
showUrlInput: false,
urlValue: "",
})
this.onChange(editorState)
}
}
checkSelection = () => {
let showNav = false
let editorPosition: ClientRect | null = null
const hasSelection = !window.getSelection().isCollapsed
if (hasSelection) |
this.setState({ showNav, editorPosition })
}
render() {
const { hasLinks, isDark, isReadOnly, placeholder } = this.props
const {
editorPosition,
editorState,
showNav,
showUrlInput,
urlValue,
} = this.state
const promptForLink = hasLinks ? this.promptForLink : undefined
return (
<ParagraphContainer>
{showNav && (
<TextNav
allowedStyles={this.allowedStyles}
editorPosition={editorPosition}
onClickOff={() => this.setState({ showNav: false })}
promptForLink={promptForLink}
toggleStyle={this.toggleInlineStyle}
/>
)}
{showUrlInput && (
<TextInputUrl
backgroundColor={isDark ? "white" : undefined}
editorPosition={editorPosition}
onClickOff={() => this.setState({ showUrlInput: false })}
onConfirmLink={this.confirmLink}
onRemoveLink={this.removeLink}
urlValue={urlValue}
/>
)}
<div
onClick={this.focus}
onMouseUp={this.checkSelection}
onKeyUp={this.checkSelection}
>
<Editor
blockRenderMap={blockRenderMap as any}
editorState={editorState}
keyBindingFn={keyBindingFn}
handleKeyCommand={this.handleKeyCommand as any}
handlePastedText={this.handlePastedText as any}
handleReturn={this.handleReturn}
onChange={this.onChange}
placeholder={placeholder || "Start typing..."}
readOnly={isReadOnly}
ref={ref => {
this.editor = ref
}}
spellCheck
/>
</div>
</ParagraphContainer>
)
}
}
const ParagraphContainer = styled.div`
position: relative;
`
| {
showNav = true
const editor = ReactDOM.findDOMNode(this.editor) as Element
editorPosition = editor.getBoundingClientRect()
} | conditional_block |
paragraph.tsx | import { Editor, EditorState, RichUtils } from "draft-js"
import { debounce } from "lodash"
import React, { Component } from "react"
import ReactDOM from "react-dom"
import styled from "styled-components"
import { TextInputUrl } from "../components/text_input_url"
import { TextNav } from "../components/text_nav"
import { decorators } from "../shared/decorators"
import { confirmLink, linkDataFromSelection, removeLink } from "../shared/links"
import {
handleReturn,
insertPastedState,
styleMapFromNodes,
styleNamesFromMap,
} from "../shared/shared"
import { AllowedStyles, StyleMap, StyleNamesParagraph } from "../typings"
import { convertDraftToHtml, convertHtmlToDraft } from "./utils/convert"
import {
allowedStylesParagraph,
blockRenderMap,
keyBindingFn,
} from "./utils/utils"
interface Props {
allowedStyles?: AllowedStyles
allowEmptyLines?: boolean // Users can insert br tags
html?: string
hasLinks: boolean
onChange: (html: string) => void
placeholder?: string
stripLinebreaks: boolean // Return a single p block
isDark?: boolean
isReadOnly?: boolean
}
interface State {
editorPosition: ClientRect | null
editorState: EditorState
html: string
showNav: boolean
showUrlInput: boolean
urlValue: string
}
/**
* Supports HTML with bold and italic styles in <p> blocks.
* Allowed styles can be limited by passing allowedStyles.
* Optionally supports links, and linebreak stripping.
*/
export class Paragraph extends Component<Props, State> {
private editor
private allowedStyles: StyleMap
private debouncedOnChange
static defaultProps = {
allowEmptyLines: false,
hasLinks: false,
stripLinebreaks: false,
}
constructor(props: Props) |
setEditorState = () => {
const { hasLinks, html } = this.props
if (html) {
return this.editorStateFromHTML(html)
} else {
return EditorState.createEmpty(decorators(hasLinks))
}
}
editorStateToHTML = (editorState: EditorState) => {
const { allowEmptyLines, stripLinebreaks } = this.props
const currentContent = editorState.getCurrentContent()
return convertDraftToHtml(
currentContent,
this.allowedStyles,
stripLinebreaks,
allowEmptyLines
)
}
editorStateFromHTML = (html: string) => {
const { hasLinks, allowEmptyLines } = this.props
const contentBlocks = convertHtmlToDraft(
html,
hasLinks,
this.allowedStyles,
allowEmptyLines
)
return EditorState.createWithContent(contentBlocks, decorators(hasLinks))
}
onChange = (editorState: EditorState) => {
const html = this.editorStateToHTML(editorState)
this.setState({ editorState, html })
if (html !== this.props.html) {
// Return html if changed
this.debouncedOnChange(html)
}
}
focus = () => {
this.editor.focus()
this.checkSelection()
}
handleReturn = e => {
const { editorState } = this.state
const { stripLinebreaks, allowEmptyLines } = this.props
if (stripLinebreaks) {
// Do nothing if linebreaks are disallowed
return "handled"
} else if (allowEmptyLines) {
return "not-handled"
} else {
// Maybe split-block, but don't create empty paragraphs
return handleReturn(e, editorState)
}
}
handleKeyCommand = (command: string) => {
const { hasLinks } = this.props
switch (command) {
case "link-prompt": {
if (hasLinks) {
// Open link input if links are supported
return this.promptForLink()
}
break
}
case "bold":
case "italic": {
return this.keyCommandInlineStyle(command)
}
}
// let draft defaults or browser handle
return "not-handled"
}
keyCommandInlineStyle = (command: "italic" | "bold") => {
// Handle style changes from key command
const { editorState } = this.state
const styles = styleNamesFromMap(this.allowedStyles)
if (styles.includes(command.toUpperCase())) {
const newState = RichUtils.handleKeyCommand(editorState, command)
// If an updated state is returned, command is handled
if (newState) {
this.onChange(newState)
return "handled"
}
} else {
return "not-handled"
}
}
toggleInlineStyle = (command: StyleNamesParagraph) => {
// Handle style changes from menu click
const { editorState } = this.state
const styles = styleNamesFromMap(this.allowedStyles)
let newEditorState
if (styles.includes(command)) {
newEditorState = RichUtils.toggleInlineStyle(editorState, command)
}
if (newEditorState) {
this.onChange(newEditorState)
}
}
handlePastedText = (text: string, html?: string) => {
const { editorState } = this.state
if (!html) {
// Wrap pasted plain text in html
html = "<p>" + text + "</p>"
}
const stateFromPastedFragment = this.editorStateFromHTML(html)
const stateWithPastedText = insertPastedState(
stateFromPastedFragment,
editorState
)
this.onChange(stateWithPastedText)
return true
}
promptForLink = () => {
// Opens a popup link input populated with selection data if link is selected
const { editorState } = this.state
const linkData = linkDataFromSelection(editorState)
const urlValue = linkData ? linkData.url : ""
const editor = ReactDOM.findDOMNode(this.editor) as Element
const editorPosition: ClientRect = editor.getBoundingClientRect()
this.setState({
editorPosition,
showUrlInput: true,
showNav: false,
urlValue,
})
return "handled"
}
confirmLink = (url: string) => {
const { editorState } = this.state
const newEditorState = confirmLink(url, editorState)
this.setState({
editorPosition: null,
showNav: false,
showUrlInput: false,
urlValue: "",
})
this.onChange(newEditorState)
}
removeLink = () => {
const editorState = removeLink(this.state.editorState)
if (editorState) {
this.setState({
editorPosition: null,
showUrlInput: false,
urlValue: "",
})
this.onChange(editorState)
}
}
checkSelection = () => {
let showNav = false
let editorPosition: ClientRect | null = null
const hasSelection = !window.getSelection().isCollapsed
if (hasSelection) {
showNav = true
const editor = ReactDOM.findDOMNode(this.editor) as Element
editorPosition = editor.getBoundingClientRect()
}
this.setState({ showNav, editorPosition })
}
render() {
const { hasLinks, isDark, isReadOnly, placeholder } = this.props
const {
editorPosition,
editorState,
showNav,
showUrlInput,
urlValue,
} = this.state
const promptForLink = hasLinks ? this.promptForLink : undefined
return (
<ParagraphContainer>
{showNav && (
<TextNav
allowedStyles={this.allowedStyles}
editorPosition={editorPosition}
onClickOff={() => this.setState({ showNav: false })}
promptForLink={promptForLink}
toggleStyle={this.toggleInlineStyle}
/>
)}
{showUrlInput && (
<TextInputUrl
backgroundColor={isDark ? "white" : undefined}
editorPosition={editorPosition}
onClickOff={() => this.setState({ showUrlInput: false })}
onConfirmLink={this.confirmLink}
onRemoveLink={this.removeLink}
urlValue={urlValue}
/>
)}
<div
onClick={this.focus}
onMouseUp={this.checkSelection}
onKeyUp={this.checkSelection}
>
<Editor
blockRenderMap={blockRenderMap as any}
editorState={editorState}
keyBindingFn={keyBindingFn}
handleKeyCommand={this.handleKeyCommand as any}
handlePastedText={this.handlePastedText as any}
handleReturn={this.handleReturn}
onChange={this.onChange}
placeholder={placeholder || "Start typing..."}
readOnly={isReadOnly}
ref={ref => {
this.editor = ref
}}
spellCheck
/>
</div>
</ParagraphContainer>
)
}
}
const ParagraphContainer = styled.div`
position: relative;
`
| {
super(props)
this.allowedStyles = styleMapFromNodes(
props.allowedStyles || allowedStylesParagraph
)
this.state = {
editorPosition: null,
editorState: this.setEditorState(),
html: props.html || "",
showNav: false,
showUrlInput: false,
urlValue: "",
}
this.debouncedOnChange = debounce((html: string) => {
props.onChange(html)
}, 250)
} | identifier_body |
paragraph.tsx | import { Editor, EditorState, RichUtils } from "draft-js"
import { debounce } from "lodash"
import React, { Component } from "react"
import ReactDOM from "react-dom"
import styled from "styled-components"
import { TextInputUrl } from "../components/text_input_url"
import { TextNav } from "../components/text_nav"
import { decorators } from "../shared/decorators"
import { confirmLink, linkDataFromSelection, removeLink } from "../shared/links"
import {
handleReturn,
insertPastedState,
styleMapFromNodes,
styleNamesFromMap,
} from "../shared/shared"
import { AllowedStyles, StyleMap, StyleNamesParagraph } from "../typings"
import { convertDraftToHtml, convertHtmlToDraft } from "./utils/convert"
import {
allowedStylesParagraph,
blockRenderMap,
keyBindingFn,
} from "./utils/utils"
interface Props {
allowedStyles?: AllowedStyles
allowEmptyLines?: boolean // Users can insert br tags
html?: string
hasLinks: boolean
onChange: (html: string) => void
placeholder?: string
stripLinebreaks: boolean // Return a single p block
isDark?: boolean
isReadOnly?: boolean
}
interface State {
editorPosition: ClientRect | null
editorState: EditorState
html: string
showNav: boolean
showUrlInput: boolean
urlValue: string
}
/**
* Supports HTML with bold and italic styles in <p> blocks.
* Allowed styles can be limited by passing allowedStyles.
* Optionally supports links, and linebreak stripping.
*/
export class Paragraph extends Component<Props, State> {
private editor
private allowedStyles: StyleMap
private debouncedOnChange
static defaultProps = {
allowEmptyLines: false,
hasLinks: false,
stripLinebreaks: false,
}
constructor(props: Props) {
super(props)
this.allowedStyles = styleMapFromNodes(
props.allowedStyles || allowedStylesParagraph
)
this.state = {
editorPosition: null,
editorState: this.setEditorState(),
html: props.html || "",
showNav: false,
showUrlInput: false,
urlValue: "",
}
this.debouncedOnChange = debounce((html: string) => {
props.onChange(html)
}, 250)
}
setEditorState = () => {
const { hasLinks, html } = this.props
if (html) {
return this.editorStateFromHTML(html)
} else {
return EditorState.createEmpty(decorators(hasLinks))
}
}
editorStateToHTML = (editorState: EditorState) => {
const { allowEmptyLines, stripLinebreaks } = this.props
const currentContent = editorState.getCurrentContent()
return convertDraftToHtml(
currentContent,
this.allowedStyles,
stripLinebreaks,
allowEmptyLines
)
}
editorStateFromHTML = (html: string) => {
const { hasLinks, allowEmptyLines } = this.props
const contentBlocks = convertHtmlToDraft(
html,
hasLinks,
this.allowedStyles,
allowEmptyLines
)
return EditorState.createWithContent(contentBlocks, decorators(hasLinks))
}
onChange = (editorState: EditorState) => {
const html = this.editorStateToHTML(editorState)
this.setState({ editorState, html })
if (html !== this.props.html) {
// Return html if changed
this.debouncedOnChange(html)
}
}
focus = () => {
this.editor.focus()
this.checkSelection()
}
handleReturn = e => {
const { editorState } = this.state
const { stripLinebreaks, allowEmptyLines } = this.props
if (stripLinebreaks) {
// Do nothing if linebreaks are disallowed
return "handled"
} else if (allowEmptyLines) {
return "not-handled"
} else {
// Maybe split-block, but don't create empty paragraphs
return handleReturn(e, editorState)
}
}
handleKeyCommand = (command: string) => {
const { hasLinks } = this.props
switch (command) {
case "link-prompt": {
if (hasLinks) {
// Open link input if links are supported
return this.promptForLink()
}
break
}
case "bold":
case "italic": {
return this.keyCommandInlineStyle(command)
}
}
// let draft defaults or browser handle
return "not-handled"
}
keyCommandInlineStyle = (command: "italic" | "bold") => {
// Handle style changes from key command
const { editorState } = this.state
const styles = styleNamesFromMap(this.allowedStyles)
if (styles.includes(command.toUpperCase())) {
const newState = RichUtils.handleKeyCommand(editorState, command)
// If an updated state is returned, command is handled
if (newState) {
this.onChange(newState)
return "handled"
}
} else {
return "not-handled"
}
}
toggleInlineStyle = (command: StyleNamesParagraph) => {
// Handle style changes from menu click
const { editorState } = this.state
const styles = styleNamesFromMap(this.allowedStyles)
let newEditorState
if (styles.includes(command)) {
newEditorState = RichUtils.toggleInlineStyle(editorState, command)
}
if (newEditorState) {
this.onChange(newEditorState)
}
}
handlePastedText = (text: string, html?: string) => {
const { editorState } = this.state
if (!html) {
// Wrap pasted plain text in html
html = "<p>" + text + "</p>"
}
const stateFromPastedFragment = this.editorStateFromHTML(html)
const stateWithPastedText = insertPastedState(
stateFromPastedFragment,
editorState
)
this.onChange(stateWithPastedText)
return true
}
promptForLink = () => {
// Opens a popup link input populated with selection data if link is selected
const { editorState } = this.state
const linkData = linkDataFromSelection(editorState)
const urlValue = linkData ? linkData.url : ""
const editor = ReactDOM.findDOMNode(this.editor) as Element
const editorPosition: ClientRect = editor.getBoundingClientRect()
this.setState({
editorPosition,
showUrlInput: true,
showNav: false,
urlValue,
})
return "handled"
}
confirmLink = (url: string) => {
const { editorState } = this.state
const newEditorState = confirmLink(url, editorState)
this.setState({
editorPosition: null,
showNav: false,
showUrlInput: false,
urlValue: "",
})
this.onChange(newEditorState)
}
removeLink = () => {
const editorState = removeLink(this.state.editorState)
if (editorState) {
this.setState({
editorPosition: null,
showUrlInput: false,
urlValue: "",
})
this.onChange(editorState)
}
}
checkSelection = () => {
let showNav = false
let editorPosition: ClientRect | null = null
const hasSelection = !window.getSelection().isCollapsed
if (hasSelection) {
showNav = true
const editor = ReactDOM.findDOMNode(this.editor) as Element
editorPosition = editor.getBoundingClientRect()
}
this.setState({ showNav, editorPosition })
}
render() {
const { hasLinks, isDark, isReadOnly, placeholder } = this.props
const {
editorPosition,
editorState,
showNav,
showUrlInput,
urlValue,
} = this.state
const promptForLink = hasLinks ? this.promptForLink : undefined
return (
<ParagraphContainer>
{showNav && (
<TextNav
allowedStyles={this.allowedStyles}
editorPosition={editorPosition}
onClickOff={() => this.setState({ showNav: false })}
promptForLink={promptForLink}
toggleStyle={this.toggleInlineStyle}
/>
)}
{showUrlInput && (
<TextInputUrl
backgroundColor={isDark ? "white" : undefined}
editorPosition={editorPosition}
onClickOff={() => this.setState({ showUrlInput: false })}
onConfirmLink={this.confirmLink}
onRemoveLink={this.removeLink}
urlValue={urlValue}
/>
)}
<div
onClick={this.focus}
onMouseUp={this.checkSelection}
onKeyUp={this.checkSelection}
>
<Editor
blockRenderMap={blockRenderMap as any}
editorState={editorState}
keyBindingFn={keyBindingFn}
handleKeyCommand={this.handleKeyCommand as any}
handlePastedText={this.handlePastedText as any}
handleReturn={this.handleReturn} | this.editor = ref
}}
spellCheck
/>
</div>
</ParagraphContainer>
)
}
}
const ParagraphContainer = styled.div`
position: relative;
` | onChange={this.onChange}
placeholder={placeholder || "Start typing..."}
readOnly={isReadOnly}
ref={ref => { | random_line_split |
iter.rs | use std::mem;
struct | {
curr: uint,
next: uint,
}
// Implement 'Iterator' for 'Fibonacci'
impl Iterator<uint> for Fibonacci {
// The 'Iterator' trait only requires the 'next' method to be defined. The
// return type is 'Option<T>', 'None' is returned when the 'Iterator' is
// over, otherwise the next value is returned wrapped in 'Some'
fn next(&mut self) -> Option<uint> {
let new_next = self.curr + self.next;
let new_curr = mem::replace(&mut self.next, new_next);
// 'Some' is always returned, this is an infinite value generator
Some(mem::replace(&mut self.curr, new_curr))
}
}
// Returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn main() {
// Iterator that generates: 0, 1 and 2
let mut sequence = range(0u, 3);
println!("Four consecutive `next` calls on range(0, 3)")
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
// The for construct will iterate an 'Iterator' until it returns 'None'.
// Every 'Some' value is unwrapped and bound to a variable.
println!("Iterate over range(0, 3) using for");
for i in range(0u, 3) {
println!("> {}", i);
}
// The 'take(n)' method will reduce an iterator to its first 'n' terms,
// which is pretty useful for infinite value generators
println!("The first four terms of the Fibonacci sequence are: ");
for i in fibonacci().take(4) {
println!("> {}", i);
}
// The 'skip(n)' method will shorten an iterator by dropping its first 'n'
// terms
println!("The next four terms of the Fibonacci sequence are: ");
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
let array = [1u, 3, 3, 7];
// The 'iter' method produces an 'Iterator' over an array/slice
println!("Iterate the following array {}", array.as_slice());
for i in array.iter() {
println!("> {}", i);
}
}
| Fibonacci | identifier_name |
iter.rs | use std::mem;
struct Fibonacci {
curr: uint,
next: uint,
}
// Implement 'Iterator' for 'Fibonacci'
impl Iterator<uint> for Fibonacci {
// The 'Iterator' trait only requires the 'next' method to be defined. The
// return type is 'Option<T>', 'None' is returned when the 'Iterator' is
// over, otherwise the next value is returned wrapped in 'Some'
fn next(&mut self) -> Option<uint> |
}
// Returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn main() {
// Iterator that generates: 0, 1 and 2
let mut sequence = range(0u, 3);
println!("Four consecutive `next` calls on range(0, 3)")
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
// The for construct will iterate an 'Iterator' until it returns 'None'.
// Every 'Some' value is unwrapped and bound to a variable.
println!("Iterate over range(0, 3) using for");
for i in range(0u, 3) {
println!("> {}", i);
}
// The 'take(n)' method will reduce an iterator to its first 'n' terms,
// which is pretty useful for infinite value generators
println!("The first four terms of the Fibonacci sequence are: ");
for i in fibonacci().take(4) {
println!("> {}", i);
}
// The 'skip(n)' method will shorten an iterator by dropping its first 'n'
// terms
println!("The next four terms of the Fibonacci sequence are: ");
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
let array = [1u, 3, 3, 7];
// The 'iter' method produces an 'Iterator' over an array/slice
println!("Iterate the following array {}", array.as_slice());
for i in array.iter() {
println!("> {}", i);
}
}
| {
let new_next = self.curr + self.next;
let new_curr = mem::replace(&mut self.next, new_next);
// 'Some' is always returned, this is an infinite value generator
Some(mem::replace(&mut self.curr, new_curr))
} | identifier_body |
iter.rs | use std::mem;
struct Fibonacci {
curr: uint,
next: uint,
}
// Implement 'Iterator' for 'Fibonacci'
impl Iterator<uint> for Fibonacci {
// The 'Iterator' trait only requires the 'next' method to be defined. The
// return type is 'Option<T>', 'None' is returned when the 'Iterator' is
// over, otherwise the next value is returned wrapped in 'Some'
fn next(&mut self) -> Option<uint> {
let new_next = self.curr + self.next;
let new_curr = mem::replace(&mut self.next, new_next);
// 'Some' is always returned, this is an infinite value generator
Some(mem::replace(&mut self.curr, new_curr))
}
}
// Returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn main() { | let mut sequence = range(0u, 3);
println!("Four consecutive `next` calls on range(0, 3)")
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
// The for construct will iterate an 'Iterator' until it returns 'None'.
// Every 'Some' value is unwrapped and bound to a variable.
println!("Iterate over range(0, 3) using for");
for i in range(0u, 3) {
println!("> {}", i);
}
// The 'take(n)' method will reduce an iterator to its first 'n' terms,
// which is pretty useful for infinite value generators
println!("The first four terms of the Fibonacci sequence are: ");
for i in fibonacci().take(4) {
println!("> {}", i);
}
// The 'skip(n)' method will shorten an iterator by dropping its first 'n'
// terms
println!("The next four terms of the Fibonacci sequence are: ");
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
let array = [1u, 3, 3, 7];
// The 'iter' method produces an 'Iterator' over an array/slice
println!("Iterate the following array {}", array.as_slice());
for i in array.iter() {
println!("> {}", i);
}
} | // Iterator that generates: 0, 1 and 2 | random_line_split |
test_bucketing.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import numpy as np
import mxnet as mx
import random
from random import randint
def test_bucket_module():
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
batch_size = 128
num_epochs = 5
num_hidden = 25
num_embed = 25
num_layers = 2
len_vocab = 50
buckets = [10, 20, 30, 40]
invalid_label = -1
num_sentence = 1000
train_sent = []
val_sent = []
for _ in range(num_sentence):
len_sentence = randint(1, max(buckets)-1) # leave out the two last buckets empty
train_sentence = []
val_sentence = []
for _ in range(len_sentence):
train_sentence.append(randint(1, len_vocab))
val_sentence.append(randint(1, len_vocab))
train_sent.append(train_sentence)
val_sent.append(val_sentence)
data_train = mx.rnn.BucketSentenceIter(train_sent, batch_size, buckets=buckets,
invalid_label=invalid_label)
data_val = mx.rnn.BucketSentenceIter(val_sent, batch_size, buckets=buckets,
invalid_label=invalid_label)
stack = mx.rnn.SequentialRNNCell()
for i in range(num_layers):
stack.add(mx.rnn.LSTMCell(num_hidden=num_hidden, prefix='lstm_l%d_' % i))
def | (seq_len):
data = mx.sym.Variable('data')
label = mx.sym.Variable('softmax_label')
embed = mx.sym.Embedding(data=data, input_dim=len_vocab,
output_dim=num_embed, name='embed')
stack.reset()
outputs, states = stack.unroll(seq_len, inputs=embed, merge_outputs=True)
pred = mx.sym.Reshape(outputs, shape=(-1, num_hidden))
pred = mx.sym.FullyConnected(data=pred, num_hidden=len_vocab, name='pred')
label = mx.sym.Reshape(label, shape=(-1,))
loss = mx.sym.SoftmaxOutput(data=pred, label=label, name='softmax')
return loss, ('data',), ('softmax_label',)
contexts = mx.cpu(0)
model = mx.mod.BucketingModule(
sym_gen=sym_gen,
default_bucket_key=data_train.default_bucket_key,
context=contexts)
logging.info('Begin fit...')
model.fit(
train_data=data_train,
eval_data=data_val,
eval_metric=mx.metric.Perplexity(invalid_label), # Use Perplexity for multiclass classification.
kvstore='device',
optimizer='sgd',
optimizer_params={'learning_rate': 0.01,
'momentum': 0,
'wd': 0.00001},
initializer=mx.init.Xavier(factor_type="in", magnitude=2.34),
num_epoch=num_epochs,
batch_end_callback=mx.callback.Speedometer(batch_size, 50))
logging.info('Finished fit...')
# This test forecasts random sequence of words to check bucketing.
# We cannot guarantee the accuracy of such an impossible task, and comments out the following line.
# assert model.score(data_val, mx.metric.MSE())[0][1] < 350, "High mean square error."
if __name__ == "__main__":
test_bucket_module()
| sym_gen | identifier_name |
test_bucketing.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import numpy as np
import mxnet as mx
import random
from random import randint
def test_bucket_module():
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
batch_size = 128
num_epochs = 5
num_hidden = 25
num_embed = 25
num_layers = 2
len_vocab = 50
buckets = [10, 20, 30, 40]
invalid_label = -1
num_sentence = 1000
train_sent = []
val_sent = []
for _ in range(num_sentence):
len_sentence = randint(1, max(buckets)-1) # leave out the two last buckets empty
train_sentence = []
val_sentence = []
for _ in range(len_sentence):
train_sentence.append(randint(1, len_vocab))
val_sentence.append(randint(1, len_vocab))
train_sent.append(train_sentence)
val_sent.append(val_sentence)
data_train = mx.rnn.BucketSentenceIter(train_sent, batch_size, buckets=buckets,
invalid_label=invalid_label)
data_val = mx.rnn.BucketSentenceIter(val_sent, batch_size, buckets=buckets,
invalid_label=invalid_label)
stack = mx.rnn.SequentialRNNCell()
for i in range(num_layers):
stack.add(mx.rnn.LSTMCell(num_hidden=num_hidden, prefix='lstm_l%d_' % i))
def sym_gen(seq_len):
data = mx.sym.Variable('data')
label = mx.sym.Variable('softmax_label')
embed = mx.sym.Embedding(data=data, input_dim=len_vocab,
output_dim=num_embed, name='embed')
stack.reset()
outputs, states = stack.unroll(seq_len, inputs=embed, merge_outputs=True)
pred = mx.sym.Reshape(outputs, shape=(-1, num_hidden))
pred = mx.sym.FullyConnected(data=pred, num_hidden=len_vocab, name='pred')
label = mx.sym.Reshape(label, shape=(-1,))
loss = mx.sym.SoftmaxOutput(data=pred, label=label, name='softmax')
return loss, ('data',), ('softmax_label',)
contexts = mx.cpu(0)
| context=contexts)
logging.info('Begin fit...')
model.fit(
train_data=data_train,
eval_data=data_val,
eval_metric=mx.metric.Perplexity(invalid_label), # Use Perplexity for multiclass classification.
kvstore='device',
optimizer='sgd',
optimizer_params={'learning_rate': 0.01,
'momentum': 0,
'wd': 0.00001},
initializer=mx.init.Xavier(factor_type="in", magnitude=2.34),
num_epoch=num_epochs,
batch_end_callback=mx.callback.Speedometer(batch_size, 50))
logging.info('Finished fit...')
# This test forecasts random sequence of words to check bucketing.
# We cannot guarantee the accuracy of such an impossible task, and comments out the following line.
# assert model.score(data_val, mx.metric.MSE())[0][1] < 350, "High mean square error."
if __name__ == "__main__":
test_bucket_module() | model = mx.mod.BucketingModule(
sym_gen=sym_gen,
default_bucket_key=data_train.default_bucket_key, | random_line_split |
test_bucketing.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import numpy as np
import mxnet as mx
import random
from random import randint
def test_bucket_module():
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
batch_size = 128
num_epochs = 5
num_hidden = 25
num_embed = 25
num_layers = 2
len_vocab = 50
buckets = [10, 20, 30, 40]
invalid_label = -1
num_sentence = 1000
train_sent = []
val_sent = []
for _ in range(num_sentence):
len_sentence = randint(1, max(buckets)-1) # leave out the two last buckets empty
train_sentence = []
val_sentence = []
for _ in range(len_sentence):
train_sentence.append(randint(1, len_vocab))
val_sentence.append(randint(1, len_vocab))
train_sent.append(train_sentence)
val_sent.append(val_sentence)
data_train = mx.rnn.BucketSentenceIter(train_sent, batch_size, buckets=buckets,
invalid_label=invalid_label)
data_val = mx.rnn.BucketSentenceIter(val_sent, batch_size, buckets=buckets,
invalid_label=invalid_label)
stack = mx.rnn.SequentialRNNCell()
for i in range(num_layers):
stack.add(mx.rnn.LSTMCell(num_hidden=num_hidden, prefix='lstm_l%d_' % i))
def sym_gen(seq_len):
|
contexts = mx.cpu(0)
model = mx.mod.BucketingModule(
sym_gen=sym_gen,
default_bucket_key=data_train.default_bucket_key,
context=contexts)
logging.info('Begin fit...')
model.fit(
train_data=data_train,
eval_data=data_val,
eval_metric=mx.metric.Perplexity(invalid_label), # Use Perplexity for multiclass classification.
kvstore='device',
optimizer='sgd',
optimizer_params={'learning_rate': 0.01,
'momentum': 0,
'wd': 0.00001},
initializer=mx.init.Xavier(factor_type="in", magnitude=2.34),
num_epoch=num_epochs,
batch_end_callback=mx.callback.Speedometer(batch_size, 50))
logging.info('Finished fit...')
# This test forecasts random sequence of words to check bucketing.
# We cannot guarantee the accuracy of such an impossible task, and comments out the following line.
# assert model.score(data_val, mx.metric.MSE())[0][1] < 350, "High mean square error."
if __name__ == "__main__":
test_bucket_module()
| data = mx.sym.Variable('data')
label = mx.sym.Variable('softmax_label')
embed = mx.sym.Embedding(data=data, input_dim=len_vocab,
output_dim=num_embed, name='embed')
stack.reset()
outputs, states = stack.unroll(seq_len, inputs=embed, merge_outputs=True)
pred = mx.sym.Reshape(outputs, shape=(-1, num_hidden))
pred = mx.sym.FullyConnected(data=pred, num_hidden=len_vocab, name='pred')
label = mx.sym.Reshape(label, shape=(-1,))
loss = mx.sym.SoftmaxOutput(data=pred, label=label, name='softmax')
return loss, ('data',), ('softmax_label',) | identifier_body |
test_bucketing.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import numpy as np
import mxnet as mx
import random
from random import randint
def test_bucket_module():
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
batch_size = 128
num_epochs = 5
num_hidden = 25
num_embed = 25
num_layers = 2
len_vocab = 50
buckets = [10, 20, 30, 40]
invalid_label = -1
num_sentence = 1000
train_sent = []
val_sent = []
for _ in range(num_sentence):
len_sentence = randint(1, max(buckets)-1) # leave out the two last buckets empty
train_sentence = []
val_sentence = []
for _ in range(len_sentence):
|
train_sent.append(train_sentence)
val_sent.append(val_sentence)
data_train = mx.rnn.BucketSentenceIter(train_sent, batch_size, buckets=buckets,
invalid_label=invalid_label)
data_val = mx.rnn.BucketSentenceIter(val_sent, batch_size, buckets=buckets,
invalid_label=invalid_label)
stack = mx.rnn.SequentialRNNCell()
for i in range(num_layers):
stack.add(mx.rnn.LSTMCell(num_hidden=num_hidden, prefix='lstm_l%d_' % i))
def sym_gen(seq_len):
data = mx.sym.Variable('data')
label = mx.sym.Variable('softmax_label')
embed = mx.sym.Embedding(data=data, input_dim=len_vocab,
output_dim=num_embed, name='embed')
stack.reset()
outputs, states = stack.unroll(seq_len, inputs=embed, merge_outputs=True)
pred = mx.sym.Reshape(outputs, shape=(-1, num_hidden))
pred = mx.sym.FullyConnected(data=pred, num_hidden=len_vocab, name='pred')
label = mx.sym.Reshape(label, shape=(-1,))
loss = mx.sym.SoftmaxOutput(data=pred, label=label, name='softmax')
return loss, ('data',), ('softmax_label',)
contexts = mx.cpu(0)
model = mx.mod.BucketingModule(
sym_gen=sym_gen,
default_bucket_key=data_train.default_bucket_key,
context=contexts)
logging.info('Begin fit...')
model.fit(
train_data=data_train,
eval_data=data_val,
eval_metric=mx.metric.Perplexity(invalid_label), # Use Perplexity for multiclass classification.
kvstore='device',
optimizer='sgd',
optimizer_params={'learning_rate': 0.01,
'momentum': 0,
'wd': 0.00001},
initializer=mx.init.Xavier(factor_type="in", magnitude=2.34),
num_epoch=num_epochs,
batch_end_callback=mx.callback.Speedometer(batch_size, 50))
logging.info('Finished fit...')
# This test forecasts random sequence of words to check bucketing.
# We cannot guarantee the accuracy of such an impossible task, and comments out the following line.
# assert model.score(data_val, mx.metric.MSE())[0][1] < 350, "High mean square error."
if __name__ == "__main__":
test_bucket_module()
| train_sentence.append(randint(1, len_vocab))
val_sentence.append(randint(1, len_vocab)) | conditional_block |
file.ts | import {bindable, autoinject} from 'aurelia-framework';
import {ExampleContext} from './example-context';
let extensionLanguageMap = {
js: 'javascript',
html: 'markup'
};
function getLanguage(filename) {
let extension = (/\.(\w+)$/).exec(filename)[1].toLowerCase();
return extensionLanguageMap[extension];
}
@autoinject
export class File {
@bindable src;
@bindable view;
@bindable model;
example:any;
base;
githubBase;
info = null;
constructor(context:ExampleContext) {
this.example = context.example;
this.base = context.base;
this.githubBase = context.githubBase;
}
bind() |
}
| {
let src = this.src, example = this.example;
this.info = {
name: src,
moduleId: this.base + '/' + src.substr(0, src.indexOf('.')),
language: getLanguage(src),
url: 'dist/' + this.base + '/' + src,
repoUrl: this.githubBase + '/dist/' + this.base + '/' + src
};
if (this.view === 'true')
example.view = this.info;
if (this.model === 'true')
example.model = this.info;
example.result = example.view && example.model;
} | identifier_body |
file.ts | import {bindable, autoinject} from 'aurelia-framework';
import {ExampleContext} from './example-context';
let extensionLanguageMap = {
js: 'javascript',
html: 'markup'
};
function getLanguage(filename) {
let extension = (/\.(\w+)$/).exec(filename)[1].toLowerCase();
return extensionLanguageMap[extension];
}
@autoinject
export class File {
@bindable src;
@bindable view;
@bindable model;
example:any;
base;
githubBase;
info = null;
constructor(context:ExampleContext) {
this.example = context.example;
this.base = context.base;
this.githubBase = context.githubBase;
}
bind() {
let src = this.src, example = this.example;
this.info = {
name: src,
moduleId: this.base + '/' + src.substr(0, src.indexOf('.')),
language: getLanguage(src),
url: 'dist/' + this.base + '/' + src,
repoUrl: this.githubBase + '/dist/' + this.base + '/' + src
};
if (this.view === 'true')
example.view = this.info;
if (this.model === 'true') | example.model = this.info;
example.result = example.view && example.model;
}
} | random_line_split | |
file.ts | import {bindable, autoinject} from 'aurelia-framework';
import {ExampleContext} from './example-context';
let extensionLanguageMap = {
js: 'javascript',
html: 'markup'
};
function getLanguage(filename) {
let extension = (/\.(\w+)$/).exec(filename)[1].toLowerCase();
return extensionLanguageMap[extension];
}
@autoinject
export class File {
@bindable src;
@bindable view;
@bindable model;
example:any;
base;
githubBase;
info = null;
constructor(context:ExampleContext) {
this.example = context.example;
this.base = context.base;
this.githubBase = context.githubBase;
}
| () {
let src = this.src, example = this.example;
this.info = {
name: src,
moduleId: this.base + '/' + src.substr(0, src.indexOf('.')),
language: getLanguage(src),
url: 'dist/' + this.base + '/' + src,
repoUrl: this.githubBase + '/dist/' + this.base + '/' + src
};
if (this.view === 'true')
example.view = this.info;
if (this.model === 'true')
example.model = this.info;
example.result = example.view && example.model;
}
}
| bind | identifier_name |
get_all_networks.py | #!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all networks. |
def main(client):
# Initialize appropriate service.
network_service = client.GetService('NetworkService', version='v201805')
networks = network_service.getAllNetworks()
# Print out some information for each network.
for network in networks:
print('Network with network code "%s" and display name "%s" was found.'
% (network['networkCode'], network['displayName']))
print '\nNumber of results found: %s' % len(networks)
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client) | """
# Import appropriate modules from the client library.
from googleads import ad_manager | random_line_split |
get_all_networks.py | #!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all networks.
"""
# Import appropriate modules from the client library.
from googleads import ad_manager
def main(client):
# Initialize appropriate service.
network_service = client.GetService('NetworkService', version='v201805')
networks = network_service.getAllNetworks()
# Print out some information for each network.
for network in networks:
print('Network with network code "%s" and display name "%s" was found.'
% (network['networkCode'], network['displayName']))
print '\nNumber of results found: %s' % len(networks)
if __name__ == '__main__':
# Initialize client object.
| ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client) | conditional_block | |
get_all_networks.py | #!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all networks.
"""
# Import appropriate modules from the client library.
from googleads import ad_manager
def | (client):
# Initialize appropriate service.
network_service = client.GetService('NetworkService', version='v201805')
networks = network_service.getAllNetworks()
# Print out some information for each network.
for network in networks:
print('Network with network code "%s" and display name "%s" was found.'
% (network['networkCode'], network['displayName']))
print '\nNumber of results found: %s' % len(networks)
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client)
| main | identifier_name |
get_all_networks.py | #!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all networks.
"""
# Import appropriate modules from the client library.
from googleads import ad_manager
def main(client):
# Initialize appropriate service.
|
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client)
| network_service = client.GetService('NetworkService', version='v201805')
networks = network_service.getAllNetworks()
# Print out some information for each network.
for network in networks:
print('Network with network code "%s" and display name "%s" was found.'
% (network['networkCode'], network['displayName']))
print '\nNumber of results found: %s' % len(networks) | identifier_body |
test_python.py | # -*- coding: utf-8 -*-
import unittest
from kiwi.python import AttributeForwarder, slicerange, enum, strip_accents
class SliceTest(unittest.TestCase):
def genlist(self, limit, start, stop=None, step=None): | return list(slicerange(slice(start, stop, step), limit))
def testStop(self):
self.assertEqual(self.genlist(10, 10), list(range(10)))
self.assertEqual(self.genlist(10, -5), list(range(5)))
self.assertEqual(self.genlist(10, -15), [])
self.assertEqual(self.genlist(5, 10), list(range(5)))
self.assertEqual(self.genlist(0, 10), [])
def testStartStop(self):
self.assertEqual(self.genlist(10, 0, 10), list(range(10)))
self.assertEqual(self.genlist(10, 1, 9), list(range(10))[1:9])
self.assertEqual(self.genlist(10, -1, -1), list(range(10))[-1:-1])
self.assertEqual(self.genlist(10, 0, -15), list(range(10))[0:-15])
self.assertEqual(self.genlist(10, 15, 0), list(range(10))[-15:0])
def testStartStopStep(self):
self.assertEqual(self.genlist(10, 0, 10, 2), list(range(10))[0:10:2])
class Status(enum):
OPEN, CLOSE = range(2)
class Color(enum):
RED, GREEN, BLUE = range(3)
class EnumTest(unittest.TestCase):
def testEnums(self):
self.assertTrue(issubclass(enum, int))
self.assertTrue(isinstance(Color.RED, Color))
self.assertTrue(isinstance(Color.RED, int))
self.assertTrue('RED' in repr(Color.RED), repr(Color.RED))
self.assertTrue(int(Color.RED) is not None)
def testComparision(self):
self.assertEqual(Color.RED, 0)
self.assertNotEqual(Color.RED, 1)
self.assertNotEqual(Color.RED, -1)
self.assertNotEqual(Color.RED, Color.GREEN)
self.assertNotEqual(Color.GREEN, Status.OPEN)
def testGet(self):
self.assertEqual(Color.get(0), Color.RED)
self.assertRaises(ValueError, Color.get, 3)
def testNew(self):
yellow = Color(3, 'YELLOW')
self.assertTrue(isinstance(yellow, Color))
self.assertEqual(Color.YELLOW, yellow)
self.assertRaises(ValueError, Color, 3, 'AGAIN')
self.assertRaises(ValueError, Color, 4, 'RED')
class AttributeForwarderTest(unittest.TestCase):
def testForward(self):
class FW(AttributeForwarder):
attributes = ['forward']
class Target(object):
forward = 'foo'
target = Target()
f = FW(target)
self.assertEqual(f.target, target)
self.assertEqual(f.forward, 'foo')
f.forward = 'bar'
self.assertEqual(target.forward, 'bar')
self.assertEqual(f.forward, 'bar')
class StripAccentsTest(unittest.TestCase):
def testStripAccents(self):
for string, string_without_accentuation in [
# bytes
('áâãäåāăąàÁÂÃÄÅĀĂĄÀ'.encode(), b'aaaaaaaaaAAAAAAAAA'),
('èééêëēĕėęěĒĔĖĘĚ'.encode(), b'eeeeeeeeeeEEEEE'),
('ìíîïìĩīĭÌÍÎÏÌĨĪĬ'.encode(), b'iiiiiiiiIIIIIIII'),
('óôõöōŏőÒÓÔÕÖŌŎŐ'.encode(), b'oooooooOOOOOOOO'),
('ùúûüũūŭůÙÚÛÜŨŪŬŮ'.encode(), b'uuuuuuuuUUUUUUUU'),
('çÇ'.encode(), b'cC'),
# strings
('áâãäåāăąàÁÂÃÄÅĀĂĄÀ', 'aaaaaaaaaAAAAAAAAA'),
('èééêëēĕėęěĒĔĖĘĚ', 'eeeeeeeeeeEEEEE'),
('ìíîïìĩīĭÌÍÎÏÌĨĪĬ', 'iiiiiiiiIIIIIIII'),
('óôõöōŏőÒÓÔÕÖŌŎŐ', 'oooooooOOOOOOOO'),
('ùúûüũūŭůÙÚÛÜŨŪŬŮ', 'uuuuuuuuUUUUUUUU'),
('çÇ', 'cC'),
]:
self.assertEqual(strip_accents(string),
string_without_accentuation)
if __name__ == '__main__':
unittest.main() | if stop is None:
stop = start
start = None
| random_line_split |
test_python.py | # -*- coding: utf-8 -*-
import unittest
from kiwi.python import AttributeForwarder, slicerange, enum, strip_accents
class SliceTest(unittest.TestCase):
|
class Status(enum):
OPEN, CLOSE = range(2)
class Color(enum):
RED, GREEN, BLUE = range(3)
class EnumTest(unittest.TestCase):
def testEnums(self):
self.assertTrue(issubclass(enum, int))
self.assertTrue(isinstance(Color.RED, Color))
self.assertTrue(isinstance(Color.RED, int))
self.assertTrue('RED' in repr(Color.RED), repr(Color.RED))
self.assertTrue(int(Color.RED) is not None)
def testComparision(self):
self.assertEqual(Color.RED, 0)
self.assertNotEqual(Color.RED, 1)
self.assertNotEqual(Color.RED, -1)
self.assertNotEqual(Color.RED, Color.GREEN)
self.assertNotEqual(Color.GREEN, Status.OPEN)
def testGet(self):
self.assertEqual(Color.get(0), Color.RED)
self.assertRaises(ValueError, Color.get, 3)
def testNew(self):
yellow = Color(3, 'YELLOW')
self.assertTrue(isinstance(yellow, Color))
self.assertEqual(Color.YELLOW, yellow)
self.assertRaises(ValueError, Color, 3, 'AGAIN')
self.assertRaises(ValueError, Color, 4, 'RED')
class AttributeForwarderTest(unittest.TestCase):
def testForward(self):
class FW(AttributeForwarder):
attributes = ['forward']
class Target(object):
forward = 'foo'
target = Target()
f = FW(target)
self.assertEqual(f.target, target)
self.assertEqual(f.forward, 'foo')
f.forward = 'bar'
self.assertEqual(target.forward, 'bar')
self.assertEqual(f.forward, 'bar')
class StripAccentsTest(unittest.TestCase):
def testStripAccents(self):
for string, string_without_accentuation in [
# bytes
('áâãäåāăąàÁÂÃÄÅĀĂĄÀ'.encode(), b'aaaaaaaaaAAAAAAAAA'),
('èééêëēĕėęěĒĔĖĘĚ'.encode(), b'eeeeeeeeeeEEEEE'),
('ìíîïìĩīĭÌÍÎÏÌĨĪĬ'.encode(), b'iiiiiiiiIIIIIIII'),
('óôõöōŏőÒÓÔÕÖŌŎŐ'.encode(), b'oooooooOOOOOOOO'),
('ùúûüũūŭůÙÚÛÜŨŪŬŮ'.encode(), b'uuuuuuuuUUUUUUUU'),
('çÇ'.encode(), b'cC'),
# strings
('áâãäåāăąàÁÂÃÄÅĀĂĄÀ', 'aaaaaaaaaAAAAAAAAA'),
('èééêëēĕėęěĒĔĖĘĚ', 'eeeeeeeeeeEEEEE'),
('ìíîïìĩīĭÌÍÎÏÌĨĪĬ', 'iiiiiiiiIIIIIIII'),
('óôõöōŏőÒÓÔÕÖŌŎŐ', 'oooooooOOOOOOOO'),
('ùúûüũūŭůÙÚÛÜŨŪŬŮ', 'uuuuuuuuUUUUUUUU'),
('çÇ', 'cC'),
]:
self.assertEqual(strip_accents(string),
string_without_accentuation)
if __name__ == '__main__':
unittest.main()
| def genlist(self, limit, start, stop=None, step=None):
if stop is None:
stop = start
start = None
return list(slicerange(slice(start, stop, step), limit))
def testStop(self):
self.assertEqual(self.genlist(10, 10), list(range(10)))
self.assertEqual(self.genlist(10, -5), list(range(5)))
self.assertEqual(self.genlist(10, -15), [])
self.assertEqual(self.genlist(5, 10), list(range(5)))
self.assertEqual(self.genlist(0, 10), [])
def testStartStop(self):
self.assertEqual(self.genlist(10, 0, 10), list(range(10)))
self.assertEqual(self.genlist(10, 1, 9), list(range(10))[1:9])
self.assertEqual(self.genlist(10, -1, -1), list(range(10))[-1:-1])
self.assertEqual(self.genlist(10, 0, -15), list(range(10))[0:-15])
self.assertEqual(self.genlist(10, 15, 0), list(range(10))[-15:0])
def testStartStopStep(self):
self.assertEqual(self.genlist(10, 0, 10, 2), list(range(10))[0:10:2]) | identifier_body |
test_python.py | # -*- coding: utf-8 -*-
import unittest
from kiwi.python import AttributeForwarder, slicerange, enum, strip_accents
class SliceTest(unittest.TestCase):
def genlist(self, limit, start, stop=None, step=None):
if stop is None:
stop = start
start = None
return list(slicerange(slice(start, stop, step), limit))
def testStop(self):
self.assertEqual(self.genlist(10, 10), list(range(10)))
self.assertEqual(self.genlist(10, -5), list(range(5)))
self.assertEqual(self.genlist(10, -15), [])
self.assertEqual(self.genlist(5, 10), list(range(5)))
self.assertEqual(self.genlist(0, 10), [])
def testStartStop(self):
self.assertEqual(self.genlist(10, 0, 10), list(range(10)))
self.assertEqual(self.genlist(10, 1, 9), list(range(10))[1:9])
self.assertEqual(self.genlist(10, -1, -1), list(range(10))[-1:-1])
self.assertEqual(self.genlist(10, 0, -15), list(range(10))[0:-15])
self.assertEqual(self.genlist(10, 15, 0), list(range(10))[-15:0])
def testStartStopStep(self):
self.assertEqual(self.genlist(10, 0, 10, 2), list(range(10))[0:10:2])
class Status(enum):
OPEN, CLOSE = range(2)
class Color(enum):
RED, GREEN, BLUE = range(3)
class EnumTest(unittest.TestCase):
def testEnums(self):
self.assertTrue(issubclass(enum, int))
self.assertTrue(isinstance(Color.RED, Color))
self.assertTrue(isinstance(Color.RED, int))
self.assertTrue('RED' in repr(Color.RED), repr(Color.RED))
self.assertTrue(int(Color.RED) is not None)
def testComparision(self):
self.assertEqual(Color.RED, 0)
self.assertNotEqual(Color.RED, 1)
self.assertNotEqual(Color.RED, -1)
self.assertNotEqual(Color.RED, Color.GREEN)
self.assertNotEqual(Color.GREEN, Status.OPEN)
def testGet(self):
self.assertEqual(Color.get(0), Color.RED)
self.assertRaises(ValueError, Color.get, 3)
def testNew(self):
yellow = Color(3, 'YELLOW')
self.assertTrue(isinstance(yellow, Color))
self.assertEqual(Color.YELLOW, yellow)
self.assertRaises(ValueError, Color, 3, 'AGAIN')
self.assertRaises(ValueError, Color, 4, 'RED')
class AttributeForwarderTest(unittest.TestCase):
def testForward(self):
class FW(AttributeForwarder):
attributes = ['forward']
class Target(object):
forward = 'foo'
target = Target()
f = FW(target)
self.assertEqual(f.target, target)
self.assertEqual(f.forward, 'foo')
f.forward = 'bar'
self.assertEqual(target.forward, 'bar')
self.assertEqual(f.forward, 'bar')
class | (unittest.TestCase):
def testStripAccents(self):
for string, string_without_accentuation in [
# bytes
('áâãäåāăąàÁÂÃÄÅĀĂĄÀ'.encode(), b'aaaaaaaaaAAAAAAAAA'),
('èééêëēĕėęěĒĔĖĘĚ'.encode(), b'eeeeeeeeeeEEEEE'),
('ìíîïìĩīĭÌÍÎÏÌĨĪĬ'.encode(), b'iiiiiiiiIIIIIIII'),
('óôõöōŏőÒÓÔÕÖŌŎŐ'.encode(), b'oooooooOOOOOOOO'),
('ùúûüũūŭůÙÚÛÜŨŪŬŮ'.encode(), b'uuuuuuuuUUUUUUUU'),
('çÇ'.encode(), b'cC'),
# strings
('áâãäåāăąàÁÂÃÄÅĀĂĄÀ', 'aaaaaaaaaAAAAAAAAA'),
('èééêëēĕėęěĒĔĖĘĚ', 'eeeeeeeeeeEEEEE'),
('ìíîïìĩīĭÌÍÎÏÌĨĪĬ', 'iiiiiiiiIIIIIIII'),
('óôõöōŏőÒÓÔÕÖŌŎŐ', 'oooooooOOOOOOOO'),
('ùúûüũūŭůÙÚÛÜŨŪŬŮ', 'uuuuuuuuUUUUUUUU'),
('çÇ', 'cC'),
]:
self.assertEqual(strip_accents(string),
string_without_accentuation)
if __name__ == '__main__':
unittest.main()
| StripAccentsTest | identifier_name |
test_python.py | # -*- coding: utf-8 -*-
import unittest
from kiwi.python import AttributeForwarder, slicerange, enum, strip_accents
class SliceTest(unittest.TestCase):
def genlist(self, limit, start, stop=None, step=None):
if stop is None:
stop = start
start = None
return list(slicerange(slice(start, stop, step), limit))
def testStop(self):
self.assertEqual(self.genlist(10, 10), list(range(10)))
self.assertEqual(self.genlist(10, -5), list(range(5)))
self.assertEqual(self.genlist(10, -15), [])
self.assertEqual(self.genlist(5, 10), list(range(5)))
self.assertEqual(self.genlist(0, 10), [])
def testStartStop(self):
self.assertEqual(self.genlist(10, 0, 10), list(range(10)))
self.assertEqual(self.genlist(10, 1, 9), list(range(10))[1:9])
self.assertEqual(self.genlist(10, -1, -1), list(range(10))[-1:-1])
self.assertEqual(self.genlist(10, 0, -15), list(range(10))[0:-15])
self.assertEqual(self.genlist(10, 15, 0), list(range(10))[-15:0])
def testStartStopStep(self):
self.assertEqual(self.genlist(10, 0, 10, 2), list(range(10))[0:10:2])
class Status(enum):
OPEN, CLOSE = range(2)
class Color(enum):
RED, GREEN, BLUE = range(3)
class EnumTest(unittest.TestCase):
def testEnums(self):
self.assertTrue(issubclass(enum, int))
self.assertTrue(isinstance(Color.RED, Color))
self.assertTrue(isinstance(Color.RED, int))
self.assertTrue('RED' in repr(Color.RED), repr(Color.RED))
self.assertTrue(int(Color.RED) is not None)
def testComparision(self):
self.assertEqual(Color.RED, 0)
self.assertNotEqual(Color.RED, 1)
self.assertNotEqual(Color.RED, -1)
self.assertNotEqual(Color.RED, Color.GREEN)
self.assertNotEqual(Color.GREEN, Status.OPEN)
def testGet(self):
self.assertEqual(Color.get(0), Color.RED)
self.assertRaises(ValueError, Color.get, 3)
def testNew(self):
yellow = Color(3, 'YELLOW')
self.assertTrue(isinstance(yellow, Color))
self.assertEqual(Color.YELLOW, yellow)
self.assertRaises(ValueError, Color, 3, 'AGAIN')
self.assertRaises(ValueError, Color, 4, 'RED')
class AttributeForwarderTest(unittest.TestCase):
def testForward(self):
class FW(AttributeForwarder):
attributes = ['forward']
class Target(object):
forward = 'foo'
target = Target()
f = FW(target)
self.assertEqual(f.target, target)
self.assertEqual(f.forward, 'foo')
f.forward = 'bar'
self.assertEqual(target.forward, 'bar')
self.assertEqual(f.forward, 'bar')
class StripAccentsTest(unittest.TestCase):
def testStripAccents(self):
for string, string_without_accentuation in [
# bytes
('áâãäåāăąàÁÂÃÄÅĀĂĄÀ'.encode(), b'aaaaaaaaaAAAAAAAAA'),
('èééêëēĕėęěĒĔĖĘĚ'.encode(), b'eeeeeeeeeeEEEEE'),
('ìíîïìĩīĭÌÍÎÏÌĨĪĬ'.encode(), b'iiiiiiiiIIIIIIII'),
('óôõöōŏőÒÓÔÕÖŌŎŐ'.encode(), b'oooooooOOOOOOOO'),
('ùúûüũūŭůÙÚÛÜŨŪŬŮ'.encode(), b'uuuuuuuuUUUUUUUU'),
('çÇ'.encode(), b'cC'),
# strings
('áâãäåāăąàÁÂÃÄÅĀĂĄÀ', 'aaaaaaaaaAAAAAAAAA'),
('èééêëēĕėęěĒĔĖĘĚ', 'eeeeeeeeeeEEEEE'),
('ìíîïìĩīĭÌÍÎÏÌĨĪĬ', 'iiiiiiiiIIIIIIII'),
('óôõöōŏőÒÓÔÕÖŌŎŐ', 'oooooooOOOOOOOO'),
('ùúûüũūŭůÙÚÛÜŨŪŬŮ', 'uuuuuuuuUUUUUUUU'),
('çÇ', 'cC'),
]:
self.assertEqual(strip_accents(string),
string_without_accentuation)
if __name__ == '__main__':
unittest.main()
| conditional_block | ||
build.rs | // Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(feature = "serde")]
use bindgen;
use fs_utils::copy::copy_directory;
use glob::glob;
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
// these need to be kept in sync with the htslib Makefile
const FILES: &[&str] = &[
"kfunc.c",
"kstring.c",
"bcf_sr_sort.c",
"bgzf.c",
"errmod.c",
"faidx.c",
"header.c",
"hfile.c",
"hts.c",
"hts_expr.c",
"hts_os.c",
"md5.c",
"multipart.c",
"probaln.c",
"realn.c",
"regidx.c",
"region.c",
"sam.c",
"synced_bcf_reader.c",
"vcf_sweep.c",
"tbx.c",
"textutils.c",
"thread_pool.c",
"vcf.c",
"vcfutils.c",
"cram/cram_codecs.c",
"cram/cram_decode.c",
"cram/cram_encode.c",
"cram/cram_external.c",
"cram/cram_index.c",
"cram/cram_io.c",
"cram/cram_stats.c",
"cram/mFILE.c",
"cram/open_trace_file.c",
"cram/pooled_alloc.c",
"cram/string_alloc.c",
"htscodecs/htscodecs/arith_dynamic.c",
"htscodecs/htscodecs/fqzcomp_qual.c",
"htscodecs/htscodecs/htscodecs.c",
"htscodecs/htscodecs/pack.c",
"htscodecs/htscodecs/rANS_static4x16pr.c",
"htscodecs/htscodecs/rANS_static.c",
"htscodecs/htscodecs/rle.c",
"htscodecs/htscodecs/tokenise_name3.c",
];
fn main() {
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let htslib_copy = out.join("htslib");
if htslib_copy.exists() {
std::fs::remove_dir_all(htslib_copy).unwrap();
}
copy_directory("htslib", &out).unwrap();
// In build.rs cfg(target_os) does not give the target when cross-compiling;
// instead use the environment variable supplied by cargo, which does.
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut cfg = cc::Build::new();
let mut lib_list = "".to_string();
// default files
let out_htslib = out.join("htslib");
let htslib = PathBuf::from("htslib");
for f in FILES {
let c_file = out_htslib.join(f);
cfg.file(&c_file);
println!("cargo:rerun-if-changed={}", htslib.join(f).display());
}
cfg.include(out.join("htslib"));
let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok();
if want_static {
cfg.warnings(false).static_flag(true).pic(true);
} else {
cfg.warnings(false).static_flag(false).pic(true);
}
if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
cfg.include(z_inc);
lib_list += " -lz";
}
// We build a config.h ourselves, rather than rely on Makefile or ./configure
let mut config_lines = vec![
"/* Default config.h generated by build.rs */",
"#define HAVE_DRAND48 1",
];
let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
if use_bzip2 {
if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
.map(PathBuf::from)
.map(|path| path.join("include"))
{
cfg.include(inc);
lib_list += " -lbz2";
config_lines.push("#define HAVE_LIBBZ2 1");
}
}
let use_libdeflate = env::var("CARGO_FEATURE_LIBDEFLATE").is_ok();
if use_libdeflate {
if let Ok(inc) = env::var("DEP_LIBDEFLATE_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -ldeflate";
config_lines.push("#define HAVE_LIBDEFLATE 1");
} else { | }
let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
if use_lzma {
if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -llzma";
config_lines.push("#define HAVE_LIBBZ2 1");
config_lines.push("#ifndef __APPLE__");
config_lines.push("#define HAVE_LZMA_H 1");
config_lines.push("#endif");
}
}
let use_curl = env::var("CARGO_FEATURE_CURL").is_ok();
if use_curl {
if let Ok(inc) = env::var("DEP_CURL_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -lcurl";
config_lines.push("#define HAVE_LIBCURL 1");
cfg.file("htslib/hfile_libcurl.c");
println!("cargo:rerun-if-changed=htslib/hfile_libcurl.c");
if target_os == "macos" {
// Use builtin MacOS CommonCrypto HMAC
config_lines.push("#define HAVE_COMMONCRYPTO 1");
} else if let Ok(inc) = env::var("DEP_OPENSSL_INCLUDE").map(PathBuf::from) {
// Must use hmac from libcrypto in openssl
cfg.include(inc);
config_lines.push("#define HAVE_HMAC 1");
} else {
panic!("No OpenSSL dependency -- need OpenSSL includes");
}
}
}
let use_gcs = env::var("CARGO_FEATURE_GCS").is_ok();
if use_gcs {
config_lines.push("#define ENABLE_GCS 1");
cfg.file("htslib/hfile_gcs.c");
println!("cargo:rerun-if-changed=htslib/hfile_gcs.c");
}
let use_s3 = env::var("CARGO_FEATURE_S3").is_ok();
if use_s3 {
config_lines.push("#define ENABLE_S3 1");
cfg.file("htslib/hfile_s3.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3.c");
cfg.file("htslib/hfile_s3_write.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3_write.c");
}
// write out config.h which controls the options htslib will use
{
let mut f = std::fs::File::create(out.join("htslib").join("config.h")).unwrap();
for l in config_lines {
writeln!(&mut f, "{}", l).unwrap();
}
}
// write out version.h
{
let version = std::process::Command::new(out.join("htslib").join("version.sh"))
.output()
.expect("failed to execute process");
let version_str = std::str::from_utf8(&version.stdout).unwrap().trim();
let mut f = std::fs::File::create(out.join("htslib").join("version.h")).unwrap();
writeln!(&mut f, "#define HTS_VERSION_TEXT \"{}\"", version_str).unwrap();
}
// write out htscodecs/htscodecs/version.h
{
let mut f = std::fs::File::create(
out.join("htslib")
.join("htscodecs")
.join("htscodecs")
.join("version.h"),
)
.unwrap();
// FIXME, using a dummy. Not sure why this should be a separate version from htslib itself.
writeln!(&mut f, "#define HTSCODECS_VERSION_TEXT \"rust-htslib\"").unwrap();
}
// write out config_vars.h which is used to expose compiler parameters via
// hts_test_feature() in hts.c. We partially fill in these values.
{
let tool = cfg.get_compiler();
let mut f = std::fs::File::create(out.join("htslib").join("config_vars.h")).unwrap();
writeln!(&mut f, "#define HTS_CC {:?}", tool.cc_env()).unwrap();
writeln!(&mut f, "#define HTS_CPPFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_CFLAGS {:?}", tool.cflags_env()).unwrap();
writeln!(&mut f, "#define HTS_LDFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_LIBS \"{}\"", lib_list).unwrap();
}
cfg.file("wrapper.c");
cfg.compile("hts");
// If bindgen is enabled, use it
#[cfg(feature = "bindgen")]
{
bindgen::Builder::default()
.header("wrapper.h")
.generate_comments(false)
.blacklist_function("strtold")
.blacklist_type("max_align_t")
.generate()
.expect("Unable to generate bindings.")
.write_to_file(out.join("bindings.rs"))
.expect("Could not write bindings.");
}
// If no bindgen, use pre-built bindings
#[cfg(not(feature = "bindgen"))]
if target_os == "macos" {
fs::copy("osx_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=osx_prebuilt_bindings.rs");
} else {
fs::copy("linux_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=linux_prebuilt_bindings.rs");
}
let include = out.join("include");
fs::create_dir_all(&include).unwrap();
if include.join("htslib").exists() {
fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
}
copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
println!("cargo:root={}", out.display());
println!("cargo:include={}", include.display());
println!("cargo:libdir={}", out.display());
println!("cargo:rerun-if-changed=wrapper.c");
println!("cargo:rerun-if-changed=wrapper.h");
let globs = std::iter::empty()
.chain(glob("htslib/*.[h]").unwrap())
.chain(glob("htslib/cram/*.[h]").unwrap())
.chain(glob("htslib/htslib/*.h").unwrap())
.chain(glob("htslib/os/*.[h]").unwrap())
.filter_map(Result::ok);
for htsfile in globs {
println!("cargo:rerun-if-changed={}", htsfile.display());
}
// Note: config.h is a function of the cargo features. Any feature change will
// cause build.rs to re-run, so don't re-run on that change.
//println!("cargo:rerun-if-changed=htslib/config.h");
}
|
panic!("no DEP_LIBDEFLATE_INCLUDE");
}
| conditional_block |
build.rs | // Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(feature = "serde")]
use bindgen;
use fs_utils::copy::copy_directory;
use glob::glob;
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
// these need to be kept in sync with the htslib Makefile
const FILES: &[&str] = &[
"kfunc.c",
"kstring.c",
"bcf_sr_sort.c",
"bgzf.c",
"errmod.c",
"faidx.c",
"header.c",
"hfile.c",
"hts.c",
"hts_expr.c",
"hts_os.c",
"md5.c",
"multipart.c",
"probaln.c",
"realn.c",
"regidx.c",
"region.c",
"sam.c",
"synced_bcf_reader.c",
"vcf_sweep.c",
"tbx.c",
"textutils.c",
"thread_pool.c",
"vcf.c",
"vcfutils.c",
"cram/cram_codecs.c",
"cram/cram_decode.c",
"cram/cram_encode.c",
"cram/cram_external.c",
"cram/cram_index.c",
"cram/cram_io.c",
"cram/cram_stats.c", | "htscodecs/htscodecs/fqzcomp_qual.c",
"htscodecs/htscodecs/htscodecs.c",
"htscodecs/htscodecs/pack.c",
"htscodecs/htscodecs/rANS_static4x16pr.c",
"htscodecs/htscodecs/rANS_static.c",
"htscodecs/htscodecs/rle.c",
"htscodecs/htscodecs/tokenise_name3.c",
];
fn main() {
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let htslib_copy = out.join("htslib");
if htslib_copy.exists() {
std::fs::remove_dir_all(htslib_copy).unwrap();
}
copy_directory("htslib", &out).unwrap();
// In build.rs cfg(target_os) does not give the target when cross-compiling;
// instead use the environment variable supplied by cargo, which does.
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut cfg = cc::Build::new();
let mut lib_list = "".to_string();
// default files
let out_htslib = out.join("htslib");
let htslib = PathBuf::from("htslib");
for f in FILES {
let c_file = out_htslib.join(f);
cfg.file(&c_file);
println!("cargo:rerun-if-changed={}", htslib.join(f).display());
}
cfg.include(out.join("htslib"));
let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok();
if want_static {
cfg.warnings(false).static_flag(true).pic(true);
} else {
cfg.warnings(false).static_flag(false).pic(true);
}
if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
cfg.include(z_inc);
lib_list += " -lz";
}
// We build a config.h ourselves, rather than rely on Makefile or ./configure
let mut config_lines = vec![
"/* Default config.h generated by build.rs */",
"#define HAVE_DRAND48 1",
];
let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
if use_bzip2 {
if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
.map(PathBuf::from)
.map(|path| path.join("include"))
{
cfg.include(inc);
lib_list += " -lbz2";
config_lines.push("#define HAVE_LIBBZ2 1");
}
}
let use_libdeflate = env::var("CARGO_FEATURE_LIBDEFLATE").is_ok();
if use_libdeflate {
if let Ok(inc) = env::var("DEP_LIBDEFLATE_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -ldeflate";
config_lines.push("#define HAVE_LIBDEFLATE 1");
} else {
panic!("no DEP_LIBDEFLATE_INCLUDE");
}
}
let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
if use_lzma {
if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -llzma";
config_lines.push("#define HAVE_LIBBZ2 1");
config_lines.push("#ifndef __APPLE__");
config_lines.push("#define HAVE_LZMA_H 1");
config_lines.push("#endif");
}
}
let use_curl = env::var("CARGO_FEATURE_CURL").is_ok();
if use_curl {
if let Ok(inc) = env::var("DEP_CURL_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -lcurl";
config_lines.push("#define HAVE_LIBCURL 1");
cfg.file("htslib/hfile_libcurl.c");
println!("cargo:rerun-if-changed=htslib/hfile_libcurl.c");
if target_os == "macos" {
// Use builtin MacOS CommonCrypto HMAC
config_lines.push("#define HAVE_COMMONCRYPTO 1");
} else if let Ok(inc) = env::var("DEP_OPENSSL_INCLUDE").map(PathBuf::from) {
// Must use hmac from libcrypto in openssl
cfg.include(inc);
config_lines.push("#define HAVE_HMAC 1");
} else {
panic!("No OpenSSL dependency -- need OpenSSL includes");
}
}
}
let use_gcs = env::var("CARGO_FEATURE_GCS").is_ok();
if use_gcs {
config_lines.push("#define ENABLE_GCS 1");
cfg.file("htslib/hfile_gcs.c");
println!("cargo:rerun-if-changed=htslib/hfile_gcs.c");
}
let use_s3 = env::var("CARGO_FEATURE_S3").is_ok();
if use_s3 {
config_lines.push("#define ENABLE_S3 1");
cfg.file("htslib/hfile_s3.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3.c");
cfg.file("htslib/hfile_s3_write.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3_write.c");
}
// write out config.h which controls the options htslib will use
{
let mut f = std::fs::File::create(out.join("htslib").join("config.h")).unwrap();
for l in config_lines {
writeln!(&mut f, "{}", l).unwrap();
}
}
// write out version.h
{
let version = std::process::Command::new(out.join("htslib").join("version.sh"))
.output()
.expect("failed to execute process");
let version_str = std::str::from_utf8(&version.stdout).unwrap().trim();
let mut f = std::fs::File::create(out.join("htslib").join("version.h")).unwrap();
writeln!(&mut f, "#define HTS_VERSION_TEXT \"{}\"", version_str).unwrap();
}
// write out htscodecs/htscodecs/version.h
{
let mut f = std::fs::File::create(
out.join("htslib")
.join("htscodecs")
.join("htscodecs")
.join("version.h"),
)
.unwrap();
// FIXME, using a dummy. Not sure why this should be a separate version from htslib itself.
writeln!(&mut f, "#define HTSCODECS_VERSION_TEXT \"rust-htslib\"").unwrap();
}
// write out config_vars.h which is used to expose compiler parameters via
// hts_test_feature() in hts.c. We partially fill in these values.
{
let tool = cfg.get_compiler();
let mut f = std::fs::File::create(out.join("htslib").join("config_vars.h")).unwrap();
writeln!(&mut f, "#define HTS_CC {:?}", tool.cc_env()).unwrap();
writeln!(&mut f, "#define HTS_CPPFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_CFLAGS {:?}", tool.cflags_env()).unwrap();
writeln!(&mut f, "#define HTS_LDFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_LIBS \"{}\"", lib_list).unwrap();
}
cfg.file("wrapper.c");
cfg.compile("hts");
// If bindgen is enabled, use it
#[cfg(feature = "bindgen")]
{
bindgen::Builder::default()
.header("wrapper.h")
.generate_comments(false)
.blacklist_function("strtold")
.blacklist_type("max_align_t")
.generate()
.expect("Unable to generate bindings.")
.write_to_file(out.join("bindings.rs"))
.expect("Could not write bindings.");
}
// If no bindgen, use pre-built bindings
#[cfg(not(feature = "bindgen"))]
if target_os == "macos" {
fs::copy("osx_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=osx_prebuilt_bindings.rs");
} else {
fs::copy("linux_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=linux_prebuilt_bindings.rs");
}
let include = out.join("include");
fs::create_dir_all(&include).unwrap();
if include.join("htslib").exists() {
fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
}
copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
println!("cargo:root={}", out.display());
println!("cargo:include={}", include.display());
println!("cargo:libdir={}", out.display());
println!("cargo:rerun-if-changed=wrapper.c");
println!("cargo:rerun-if-changed=wrapper.h");
let globs = std::iter::empty()
.chain(glob("htslib/*.[h]").unwrap())
.chain(glob("htslib/cram/*.[h]").unwrap())
.chain(glob("htslib/htslib/*.h").unwrap())
.chain(glob("htslib/os/*.[h]").unwrap())
.filter_map(Result::ok);
for htsfile in globs {
println!("cargo:rerun-if-changed={}", htsfile.display());
}
// Note: config.h is a function of the cargo features. Any feature change will
// cause build.rs to re-run, so don't re-run on that change.
//println!("cargo:rerun-if-changed=htslib/config.h");
} | "cram/mFILE.c",
"cram/open_trace_file.c",
"cram/pooled_alloc.c",
"cram/string_alloc.c",
"htscodecs/htscodecs/arith_dynamic.c", | random_line_split |
build.rs | // Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(feature = "serde")]
use bindgen;
use fs_utils::copy::copy_directory;
use glob::glob;
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
// these need to be kept in sync with the htslib Makefile
const FILES: &[&str] = &[
"kfunc.c",
"kstring.c",
"bcf_sr_sort.c",
"bgzf.c",
"errmod.c",
"faidx.c",
"header.c",
"hfile.c",
"hts.c",
"hts_expr.c",
"hts_os.c",
"md5.c",
"multipart.c",
"probaln.c",
"realn.c",
"regidx.c",
"region.c",
"sam.c",
"synced_bcf_reader.c",
"vcf_sweep.c",
"tbx.c",
"textutils.c",
"thread_pool.c",
"vcf.c",
"vcfutils.c",
"cram/cram_codecs.c",
"cram/cram_decode.c",
"cram/cram_encode.c",
"cram/cram_external.c",
"cram/cram_index.c",
"cram/cram_io.c",
"cram/cram_stats.c",
"cram/mFILE.c",
"cram/open_trace_file.c",
"cram/pooled_alloc.c",
"cram/string_alloc.c",
"htscodecs/htscodecs/arith_dynamic.c",
"htscodecs/htscodecs/fqzcomp_qual.c",
"htscodecs/htscodecs/htscodecs.c",
"htscodecs/htscodecs/pack.c",
"htscodecs/htscodecs/rANS_static4x16pr.c",
"htscodecs/htscodecs/rANS_static.c",
"htscodecs/htscodecs/rle.c",
"htscodecs/htscodecs/tokenise_name3.c",
];
fn main() { |
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let htslib_copy = out.join("htslib");
if htslib_copy.exists() {
std::fs::remove_dir_all(htslib_copy).unwrap();
}
copy_directory("htslib", &out).unwrap();
// In build.rs cfg(target_os) does not give the target when cross-compiling;
// instead use the environment variable supplied by cargo, which does.
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut cfg = cc::Build::new();
let mut lib_list = "".to_string();
// default files
let out_htslib = out.join("htslib");
let htslib = PathBuf::from("htslib");
for f in FILES {
let c_file = out_htslib.join(f);
cfg.file(&c_file);
println!("cargo:rerun-if-changed={}", htslib.join(f).display());
}
cfg.include(out.join("htslib"));
let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok();
if want_static {
cfg.warnings(false).static_flag(true).pic(true);
} else {
cfg.warnings(false).static_flag(false).pic(true);
}
if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
cfg.include(z_inc);
lib_list += " -lz";
}
// We build a config.h ourselves, rather than rely on Makefile or ./configure
let mut config_lines = vec![
"/* Default config.h generated by build.rs */",
"#define HAVE_DRAND48 1",
];
let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
if use_bzip2 {
if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
.map(PathBuf::from)
.map(|path| path.join("include"))
{
cfg.include(inc);
lib_list += " -lbz2";
config_lines.push("#define HAVE_LIBBZ2 1");
}
}
let use_libdeflate = env::var("CARGO_FEATURE_LIBDEFLATE").is_ok();
if use_libdeflate {
if let Ok(inc) = env::var("DEP_LIBDEFLATE_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -ldeflate";
config_lines.push("#define HAVE_LIBDEFLATE 1");
} else {
panic!("no DEP_LIBDEFLATE_INCLUDE");
}
}
let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
if use_lzma {
if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -llzma";
config_lines.push("#define HAVE_LIBBZ2 1");
config_lines.push("#ifndef __APPLE__");
config_lines.push("#define HAVE_LZMA_H 1");
config_lines.push("#endif");
}
}
let use_curl = env::var("CARGO_FEATURE_CURL").is_ok();
if use_curl {
if let Ok(inc) = env::var("DEP_CURL_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -lcurl";
config_lines.push("#define HAVE_LIBCURL 1");
cfg.file("htslib/hfile_libcurl.c");
println!("cargo:rerun-if-changed=htslib/hfile_libcurl.c");
if target_os == "macos" {
// Use builtin MacOS CommonCrypto HMAC
config_lines.push("#define HAVE_COMMONCRYPTO 1");
} else if let Ok(inc) = env::var("DEP_OPENSSL_INCLUDE").map(PathBuf::from) {
// Must use hmac from libcrypto in openssl
cfg.include(inc);
config_lines.push("#define HAVE_HMAC 1");
} else {
panic!("No OpenSSL dependency -- need OpenSSL includes");
}
}
}
let use_gcs = env::var("CARGO_FEATURE_GCS").is_ok();
if use_gcs {
config_lines.push("#define ENABLE_GCS 1");
cfg.file("htslib/hfile_gcs.c");
println!("cargo:rerun-if-changed=htslib/hfile_gcs.c");
}
let use_s3 = env::var("CARGO_FEATURE_S3").is_ok();
if use_s3 {
config_lines.push("#define ENABLE_S3 1");
cfg.file("htslib/hfile_s3.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3.c");
cfg.file("htslib/hfile_s3_write.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3_write.c");
}
// write out config.h which controls the options htslib will use
{
let mut f = std::fs::File::create(out.join("htslib").join("config.h")).unwrap();
for l in config_lines {
writeln!(&mut f, "{}", l).unwrap();
}
}
// write out version.h
{
let version = std::process::Command::new(out.join("htslib").join("version.sh"))
.output()
.expect("failed to execute process");
let version_str = std::str::from_utf8(&version.stdout).unwrap().trim();
let mut f = std::fs::File::create(out.join("htslib").join("version.h")).unwrap();
writeln!(&mut f, "#define HTS_VERSION_TEXT \"{}\"", version_str).unwrap();
}
// write out htscodecs/htscodecs/version.h
{
let mut f = std::fs::File::create(
out.join("htslib")
.join("htscodecs")
.join("htscodecs")
.join("version.h"),
)
.unwrap();
// FIXME, using a dummy. Not sure why this should be a separate version from htslib itself.
writeln!(&mut f, "#define HTSCODECS_VERSION_TEXT \"rust-htslib\"").unwrap();
}
// write out config_vars.h which is used to expose compiler parameters via
// hts_test_feature() in hts.c. We partially fill in these values.
{
let tool = cfg.get_compiler();
let mut f = std::fs::File::create(out.join("htslib").join("config_vars.h")).unwrap();
writeln!(&mut f, "#define HTS_CC {:?}", tool.cc_env()).unwrap();
writeln!(&mut f, "#define HTS_CPPFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_CFLAGS {:?}", tool.cflags_env()).unwrap();
writeln!(&mut f, "#define HTS_LDFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_LIBS \"{}\"", lib_list).unwrap();
}
cfg.file("wrapper.c");
cfg.compile("hts");
// If bindgen is enabled, use it
#[cfg(feature = "bindgen")]
{
bindgen::Builder::default()
.header("wrapper.h")
.generate_comments(false)
.blacklist_function("strtold")
.blacklist_type("max_align_t")
.generate()
.expect("Unable to generate bindings.")
.write_to_file(out.join("bindings.rs"))
.expect("Could not write bindings.");
}
// If no bindgen, use pre-built bindings
#[cfg(not(feature = "bindgen"))]
if target_os == "macos" {
fs::copy("osx_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=osx_prebuilt_bindings.rs");
} else {
fs::copy("linux_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=linux_prebuilt_bindings.rs");
}
let include = out.join("include");
fs::create_dir_all(&include).unwrap();
if include.join("htslib").exists() {
fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
}
copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
println!("cargo:root={}", out.display());
println!("cargo:include={}", include.display());
println!("cargo:libdir={}", out.display());
println!("cargo:rerun-if-changed=wrapper.c");
println!("cargo:rerun-if-changed=wrapper.h");
let globs = std::iter::empty()
.chain(glob("htslib/*.[h]").unwrap())
.chain(glob("htslib/cram/*.[h]").unwrap())
.chain(glob("htslib/htslib/*.h").unwrap())
.chain(glob("htslib/os/*.[h]").unwrap())
.filter_map(Result::ok);
for htsfile in globs {
println!("cargo:rerun-if-changed={}", htsfile.display());
}
// Note: config.h is a function of the cargo features. Any feature change will
// cause build.rs to re-run, so don't re-run on that change.
//println!("cargo:rerun-if-changed=htslib/config.h");
}
| identifier_body | |
build.rs | // Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(feature = "serde")]
use bindgen;
use fs_utils::copy::copy_directory;
use glob::glob;
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
// these need to be kept in sync with the htslib Makefile
const FILES: &[&str] = &[
"kfunc.c",
"kstring.c",
"bcf_sr_sort.c",
"bgzf.c",
"errmod.c",
"faidx.c",
"header.c",
"hfile.c",
"hts.c",
"hts_expr.c",
"hts_os.c",
"md5.c",
"multipart.c",
"probaln.c",
"realn.c",
"regidx.c",
"region.c",
"sam.c",
"synced_bcf_reader.c",
"vcf_sweep.c",
"tbx.c",
"textutils.c",
"thread_pool.c",
"vcf.c",
"vcfutils.c",
"cram/cram_codecs.c",
"cram/cram_decode.c",
"cram/cram_encode.c",
"cram/cram_external.c",
"cram/cram_index.c",
"cram/cram_io.c",
"cram/cram_stats.c",
"cram/mFILE.c",
"cram/open_trace_file.c",
"cram/pooled_alloc.c",
"cram/string_alloc.c",
"htscodecs/htscodecs/arith_dynamic.c",
"htscodecs/htscodecs/fqzcomp_qual.c",
"htscodecs/htscodecs/htscodecs.c",
"htscodecs/htscodecs/pack.c",
"htscodecs/htscodecs/rANS_static4x16pr.c",
"htscodecs/htscodecs/rANS_static.c",
"htscodecs/htscodecs/rle.c",
"htscodecs/htscodecs/tokenise_name3.c",
];
fn m | ) {
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let htslib_copy = out.join("htslib");
if htslib_copy.exists() {
std::fs::remove_dir_all(htslib_copy).unwrap();
}
copy_directory("htslib", &out).unwrap();
// In build.rs cfg(target_os) does not give the target when cross-compiling;
// instead use the environment variable supplied by cargo, which does.
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut cfg = cc::Build::new();
let mut lib_list = "".to_string();
// default files
let out_htslib = out.join("htslib");
let htslib = PathBuf::from("htslib");
for f in FILES {
let c_file = out_htslib.join(f);
cfg.file(&c_file);
println!("cargo:rerun-if-changed={}", htslib.join(f).display());
}
cfg.include(out.join("htslib"));
let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok();
if want_static {
cfg.warnings(false).static_flag(true).pic(true);
} else {
cfg.warnings(false).static_flag(false).pic(true);
}
if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
cfg.include(z_inc);
lib_list += " -lz";
}
// We build a config.h ourselves, rather than rely on Makefile or ./configure
let mut config_lines = vec![
"/* Default config.h generated by build.rs */",
"#define HAVE_DRAND48 1",
];
let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
if use_bzip2 {
if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
.map(PathBuf::from)
.map(|path| path.join("include"))
{
cfg.include(inc);
lib_list += " -lbz2";
config_lines.push("#define HAVE_LIBBZ2 1");
}
}
let use_libdeflate = env::var("CARGO_FEATURE_LIBDEFLATE").is_ok();
if use_libdeflate {
if let Ok(inc) = env::var("DEP_LIBDEFLATE_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -ldeflate";
config_lines.push("#define HAVE_LIBDEFLATE 1");
} else {
panic!("no DEP_LIBDEFLATE_INCLUDE");
}
}
let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
if use_lzma {
if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -llzma";
config_lines.push("#define HAVE_LIBBZ2 1");
config_lines.push("#ifndef __APPLE__");
config_lines.push("#define HAVE_LZMA_H 1");
config_lines.push("#endif");
}
}
let use_curl = env::var("CARGO_FEATURE_CURL").is_ok();
if use_curl {
if let Ok(inc) = env::var("DEP_CURL_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -lcurl";
config_lines.push("#define HAVE_LIBCURL 1");
cfg.file("htslib/hfile_libcurl.c");
println!("cargo:rerun-if-changed=htslib/hfile_libcurl.c");
if target_os == "macos" {
// Use builtin MacOS CommonCrypto HMAC
config_lines.push("#define HAVE_COMMONCRYPTO 1");
} else if let Ok(inc) = env::var("DEP_OPENSSL_INCLUDE").map(PathBuf::from) {
// Must use hmac from libcrypto in openssl
cfg.include(inc);
config_lines.push("#define HAVE_HMAC 1");
} else {
panic!("No OpenSSL dependency -- need OpenSSL includes");
}
}
}
let use_gcs = env::var("CARGO_FEATURE_GCS").is_ok();
if use_gcs {
config_lines.push("#define ENABLE_GCS 1");
cfg.file("htslib/hfile_gcs.c");
println!("cargo:rerun-if-changed=htslib/hfile_gcs.c");
}
let use_s3 = env::var("CARGO_FEATURE_S3").is_ok();
if use_s3 {
config_lines.push("#define ENABLE_S3 1");
cfg.file("htslib/hfile_s3.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3.c");
cfg.file("htslib/hfile_s3_write.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3_write.c");
}
// write out config.h which controls the options htslib will use
{
let mut f = std::fs::File::create(out.join("htslib").join("config.h")).unwrap();
for l in config_lines {
writeln!(&mut f, "{}", l).unwrap();
}
}
// write out version.h
{
let version = std::process::Command::new(out.join("htslib").join("version.sh"))
.output()
.expect("failed to execute process");
let version_str = std::str::from_utf8(&version.stdout).unwrap().trim();
let mut f = std::fs::File::create(out.join("htslib").join("version.h")).unwrap();
writeln!(&mut f, "#define HTS_VERSION_TEXT \"{}\"", version_str).unwrap();
}
// write out htscodecs/htscodecs/version.h
{
let mut f = std::fs::File::create(
out.join("htslib")
.join("htscodecs")
.join("htscodecs")
.join("version.h"),
)
.unwrap();
// FIXME, using a dummy. Not sure why this should be a separate version from htslib itself.
writeln!(&mut f, "#define HTSCODECS_VERSION_TEXT \"rust-htslib\"").unwrap();
}
// write out config_vars.h which is used to expose compiler parameters via
// hts_test_feature() in hts.c. We partially fill in these values.
{
let tool = cfg.get_compiler();
let mut f = std::fs::File::create(out.join("htslib").join("config_vars.h")).unwrap();
writeln!(&mut f, "#define HTS_CC {:?}", tool.cc_env()).unwrap();
writeln!(&mut f, "#define HTS_CPPFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_CFLAGS {:?}", tool.cflags_env()).unwrap();
writeln!(&mut f, "#define HTS_LDFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_LIBS \"{}\"", lib_list).unwrap();
}
cfg.file("wrapper.c");
cfg.compile("hts");
// If bindgen is enabled, use it
#[cfg(feature = "bindgen")]
{
bindgen::Builder::default()
.header("wrapper.h")
.generate_comments(false)
.blacklist_function("strtold")
.blacklist_type("max_align_t")
.generate()
.expect("Unable to generate bindings.")
.write_to_file(out.join("bindings.rs"))
.expect("Could not write bindings.");
}
// If no bindgen, use pre-built bindings
#[cfg(not(feature = "bindgen"))]
if target_os == "macos" {
fs::copy("osx_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=osx_prebuilt_bindings.rs");
} else {
fs::copy("linux_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=linux_prebuilt_bindings.rs");
}
let include = out.join("include");
fs::create_dir_all(&include).unwrap();
if include.join("htslib").exists() {
fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
}
copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
println!("cargo:root={}", out.display());
println!("cargo:include={}", include.display());
println!("cargo:libdir={}", out.display());
println!("cargo:rerun-if-changed=wrapper.c");
println!("cargo:rerun-if-changed=wrapper.h");
let globs = std::iter::empty()
.chain(glob("htslib/*.[h]").unwrap())
.chain(glob("htslib/cram/*.[h]").unwrap())
.chain(glob("htslib/htslib/*.h").unwrap())
.chain(glob("htslib/os/*.[h]").unwrap())
.filter_map(Result::ok);
for htsfile in globs {
println!("cargo:rerun-if-changed={}", htsfile.display());
}
// Note: config.h is a function of the cargo features. Any feature change will
// cause build.rs to re-run, so don't re-run on that change.
//println!("cargo:rerun-if-changed=htslib/config.h");
}
| ain( | identifier_name |
courselist.js | app.directive('modelanythingPluginsCourselist', [
"settings",
"$location",
"SessionService",
"User",
"Course",
function(
settings,
$location,
SessionService,
User,
Course
) {
return {
templateUrl: settings.widgets + 'modelanything/plugins/courselist.html',
link: function(scope, element, attrs) {
var session_user;
var getCourse = function(course) {
Course.get({_id: course._id}, function(course) {
return course[0];
});
}
var refresh = function(){
SessionService.getSession().success(function(response) {
User.get({_id: response.user._id, _populate:"courses"}, function(user) {
session_user = user;
if(session_user[0].role == "admin") {
scope.heading = "All courses";
} else if((session_user[0].role == "student") || (session_user[0].role == "teacher")) {
scope.heading = "My courses";
}
scope.pinnedCourses = [];
if(user[0].courses_pinned.length > 0) {
var allPinnedCourses = [];
for (i = 0; i < user[0].courses_pinned.length; i++) {
currentObj = session_user[0].courses_pinned[i];
if(currentObj.pinned) {
Course.get({_id: currentObj.course}, function(course) {
scope.pinnedCourses.push(course[0]);
});
}
}
}
});
});
}
//Runs on page update
refresh();
function | (array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
}
scope.class = "assignClass"
scope.courseLocation = function(obj) {
$location.path("courses/" + obj.currentTarget.attributes.dataLocation.value);
};
scope.$root.$on('addedCourse', function() {
refresh();
});
}
}
}
]);
| findWithAttr | identifier_name |
courselist.js | app.directive('modelanythingPluginsCourselist', [
"settings",
"$location",
"SessionService",
"User",
"Course",
function(
settings,
$location,
SessionService,
User,
Course
) {
return {
templateUrl: settings.widgets + 'modelanything/plugins/courselist.html',
link: function(scope, element, attrs) {
var session_user;
var getCourse = function(course) {
Course.get({_id: course._id}, function(course) {
return course[0];
});
}
var refresh = function(){
SessionService.getSession().success(function(response) {
User.get({_id: response.user._id, _populate:"courses"}, function(user) {
session_user = user;
if(session_user[0].role == "admin") {
scope.heading = "All courses";
} else if((session_user[0].role == "student") || (session_user[0].role == "teacher")) {
scope.heading = "My courses";
}
scope.pinnedCourses = [];
if(user[0].courses_pinned.length > 0) {
var allPinnedCourses = [];
for (i = 0; i < user[0].courses_pinned.length; i++) {
currentObj = session_user[0].courses_pinned[i];
if(currentObj.pinned) {
Course.get({_id: currentObj.course}, function(course) {
scope.pinnedCourses.push(course[0]);
});
}
}
}
});
});
}
//Runs on page update
refresh();
function findWithAttr(array, attr, value) |
scope.class = "assignClass"
scope.courseLocation = function(obj) {
$location.path("courses/" + obj.currentTarget.attributes.dataLocation.value);
};
scope.$root.$on('addedCourse', function() {
refresh();
});
}
}
}
]);
| {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
} | identifier_body |
courselist.js | app.directive('modelanythingPluginsCourselist', [
"settings",
"$location",
"SessionService",
"User",
"Course",
function(
settings,
$location,
SessionService,
User,
Course
) {
return {
templateUrl: settings.widgets + 'modelanything/plugins/courselist.html',
link: function(scope, element, attrs) {
var session_user;
var getCourse = function(course) {
Course.get({_id: course._id}, function(course) {
return course[0];
});
}
var refresh = function(){
SessionService.getSession().success(function(response) {
User.get({_id: response.user._id, _populate:"courses"}, function(user) {
session_user = user;
if(session_user[0].role == "admin") | else if((session_user[0].role == "student") || (session_user[0].role == "teacher")) {
scope.heading = "My courses";
}
scope.pinnedCourses = [];
if(user[0].courses_pinned.length > 0) {
var allPinnedCourses = [];
for (i = 0; i < user[0].courses_pinned.length; i++) {
currentObj = session_user[0].courses_pinned[i];
if(currentObj.pinned) {
Course.get({_id: currentObj.course}, function(course) {
scope.pinnedCourses.push(course[0]);
});
}
}
}
});
});
}
//Runs on page update
refresh();
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
}
scope.class = "assignClass"
scope.courseLocation = function(obj) {
$location.path("courses/" + obj.currentTarget.attributes.dataLocation.value);
};
scope.$root.$on('addedCourse', function() {
refresh();
});
}
}
}
]);
| {
scope.heading = "All courses";
} | conditional_block |
courselist.js | app.directive('modelanythingPluginsCourselist', [
"settings",
"$location",
"SessionService",
"User",
"Course",
function(
settings,
$location,
SessionService,
User,
Course
) {
return {
templateUrl: settings.widgets + 'modelanything/plugins/courselist.html',
link: function(scope, element, attrs) {
var session_user;
var getCourse = function(course) {
Course.get({_id: course._id}, function(course) {
return course[0];
});
}
var refresh = function(){
SessionService.getSession().success(function(response) {
User.get({_id: response.user._id, _populate:"courses"}, function(user) {
session_user = user;
if(session_user[0].role == "admin") {
scope.heading = "All courses";
} else if((session_user[0].role == "student") || (session_user[0].role == "teacher")) { | scope.heading = "My courses";
}
scope.pinnedCourses = [];
if(user[0].courses_pinned.length > 0) {
var allPinnedCourses = [];
for (i = 0; i < user[0].courses_pinned.length; i++) {
currentObj = session_user[0].courses_pinned[i];
if(currentObj.pinned) {
Course.get({_id: currentObj.course}, function(course) {
scope.pinnedCourses.push(course[0]);
});
}
}
}
});
});
}
//Runs on page update
refresh();
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
}
scope.class = "assignClass"
scope.courseLocation = function(obj) {
$location.path("courses/" + obj.currentTarget.attributes.dataLocation.value);
};
scope.$root.$on('addedCourse', function() {
refresh();
});
}
}
}
]); | random_line_split | |
backboneApp.js | var Backbone = require('backbone'),
_ = require('underscore');
global.App = {};
App.Task = Backbone.Model.extend({
url : 'http://localhost:9292/tasks/' + this.get('id'),
defaults : {
title: 'Untitled Task 1',
done : false
}
});
App.TaskCollection = Backbone.collection.extend({
model : Task,
urlRoot : 'http://localhost:9292/tasks'
});
App.TaskView = Backbone.View.extend({
tagName : 'li',
className : 'task',
template : _.template(require('./templates/task.html')),
initialize : function() {
this.render();
},
render : function() {
this.$el.html(this.template(this.model.attributes));
this.delegateEvents();
return this;
}
});
App.TaskCollectionView = Backbone.View.extend({
tagName : 'ul',
className : 'task-list',
initialize: function() {
this.render();
},
render : function() {
this.$el.empty();
_.each(this.collection.models, function(task) {
var view = new App.TaskView({model: task});
this.$el.append(view.render().$el);
});
this.delegateEvents();
return this;
}
});
App.Router = Backbone.Router.extend({
routes : { |
showList: function() {
var tasks = new App.TaskCollection();
var view = new App.TaskCollectionView({collection: tasks});
$('body').html(view.render().el);
}
});
module.exports = App; | '(/)' : 'showList'
}, | random_line_split |
tooltip.js | /*!
* AngularJS Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.5
*/
goog.provide('ngmaterial.components.tooltip');
goog.require('ngmaterial.components.panel');
goog.require('ngmaterial.core');
/**
* @ngdoc module
* @name material.components.tooltip
*/
MdTooltipDirective['$inject'] = ["$timeout", "$window", "$$rAF", "$document", "$interpolate", "$mdUtil", "$mdPanel", "$$mdTooltipRegistry"];
angular
.module('material.components.tooltip', [
'material.core',
'material.components.panel'
])
.directive('mdTooltip', MdTooltipDirective)
.service('$$mdTooltipRegistry', MdTooltipRegistry);
/**
* @ngdoc directive
* @name mdTooltip
* @module material.components.tooltip
* @description
* Tooltips are used to describe elements that are interactive and primarily
* graphical (not textual).
*
* Place a `<md-tooltip>` as a child of the element it describes.
*
* A tooltip will activate when the user hovers over, focuses, or touches the
* parent element.
*
* @usage
* <hljs lang="html">
* <md-button class="md-fab md-accent" aria-label="Play">
* <md-tooltip>Play Music</md-tooltip>
* <md-icon md-svg-src="img/icons/ic_play_arrow_24px.svg"></md-icon>
* </md-button>
* </hljs>
*
* @param {number=} md-z-index The visual level that the tooltip will appear
* in comparison with the rest of the elements of the application.
* @param {expression=} md-visible Boolean bound to whether the tooltip is
* currently visible.
* @param {number=} md-delay How many milliseconds to wait to show the tooltip
* after the user hovers over, focuses, or touches the parent element.
* Defaults to 0ms on non-touch devices and 75ms on touch.
* @param {boolean=} md-autohide If present or provided with a boolean value,
* the tooltip will hide on mouse leave, regardless of focus.
* @param {string=} md-direction The direction that the tooltip is shown,
* relative to the parent element. Supports top, right, bottom, and left.
* Defaults to bottom.
*/
function MdTooltipDirective($timeout, $window, $$rAF, $document, $interpolate,
$mdUtil, $mdPanel, $$mdTooltipRegistry) {
var ENTER_EVENTS = 'focus touchstart mouseenter';
var LEAVE_EVENTS = 'blur touchcancel mouseleave';
var TOOLTIP_DEFAULT_Z_INDEX = 100;
var TOOLTIP_DEFAULT_SHOW_DELAY = 0;
var TOOLTIP_DEFAULT_DIRECTION = 'bottom';
var TOOLTIP_DIRECTIONS = {
top: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.ABOVE },
right: { x: $mdPanel.xPosition.OFFSET_END, y: $mdPanel.yPosition.CENTER },
bottom: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.BELOW },
left: { x: $mdPanel.xPosition.OFFSET_START, y: $mdPanel.yPosition.CENTER }
};
return {
restrict: 'E',
priority: 210, // Before ngAria
scope: {
mdZIndex: '=?mdZIndex',
mdDelay: '=?mdDelay',
mdVisible: '=?mdVisible',
mdAutohide: '=?mdAutohide',
mdDirection: '@?mdDirection' // Do not expect expressions.
},
link: linkFunc
};
function linkFunc(scope, element, attr) {
// Set constants.
var tooltipId = 'md-tooltip-' + $mdUtil.nextUid();
var parent = $mdUtil.getParentWithPointerEvents(element);
var debouncedOnResize = $$rAF.throttle(updatePosition);
var mouseActive = false;
var origin, position, panelPosition, panelRef, autohide, showTimeout,
elementFocusedOnWindowBlur = null;
// Set defaults
setDefaults();
// Set parent aria-label.
addAriaLabel();
// Remove the element from its current DOM position.
element.detach();
updatePosition();
bindEvents();
configureWatchers();
function setDefaults() {
scope.mdZIndex = scope.mdZIndex || TOOLTIP_DEFAULT_Z_INDEX;
scope.mdDelay = scope.mdDelay || TOOLTIP_DEFAULT_SHOW_DELAY;
if (!TOOLTIP_DIRECTIONS[scope.mdDirection]) {
scope.mdDirection = TOOLTIP_DEFAULT_DIRECTION;
}
}
function addAriaLabel(labelText) {
// Only interpolate the text from the HTML element because otherwise the custom text could
// be interpolated twice and cause XSS violations.
var interpolatedText = labelText || $interpolate(element.text().trim())(scope.$parent);
// Only add the `aria-label` to the parent if there isn't already one, if there isn't an
// already present `aria-labelledby`, or if the previous `aria-label` was added by the
// tooltip directive.
if (
(!parent.attr('aria-label') && !parent.attr('aria-labelledby')) ||
parent.attr('md-labeled-by-tooltip')
) {
parent.attr('aria-label', interpolatedText);
// Set the `md-labeled-by-tooltip` attribute if it has not already been set.
if (!parent.attr('md-labeled-by-tooltip')) {
parent.attr('md-labeled-by-tooltip', tooltipId);
}
}
}
function updatePosition() {
setDefaults();
// If the panel has already been created, remove the current origin
// class from the panel element.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.removeClass(origin);
}
// Set the panel element origin class based off of the current
// mdDirection.
origin = 'md-origin-' + scope.mdDirection;
// Create the position of the panel based off of the mdDirection.
position = TOOLTIP_DIRECTIONS[scope.mdDirection];
// Using the newly created position object, use the MdPanel
// panelPosition API to build the panel's position.
panelPosition = $mdPanel.newPanelPosition()
.relativeTo(parent)
.addPanelPosition(position.x, position.y);
// If the panel has already been created, add the new origin class to
// the panel element and update it's position with the panelPosition.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.addClass(origin);
panelRef.updatePosition(panelPosition);
}
}
function bindEvents() {
// Add a mutationObserver where there is support for it and the need
// for it in the form of viable host(parent[0]).
if (parent[0] && 'MutationObserver' in $window) {
// Use a mutationObserver to tackle #2602.
var attributeObserver = new MutationObserver(function(mutations) {
if (isDisabledMutation(mutations)) {
$mdUtil.nextTick(function() {
setVisible(false);
});
}
});
attributeObserver.observe(parent[0], {
attributes: true
});
}
elementFocusedOnWindowBlur = false;
$$mdTooltipRegistry.register('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.register('blur', windowBlurEventHandler);
$$mdTooltipRegistry.register('resize', debouncedOnResize);
scope.$on('$destroy', onDestroy);
// To avoid 'synthetic clicks', we listen to mousedown instead of
// 'click'.
parent.on('mousedown', mousedownEventHandler);
parent.on(ENTER_EVENTS, enterEventHandler);
function isDisabledMutation(mutations) {
mutations.some(function(mutation) {
return mutation.attributeName === 'disabled' && parent[0].disabled;
});
return false;
}
function windowScrollEventHandler() {
setVisible(false);
}
function windowBlurEventHandler() {
elementFocusedOnWindowBlur = document.activeElement === parent[0];
}
function enterEventHandler($event) {
// Prevent the tooltip from showing when the window is receiving
// focus.
if ($event.type === 'focus' && elementFocusedOnWindowBlur) {
elementFocusedOnWindowBlur = false;
} else if (!scope.mdVisible) {
parent.on(LEAVE_EVENTS, leaveEventHandler);
setVisible(true);
// If the user is on a touch device, we should bind the tap away
// after the 'touched' in order to prevent the tooltip being
// removed immediately.
if ($event.type === 'touchstart') {
parent.one('touchend', function() {
$mdUtil.nextTick(function() {
$document.one('touchend', leaveEventHandler);
}, false);
});
}
}
}
function leaveEventHandler() {
autohide = scope.hasOwnProperty('mdAutohide') ?
scope.mdAutohide :
attr.hasOwnProperty('mdAutohide');
if (autohide || mouseActive ||
$document[0].activeElement !== parent[0]) {
// When a show timeout is currently in progress, then we have
// to cancel it, otherwise the tooltip will remain showing
// without focus or hover.
if (showTimeout) {
$timeout.cancel(showTimeout);
setVisible.queued = false;
showTimeout = null;
}
parent.off(LEAVE_EVENTS, leaveEventHandler);
parent.triggerHandler('blur');
setVisible(false);
}
mouseActive = false;
}
function mousedownEventHandler() {
mouseActive = true;
}
function onDestroy() {
$$mdTooltipRegistry.deregister('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.deregister('blur', windowBlurEventHandler);
$$mdTooltipRegistry.deregister('resize', debouncedOnResize);
parent
.off(ENTER_EVENTS, enterEventHandler)
.off(LEAVE_EVENTS, leaveEventHandler)
.off('mousedown', mousedownEventHandler);
// Trigger the handler in case any of the tooltips are
// still visible.
leaveEventHandler();
attributeObserver && attributeObserver.disconnect();
}
}
function configureWatchers() {
if (element[0] && 'MutationObserver' in $window) {
var attributeObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === 'md-visible' &&
!scope.visibleWatcher ) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
});
});
attributeObserver.observe(element[0], {
attributes: true
});
// Build watcher only if mdVisible is being used.
if (attr.hasOwnProperty('mdVisible')) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
} else {
// MutationObserver not supported
scope.visibleWatcher = scope.$watch('mdVisible', onVisibleChanged);
}
// Direction watcher
scope.$watch('mdDirection', updatePosition);
// Clean up if the element or parent was removed via jqLite's .remove.
// A couple of notes:
// - In these cases the scope might not have been destroyed, which
// is why we destroy it manually. An example of this can be having
// `md-visible="false"` and adding tooltips while they're
// invisible. If `md-visible` becomes true, at some point, you'd
// usually get a lot of tooltips.
// - We use `.one`, not `.on`, because this only needs to fire once.
// If we were using `.on`, it would get thrown into an infinite
// loop.
// - This kicks off the scope's `$destroy` event which finishes the
// cleanup.
element.one('$destroy', onElementDestroy);
parent.one('$destroy', onElementDestroy);
scope.$on('$destroy', function() {
setVisible(false);
panelRef && panelRef.destroy();
attributeObserver && attributeObserver.disconnect();
element.remove();
});
// Updates the aria-label when the element text changes. This watch
// doesn't need to be set up if the element doesn't have any data
// bindings.
if (element.text().indexOf($interpolate.startSymbol()) > -1) {
scope.$watch(function() {
return element.text().trim();
}, addAriaLabel);
}
function onElementDestroy() {
scope.$destroy();
}
}
function setVisible(value) {
// Break if passed value is already in queue or there is no queue and
// passed value is current in the controller.
if (setVisible.queued && setVisible.value === !!value ||
!setVisible.queued && scope.mdVisible === !!value) {
return;
}
setVisible.value = !!value;
if (!setVisible.queued) {
if (value) {
setVisible.queued = true;
showTimeout = $timeout(function() {
scope.mdVisible = setVisible.value;
setVisible.queued = false;
showTimeout = null;
if (!scope.visibleWatcher) {
onVisibleChanged(scope.mdVisible);
}
}, scope.mdDelay);
} else {
$mdUtil.nextTick(function() {
scope.mdVisible = false; | }
});
}
}
}
function onVisibleChanged(isVisible) {
isVisible ? showTooltip() : hideTooltip();
}
function showTooltip() {
// Do not show the tooltip if the text is empty.
if (!element[0].textContent.trim()) {
throw new Error('Text for the tooltip has not been provided. ' +
'Please include text within the mdTooltip element.');
}
if (!panelRef) {
var attachTo = angular.element(document.body);
var panelAnimation = $mdPanel.newPanelAnimation()
.openFrom(parent)
.closeTo(parent)
.withAnimation({
open: 'md-show',
close: 'md-hide'
});
var panelConfig = {
id: tooltipId,
attachTo: attachTo,
contentElement: element,
propagateContainerEvents: true,
panelClass: 'md-tooltip ' + origin,
animation: panelAnimation,
position: panelPosition,
zIndex: scope.mdZIndex,
focusOnOpen: false
};
panelRef = $mdPanel.create(panelConfig);
}
panelRef.open().then(function() {
panelRef.panelEl.attr('role', 'tooltip');
});
}
function hideTooltip() {
panelRef && panelRef.close();
}
}
}
/**
* Service that is used to reduce the amount of listeners that are being
* registered on the `window` by the tooltip component. Works by collecting
* the individual event handlers and dispatching them from a global handler.
*
* ngInject
*/
function MdTooltipRegistry() {
var listeners = {};
var ngWindow = angular.element(window);
return {
register: register,
deregister: deregister
};
/**
* Global event handler that dispatches the registered handlers in the
* service.
* @param {!Event} event Event object passed in by the browser
*/
function globalEventHandler(event) {
if (listeners[event.type]) {
listeners[event.type].forEach(function(currentHandler) {
currentHandler.call(this, event);
}, this);
}
}
/**
* Registers a new handler with the service.
* @param {string} type Type of event to be registered.
* @param {!Function} handler Event handler.
* @param {boolean} useCapture Whether to use event capturing.
*/
function register(type, handler, useCapture) {
var handlers = listeners[type] = listeners[type] || [];
if (!handlers.length) {
useCapture ? window.addEventListener(type, globalEventHandler, true) :
ngWindow.on(type, globalEventHandler);
}
if (handlers.indexOf(handler) === -1) {
handlers.push(handler);
}
}
/**
* Removes an event handler from the service.
* @param {string} type Type of event handler.
* @param {!Function} handler The event handler itself.
* @param {boolean} useCapture Whether the event handler used event capturing.
*/
function deregister(type, handler, useCapture) {
var handlers = listeners[type];
var index = handlers ? handlers.indexOf(handler) : -1;
if (index > -1) {
handlers.splice(index, 1);
if (handlers.length === 0) {
useCapture ? window.removeEventListener(type, globalEventHandler, true) :
ngWindow.off(type, globalEventHandler);
}
}
}
}
ngmaterial.components.tooltip = angular.module("material.components.tooltip"); | if (!scope.visibleWatcher) {
onVisibleChanged(false); | random_line_split |
tooltip.js | /*!
* AngularJS Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.5
*/
goog.provide('ngmaterial.components.tooltip');
goog.require('ngmaterial.components.panel');
goog.require('ngmaterial.core');
/**
* @ngdoc module
* @name material.components.tooltip
*/
MdTooltipDirective['$inject'] = ["$timeout", "$window", "$$rAF", "$document", "$interpolate", "$mdUtil", "$mdPanel", "$$mdTooltipRegistry"];
angular
.module('material.components.tooltip', [
'material.core',
'material.components.panel'
])
.directive('mdTooltip', MdTooltipDirective)
.service('$$mdTooltipRegistry', MdTooltipRegistry);
/**
* @ngdoc directive
* @name mdTooltip
* @module material.components.tooltip
* @description
* Tooltips are used to describe elements that are interactive and primarily
* graphical (not textual).
*
* Place a `<md-tooltip>` as a child of the element it describes.
*
* A tooltip will activate when the user hovers over, focuses, or touches the
* parent element.
*
* @usage
* <hljs lang="html">
* <md-button class="md-fab md-accent" aria-label="Play">
* <md-tooltip>Play Music</md-tooltip>
* <md-icon md-svg-src="img/icons/ic_play_arrow_24px.svg"></md-icon>
* </md-button>
* </hljs>
*
* @param {number=} md-z-index The visual level that the tooltip will appear
* in comparison with the rest of the elements of the application.
* @param {expression=} md-visible Boolean bound to whether the tooltip is
* currently visible.
* @param {number=} md-delay How many milliseconds to wait to show the tooltip
* after the user hovers over, focuses, or touches the parent element.
* Defaults to 0ms on non-touch devices and 75ms on touch.
* @param {boolean=} md-autohide If present or provided with a boolean value,
* the tooltip will hide on mouse leave, regardless of focus.
* @param {string=} md-direction The direction that the tooltip is shown,
* relative to the parent element. Supports top, right, bottom, and left.
* Defaults to bottom.
*/
function MdTooltipDirective($timeout, $window, $$rAF, $document, $interpolate,
$mdUtil, $mdPanel, $$mdTooltipRegistry) {
var ENTER_EVENTS = 'focus touchstart mouseenter';
var LEAVE_EVENTS = 'blur touchcancel mouseleave';
var TOOLTIP_DEFAULT_Z_INDEX = 100;
var TOOLTIP_DEFAULT_SHOW_DELAY = 0;
var TOOLTIP_DEFAULT_DIRECTION = 'bottom';
var TOOLTIP_DIRECTIONS = {
top: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.ABOVE },
right: { x: $mdPanel.xPosition.OFFSET_END, y: $mdPanel.yPosition.CENTER },
bottom: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.BELOW },
left: { x: $mdPanel.xPosition.OFFSET_START, y: $mdPanel.yPosition.CENTER }
};
return {
restrict: 'E',
priority: 210, // Before ngAria
scope: {
mdZIndex: '=?mdZIndex',
mdDelay: '=?mdDelay',
mdVisible: '=?mdVisible',
mdAutohide: '=?mdAutohide',
mdDirection: '@?mdDirection' // Do not expect expressions.
},
link: linkFunc
};
function linkFunc(scope, element, attr) {
// Set constants.
var tooltipId = 'md-tooltip-' + $mdUtil.nextUid();
var parent = $mdUtil.getParentWithPointerEvents(element);
var debouncedOnResize = $$rAF.throttle(updatePosition);
var mouseActive = false;
var origin, position, panelPosition, panelRef, autohide, showTimeout,
elementFocusedOnWindowBlur = null;
// Set defaults
setDefaults();
// Set parent aria-label.
addAriaLabel();
// Remove the element from its current DOM position.
element.detach();
updatePosition();
bindEvents();
configureWatchers();
function setDefaults() {
scope.mdZIndex = scope.mdZIndex || TOOLTIP_DEFAULT_Z_INDEX;
scope.mdDelay = scope.mdDelay || TOOLTIP_DEFAULT_SHOW_DELAY;
if (!TOOLTIP_DIRECTIONS[scope.mdDirection]) {
scope.mdDirection = TOOLTIP_DEFAULT_DIRECTION;
}
}
function addAriaLabel(labelText) {
// Only interpolate the text from the HTML element because otherwise the custom text could
// be interpolated twice and cause XSS violations.
var interpolatedText = labelText || $interpolate(element.text().trim())(scope.$parent);
// Only add the `aria-label` to the parent if there isn't already one, if there isn't an
// already present `aria-labelledby`, or if the previous `aria-label` was added by the
// tooltip directive.
if (
(!parent.attr('aria-label') && !parent.attr('aria-labelledby')) ||
parent.attr('md-labeled-by-tooltip')
) {
parent.attr('aria-label', interpolatedText);
// Set the `md-labeled-by-tooltip` attribute if it has not already been set.
if (!parent.attr('md-labeled-by-tooltip')) {
parent.attr('md-labeled-by-tooltip', tooltipId);
}
}
}
function updatePosition() {
setDefaults();
// If the panel has already been created, remove the current origin
// class from the panel element.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.removeClass(origin);
}
// Set the panel element origin class based off of the current
// mdDirection.
origin = 'md-origin-' + scope.mdDirection;
// Create the position of the panel based off of the mdDirection.
position = TOOLTIP_DIRECTIONS[scope.mdDirection];
// Using the newly created position object, use the MdPanel
// panelPosition API to build the panel's position.
panelPosition = $mdPanel.newPanelPosition()
.relativeTo(parent)
.addPanelPosition(position.x, position.y);
// If the panel has already been created, add the new origin class to
// the panel element and update it's position with the panelPosition.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.addClass(origin);
panelRef.updatePosition(panelPosition);
}
}
function bindEvents() {
// Add a mutationObserver where there is support for it and the need
// for it in the form of viable host(parent[0]).
if (parent[0] && 'MutationObserver' in $window) {
// Use a mutationObserver to tackle #2602.
var attributeObserver = new MutationObserver(function(mutations) {
if (isDisabledMutation(mutations)) {
$mdUtil.nextTick(function() {
setVisible(false);
});
}
});
attributeObserver.observe(parent[0], {
attributes: true
});
}
elementFocusedOnWindowBlur = false;
$$mdTooltipRegistry.register('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.register('blur', windowBlurEventHandler);
$$mdTooltipRegistry.register('resize', debouncedOnResize);
scope.$on('$destroy', onDestroy);
// To avoid 'synthetic clicks', we listen to mousedown instead of
// 'click'.
parent.on('mousedown', mousedownEventHandler);
parent.on(ENTER_EVENTS, enterEventHandler);
function isDisabledMutation(mutations) {
mutations.some(function(mutation) {
return mutation.attributeName === 'disabled' && parent[0].disabled;
});
return false;
}
function windowScrollEventHandler() {
setVisible(false);
}
function windowBlurEventHandler() {
elementFocusedOnWindowBlur = document.activeElement === parent[0];
}
function enterEventHandler($event) {
// Prevent the tooltip from showing when the window is receiving
// focus.
if ($event.type === 'focus' && elementFocusedOnWindowBlur) {
elementFocusedOnWindowBlur = false;
} else if (!scope.mdVisible) {
parent.on(LEAVE_EVENTS, leaveEventHandler);
setVisible(true);
// If the user is on a touch device, we should bind the tap away
// after the 'touched' in order to prevent the tooltip being
// removed immediately.
if ($event.type === 'touchstart') {
parent.one('touchend', function() {
$mdUtil.nextTick(function() {
$document.one('touchend', leaveEventHandler);
}, false);
});
}
}
}
function leaveEventHandler() {
autohide = scope.hasOwnProperty('mdAutohide') ?
scope.mdAutohide :
attr.hasOwnProperty('mdAutohide');
if (autohide || mouseActive ||
$document[0].activeElement !== parent[0]) {
// When a show timeout is currently in progress, then we have
// to cancel it, otherwise the tooltip will remain showing
// without focus or hover.
if (showTimeout) {
$timeout.cancel(showTimeout);
setVisible.queued = false;
showTimeout = null;
}
parent.off(LEAVE_EVENTS, leaveEventHandler);
parent.triggerHandler('blur');
setVisible(false);
}
mouseActive = false;
}
function mousedownEventHandler() {
mouseActive = true;
}
function onDestroy() {
$$mdTooltipRegistry.deregister('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.deregister('blur', windowBlurEventHandler);
$$mdTooltipRegistry.deregister('resize', debouncedOnResize);
parent
.off(ENTER_EVENTS, enterEventHandler)
.off(LEAVE_EVENTS, leaveEventHandler)
.off('mousedown', mousedownEventHandler);
// Trigger the handler in case any of the tooltips are
// still visible.
leaveEventHandler();
attributeObserver && attributeObserver.disconnect();
}
}
function configureWatchers() {
if (element[0] && 'MutationObserver' in $window) {
var attributeObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === 'md-visible' &&
!scope.visibleWatcher ) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
});
});
attributeObserver.observe(element[0], {
attributes: true
});
// Build watcher only if mdVisible is being used.
if (attr.hasOwnProperty('mdVisible')) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
} else {
// MutationObserver not supported
scope.visibleWatcher = scope.$watch('mdVisible', onVisibleChanged);
}
// Direction watcher
scope.$watch('mdDirection', updatePosition);
// Clean up if the element or parent was removed via jqLite's .remove.
// A couple of notes:
// - In these cases the scope might not have been destroyed, which
// is why we destroy it manually. An example of this can be having
// `md-visible="false"` and adding tooltips while they're
// invisible. If `md-visible` becomes true, at some point, you'd
// usually get a lot of tooltips.
// - We use `.one`, not `.on`, because this only needs to fire once.
// If we were using `.on`, it would get thrown into an infinite
// loop.
// - This kicks off the scope's `$destroy` event which finishes the
// cleanup.
element.one('$destroy', onElementDestroy);
parent.one('$destroy', onElementDestroy);
scope.$on('$destroy', function() {
setVisible(false);
panelRef && panelRef.destroy();
attributeObserver && attributeObserver.disconnect();
element.remove();
});
// Updates the aria-label when the element text changes. This watch
// doesn't need to be set up if the element doesn't have any data
// bindings.
if (element.text().indexOf($interpolate.startSymbol()) > -1) {
scope.$watch(function() {
return element.text().trim();
}, addAriaLabel);
}
function onElementDestroy() {
scope.$destroy();
}
}
function setVisible(value) {
// Break if passed value is already in queue or there is no queue and
// passed value is current in the controller.
if (setVisible.queued && setVisible.value === !!value ||
!setVisible.queued && scope.mdVisible === !!value) {
return;
}
setVisible.value = !!value;
if (!setVisible.queued) {
if (value) {
setVisible.queued = true;
showTimeout = $timeout(function() {
scope.mdVisible = setVisible.value;
setVisible.queued = false;
showTimeout = null;
if (!scope.visibleWatcher) {
onVisibleChanged(scope.mdVisible);
}
}, scope.mdDelay);
} else {
$mdUtil.nextTick(function() {
scope.mdVisible = false;
if (!scope.visibleWatcher) {
onVisibleChanged(false);
}
});
}
}
}
function onVisibleChanged(isVisible) {
isVisible ? showTooltip() : hideTooltip();
}
function showTooltip() {
// Do not show the tooltip if the text is empty.
if (!element[0].textContent.trim()) {
throw new Error('Text for the tooltip has not been provided. ' +
'Please include text within the mdTooltip element.');
}
if (!panelRef) |
panelRef.open().then(function() {
panelRef.panelEl.attr('role', 'tooltip');
});
}
function hideTooltip() {
panelRef && panelRef.close();
}
}
}
/**
* Service that is used to reduce the amount of listeners that are being
* registered on the `window` by the tooltip component. Works by collecting
* the individual event handlers and dispatching them from a global handler.
*
* ngInject
*/
function MdTooltipRegistry() {
var listeners = {};
var ngWindow = angular.element(window);
return {
register: register,
deregister: deregister
};
/**
* Global event handler that dispatches the registered handlers in the
* service.
* @param {!Event} event Event object passed in by the browser
*/
function globalEventHandler(event) {
if (listeners[event.type]) {
listeners[event.type].forEach(function(currentHandler) {
currentHandler.call(this, event);
}, this);
}
}
/**
* Registers a new handler with the service.
* @param {string} type Type of event to be registered.
* @param {!Function} handler Event handler.
* @param {boolean} useCapture Whether to use event capturing.
*/
function register(type, handler, useCapture) {
var handlers = listeners[type] = listeners[type] || [];
if (!handlers.length) {
useCapture ? window.addEventListener(type, globalEventHandler, true) :
ngWindow.on(type, globalEventHandler);
}
if (handlers.indexOf(handler) === -1) {
handlers.push(handler);
}
}
/**
* Removes an event handler from the service.
* @param {string} type Type of event handler.
* @param {!Function} handler The event handler itself.
* @param {boolean} useCapture Whether the event handler used event capturing.
*/
function deregister(type, handler, useCapture) {
var handlers = listeners[type];
var index = handlers ? handlers.indexOf(handler) : -1;
if (index > -1) {
handlers.splice(index, 1);
if (handlers.length === 0) {
useCapture ? window.removeEventListener(type, globalEventHandler, true) :
ngWindow.off(type, globalEventHandler);
}
}
}
}
ngmaterial.components.tooltip = angular.module("material.components.tooltip"); | {
var attachTo = angular.element(document.body);
var panelAnimation = $mdPanel.newPanelAnimation()
.openFrom(parent)
.closeTo(parent)
.withAnimation({
open: 'md-show',
close: 'md-hide'
});
var panelConfig = {
id: tooltipId,
attachTo: attachTo,
contentElement: element,
propagateContainerEvents: true,
panelClass: 'md-tooltip ' + origin,
animation: panelAnimation,
position: panelPosition,
zIndex: scope.mdZIndex,
focusOnOpen: false
};
panelRef = $mdPanel.create(panelConfig);
} | conditional_block |
tooltip.js | /*!
* AngularJS Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.5
*/
goog.provide('ngmaterial.components.tooltip');
goog.require('ngmaterial.components.panel');
goog.require('ngmaterial.core');
/**
* @ngdoc module
* @name material.components.tooltip
*/
MdTooltipDirective['$inject'] = ["$timeout", "$window", "$$rAF", "$document", "$interpolate", "$mdUtil", "$mdPanel", "$$mdTooltipRegistry"];
angular
.module('material.components.tooltip', [
'material.core',
'material.components.panel'
])
.directive('mdTooltip', MdTooltipDirective)
.service('$$mdTooltipRegistry', MdTooltipRegistry);
/**
* @ngdoc directive
* @name mdTooltip
* @module material.components.tooltip
* @description
* Tooltips are used to describe elements that are interactive and primarily
* graphical (not textual).
*
* Place a `<md-tooltip>` as a child of the element it describes.
*
* A tooltip will activate when the user hovers over, focuses, or touches the
* parent element.
*
* @usage
* <hljs lang="html">
* <md-button class="md-fab md-accent" aria-label="Play">
* <md-tooltip>Play Music</md-tooltip>
* <md-icon md-svg-src="img/icons/ic_play_arrow_24px.svg"></md-icon>
* </md-button>
* </hljs>
*
* @param {number=} md-z-index The visual level that the tooltip will appear
* in comparison with the rest of the elements of the application.
* @param {expression=} md-visible Boolean bound to whether the tooltip is
* currently visible.
* @param {number=} md-delay How many milliseconds to wait to show the tooltip
* after the user hovers over, focuses, or touches the parent element.
* Defaults to 0ms on non-touch devices and 75ms on touch.
* @param {boolean=} md-autohide If present or provided with a boolean value,
* the tooltip will hide on mouse leave, regardless of focus.
* @param {string=} md-direction The direction that the tooltip is shown,
* relative to the parent element. Supports top, right, bottom, and left.
* Defaults to bottom.
*/
function MdTooltipDirective($timeout, $window, $$rAF, $document, $interpolate,
$mdUtil, $mdPanel, $$mdTooltipRegistry) {
var ENTER_EVENTS = 'focus touchstart mouseenter';
var LEAVE_EVENTS = 'blur touchcancel mouseleave';
var TOOLTIP_DEFAULT_Z_INDEX = 100;
var TOOLTIP_DEFAULT_SHOW_DELAY = 0;
var TOOLTIP_DEFAULT_DIRECTION = 'bottom';
var TOOLTIP_DIRECTIONS = {
top: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.ABOVE },
right: { x: $mdPanel.xPosition.OFFSET_END, y: $mdPanel.yPosition.CENTER },
bottom: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.BELOW },
left: { x: $mdPanel.xPosition.OFFSET_START, y: $mdPanel.yPosition.CENTER }
};
return {
restrict: 'E',
priority: 210, // Before ngAria
scope: {
mdZIndex: '=?mdZIndex',
mdDelay: '=?mdDelay',
mdVisible: '=?mdVisible',
mdAutohide: '=?mdAutohide',
mdDirection: '@?mdDirection' // Do not expect expressions.
},
link: linkFunc
};
function linkFunc(scope, element, attr) {
// Set constants.
var tooltipId = 'md-tooltip-' + $mdUtil.nextUid();
var parent = $mdUtil.getParentWithPointerEvents(element);
var debouncedOnResize = $$rAF.throttle(updatePosition);
var mouseActive = false;
var origin, position, panelPosition, panelRef, autohide, showTimeout,
elementFocusedOnWindowBlur = null;
// Set defaults
setDefaults();
// Set parent aria-label.
addAriaLabel();
// Remove the element from its current DOM position.
element.detach();
updatePosition();
bindEvents();
configureWatchers();
function setDefaults() {
scope.mdZIndex = scope.mdZIndex || TOOLTIP_DEFAULT_Z_INDEX;
scope.mdDelay = scope.mdDelay || TOOLTIP_DEFAULT_SHOW_DELAY;
if (!TOOLTIP_DIRECTIONS[scope.mdDirection]) {
scope.mdDirection = TOOLTIP_DEFAULT_DIRECTION;
}
}
function addAriaLabel(labelText) {
// Only interpolate the text from the HTML element because otherwise the custom text could
// be interpolated twice and cause XSS violations.
var interpolatedText = labelText || $interpolate(element.text().trim())(scope.$parent);
// Only add the `aria-label` to the parent if there isn't already one, if there isn't an
// already present `aria-labelledby`, or if the previous `aria-label` was added by the
// tooltip directive.
if (
(!parent.attr('aria-label') && !parent.attr('aria-labelledby')) ||
parent.attr('md-labeled-by-tooltip')
) {
parent.attr('aria-label', interpolatedText);
// Set the `md-labeled-by-tooltip` attribute if it has not already been set.
if (!parent.attr('md-labeled-by-tooltip')) {
parent.attr('md-labeled-by-tooltip', tooltipId);
}
}
}
function updatePosition() {
setDefaults();
// If the panel has already been created, remove the current origin
// class from the panel element.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.removeClass(origin);
}
// Set the panel element origin class based off of the current
// mdDirection.
origin = 'md-origin-' + scope.mdDirection;
// Create the position of the panel based off of the mdDirection.
position = TOOLTIP_DIRECTIONS[scope.mdDirection];
// Using the newly created position object, use the MdPanel
// panelPosition API to build the panel's position.
panelPosition = $mdPanel.newPanelPosition()
.relativeTo(parent)
.addPanelPosition(position.x, position.y);
// If the panel has already been created, add the new origin class to
// the panel element and update it's position with the panelPosition.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.addClass(origin);
panelRef.updatePosition(panelPosition);
}
}
function bindEvents() {
// Add a mutationObserver where there is support for it and the need
// for it in the form of viable host(parent[0]).
if (parent[0] && 'MutationObserver' in $window) {
// Use a mutationObserver to tackle #2602.
var attributeObserver = new MutationObserver(function(mutations) {
if (isDisabledMutation(mutations)) {
$mdUtil.nextTick(function() {
setVisible(false);
});
}
});
attributeObserver.observe(parent[0], {
attributes: true
});
}
elementFocusedOnWindowBlur = false;
$$mdTooltipRegistry.register('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.register('blur', windowBlurEventHandler);
$$mdTooltipRegistry.register('resize', debouncedOnResize);
scope.$on('$destroy', onDestroy);
// To avoid 'synthetic clicks', we listen to mousedown instead of
// 'click'.
parent.on('mousedown', mousedownEventHandler);
parent.on(ENTER_EVENTS, enterEventHandler);
function isDisabledMutation(mutations) {
mutations.some(function(mutation) {
return mutation.attributeName === 'disabled' && parent[0].disabled;
});
return false;
}
function windowScrollEventHandler() {
setVisible(false);
}
function windowBlurEventHandler() {
elementFocusedOnWindowBlur = document.activeElement === parent[0];
}
function enterEventHandler($event) {
// Prevent the tooltip from showing when the window is receiving
// focus.
if ($event.type === 'focus' && elementFocusedOnWindowBlur) {
elementFocusedOnWindowBlur = false;
} else if (!scope.mdVisible) {
parent.on(LEAVE_EVENTS, leaveEventHandler);
setVisible(true);
// If the user is on a touch device, we should bind the tap away
// after the 'touched' in order to prevent the tooltip being
// removed immediately.
if ($event.type === 'touchstart') {
parent.one('touchend', function() {
$mdUtil.nextTick(function() {
$document.one('touchend', leaveEventHandler);
}, false);
});
}
}
}
function leaveEventHandler() {
autohide = scope.hasOwnProperty('mdAutohide') ?
scope.mdAutohide :
attr.hasOwnProperty('mdAutohide');
if (autohide || mouseActive ||
$document[0].activeElement !== parent[0]) {
// When a show timeout is currently in progress, then we have
// to cancel it, otherwise the tooltip will remain showing
// without focus or hover.
if (showTimeout) {
$timeout.cancel(showTimeout);
setVisible.queued = false;
showTimeout = null;
}
parent.off(LEAVE_EVENTS, leaveEventHandler);
parent.triggerHandler('blur');
setVisible(false);
}
mouseActive = false;
}
function mousedownEventHandler() {
mouseActive = true;
}
function onDestroy() {
$$mdTooltipRegistry.deregister('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.deregister('blur', windowBlurEventHandler);
$$mdTooltipRegistry.deregister('resize', debouncedOnResize);
parent
.off(ENTER_EVENTS, enterEventHandler)
.off(LEAVE_EVENTS, leaveEventHandler)
.off('mousedown', mousedownEventHandler);
// Trigger the handler in case any of the tooltips are
// still visible.
leaveEventHandler();
attributeObserver && attributeObserver.disconnect();
}
}
function | () {
if (element[0] && 'MutationObserver' in $window) {
var attributeObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === 'md-visible' &&
!scope.visibleWatcher ) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
});
});
attributeObserver.observe(element[0], {
attributes: true
});
// Build watcher only if mdVisible is being used.
if (attr.hasOwnProperty('mdVisible')) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
} else {
// MutationObserver not supported
scope.visibleWatcher = scope.$watch('mdVisible', onVisibleChanged);
}
// Direction watcher
scope.$watch('mdDirection', updatePosition);
// Clean up if the element or parent was removed via jqLite's .remove.
// A couple of notes:
// - In these cases the scope might not have been destroyed, which
// is why we destroy it manually. An example of this can be having
// `md-visible="false"` and adding tooltips while they're
// invisible. If `md-visible` becomes true, at some point, you'd
// usually get a lot of tooltips.
// - We use `.one`, not `.on`, because this only needs to fire once.
// If we were using `.on`, it would get thrown into an infinite
// loop.
// - This kicks off the scope's `$destroy` event which finishes the
// cleanup.
element.one('$destroy', onElementDestroy);
parent.one('$destroy', onElementDestroy);
scope.$on('$destroy', function() {
setVisible(false);
panelRef && panelRef.destroy();
attributeObserver && attributeObserver.disconnect();
element.remove();
});
// Updates the aria-label when the element text changes. This watch
// doesn't need to be set up if the element doesn't have any data
// bindings.
if (element.text().indexOf($interpolate.startSymbol()) > -1) {
scope.$watch(function() {
return element.text().trim();
}, addAriaLabel);
}
function onElementDestroy() {
scope.$destroy();
}
}
function setVisible(value) {
// Break if passed value is already in queue or there is no queue and
// passed value is current in the controller.
if (setVisible.queued && setVisible.value === !!value ||
!setVisible.queued && scope.mdVisible === !!value) {
return;
}
setVisible.value = !!value;
if (!setVisible.queued) {
if (value) {
setVisible.queued = true;
showTimeout = $timeout(function() {
scope.mdVisible = setVisible.value;
setVisible.queued = false;
showTimeout = null;
if (!scope.visibleWatcher) {
onVisibleChanged(scope.mdVisible);
}
}, scope.mdDelay);
} else {
$mdUtil.nextTick(function() {
scope.mdVisible = false;
if (!scope.visibleWatcher) {
onVisibleChanged(false);
}
});
}
}
}
function onVisibleChanged(isVisible) {
isVisible ? showTooltip() : hideTooltip();
}
function showTooltip() {
// Do not show the tooltip if the text is empty.
if (!element[0].textContent.trim()) {
throw new Error('Text for the tooltip has not been provided. ' +
'Please include text within the mdTooltip element.');
}
if (!panelRef) {
var attachTo = angular.element(document.body);
var panelAnimation = $mdPanel.newPanelAnimation()
.openFrom(parent)
.closeTo(parent)
.withAnimation({
open: 'md-show',
close: 'md-hide'
});
var panelConfig = {
id: tooltipId,
attachTo: attachTo,
contentElement: element,
propagateContainerEvents: true,
panelClass: 'md-tooltip ' + origin,
animation: panelAnimation,
position: panelPosition,
zIndex: scope.mdZIndex,
focusOnOpen: false
};
panelRef = $mdPanel.create(panelConfig);
}
panelRef.open().then(function() {
panelRef.panelEl.attr('role', 'tooltip');
});
}
function hideTooltip() {
panelRef && panelRef.close();
}
}
}
/**
* Service that is used to reduce the amount of listeners that are being
* registered on the `window` by the tooltip component. Works by collecting
* the individual event handlers and dispatching them from a global handler.
*
* ngInject
*/
function MdTooltipRegistry() {
var listeners = {};
var ngWindow = angular.element(window);
return {
register: register,
deregister: deregister
};
/**
* Global event handler that dispatches the registered handlers in the
* service.
* @param {!Event} event Event object passed in by the browser
*/
function globalEventHandler(event) {
if (listeners[event.type]) {
listeners[event.type].forEach(function(currentHandler) {
currentHandler.call(this, event);
}, this);
}
}
/**
* Registers a new handler with the service.
* @param {string} type Type of event to be registered.
* @param {!Function} handler Event handler.
* @param {boolean} useCapture Whether to use event capturing.
*/
function register(type, handler, useCapture) {
var handlers = listeners[type] = listeners[type] || [];
if (!handlers.length) {
useCapture ? window.addEventListener(type, globalEventHandler, true) :
ngWindow.on(type, globalEventHandler);
}
if (handlers.indexOf(handler) === -1) {
handlers.push(handler);
}
}
/**
* Removes an event handler from the service.
* @param {string} type Type of event handler.
* @param {!Function} handler The event handler itself.
* @param {boolean} useCapture Whether the event handler used event capturing.
*/
function deregister(type, handler, useCapture) {
var handlers = listeners[type];
var index = handlers ? handlers.indexOf(handler) : -1;
if (index > -1) {
handlers.splice(index, 1);
if (handlers.length === 0) {
useCapture ? window.removeEventListener(type, globalEventHandler, true) :
ngWindow.off(type, globalEventHandler);
}
}
}
}
ngmaterial.components.tooltip = angular.module("material.components.tooltip"); | configureWatchers | identifier_name |
tooltip.js | /*!
* AngularJS Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.5
*/
goog.provide('ngmaterial.components.tooltip');
goog.require('ngmaterial.components.panel');
goog.require('ngmaterial.core');
/**
* @ngdoc module
* @name material.components.tooltip
*/
MdTooltipDirective['$inject'] = ["$timeout", "$window", "$$rAF", "$document", "$interpolate", "$mdUtil", "$mdPanel", "$$mdTooltipRegistry"];
angular
.module('material.components.tooltip', [
'material.core',
'material.components.panel'
])
.directive('mdTooltip', MdTooltipDirective)
.service('$$mdTooltipRegistry', MdTooltipRegistry);
/**
* @ngdoc directive
* @name mdTooltip
* @module material.components.tooltip
* @description
* Tooltips are used to describe elements that are interactive and primarily
* graphical (not textual).
*
* Place a `<md-tooltip>` as a child of the element it describes.
*
* A tooltip will activate when the user hovers over, focuses, or touches the
* parent element.
*
* @usage
* <hljs lang="html">
* <md-button class="md-fab md-accent" aria-label="Play">
* <md-tooltip>Play Music</md-tooltip>
* <md-icon md-svg-src="img/icons/ic_play_arrow_24px.svg"></md-icon>
* </md-button>
* </hljs>
*
* @param {number=} md-z-index The visual level that the tooltip will appear
* in comparison with the rest of the elements of the application.
* @param {expression=} md-visible Boolean bound to whether the tooltip is
* currently visible.
* @param {number=} md-delay How many milliseconds to wait to show the tooltip
* after the user hovers over, focuses, or touches the parent element.
* Defaults to 0ms on non-touch devices and 75ms on touch.
* @param {boolean=} md-autohide If present or provided with a boolean value,
* the tooltip will hide on mouse leave, regardless of focus.
* @param {string=} md-direction The direction that the tooltip is shown,
* relative to the parent element. Supports top, right, bottom, and left.
* Defaults to bottom.
*/
function MdTooltipDirective($timeout, $window, $$rAF, $document, $interpolate,
$mdUtil, $mdPanel, $$mdTooltipRegistry) {
var ENTER_EVENTS = 'focus touchstart mouseenter';
var LEAVE_EVENTS = 'blur touchcancel mouseleave';
var TOOLTIP_DEFAULT_Z_INDEX = 100;
var TOOLTIP_DEFAULT_SHOW_DELAY = 0;
var TOOLTIP_DEFAULT_DIRECTION = 'bottom';
var TOOLTIP_DIRECTIONS = {
top: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.ABOVE },
right: { x: $mdPanel.xPosition.OFFSET_END, y: $mdPanel.yPosition.CENTER },
bottom: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.BELOW },
left: { x: $mdPanel.xPosition.OFFSET_START, y: $mdPanel.yPosition.CENTER }
};
return {
restrict: 'E',
priority: 210, // Before ngAria
scope: {
mdZIndex: '=?mdZIndex',
mdDelay: '=?mdDelay',
mdVisible: '=?mdVisible',
mdAutohide: '=?mdAutohide',
mdDirection: '@?mdDirection' // Do not expect expressions.
},
link: linkFunc
};
function linkFunc(scope, element, attr) {
// Set constants.
var tooltipId = 'md-tooltip-' + $mdUtil.nextUid();
var parent = $mdUtil.getParentWithPointerEvents(element);
var debouncedOnResize = $$rAF.throttle(updatePosition);
var mouseActive = false;
var origin, position, panelPosition, panelRef, autohide, showTimeout,
elementFocusedOnWindowBlur = null;
// Set defaults
setDefaults();
// Set parent aria-label.
addAriaLabel();
// Remove the element from its current DOM position.
element.detach();
updatePosition();
bindEvents();
configureWatchers();
function setDefaults() {
scope.mdZIndex = scope.mdZIndex || TOOLTIP_DEFAULT_Z_INDEX;
scope.mdDelay = scope.mdDelay || TOOLTIP_DEFAULT_SHOW_DELAY;
if (!TOOLTIP_DIRECTIONS[scope.mdDirection]) {
scope.mdDirection = TOOLTIP_DEFAULT_DIRECTION;
}
}
function addAriaLabel(labelText) {
// Only interpolate the text from the HTML element because otherwise the custom text could
// be interpolated twice and cause XSS violations.
var interpolatedText = labelText || $interpolate(element.text().trim())(scope.$parent);
// Only add the `aria-label` to the parent if there isn't already one, if there isn't an
// already present `aria-labelledby`, or if the previous `aria-label` was added by the
// tooltip directive.
if (
(!parent.attr('aria-label') && !parent.attr('aria-labelledby')) ||
parent.attr('md-labeled-by-tooltip')
) {
parent.attr('aria-label', interpolatedText);
// Set the `md-labeled-by-tooltip` attribute if it has not already been set.
if (!parent.attr('md-labeled-by-tooltip')) {
parent.attr('md-labeled-by-tooltip', tooltipId);
}
}
}
function updatePosition() |
function bindEvents() {
// Add a mutationObserver where there is support for it and the need
// for it in the form of viable host(parent[0]).
if (parent[0] && 'MutationObserver' in $window) {
// Use a mutationObserver to tackle #2602.
var attributeObserver = new MutationObserver(function(mutations) {
if (isDisabledMutation(mutations)) {
$mdUtil.nextTick(function() {
setVisible(false);
});
}
});
attributeObserver.observe(parent[0], {
attributes: true
});
}
elementFocusedOnWindowBlur = false;
$$mdTooltipRegistry.register('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.register('blur', windowBlurEventHandler);
$$mdTooltipRegistry.register('resize', debouncedOnResize);
scope.$on('$destroy', onDestroy);
// To avoid 'synthetic clicks', we listen to mousedown instead of
// 'click'.
parent.on('mousedown', mousedownEventHandler);
parent.on(ENTER_EVENTS, enterEventHandler);
function isDisabledMutation(mutations) {
mutations.some(function(mutation) {
return mutation.attributeName === 'disabled' && parent[0].disabled;
});
return false;
}
function windowScrollEventHandler() {
setVisible(false);
}
function windowBlurEventHandler() {
elementFocusedOnWindowBlur = document.activeElement === parent[0];
}
function enterEventHandler($event) {
// Prevent the tooltip from showing when the window is receiving
// focus.
if ($event.type === 'focus' && elementFocusedOnWindowBlur) {
elementFocusedOnWindowBlur = false;
} else if (!scope.mdVisible) {
parent.on(LEAVE_EVENTS, leaveEventHandler);
setVisible(true);
// If the user is on a touch device, we should bind the tap away
// after the 'touched' in order to prevent the tooltip being
// removed immediately.
if ($event.type === 'touchstart') {
parent.one('touchend', function() {
$mdUtil.nextTick(function() {
$document.one('touchend', leaveEventHandler);
}, false);
});
}
}
}
function leaveEventHandler() {
autohide = scope.hasOwnProperty('mdAutohide') ?
scope.mdAutohide :
attr.hasOwnProperty('mdAutohide');
if (autohide || mouseActive ||
$document[0].activeElement !== parent[0]) {
// When a show timeout is currently in progress, then we have
// to cancel it, otherwise the tooltip will remain showing
// without focus or hover.
if (showTimeout) {
$timeout.cancel(showTimeout);
setVisible.queued = false;
showTimeout = null;
}
parent.off(LEAVE_EVENTS, leaveEventHandler);
parent.triggerHandler('blur');
setVisible(false);
}
mouseActive = false;
}
function mousedownEventHandler() {
mouseActive = true;
}
function onDestroy() {
$$mdTooltipRegistry.deregister('scroll', windowScrollEventHandler, true);
$$mdTooltipRegistry.deregister('blur', windowBlurEventHandler);
$$mdTooltipRegistry.deregister('resize', debouncedOnResize);
parent
.off(ENTER_EVENTS, enterEventHandler)
.off(LEAVE_EVENTS, leaveEventHandler)
.off('mousedown', mousedownEventHandler);
// Trigger the handler in case any of the tooltips are
// still visible.
leaveEventHandler();
attributeObserver && attributeObserver.disconnect();
}
}
function configureWatchers() {
if (element[0] && 'MutationObserver' in $window) {
var attributeObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === 'md-visible' &&
!scope.visibleWatcher ) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
});
});
attributeObserver.observe(element[0], {
attributes: true
});
// Build watcher only if mdVisible is being used.
if (attr.hasOwnProperty('mdVisible')) {
scope.visibleWatcher = scope.$watch('mdVisible',
onVisibleChanged);
}
} else {
// MutationObserver not supported
scope.visibleWatcher = scope.$watch('mdVisible', onVisibleChanged);
}
// Direction watcher
scope.$watch('mdDirection', updatePosition);
// Clean up if the element or parent was removed via jqLite's .remove.
// A couple of notes:
// - In these cases the scope might not have been destroyed, which
// is why we destroy it manually. An example of this can be having
// `md-visible="false"` and adding tooltips while they're
// invisible. If `md-visible` becomes true, at some point, you'd
// usually get a lot of tooltips.
// - We use `.one`, not `.on`, because this only needs to fire once.
// If we were using `.on`, it would get thrown into an infinite
// loop.
// - This kicks off the scope's `$destroy` event which finishes the
// cleanup.
element.one('$destroy', onElementDestroy);
parent.one('$destroy', onElementDestroy);
scope.$on('$destroy', function() {
setVisible(false);
panelRef && panelRef.destroy();
attributeObserver && attributeObserver.disconnect();
element.remove();
});
// Updates the aria-label when the element text changes. This watch
// doesn't need to be set up if the element doesn't have any data
// bindings.
if (element.text().indexOf($interpolate.startSymbol()) > -1) {
scope.$watch(function() {
return element.text().trim();
}, addAriaLabel);
}
function onElementDestroy() {
scope.$destroy();
}
}
function setVisible(value) {
// Break if passed value is already in queue or there is no queue and
// passed value is current in the controller.
if (setVisible.queued && setVisible.value === !!value ||
!setVisible.queued && scope.mdVisible === !!value) {
return;
}
setVisible.value = !!value;
if (!setVisible.queued) {
if (value) {
setVisible.queued = true;
showTimeout = $timeout(function() {
scope.mdVisible = setVisible.value;
setVisible.queued = false;
showTimeout = null;
if (!scope.visibleWatcher) {
onVisibleChanged(scope.mdVisible);
}
}, scope.mdDelay);
} else {
$mdUtil.nextTick(function() {
scope.mdVisible = false;
if (!scope.visibleWatcher) {
onVisibleChanged(false);
}
});
}
}
}
function onVisibleChanged(isVisible) {
isVisible ? showTooltip() : hideTooltip();
}
function showTooltip() {
// Do not show the tooltip if the text is empty.
if (!element[0].textContent.trim()) {
throw new Error('Text for the tooltip has not been provided. ' +
'Please include text within the mdTooltip element.');
}
if (!panelRef) {
var attachTo = angular.element(document.body);
var panelAnimation = $mdPanel.newPanelAnimation()
.openFrom(parent)
.closeTo(parent)
.withAnimation({
open: 'md-show',
close: 'md-hide'
});
var panelConfig = {
id: tooltipId,
attachTo: attachTo,
contentElement: element,
propagateContainerEvents: true,
panelClass: 'md-tooltip ' + origin,
animation: panelAnimation,
position: panelPosition,
zIndex: scope.mdZIndex,
focusOnOpen: false
};
panelRef = $mdPanel.create(panelConfig);
}
panelRef.open().then(function() {
panelRef.panelEl.attr('role', 'tooltip');
});
}
function hideTooltip() {
panelRef && panelRef.close();
}
}
}
/**
* Service that is used to reduce the amount of listeners that are being
* registered on the `window` by the tooltip component. Works by collecting
* the individual event handlers and dispatching them from a global handler.
*
* ngInject
*/
function MdTooltipRegistry() {
var listeners = {};
var ngWindow = angular.element(window);
return {
register: register,
deregister: deregister
};
/**
* Global event handler that dispatches the registered handlers in the
* service.
* @param {!Event} event Event object passed in by the browser
*/
function globalEventHandler(event) {
if (listeners[event.type]) {
listeners[event.type].forEach(function(currentHandler) {
currentHandler.call(this, event);
}, this);
}
}
/**
* Registers a new handler with the service.
* @param {string} type Type of event to be registered.
* @param {!Function} handler Event handler.
* @param {boolean} useCapture Whether to use event capturing.
*/
function register(type, handler, useCapture) {
var handlers = listeners[type] = listeners[type] || [];
if (!handlers.length) {
useCapture ? window.addEventListener(type, globalEventHandler, true) :
ngWindow.on(type, globalEventHandler);
}
if (handlers.indexOf(handler) === -1) {
handlers.push(handler);
}
}
/**
* Removes an event handler from the service.
* @param {string} type Type of event handler.
* @param {!Function} handler The event handler itself.
* @param {boolean} useCapture Whether the event handler used event capturing.
*/
function deregister(type, handler, useCapture) {
var handlers = listeners[type];
var index = handlers ? handlers.indexOf(handler) : -1;
if (index > -1) {
handlers.splice(index, 1);
if (handlers.length === 0) {
useCapture ? window.removeEventListener(type, globalEventHandler, true) :
ngWindow.off(type, globalEventHandler);
}
}
}
}
ngmaterial.components.tooltip = angular.module("material.components.tooltip"); | {
setDefaults();
// If the panel has already been created, remove the current origin
// class from the panel element.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.removeClass(origin);
}
// Set the panel element origin class based off of the current
// mdDirection.
origin = 'md-origin-' + scope.mdDirection;
// Create the position of the panel based off of the mdDirection.
position = TOOLTIP_DIRECTIONS[scope.mdDirection];
// Using the newly created position object, use the MdPanel
// panelPosition API to build the panel's position.
panelPosition = $mdPanel.newPanelPosition()
.relativeTo(parent)
.addPanelPosition(position.x, position.y);
// If the panel has already been created, add the new origin class to
// the panel element and update it's position with the panelPosition.
if (panelRef && panelRef.panelEl) {
panelRef.panelEl.addClass(origin);
panelRef.updatePosition(panelPosition);
}
} | identifier_body |
recursiveFunctionTypes.js | //// [recursiveFunctionTypes.ts]
function fn(): typeof fn { return 1; }
var x: number = fn; // error
var y: () => number = fn; // ok
var f: () => typeof g;
var g: () => typeof f;
function f1(d: typeof f1) { }
function f2(): typeof g2 { }
function g2(): typeof f2 { }
interface I<T> { }
function f3(): I<typeof f3> { return f3; }
var a: number = f3; // error
class C {
static g(t: typeof C.g){ }
}
C.g(3); // error
var f4: () => typeof f4;
f4 = 3; // error
function f5() { return f5; }
function f6(): typeof f6;
function f6(a: typeof f6): () => number;
function f6(a?: any) { return f6; }
f6("", 3); // error (arity mismatch)
f6(""); // ok (function takes an any param)
f6(); // ok | declare function f7(a?: typeof f7): typeof f7;
f7("", 3); // error (arity mismatch)
f7(""); // ok (function takes an any param)
f7(); // ok
//// [recursiveFunctionTypes.js]
function fn() { return 1; }
var x = fn; // error
var y = fn; // ok
var f;
var g;
function f1(d) { }
function f2() { }
function g2() { }
function f3() { return f3; }
var a = f3; // error
var C = (function () {
function C() {
}
C.g = function (t) { };
return C;
})();
C.g(3); // error
var f4;
f4 = 3; // error
function f5() { return f5; }
function f6(a) { return f6; }
f6("", 3); // error (arity mismatch)
f6(""); // ok (function takes an any param)
f6(); // ok
f7("", 3); // error (arity mismatch)
f7(""); // ok (function takes an any param)
f7(); // ok |
declare function f7(): typeof f7;
declare function f7(a: typeof f7): () => number;
declare function f7(a: number): number; | random_line_split |
recursiveFunctionTypes.js | //// [recursiveFunctionTypes.ts]
function fn(): typeof fn { return 1; }
var x: number = fn; // error
var y: () => number = fn; // ok
var f: () => typeof g;
var g: () => typeof f;
function f1(d: typeof f1) { }
function f2(): typeof g2 { }
function g2(): typeof f2 { }
interface I<T> { }
function f3(): I<typeof f3> { return f3; }
var a: number = f3; // error
class | {
static g(t: typeof C.g){ }
}
C.g(3); // error
var f4: () => typeof f4;
f4 = 3; // error
function f5() { return f5; }
function f6(): typeof f6;
function f6(a: typeof f6): () => number;
function f6(a?: any) { return f6; }
f6("", 3); // error (arity mismatch)
f6(""); // ok (function takes an any param)
f6(); // ok
declare function f7(): typeof f7;
declare function f7(a: typeof f7): () => number;
declare function f7(a: number): number;
declare function f7(a?: typeof f7): typeof f7;
f7("", 3); // error (arity mismatch)
f7(""); // ok (function takes an any param)
f7(); // ok
//// [recursiveFunctionTypes.js]
function fn() { return 1; }
var x = fn; // error
var y = fn; // ok
var f;
var g;
function f1(d) { }
function f2() { }
function g2() { }
function f3() { return f3; }
var a = f3; // error
var C = (function () {
function C() {
}
C.g = function (t) { };
return C;
})();
C.g(3); // error
var f4;
f4 = 3; // error
function f5() { return f5; }
function f6(a) { return f6; }
f6("", 3); // error (arity mismatch)
f6(""); // ok (function takes an any param)
f6(); // ok
f7("", 3); // error (arity mismatch)
f7(""); // ok (function takes an any param)
f7(); // ok
| C | identifier_name |
recursiveFunctionTypes.js | //// [recursiveFunctionTypes.ts]
function fn(): typeof fn |
var x: number = fn; // error
var y: () => number = fn; // ok
var f: () => typeof g;
var g: () => typeof f;
function f1(d: typeof f1) { }
function f2(): typeof g2 { }
function g2(): typeof f2 { }
interface I<T> { }
function f3(): I<typeof f3> { return f3; }
var a: number = f3; // error
class C {
static g(t: typeof C.g){ }
}
C.g(3); // error
var f4: () => typeof f4;
f4 = 3; // error
function f5() { return f5; }
function f6(): typeof f6;
function f6(a: typeof f6): () => number;
function f6(a?: any) { return f6; }
f6("", 3); // error (arity mismatch)
f6(""); // ok (function takes an any param)
f6(); // ok
declare function f7(): typeof f7;
declare function f7(a: typeof f7): () => number;
declare function f7(a: number): number;
declare function f7(a?: typeof f7): typeof f7;
f7("", 3); // error (arity mismatch)
f7(""); // ok (function takes an any param)
f7(); // ok
//// [recursiveFunctionTypes.js]
function fn() { return 1; }
var x = fn; // error
var y = fn; // ok
var f;
var g;
function f1(d) { }
function f2() { }
function g2() { }
function f3() { return f3; }
var a = f3; // error
var C = (function () {
function C() {
}
C.g = function (t) { };
return C;
})();
C.g(3); // error
var f4;
f4 = 3; // error
function f5() { return f5; }
function f6(a) { return f6; }
f6("", 3); // error (arity mismatch)
f6(""); // ok (function takes an any param)
f6(); // ok
f7("", 3); // error (arity mismatch)
f7(""); // ok (function takes an any param)
f7(); // ok
| { return 1; } | identifier_body |
drf.py | import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
|
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
| self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs) | identifier_body |
drf.py | import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value) |
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"} | random_line_split | |
drf.py | import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
|
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
| raise serializers.SkipField() | conditional_block |
drf.py | import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def | (self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
| to_internal_value | identifier_name |
ToolbarIcon.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import Glyph from './Glyph'; | import {Tracked} from 'flipper-plugin';
type Props = React.ComponentProps<typeof ToolbarIconContainer> & {
active?: boolean;
icon: string;
title: string;
onClick: () => void;
};
const ToolbarIconContainer = styled.div({
marginRight: 9,
marginTop: -3,
marginLeft: 4,
position: 'relative', // for settings popover positioning
});
export default function ToolbarIcon({active, icon, title, ...props}: Props) {
return (
<Tooltip title={title}>
<Tracked action={title}>
<ToolbarIconContainer {...props}>
<Glyph
name={icon}
size={16}
color={
active
? colors.macOSTitleBarIconSelected
: colors.macOSTitleBarIconActive
}
/>
</ToolbarIconContainer>
</Tracked>
</Tooltip>
);
} | import Tooltip from './Tooltip';
import {colors} from './colors';
import styled from '@emotion/styled';
import React from 'react'; | random_line_split |
ToolbarIcon.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import Glyph from './Glyph';
import Tooltip from './Tooltip';
import {colors} from './colors';
import styled from '@emotion/styled';
import React from 'react';
import {Tracked} from 'flipper-plugin';
type Props = React.ComponentProps<typeof ToolbarIconContainer> & {
active?: boolean;
icon: string;
title: string;
onClick: () => void;
};
const ToolbarIconContainer = styled.div({
marginRight: 9,
marginTop: -3,
marginLeft: 4,
position: 'relative', // for settings popover positioning
});
export default function | ({active, icon, title, ...props}: Props) {
return (
<Tooltip title={title}>
<Tracked action={title}>
<ToolbarIconContainer {...props}>
<Glyph
name={icon}
size={16}
color={
active
? colors.macOSTitleBarIconSelected
: colors.macOSTitleBarIconActive
}
/>
</ToolbarIconContainer>
</Tracked>
</Tooltip>
);
}
| ToolbarIcon | identifier_name |
ToolbarIcon.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import Glyph from './Glyph';
import Tooltip from './Tooltip';
import {colors} from './colors';
import styled from '@emotion/styled';
import React from 'react';
import {Tracked} from 'flipper-plugin';
type Props = React.ComponentProps<typeof ToolbarIconContainer> & {
active?: boolean;
icon: string;
title: string;
onClick: () => void;
};
const ToolbarIconContainer = styled.div({
marginRight: 9,
marginTop: -3,
marginLeft: 4,
position: 'relative', // for settings popover positioning
});
export default function ToolbarIcon({active, icon, title, ...props}: Props) | {
return (
<Tooltip title={title}>
<Tracked action={title}>
<ToolbarIconContainer {...props}>
<Glyph
name={icon}
size={16}
color={
active
? colors.macOSTitleBarIconSelected
: colors.macOSTitleBarIconActive
}
/>
</ToolbarIconContainer>
</Tracked>
</Tooltip>
);
} | identifier_body | |
timelineTemplete.js | exports.tableTemplete = function(dataArray){
var tableView = Ti.UI.createTableView({
width:Ti.UI.FILL,
height:Ti.UI.FILL,
selectionStyle: Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
backgroundColor:"#F5F1E9",
prependMovie:"none",
old_row:"null",
leastId:0,
});
var tableViewData= {new_data:'',
reload_flg:false,
first_flg:false,
lastDistance:0,
upper_reloading:false,
pulling:false
};
tableView.addEventListener('singletap',function(e){
// console.log('log '+e.source.video);
if(e.source == '[object TiUIImageView]'){
if(tableView.prependMovie != "none"){
tableView.prependMovie.stop();
tableView.prependMovie = e.source.video;
console.log(e.source.video);
console.log(tableView.prependMovie);
console.log("-------------------------------------------------------");
}
//すでに一回再生していた場合追加する必要性がないため存在の確認
if(e.source.video == undefined){
var video = Ti.Media.createVideoPlayer({
backgroundColor : 'black',
top:4,
height : 300,
width : 300,
movieControlMode: Titanium.Media.VIDEO_CONTROL_HIDDEN,
mediaControlStyle: Titanium.Media.VIDEO_CONTROL_NONE,
scalingMode:Titanium.Media.VIDEO_SCALING_NONE,
url : e.source.videoUrl,
autoplay:false,
// borderColor:"#ff0000",
});
var act = require('UI/actind').actind();
e.source.add(act);
act.show();
video.addEventListener('mediatypesavailable',function(){
// e.source.remove(act);
act.hide();
// act = null;
video.play();
e.source.add(video);
tableView.prependMovie = video;
});
e.source.video = video;
}
else{
var animation = Ti.UI.createAnimation({
opacity:1,
duration:1
});
//opacityを1にする
e.source.video.animate(animation);
animation.addEventListener('complete',function(){
e.source.video.play();
console.log(e.source.video);
console.log("---------------------else video start--------------");
animation = null;
});
}
e.source.video.addEventListener('complete',function(){
e.source.video.stop();
console.log("----------------------video complete-----------------");
var animation2 = Ti.UI.createAnimation({
opacity:0,
duration:1
});
e.source.video.animate(animation2);
animation2 = null;
});
// e.source.video.addEventListener('playing',function(e){
// console.log(e);
// });
}
});
tableView.data = require('UI/timelineTemplete').createRow(dataArray);
////////////////////上更新 pull down to refresh //////////////////////////////////
tableView.headerPullView = require('UI/pullToDown').pull_to_down(); //UIの参照
tableView.addEventListener('scroll',function(e){
var offset = e.contentOffset.y;
if (offset < -70.0 && !tableViewData.pulling && !tableViewData.reloading){
var t = Ti.UI.create2DMatrix();
t = t.rotate(-180);
tableViewData.pulling = true;
tableView.headerPullView.arrow.animate({transform:t,duration:180});
tableView.headerPullView.statusLabel.text = "Release to refresh...";
}
else if((offset > -70.0 && offset < 0 ) && tableViewData.pulling && !tableViewData.reloading){
tableViewData.pulling = false;
var t = Ti.UI.create2DMatrix();
tableView.headerPullView.arrow.animate({transform:t,duration:180});
tableView.headerPullView.statusLabel.text = "Pull down to refresh...";
}
});
tableView.addEventListener('dragEnd', function(){
if(tableViewData.pulling && !tableViewData.reloading){
tableViewData.reloading = true;
tableViewData.pulling = false;
// statusLabel.text = "Reloading...";
tableView.setContentInsets({top:60},{animated:true});
tableView.scrollToTop(-60,true);
tableView.headerPullView.arrow.transform = Ti.UI.create2DMatrix();
tableView.fireEvent('upReload');
// tableView.leastId = data[data.length].postId;
tableView.setContentInsets({top:0},{animated:true});
tableView.headerPullView.statusLabel.text = "Pull down to refresh...";
tableView.headerPullView.arrow.show();
tableViewData.reload_flg = false;
tableViewData.reloading = false;
}
});
//下更新
tableView.addEventListener('scroll',function(e){
var offset = e.contentOffset.y; // テーブルの見えてる部分の位置(上)
var height = e.size.height; // テーブルの見えてる部分のサイズ(画面内の)固定
var total = offset + height; // テーブルの見えている部分の位置(下)
var theEnd = e.contentSize.height;
var distance = theEnd - total; // テーブル全体の底辺からの今見えてる部分の距離
if (distance < tableViewData.lastDistance){
var nearEnd = theEnd;
// 更新中じゃなく、テーブルのサイズの99%以上までスクロールしたら。
if (!tableViewData.reload_flg && (total >= nearEnd)){
// var actind = require('UI/UI_option').actind();
// actind.show();
// Ti.App.win_base.add(actind);
tableView.fireEvent('underReload');
tableViewData.reload_flg = false;
}
//home_time_line_data.lastDistance = distance; //現在の距離を保存する。
}
tableViewData.lastDistance = distance; //現在の距離を保存する。
});
return tableView;
};
exports.createRow = function(dataArray){
var rowArray = [];
for(var i in dataArray){
var row = Ti.UI.createTableViewRow({
width:Ti.UI.FILL,
height:Ti.UI.SIZE,
});
row.hide();
var view = Ti.UI.createView({
width:Ti.UI.FILL,
height:Ti.UI.SIZE,
});
row.add(view);
// if(i == 0){
// console.log(json.data.records[i]);
// }
// console.log(json.data.records[i]);
var videoView = Ti.UI.createImageView({
top:5,
height:300,
width:300,
image:dataArray[i].thumbnailUrl,
});
/*
構造
5px
============================================
videoを再生する場所
============================================
10px =======投稿時間===================
======= 5px ==============
profile username
image ==============
======= 5px
=================================
投稿コメント
=================================
5px
=================================
各種ボタン
=================================
*/
//整形させる
var day = dataArray[i].created.split('T');
var day_parts = day[0].split('-');
var time = day[1].split(':');
// console.log(day_parts);
// +9hさせる
var timeLabel = Ti.UI.createLabel({
right:10,
top:305,
text:day_parts[0]+" "+day_parts[1]+" "+day_parts[2]+" "+time[0]+":"+time[1],
font: { fontSize: 15, fontFamily: 'AppleGothic', } ,
textAlign: 'right',
color:"#111",
});
var profileImage = Ti.UI.createImageView({
left:5,
top:315,
width:45,
height:45,
image:dataArray[i].avatarUrl
});
var usernameLabel = Ti.UI.createLabel({
left:55,
top:315,
text:dataArray[i].username,
font: { fontSize: 15, fontFamily: 'AppleGothic', } ,
textAlign: 'left',
color:"#111"
});
//コメントの高さが可変長なためコメントの高さを最小に押さえてその下にボタンのviewをはる
var verticalView = Ti.UI.createView({
top:345,
left:55,
width:Titanium.Platform.displayCaps.platformWidth - 55 - 5, //-5 は右の空白分
height:Ti.UI.SIZE,
// borderColor:"#ff00ff",
layout:"vertical"
});
if(dataArray[i].description != null){
var commentLabel = Ti.UI.createLabel({
left:0,
top:0,
text:dataArray[i].description,
font: { fontSize: 17, fontFamily: 'AppleGothic', } ,
textAlign: 'left',
color:"#111"
});
verticalView.add(commentLabel);
}
var buttonView = Ti.UI.createView({
width:Ti.UI.FILL,
height:Ti.UI.SIZE,
top:2,
bottom:5,
layout:"horizontal"
});
var likeButton = Ti.UI.createButton({
//title:"like",
backgroundImage : "/images/thumbs_up.png",
width:20,//45
height:20,//25
left:10,
postId:dataArray[i].postId
});
var commentButton = Ti.UI.createButton({
//title:"comment",
backgroundImage : "/images/comment.png",
left:20,
width:20,
height:20,
});
//copy this row's url
var shareButton = Ti.UI.createButton({
//title:"share",
backgroundImage : "/images/share.png",
left:20,
width:20,
height:20,
});
likeButton.addEventListener('singletap',function(e){
///// api.vimapp.com/posts/movie_id/likes
// console.log(e);
require('lib/vineAPI').PostLike(e.source.postId);
});
shareButton.addEventListener('singletap',function(){
Ti.UI.Clipboard.clearText();
Ti.UI.Clipboard.setText(dataArray[i].shareUrl);
//message
});
buttonView.add(likeButton);
buttonView.add(commentButton);
buttonView.add(shareButton);
//もし自分の投稿なら消すボタンの設置
if(Ti.App.username == dataArray[i].username){
var deleteButton = Ti.UI.createButton({
//title:"delete",
backgroundImage : "/images/remove.png",
left:25,
width:20,
height:25,
postId:dataArray[i].postId
});
deleteButton.addEventListener('singletap',function(e){
console.log(e);
// require('lib/vineAPI').myPostDelete(e.source.postId);
});
buttonView.add(deleteButton);
}
verticalView.add(buttonView);
view.add(timeLabel);
view.add(profileImage);
view.add(usernameLabel);
view.add(verticalView);
videoView.videoUrl | = dataArray[i].videoUrl;
view.add(videoView);
row.show();
rowArray.push(row);
}
return rowArray;
}; | conditional_block | |
timelineTemplete.js | exports.tableTemplete = function(dataArray){
var tableView = Ti.UI.createTableView({
width:Ti.UI.FILL,
height:Ti.UI.FILL,
selectionStyle: Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
backgroundColor:"#F5F1E9",
prependMovie:"none",
old_row:"null",
leastId:0,
});
var tableViewData= {new_data:'',
reload_flg:false,
first_flg:false,
lastDistance:0,
upper_reloading:false,
pulling:false
};
tableView.addEventListener('singletap',function(e){
// console.log('log '+e.source.video);
if(e.source == '[object TiUIImageView]'){
if(tableView.prependMovie != "none"){
tableView.prependMovie.stop();
tableView.prependMovie = e.source.video;
console.log(e.source.video);
console.log(tableView.prependMovie);
console.log("-------------------------------------------------------");
}
//すでに一回再生していた場合追加する必要性がないため存在の確認
if(e.source.video == undefined){
var video = Ti.Media.createVideoPlayer({
backgroundColor : 'black',
top:4,
height : 300,
width : 300,
movieControlMode: Titanium.Media.VIDEO_CONTROL_HIDDEN,
mediaControlStyle: Titanium.Media.VIDEO_CONTROL_NONE,
scalingMode:Titanium.Media.VIDEO_SCALING_NONE,
url : e.source.videoUrl,
autoplay:false,
// borderColor:"#ff0000",
});
var act = require('UI/actind').actind();
e.source.add(act);
act.show();
video.addEventListener('mediatypesavailable',function(){
// e.source.remove(act);
act.hide();
// act = null;
video.play();
e.source.add(video);
tableView.prependMovie = video;
});
e.source.video = video;
}
else{
var animation = Ti.UI.createAnimation({
opacity:1,
duration:1
});
//opacityを1にする
e.source.video.animate(animation);
animation.addEventListener('complete',function(){
e.source.video.play();
console.log(e.source.video);
console.log("---------------------else video start--------------");
animation = null;
});
}
e.source.video.addEventListener('complete',function(){
e.source.video.stop();
console.log("----------------------video complete-----------------");
var animation2 = Ti.UI.createAnimation({
opacity:0,
duration:1
});
e.source.video.animate(animation2);
animation2 = null;
});
// e.source.video.addEventListener('playing',function(e){
// console.log(e);
// });
}
});
tableView.data = require('UI/timelineTemplete').createRow(dataArray);
////////////////////上更新 pull down to refresh //////////////////////////////////
tableView.headerPullView = require('UI/pullToDown').pull_to_down(); //UIの参照
tableView.addEventListener('scroll',function(e){
var offset = e.contentOffset.y;
if (offset < -70.0 && !tableViewData.pulling && !tableViewData.reloading){
var t = Ti.UI.create2DMatrix();
t = t.rotate(-180);
tableViewData.pulling = true;
tableView.headerPullView.arrow.animate({transform:t,duration:180});
tableView.headerPullView.statusLabel.text = "Release to refresh...";
}
else if((offset > -70.0 && offset < 0 ) && tableViewData.pulling && !tableViewData.reloading){
tableViewData.pulling = false;
var t = Ti.UI.create2DMatrix();
tableView.headerPullView.arrow.animate({transform:t,duration:180});
tableView.headerPullView.statusLabel.text = "Pull down to refresh...";
}
});
tableView.addEventListener('dragEnd', function(){
if(tableViewData.pulling && !tableViewData.reloading){
tableViewData.reloading = true;
tableViewData.pulling = false;
// statusLabel.text = "Reloading...";
tableView.setContentInsets({top:60},{animated:true});
tableView.scrollToTop(-60,true);
tableView.headerPullView.arrow.transform = Ti.UI.create2DMatrix();
tableView.fireEvent('upReload');
// tableView.leastId = data[data.length].postId;
tableView.setContentInsets({top:0},{animated:true});
tableView.headerPullView.statusLabel.text = "Pull down to refresh...";
tableView.headerPullView.arrow.show();
tableViewData.reload_flg = false;
tableViewData.reloading = false;
}
});
//下更新
tableView.addEventListener('scroll',function(e){
var offset = e.contentOffset.y; // テーブルの見えてる部分の位置(上)
var height = e.size.height; // テーブルの見えてる部分のサイズ(画面内の)固定
var total = offset + height; // テーブルの見えている部分の位置(下)
var theEnd = e.contentSize.height;
var distance = theEnd - total; // テーブル全体の底辺からの今見えてる部分の距離
if (distance < tableViewData.lastDistance){
var nearEnd = theEnd;
// 更新中じゃなく、テーブルのサイズの99%以上までスクロールしたら。
if (!tableViewData.reload_flg && (total >= nearEnd)){
// var actind = require('UI/UI_option').actind();
// actind.show();
// Ti.App.win_base.add(actind);
tableView.fireEvent('underReload');
tableViewData.reload_flg = false;
}
//home_time_line_data.lastDistance = distance; //現在の距離を保存する。
}
tableViewData.lastDistance = distance; //現在の距離を保存する。
});
return tableView;
};
exports.createRow = function(dataArray){
var rowArray = [];
for(var i in dataArray){
var row = Ti.UI.createTableViewRow({
width:Ti.UI.FILL,
height:Ti.UI.SIZE,
});
row.hide(); | width:Ti.UI.FILL,
height:Ti.UI.SIZE,
});
row.add(view);
// if(i == 0){
// console.log(json.data.records[i]);
// }
// console.log(json.data.records[i]);
var videoView = Ti.UI.createImageView({
top:5,
height:300,
width:300,
image:dataArray[i].thumbnailUrl,
});
/*
構造
5px
============================================
videoを再生する場所
============================================
10px =======投稿時間===================
======= 5px ==============
profile username
image ==============
======= 5px
=================================
投稿コメント
=================================
5px
=================================
各種ボタン
=================================
*/
//整形させる
var day = dataArray[i].created.split('T');
var day_parts = day[0].split('-');
var time = day[1].split(':');
// console.log(day_parts);
// +9hさせる
var timeLabel = Ti.UI.createLabel({
right:10,
top:305,
text:day_parts[0]+" "+day_parts[1]+" "+day_parts[2]+" "+time[0]+":"+time[1],
font: { fontSize: 15, fontFamily: 'AppleGothic', } ,
textAlign: 'right',
color:"#111",
});
var profileImage = Ti.UI.createImageView({
left:5,
top:315,
width:45,
height:45,
image:dataArray[i].avatarUrl
});
var usernameLabel = Ti.UI.createLabel({
left:55,
top:315,
text:dataArray[i].username,
font: { fontSize: 15, fontFamily: 'AppleGothic', } ,
textAlign: 'left',
color:"#111"
});
//コメントの高さが可変長なためコメントの高さを最小に押さえてその下にボタンのviewをはる
var verticalView = Ti.UI.createView({
top:345,
left:55,
width:Titanium.Platform.displayCaps.platformWidth - 55 - 5, //-5 は右の空白分
height:Ti.UI.SIZE,
// borderColor:"#ff00ff",
layout:"vertical"
});
if(dataArray[i].description != null){
var commentLabel = Ti.UI.createLabel({
left:0,
top:0,
text:dataArray[i].description,
font: { fontSize: 17, fontFamily: 'AppleGothic', } ,
textAlign: 'left',
color:"#111"
});
verticalView.add(commentLabel);
}
var buttonView = Ti.UI.createView({
width:Ti.UI.FILL,
height:Ti.UI.SIZE,
top:2,
bottom:5,
layout:"horizontal"
});
var likeButton = Ti.UI.createButton({
//title:"like",
backgroundImage : "/images/thumbs_up.png",
width:20,//45
height:20,//25
left:10,
postId:dataArray[i].postId
});
var commentButton = Ti.UI.createButton({
//title:"comment",
backgroundImage : "/images/comment.png",
left:20,
width:20,
height:20,
});
//copy this row's url
var shareButton = Ti.UI.createButton({
//title:"share",
backgroundImage : "/images/share.png",
left:20,
width:20,
height:20,
});
likeButton.addEventListener('singletap',function(e){
///// api.vimapp.com/posts/movie_id/likes
// console.log(e);
require('lib/vineAPI').PostLike(e.source.postId);
});
shareButton.addEventListener('singletap',function(){
Ti.UI.Clipboard.clearText();
Ti.UI.Clipboard.setText(dataArray[i].shareUrl);
//message
});
buttonView.add(likeButton);
buttonView.add(commentButton);
buttonView.add(shareButton);
//もし自分の投稿なら消すボタンの設置
if(Ti.App.username == dataArray[i].username){
var deleteButton = Ti.UI.createButton({
//title:"delete",
backgroundImage : "/images/remove.png",
left:25,
width:20,
height:25,
postId:dataArray[i].postId
});
deleteButton.addEventListener('singletap',function(e){
console.log(e);
// require('lib/vineAPI').myPostDelete(e.source.postId);
});
buttonView.add(deleteButton);
}
verticalView.add(buttonView);
view.add(timeLabel);
view.add(profileImage);
view.add(usernameLabel);
view.add(verticalView);
videoView.videoUrl = dataArray[i].videoUrl;
view.add(videoView);
row.show();
rowArray.push(row);
}
return rowArray;
}; |
var view = Ti.UI.createView({ | random_line_split |
lib.rs | /* Copyright (C) 2015 Yutaka Kamei */
#![feature(test)]
extern crate urlparse;
extern crate test;
use urlparse::*;
use test::Bencher;
#[bench]
fn bench_quote(b: &mut Bencher) {
b.iter(|| quote("/a/テスト !/", &[b'/']));
}
#[bench]
fn bench_quote_plus(b: &mut Bencher) {
b.iter(|| quote_plus("/a/テスト !/", &[b'/']));
}
#[bench]
fn bench_unquot | cher) {
b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_unquote_plus(b: &mut Bencher) {
b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_parse_qs(b: &mut Bencher) {
b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%E3%83%88+%E3%83%86%E3%82%B9%E3%83%88&e=utf-8"));
}
#[bench]
fn bench_urlparse(b: &mut Bencher) {
b.iter(|| urlparse("http://Example.com:8080/foo?filter=%28%21%28cn%3Dbar%29%29"));
}
#[bench]
fn bench_urlunparse(b: &mut Bencher) {
b.iter(|| {
let url = Url::new();
let url = Url{
scheme: "http".to_string(),
netloc: "www.example.com".to_string(),
path: "/foo".to_string(),
query: Some("filter=%28%21%28cn%3Dbar%29%29".to_string()),
.. url};
urlunparse(url)
});
}
| e(b: &mut Ben | identifier_name |
lib.rs | /* Copyright (C) 2015 Yutaka Kamei */
#![feature(test)]
extern crate urlparse;
extern crate test;
use urlparse::*;
use test::Bencher;
#[bench]
fn bench_quote(b: &mut Bencher) {
b.iter(|| quote("/a/テスト !/", &[b'/']));
}
#[bench]
fn bench_quote_plus(b: &mut Bencher) {
b.iter(|| quote_plus("/a/テスト !/", &[b'/']));
}
#[bench]
fn bench_unquote(b: &mut Bencher) {
b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_unquote_plus(b: &mut Bencher) {
b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_parse_qs(b: &mut Bencher) {
b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%E3%83%88+%E3%83%86%E3%82%B9%E3%83%88&e=utf-8"));
}
#[bench]
fn bench_urlparse(b: &mut Bencher) {
b.iter(|| urlparse("http://Example.com:8080/foo?filter=%28%21%28cn%3Dbar%29%29"));
}
#[bench]
fn bench_urlunparse(b: &mut Bencher) {
b.iter(|| {
let url = Url::new();
let url = Url{
scheme: "http".to_string(),
netloc: "www.example.com".to_string(),
path: "/foo".to_string(), | } | query: Some("filter=%28%21%28cn%3Dbar%29%29".to_string()),
.. url};
urlunparse(url)
}); | random_line_split |
lib.rs | /* Copyright (C) 2015 Yutaka Kamei */
#![feature(test)]
extern crate urlparse;
extern crate test;
use urlparse::*;
use test::Bencher;
#[bench]
fn bench_quote(b: &mut Bencher) {
b.iter(|| quote("/a/テスト !/", &[b'/']));
}
#[bench]
fn bench_quote_plus(b: &mut Bencher) {
| fn bench_unquote(b: &mut Bencher) {
b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_unquote_plus(b: &mut Bencher) {
b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_parse_qs(b: &mut Bencher) {
b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%E3%83%88+%E3%83%86%E3%82%B9%E3%83%88&e=utf-8"));
}
#[bench]
fn bench_urlparse(b: &mut Bencher) {
b.iter(|| urlparse("http://Example.com:8080/foo?filter=%28%21%28cn%3Dbar%29%29"));
}
#[bench]
fn bench_urlunparse(b: &mut Bencher) {
b.iter(|| {
let url = Url::new();
let url = Url{
scheme: "http".to_string(),
netloc: "www.example.com".to_string(),
path: "/foo".to_string(),
query: Some("filter=%28%21%28cn%3Dbar%29%29".to_string()),
.. url};
urlunparse(url)
});
}
| b.iter(|| quote_plus("/a/テスト !/", &[b'/']));
}
#[bench]
| identifier_body |
linux_gl_hooks.rs | #![cfg(target_os = "linux")]
#[link(name = "dl")]
extern "C" {}
use crate::gl;
use const_cstr::const_cstr;
use lazy_static::lazy_static;
use libc::{c_char, c_int, c_ulong, c_void};
use libc_print::libc_println;
use log::*;
use std::ffi::CString;
use std::sync::Once;
use std::time::SystemTime;
///////////////////////////////////////////
// libdl definition & link instructions
///////////////////////////////////////////
#[allow(unused)]
pub const RTLD_LAZY: c_int = 0x00001;
#[allow(unused)]
pub const RTLD_NOW: c_int = 0x00002;
#[allow(unused)]
pub const RTLD_NOLOAD: c_int = 0x0004;
#[allow(unused)]
pub const RTLD_DEFAULT: *const c_void = 0x00000 as *const c_void;
#[allow(unused)]
pub const RTLD_NEXT: *const c_void = (-1 as isize) as *const c_void;
extern "C" {
pub fn dlsym(handle: *const c_void, symbol: *const c_char) -> *const c_void;
pub fn dlclose(handle: *const c_void);
}
///////////////////////////////////////////
// lazily-opened libGL handle
///////////////////////////////////////////
struct LibHandle {
addr: *const c_void,
}
unsafe impl std::marker::Sync for LibHandle {}
lazy_static! {
static ref libGLHandle: LibHandle = {
use const_cstr::*;
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_LAZY);
if handle.is_null() {
panic!("could not dlopen libGL.so.1")
}
LibHandle { addr: handle }
};
}
///////////////////////////////////////////
// glXGetProcAddressARB wrapper
///////////////////////////////////////////
lazy_static! {
static ref glXGetProcAddressARB: unsafe extern "C" fn(name: *const c_char) -> *const c_void = unsafe {
let addr = dlsym(
libGLHandle.addr,
const_cstr!("glXGetProcAddressARB").as_ptr(),
);
if addr.is_null() {
panic!("libGL.so.1 does not contain glXGetProcAddressARB")
}
std::mem::transmute(addr)
};
}
unsafe fn get_glx_proc_address(rustName: &str) -> *const () {
let name = CString::new(rustName).unwrap();
let addr = glXGetProcAddressARB(name.as_ptr());
info!("glXGetProcAddressARB({}) = {:x}", rustName, addr as isize);
addr as *const ()
}
lazy_static! {
static ref startTime: SystemTime = SystemTime::now();
}
///////////////////////////////////////////
// dlopen hook
///////////////////////////////////////////
hook_ld! {
"dl" => fn dlopen(filename: *const c_char, flags: c_int) -> *const c_void {
let res = dlopen::next(filename, flags);
hook_if_needed();
res
}
}
///////////////////////////////////////////
// glXSwapBuffers hook
///////////////////////////////////////////
hook_dynamic! {
get_glx_proc_address => {
fn glXSwapBuffers(display: *const c_void, drawable: c_ulong) -> () {
if super::SETTINGS.in_test && display == 0xDEADBEEF as *const c_void {
libc_println!("caught dead beef");
std::process::exit(0);
}
info!(
"[{:08}] swapping buffers! (display=0x{:X}, drawable=0x{:X})",
startTime.elapsed().unwrap().as_millis(),
display as isize,
drawable as isize
);
capture_gl_frame();
glXSwapBuffers::next(display, drawable)
}
fn glXQueryVersion(display: *const c_void, major: *mut c_int, minor: *mut c_int) -> c_int {
// useless hook, just here to demonstrate we can do multiple hooks if needed
let ret = glXQueryVersion::next(display, major, minor);
if ret == 1 {
info!("GLX server version {}.{}", *major, *minor);
}
ret
}
}
}
/// Returns true if libGL.so.1 was loaded in this process,
/// either by ld-linux on startup (if linked with -lGL),
/// or by dlopen() afterwards.
unsafe fn is_using_opengl() -> bool {
// RTLD_NOLOAD lets us check if a library is already loaded.
// FIXME: we actually do need to call dlclose here, apparently
// modules are reference-counted.
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY);
let using = !handle.is_null();
if using {
dlclose(handle);
}
using
}
static HOOK_SWAPBUFFERS_ONCE: Once = Once::new();
/// If libGL.so.1 was loaded, and only once in the lifetime
/// of this process, hook libGL functions for libcapsule usage.
unsafe fn hook_if_needed() {
if is_using_opengl() {
HOOK_SWAPBUFFERS_ONCE.call_once(|| {
info!("libGL usage detected, hooking OpenGL");
glXSwapBuffers::enable_hook();
glXQueryVersion::enable_hook();
})
}
}
pub fn initialize() {
unsafe { hook_if_needed() }
}
lazy_static! {
static ref frame_buffer: Vec<u8> = {
let num_bytes = (1920 * 1080 * 4) as usize;
let mut data = Vec::<u8>::with_capacity(num_bytes);
data.resize(num_bytes, 0);
data
};
}
static mut frame_index: i64 = 0;
unsafe fn capture_gl_frame() | {
let cc = gl::get_capture_context(get_glx_proc_address);
cc.capture_frame();
let x: gl::GLint = 0;
let y: gl::GLint = 0;
let width: gl::GLsizei = 400;
let height: gl::GLsizei = 400;
let bytes_per_pixel: usize = 4;
let bytes_per_frame: usize = width as usize * height as usize * bytes_per_pixel;
let mut viewport = Vec::<gl::GLint>::with_capacity(4);
viewport.resize(4, 0);
cc.funcs
.glGetIntegerv(gl::GL_VIEWPORT, std::mem::transmute(viewport.as_ptr()));
info!("viewport: {:?}", viewport);
cc.funcs.glReadPixels(
x,
y,
width,
height,
gl::GL_RGBA,
gl::GL_UNSIGNED_BYTE,
std::mem::transmute(frame_buffer.as_ptr()),
);
let mut num_black = 0;
for y in 0..height {
for x in 0..width {
let i = (y * width + x) as usize;
let (r, g, b) = (
frame_buffer[i * 4],
frame_buffer[i * 4 + 1],
frame_buffer[i * 4 + 2],
);
if r == 0 && g == 0 && b == 0 {
num_black += 1;
}
}
}
info!("[frame {}] {} black pixels", frame_index, num_black);
frame_index += 1;
if frame_index < 200 {
use std::fs::File;
use std::io::prelude::*;
let name = format!("frame-{}x{}-{}.raw", width, height, frame_index);
let mut file = File::create(&name).unwrap();
file.write_all(&frame_buffer.as_slice()[..bytes_per_frame])
.unwrap();
info!("{} written", name)
}
} | identifier_body | |
linux_gl_hooks.rs | #![cfg(target_os = "linux")]
#[link(name = "dl")]
extern "C" {}
use crate::gl;
use const_cstr::const_cstr;
use lazy_static::lazy_static;
use libc::{c_char, c_int, c_ulong, c_void};
use libc_print::libc_println;
use log::*;
use std::ffi::CString;
use std::sync::Once;
use std::time::SystemTime;
///////////////////////////////////////////
// libdl definition & link instructions
///////////////////////////////////////////
#[allow(unused)]
pub const RTLD_LAZY: c_int = 0x00001;
#[allow(unused)]
pub const RTLD_NOW: c_int = 0x00002;
#[allow(unused)]
pub const RTLD_NOLOAD: c_int = 0x0004;
#[allow(unused)]
pub const RTLD_DEFAULT: *const c_void = 0x00000 as *const c_void;
#[allow(unused)]
pub const RTLD_NEXT: *const c_void = (-1 as isize) as *const c_void;
extern "C" {
pub fn dlsym(handle: *const c_void, symbol: *const c_char) -> *const c_void;
pub fn dlclose(handle: *const c_void);
}
///////////////////////////////////////////
// lazily-opened libGL handle
///////////////////////////////////////////
struct LibHandle {
addr: *const c_void,
}
unsafe impl std::marker::Sync for LibHandle {}
lazy_static! {
static ref libGLHandle: LibHandle = {
use const_cstr::*;
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_LAZY);
if handle.is_null() {
panic!("could not dlopen libGL.so.1")
}
LibHandle { addr: handle }
};
}
///////////////////////////////////////////
// glXGetProcAddressARB wrapper
///////////////////////////////////////////
lazy_static! {
static ref glXGetProcAddressARB: unsafe extern "C" fn(name: *const c_char) -> *const c_void = unsafe {
let addr = dlsym(
libGLHandle.addr,
const_cstr!("glXGetProcAddressARB").as_ptr(),
);
if addr.is_null() {
panic!("libGL.so.1 does not contain glXGetProcAddressARB")
}
std::mem::transmute(addr)
};
}
unsafe fn get_glx_proc_address(rustName: &str) -> *const () {
let name = CString::new(rustName).unwrap();
let addr = glXGetProcAddressARB(name.as_ptr());
info!("glXGetProcAddressARB({}) = {:x}", rustName, addr as isize);
addr as *const ()
}
lazy_static! {
static ref startTime: SystemTime = SystemTime::now();
}
///////////////////////////////////////////
// dlopen hook
///////////////////////////////////////////
hook_ld! {
"dl" => fn dlopen(filename: *const c_char, flags: c_int) -> *const c_void {
let res = dlopen::next(filename, flags);
hook_if_needed();
res
}
}
///////////////////////////////////////////
// glXSwapBuffers hook
///////////////////////////////////////////
hook_dynamic! {
get_glx_proc_address => {
fn glXSwapBuffers(display: *const c_void, drawable: c_ulong) -> () {
if super::SETTINGS.in_test && display == 0xDEADBEEF as *const c_void {
libc_println!("caught dead beef");
std::process::exit(0);
}
info!(
"[{:08}] swapping buffers! (display=0x{:X}, drawable=0x{:X})",
startTime.elapsed().unwrap().as_millis(),
display as isize,
drawable as isize
);
capture_gl_frame();
glXSwapBuffers::next(display, drawable)
}
fn glXQueryVersion(display: *const c_void, major: *mut c_int, minor: *mut c_int) -> c_int {
// useless hook, just here to demonstrate we can do multiple hooks if needed
let ret = glXQueryVersion::next(display, major, minor);
if ret == 1 {
info!("GLX server version {}.{}", *major, *minor);
}
ret
}
}
}
/// Returns true if libGL.so.1 was loaded in this process,
/// either by ld-linux on startup (if linked with -lGL),
/// or by dlopen() afterwards.
unsafe fn is_using_opengl() -> bool {
// RTLD_NOLOAD lets us check if a library is already loaded.
// FIXME: we actually do need to call dlclose here, apparently
// modules are reference-counted.
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY);
let using = !handle.is_null();
if using {
dlclose(handle);
}
using
}
static HOOK_SWAPBUFFERS_ONCE: Once = Once::new();
/// If libGL.so.1 was loaded, and only once in the lifetime
/// of this process, hook libGL functions for libcapsule usage.
unsafe fn hook_if_needed() {
if is_using_opengl() {
HOOK_SWAPBUFFERS_ONCE.call_once(|| {
info!("libGL usage detected, hooking OpenGL");
glXSwapBuffers::enable_hook();
glXQueryVersion::enable_hook();
})
}
}
pub fn initialize() {
unsafe { hook_if_needed() }
}
lazy_static! {
static ref frame_buffer: Vec<u8> = {
let num_bytes = (1920 * 1080 * 4) as usize;
let mut data = Vec::<u8>::with_capacity(num_bytes);
data.resize(num_bytes, 0);
data
};
}
static mut frame_index: i64 = 0;
unsafe fn | () {
let cc = gl::get_capture_context(get_glx_proc_address);
cc.capture_frame();
let x: gl::GLint = 0;
let y: gl::GLint = 0;
let width: gl::GLsizei = 400;
let height: gl::GLsizei = 400;
let bytes_per_pixel: usize = 4;
let bytes_per_frame: usize = width as usize * height as usize * bytes_per_pixel;
let mut viewport = Vec::<gl::GLint>::with_capacity(4);
viewport.resize(4, 0);
cc.funcs
.glGetIntegerv(gl::GL_VIEWPORT, std::mem::transmute(viewport.as_ptr()));
info!("viewport: {:?}", viewport);
cc.funcs.glReadPixels(
x,
y,
width,
height,
gl::GL_RGBA,
gl::GL_UNSIGNED_BYTE,
std::mem::transmute(frame_buffer.as_ptr()),
);
let mut num_black = 0;
for y in 0..height {
for x in 0..width {
let i = (y * width + x) as usize;
let (r, g, b) = (
frame_buffer[i * 4],
frame_buffer[i * 4 + 1],
frame_buffer[i * 4 + 2],
);
if r == 0 && g == 0 && b == 0 {
num_black += 1;
}
}
}
info!("[frame {}] {} black pixels", frame_index, num_black);
frame_index += 1;
if frame_index < 200 {
use std::fs::File;
use std::io::prelude::*;
let name = format!("frame-{}x{}-{}.raw", width, height, frame_index);
let mut file = File::create(&name).unwrap();
file.write_all(&frame_buffer.as_slice()[..bytes_per_frame])
.unwrap();
info!("{} written", name)
}
}
| capture_gl_frame | identifier_name |
linux_gl_hooks.rs | #![cfg(target_os = "linux")]
#[link(name = "dl")]
extern "C" {}
use crate::gl;
use const_cstr::const_cstr;
use lazy_static::lazy_static;
use libc::{c_char, c_int, c_ulong, c_void};
use libc_print::libc_println;
use log::*;
use std::ffi::CString;
use std::sync::Once;
use std::time::SystemTime;
///////////////////////////////////////////
// libdl definition & link instructions
///////////////////////////////////////////
#[allow(unused)]
pub const RTLD_LAZY: c_int = 0x00001;
#[allow(unused)]
pub const RTLD_NOW: c_int = 0x00002;
#[allow(unused)]
pub const RTLD_NOLOAD: c_int = 0x0004;
#[allow(unused)]
pub const RTLD_DEFAULT: *const c_void = 0x00000 as *const c_void;
#[allow(unused)]
pub const RTLD_NEXT: *const c_void = (-1 as isize) as *const c_void;
extern "C" {
pub fn dlsym(handle: *const c_void, symbol: *const c_char) -> *const c_void;
pub fn dlclose(handle: *const c_void);
}
///////////////////////////////////////////
// lazily-opened libGL handle
///////////////////////////////////////////
struct LibHandle {
addr: *const c_void,
}
unsafe impl std::marker::Sync for LibHandle {}
lazy_static! {
static ref libGLHandle: LibHandle = {
use const_cstr::*;
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_LAZY);
if handle.is_null() {
panic!("could not dlopen libGL.so.1")
}
LibHandle { addr: handle }
};
}
///////////////////////////////////////////
// glXGetProcAddressARB wrapper
///////////////////////////////////////////
lazy_static! {
static ref glXGetProcAddressARB: unsafe extern "C" fn(name: *const c_char) -> *const c_void = unsafe {
let addr = dlsym(
libGLHandle.addr,
const_cstr!("glXGetProcAddressARB").as_ptr(),
);
if addr.is_null() {
panic!("libGL.so.1 does not contain glXGetProcAddressARB")
}
std::mem::transmute(addr)
};
}
unsafe fn get_glx_proc_address(rustName: &str) -> *const () {
let name = CString::new(rustName).unwrap();
let addr = glXGetProcAddressARB(name.as_ptr());
info!("glXGetProcAddressARB({}) = {:x}", rustName, addr as isize);
addr as *const ()
}
lazy_static! {
static ref startTime: SystemTime = SystemTime::now();
}
///////////////////////////////////////////
// dlopen hook
///////////////////////////////////////////
hook_ld! {
"dl" => fn dlopen(filename: *const c_char, flags: c_int) -> *const c_void {
let res = dlopen::next(filename, flags);
hook_if_needed();
res
}
}
///////////////////////////////////////////
// glXSwapBuffers hook
///////////////////////////////////////////
hook_dynamic! {
get_glx_proc_address => {
fn glXSwapBuffers(display: *const c_void, drawable: c_ulong) -> () {
if super::SETTINGS.in_test && display == 0xDEADBEEF as *const c_void {
libc_println!("caught dead beef");
std::process::exit(0);
}
info!(
"[{:08}] swapping buffers! (display=0x{:X}, drawable=0x{:X})",
startTime.elapsed().unwrap().as_millis(),
display as isize,
drawable as isize
);
capture_gl_frame();
glXSwapBuffers::next(display, drawable)
}
fn glXQueryVersion(display: *const c_void, major: *mut c_int, minor: *mut c_int) -> c_int {
// useless hook, just here to demonstrate we can do multiple hooks if needed
let ret = glXQueryVersion::next(display, major, minor);
if ret == 1 {
info!("GLX server version {}.{}", *major, *minor);
}
ret
}
}
}
/// Returns true if libGL.so.1 was loaded in this process,
/// either by ld-linux on startup (if linked with -lGL),
/// or by dlopen() afterwards.
unsafe fn is_using_opengl() -> bool {
// RTLD_NOLOAD lets us check if a library is already loaded.
// FIXME: we actually do need to call dlclose here, apparently
// modules are reference-counted.
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY);
let using = !handle.is_null();
if using |
using
}
static HOOK_SWAPBUFFERS_ONCE: Once = Once::new();
/// If libGL.so.1 was loaded, and only once in the lifetime
/// of this process, hook libGL functions for libcapsule usage.
unsafe fn hook_if_needed() {
if is_using_opengl() {
HOOK_SWAPBUFFERS_ONCE.call_once(|| {
info!("libGL usage detected, hooking OpenGL");
glXSwapBuffers::enable_hook();
glXQueryVersion::enable_hook();
})
}
}
pub fn initialize() {
unsafe { hook_if_needed() }
}
lazy_static! {
static ref frame_buffer: Vec<u8> = {
let num_bytes = (1920 * 1080 * 4) as usize;
let mut data = Vec::<u8>::with_capacity(num_bytes);
data.resize(num_bytes, 0);
data
};
}
static mut frame_index: i64 = 0;
unsafe fn capture_gl_frame() {
let cc = gl::get_capture_context(get_glx_proc_address);
cc.capture_frame();
let x: gl::GLint = 0;
let y: gl::GLint = 0;
let width: gl::GLsizei = 400;
let height: gl::GLsizei = 400;
let bytes_per_pixel: usize = 4;
let bytes_per_frame: usize = width as usize * height as usize * bytes_per_pixel;
let mut viewport = Vec::<gl::GLint>::with_capacity(4);
viewport.resize(4, 0);
cc.funcs
.glGetIntegerv(gl::GL_VIEWPORT, std::mem::transmute(viewport.as_ptr()));
info!("viewport: {:?}", viewport);
cc.funcs.glReadPixels(
x,
y,
width,
height,
gl::GL_RGBA,
gl::GL_UNSIGNED_BYTE,
std::mem::transmute(frame_buffer.as_ptr()),
);
let mut num_black = 0;
for y in 0..height {
for x in 0..width {
let i = (y * width + x) as usize;
let (r, g, b) = (
frame_buffer[i * 4],
frame_buffer[i * 4 + 1],
frame_buffer[i * 4 + 2],
);
if r == 0 && g == 0 && b == 0 {
num_black += 1;
}
}
}
info!("[frame {}] {} black pixels", frame_index, num_black);
frame_index += 1;
if frame_index < 200 {
use std::fs::File;
use std::io::prelude::*;
let name = format!("frame-{}x{}-{}.raw", width, height, frame_index);
let mut file = File::create(&name).unwrap();
file.write_all(&frame_buffer.as_slice()[..bytes_per_frame])
.unwrap();
info!("{} written", name)
}
}
| {
dlclose(handle);
} | conditional_block |
linux_gl_hooks.rs | #![cfg(target_os = "linux")]
#[link(name = "dl")]
extern "C" {}
use crate::gl;
use const_cstr::const_cstr;
use lazy_static::lazy_static;
use libc::{c_char, c_int, c_ulong, c_void};
use libc_print::libc_println;
use log::*;
use std::ffi::CString;
use std::sync::Once;
use std::time::SystemTime;
///////////////////////////////////////////
// libdl definition & link instructions
///////////////////////////////////////////
#[allow(unused)]
pub const RTLD_LAZY: c_int = 0x00001;
#[allow(unused)]
pub const RTLD_NOW: c_int = 0x00002;
#[allow(unused)]
pub const RTLD_NOLOAD: c_int = 0x0004;
#[allow(unused)]
pub const RTLD_DEFAULT: *const c_void = 0x00000 as *const c_void;
#[allow(unused)]
pub const RTLD_NEXT: *const c_void = (-1 as isize) as *const c_void;
extern "C" {
pub fn dlsym(handle: *const c_void, symbol: *const c_char) -> *const c_void;
pub fn dlclose(handle: *const c_void);
}
///////////////////////////////////////////
// lazily-opened libGL handle
///////////////////////////////////////////
struct LibHandle {
addr: *const c_void,
}
unsafe impl std::marker::Sync for LibHandle {}
lazy_static! {
static ref libGLHandle: LibHandle = {
use const_cstr::*;
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_LAZY);
if handle.is_null() {
panic!("could not dlopen libGL.so.1")
}
LibHandle { addr: handle }
};
}
///////////////////////////////////////////
// glXGetProcAddressARB wrapper
///////////////////////////////////////////
lazy_static! {
static ref glXGetProcAddressARB: unsafe extern "C" fn(name: *const c_char) -> *const c_void = unsafe {
let addr = dlsym(
libGLHandle.addr,
const_cstr!("glXGetProcAddressARB").as_ptr(),
);
if addr.is_null() {
panic!("libGL.so.1 does not contain glXGetProcAddressARB")
}
std::mem::transmute(addr)
};
}
unsafe fn get_glx_proc_address(rustName: &str) -> *const () {
let name = CString::new(rustName).unwrap();
let addr = glXGetProcAddressARB(name.as_ptr());
info!("glXGetProcAddressARB({}) = {:x}", rustName, addr as isize);
addr as *const ()
}
lazy_static! {
static ref startTime: SystemTime = SystemTime::now();
}
///////////////////////////////////////////
// dlopen hook
///////////////////////////////////////////
hook_ld! {
"dl" => fn dlopen(filename: *const c_char, flags: c_int) -> *const c_void {
let res = dlopen::next(filename, flags);
hook_if_needed();
res
}
}
///////////////////////////////////////////
// glXSwapBuffers hook
///////////////////////////////////////////
hook_dynamic! {
get_glx_proc_address => {
fn glXSwapBuffers(display: *const c_void, drawable: c_ulong) -> () {
if super::SETTINGS.in_test && display == 0xDEADBEEF as *const c_void {
libc_println!("caught dead beef");
std::process::exit(0);
}
info!(
"[{:08}] swapping buffers! (display=0x{:X}, drawable=0x{:X})",
startTime.elapsed().unwrap().as_millis(),
display as isize,
drawable as isize
);
capture_gl_frame();
glXSwapBuffers::next(display, drawable)
}
fn glXQueryVersion(display: *const c_void, major: *mut c_int, minor: *mut c_int) -> c_int {
// useless hook, just here to demonstrate we can do multiple hooks if needed
let ret = glXQueryVersion::next(display, major, minor);
if ret == 1 {
info!("GLX server version {}.{}", *major, *minor);
}
ret
}
}
}
/// Returns true if libGL.so.1 was loaded in this process,
/// either by ld-linux on startup (if linked with -lGL),
/// or by dlopen() afterwards.
unsafe fn is_using_opengl() -> bool {
// RTLD_NOLOAD lets us check if a library is already loaded.
// FIXME: we actually do need to call dlclose here, apparently | let using = !handle.is_null();
if using {
dlclose(handle);
}
using
}
static HOOK_SWAPBUFFERS_ONCE: Once = Once::new();
/// If libGL.so.1 was loaded, and only once in the lifetime
/// of this process, hook libGL functions for libcapsule usage.
unsafe fn hook_if_needed() {
if is_using_opengl() {
HOOK_SWAPBUFFERS_ONCE.call_once(|| {
info!("libGL usage detected, hooking OpenGL");
glXSwapBuffers::enable_hook();
glXQueryVersion::enable_hook();
})
}
}
pub fn initialize() {
unsafe { hook_if_needed() }
}
lazy_static! {
static ref frame_buffer: Vec<u8> = {
let num_bytes = (1920 * 1080 * 4) as usize;
let mut data = Vec::<u8>::with_capacity(num_bytes);
data.resize(num_bytes, 0);
data
};
}
static mut frame_index: i64 = 0;
unsafe fn capture_gl_frame() {
let cc = gl::get_capture_context(get_glx_proc_address);
cc.capture_frame();
let x: gl::GLint = 0;
let y: gl::GLint = 0;
let width: gl::GLsizei = 400;
let height: gl::GLsizei = 400;
let bytes_per_pixel: usize = 4;
let bytes_per_frame: usize = width as usize * height as usize * bytes_per_pixel;
let mut viewport = Vec::<gl::GLint>::with_capacity(4);
viewport.resize(4, 0);
cc.funcs
.glGetIntegerv(gl::GL_VIEWPORT, std::mem::transmute(viewport.as_ptr()));
info!("viewport: {:?}", viewport);
cc.funcs.glReadPixels(
x,
y,
width,
height,
gl::GL_RGBA,
gl::GL_UNSIGNED_BYTE,
std::mem::transmute(frame_buffer.as_ptr()),
);
let mut num_black = 0;
for y in 0..height {
for x in 0..width {
let i = (y * width + x) as usize;
let (r, g, b) = (
frame_buffer[i * 4],
frame_buffer[i * 4 + 1],
frame_buffer[i * 4 + 2],
);
if r == 0 && g == 0 && b == 0 {
num_black += 1;
}
}
}
info!("[frame {}] {} black pixels", frame_index, num_black);
frame_index += 1;
if frame_index < 200 {
use std::fs::File;
use std::io::prelude::*;
let name = format!("frame-{}x{}-{}.raw", width, height, frame_index);
let mut file = File::create(&name).unwrap();
file.write_all(&frame_buffer.as_slice()[..bytes_per_frame])
.unwrap();
info!("{} written", name)
}
} | // modules are reference-counted.
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY); | random_line_split |
pseudo_element.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.
use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;
include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
impl ::selectors::parser::PseudoElement for PseudoElement {
type Impl = SelectorImpl;
fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool |
}
impl PseudoElement {
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn cascade_type(&self) -> PseudoElementCascadeType {
if self.is_eager() {
debug_assert!(!self.is_anon_box());
return PseudoElementCascadeType::Eager
}
if self.is_precomputed() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
/// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element.
///
/// This is not the common thing, but there are some pseudos (namely:
/// ::backdrop), that shouldn't inherit from the parent element.
pub fn inherits_from_default_values(&self) -> bool {
matches!(*self, PseudoElement::Backdrop)
}
/// Gets the canonical index of this eagerly-cascaded pseudo-element.
#[inline]
pub fn eager_index(&self) -> usize {
EAGER_PSEUDOS.iter().position(|p| p == self)
.expect("Not an eager pseudo")
}
/// Creates a pseudo-element from an eager index.
#[inline]
pub fn from_eager_index(i: usize) -> Self {
EAGER_PSEUDOS[i].clone()
}
/// Whether the current pseudo element is ::before or ::after.
#[inline]
pub fn is_before_or_after(&self) -> bool {
self.is_before() || self.is_after()
}
/// Whether this pseudo-element is the ::before pseudo.
#[inline]
pub fn is_before(&self) -> bool {
*self == PseudoElement::Before
}
/// Whether this pseudo-element is the ::after pseudo.
#[inline]
pub fn is_after(&self) -> bool {
*self == PseudoElement::After
}
/// Whether this pseudo-element is ::first-letter.
#[inline]
pub fn is_first_letter(&self) -> bool {
*self == PseudoElement::FirstLetter
}
/// Whether this pseudo-element is ::first-line.
#[inline]
pub fn is_first_line(&self) -> bool {
*self == PseudoElement::FirstLine
}
/// Whether this pseudo-element is ::-moz-fieldset-content.
#[inline]
pub fn is_fieldset_content(&self) -> bool {
*self == PseudoElement::FieldsetContent
}
/// Whether this pseudo-element is lazily-cascaded.
#[inline]
pub fn is_lazy(&self) -> bool {
!self.is_eager() && !self.is_precomputed()
}
/// Whether this pseudo-element is web-exposed.
pub fn exposed_in_non_ua_sheets(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
}
/// Whether this pseudo-element supports user action selectors.
pub fn supports_user_action_state(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
}
/// Whether this pseudo-element skips flex/grid container display-based
/// fixup.
#[inline]
pub fn skip_item_based_display_fixup(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
}
/// Whether this pseudo-element is precomputed.
#[inline]
pub fn is_precomputed(&self) -> bool {
self.is_anon_box() && !self.is_tree_pseudo_element()
}
/// Covert non-canonical pseudo-element to canonical one, and keep a
/// canonical one as it is.
pub fn canonical(&self) -> PseudoElement {
match *self {
PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
_ => self.clone(),
}
}
/// Property flag that properties must have to apply to this pseudo-element.
#[inline]
pub fn property_restriction(&self) -> Option<PropertyFlags> {
match *self {
PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
_ => None,
}
}
/// Whether this pseudo-element should actually exist if it has
/// the given styles.
pub fn should_exist(&self, style: &ComputedValues) -> bool
{
let display = style.get_box().clone_display();
if display == display::T::none {
return false;
}
if self.is_before_or_after() && style.ineffective_content_property() {
return false;
}
true
}
}
| {
if !self.supports_user_action_state() {
return false;
}
return pseudo_class.is_safe_user_action_state();
} | identifier_body |
pseudo_element.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.
use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;
include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
impl ::selectors::parser::PseudoElement for PseudoElement {
type Impl = SelectorImpl;
fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
if !self.supports_user_action_state() {
return false;
}
return pseudo_class.is_safe_user_action_state();
}
}
impl PseudoElement {
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed | pub fn cascade_type(&self) -> PseudoElementCascadeType {
if self.is_eager() {
debug_assert!(!self.is_anon_box());
return PseudoElementCascadeType::Eager
}
if self.is_precomputed() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
/// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element.
///
/// This is not the common thing, but there are some pseudos (namely:
/// ::backdrop), that shouldn't inherit from the parent element.
pub fn inherits_from_default_values(&self) -> bool {
matches!(*self, PseudoElement::Backdrop)
}
/// Gets the canonical index of this eagerly-cascaded pseudo-element.
#[inline]
pub fn eager_index(&self) -> usize {
EAGER_PSEUDOS.iter().position(|p| p == self)
.expect("Not an eager pseudo")
}
/// Creates a pseudo-element from an eager index.
#[inline]
pub fn from_eager_index(i: usize) -> Self {
EAGER_PSEUDOS[i].clone()
}
/// Whether the current pseudo element is ::before or ::after.
#[inline]
pub fn is_before_or_after(&self) -> bool {
self.is_before() || self.is_after()
}
/// Whether this pseudo-element is the ::before pseudo.
#[inline]
pub fn is_before(&self) -> bool {
*self == PseudoElement::Before
}
/// Whether this pseudo-element is the ::after pseudo.
#[inline]
pub fn is_after(&self) -> bool {
*self == PseudoElement::After
}
/// Whether this pseudo-element is ::first-letter.
#[inline]
pub fn is_first_letter(&self) -> bool {
*self == PseudoElement::FirstLetter
}
/// Whether this pseudo-element is ::first-line.
#[inline]
pub fn is_first_line(&self) -> bool {
*self == PseudoElement::FirstLine
}
/// Whether this pseudo-element is ::-moz-fieldset-content.
#[inline]
pub fn is_fieldset_content(&self) -> bool {
*self == PseudoElement::FieldsetContent
}
/// Whether this pseudo-element is lazily-cascaded.
#[inline]
pub fn is_lazy(&self) -> bool {
!self.is_eager() && !self.is_precomputed()
}
/// Whether this pseudo-element is web-exposed.
pub fn exposed_in_non_ua_sheets(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
}
/// Whether this pseudo-element supports user action selectors.
pub fn supports_user_action_state(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
}
/// Whether this pseudo-element skips flex/grid container display-based
/// fixup.
#[inline]
pub fn skip_item_based_display_fixup(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
}
/// Whether this pseudo-element is precomputed.
#[inline]
pub fn is_precomputed(&self) -> bool {
self.is_anon_box() && !self.is_tree_pseudo_element()
}
/// Covert non-canonical pseudo-element to canonical one, and keep a
/// canonical one as it is.
pub fn canonical(&self) -> PseudoElement {
match *self {
PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
_ => self.clone(),
}
}
/// Property flag that properties must have to apply to this pseudo-element.
#[inline]
pub fn property_restriction(&self) -> Option<PropertyFlags> {
match *self {
PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
_ => None,
}
}
/// Whether this pseudo-element should actually exist if it has
/// the given styles.
pub fn should_exist(&self, style: &ComputedValues) -> bool
{
let display = style.get_box().clone_display();
if display == display::T::none {
return false;
}
if self.is_before_or_after() && style.ineffective_content_property() {
return false;
}
true
}
} | /// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`. | random_line_split |
pseudo_element.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.
use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;
include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
impl ::selectors::parser::PseudoElement for PseudoElement {
type Impl = SelectorImpl;
fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
if !self.supports_user_action_state() {
return false;
}
return pseudo_class.is_safe_user_action_state();
}
}
impl PseudoElement {
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn cascade_type(&self) -> PseudoElementCascadeType {
if self.is_eager() {
debug_assert!(!self.is_anon_box());
return PseudoElementCascadeType::Eager
}
if self.is_precomputed() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
/// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element.
///
/// This is not the common thing, but there are some pseudos (namely:
/// ::backdrop), that shouldn't inherit from the parent element.
pub fn inherits_from_default_values(&self) -> bool {
matches!(*self, PseudoElement::Backdrop)
}
/// Gets the canonical index of this eagerly-cascaded pseudo-element.
#[inline]
pub fn eager_index(&self) -> usize {
EAGER_PSEUDOS.iter().position(|p| p == self)
.expect("Not an eager pseudo")
}
/// Creates a pseudo-element from an eager index.
#[inline]
pub fn from_eager_index(i: usize) -> Self {
EAGER_PSEUDOS[i].clone()
}
/// Whether the current pseudo element is ::before or ::after.
#[inline]
pub fn is_before_or_after(&self) -> bool {
self.is_before() || self.is_after()
}
/// Whether this pseudo-element is the ::before pseudo.
#[inline]
pub fn is_before(&self) -> bool {
*self == PseudoElement::Before
}
/// Whether this pseudo-element is the ::after pseudo.
#[inline]
pub fn is_after(&self) -> bool {
*self == PseudoElement::After
}
/// Whether this pseudo-element is ::first-letter.
#[inline]
pub fn is_first_letter(&self) -> bool {
*self == PseudoElement::FirstLetter
}
/// Whether this pseudo-element is ::first-line.
#[inline]
pub fn is_first_line(&self) -> bool {
*self == PseudoElement::FirstLine
}
/// Whether this pseudo-element is ::-moz-fieldset-content.
#[inline]
pub fn is_fieldset_content(&self) -> bool {
*self == PseudoElement::FieldsetContent
}
/// Whether this pseudo-element is lazily-cascaded.
#[inline]
pub fn is_lazy(&self) -> bool {
!self.is_eager() && !self.is_precomputed()
}
/// Whether this pseudo-element is web-exposed.
pub fn exposed_in_non_ua_sheets(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
}
/// Whether this pseudo-element supports user action selectors.
pub fn supports_user_action_state(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE) != 0
}
/// Whether this pseudo-element skips flex/grid container display-based
/// fixup.
#[inline]
pub fn | (&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
}
/// Whether this pseudo-element is precomputed.
#[inline]
pub fn is_precomputed(&self) -> bool {
self.is_anon_box() && !self.is_tree_pseudo_element()
}
/// Covert non-canonical pseudo-element to canonical one, and keep a
/// canonical one as it is.
pub fn canonical(&self) -> PseudoElement {
match *self {
PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
_ => self.clone(),
}
}
/// Property flag that properties must have to apply to this pseudo-element.
#[inline]
pub fn property_restriction(&self) -> Option<PropertyFlags> {
match *self {
PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
_ => None,
}
}
/// Whether this pseudo-element should actually exist if it has
/// the given styles.
pub fn should_exist(&self, style: &ComputedValues) -> bool
{
let display = style.get_box().clone_display();
if display == display::T::none {
return false;
}
if self.is_before_or_after() && style.ineffective_content_property() {
return false;
}
true
}
}
| skip_item_based_display_fixup | identifier_name |
control_slider.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/yeison/Documentos/python/developing/pinguino/pinguino-ide/qtgui/gide/bloques/widgets/control_slider.ui'
#
# Created: Wed Mar 4 01:39:58 2015
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Frame(object):
| def setupUi(self, Frame):
Frame.setObjectName("Frame")
Frame.resize(237, 36)
Frame.setWindowTitle("")
self.gridLayout = QtGui.QGridLayout(Frame)
self.gridLayout.setSpacing(0)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.lineEdit_2 = QtGui.QLineEdit(Frame)
self.lineEdit_2.setMaximumSize(QtCore.QSize(46, 16777215))
font = QtGui.QFont()
font.setFamily("Ubuntu Mono")
font.setPointSize(15)
font.setWeight(75)
font.setBold(True)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.lineEdit_2.setText("0000")
self.lineEdit_2.setFrame(False)
self.lineEdit_2.setReadOnly(True)
self.lineEdit_2.setObjectName("lineEdit_2")
self.gridLayout.addWidget(self.lineEdit_2, 0, 1, 1, 1)
self.horizontalSlider = QtGui.QSlider(Frame)
self.horizontalSlider.setCursor(QtCore.Qt.PointingHandCursor)
self.horizontalSlider.setFocusPolicy(QtCore.Qt.NoFocus)
self.horizontalSlider.setMaximum(1023)
self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider.setInvertedAppearance(False)
self.horizontalSlider.setTickPosition(QtGui.QSlider.NoTicks)
self.horizontalSlider.setTickInterval(128)
self.horizontalSlider.setObjectName("horizontalSlider")
self.gridLayout.addWidget(self.horizontalSlider, 0, 2, 1, 1)
self.retranslateUi(Frame)
QtCore.QMetaObject.connectSlotsByName(Frame)
def retranslateUi(self, Frame):
pass | identifier_body | |
control_slider.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/yeison/Documentos/python/developing/pinguino/pinguino-ide/qtgui/gide/bloques/widgets/control_slider.ui'
#
# Created: Wed Mar 4 01:39:58 2015
# by: pyside-uic 0.2.15 running on PySide 1.2.2
# | def setupUi(self, Frame):
Frame.setObjectName("Frame")
Frame.resize(237, 36)
Frame.setWindowTitle("")
self.gridLayout = QtGui.QGridLayout(Frame)
self.gridLayout.setSpacing(0)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.lineEdit_2 = QtGui.QLineEdit(Frame)
self.lineEdit_2.setMaximumSize(QtCore.QSize(46, 16777215))
font = QtGui.QFont()
font.setFamily("Ubuntu Mono")
font.setPointSize(15)
font.setWeight(75)
font.setBold(True)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.lineEdit_2.setText("0000")
self.lineEdit_2.setFrame(False)
self.lineEdit_2.setReadOnly(True)
self.lineEdit_2.setObjectName("lineEdit_2")
self.gridLayout.addWidget(self.lineEdit_2, 0, 1, 1, 1)
self.horizontalSlider = QtGui.QSlider(Frame)
self.horizontalSlider.setCursor(QtCore.Qt.PointingHandCursor)
self.horizontalSlider.setFocusPolicy(QtCore.Qt.NoFocus)
self.horizontalSlider.setMaximum(1023)
self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider.setInvertedAppearance(False)
self.horizontalSlider.setTickPosition(QtGui.QSlider.NoTicks)
self.horizontalSlider.setTickInterval(128)
self.horizontalSlider.setObjectName("horizontalSlider")
self.gridLayout.addWidget(self.horizontalSlider, 0, 2, 1, 1)
self.retranslateUi(Frame)
QtCore.QMetaObject.connectSlotsByName(Frame)
def retranslateUi(self, Frame):
pass | # WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Frame(object): | random_line_split |
control_slider.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/yeison/Documentos/python/developing/pinguino/pinguino-ide/qtgui/gide/bloques/widgets/control_slider.ui'
#
# Created: Wed Mar 4 01:39:58 2015
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Frame(object):
def | (self, Frame):
Frame.setObjectName("Frame")
Frame.resize(237, 36)
Frame.setWindowTitle("")
self.gridLayout = QtGui.QGridLayout(Frame)
self.gridLayout.setSpacing(0)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.lineEdit_2 = QtGui.QLineEdit(Frame)
self.lineEdit_2.setMaximumSize(QtCore.QSize(46, 16777215))
font = QtGui.QFont()
font.setFamily("Ubuntu Mono")
font.setPointSize(15)
font.setWeight(75)
font.setBold(True)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.lineEdit_2.setText("0000")
self.lineEdit_2.setFrame(False)
self.lineEdit_2.setReadOnly(True)
self.lineEdit_2.setObjectName("lineEdit_2")
self.gridLayout.addWidget(self.lineEdit_2, 0, 1, 1, 1)
self.horizontalSlider = QtGui.QSlider(Frame)
self.horizontalSlider.setCursor(QtCore.Qt.PointingHandCursor)
self.horizontalSlider.setFocusPolicy(QtCore.Qt.NoFocus)
self.horizontalSlider.setMaximum(1023)
self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider.setInvertedAppearance(False)
self.horizontalSlider.setTickPosition(QtGui.QSlider.NoTicks)
self.horizontalSlider.setTickInterval(128)
self.horizontalSlider.setObjectName("horizontalSlider")
self.gridLayout.addWidget(self.horizontalSlider, 0, 2, 1, 1)
self.retranslateUi(Frame)
QtCore.QMetaObject.connectSlotsByName(Frame)
def retranslateUi(self, Frame):
pass
| setupUi | identifier_name |
dynamic_form.js | $( document ).ready( function()
{
'use strict';
function validateEmail (email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateInput (str) {
if (str === null || str === '' || str === undefined)
return false;
return true;
}
function validatePassword (str) {
if (str.length < 8)
return false;
return true;
}
function addError (msg, type) |
function init() {
$('form[data-dynamic_form]').bind('keypress', function (e) {
if(e.keyCode == 13)
return false;
});
// Handles the signin process, basic validation
$('form#new_user').on('submit', function () {
var email = $('input#user_email').val();
var password_confirmation = $('input#user_password_confirmation').val();
var password = $('input#user_password').val();
var errors = true;
$('#email-error,#password-error').remove();
if ($('input[data-req-msg]').length > 0 && $('input#user_password').length > 0 && !validateInput(password)) {
var msg = $('input#user_password').attr('data-req-msg');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-pwd-short]').length > 0 && $('input#user_password_confirmation').length > 0 && errors && !validatePassword(password)) {
var msg = $('input#user_password').attr('data-pwd-short');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-pwd-match]').length > 0 && $('input#user_password_confirmation').length > 0 && password != password_confirmation) {
var msg = $('input#user_password_confirmation').attr('data-pwd-match');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-email-valid]').length > 0 &&!validateEmail(email)) {
var msg = $('input#user_email').attr('data-email-valid');
addError(msg, 'email-error');
errors = false;
}
return errors;
});
$('[data-dynamic_form]' ).find('input[name],select[name]').on( 'change', function() {
var form = $(this).parents('[data-dynamic_form]'),
url = form.data( 'dynamic_form' ),
page = window.location.href.split('/')[window.location.href.split('/').length-1];
form.ajaxSubmit( { url:url, success:function( result ) {
form.trigger( 'ajax_submit', result );
}});
});
}
init();
});
| {
$('<div class="standalone_form--message" id="' + type+ '">' + msg + '</div>').insertAfter('.standalone_form--heading');
} | identifier_body |
dynamic_form.js | $( document ).ready( function()
{
'use strict';
function validateEmail (email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateInput (str) {
if (str === null || str === '' || str === undefined)
return false;
return true;
}
function validatePassword (str) {
if (str.length < 8)
return false;
return true;
}
function addError (msg, type) {
$('<div class="standalone_form--message" id="' + type+ '">' + msg + '</div>').insertAfter('.standalone_form--heading');
}
function init() {
$('form[data-dynamic_form]').bind('keypress', function (e) {
if(e.keyCode == 13)
return false;
});
// Handles the signin process, basic validation
$('form#new_user').on('submit', function () {
var email = $('input#user_email').val();
var password_confirmation = $('input#user_password_confirmation').val();
var password = $('input#user_password').val();
var errors = true;
$('#email-error,#password-error').remove();
if ($('input[data-req-msg]').length > 0 && $('input#user_password').length > 0 && !validateInput(password)) |
if ($('input[data-pwd-short]').length > 0 && $('input#user_password_confirmation').length > 0 && errors && !validatePassword(password)) {
var msg = $('input#user_password').attr('data-pwd-short');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-pwd-match]').length > 0 && $('input#user_password_confirmation').length > 0 && password != password_confirmation) {
var msg = $('input#user_password_confirmation').attr('data-pwd-match');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-email-valid]').length > 0 &&!validateEmail(email)) {
var msg = $('input#user_email').attr('data-email-valid');
addError(msg, 'email-error');
errors = false;
}
return errors;
});
$('[data-dynamic_form]' ).find('input[name],select[name]').on( 'change', function() {
var form = $(this).parents('[data-dynamic_form]'),
url = form.data( 'dynamic_form' ),
page = window.location.href.split('/')[window.location.href.split('/').length-1];
form.ajaxSubmit( { url:url, success:function( result ) {
form.trigger( 'ajax_submit', result );
}});
});
}
init();
});
| {
var msg = $('input#user_password').attr('data-req-msg');
addError(msg, 'password-error');
errors = false;
} | conditional_block |
dynamic_form.js | $( document ).ready( function()
{
'use strict';
function validateEmail (email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateInput (str) {
if (str === null || str === '' || str === undefined)
return false;
return true;
}
function validatePassword (str) {
if (str.length < 8)
return false;
return true;
}
function | (msg, type) {
$('<div class="standalone_form--message" id="' + type+ '">' + msg + '</div>').insertAfter('.standalone_form--heading');
}
function init() {
$('form[data-dynamic_form]').bind('keypress', function (e) {
if(e.keyCode == 13)
return false;
});
// Handles the signin process, basic validation
$('form#new_user').on('submit', function () {
var email = $('input#user_email').val();
var password_confirmation = $('input#user_password_confirmation').val();
var password = $('input#user_password').val();
var errors = true;
$('#email-error,#password-error').remove();
if ($('input[data-req-msg]').length > 0 && $('input#user_password').length > 0 && !validateInput(password)) {
var msg = $('input#user_password').attr('data-req-msg');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-pwd-short]').length > 0 && $('input#user_password_confirmation').length > 0 && errors && !validatePassword(password)) {
var msg = $('input#user_password').attr('data-pwd-short');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-pwd-match]').length > 0 && $('input#user_password_confirmation').length > 0 && password != password_confirmation) {
var msg = $('input#user_password_confirmation').attr('data-pwd-match');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-email-valid]').length > 0 &&!validateEmail(email)) {
var msg = $('input#user_email').attr('data-email-valid');
addError(msg, 'email-error');
errors = false;
}
return errors;
});
$('[data-dynamic_form]' ).find('input[name],select[name]').on( 'change', function() {
var form = $(this).parents('[data-dynamic_form]'),
url = form.data( 'dynamic_form' ),
page = window.location.href.split('/')[window.location.href.split('/').length-1];
form.ajaxSubmit( { url:url, success:function( result ) {
form.trigger( 'ajax_submit', result );
}});
});
}
init();
});
| addError | identifier_name |
dynamic_form.js | $( document ).ready( function()
{
'use strict';
function validateEmail (email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateInput (str) {
if (str === null || str === '' || str === undefined)
return false;
return true;
}
function validatePassword (str) {
if (str.length < 8)
return false;
return true;
}
function addError (msg, type) {
$('<div class="standalone_form--message" id="' + type+ '">' + msg + '</div>').insertAfter('.standalone_form--heading');
}
function init() {
$('form[data-dynamic_form]').bind('keypress', function (e) {
if(e.keyCode == 13)
return false;
});
// Handles the signin process, basic validation
$('form#new_user').on('submit', function () {
var email = $('input#user_email').val();
var password_confirmation = $('input#user_password_confirmation').val();
var password = $('input#user_password').val();
var errors = true;
$('#email-error,#password-error').remove();
if ($('input[data-req-msg]').length > 0 && $('input#user_password').length > 0 && !validateInput(password)) {
var msg = $('input#user_password').attr('data-req-msg');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-pwd-short]').length > 0 && $('input#user_password_confirmation').length > 0 && errors && !validatePassword(password)) {
var msg = $('input#user_password').attr('data-pwd-short');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-pwd-match]').length > 0 && $('input#user_password_confirmation').length > 0 && password != password_confirmation) {
var msg = $('input#user_password_confirmation').attr('data-pwd-match');
addError(msg, 'password-error');
errors = false;
}
if ($('input[data-email-valid]').length > 0 &&!validateEmail(email)) {
var msg = $('input#user_email').attr('data-email-valid'); | errors = false;
}
return errors;
});
$('[data-dynamic_form]' ).find('input[name],select[name]').on( 'change', function() {
var form = $(this).parents('[data-dynamic_form]'),
url = form.data( 'dynamic_form' ),
page = window.location.href.split('/')[window.location.href.split('/').length-1];
form.ajaxSubmit( { url:url, success:function( result ) {
form.trigger( 'ajax_submit', result );
}});
});
}
init();
}); | addError(msg, 'email-error'); | random_line_split |
pmc__utils_8c.js | var pmc__utils_8c =
[
[ "char_replace", "pmc__utils_8c.html#aafd74bb6564c3c3c057175e5b7973fec", null ],
[ "cmp_float", "pmc__utils_8c.html#a7051d2192267dcba608e4720c7b0187c", null ],
[ "cmp_int32", "pmc__utils_8c.html#ad08429d28a59ccf2ac45c0f54a16c323", null ],
[ "error", "pmc__utils_8c.html#a7e15c8e2885871839fc2b820dfbdb4ce", null ],
[ "estimate_sample", "pmc__utils_8c.html#a9ad8ffa0feaf3ed31f6f636831aba2fc", null ],
[ "file_load", "pmc__utils_8c.html#aa976c6b19d9185f24efdb2873cef0e50", null ],
[ "find_ind_float", "pmc__utils_8c.html#a3c775eb4a5014b61b83e2ad2244b58dd", null ],
[ "find_ind_int64", "pmc__utils_8c.html#aa57936e71de3e8889a77b2930256f983", null ], | [ "find_new_el", "pmc__utils_8c.html#a0fac58c8eda4e3ec6634f2273d6db252", null ],
[ "print_rules", "pmc__utils_8c.html#ac0dfe064e97b8cbcb1ecfbc4355c15ac", null ],
[ "read_line", "pmc__utils_8c.html#a777131faf4806e7eee788b65cab4a584", null ],
[ "shift_char_p", "pmc__utils_8c.html#a3409419eecfac258ec7f1fb6c40aff88", null ]
]; | [ "find_n_el", "pmc__utils_8c.html#a00060354a866563dd8b9df73eb3899c3", null ], | random_line_split |
tests_params.py | #!/usr/bin/env python2.7
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#Reference
#https://docs.python.org/2/library/unittest.html
#http://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases
#public domain license reference: http://eli.thegreenplace.net/pages/code
#Run
#python tika/tests/tests_params.py
import csv
import unittest
import tika.parser
class CreateTest(unittest.TestCase):
"test for file types"
def __init__(self, methodName='runTest', param1=None, param2=None):
super(CreateTest, self).__init__(methodName)
self.param1 = param1
@staticmethod
def parameterize(test_case, param1=None, param2=None):
testloader = unittest.TestLoader()
testnames = testloader.getTestCaseNames(test_case)
suite = unittest.TestSuite()
for name in testnames:
|
return suite
class RemoteTest(CreateTest):
def setUp(self):
self.param1 = tika.parser.from_file(self.param1)
def test_true(self):
self.assertTrue(self.param1)
def test_meta(self):
self.assertTrue(self.param1['metadata'])
def test_content(self):
self.assertTrue(self.param1['content'])
def test_url():
with open('tika/tests/arguments/test_remote_content.csv', 'r') as csvfile:
urlread = csv.reader(csvfile)
for url in urlread:
yield url[1]
if __name__ == '__main__':
suite = unittest.TestSuite()
t_urls = list(test_url())
t_urls.pop(0) #remove header
for x in t_urls:
try:
suite.addTest(CreateTest.parameterize(RemoteTest,param1=x))
except IOError as e:
print(e.strerror)
unittest.TextTestRunner(verbosity=2).run(suite) | suite.addTest(test_case(name, param1=param1, param2=param2)) | conditional_block |
tests_params.py | #!/usr/bin/env python2.7
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#Reference
#https://docs.python.org/2/library/unittest.html
#http://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases
#public domain license reference: http://eli.thegreenplace.net/pages/code
#Run
#python tika/tests/tests_params.py
import csv
import unittest
import tika.parser
class CreateTest(unittest.TestCase):
"test for file types"
def | (self, methodName='runTest', param1=None, param2=None):
super(CreateTest, self).__init__(methodName)
self.param1 = param1
@staticmethod
def parameterize(test_case, param1=None, param2=None):
testloader = unittest.TestLoader()
testnames = testloader.getTestCaseNames(test_case)
suite = unittest.TestSuite()
for name in testnames:
suite.addTest(test_case(name, param1=param1, param2=param2))
return suite
class RemoteTest(CreateTest):
def setUp(self):
self.param1 = tika.parser.from_file(self.param1)
def test_true(self):
self.assertTrue(self.param1)
def test_meta(self):
self.assertTrue(self.param1['metadata'])
def test_content(self):
self.assertTrue(self.param1['content'])
def test_url():
with open('tika/tests/arguments/test_remote_content.csv', 'r') as csvfile:
urlread = csv.reader(csvfile)
for url in urlread:
yield url[1]
if __name__ == '__main__':
suite = unittest.TestSuite()
t_urls = list(test_url())
t_urls.pop(0) #remove header
for x in t_urls:
try:
suite.addTest(CreateTest.parameterize(RemoteTest,param1=x))
except IOError as e:
print(e.strerror)
unittest.TextTestRunner(verbosity=2).run(suite) | __init__ | identifier_name |
tests_params.py | #!/usr/bin/env python2.7
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#Reference
#https://docs.python.org/2/library/unittest.html
#http://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases
#public domain license reference: http://eli.thegreenplace.net/pages/code
#Run
#python tika/tests/tests_params.py
import csv
import unittest
import tika.parser
class CreateTest(unittest.TestCase):
"test for file types"
def __init__(self, methodName='runTest', param1=None, param2=None):
super(CreateTest, self).__init__(methodName)
self.param1 = param1
@staticmethod
def parameterize(test_case, param1=None, param2=None):
testloader = unittest.TestLoader()
testnames = testloader.getTestCaseNames(test_case)
suite = unittest.TestSuite()
for name in testnames:
suite.addTest(test_case(name, param1=param1, param2=param2))
return suite
class RemoteTest(CreateTest):
def setUp(self):
self.param1 = tika.parser.from_file(self.param1)
def test_true(self):
self.assertTrue(self.param1)
def test_meta(self):
self.assertTrue(self.param1['metadata'])
def test_content(self):
self.assertTrue(self.param1['content'])
def test_url():
with open('tika/tests/arguments/test_remote_content.csv', 'r') as csvfile:
urlread = csv.reader(csvfile)
for url in urlread:
yield url[1]
if __name__ == '__main__':
suite = unittest.TestSuite() | try:
suite.addTest(CreateTest.parameterize(RemoteTest,param1=x))
except IOError as e:
print(e.strerror)
unittest.TextTestRunner(verbosity=2).run(suite) | t_urls = list(test_url())
t_urls.pop(0) #remove header
for x in t_urls: | random_line_split |
tests_params.py | #!/usr/bin/env python2.7
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#Reference
#https://docs.python.org/2/library/unittest.html
#http://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases
#public domain license reference: http://eli.thegreenplace.net/pages/code
#Run
#python tika/tests/tests_params.py
import csv
import unittest
import tika.parser
class CreateTest(unittest.TestCase):
"test for file types"
def __init__(self, methodName='runTest', param1=None, param2=None):
|
@staticmethod
def parameterize(test_case, param1=None, param2=None):
testloader = unittest.TestLoader()
testnames = testloader.getTestCaseNames(test_case)
suite = unittest.TestSuite()
for name in testnames:
suite.addTest(test_case(name, param1=param1, param2=param2))
return suite
class RemoteTest(CreateTest):
def setUp(self):
self.param1 = tika.parser.from_file(self.param1)
def test_true(self):
self.assertTrue(self.param1)
def test_meta(self):
self.assertTrue(self.param1['metadata'])
def test_content(self):
self.assertTrue(self.param1['content'])
def test_url():
with open('tika/tests/arguments/test_remote_content.csv', 'r') as csvfile:
urlread = csv.reader(csvfile)
for url in urlread:
yield url[1]
if __name__ == '__main__':
suite = unittest.TestSuite()
t_urls = list(test_url())
t_urls.pop(0) #remove header
for x in t_urls:
try:
suite.addTest(CreateTest.parameterize(RemoteTest,param1=x))
except IOError as e:
print(e.strerror)
unittest.TextTestRunner(verbosity=2).run(suite) | super(CreateTest, self).__init__(methodName)
self.param1 = param1 | identifier_body |
tens.py | ## -*- coding: utf-8 -*-
## Copyright (c) 2015-2018, Exa Analytics Development Team
## Distributed under the terms of the Apache License 2.0
#import six
##import numpy as np
#import pandas as pd
#from io import StringIO
##from exa import Series, TypedMeta
#from exa import TypedMeta
#from exatomic.core import Editor, Tensor
#
#
#class Meta(TypedMeta):
# tensor = Tensor
#
#
#class RTensor(six.with_metaclass(Meta, Editor)):
# """
# This is a simple script to read a rank-2 tensor file with frame, label and atom index
# labels. The format for such a file is,
#
# 0: f=** l=** a=**
# 1: xx xy xz
# 2: yx yy yz
# 3: zx zy zz
# 4:
# 5: Same as above for a second tensor
#
# """
### Must make this into a class that looks like the XYZ and Cube
## classes. Must have something like parse_tensor.
## Then on the Tensor class there should be something that can
## be activated to find the eigenvalues and eigenvectors of the
## matrix to plot the basis vectors.
## Look at untitled1.ipynb for more info.
# _to_universe = Editor.to_universe
#
# def to_universe(self):
# raise NotImplementedError("Tensor file format has no atom table")
#
# def parse_tensor(self):
# df = pd.read_csv(StringIO(str(self)), delim_whitespace=True, header=None,
# skip_blank_lines=False)
# #print(df)
# try:
# i=0
# data = ''
# while True:
# a = df.loc[[i*5],:].values[0]
# labels = []
# for lbl in a: | # labels.append(d[1])
# cols = ['xx','xy','xz','yx','yy','yz','zx','zy','zz']
# af = pd.DataFrame([df.loc[[i*5+1,i*5+2,i*5+3],:].unstack().values], \
# columns=cols)
# af['frame'] = labels[0] if labels[0] != '' else 0
# af['label'] = labels[1] if labels[1] != '' else None
# af['atom'] = labels[2] if labels[0] != '' else 0
# if i >= 1:
# data = pd.concat([data,af],keys=[o for o in range(i+1)])
# #data = data.append(af)
# print('tens.py--------')
# print(data)
# print('---------------')
# else:
# data = af
# i+=1
# except:
# print('tens.py--------')
# print("Reached EOF reading {} tensor".format(i))
# print(data)
# print('---------------')
# self.tensor = data
#
## @classmethod
## def from_universe(cls):
## pass | # d = lbl.split('=') | random_line_split |
constrain-trait.rs | // run-rustfix
// check-only
#[derive(Debug)]
struct Demo {
a: String
}
trait GetString {
fn get_a(&self) -> &String;
}
trait UseString: std::fmt::Debug {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
trait UseString2 {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
impl GetString for Demo {
fn get_a(&self) -> &String {
&self.a
}
}
impl UseString for Demo {}
impl UseString2 for Demo {}
#[cfg(test)]
mod tests {
use crate::{Demo, UseString};
#[test]
fn it_works() |
}
fn main() {}
| {
let d = Demo { a: "test".to_string() };
d.use_string();
} | identifier_body |
constrain-trait.rs | // run-rustfix
// check-only
#[derive(Debug)]
struct Demo {
a: String
}
trait GetString {
fn get_a(&self) -> &String;
}
trait UseString: std::fmt::Debug {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
trait UseString2 {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
impl GetString for Demo {
fn get_a(&self) -> &String {
&self.a
}
}
| impl UseString2 for Demo {}
#[cfg(test)]
mod tests {
use crate::{Demo, UseString};
#[test]
fn it_works() {
let d = Demo { a: "test".to_string() };
d.use_string();
}
}
fn main() {} | impl UseString for Demo {} | random_line_split |
constrain-trait.rs | // run-rustfix
// check-only
#[derive(Debug)]
struct Demo {
a: String
}
trait GetString {
fn get_a(&self) -> &String;
}
trait UseString: std::fmt::Debug {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
trait UseString2 {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
impl GetString for Demo {
fn | (&self) -> &String {
&self.a
}
}
impl UseString for Demo {}
impl UseString2 for Demo {}
#[cfg(test)]
mod tests {
use crate::{Demo, UseString};
#[test]
fn it_works() {
let d = Demo { a: "test".to_string() };
d.use_string();
}
}
fn main() {}
| get_a | identifier_name |
sparsemax.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Sparsemax op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
__all__ = ["sparsemax"]
def | (logits, name=None):
"""Computes sparsemax activations [1].
For each batch `i` and class `j` we have
$$sparsemax[i, j] = max(logits[i, j] - tau(logits[i, :]), 0)$$
[1]: https://arxiv.org/abs/1602.02068
Args:
logits: A `Tensor`. Must be one of the following types: `half`, `float32`,
`float64`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `logits`.
"""
with ops.name_scope(name, "sparsemax", [logits]) as name:
logits = ops.convert_to_tensor(logits, name="logits")
obs = array_ops.shape(logits)[0]
dims = array_ops.shape(logits)[1]
# In the paper, they call the logits z.
# The mean(logits) can be substracted from logits to make the algorithm
# more numerically stable. the instability in this algorithm comes mostly
# from the z_cumsum. Substacting the mean will cause z_cumsum to be close
# to zero. However, in practise the numerical instability issues are very
# minor and substacting the mean causes extra issues with inf and nan
# input.
z = logits
# sort z
z_sorted, _ = nn.top_k(z, k=dims)
# calculate k(z)
z_cumsum = math_ops.cumsum(z_sorted, axis=1)
k = math_ops.range(
1, math_ops.cast(dims, logits.dtype) + 1, dtype=logits.dtype)
z_check = 1 + k * z_sorted > z_cumsum
# because the z_check vector is always [1,1,...1,0,0,...0] finding the
# (index + 1) of the last `1` is the same as just summing the number of 1.
k_z = math_ops.reduce_sum(math_ops.cast(z_check, dtypes.int32), axis=1)
# calculate tau(z)
# If there are inf values or all values are -inf, the k_z will be zero,
# this is mathematically invalid and will also cause the gather_nd to fail.
# Prevent this issue for now by setting k_z = 1 if k_z = 0, this is then
# fixed later (see p_safe) by returning p = nan. This results in the same
# behavior as softmax.
k_z_safe = math_ops.maximum(k_z, 1)
indices = array_ops.stack([math_ops.range(0, obs), k_z_safe - 1], axis=1)
tau_sum = array_ops.gather_nd(z_cumsum, indices)
tau_z = (tau_sum - 1) / math_ops.cast(k_z, logits.dtype)
# calculate p
p = math_ops.maximum(
math_ops.cast(0, logits.dtype), z - tau_z[:, array_ops.newaxis])
# If k_z = 0 or if z = nan, then the input is invalid
p_safe = array_ops.where(
math_ops.logical_or(
math_ops.equal(k_z, 0), math_ops.is_nan(z_cumsum[:, -1])),
array_ops.fill([obs, dims], math_ops.cast(float("nan"), logits.dtype)),
p)
return p_safe
| sparsemax | identifier_name |
sparsemax.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Sparsemax op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
__all__ = ["sparsemax"]
def sparsemax(logits, name=None):
"""Computes sparsemax activations [1].
For each batch `i` and class `j` we have
$$sparsemax[i, j] = max(logits[i, j] - tau(logits[i, :]), 0)$$
[1]: https://arxiv.org/abs/1602.02068
Args:
logits: A `Tensor`. Must be one of the following types: `half`, `float32`,
`float64`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `logits`.
"""
with ops.name_scope(name, "sparsemax", [logits]) as name:
logits = ops.convert_to_tensor(logits, name="logits")
obs = array_ops.shape(logits)[0]
dims = array_ops.shape(logits)[1]
# In the paper, they call the logits z.
# The mean(logits) can be substracted from logits to make the algorithm
# more numerically stable. the instability in this algorithm comes mostly
# from the z_cumsum. Substacting the mean will cause z_cumsum to be close | # minor and substacting the mean causes extra issues with inf and nan
# input.
z = logits
# sort z
z_sorted, _ = nn.top_k(z, k=dims)
# calculate k(z)
z_cumsum = math_ops.cumsum(z_sorted, axis=1)
k = math_ops.range(
1, math_ops.cast(dims, logits.dtype) + 1, dtype=logits.dtype)
z_check = 1 + k * z_sorted > z_cumsum
# because the z_check vector is always [1,1,...1,0,0,...0] finding the
# (index + 1) of the last `1` is the same as just summing the number of 1.
k_z = math_ops.reduce_sum(math_ops.cast(z_check, dtypes.int32), axis=1)
# calculate tau(z)
# If there are inf values or all values are -inf, the k_z will be zero,
# this is mathematically invalid and will also cause the gather_nd to fail.
# Prevent this issue for now by setting k_z = 1 if k_z = 0, this is then
# fixed later (see p_safe) by returning p = nan. This results in the same
# behavior as softmax.
k_z_safe = math_ops.maximum(k_z, 1)
indices = array_ops.stack([math_ops.range(0, obs), k_z_safe - 1], axis=1)
tau_sum = array_ops.gather_nd(z_cumsum, indices)
tau_z = (tau_sum - 1) / math_ops.cast(k_z, logits.dtype)
# calculate p
p = math_ops.maximum(
math_ops.cast(0, logits.dtype), z - tau_z[:, array_ops.newaxis])
# If k_z = 0 or if z = nan, then the input is invalid
p_safe = array_ops.where(
math_ops.logical_or(
math_ops.equal(k_z, 0), math_ops.is_nan(z_cumsum[:, -1])),
array_ops.fill([obs, dims], math_ops.cast(float("nan"), logits.dtype)),
p)
return p_safe | # to zero. However, in practise the numerical instability issues are very | random_line_split |
sparsemax.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Sparsemax op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
__all__ = ["sparsemax"]
def sparsemax(logits, name=None):
| """Computes sparsemax activations [1].
For each batch `i` and class `j` we have
$$sparsemax[i, j] = max(logits[i, j] - tau(logits[i, :]), 0)$$
[1]: https://arxiv.org/abs/1602.02068
Args:
logits: A `Tensor`. Must be one of the following types: `half`, `float32`,
`float64`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `logits`.
"""
with ops.name_scope(name, "sparsemax", [logits]) as name:
logits = ops.convert_to_tensor(logits, name="logits")
obs = array_ops.shape(logits)[0]
dims = array_ops.shape(logits)[1]
# In the paper, they call the logits z.
# The mean(logits) can be substracted from logits to make the algorithm
# more numerically stable. the instability in this algorithm comes mostly
# from the z_cumsum. Substacting the mean will cause z_cumsum to be close
# to zero. However, in practise the numerical instability issues are very
# minor and substacting the mean causes extra issues with inf and nan
# input.
z = logits
# sort z
z_sorted, _ = nn.top_k(z, k=dims)
# calculate k(z)
z_cumsum = math_ops.cumsum(z_sorted, axis=1)
k = math_ops.range(
1, math_ops.cast(dims, logits.dtype) + 1, dtype=logits.dtype)
z_check = 1 + k * z_sorted > z_cumsum
# because the z_check vector is always [1,1,...1,0,0,...0] finding the
# (index + 1) of the last `1` is the same as just summing the number of 1.
k_z = math_ops.reduce_sum(math_ops.cast(z_check, dtypes.int32), axis=1)
# calculate tau(z)
# If there are inf values or all values are -inf, the k_z will be zero,
# this is mathematically invalid and will also cause the gather_nd to fail.
# Prevent this issue for now by setting k_z = 1 if k_z = 0, this is then
# fixed later (see p_safe) by returning p = nan. This results in the same
# behavior as softmax.
k_z_safe = math_ops.maximum(k_z, 1)
indices = array_ops.stack([math_ops.range(0, obs), k_z_safe - 1], axis=1)
tau_sum = array_ops.gather_nd(z_cumsum, indices)
tau_z = (tau_sum - 1) / math_ops.cast(k_z, logits.dtype)
# calculate p
p = math_ops.maximum(
math_ops.cast(0, logits.dtype), z - tau_z[:, array_ops.newaxis])
# If k_z = 0 or if z = nan, then the input is invalid
p_safe = array_ops.where(
math_ops.logical_or(
math_ops.equal(k_z, 0), math_ops.is_nan(z_cumsum[:, -1])),
array_ops.fill([obs, dims], math_ops.cast(float("nan"), logits.dtype)),
p)
return p_safe | identifier_body | |
bin_xlsx.ts | /* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* eslint-env node */
/* vim: set ts=2 ft=javascript: */
/// <reference types="../node_modules/@types/node/" />
const n = "xlsx";
import X = require("xlsx");
import 'exit-on-epipe';
import * as fs from 'fs';
import program = require('commander');
program
.version(X.version)
.usage('[options] <file> [sheetname]')
.option('-f, --file <file>', 'use specified workbook')
.option('-s, --sheet <sheet>', 'print specified sheet (default first sheet)')
.option('-N, --sheet-index <idx>', 'use specified sheet index (0-based)')
.option('-p, --password <pw>', 'if file is encrypted, try with specified pw')
.option('-l, --list-sheets', 'list sheet names and exit')
.option('-o, --output <file>', 'output to specified file')
.option('-B, --xlsb', 'emit XLSB to <sheetname> or <file>.xlsb')
.option('-M, --xlsm', 'emit XLSM to <sheetname> or <file>.xlsm')
.option('-X, --xlsx', 'emit XLSX to <sheetname> or <file>.xlsx')
.option('-I, --xlam', 'emit XLAM to <sheetname> or <file>.xlam')
.option('-Y, --ods', 'emit ODS to <sheetname> or <file>.ods')
.option('-8, --xls', 'emit XLS to <sheetname> or <file>.xls (BIFF8)')
.option('-5, --biff5','emit XLS to <sheetname> or <file>.xls (BIFF5)')
.option('-2, --biff2','emit XLS to <sheetname> or <file>.xls (BIFF2)')
.option('-i, --xla', 'emit XLA to <sheetname> or <file>.xla')
.option('-6, --xlml', 'emit SSML to <sheetname> or <file>.xls (2003 XML)')
.option('-T, --fods', 'emit FODS to <sheetname> or <file>.fods (Flat ODS)')
.option('-S, --formulae', 'emit list of values and formulae')
.option('-j, --json', 'emit formatted JSON (all fields text)')
.option('-J, --raw-js', 'emit raw JS object (raw numbers)')
.option('-A, --arrays', 'emit rows as JS objects (raw numbers)')
.option('-H, --html', 'emit HTML to <sheetname> or <file>.html')
.option('-D, --dif', 'emit DIF to <sheetname> or <file>.dif (Lotus DIF)')
.option('-U, --dbf', 'emit DBF to <sheetname> or <file>.dbf (MSVFP DBF)')
.option('-K, --sylk', 'emit SYLK to <sheetname> or <file>.slk (Excel SYLK)')
.option('-P, --prn', 'emit PRN to <sheetname> or <file>.prn (Lotus PRN)')
.option('-E, --eth', 'emit ETH to <sheetname> or <file>.eth (Ethercalc)')
.option('-t, --txt', 'emit TXT to <sheetname> or <file>.txt (UTF-8 TSV)')
.option('-r, --rtf', 'emit RTF to <sheetname> or <file>.txt (Table RTF)')
.option('-z, --dump', 'dump internal representation as JSON')
.option('--props', 'dump workbook properties as CSV')
.option('-F, --field-sep <sep>', 'CSV field separator', ",")
.option('-R, --row-sep <sep>', 'CSV row separator', "\n")
.option('-n, --sheet-rows <num>', 'Number of rows to process (0=all rows)')
.option('--codepage <cp>', 'default to specified codepage when ambiguous')
.option('--req <module>', 'require module before processing')
.option('--sst', 'generate shared string table for XLS* formats')
.option('--compress', 'use compression when writing XLSX/M/B and ODS')
.option('--read', 'read but do not generate output')
.option('--book', 'for single-sheet formats, emit a file per worksheet')
.option('--all', 'parse everything; write as much as possible')
.option('--dev', 'development mode')
.option('--sparse', 'sparse mode')
.option('-q, --quiet', 'quiet mode');
program.on('--help', function() {
console.log(' Default output format is CSV');
console.log(' Support email: dev@sheetjs.com');
console.log(' Web Demo: http://oss.sheetjs.com/js-'+n+'/');
});
/* flag, bookType, default ext */
const workbook_formats = [
['xlsx', 'xlsx', 'xlsx'],
['xlsm', 'xlsm', 'xlsm'],
['xlam', 'xlam', 'xlam'],
['xlsb', 'xlsb', 'xlsb'],
['xls', 'xls', 'xls'],
['xla', 'xla', 'xla'],
['biff5', 'biff5', 'xls'],
['ods', 'ods', 'ods'],
['fods', 'fods', 'fods']
];
const wb_formats_2 = [
['xlml', 'xlml', 'xls']
];
program.parse(process.argv);
let filename = '', sheetname = '';
if(program.args[0]) {
filename = program.args[0];
if(program.args[1]) sheetname = program.args[1];
}
if(program.sheet) sheetname = program.sheet;
if(program.file) filename = program.file;
if(!filename) {
console.error(n + ": must specify a filename");
process.exit(1);
}
if(!fs.existsSync(filename)) {
console.error(n + ": " + filename + ": No such file or directory");
process.exit(2);
}
const opts: X.ParsingOptions = {};
let wb: X.WorkBook;
if(program.listSheets) opts.bookSheets = true;
if(program.sheetRows) opts.sheetRows = program.sheetRows;
if(program.password) opts.password = program.password;
let seen = false;
function wb_fmt() {
seen = true;
opts.cellFormula = true;
opts.cellNF = true;
if(program.output) sheetname = program.output;
}
function isfmt(m: string): boolean |
workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } });
wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } });
if(seen) {
} else if(program.formulae) opts.cellFormula = true;
else opts.cellFormula = false;
const wopts: X.WritingOptions = ({WTF:opts.WTF, bookSST:program.sst}/*:any*/);
if(program.compress) wopts.compression = true;
if(program.all) {
opts.cellFormula = true;
opts.bookVBA = true;
opts.cellNF = true;
opts.cellHTML = true;
opts.cellStyles = true;
opts.sheetStubs = true;
opts.cellDates = true;
wopts.cellStyles = true;
wopts.bookVBA = true;
}
if(program.sparse) opts.dense = false; else opts.dense = true;
if(program.codepage) opts.codepage = +program.codepage;
if(program.dev) {
opts.WTF = true;
wb = X.readFile(filename, opts);
} else try {
wb = X.readFile(filename, opts);
} catch(e) {
let msg = (program.quiet) ? "" : n + ": error parsing ";
msg += filename + ": " + e;
console.error(msg);
process.exit(3);
}
if(program.read) process.exit(0);
if(!wb) { console.error(n + ": error parsing " + filename + ": empty workbook"); process.exit(0); }
/*:: if(!wb) throw new Error("unreachable"); */
if(program.listSheets) {
console.log((wb.SheetNames||[]).join("\n"));
process.exit(0);
}
if(program.dump) {
console.log(JSON.stringify(wb));
process.exit(0);
}
if(program.props) {
dump_props(wb);
process.exit(0);
}
/* full workbook formats */
workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) {
wopts.bookType = <X.BookType>(m[1]);
X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts);
process.exit(0);
} });
wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) {
wopts.bookType = <X.BookType>(m[1]);
X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts);
process.exit(0);
} });
let target_sheet = sheetname || '';
if(target_sheet === '') {
if(program.sheetIndex < (wb.SheetNames||[]).length) target_sheet = wb.SheetNames[program.sheetIndex];
else target_sheet = (wb.SheetNames||[""])[0];
}
let ws: X.WorkSheet;
try {
ws = wb.Sheets[target_sheet];
if(!ws) {
console.error("Sheet " + target_sheet + " cannot be found");
process.exit(3);
}
} catch(e) {
console.error(n + ": error parsing "+filename+" "+target_sheet+": " + e);
process.exit(4);
}
if(!program.quiet && !program.book) console.error(target_sheet);
/* single worksheet file formats */
[
['biff2', '.xls'],
['biff3', '.xls'],
['biff4', '.xls'],
['sylk', '.slk'],
['html', '.html'],
['prn', '.prn'],
['eth', '.eth'],
['rtf', '.rtf'],
['txt', '.txt'],
['dbf', '.dbf'],
['dif', '.dif']
].forEach(function(m) { if(program[m[0]] || isfmt(m[1])) {
wopts.bookType = <X.BookType>(m[0]);
X.writeFile(wb, program.output || sheetname || ((filename || "") + m[1]), wopts);
process.exit(0);
} });
let oo = "", strm = false;
if(!program.quiet) console.error(target_sheet);
if(program.formulae) oo = X.utils.sheet_to_formulae(ws).join("\n");
else if(program.json) oo = JSON.stringify(X.utils.sheet_to_json(ws));
else if(program.rawJs) oo = JSON.stringify(X.utils.sheet_to_json(ws,{raw:true}));
else if(program.arrays) oo = JSON.stringify(X.utils.sheet_to_json(ws,{raw:true, header:1}));
else {
strm = true;
const stream: NodeJS.ReadableStream = X.stream.to_csv(ws, {FS:program.fieldSep, RS:program.rowSep});
if(program.output) stream.pipe(fs.createWriteStream(program.output));
else stream.pipe(process.stdout);
}
if(!strm) {
if(program.output) fs.writeFileSync(program.output, oo);
else console.log(oo);
}
/*:: } */
/*:: } */
function dump_props(wb: X.WorkBook) {
let propaoa: any[][] = [];
propaoa = (<any>Object).entries({...wb.Props, ...wb.Custprops});
console.log(X.utils.sheet_to_csv(X.utils.aoa_to_sheet(propaoa)));
}
| {
if(!program.output) return false;
const t = m.charAt(0) === "." ? m : "." + m;
return program.output.slice(-t.length) === t;
} | identifier_body |
bin_xlsx.ts | /* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* eslint-env node */
/* vim: set ts=2 ft=javascript: */
/// <reference types="../node_modules/@types/node/" />
const n = "xlsx";
import X = require("xlsx");
import 'exit-on-epipe';
import * as fs from 'fs';
import program = require('commander');
program
.version(X.version)
.usage('[options] <file> [sheetname]')
.option('-f, --file <file>', 'use specified workbook')
.option('-s, --sheet <sheet>', 'print specified sheet (default first sheet)')
.option('-N, --sheet-index <idx>', 'use specified sheet index (0-based)')
.option('-p, --password <pw>', 'if file is encrypted, try with specified pw')
.option('-l, --list-sheets', 'list sheet names and exit')
.option('-o, --output <file>', 'output to specified file')
.option('-B, --xlsb', 'emit XLSB to <sheetname> or <file>.xlsb')
.option('-M, --xlsm', 'emit XLSM to <sheetname> or <file>.xlsm')
.option('-X, --xlsx', 'emit XLSX to <sheetname> or <file>.xlsx')
.option('-I, --xlam', 'emit XLAM to <sheetname> or <file>.xlam')
.option('-Y, --ods', 'emit ODS to <sheetname> or <file>.ods')
.option('-8, --xls', 'emit XLS to <sheetname> or <file>.xls (BIFF8)')
.option('-5, --biff5','emit XLS to <sheetname> or <file>.xls (BIFF5)')
.option('-2, --biff2','emit XLS to <sheetname> or <file>.xls (BIFF2)')
.option('-i, --xla', 'emit XLA to <sheetname> or <file>.xla')
.option('-6, --xlml', 'emit SSML to <sheetname> or <file>.xls (2003 XML)')
.option('-T, --fods', 'emit FODS to <sheetname> or <file>.fods (Flat ODS)')
.option('-S, --formulae', 'emit list of values and formulae')
.option('-j, --json', 'emit formatted JSON (all fields text)')
.option('-J, --raw-js', 'emit raw JS object (raw numbers)')
.option('-A, --arrays', 'emit rows as JS objects (raw numbers)')
.option('-H, --html', 'emit HTML to <sheetname> or <file>.html')
.option('-D, --dif', 'emit DIF to <sheetname> or <file>.dif (Lotus DIF)')
.option('-U, --dbf', 'emit DBF to <sheetname> or <file>.dbf (MSVFP DBF)')
.option('-K, --sylk', 'emit SYLK to <sheetname> or <file>.slk (Excel SYLK)')
.option('-P, --prn', 'emit PRN to <sheetname> or <file>.prn (Lotus PRN)')
.option('-E, --eth', 'emit ETH to <sheetname> or <file>.eth (Ethercalc)')
.option('-t, --txt', 'emit TXT to <sheetname> or <file>.txt (UTF-8 TSV)')
.option('-r, --rtf', 'emit RTF to <sheetname> or <file>.txt (Table RTF)')
.option('-z, --dump', 'dump internal representation as JSON')
.option('--props', 'dump workbook properties as CSV')
.option('-F, --field-sep <sep>', 'CSV field separator', ",")
.option('-R, --row-sep <sep>', 'CSV row separator', "\n")
.option('-n, --sheet-rows <num>', 'Number of rows to process (0=all rows)')
.option('--codepage <cp>', 'default to specified codepage when ambiguous')
.option('--req <module>', 'require module before processing')
.option('--sst', 'generate shared string table for XLS* formats')
.option('--compress', 'use compression when writing XLSX/M/B and ODS')
.option('--read', 'read but do not generate output')
.option('--book', 'for single-sheet formats, emit a file per worksheet')
.option('--all', 'parse everything; write as much as possible')
.option('--dev', 'development mode')
.option('--sparse', 'sparse mode')
.option('-q, --quiet', 'quiet mode');
program.on('--help', function() {
console.log(' Default output format is CSV');
console.log(' Support email: dev@sheetjs.com');
console.log(' Web Demo: http://oss.sheetjs.com/js-'+n+'/');
});
/* flag, bookType, default ext */
const workbook_formats = [
['xlsx', 'xlsx', 'xlsx'],
['xlsm', 'xlsm', 'xlsm'],
['xlam', 'xlam', 'xlam'],
['xlsb', 'xlsb', 'xlsb'],
['xls', 'xls', 'xls'],
['xla', 'xla', 'xla'],
['biff5', 'biff5', 'xls'],
['ods', 'ods', 'ods'],
['fods', 'fods', 'fods']
];
const wb_formats_2 = [
['xlml', 'xlml', 'xls']
];
program.parse(process.argv);
let filename = '', sheetname = '';
if(program.args[0]) {
filename = program.args[0];
if(program.args[1]) sheetname = program.args[1];
}
if(program.sheet) sheetname = program.sheet;
if(program.file) filename = program.file;
if(!filename) {
console.error(n + ": must specify a filename");
process.exit(1);
}
if(!fs.existsSync(filename)) {
console.error(n + ": " + filename + ": No such file or directory");
process.exit(2);
}
const opts: X.ParsingOptions = {};
let wb: X.WorkBook;
if(program.listSheets) opts.bookSheets = true;
if(program.sheetRows) opts.sheetRows = program.sheetRows;
if(program.password) opts.password = program.password;
let seen = false;
function wb_fmt() {
seen = true;
opts.cellFormula = true;
opts.cellNF = true;
if(program.output) sheetname = program.output;
}
function isfmt(m: string): boolean {
if(!program.output) return false;
const t = m.charAt(0) === "." ? m : "." + m;
return program.output.slice(-t.length) === t;
}
workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } });
wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } });
if(seen) {
} else if(program.formulae) opts.cellFormula = true;
else opts.cellFormula = false;
const wopts: X.WritingOptions = ({WTF:opts.WTF, bookSST:program.sst}/*:any*/);
if(program.compress) wopts.compression = true;
if(program.all) {
opts.cellFormula = true;
opts.bookVBA = true; | opts.cellNF = true;
opts.cellHTML = true;
opts.cellStyles = true;
opts.sheetStubs = true;
opts.cellDates = true;
wopts.cellStyles = true;
wopts.bookVBA = true;
}
if(program.sparse) opts.dense = false; else opts.dense = true;
if(program.codepage) opts.codepage = +program.codepage;
if(program.dev) {
opts.WTF = true;
wb = X.readFile(filename, opts);
} else try {
wb = X.readFile(filename, opts);
} catch(e) {
let msg = (program.quiet) ? "" : n + ": error parsing ";
msg += filename + ": " + e;
console.error(msg);
process.exit(3);
}
if(program.read) process.exit(0);
if(!wb) { console.error(n + ": error parsing " + filename + ": empty workbook"); process.exit(0); }
/*:: if(!wb) throw new Error("unreachable"); */
if(program.listSheets) {
console.log((wb.SheetNames||[]).join("\n"));
process.exit(0);
}
if(program.dump) {
console.log(JSON.stringify(wb));
process.exit(0);
}
if(program.props) {
dump_props(wb);
process.exit(0);
}
/* full workbook formats */
workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) {
wopts.bookType = <X.BookType>(m[1]);
X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts);
process.exit(0);
} });
wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) {
wopts.bookType = <X.BookType>(m[1]);
X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts);
process.exit(0);
} });
let target_sheet = sheetname || '';
if(target_sheet === '') {
if(program.sheetIndex < (wb.SheetNames||[]).length) target_sheet = wb.SheetNames[program.sheetIndex];
else target_sheet = (wb.SheetNames||[""])[0];
}
let ws: X.WorkSheet;
try {
ws = wb.Sheets[target_sheet];
if(!ws) {
console.error("Sheet " + target_sheet + " cannot be found");
process.exit(3);
}
} catch(e) {
console.error(n + ": error parsing "+filename+" "+target_sheet+": " + e);
process.exit(4);
}
if(!program.quiet && !program.book) console.error(target_sheet);
/* single worksheet file formats */
[
['biff2', '.xls'],
['biff3', '.xls'],
['biff4', '.xls'],
['sylk', '.slk'],
['html', '.html'],
['prn', '.prn'],
['eth', '.eth'],
['rtf', '.rtf'],
['txt', '.txt'],
['dbf', '.dbf'],
['dif', '.dif']
].forEach(function(m) { if(program[m[0]] || isfmt(m[1])) {
wopts.bookType = <X.BookType>(m[0]);
X.writeFile(wb, program.output || sheetname || ((filename || "") + m[1]), wopts);
process.exit(0);
} });
let oo = "", strm = false;
if(!program.quiet) console.error(target_sheet);
if(program.formulae) oo = X.utils.sheet_to_formulae(ws).join("\n");
else if(program.json) oo = JSON.stringify(X.utils.sheet_to_json(ws));
else if(program.rawJs) oo = JSON.stringify(X.utils.sheet_to_json(ws,{raw:true}));
else if(program.arrays) oo = JSON.stringify(X.utils.sheet_to_json(ws,{raw:true, header:1}));
else {
strm = true;
const stream: NodeJS.ReadableStream = X.stream.to_csv(ws, {FS:program.fieldSep, RS:program.rowSep});
if(program.output) stream.pipe(fs.createWriteStream(program.output));
else stream.pipe(process.stdout);
}
if(!strm) {
if(program.output) fs.writeFileSync(program.output, oo);
else console.log(oo);
}
/*:: } */
/*:: } */
function dump_props(wb: X.WorkBook) {
let propaoa: any[][] = [];
propaoa = (<any>Object).entries({...wb.Props, ...wb.Custprops});
console.log(X.utils.sheet_to_csv(X.utils.aoa_to_sheet(propaoa)));
} | random_line_split | |
bin_xlsx.ts | /* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* eslint-env node */
/* vim: set ts=2 ft=javascript: */
/// <reference types="../node_modules/@types/node/" />
const n = "xlsx";
import X = require("xlsx");
import 'exit-on-epipe';
import * as fs from 'fs';
import program = require('commander');
program
.version(X.version)
.usage('[options] <file> [sheetname]')
.option('-f, --file <file>', 'use specified workbook')
.option('-s, --sheet <sheet>', 'print specified sheet (default first sheet)')
.option('-N, --sheet-index <idx>', 'use specified sheet index (0-based)')
.option('-p, --password <pw>', 'if file is encrypted, try with specified pw')
.option('-l, --list-sheets', 'list sheet names and exit')
.option('-o, --output <file>', 'output to specified file')
.option('-B, --xlsb', 'emit XLSB to <sheetname> or <file>.xlsb')
.option('-M, --xlsm', 'emit XLSM to <sheetname> or <file>.xlsm')
.option('-X, --xlsx', 'emit XLSX to <sheetname> or <file>.xlsx')
.option('-I, --xlam', 'emit XLAM to <sheetname> or <file>.xlam')
.option('-Y, --ods', 'emit ODS to <sheetname> or <file>.ods')
.option('-8, --xls', 'emit XLS to <sheetname> or <file>.xls (BIFF8)')
.option('-5, --biff5','emit XLS to <sheetname> or <file>.xls (BIFF5)')
.option('-2, --biff2','emit XLS to <sheetname> or <file>.xls (BIFF2)')
.option('-i, --xla', 'emit XLA to <sheetname> or <file>.xla')
.option('-6, --xlml', 'emit SSML to <sheetname> or <file>.xls (2003 XML)')
.option('-T, --fods', 'emit FODS to <sheetname> or <file>.fods (Flat ODS)')
.option('-S, --formulae', 'emit list of values and formulae')
.option('-j, --json', 'emit formatted JSON (all fields text)')
.option('-J, --raw-js', 'emit raw JS object (raw numbers)')
.option('-A, --arrays', 'emit rows as JS objects (raw numbers)')
.option('-H, --html', 'emit HTML to <sheetname> or <file>.html')
.option('-D, --dif', 'emit DIF to <sheetname> or <file>.dif (Lotus DIF)')
.option('-U, --dbf', 'emit DBF to <sheetname> or <file>.dbf (MSVFP DBF)')
.option('-K, --sylk', 'emit SYLK to <sheetname> or <file>.slk (Excel SYLK)')
.option('-P, --prn', 'emit PRN to <sheetname> or <file>.prn (Lotus PRN)')
.option('-E, --eth', 'emit ETH to <sheetname> or <file>.eth (Ethercalc)')
.option('-t, --txt', 'emit TXT to <sheetname> or <file>.txt (UTF-8 TSV)')
.option('-r, --rtf', 'emit RTF to <sheetname> or <file>.txt (Table RTF)')
.option('-z, --dump', 'dump internal representation as JSON')
.option('--props', 'dump workbook properties as CSV')
.option('-F, --field-sep <sep>', 'CSV field separator', ",")
.option('-R, --row-sep <sep>', 'CSV row separator', "\n")
.option('-n, --sheet-rows <num>', 'Number of rows to process (0=all rows)')
.option('--codepage <cp>', 'default to specified codepage when ambiguous')
.option('--req <module>', 'require module before processing')
.option('--sst', 'generate shared string table for XLS* formats')
.option('--compress', 'use compression when writing XLSX/M/B and ODS')
.option('--read', 'read but do not generate output')
.option('--book', 'for single-sheet formats, emit a file per worksheet')
.option('--all', 'parse everything; write as much as possible')
.option('--dev', 'development mode')
.option('--sparse', 'sparse mode')
.option('-q, --quiet', 'quiet mode');
program.on('--help', function() {
console.log(' Default output format is CSV');
console.log(' Support email: dev@sheetjs.com');
console.log(' Web Demo: http://oss.sheetjs.com/js-'+n+'/');
});
/* flag, bookType, default ext */
const workbook_formats = [
['xlsx', 'xlsx', 'xlsx'],
['xlsm', 'xlsm', 'xlsm'],
['xlam', 'xlam', 'xlam'],
['xlsb', 'xlsb', 'xlsb'],
['xls', 'xls', 'xls'],
['xla', 'xla', 'xla'],
['biff5', 'biff5', 'xls'],
['ods', 'ods', 'ods'],
['fods', 'fods', 'fods']
];
const wb_formats_2 = [
['xlml', 'xlml', 'xls']
];
program.parse(process.argv);
let filename = '', sheetname = '';
if(program.args[0]) {
filename = program.args[0];
if(program.args[1]) sheetname = program.args[1];
}
if(program.sheet) sheetname = program.sheet;
if(program.file) filename = program.file;
if(!filename) {
console.error(n + ": must specify a filename");
process.exit(1);
}
if(!fs.existsSync(filename)) {
console.error(n + ": " + filename + ": No such file or directory");
process.exit(2);
}
const opts: X.ParsingOptions = {};
let wb: X.WorkBook;
if(program.listSheets) opts.bookSheets = true;
if(program.sheetRows) opts.sheetRows = program.sheetRows;
if(program.password) opts.password = program.password;
let seen = false;
function wb_fmt() {
seen = true;
opts.cellFormula = true;
opts.cellNF = true;
if(program.output) sheetname = program.output;
}
function isfmt(m: string): boolean {
if(!program.output) return false;
const t = m.charAt(0) === "." ? m : "." + m;
return program.output.slice(-t.length) === t;
}
workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } });
wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } });
if(seen) {
} else if(program.formulae) opts.cellFormula = true;
else opts.cellFormula = false;
const wopts: X.WritingOptions = ({WTF:opts.WTF, bookSST:program.sst}/*:any*/);
if(program.compress) wopts.compression = true;
if(program.all) {
opts.cellFormula = true;
opts.bookVBA = true;
opts.cellNF = true;
opts.cellHTML = true;
opts.cellStyles = true;
opts.sheetStubs = true;
opts.cellDates = true;
wopts.cellStyles = true;
wopts.bookVBA = true;
}
if(program.sparse) opts.dense = false; else opts.dense = true;
if(program.codepage) opts.codepage = +program.codepage;
if(program.dev) {
opts.WTF = true;
wb = X.readFile(filename, opts);
} else try {
wb = X.readFile(filename, opts);
} catch(e) {
let msg = (program.quiet) ? "" : n + ": error parsing ";
msg += filename + ": " + e;
console.error(msg);
process.exit(3);
}
if(program.read) process.exit(0);
if(!wb) { console.error(n + ": error parsing " + filename + ": empty workbook"); process.exit(0); }
/*:: if(!wb) throw new Error("unreachable"); */
if(program.listSheets) {
console.log((wb.SheetNames||[]).join("\n"));
process.exit(0);
}
if(program.dump) {
console.log(JSON.stringify(wb));
process.exit(0);
}
if(program.props) {
dump_props(wb);
process.exit(0);
}
/* full workbook formats */
workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) {
wopts.bookType = <X.BookType>(m[1]);
X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts);
process.exit(0);
} });
wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) {
wopts.bookType = <X.BookType>(m[1]);
X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts);
process.exit(0);
} });
let target_sheet = sheetname || '';
if(target_sheet === '') {
if(program.sheetIndex < (wb.SheetNames||[]).length) target_sheet = wb.SheetNames[program.sheetIndex];
else target_sheet = (wb.SheetNames||[""])[0];
}
let ws: X.WorkSheet;
try {
ws = wb.Sheets[target_sheet];
if(!ws) {
console.error("Sheet " + target_sheet + " cannot be found");
process.exit(3);
}
} catch(e) {
console.error(n + ": error parsing "+filename+" "+target_sheet+": " + e);
process.exit(4);
}
if(!program.quiet && !program.book) console.error(target_sheet);
/* single worksheet file formats */
[
['biff2', '.xls'],
['biff3', '.xls'],
['biff4', '.xls'],
['sylk', '.slk'],
['html', '.html'],
['prn', '.prn'],
['eth', '.eth'],
['rtf', '.rtf'],
['txt', '.txt'],
['dbf', '.dbf'],
['dif', '.dif']
].forEach(function(m) { if(program[m[0]] || isfmt(m[1])) {
wopts.bookType = <X.BookType>(m[0]);
X.writeFile(wb, program.output || sheetname || ((filename || "") + m[1]), wopts);
process.exit(0);
} });
let oo = "", strm = false;
if(!program.quiet) console.error(target_sheet);
if(program.formulae) oo = X.utils.sheet_to_formulae(ws).join("\n");
else if(program.json) oo = JSON.stringify(X.utils.sheet_to_json(ws));
else if(program.rawJs) oo = JSON.stringify(X.utils.sheet_to_json(ws,{raw:true}));
else if(program.arrays) oo = JSON.stringify(X.utils.sheet_to_json(ws,{raw:true, header:1}));
else {
strm = true;
const stream: NodeJS.ReadableStream = X.stream.to_csv(ws, {FS:program.fieldSep, RS:program.rowSep});
if(program.output) stream.pipe(fs.createWriteStream(program.output));
else stream.pipe(process.stdout);
}
if(!strm) {
if(program.output) fs.writeFileSync(program.output, oo);
else console.log(oo);
}
/*:: } */
/*:: } */
function | (wb: X.WorkBook) {
let propaoa: any[][] = [];
propaoa = (<any>Object).entries({...wb.Props, ...wb.Custprops});
console.log(X.utils.sheet_to_csv(X.utils.aoa_to_sheet(propaoa)));
}
| dump_props | identifier_name |
filters.py | """
These are filters placed at the end of a tunnel for watching or modifying
the traffic.
"""
##############################################################################
from __future__ import absolute_import
LICENSE = """\
This file is part of pagekite.py.
Copyright 2010-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see: <http://www.gnu.org/licenses/>
"""
##############################################################################
import six
import re
import time
import pagekite.logging as logging
from pagekite.compat import *
class TunnelFilter:
"""Base class for watchers/filters for data going in/out of Tunnels."""
FILTERS = ('connected', 'data_in', 'data_out')
IDLE_TIMEOUT = 1800
def __init__(self, ui):
self.sid = {}
self.ui = ui
def clean_idle_sids(self, now=None):
now = now or time.time()
for sid in list(six.iterkeys(self.sid)):
if self.sid[sid]['_ts'] < now - self.IDLE_TIMEOUT:
del self.sid[sid]
def filter_set_sid(self, sid, info):
now = time.time()
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid].update(info)
self.sid[sid]['_ts'] = now
self.clean_idle_sids(now=now)
def filter_connected(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
def filter_data_in(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
def filter_data_out(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
class TunnelWatcher(TunnelFilter):
"""Base class for watchers/filters for data going in/out of Tunnels."""
FILTERS = ('data_in', 'data_out')
def __init__(self, ui, watch_level=0):
TunnelFilter.__init__(self, ui)
self.watch_level = watch_level
def format_data(self, data, level):
|
def now(self):
return ts_to_iso(int(10*time.time())/10.0
).replace('T', ' ').replace('00000', '')
def filter_data_in(self, tunnel, sid, data):
if data and self.watch_level[0] > 0:
self.ui.Notify('===[ INCOMING @ %s / %s ]===' % (self.now(), sid),
color=self.ui.WHITE, prefix=' __')
for line in self.format_data(data, self.watch_level[0]):
self.ui.Notify(line, prefix=' <=', now=-1, color=self.ui.GREEN)
return TunnelFilter.filter_data_in(self, tunnel, sid, data)
def filter_data_out(self, tunnel, sid, data):
if data and self.watch_level[0] > 1:
self.ui.Notify('===[ OUTGOING @ %s / %s ]===' % (self.now(), sid),
color=self.ui.WHITE, prefix=' __')
for line in self.format_data(data, self.watch_level[0]):
self.ui.Notify(line, prefix=' =>', now=-1, color=self.ui.BLUE)
return TunnelFilter.filter_data_out(self, tunnel, sid, data)
class HaproxyProtocolFilter(TunnelFilter):
"""Filter prefixes the HAProxy PROXY protocol info to requests."""
FILTERS = ('connected')
ENABLE = 'proxyproto'
def filter_connected(self, tunnel, sid, data):
info = self.sid.get(sid)
if info:
if not info.get(self.ENABLE, False):
pass
elif info[self.ENABLE] in ("1", True):
remote_ip = info['remote_ip']
if '.' in remote_ip:
remote_ip = remote_ip.rsplit(':', 1)[1]
data = 'PROXY TCP%s %s 0.0.0.0 %s %s\r\n%s' % (
'4' if ('.' in remote_ip) else '6',
remote_ip, info['remote_port'], info['port'], data or '')
else:
logging.LogError(
'FIXME: Unimplemented PROXY protocol v%s\n' % info[self.ENABLE])
return TunnelFilter.filter_connected(self, tunnel, sid, data)
class HttpHeaderFilter(TunnelFilter):
"""Filter that adds X-Forwarded-For and X-Forwarded-Proto to requests."""
FILTERS = ('data_in')
HTTP_HEADER = re.compile('(?ism)^(([A-Z]+) ([^\n]+) HTTP/\d+\.\d+\s*)$')
DISABLE = 'rawheaders'
def filter_data_in(self, tunnel, sid, data):
info = self.sid.get(sid)
if (info and
info.get('proto') in ('http', 'http2', 'http3', 'websocket') and
not info.get(self.DISABLE, False)):
# FIXME: Check content-length and skip bodies entirely
http_hdr = self.HTTP_HEADER.search(data)
if http_hdr:
data = self.filter_header_data_in(http_hdr, data, info)
return TunnelFilter.filter_data_in(self, tunnel, sid, data)
def filter_header_data_in(self, http_hdr, data, info):
clean_headers = [
r'(?mi)^(X-(PageKite|Forwarded)-(For|Proto|Port):)'
]
add_headers = [
'X-Forwarded-For: %s' % info.get('remote_ip', 'unknown'),
'X-Forwarded-Proto: %s' % (info.get('using_tls') and 'https' or 'http'),
'X-PageKite-Port: %s' % info.get('port', 0)
]
if info.get('rewritehost', False):
add_headers.append('Host: %s' % info.get('rewritehost'))
clean_headers.append(r'(?mi)^(Host:)')
if http_hdr.group(1).upper() in ('POST', 'PUT'):
# FIXME: This is a bit ugly
add_headers.append('Connection: close')
clean_headers.append(r'(?mi)^(Connection|Keep-Alive):')
info['rawheaders'] = True
for hdr_re in clean_headers:
data = re.sub(hdr_re, 'X-Old-\\1', data)
return re.sub(self.HTTP_HEADER,
'\\1\n%s\r' % '\r\n'.join(add_headers),
data)
class HttpSecurityFilter(HttpHeaderFilter):
"""Filter that blocks known-to-be-dangerous requests."""
DISABLE = 'trusted'
HTTP_DANGER = re.compile('(?ism)^((get|post|put|patch|delete) '
# xampp paths, anything starting with /adm*
'((?:/+(?:xampp/|security/|licenses/|webalizer/|server-(?:status|info)|adm)'
'|[^\n]*/'
# WordPress admin pages
'(?:wp-admin/(?!admin-ajax|css/)|wp-config\.php'
# Hackzor tricks
'|system32/|\.\.|\.ht(?:access|pass)'
# phpMyAdmin and similar tools
'|(?:php|sql)?my(?:sql)?(?:adm|manager)'
# Setup pages for common PHP tools
'|(?:adm[^\n]*|install[^\n]*|setup)\.php)'
')[^\n]*)'
' HTTP/\d+\.\d+\s*)$')
REJECT = 'PAGEKITE_REJECT_'
def filter_header_data_in(self, http_hdr, data, info):
danger = self.HTTP_DANGER.search(data)
if danger:
self.ui.Notify('BLOCKED: %s %s' % (danger.group(2), danger.group(3)),
color=self.ui.RED, prefix='***')
self.ui.Notify('See https://pagekite.net/support/security/ for more'
' details.')
return self.REJECT+data
else:
return data
| if '\r\n\r\n' in data:
head, tail = data.split('\r\n\r\n', 1)
output = self.format_data(head, level)
output[-1] += '\\r\\n'
output.append('\\r\\n')
if tail:
output.extend(self.format_data(tail, level))
return output
else:
output = data.encode('string_escape').replace('\\n', '\\n\n')
if output.count('\\') > 0.15*len(output):
if level > 2:
output = [['', '']]
count = 0
for d in data:
output[-1][0] += '%2.2x' % ord(d)
output[-1][1] += '%c' % ((ord(d) > 31 and ord(d) < 127) and d or '.')
count += 1
if (count % 2) == 0:
output[-1][0] += ' '
if (count % 20) == 0:
output.append(['', ''])
return ['%-50s %s' % (l[0], l[1]) for l in output]
else:
return ['<< Binary bytes: %d >>' % len(data)]
else:
return output.strip().splitlines() | identifier_body |
filters.py | """
These are filters placed at the end of a tunnel for watching or modifying
the traffic.
"""
##############################################################################
from __future__ import absolute_import
LICENSE = """\
This file is part of pagekite.py.
Copyright 2010-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see: <http://www.gnu.org/licenses/>
"""
##############################################################################
import six
import re
import time
import pagekite.logging as logging
from pagekite.compat import *
class TunnelFilter:
"""Base class for watchers/filters for data going in/out of Tunnels."""
FILTERS = ('connected', 'data_in', 'data_out')
IDLE_TIMEOUT = 1800
def __init__(self, ui):
self.sid = {}
self.ui = ui
def clean_idle_sids(self, now=None):
now = now or time.time()
for sid in list(six.iterkeys(self.sid)):
if self.sid[sid]['_ts'] < now - self.IDLE_TIMEOUT:
del self.sid[sid]
def filter_set_sid(self, sid, info):
now = time.time()
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid].update(info)
self.sid[sid]['_ts'] = now
self.clean_idle_sids(now=now)
def filter_connected(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
def filter_data_in(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
def filter_data_out(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
class TunnelWatcher(TunnelFilter):
"""Base class for watchers/filters for data going in/out of Tunnels."""
FILTERS = ('data_in', 'data_out')
def __init__(self, ui, watch_level=0):
TunnelFilter.__init__(self, ui)
self.watch_level = watch_level
def format_data(self, data, level):
if '\r\n\r\n' in data:
head, tail = data.split('\r\n\r\n', 1)
output = self.format_data(head, level)
output[-1] += '\\r\\n'
output.append('\\r\\n')
if tail:
output.extend(self.format_data(tail, level))
return output
else:
output = data.encode('string_escape').replace('\\n', '\\n\n')
if output.count('\\') > 0.15*len(output):
if level > 2:
output = [['', '']]
count = 0
for d in data:
output[-1][0] += '%2.2x' % ord(d)
output[-1][1] += '%c' % ((ord(d) > 31 and ord(d) < 127) and d or '.')
count += 1
if (count % 2) == 0:
output[-1][0] += ' '
if (count % 20) == 0:
output.append(['', ''])
return ['%-50s %s' % (l[0], l[1]) for l in output]
else:
return ['<< Binary bytes: %d >>' % len(data)]
else:
return output.strip().splitlines()
def now(self):
return ts_to_iso(int(10*time.time())/10.0
).replace('T', ' ').replace('00000', '')
def filter_data_in(self, tunnel, sid, data):
if data and self.watch_level[0] > 0:
self.ui.Notify('===[ INCOMING @ %s / %s ]===' % (self.now(), sid),
color=self.ui.WHITE, prefix=' __')
for line in self.format_data(data, self.watch_level[0]):
self.ui.Notify(line, prefix=' <=', now=-1, color=self.ui.GREEN)
return TunnelFilter.filter_data_in(self, tunnel, sid, data)
def filter_data_out(self, tunnel, sid, data):
if data and self.watch_level[0] > 1:
self.ui.Notify('===[ OUTGOING @ %s / %s ]===' % (self.now(), sid),
color=self.ui.WHITE, prefix=' __')
for line in self.format_data(data, self.watch_level[0]):
self.ui.Notify(line, prefix=' =>', now=-1, color=self.ui.BLUE)
return TunnelFilter.filter_data_out(self, tunnel, sid, data)
class HaproxyProtocolFilter(TunnelFilter):
"""Filter prefixes the HAProxy PROXY protocol info to requests."""
FILTERS = ('connected')
ENABLE = 'proxyproto'
def filter_connected(self, tunnel, sid, data):
info = self.sid.get(sid)
if info:
if not info.get(self.ENABLE, False):
pass
elif info[self.ENABLE] in ("1", True):
remote_ip = info['remote_ip']
if '.' in remote_ip:
remote_ip = remote_ip.rsplit(':', 1)[1]
data = 'PROXY TCP%s %s 0.0.0.0 %s %s\r\n%s' % (
'4' if ('.' in remote_ip) else '6',
remote_ip, info['remote_port'], info['port'], data or '')
else:
logging.LogError(
'FIXME: Unimplemented PROXY protocol v%s\n' % info[self.ENABLE])
return TunnelFilter.filter_connected(self, tunnel, sid, data)
class HttpHeaderFilter(TunnelFilter):
"""Filter that adds X-Forwarded-For and X-Forwarded-Proto to requests."""
FILTERS = ('data_in')
HTTP_HEADER = re.compile('(?ism)^(([A-Z]+) ([^\n]+) HTTP/\d+\.\d+\s*)$')
DISABLE = 'rawheaders'
def filter_data_in(self, tunnel, sid, data):
info = self.sid.get(sid)
if (info and
info.get('proto') in ('http', 'http2', 'http3', 'websocket') and
not info.get(self.DISABLE, False)):
# FIXME: Check content-length and skip bodies entirely
http_hdr = self.HTTP_HEADER.search(data)
if http_hdr:
data = self.filter_header_data_in(http_hdr, data, info)
return TunnelFilter.filter_data_in(self, tunnel, sid, data)
def filter_header_data_in(self, http_hdr, data, info):
clean_headers = [
r'(?mi)^(X-(PageKite|Forwarded)-(For|Proto|Port):)'
]
add_headers = [
'X-Forwarded-For: %s' % info.get('remote_ip', 'unknown'),
'X-Forwarded-Proto: %s' % (info.get('using_tls') and 'https' or 'http'),
'X-PageKite-Port: %s' % info.get('port', 0)
]
if info.get('rewritehost', False):
|
if http_hdr.group(1).upper() in ('POST', 'PUT'):
# FIXME: This is a bit ugly
add_headers.append('Connection: close')
clean_headers.append(r'(?mi)^(Connection|Keep-Alive):')
info['rawheaders'] = True
for hdr_re in clean_headers:
data = re.sub(hdr_re, 'X-Old-\\1', data)
return re.sub(self.HTTP_HEADER,
'\\1\n%s\r' % '\r\n'.join(add_headers),
data)
class HttpSecurityFilter(HttpHeaderFilter):
"""Filter that blocks known-to-be-dangerous requests."""
DISABLE = 'trusted'
HTTP_DANGER = re.compile('(?ism)^((get|post|put|patch|delete) '
# xampp paths, anything starting with /adm*
'((?:/+(?:xampp/|security/|licenses/|webalizer/|server-(?:status|info)|adm)'
'|[^\n]*/'
# WordPress admin pages
'(?:wp-admin/(?!admin-ajax|css/)|wp-config\.php'
# Hackzor tricks
'|system32/|\.\.|\.ht(?:access|pass)'
# phpMyAdmin and similar tools
'|(?:php|sql)?my(?:sql)?(?:adm|manager)'
# Setup pages for common PHP tools
'|(?:adm[^\n]*|install[^\n]*|setup)\.php)'
')[^\n]*)'
' HTTP/\d+\.\d+\s*)$')
REJECT = 'PAGEKITE_REJECT_'
def filter_header_data_in(self, http_hdr, data, info):
danger = self.HTTP_DANGER.search(data)
if danger:
self.ui.Notify('BLOCKED: %s %s' % (danger.group(2), danger.group(3)),
color=self.ui.RED, prefix='***')
self.ui.Notify('See https://pagekite.net/support/security/ for more'
' details.')
return self.REJECT+data
else:
return data
| add_headers.append('Host: %s' % info.get('rewritehost'))
clean_headers.append(r'(?mi)^(Host:)') | conditional_block |
filters.py | """
These are filters placed at the end of a tunnel for watching or modifying
the traffic.
"""
##############################################################################
from __future__ import absolute_import
LICENSE = """\
This file is part of pagekite.py.
Copyright 2010-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see: <http://www.gnu.org/licenses/>
"""
##############################################################################
import six
import re
import time
import pagekite.logging as logging
from pagekite.compat import *
class TunnelFilter:
"""Base class for watchers/filters for data going in/out of Tunnels."""
FILTERS = ('connected', 'data_in', 'data_out')
IDLE_TIMEOUT = 1800
def __init__(self, ui):
self.sid = {}
self.ui = ui
def clean_idle_sids(self, now=None):
now = now or time.time()
for sid in list(six.iterkeys(self.sid)):
if self.sid[sid]['_ts'] < now - self.IDLE_TIMEOUT:
del self.sid[sid]
def filter_set_sid(self, sid, info):
now = time.time()
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid].update(info)
self.sid[sid]['_ts'] = now
self.clean_idle_sids(now=now)
def filter_connected(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
def filter_data_in(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
def filter_data_out(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
class TunnelWatcher(TunnelFilter):
"""Base class for watchers/filters for data going in/out of Tunnels."""
FILTERS = ('data_in', 'data_out')
def __init__(self, ui, watch_level=0):
TunnelFilter.__init__(self, ui)
self.watch_level = watch_level
def format_data(self, data, level):
if '\r\n\r\n' in data:
head, tail = data.split('\r\n\r\n', 1)
output = self.format_data(head, level)
output[-1] += '\\r\\n'
output.append('\\r\\n')
if tail:
output.extend(self.format_data(tail, level))
return output
else:
output = data.encode('string_escape').replace('\\n', '\\n\n')
if output.count('\\') > 0.15*len(output):
if level > 2:
output = [['', '']]
count = 0
for d in data:
output[-1][0] += '%2.2x' % ord(d)
output[-1][1] += '%c' % ((ord(d) > 31 and ord(d) < 127) and d or '.')
count += 1
if (count % 2) == 0:
output[-1][0] += ' '
if (count % 20) == 0:
output.append(['', ''])
return ['%-50s %s' % (l[0], l[1]) for l in output]
else:
return ['<< Binary bytes: %d >>' % len(data)]
else:
return output.strip().splitlines()
def now(self):
return ts_to_iso(int(10*time.time())/10.0
).replace('T', ' ').replace('00000', '')
def filter_data_in(self, tunnel, sid, data):
if data and self.watch_level[0] > 0:
self.ui.Notify('===[ INCOMING @ %s / %s ]===' % (self.now(), sid),
color=self.ui.WHITE, prefix=' __')
for line in self.format_data(data, self.watch_level[0]):
self.ui.Notify(line, prefix=' <=', now=-1, color=self.ui.GREEN)
return TunnelFilter.filter_data_in(self, tunnel, sid, data)
def filter_data_out(self, tunnel, sid, data):
if data and self.watch_level[0] > 1:
self.ui.Notify('===[ OUTGOING @ %s / %s ]===' % (self.now(), sid),
color=self.ui.WHITE, prefix=' __')
for line in self.format_data(data, self.watch_level[0]):
self.ui.Notify(line, prefix=' =>', now=-1, color=self.ui.BLUE)
return TunnelFilter.filter_data_out(self, tunnel, sid, data)
class HaproxyProtocolFilter(TunnelFilter):
"""Filter prefixes the HAProxy PROXY protocol info to requests."""
FILTERS = ('connected')
ENABLE = 'proxyproto'
def filter_connected(self, tunnel, sid, data):
info = self.sid.get(sid)
if info:
if not info.get(self.ENABLE, False):
pass
elif info[self.ENABLE] in ("1", True):
remote_ip = info['remote_ip']
if '.' in remote_ip:
remote_ip = remote_ip.rsplit(':', 1)[1]
data = 'PROXY TCP%s %s 0.0.0.0 %s %s\r\n%s' % (
'4' if ('.' in remote_ip) else '6',
remote_ip, info['remote_port'], info['port'], data or '')
else:
logging.LogError(
'FIXME: Unimplemented PROXY protocol v%s\n' % info[self.ENABLE])
return TunnelFilter.filter_connected(self, tunnel, sid, data)
class HttpHeaderFilter(TunnelFilter):
"""Filter that adds X-Forwarded-For and X-Forwarded-Proto to requests."""
FILTERS = ('data_in')
HTTP_HEADER = re.compile('(?ism)^(([A-Z]+) ([^\n]+) HTTP/\d+\.\d+\s*)$')
DISABLE = 'rawheaders'
def filter_data_in(self, tunnel, sid, data):
info = self.sid.get(sid)
if (info and
info.get('proto') in ('http', 'http2', 'http3', 'websocket') and
not info.get(self.DISABLE, False)):
# FIXME: Check content-length and skip bodies entirely
http_hdr = self.HTTP_HEADER.search(data)
if http_hdr:
data = self.filter_header_data_in(http_hdr, data, info)
return TunnelFilter.filter_data_in(self, tunnel, sid, data)
def | (self, http_hdr, data, info):
clean_headers = [
r'(?mi)^(X-(PageKite|Forwarded)-(For|Proto|Port):)'
]
add_headers = [
'X-Forwarded-For: %s' % info.get('remote_ip', 'unknown'),
'X-Forwarded-Proto: %s' % (info.get('using_tls') and 'https' or 'http'),
'X-PageKite-Port: %s' % info.get('port', 0)
]
if info.get('rewritehost', False):
add_headers.append('Host: %s' % info.get('rewritehost'))
clean_headers.append(r'(?mi)^(Host:)')
if http_hdr.group(1).upper() in ('POST', 'PUT'):
# FIXME: This is a bit ugly
add_headers.append('Connection: close')
clean_headers.append(r'(?mi)^(Connection|Keep-Alive):')
info['rawheaders'] = True
for hdr_re in clean_headers:
data = re.sub(hdr_re, 'X-Old-\\1', data)
return re.sub(self.HTTP_HEADER,
'\\1\n%s\r' % '\r\n'.join(add_headers),
data)
class HttpSecurityFilter(HttpHeaderFilter):
"""Filter that blocks known-to-be-dangerous requests."""
DISABLE = 'trusted'
HTTP_DANGER = re.compile('(?ism)^((get|post|put|patch|delete) '
# xampp paths, anything starting with /adm*
'((?:/+(?:xampp/|security/|licenses/|webalizer/|server-(?:status|info)|adm)'
'|[^\n]*/'
# WordPress admin pages
'(?:wp-admin/(?!admin-ajax|css/)|wp-config\.php'
# Hackzor tricks
'|system32/|\.\.|\.ht(?:access|pass)'
# phpMyAdmin and similar tools
'|(?:php|sql)?my(?:sql)?(?:adm|manager)'
# Setup pages for common PHP tools
'|(?:adm[^\n]*|install[^\n]*|setup)\.php)'
')[^\n]*)'
' HTTP/\d+\.\d+\s*)$')
REJECT = 'PAGEKITE_REJECT_'
def filter_header_data_in(self, http_hdr, data, info):
danger = self.HTTP_DANGER.search(data)
if danger:
self.ui.Notify('BLOCKED: %s %s' % (danger.group(2), danger.group(3)),
color=self.ui.RED, prefix='***')
self.ui.Notify('See https://pagekite.net/support/security/ for more'
' details.')
return self.REJECT+data
else:
return data
| filter_header_data_in | identifier_name |
filters.py | """
These are filters placed at the end of a tunnel for watching or modifying
the traffic.
"""
##############################################################################
from __future__ import absolute_import
LICENSE = """\
This file is part of pagekite.py.
Copyright 2010-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see: <http://www.gnu.org/licenses/>
"""
##############################################################################
import six
import re
import time |
class TunnelFilter:
"""Base class for watchers/filters for data going in/out of Tunnels."""
FILTERS = ('connected', 'data_in', 'data_out')
IDLE_TIMEOUT = 1800
def __init__(self, ui):
self.sid = {}
self.ui = ui
def clean_idle_sids(self, now=None):
now = now or time.time()
for sid in list(six.iterkeys(self.sid)):
if self.sid[sid]['_ts'] < now - self.IDLE_TIMEOUT:
del self.sid[sid]
def filter_set_sid(self, sid, info):
now = time.time()
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid].update(info)
self.sid[sid]['_ts'] = now
self.clean_idle_sids(now=now)
def filter_connected(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
def filter_data_in(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
def filter_data_out(self, tunnel, sid, data):
if sid not in self.sid:
self.sid[sid] = {}
self.sid[sid]['_ts'] = time.time()
return data
class TunnelWatcher(TunnelFilter):
"""Base class for watchers/filters for data going in/out of Tunnels."""
FILTERS = ('data_in', 'data_out')
def __init__(self, ui, watch_level=0):
TunnelFilter.__init__(self, ui)
self.watch_level = watch_level
def format_data(self, data, level):
if '\r\n\r\n' in data:
head, tail = data.split('\r\n\r\n', 1)
output = self.format_data(head, level)
output[-1] += '\\r\\n'
output.append('\\r\\n')
if tail:
output.extend(self.format_data(tail, level))
return output
else:
output = data.encode('string_escape').replace('\\n', '\\n\n')
if output.count('\\') > 0.15*len(output):
if level > 2:
output = [['', '']]
count = 0
for d in data:
output[-1][0] += '%2.2x' % ord(d)
output[-1][1] += '%c' % ((ord(d) > 31 and ord(d) < 127) and d or '.')
count += 1
if (count % 2) == 0:
output[-1][0] += ' '
if (count % 20) == 0:
output.append(['', ''])
return ['%-50s %s' % (l[0], l[1]) for l in output]
else:
return ['<< Binary bytes: %d >>' % len(data)]
else:
return output.strip().splitlines()
def now(self):
return ts_to_iso(int(10*time.time())/10.0
).replace('T', ' ').replace('00000', '')
def filter_data_in(self, tunnel, sid, data):
if data and self.watch_level[0] > 0:
self.ui.Notify('===[ INCOMING @ %s / %s ]===' % (self.now(), sid),
color=self.ui.WHITE, prefix=' __')
for line in self.format_data(data, self.watch_level[0]):
self.ui.Notify(line, prefix=' <=', now=-1, color=self.ui.GREEN)
return TunnelFilter.filter_data_in(self, tunnel, sid, data)
def filter_data_out(self, tunnel, sid, data):
if data and self.watch_level[0] > 1:
self.ui.Notify('===[ OUTGOING @ %s / %s ]===' % (self.now(), sid),
color=self.ui.WHITE, prefix=' __')
for line in self.format_data(data, self.watch_level[0]):
self.ui.Notify(line, prefix=' =>', now=-1, color=self.ui.BLUE)
return TunnelFilter.filter_data_out(self, tunnel, sid, data)
class HaproxyProtocolFilter(TunnelFilter):
"""Filter prefixes the HAProxy PROXY protocol info to requests."""
FILTERS = ('connected')
ENABLE = 'proxyproto'
def filter_connected(self, tunnel, sid, data):
info = self.sid.get(sid)
if info:
if not info.get(self.ENABLE, False):
pass
elif info[self.ENABLE] in ("1", True):
remote_ip = info['remote_ip']
if '.' in remote_ip:
remote_ip = remote_ip.rsplit(':', 1)[1]
data = 'PROXY TCP%s %s 0.0.0.0 %s %s\r\n%s' % (
'4' if ('.' in remote_ip) else '6',
remote_ip, info['remote_port'], info['port'], data or '')
else:
logging.LogError(
'FIXME: Unimplemented PROXY protocol v%s\n' % info[self.ENABLE])
return TunnelFilter.filter_connected(self, tunnel, sid, data)
class HttpHeaderFilter(TunnelFilter):
"""Filter that adds X-Forwarded-For and X-Forwarded-Proto to requests."""
FILTERS = ('data_in')
HTTP_HEADER = re.compile('(?ism)^(([A-Z]+) ([^\n]+) HTTP/\d+\.\d+\s*)$')
DISABLE = 'rawheaders'
def filter_data_in(self, tunnel, sid, data):
info = self.sid.get(sid)
if (info and
info.get('proto') in ('http', 'http2', 'http3', 'websocket') and
not info.get(self.DISABLE, False)):
# FIXME: Check content-length and skip bodies entirely
http_hdr = self.HTTP_HEADER.search(data)
if http_hdr:
data = self.filter_header_data_in(http_hdr, data, info)
return TunnelFilter.filter_data_in(self, tunnel, sid, data)
def filter_header_data_in(self, http_hdr, data, info):
clean_headers = [
r'(?mi)^(X-(PageKite|Forwarded)-(For|Proto|Port):)'
]
add_headers = [
'X-Forwarded-For: %s' % info.get('remote_ip', 'unknown'),
'X-Forwarded-Proto: %s' % (info.get('using_tls') and 'https' or 'http'),
'X-PageKite-Port: %s' % info.get('port', 0)
]
if info.get('rewritehost', False):
add_headers.append('Host: %s' % info.get('rewritehost'))
clean_headers.append(r'(?mi)^(Host:)')
if http_hdr.group(1).upper() in ('POST', 'PUT'):
# FIXME: This is a bit ugly
add_headers.append('Connection: close')
clean_headers.append(r'(?mi)^(Connection|Keep-Alive):')
info['rawheaders'] = True
for hdr_re in clean_headers:
data = re.sub(hdr_re, 'X-Old-\\1', data)
return re.sub(self.HTTP_HEADER,
'\\1\n%s\r' % '\r\n'.join(add_headers),
data)
class HttpSecurityFilter(HttpHeaderFilter):
"""Filter that blocks known-to-be-dangerous requests."""
DISABLE = 'trusted'
HTTP_DANGER = re.compile('(?ism)^((get|post|put|patch|delete) '
# xampp paths, anything starting with /adm*
'((?:/+(?:xampp/|security/|licenses/|webalizer/|server-(?:status|info)|adm)'
'|[^\n]*/'
# WordPress admin pages
'(?:wp-admin/(?!admin-ajax|css/)|wp-config\.php'
# Hackzor tricks
'|system32/|\.\.|\.ht(?:access|pass)'
# phpMyAdmin and similar tools
'|(?:php|sql)?my(?:sql)?(?:adm|manager)'
# Setup pages for common PHP tools
'|(?:adm[^\n]*|install[^\n]*|setup)\.php)'
')[^\n]*)'
' HTTP/\d+\.\d+\s*)$')
REJECT = 'PAGEKITE_REJECT_'
def filter_header_data_in(self, http_hdr, data, info):
danger = self.HTTP_DANGER.search(data)
if danger:
self.ui.Notify('BLOCKED: %s %s' % (danger.group(2), danger.group(3)),
color=self.ui.RED, prefix='***')
self.ui.Notify('See https://pagekite.net/support/security/ for more'
' details.')
return self.REJECT+data
else:
return data | import pagekite.logging as logging
from pagekite.compat import * | random_line_split |
tp.py | from pylab import *
from math import exp, sqrt
from image import *
from filters import *
from nibabel import load
import numpy
import image_processing
import image as img
import os
# This module generates
class C:
#a Config class, just a collection of constants
output_dir = '../report/img/results/'
input_dir = '../report/img/input/'
output_dir_plots = '../report/img/plots/'
# algorithm parameters to generate Sim and Reg plots
noise_levels = [0, 0.25, 0.5,1,2,3,5] # noise levels to distort the images
gaussian_sigmas = [0.5,1,2]
bilateral_sigmaDs = [0.5,1,2]
bilateral_sigmaRs = [2,20]
# plot configuration variables
column_names=['sim','reg','e','noise']
colors=['g','r','c','m','y','b'] # for different sigmaD
markers=['<','>','v','^'] # for different sigmaR
lines=['-',''] # for different typtes of algorithms
# algorithm parameters to generate result images
default_noise_level = 1.5
default_noise_level_mri = 1.5
default_gaussian_sigma = 1
default_gaussian_sigma_noise = 1.5
default_bilateral_sigma = (1, 7)
default_bilateral_sigma_noise = (1.5, 7)
default_number_of_bins = 256
# generate the plot for filtering algorithms
def generate_plot_filtering(results,name,column_y):
xlabel('Noise ($\sigma$)')
for sigma in C.gaussian_sigmas:
gaussian = results['gaussian']
gaussian = gaussian[gaussian[:, 4] == sigma]
label = 'Gaussian, $\sigma=%.2f$' % sigma
style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--'
plot(gaussian[:, 3], gaussian[:, column_y], style,label=label)
legend(loc=2)
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
bilateral= results['bilateral']
bilateral = bilateral[bilateral[:, 4] == sigmaD]
bilateral = bilateral[bilateral[:, 5] == sigmaR]
label = 'Bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (sigmaD,sigmaR)
style=C.markers[C.bilateral_sigmaRs.index(sigmaR)]+C.colors[C.bilateral_sigmaDs.index(sigmaD)]+'-'
plot(bilateral[:, 3], bilateral[:, column_y],style,label=label )
legend(loc=2)
savepngfig(C.output_dir_plots+name+'_filtering_'+C.column_names[column_y])
# generate the plot for otsu's algorithm, with and without noise and different
# types of filters
def generate_plot_otsu(results,name,column_y):
xlabel('Noise ($\sigma$)')
otsu = results['otsu']
plot(otsu[:, 3], otsu[:, column_y],'-.', label='otsu')
legend(loc=2)
for sigma in C.gaussian_sigmas:
otsu = results['otsu_gaussian']
otsu = otsu[otsu[:, 4] == sigma]
label = 'Otsu with gaussian, $\sigma=%.2f$' % sigma
style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--'
plot(otsu[:, 3], otsu[:, column_y], style,label=label)
legend(loc=1)
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
otsu = results['otsu_bilateral']
otsu = otsu[otsu[:, 4] == sigmaD]
otsu = otsu[otsu[:, 5] == sigmaR]
label = 'Otsu with bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (sigmaD,sigmaR)
style=C.markers[C.bilateral_sigmaRs.index(sigmaR)]+C.colors[C.bilateral_sigmaDs.index(sigmaD)]+'-'
plot(otsu[:, 3], otsu[:, column_y],style, label=label)
legend(loc=1)
savepngfig(C.output_dir_plots+name+'_otsu_'+C.column_names[column_y])
# Generate all the plot images according to the results dictionary
# for image with given name
def generate_plot_images(results, name):
for k in results:
results[k] = array(results[k])
functions=[generate_plot_otsu,generate_plot_filtering]
labels=[(0,'$Sim(I,J)$'),(1,'$Reg(J)$')]
for f in functions:
for (column_y,label) in labels:
figure()
ylabel(label)
f(results,name,column_y)
xlim(0,C.noise_levels[-1]*1.5)
# generate a dictionary with Sim, Reg and E values for every combination of the
# algorithm parameters in class C, for a given image with a certain name
def generate_plots(image, name):
results = {}
results['otsu'] = []
results['otsu_bilateral'] = []
results['otsu_gaussian'] = []
results['bilateral'] = []
results['gaussian'] = []
otsu, t = image_processing.threshold_otsu(image, C.default_number_of_bins)
for noise in C.noise_levels:
print 'Image %s, Noise %.2f ' % (name, noise)
image_with_noise = add_gaussian_noise(image, noise)
print 'Image %s, otsu ' % (name)
otsu_noise, t = image_processing.threshold_otsu(image_with_noise, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_noise)
results['otsu'].append([s, r, e, noise])
for sigma in C.gaussian_sigmas:
print 'Image %s, gaussian s=%.2f ' % (name, sigma)
gaussian = gaussian_filter(image_with_noise, sigma)
s, r, e = transformation_energy(image, gaussian)
results['gaussian'].append([s, r, e, noise, sigma])
if (sigma<2):
otsu_gaussian, t = image_processing.threshold_otsu(gaussian, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_gaussian)
results['otsu_gaussian'].append([s, r, e, noise, sigma])
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
print 'Image %s, bilateral sd=%.2f, sr=%.2f ' % (name, sigmaD,sigmaR)
bilateral = bilateral_filter(image_with_noise, sigmaD, sigmaR)
s, r, e = transformation_energy(image, bilateral)
results['bilateral'].append([s, r, e, noise, sigmaD, sigmaR])
otsu_bilateral, t = image_processing.threshold_otsu(bilateral, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_bilateral)
results['otsu_bilateral'].append([s, r, e, noise, sigmaD, sigmaR])
print 'Generating plot images...'
generate_plot_images(results, name)
# Generate the images that will be visually inspected
# For the given image, calculate:
# 1) Bilateral, gaussian and otsu's without noise
# 2) Bilateral, gaussian and otsu's with noise
# 3) Otsu's with noise, but after applying Bilateral, gaussian filtering
# Result images are saved with the given name as a prefix
def generate_result_images(image, name):
image = add_gaussian_noise(image, 0)
print 'Processing image %s' % name
save_image_png(image, C.output_dir + name)
if (name.startswith('mri')):
noise = C.default_noise_level_mri
else:
noise = C.default_noise_level
image_with_default_noise = add_gaussian_noise(image, noise)
save_image_png(image_with_default_noise, C.output_dir + name + '_noise')
print 'Image %s: bilateral' % name
(sigmaD, sigmaR) = C.default_bilateral_sigma
bilateral = bilateral_filter(image, sigmaD, sigmaR)
save_image_png(bilateral, C.output_dir + name + '_bilateral')
## for sigmaR in [1,2,3,4,5,7,8,9,10,11,12,13,14,15,17,18]:
## bilateral = bilateral_filter(image, sigmaD, sigmaR)
## if (sigmaR<10):
## n='0'+str(sigmaR)
## else:
## n=str(sigmaR)
## save_image_png(bilateral, C.output_dir + name + '_bilateral_'+n)
print 'Image %s: bilateral noise' % name
(sigmaD, sigmaR) = C.default_bilateral_sigma_noise
bilateral_noise = bilateral_filter(image_with_default_noise, sigmaD, sigmaR)
save_image_png(bilateral_noise, C.output_dir + name + '_noise_bilateral')
print 'Image %s: gaussian' % name
sigma = C.default_gaussian_sigma
gaussian = gaussian_filter(image, sigma)
save_image_png(gaussian, C.output_dir + name + '_gaussian')
print 'Image %s: gaussian noise' % name
sigma = C.default_gaussian_sigma_noise
gaussian_noise = gaussian_filter(image_with_default_noise, sigma)
save_image_png(gaussian_noise, C.output_dir + name + '_noise_gaussian')
print 'Image %s: Otsu' % name
otsu, t = image_processing.threshold_otsu(image, C.default_number_of_bins)
save_image_png(otsu, C.output_dir + name + '_otsu')
print 'Image %s: Otsu noise' % name
otsu_noise, t = image_processing.threshold_otsu(image_with_default_noise, C.default_number_of_bins)
save_image_png(otsu_noise, C.output_dir + name + '_otsu_noise')
print 'Image %s: Otsu noise bilateral' % name
otsu_bilateral_noise, t = image_processing.threshold_otsu(bilateral_noise, C.default_number_of_bins)
save_image_png(otsu_bilateral_noise, C.output_dir + name + '_otsu_noise_bilateral')
print 'Image %s: Otsu noise gaussian' % name
otsu_gaussian_noise, t = image_processing.threshold_otsu(gaussian_noise, C.default_number_of_bins)
save_image_png(otsu_gaussian_noise, C.output_dir + name + '_otsu_noise_gaussian')
# reads an image with a given extension from C.input_dir
def | (filename,extension):
if (extension=='gz'):
data = load(C.input_dir+ filename + '.'+extension)
image = data.get_data()
else:
image = imread(C.input_dir + filename + '.'+extension)
s = image.shape
if len(s) > 2 and s[2] in [3, 4]: # "detect" rgb images
image = img.rgb2gray(image)
#image= img.rgb2gray_color_preserving(image)
image=rescale_grayscale_image(image)
return image
def main():
set_printoptions(precision=4, linewidth=150, suppress=True) # print values with less precision
params = {'legend.fontsize': 8,
'legend.linewidth': 1,
'legend.labelspacing':0.2,
'legend.loc':2}
rcParams.update(params) # change global plotting parameters
if not os.path.exists(C.output_dir_plots):# generate output_dir_plots
os.makedirs(C.output_dir_plots)
if not os.path.exists(C.output_dir):# generate output_dir
os.makedirs(C.output_dir)
#image sets
synthetic_images=[('borders','png'),
('borders_contrast','png'),
('gradient1','png'),
('gradient2','png'),]
mri_images=[('mri1','png'),
('mri2','png'),
('mri3','png')]
mri_image=[('T1w_acpc_dc_restore_1.25.nii','gz')]
# select image set
#images=synthetic_images+mri_images
#images = mri_image
images=synthetic_images
# for each image, read it, and generate the resulting plots
# for each image, read it, and generate the resulting images
for filename,extension in images:
image = read_image(filename,extension)
#generate_result_images(image,filename)
generate_plots(image, filename)
if __name__ == '__main__':
main()
| read_image | identifier_name |
tp.py | from pylab import *
from math import exp, sqrt
from image import *
from filters import *
from nibabel import load
import numpy
import image_processing
import image as img
import os
# This module generates
class C:
#a Config class, just a collection of constants
output_dir = '../report/img/results/'
input_dir = '../report/img/input/'
output_dir_plots = '../report/img/plots/'
# algorithm parameters to generate Sim and Reg plots
noise_levels = [0, 0.25, 0.5,1,2,3,5] # noise levels to distort the images
gaussian_sigmas = [0.5,1,2]
bilateral_sigmaDs = [0.5,1,2]
bilateral_sigmaRs = [2,20]
# plot configuration variables
column_names=['sim','reg','e','noise']
colors=['g','r','c','m','y','b'] # for different sigmaD
markers=['<','>','v','^'] # for different sigmaR
lines=['-',''] # for different typtes of algorithms
# algorithm parameters to generate result images
default_noise_level = 1.5
default_noise_level_mri = 1.5
default_gaussian_sigma = 1
default_gaussian_sigma_noise = 1.5
default_bilateral_sigma = (1, 7)
default_bilateral_sigma_noise = (1.5, 7)
default_number_of_bins = 256
# generate the plot for filtering algorithms
def generate_plot_filtering(results,name,column_y):
xlabel('Noise ($\sigma$)')
for sigma in C.gaussian_sigmas:
gaussian = results['gaussian']
gaussian = gaussian[gaussian[:, 4] == sigma]
label = 'Gaussian, $\sigma=%.2f$' % sigma
style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--'
plot(gaussian[:, 3], gaussian[:, column_y], style,label=label)
legend(loc=2)
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
bilateral= results['bilateral']
bilateral = bilateral[bilateral[:, 4] == sigmaD]
bilateral = bilateral[bilateral[:, 5] == sigmaR]
label = 'Bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (sigmaD,sigmaR)
style=C.markers[C.bilateral_sigmaRs.index(sigmaR)]+C.colors[C.bilateral_sigmaDs.index(sigmaD)]+'-'
plot(bilateral[:, 3], bilateral[:, column_y],style,label=label )
legend(loc=2)
savepngfig(C.output_dir_plots+name+'_filtering_'+C.column_names[column_y])
# generate the plot for otsu's algorithm, with and without noise and different
# types of filters
def generate_plot_otsu(results,name,column_y):
xlabel('Noise ($\sigma$)')
otsu = results['otsu']
plot(otsu[:, 3], otsu[:, column_y],'-.', label='otsu')
legend(loc=2)
for sigma in C.gaussian_sigmas:
otsu = results['otsu_gaussian']
otsu = otsu[otsu[:, 4] == sigma]
label = 'Otsu with gaussian, $\sigma=%.2f$' % sigma
style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--'
plot(otsu[:, 3], otsu[:, column_y], style,label=label)
legend(loc=1)
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
otsu = results['otsu_bilateral']
otsu = otsu[otsu[:, 4] == sigmaD]
otsu = otsu[otsu[:, 5] == sigmaR]
label = 'Otsu with bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (sigmaD,sigmaR)
style=C.markers[C.bilateral_sigmaRs.index(sigmaR)]+C.colors[C.bilateral_sigmaDs.index(sigmaD)]+'-'
plot(otsu[:, 3], otsu[:, column_y],style, label=label)
legend(loc=1)
savepngfig(C.output_dir_plots+name+'_otsu_'+C.column_names[column_y])
# Generate all the plot images according to the results dictionary
# for image with given name
def generate_plot_images(results, name):
for k in results:
results[k] = array(results[k])
functions=[generate_plot_otsu,generate_plot_filtering]
labels=[(0,'$Sim(I,J)$'),(1,'$Reg(J)$')]
for f in functions:
for (column_y,label) in labels:
figure()
ylabel(label)
f(results,name,column_y)
xlim(0,C.noise_levels[-1]*1.5)
# generate a dictionary with Sim, Reg and E values for every combination of the
# algorithm parameters in class C, for a given image with a certain name
def generate_plots(image, name):
results = {}
results['otsu'] = []
results['otsu_bilateral'] = []
results['otsu_gaussian'] = []
results['bilateral'] = []
results['gaussian'] = []
otsu, t = image_processing.threshold_otsu(image, C.default_number_of_bins)
for noise in C.noise_levels:
print 'Image %s, Noise %.2f ' % (name, noise)
image_with_noise = add_gaussian_noise(image, noise)
print 'Image %s, otsu ' % (name)
otsu_noise, t = image_processing.threshold_otsu(image_with_noise, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_noise)
results['otsu'].append([s, r, e, noise])
for sigma in C.gaussian_sigmas:
print 'Image %s, gaussian s=%.2f ' % (name, sigma)
gaussian = gaussian_filter(image_with_noise, sigma)
s, r, e = transformation_energy(image, gaussian)
results['gaussian'].append([s, r, e, noise, sigma])
if (sigma<2):
otsu_gaussian, t = image_processing.threshold_otsu(gaussian, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_gaussian)
results['otsu_gaussian'].append([s, r, e, noise, sigma])
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
print 'Image %s, bilateral sd=%.2f, sr=%.2f ' % (name, sigmaD,sigmaR)
bilateral = bilateral_filter(image_with_noise, sigmaD, sigmaR)
s, r, e = transformation_energy(image, bilateral)
results['bilateral'].append([s, r, e, noise, sigmaD, sigmaR])
otsu_bilateral, t = image_processing.threshold_otsu(bilateral, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_bilateral)
results['otsu_bilateral'].append([s, r, e, noise, sigmaD, sigmaR])
print 'Generating plot images...'
generate_plot_images(results, name)
# Generate the images that will be visually inspected
# For the given image, calculate:
# 1) Bilateral, gaussian and otsu's without noise
# 2) Bilateral, gaussian and otsu's with noise
# 3) Otsu's with noise, but after applying Bilateral, gaussian filtering
# Result images are saved with the given name as a prefix
def generate_result_images(image, name):
image = add_gaussian_noise(image, 0)
print 'Processing image %s' % name
save_image_png(image, C.output_dir + name)
if (name.startswith('mri')):
noise = C.default_noise_level_mri
else:
noise = C.default_noise_level
image_with_default_noise = add_gaussian_noise(image, noise)
save_image_png(image_with_default_noise, C.output_dir + name + '_noise')
print 'Image %s: bilateral' % name
(sigmaD, sigmaR) = C.default_bilateral_sigma
bilateral = bilateral_filter(image, sigmaD, sigmaR)
save_image_png(bilateral, C.output_dir + name + '_bilateral')
## for sigmaR in [1,2,3,4,5,7,8,9,10,11,12,13,14,15,17,18]:
## bilateral = bilateral_filter(image, sigmaD, sigmaR)
## if (sigmaR<10):
## n='0'+str(sigmaR)
## else:
## n=str(sigmaR)
## save_image_png(bilateral, C.output_dir + name + '_bilateral_'+n)
print 'Image %s: bilateral noise' % name
(sigmaD, sigmaR) = C.default_bilateral_sigma_noise
bilateral_noise = bilateral_filter(image_with_default_noise, sigmaD, sigmaR)
save_image_png(bilateral_noise, C.output_dir + name + '_noise_bilateral')
print 'Image %s: gaussian' % name
sigma = C.default_gaussian_sigma
gaussian = gaussian_filter(image, sigma)
save_image_png(gaussian, C.output_dir + name + '_gaussian')
print 'Image %s: gaussian noise' % name
sigma = C.default_gaussian_sigma_noise
gaussian_noise = gaussian_filter(image_with_default_noise, sigma)
save_image_png(gaussian_noise, C.output_dir + name + '_noise_gaussian')
print 'Image %s: Otsu' % name
otsu, t = image_processing.threshold_otsu(image, C.default_number_of_bins)
save_image_png(otsu, C.output_dir + name + '_otsu')
print 'Image %s: Otsu noise' % name
otsu_noise, t = image_processing.threshold_otsu(image_with_default_noise, C.default_number_of_bins)
save_image_png(otsu_noise, C.output_dir + name + '_otsu_noise')
print 'Image %s: Otsu noise bilateral' % name
otsu_bilateral_noise, t = image_processing.threshold_otsu(bilateral_noise, C.default_number_of_bins)
save_image_png(otsu_bilateral_noise, C.output_dir + name + '_otsu_noise_bilateral')
print 'Image %s: Otsu noise gaussian' % name
otsu_gaussian_noise, t = image_processing.threshold_otsu(gaussian_noise, C.default_number_of_bins)
save_image_png(otsu_gaussian_noise, C.output_dir + name + '_otsu_noise_gaussian')
# reads an image with a given extension from C.input_dir
def read_image(filename,extension):
if (extension=='gz'):
data = load(C.input_dir+ filename + '.'+extension)
image = data.get_data()
else:
image = imread(C.input_dir + filename + '.'+extension)
s = image.shape
if len(s) > 2 and s[2] in [3, 4]: # "detect" rgb images
image = img.rgb2gray(image)
#image= img.rgb2gray_color_preserving(image)
image=rescale_grayscale_image(image)
return image
def main():
set_printoptions(precision=4, linewidth=150, suppress=True) # print values with less precision
params = {'legend.fontsize': 8,
'legend.linewidth': 1,
'legend.labelspacing':0.2,
'legend.loc':2}
rcParams.update(params) # change global plotting parameters
if not os.path.exists(C.output_dir_plots):# generate output_dir_plots
os.makedirs(C.output_dir_plots)
if not os.path.exists(C.output_dir):# generate output_dir | ('gradient2','png'),]
mri_images=[('mri1','png'),
('mri2','png'),
('mri3','png')]
mri_image=[('T1w_acpc_dc_restore_1.25.nii','gz')]
# select image set
#images=synthetic_images+mri_images
#images = mri_image
images=synthetic_images
# for each image, read it, and generate the resulting plots
# for each image, read it, and generate the resulting images
for filename,extension in images:
image = read_image(filename,extension)
#generate_result_images(image,filename)
generate_plots(image, filename)
if __name__ == '__main__':
main() | os.makedirs(C.output_dir)
#image sets
synthetic_images=[('borders','png'),
('borders_contrast','png'),
('gradient1','png'), | random_line_split |
tp.py | from pylab import *
from math import exp, sqrt
from image import *
from filters import *
from nibabel import load
import numpy
import image_processing
import image as img
import os
# This module generates
class C:
#a Config class, just a collection of constants
output_dir = '../report/img/results/'
input_dir = '../report/img/input/'
output_dir_plots = '../report/img/plots/'
# algorithm parameters to generate Sim and Reg plots
noise_levels = [0, 0.25, 0.5,1,2,3,5] # noise levels to distort the images
gaussian_sigmas = [0.5,1,2]
bilateral_sigmaDs = [0.5,1,2]
bilateral_sigmaRs = [2,20]
# plot configuration variables
column_names=['sim','reg','e','noise']
colors=['g','r','c','m','y','b'] # for different sigmaD
markers=['<','>','v','^'] # for different sigmaR
lines=['-',''] # for different typtes of algorithms
# algorithm parameters to generate result images
default_noise_level = 1.5
default_noise_level_mri = 1.5
default_gaussian_sigma = 1
default_gaussian_sigma_noise = 1.5
default_bilateral_sigma = (1, 7)
default_bilateral_sigma_noise = (1.5, 7)
default_number_of_bins = 256
# generate the plot for filtering algorithms
def generate_plot_filtering(results,name,column_y):
xlabel('Noise ($\sigma$)')
for sigma in C.gaussian_sigmas:
gaussian = results['gaussian']
gaussian = gaussian[gaussian[:, 4] == sigma]
label = 'Gaussian, $\sigma=%.2f$' % sigma
style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--'
plot(gaussian[:, 3], gaussian[:, column_y], style,label=label)
legend(loc=2)
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
bilateral= results['bilateral']
bilateral = bilateral[bilateral[:, 4] == sigmaD]
bilateral = bilateral[bilateral[:, 5] == sigmaR]
label = 'Bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (sigmaD,sigmaR)
style=C.markers[C.bilateral_sigmaRs.index(sigmaR)]+C.colors[C.bilateral_sigmaDs.index(sigmaD)]+'-'
plot(bilateral[:, 3], bilateral[:, column_y],style,label=label )
legend(loc=2)
savepngfig(C.output_dir_plots+name+'_filtering_'+C.column_names[column_y])
# generate the plot for otsu's algorithm, with and without noise and different
# types of filters
def generate_plot_otsu(results,name,column_y):
xlabel('Noise ($\sigma$)')
otsu = results['otsu']
plot(otsu[:, 3], otsu[:, column_y],'-.', label='otsu')
legend(loc=2)
for sigma in C.gaussian_sigmas:
otsu = results['otsu_gaussian']
otsu = otsu[otsu[:, 4] == sigma]
label = 'Otsu with gaussian, $\sigma=%.2f$' % sigma
style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--'
plot(otsu[:, 3], otsu[:, column_y], style,label=label)
legend(loc=1)
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
otsu = results['otsu_bilateral']
otsu = otsu[otsu[:, 4] == sigmaD]
otsu = otsu[otsu[:, 5] == sigmaR]
label = 'Otsu with bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (sigmaD,sigmaR)
style=C.markers[C.bilateral_sigmaRs.index(sigmaR)]+C.colors[C.bilateral_sigmaDs.index(sigmaD)]+'-'
plot(otsu[:, 3], otsu[:, column_y],style, label=label)
legend(loc=1)
savepngfig(C.output_dir_plots+name+'_otsu_'+C.column_names[column_y])
# Generate all the plot images according to the results dictionary
# for image with given name
def generate_plot_images(results, name):
for k in results:
results[k] = array(results[k])
functions=[generate_plot_otsu,generate_plot_filtering]
labels=[(0,'$Sim(I,J)$'),(1,'$Reg(J)$')]
for f in functions:
for (column_y,label) in labels:
figure()
ylabel(label)
f(results,name,column_y)
xlim(0,C.noise_levels[-1]*1.5)
# generate a dictionary with Sim, Reg and E values for every combination of the
# algorithm parameters in class C, for a given image with a certain name
def generate_plots(image, name):
results = {}
results['otsu'] = []
results['otsu_bilateral'] = []
results['otsu_gaussian'] = []
results['bilateral'] = []
results['gaussian'] = []
otsu, t = image_processing.threshold_otsu(image, C.default_number_of_bins)
for noise in C.noise_levels:
print 'Image %s, Noise %.2f ' % (name, noise)
image_with_noise = add_gaussian_noise(image, noise)
print 'Image %s, otsu ' % (name)
otsu_noise, t = image_processing.threshold_otsu(image_with_noise, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_noise)
results['otsu'].append([s, r, e, noise])
for sigma in C.gaussian_sigmas:
print 'Image %s, gaussian s=%.2f ' % (name, sigma)
gaussian = gaussian_filter(image_with_noise, sigma)
s, r, e = transformation_energy(image, gaussian)
results['gaussian'].append([s, r, e, noise, sigma])
if (sigma<2):
otsu_gaussian, t = image_processing.threshold_otsu(gaussian, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_gaussian)
results['otsu_gaussian'].append([s, r, e, noise, sigma])
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
print 'Image %s, bilateral sd=%.2f, sr=%.2f ' % (name, sigmaD,sigmaR)
bilateral = bilateral_filter(image_with_noise, sigmaD, sigmaR)
s, r, e = transformation_energy(image, bilateral)
results['bilateral'].append([s, r, e, noise, sigmaD, sigmaR])
otsu_bilateral, t = image_processing.threshold_otsu(bilateral, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_bilateral)
results['otsu_bilateral'].append([s, r, e, noise, sigmaD, sigmaR])
print 'Generating plot images...'
generate_plot_images(results, name)
# Generate the images that will be visually inspected
# For the given image, calculate:
# 1) Bilateral, gaussian and otsu's without noise
# 2) Bilateral, gaussian and otsu's with noise
# 3) Otsu's with noise, but after applying Bilateral, gaussian filtering
# Result images are saved with the given name as a prefix
def generate_result_images(image, name):
image = add_gaussian_noise(image, 0)
print 'Processing image %s' % name
save_image_png(image, C.output_dir + name)
if (name.startswith('mri')):
noise = C.default_noise_level_mri
else:
noise = C.default_noise_level
image_with_default_noise = add_gaussian_noise(image, noise)
save_image_png(image_with_default_noise, C.output_dir + name + '_noise')
print 'Image %s: bilateral' % name
(sigmaD, sigmaR) = C.default_bilateral_sigma
bilateral = bilateral_filter(image, sigmaD, sigmaR)
save_image_png(bilateral, C.output_dir + name + '_bilateral')
## for sigmaR in [1,2,3,4,5,7,8,9,10,11,12,13,14,15,17,18]:
## bilateral = bilateral_filter(image, sigmaD, sigmaR)
## if (sigmaR<10):
## n='0'+str(sigmaR)
## else:
## n=str(sigmaR)
## save_image_png(bilateral, C.output_dir + name + '_bilateral_'+n)
print 'Image %s: bilateral noise' % name
(sigmaD, sigmaR) = C.default_bilateral_sigma_noise
bilateral_noise = bilateral_filter(image_with_default_noise, sigmaD, sigmaR)
save_image_png(bilateral_noise, C.output_dir + name + '_noise_bilateral')
print 'Image %s: gaussian' % name
sigma = C.default_gaussian_sigma
gaussian = gaussian_filter(image, sigma)
save_image_png(gaussian, C.output_dir + name + '_gaussian')
print 'Image %s: gaussian noise' % name
sigma = C.default_gaussian_sigma_noise
gaussian_noise = gaussian_filter(image_with_default_noise, sigma)
save_image_png(gaussian_noise, C.output_dir + name + '_noise_gaussian')
print 'Image %s: Otsu' % name
otsu, t = image_processing.threshold_otsu(image, C.default_number_of_bins)
save_image_png(otsu, C.output_dir + name + '_otsu')
print 'Image %s: Otsu noise' % name
otsu_noise, t = image_processing.threshold_otsu(image_with_default_noise, C.default_number_of_bins)
save_image_png(otsu_noise, C.output_dir + name + '_otsu_noise')
print 'Image %s: Otsu noise bilateral' % name
otsu_bilateral_noise, t = image_processing.threshold_otsu(bilateral_noise, C.default_number_of_bins)
save_image_png(otsu_bilateral_noise, C.output_dir + name + '_otsu_noise_bilateral')
print 'Image %s: Otsu noise gaussian' % name
otsu_gaussian_noise, t = image_processing.threshold_otsu(gaussian_noise, C.default_number_of_bins)
save_image_png(otsu_gaussian_noise, C.output_dir + name + '_otsu_noise_gaussian')
# reads an image with a given extension from C.input_dir
def read_image(filename,extension):
if (extension=='gz'):
data = load(C.input_dir+ filename + '.'+extension)
image = data.get_data()
else:
image = imread(C.input_dir + filename + '.'+extension)
s = image.shape
if len(s) > 2 and s[2] in [3, 4]: # "detect" rgb images
image = img.rgb2gray(image)
#image= img.rgb2gray_color_preserving(image)
image=rescale_grayscale_image(image)
return image
def main():
|
if __name__ == '__main__':
main()
| set_printoptions(precision=4, linewidth=150, suppress=True) # print values with less precision
params = {'legend.fontsize': 8,
'legend.linewidth': 1,
'legend.labelspacing':0.2,
'legend.loc':2}
rcParams.update(params) # change global plotting parameters
if not os.path.exists(C.output_dir_plots):# generate output_dir_plots
os.makedirs(C.output_dir_plots)
if not os.path.exists(C.output_dir):# generate output_dir
os.makedirs(C.output_dir)
#image sets
synthetic_images=[('borders','png'),
('borders_contrast','png'),
('gradient1','png'),
('gradient2','png'),]
mri_images=[('mri1','png'),
('mri2','png'),
('mri3','png')]
mri_image=[('T1w_acpc_dc_restore_1.25.nii','gz')]
# select image set
#images=synthetic_images+mri_images
#images = mri_image
images=synthetic_images
# for each image, read it, and generate the resulting plots
# for each image, read it, and generate the resulting images
for filename,extension in images:
image = read_image(filename,extension)
#generate_result_images(image,filename)
generate_plots(image, filename) | identifier_body |
tp.py | from pylab import *
from math import exp, sqrt
from image import *
from filters import *
from nibabel import load
import numpy
import image_processing
import image as img
import os
# This module generates
class C:
#a Config class, just a collection of constants
output_dir = '../report/img/results/'
input_dir = '../report/img/input/'
output_dir_plots = '../report/img/plots/'
# algorithm parameters to generate Sim and Reg plots
noise_levels = [0, 0.25, 0.5,1,2,3,5] # noise levels to distort the images
gaussian_sigmas = [0.5,1,2]
bilateral_sigmaDs = [0.5,1,2]
bilateral_sigmaRs = [2,20]
# plot configuration variables
column_names=['sim','reg','e','noise']
colors=['g','r','c','m','y','b'] # for different sigmaD
markers=['<','>','v','^'] # for different sigmaR
lines=['-',''] # for different typtes of algorithms
# algorithm parameters to generate result images
default_noise_level = 1.5
default_noise_level_mri = 1.5
default_gaussian_sigma = 1
default_gaussian_sigma_noise = 1.5
default_bilateral_sigma = (1, 7)
default_bilateral_sigma_noise = (1.5, 7)
default_number_of_bins = 256
# generate the plot for filtering algorithms
def generate_plot_filtering(results,name,column_y):
xlabel('Noise ($\sigma$)')
for sigma in C.gaussian_sigmas:
|
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
bilateral= results['bilateral']
bilateral = bilateral[bilateral[:, 4] == sigmaD]
bilateral = bilateral[bilateral[:, 5] == sigmaR]
label = 'Bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (sigmaD,sigmaR)
style=C.markers[C.bilateral_sigmaRs.index(sigmaR)]+C.colors[C.bilateral_sigmaDs.index(sigmaD)]+'-'
plot(bilateral[:, 3], bilateral[:, column_y],style,label=label )
legend(loc=2)
savepngfig(C.output_dir_plots+name+'_filtering_'+C.column_names[column_y])
# generate the plot for otsu's algorithm, with and without noise and different
# types of filters
def generate_plot_otsu(results,name,column_y):
xlabel('Noise ($\sigma$)')
otsu = results['otsu']
plot(otsu[:, 3], otsu[:, column_y],'-.', label='otsu')
legend(loc=2)
for sigma in C.gaussian_sigmas:
otsu = results['otsu_gaussian']
otsu = otsu[otsu[:, 4] == sigma]
label = 'Otsu with gaussian, $\sigma=%.2f$' % sigma
style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--'
plot(otsu[:, 3], otsu[:, column_y], style,label=label)
legend(loc=1)
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
otsu = results['otsu_bilateral']
otsu = otsu[otsu[:, 4] == sigmaD]
otsu = otsu[otsu[:, 5] == sigmaR]
label = 'Otsu with bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (sigmaD,sigmaR)
style=C.markers[C.bilateral_sigmaRs.index(sigmaR)]+C.colors[C.bilateral_sigmaDs.index(sigmaD)]+'-'
plot(otsu[:, 3], otsu[:, column_y],style, label=label)
legend(loc=1)
savepngfig(C.output_dir_plots+name+'_otsu_'+C.column_names[column_y])
# Generate all the plot images according to the results dictionary
# for image with given name
def generate_plot_images(results, name):
for k in results:
results[k] = array(results[k])
functions=[generate_plot_otsu,generate_plot_filtering]
labels=[(0,'$Sim(I,J)$'),(1,'$Reg(J)$')]
for f in functions:
for (column_y,label) in labels:
figure()
ylabel(label)
f(results,name,column_y)
xlim(0,C.noise_levels[-1]*1.5)
# generate a dictionary with Sim, Reg and E values for every combination of the
# algorithm parameters in class C, for a given image with a certain name
def generate_plots(image, name):
results = {}
results['otsu'] = []
results['otsu_bilateral'] = []
results['otsu_gaussian'] = []
results['bilateral'] = []
results['gaussian'] = []
otsu, t = image_processing.threshold_otsu(image, C.default_number_of_bins)
for noise in C.noise_levels:
print 'Image %s, Noise %.2f ' % (name, noise)
image_with_noise = add_gaussian_noise(image, noise)
print 'Image %s, otsu ' % (name)
otsu_noise, t = image_processing.threshold_otsu(image_with_noise, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_noise)
results['otsu'].append([s, r, e, noise])
for sigma in C.gaussian_sigmas:
print 'Image %s, gaussian s=%.2f ' % (name, sigma)
gaussian = gaussian_filter(image_with_noise, sigma)
s, r, e = transformation_energy(image, gaussian)
results['gaussian'].append([s, r, e, noise, sigma])
if (sigma<2):
otsu_gaussian, t = image_processing.threshold_otsu(gaussian, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_gaussian)
results['otsu_gaussian'].append([s, r, e, noise, sigma])
for sigmaD in C.bilateral_sigmaDs:
for sigmaR in C.bilateral_sigmaRs:
print 'Image %s, bilateral sd=%.2f, sr=%.2f ' % (name, sigmaD,sigmaR)
bilateral = bilateral_filter(image_with_noise, sigmaD, sigmaR)
s, r, e = transformation_energy(image, bilateral)
results['bilateral'].append([s, r, e, noise, sigmaD, sigmaR])
otsu_bilateral, t = image_processing.threshold_otsu(bilateral, C.default_number_of_bins)
s, r, e = transformation_energy(otsu, otsu_bilateral)
results['otsu_bilateral'].append([s, r, e, noise, sigmaD, sigmaR])
print 'Generating plot images...'
generate_plot_images(results, name)
# Generate the images that will be visually inspected
# For the given image, calculate:
# 1) Bilateral, gaussian and otsu's without noise
# 2) Bilateral, gaussian and otsu's with noise
# 3) Otsu's with noise, but after applying Bilateral, gaussian filtering
# Result images are saved with the given name as a prefix
def generate_result_images(image, name):
image = add_gaussian_noise(image, 0)
print 'Processing image %s' % name
save_image_png(image, C.output_dir + name)
if (name.startswith('mri')):
noise = C.default_noise_level_mri
else:
noise = C.default_noise_level
image_with_default_noise = add_gaussian_noise(image, noise)
save_image_png(image_with_default_noise, C.output_dir + name + '_noise')
print 'Image %s: bilateral' % name
(sigmaD, sigmaR) = C.default_bilateral_sigma
bilateral = bilateral_filter(image, sigmaD, sigmaR)
save_image_png(bilateral, C.output_dir + name + '_bilateral')
## for sigmaR in [1,2,3,4,5,7,8,9,10,11,12,13,14,15,17,18]:
## bilateral = bilateral_filter(image, sigmaD, sigmaR)
## if (sigmaR<10):
## n='0'+str(sigmaR)
## else:
## n=str(sigmaR)
## save_image_png(bilateral, C.output_dir + name + '_bilateral_'+n)
print 'Image %s: bilateral noise' % name
(sigmaD, sigmaR) = C.default_bilateral_sigma_noise
bilateral_noise = bilateral_filter(image_with_default_noise, sigmaD, sigmaR)
save_image_png(bilateral_noise, C.output_dir + name + '_noise_bilateral')
print 'Image %s: gaussian' % name
sigma = C.default_gaussian_sigma
gaussian = gaussian_filter(image, sigma)
save_image_png(gaussian, C.output_dir + name + '_gaussian')
print 'Image %s: gaussian noise' % name
sigma = C.default_gaussian_sigma_noise
gaussian_noise = gaussian_filter(image_with_default_noise, sigma)
save_image_png(gaussian_noise, C.output_dir + name + '_noise_gaussian')
print 'Image %s: Otsu' % name
otsu, t = image_processing.threshold_otsu(image, C.default_number_of_bins)
save_image_png(otsu, C.output_dir + name + '_otsu')
print 'Image %s: Otsu noise' % name
otsu_noise, t = image_processing.threshold_otsu(image_with_default_noise, C.default_number_of_bins)
save_image_png(otsu_noise, C.output_dir + name + '_otsu_noise')
print 'Image %s: Otsu noise bilateral' % name
otsu_bilateral_noise, t = image_processing.threshold_otsu(bilateral_noise, C.default_number_of_bins)
save_image_png(otsu_bilateral_noise, C.output_dir + name + '_otsu_noise_bilateral')
print 'Image %s: Otsu noise gaussian' % name
otsu_gaussian_noise, t = image_processing.threshold_otsu(gaussian_noise, C.default_number_of_bins)
save_image_png(otsu_gaussian_noise, C.output_dir + name + '_otsu_noise_gaussian')
# reads an image with a given extension from C.input_dir
def read_image(filename,extension):
if (extension=='gz'):
data = load(C.input_dir+ filename + '.'+extension)
image = data.get_data()
else:
image = imread(C.input_dir + filename + '.'+extension)
s = image.shape
if len(s) > 2 and s[2] in [3, 4]: # "detect" rgb images
image = img.rgb2gray(image)
#image= img.rgb2gray_color_preserving(image)
image=rescale_grayscale_image(image)
return image
def main():
set_printoptions(precision=4, linewidth=150, suppress=True) # print values with less precision
params = {'legend.fontsize': 8,
'legend.linewidth': 1,
'legend.labelspacing':0.2,
'legend.loc':2}
rcParams.update(params) # change global plotting parameters
if not os.path.exists(C.output_dir_plots):# generate output_dir_plots
os.makedirs(C.output_dir_plots)
if not os.path.exists(C.output_dir):# generate output_dir
os.makedirs(C.output_dir)
#image sets
synthetic_images=[('borders','png'),
('borders_contrast','png'),
('gradient1','png'),
('gradient2','png'),]
mri_images=[('mri1','png'),
('mri2','png'),
('mri3','png')]
mri_image=[('T1w_acpc_dc_restore_1.25.nii','gz')]
# select image set
#images=synthetic_images+mri_images
#images = mri_image
images=synthetic_images
# for each image, read it, and generate the resulting plots
# for each image, read it, and generate the resulting images
for filename,extension in images:
image = read_image(filename,extension)
#generate_result_images(image,filename)
generate_plots(image, filename)
if __name__ == '__main__':
main()
| gaussian = results['gaussian']
gaussian = gaussian[gaussian[:, 4] == sigma]
label = 'Gaussian, $\sigma=%.2f$' % sigma
style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--'
plot(gaussian[:, 3], gaussian[:, column_y], style,label=label)
legend(loc=2) | conditional_block |
extract_images_to_s3.py | import os
import posixpath
import random
import string
import logging
import tempfile
import time
from .extract_images import ExtractImages
logger = logging.getLogger(__name__)
class ExtractImagesToS3(ExtractImages):
'''
This KnowledgePostProcessor subclass extracts images from posts to S3. It
is designed to be used upon addition to a knowledge repository, which can
reduce the size of repositories. It replaces local images with remote urls
based on `http_image_root`.
`s3_image_root` should be the root of the image folder on an S3 remote, such
as "s3://my_bucket/images".
`http_image_root` should be the root of the server where the images will be
accessible after uploading.
Note: This requires that user AWS credentials are set up appropriately and
that they have installed the aws cli packages.
'''
_registry_keys = ['extract_images_to_s3']
def __init__(self, s3_image_root, http_image_root):
self.s3_image_root = s3_image_root
self.http_image_root = http_image_root
def copy_image(self, kp, img_path, is_ref=False, repo_name='knowledge'):
# Copy image data to new file
if is_ref:
_, tmp_path = tempfile.mkstemp()
with open(tmp_path, 'wb') as f:
f.write(kp._read_ref(img_path))
else:
tmp_path = img_path
try:
# Get image type
img_ext = posixpath.splitext(img_path)[1]
# Make random filename for image
random_string = ''.join(random.choice(string.ascii_lowercase) for i in range(6))
fname_img = '{repo_name}_{time}_{random_string}{ext}'.format(
repo_name=repo_name,
time=int(round(time.time() * 100)),
random_string=random_string,
ext=img_ext).strip().replace(' ', '-')
| # for example, to handle multi-factor authentication.
cmd = "aws s3 cp '{0}' {1}".format(tmp_path, fname_s3)
logger.info("Uploading images to S3: {cmd}".format(cmd=cmd))
retval = os.system(cmd)
if retval != 0:
raise Exception('Problem uploading images to s3')
finally:
# Clean up temporary file
if is_ref:
os.remove(tmp_path)
# return uploaded path of file
return posixpath.join(self.http_image_root, repo_name, fname_img)
def skip_image(self, kp, image):
import re
if re.match('http[s]?://', image['src']):
return True
return False
def cleanup(self, kp):
if kp._has_ref('images'):
kp._drop_ref('images') | # Copy image to accessible folder on S3
fname_s3 = posixpath.join(self.s3_image_root, repo_name, fname_img)
# Note: The following command may need to be prefixed with a login agent; | random_line_split |
extract_images_to_s3.py | import os
import posixpath
import random
import string
import logging
import tempfile
import time
from .extract_images import ExtractImages
logger = logging.getLogger(__name__)
class ExtractImagesToS3(ExtractImages):
'''
This KnowledgePostProcessor subclass extracts images from posts to S3. It
is designed to be used upon addition to a knowledge repository, which can
reduce the size of repositories. It replaces local images with remote urls
based on `http_image_root`.
`s3_image_root` should be the root of the image folder on an S3 remote, such
as "s3://my_bucket/images".
`http_image_root` should be the root of the server where the images will be
accessible after uploading.
Note: This requires that user AWS credentials are set up appropriately and
that they have installed the aws cli packages.
'''
_registry_keys = ['extract_images_to_s3']
def __init__(self, s3_image_root, http_image_root):
self.s3_image_root = s3_image_root
self.http_image_root = http_image_root
def copy_image(self, kp, img_path, is_ref=False, repo_name='knowledge'):
# Copy image data to new file
|
def skip_image(self, kp, image):
import re
if re.match('http[s]?://', image['src']):
return True
return False
def cleanup(self, kp):
if kp._has_ref('images'):
kp._drop_ref('images')
| if is_ref:
_, tmp_path = tempfile.mkstemp()
with open(tmp_path, 'wb') as f:
f.write(kp._read_ref(img_path))
else:
tmp_path = img_path
try:
# Get image type
img_ext = posixpath.splitext(img_path)[1]
# Make random filename for image
random_string = ''.join(random.choice(string.ascii_lowercase) for i in range(6))
fname_img = '{repo_name}_{time}_{random_string}{ext}'.format(
repo_name=repo_name,
time=int(round(time.time() * 100)),
random_string=random_string,
ext=img_ext).strip().replace(' ', '-')
# Copy image to accessible folder on S3
fname_s3 = posixpath.join(self.s3_image_root, repo_name, fname_img)
# Note: The following command may need to be prefixed with a login agent;
# for example, to handle multi-factor authentication.
cmd = "aws s3 cp '{0}' {1}".format(tmp_path, fname_s3)
logger.info("Uploading images to S3: {cmd}".format(cmd=cmd))
retval = os.system(cmd)
if retval != 0:
raise Exception('Problem uploading images to s3')
finally:
# Clean up temporary file
if is_ref:
os.remove(tmp_path)
# return uploaded path of file
return posixpath.join(self.http_image_root, repo_name, fname_img) | identifier_body |
extract_images_to_s3.py | import os
import posixpath
import random
import string
import logging
import tempfile
import time
from .extract_images import ExtractImages
logger = logging.getLogger(__name__)
class ExtractImagesToS3(ExtractImages):
'''
This KnowledgePostProcessor subclass extracts images from posts to S3. It
is designed to be used upon addition to a knowledge repository, which can
reduce the size of repositories. It replaces local images with remote urls
based on `http_image_root`.
`s3_image_root` should be the root of the image folder on an S3 remote, such
as "s3://my_bucket/images".
`http_image_root` should be the root of the server where the images will be
accessible after uploading.
Note: This requires that user AWS credentials are set up appropriately and
that they have installed the aws cli packages.
'''
_registry_keys = ['extract_images_to_s3']
def __init__(self, s3_image_root, http_image_root):
self.s3_image_root = s3_image_root
self.http_image_root = http_image_root
def copy_image(self, kp, img_path, is_ref=False, repo_name='knowledge'):
# Copy image data to new file
if is_ref:
_, tmp_path = tempfile.mkstemp()
with open(tmp_path, 'wb') as f:
f.write(kp._read_ref(img_path))
else:
tmp_path = img_path
try:
# Get image type
img_ext = posixpath.splitext(img_path)[1]
# Make random filename for image
random_string = ''.join(random.choice(string.ascii_lowercase) for i in range(6))
fname_img = '{repo_name}_{time}_{random_string}{ext}'.format(
repo_name=repo_name,
time=int(round(time.time() * 100)),
random_string=random_string,
ext=img_ext).strip().replace(' ', '-')
# Copy image to accessible folder on S3
fname_s3 = posixpath.join(self.s3_image_root, repo_name, fname_img)
# Note: The following command may need to be prefixed with a login agent;
# for example, to handle multi-factor authentication.
cmd = "aws s3 cp '{0}' {1}".format(tmp_path, fname_s3)
logger.info("Uploading images to S3: {cmd}".format(cmd=cmd))
retval = os.system(cmd)
if retval != 0:
raise Exception('Problem uploading images to s3')
finally:
# Clean up temporary file
if is_ref:
os.remove(tmp_path)
# return uploaded path of file
return posixpath.join(self.http_image_root, repo_name, fname_img)
def skip_image(self, kp, image):
import re
if re.match('http[s]?://', image['src']):
|
return False
def cleanup(self, kp):
if kp._has_ref('images'):
kp._drop_ref('images')
| return True | conditional_block |
extract_images_to_s3.py | import os
import posixpath
import random
import string
import logging
import tempfile
import time
from .extract_images import ExtractImages
logger = logging.getLogger(__name__)
class | (ExtractImages):
'''
This KnowledgePostProcessor subclass extracts images from posts to S3. It
is designed to be used upon addition to a knowledge repository, which can
reduce the size of repositories. It replaces local images with remote urls
based on `http_image_root`.
`s3_image_root` should be the root of the image folder on an S3 remote, such
as "s3://my_bucket/images".
`http_image_root` should be the root of the server where the images will be
accessible after uploading.
Note: This requires that user AWS credentials are set up appropriately and
that they have installed the aws cli packages.
'''
_registry_keys = ['extract_images_to_s3']
def __init__(self, s3_image_root, http_image_root):
self.s3_image_root = s3_image_root
self.http_image_root = http_image_root
def copy_image(self, kp, img_path, is_ref=False, repo_name='knowledge'):
# Copy image data to new file
if is_ref:
_, tmp_path = tempfile.mkstemp()
with open(tmp_path, 'wb') as f:
f.write(kp._read_ref(img_path))
else:
tmp_path = img_path
try:
# Get image type
img_ext = posixpath.splitext(img_path)[1]
# Make random filename for image
random_string = ''.join(random.choice(string.ascii_lowercase) for i in range(6))
fname_img = '{repo_name}_{time}_{random_string}{ext}'.format(
repo_name=repo_name,
time=int(round(time.time() * 100)),
random_string=random_string,
ext=img_ext).strip().replace(' ', '-')
# Copy image to accessible folder on S3
fname_s3 = posixpath.join(self.s3_image_root, repo_name, fname_img)
# Note: The following command may need to be prefixed with a login agent;
# for example, to handle multi-factor authentication.
cmd = "aws s3 cp '{0}' {1}".format(tmp_path, fname_s3)
logger.info("Uploading images to S3: {cmd}".format(cmd=cmd))
retval = os.system(cmd)
if retval != 0:
raise Exception('Problem uploading images to s3')
finally:
# Clean up temporary file
if is_ref:
os.remove(tmp_path)
# return uploaded path of file
return posixpath.join(self.http_image_root, repo_name, fname_img)
def skip_image(self, kp, image):
import re
if re.match('http[s]?://', image['src']):
return True
return False
def cleanup(self, kp):
if kp._has_ref('images'):
kp._drop_ref('images')
| ExtractImagesToS3 | identifier_name |
SHA224.py | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""SHA-224 cryptographic hash algorithm.
SHA-224 belongs to the SHA-2_ family of cryptographic hashes.
It produces the 224 bit digest of a message.
>>> from Cryptodome.Hash import SHA224
>>>
>>> h = SHA224.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Secure Hash Algorithm.
.. _SHA-2: http://csrc.nist.gov/publications/fips/fips180-2/fips180-4.pdf
"""
from Cryptodome.Util.py3compat import *
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
VoidPointer, SmartPointer,
create_string_buffer,
get_raw_buffer, c_size_t,
expect_byte_string)
_raw_sha224_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._SHA224",
"""
int SHA224_init(void **shaState);
int SHA224_destroy(void *shaState);
int SHA224_update(void *hs,
const uint8_t *buf,
size_t len);
int SHA224_digest(const void *shaState,
uint8_t digest[16]);
int SHA224_copy(const void *src, void *dst);
""")
class SHA224Hash(object):
"""Class that implements a SHA-224 hash
"""
#: The size of the resulting hash in bytes.
digest_size = 28
#: The internal block size of the hash algorithm in bytes.
block_size = 64
#: ASN.1 Object ID
oid = '2.16.840.1.101.3.4.2.4'
def __init__(self, data=None):
state = VoidPointer()
result = _raw_sha224_lib.SHA224_init(state.address_of())
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
self._state = SmartPointer(state.get(),
_raw_sha224_lib.SHA224_destroy)
if data:
self.update(data)
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_sha224_lib.SHA224_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_sha224_lib.SHA224_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
return get_raw_buffer(bfr)
def hexdigest(self):
"""Return the **printable** digest of the message that has been hashed so far.
This method does not change the state of the hash object.
:Return: A string of 2* `digest_size` characters. It contains only
hexadecimal ASCII digits.
"""
return "".join(["%02x" % bord(x) for x in self.digest()])
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = SHA224Hash()
result = _raw_sha224_lib.SHA224_copy(self._state.get(),
clone._state.get())
if result:
|
return clone
def new(self, data=None):
return SHA224Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `SHA224Hash.update()`.
Optional.
:Return: A `SHA224Hash` object
"""
return SHA224Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = SHA224Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = SHA224Hash.block_size
| raise ValueError("Error %d while copying SHA224" % result) | conditional_block |
SHA224.py | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""SHA-224 cryptographic hash algorithm.
SHA-224 belongs to the SHA-2_ family of cryptographic hashes.
It produces the 224 bit digest of a message.
>>> from Cryptodome.Hash import SHA224
>>>
>>> h = SHA224.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Secure Hash Algorithm.
.. _SHA-2: http://csrc.nist.gov/publications/fips/fips180-2/fips180-4.pdf
"""
from Cryptodome.Util.py3compat import *
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
VoidPointer, SmartPointer,
create_string_buffer,
get_raw_buffer, c_size_t,
expect_byte_string)
_raw_sha224_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._SHA224",
"""
int SHA224_init(void **shaState);
int SHA224_destroy(void *shaState);
int SHA224_update(void *hs,
const uint8_t *buf,
size_t len);
int SHA224_digest(const void *shaState,
uint8_t digest[16]);
int SHA224_copy(const void *src, void *dst);
""")
class SHA224Hash(object):
"""Class that implements a SHA-224 hash
"""
#: The size of the resulting hash in bytes.
digest_size = 28
#: The internal block size of the hash algorithm in bytes.
block_size = 64
#: ASN.1 Object ID
oid = '2.16.840.1.101.3.4.2.4'
def | (self, data=None):
state = VoidPointer()
result = _raw_sha224_lib.SHA224_init(state.address_of())
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
self._state = SmartPointer(state.get(),
_raw_sha224_lib.SHA224_destroy)
if data:
self.update(data)
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_sha224_lib.SHA224_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_sha224_lib.SHA224_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
return get_raw_buffer(bfr)
def hexdigest(self):
"""Return the **printable** digest of the message that has been hashed so far.
This method does not change the state of the hash object.
:Return: A string of 2* `digest_size` characters. It contains only
hexadecimal ASCII digits.
"""
return "".join(["%02x" % bord(x) for x in self.digest()])
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = SHA224Hash()
result = _raw_sha224_lib.SHA224_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying SHA224" % result)
return clone
def new(self, data=None):
return SHA224Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `SHA224Hash.update()`.
Optional.
:Return: A `SHA224Hash` object
"""
return SHA224Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = SHA224Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = SHA224Hash.block_size
| __init__ | identifier_name |
SHA224.py | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""SHA-224 cryptographic hash algorithm.
SHA-224 belongs to the SHA-2_ family of cryptographic hashes.
It produces the 224 bit digest of a message.
>>> from Cryptodome.Hash import SHA224
>>>
>>> h = SHA224.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Secure Hash Algorithm.
.. _SHA-2: http://csrc.nist.gov/publications/fips/fips180-2/fips180-4.pdf
"""
from Cryptodome.Util.py3compat import *
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
VoidPointer, SmartPointer,
create_string_buffer,
get_raw_buffer, c_size_t,
expect_byte_string)
_raw_sha224_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._SHA224",
"""
int SHA224_init(void **shaState);
int SHA224_destroy(void *shaState);
int SHA224_update(void *hs,
const uint8_t *buf,
size_t len);
int SHA224_digest(const void *shaState,
uint8_t digest[16]);
int SHA224_copy(const void *src, void *dst);
""")
class SHA224Hash(object):
"""Class that implements a SHA-224 hash
"""
#: The size of the resulting hash in bytes.
digest_size = 28
#: The internal block size of the hash algorithm in bytes.
block_size = 64
#: ASN.1 Object ID
oid = '2.16.840.1.101.3.4.2.4'
def __init__(self, data=None):
state = VoidPointer()
result = _raw_sha224_lib.SHA224_init(state.address_of())
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
self._state = SmartPointer(state.get(),
_raw_sha224_lib.SHA224_destroy)
if data:
self.update(data)
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_sha224_lib.SHA224_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
def digest(self):
|
def hexdigest(self):
"""Return the **printable** digest of the message that has been hashed so far.
This method does not change the state of the hash object.
:Return: A string of 2* `digest_size` characters. It contains only
hexadecimal ASCII digits.
"""
return "".join(["%02x" % bord(x) for x in self.digest()])
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = SHA224Hash()
result = _raw_sha224_lib.SHA224_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying SHA224" % result)
return clone
def new(self, data=None):
return SHA224Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `SHA224Hash.update()`.
Optional.
:Return: A `SHA224Hash` object
"""
return SHA224Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = SHA224Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = SHA224Hash.block_size
| """Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_sha224_lib.SHA224_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
return get_raw_buffer(bfr) | identifier_body |
SHA224.py | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""SHA-224 cryptographic hash algorithm.
SHA-224 belongs to the SHA-2_ family of cryptographic hashes.
It produces the 224 bit digest of a message.
>>> from Cryptodome.Hash import SHA224
>>>
>>> h = SHA224.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Secure Hash Algorithm.
.. _SHA-2: http://csrc.nist.gov/publications/fips/fips180-2/fips180-4.pdf
"""
from Cryptodome.Util.py3compat import *
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
VoidPointer, SmartPointer,
create_string_buffer,
get_raw_buffer, c_size_t,
expect_byte_string)
_raw_sha224_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._SHA224",
"""
int SHA224_init(void **shaState);
int SHA224_destroy(void *shaState);
int SHA224_update(void *hs,
const uint8_t *buf,
size_t len);
int SHA224_digest(const void *shaState,
uint8_t digest[16]);
int SHA224_copy(const void *src, void *dst);
""")
class SHA224Hash(object):
"""Class that implements a SHA-224 hash
"""
#: The size of the resulting hash in bytes.
digest_size = 28
#: The internal block size of the hash algorithm in bytes.
block_size = 64
#: ASN.1 Object ID
oid = '2.16.840.1.101.3.4.2.4'
def __init__(self, data=None):
state = VoidPointer()
result = _raw_sha224_lib.SHA224_init(state.address_of())
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
self._state = SmartPointer(state.get(),
_raw_sha224_lib.SHA224_destroy)
if data:
self.update(data)
def update(self, data):
"""Continue hashing of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to: |
>>> m.update(a+b)
:Parameters:
data : byte string
The next chunk of the message being hashed.
"""
expect_byte_string(data)
result = _raw_sha224_lib.SHA224_update(self._state.get(),
data,
c_size_t(len(data)))
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_sha224_lib.SHA224_digest(self._state.get(),
bfr)
if result:
raise ValueError("Error %d while instantiating SHA224"
% result)
return get_raw_buffer(bfr)
def hexdigest(self):
"""Return the **printable** digest of the message that has been hashed so far.
This method does not change the state of the hash object.
:Return: A string of 2* `digest_size` characters. It contains only
hexadecimal ASCII digits.
"""
return "".join(["%02x" % bord(x) for x in self.digest()])
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
clone = SHA224Hash()
result = _raw_sha224_lib.SHA224_copy(self._state.get(),
clone._state.get())
if result:
raise ValueError("Error %d while copying SHA224" % result)
return clone
def new(self, data=None):
return SHA224Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `SHA224Hash.update()`.
Optional.
:Return: A `SHA224Hash` object
"""
return SHA224Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = SHA224Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = SHA224Hash.block_size | random_line_split | |
run.ts | import chai from 'chai';
import { unlink, writeFileSync } from 'fs';
import { sync } from 'mkdirp';
import Mocha, { Reporter, ReporterConstructor } from 'mocha';
import { tmpdir } from 'os';
import { join } from 'path';
import { TestResults } from './entities';
import { Insomnia, InsomniaOptions } from './insomnia';
import { JavaScriptReporter } from './javascript-reporter';
declare global {
namespace NodeJS {
interface Global {
insomnia?: Insomnia;
chai?: typeof chai;
}
}
}
const runInternal = async <TReturn, TNetworkResponse>(
testSrc: string | string[],
options: InsomniaOptions<TNetworkResponse>,
reporter: Reporter | ReporterConstructor = 'spec',
extractResult: (runner: Mocha.Runner) => TReturn,
) => new Promise<TReturn>((resolve, reject) => {
const { bail, keepFile, testFilter } = options;
// Add global `insomnia` helper.
// This is the only way to add new globals to the Mocha environment as far as I can tell
global.insomnia = new Insomnia(options);
global.chai = chai;
const mocha: Mocha = new Mocha({
// ms * sec * min
timeout: 1000 * 60 * 1,
globals: ['insomnia', 'chai'],
bail,
reporter,
// @ts-expect-error https://github.com/DefinitelyTyped/DefinitelyTyped/pull/51770
fgrep: testFilter,
});
const sources = Array.isArray(testSrc) ? testSrc : [testSrc];
sources.forEach(source => {
mocha.addFile(writeTempFile(source));
});
try {
const runner = mocha.run(() => {
resolve(extractResult(runner));
// Remove global since we don't need it anymore
delete global.insomnia;
delete global.chai;
if (keepFile && mocha.files.length) |
// Clean up temp files
mocha.files.forEach(file => {
unlink(file, err => {
if (err) {
console.log('Failed to clean up test file', file, err);
}
});
});
});
} catch (err) {
reject(err);
}
});
/**
* Copy test to tmp dir and return the file path
*/
const writeTempFile = (sourceCode: string) => {
const root = join(tmpdir(), 'insomnia-testing');
sync(root);
const path = join(root, `${Math.random()}-test.ts`);
writeFileSync(path, sourceCode);
return path;
};
type CliOptions<TNetworkResponse> = InsomniaOptions<TNetworkResponse> & {
reporter?: Reporter;
};
/**
* Run a test file using Mocha
*/
export const runTestsCli = async <TNetworkResponse>(
testSrc: string | string[],
{ reporter, ...options }: CliOptions<TNetworkResponse>,
) => runInternal(
testSrc,
options,
reporter,
runner => !Boolean(runner.stats?.failures),
);
/**
* Run a test file using Mocha and returns JS results
*/
export const runTests = async <TNetworkResponse>(
testSrc: string | string[],
options: InsomniaOptions<TNetworkResponse>,
) => runInternal(
testSrc,
options,
JavaScriptReporter,
// @ts-expect-error the `testResults` property is added onto the runner by the JavascriptReporter
runner => runner.testResults as TestResults,
);
| {
console.log(`Test files: ${JSON.stringify(mocha.files)}.`);
return;
} | conditional_block |
user.component.ts | import { Component, OnInit } from "@angular/core";
import { CommonComponent } from "./common.component";
import { UserService } from "../services/resource.service";
import { MessageService } from "../services/message";
import { FormControl, Validators, FormGroup, FormBuilder } from "@angular/forms";
import { User, Message } from '../model';
import * as com from "../common";
import * as _ from 'lodash';
declare var $;
@Component({
selector: 'user',
templateUrl: '../../assets/templates/user.component.html',
providers: [UserService, MessageService]
})
export class UserComponent extends CommonComponent{
admin: string = ""; // used for select ele
users: User[];
currentUser: User = new User();
oldUser: User = new User();
constructor(public messageService: MessageService, public fb: FormBuilder, private userService: UserService){
super(messageService, fb, userService, "user");
this.form = fb.group({
"userName": this.nameCtl,
"groupName": this.groupCtl,
"appTeamName": this.appTeamCtl,
"serviceID": this.serviceIDCtl,
"email": this.emailCtl,
"emailForEmg": this.emailForEmgCtl,
"password": this.passwordCtl
});
}
ngOnInit(): void {
super.ngOnInit();
this.getRecords();
}
getRecords(){
var callback = (result: any[]) : void => {
this.users = result;
this.eleActive = [];
this.eleHovered = [];
for (var i = 0; i < this.users.length; i++){
this.users[i].last_login_at = com.formatTime(this.users[i].last_login_at);
this.users[i].created_at = com.formatTime(this.users[i].created_at);
this.users[i].updated_at = com.formatTime(this.users[i].updated_at);
this.eleActive.push(new Array<boolean>());
this.eleHovered.push(new Array<boolean>());
for(var j = 0; j < 5; j++){
this.eleActive[i].push(false);
this.eleHovered[i].push(false);
}
}
}
super._getRecords(this.userService, callback);
}
addRecord(){
this.currentUser.admin = false;
var callback = (result: any) : void => {
if(result == "ok") {
this.getRecords();
}
}
super._addRecord(this.userService, this.currentUser.user_name, this.currentUser, callback);
}
editRecord(param?:any){
super.submitEdit();
this.currentUser.admin = this.admin == "true"? true: false;
var callback = (result: any) : void => {
if(result == "ok") {
for( var i = 0; i < this.users.length; i++){
if (this.users[i].user_name == this.oldUser.user_name)
{
// this.users[r + this.itemNumPerPage * (this.curentP -1)] = _.cloneDeep(this.currentUser); //if don't clone, when click add user, the record editted last time will be set as empty
this.users[i] = _.cloneDeep(this.currentUser); //if don't clone, when click, the record editted last time will be set as empty
}
}
}
}
super._editRecord(this.userService, this.currentUser.user_name, this.oldUser, this.currentUser, callback, true, param);
}
deleteRecord(){
var callback = (result: any) : void => {
if(result == "ok") {
this.getRecords();
}
}
super._deleteRecord(this.userService, this.currentUser.user_name, callback);
}
openAddModal(){
super.openAddModal();
this.checkboxControl = new FormControl(false);
}
openDelModal(obj) |
onEdit(row, col, obj){
super.onEdit(row, col, obj);
this.admin = obj.admin? "true": "false";
this.currentUser = _.cloneDeep(obj);
this.oldUser = _.cloneDeep(obj);
}
}
| {
this.currentUser = _.cloneDeep(obj);
} | identifier_body |
user.component.ts | import { Component, OnInit } from "@angular/core";
import { CommonComponent } from "./common.component";
import { UserService } from "../services/resource.service";
import { MessageService } from "../services/message";
import { FormControl, Validators, FormGroup, FormBuilder } from "@angular/forms";
import { User, Message } from '../model';
import * as com from "../common";
import * as _ from 'lodash';
declare var $;
@Component({
selector: 'user',
templateUrl: '../../assets/templates/user.component.html',
providers: [UserService, MessageService]
})
export class UserComponent extends CommonComponent{
admin: string = ""; // used for select ele
users: User[];
currentUser: User = new User();
oldUser: User = new User();
constructor(public messageService: MessageService, public fb: FormBuilder, private userService: UserService){
super(messageService, fb, userService, "user");
this.form = fb.group({
"userName": this.nameCtl,
"groupName": this.groupCtl,
"appTeamName": this.appTeamCtl,
"serviceID": this.serviceIDCtl,
"email": this.emailCtl,
"emailForEmg": this.emailForEmgCtl,
"password": this.passwordCtl
});
}
| (): void {
super.ngOnInit();
this.getRecords();
}
getRecords(){
var callback = (result: any[]) : void => {
this.users = result;
this.eleActive = [];
this.eleHovered = [];
for (var i = 0; i < this.users.length; i++){
this.users[i].last_login_at = com.formatTime(this.users[i].last_login_at);
this.users[i].created_at = com.formatTime(this.users[i].created_at);
this.users[i].updated_at = com.formatTime(this.users[i].updated_at);
this.eleActive.push(new Array<boolean>());
this.eleHovered.push(new Array<boolean>());
for(var j = 0; j < 5; j++){
this.eleActive[i].push(false);
this.eleHovered[i].push(false);
}
}
}
super._getRecords(this.userService, callback);
}
addRecord(){
this.currentUser.admin = false;
var callback = (result: any) : void => {
if(result == "ok") {
this.getRecords();
}
}
super._addRecord(this.userService, this.currentUser.user_name, this.currentUser, callback);
}
editRecord(param?:any){
super.submitEdit();
this.currentUser.admin = this.admin == "true"? true: false;
var callback = (result: any) : void => {
if(result == "ok") {
for( var i = 0; i < this.users.length; i++){
if (this.users[i].user_name == this.oldUser.user_name)
{
// this.users[r + this.itemNumPerPage * (this.curentP -1)] = _.cloneDeep(this.currentUser); //if don't clone, when click add user, the record editted last time will be set as empty
this.users[i] = _.cloneDeep(this.currentUser); //if don't clone, when click, the record editted last time will be set as empty
}
}
}
}
super._editRecord(this.userService, this.currentUser.user_name, this.oldUser, this.currentUser, callback, true, param);
}
deleteRecord(){
var callback = (result: any) : void => {
if(result == "ok") {
this.getRecords();
}
}
super._deleteRecord(this.userService, this.currentUser.user_name, callback);
}
openAddModal(){
super.openAddModal();
this.checkboxControl = new FormControl(false);
}
openDelModal(obj){
this.currentUser = _.cloneDeep(obj);
}
onEdit(row, col, obj){
super.onEdit(row, col, obj);
this.admin = obj.admin? "true": "false";
this.currentUser = _.cloneDeep(obj);
this.oldUser = _.cloneDeep(obj);
}
}
| ngOnInit | identifier_name |
user.component.ts | import { Component, OnInit } from "@angular/core";
import { CommonComponent } from "./common.component";
import { UserService } from "../services/resource.service";
import { MessageService } from "../services/message";
import { FormControl, Validators, FormGroup, FormBuilder } from "@angular/forms";
import { User, Message } from '../model';
import * as com from "../common";
import * as _ from 'lodash';
declare var $;
@Component({
selector: 'user',
templateUrl: '../../assets/templates/user.component.html',
providers: [UserService, MessageService]
})
export class UserComponent extends CommonComponent{
admin: string = ""; // used for select ele
users: User[];
currentUser: User = new User();
oldUser: User = new User();
constructor(public messageService: MessageService, public fb: FormBuilder, private userService: UserService){
super(messageService, fb, userService, "user");
this.form = fb.group({
"userName": this.nameCtl,
"groupName": this.groupCtl,
"appTeamName": this.appTeamCtl,
"serviceID": this.serviceIDCtl,
"email": this.emailCtl,
"emailForEmg": this.emailForEmgCtl,
"password": this.passwordCtl
});
}
ngOnInit(): void {
super.ngOnInit();
this.getRecords();
}
getRecords(){
var callback = (result: any[]) : void => {
this.users = result;
this.eleActive = [];
this.eleHovered = [];
for (var i = 0; i < this.users.length; i++){
this.users[i].last_login_at = com.formatTime(this.users[i].last_login_at);
this.users[i].created_at = com.formatTime(this.users[i].created_at);
this.users[i].updated_at = com.formatTime(this.users[i].updated_at);
this.eleActive.push(new Array<boolean>());
this.eleHovered.push(new Array<boolean>());
for(var j = 0; j < 5; j++){
this.eleActive[i].push(false);
this.eleHovered[i].push(false);
}
}
}
super._getRecords(this.userService, callback);
}
addRecord(){
this.currentUser.admin = false;
var callback = (result: any) : void => {
if(result == "ok") {
this.getRecords();
}
}
super._addRecord(this.userService, this.currentUser.user_name, this.currentUser, callback);
}
editRecord(param?:any){
super.submitEdit();
this.currentUser.admin = this.admin == "true"? true: false;
var callback = (result: any) : void => {
if(result == "ok") |
}
super._editRecord(this.userService, this.currentUser.user_name, this.oldUser, this.currentUser, callback, true, param);
}
deleteRecord(){
var callback = (result: any) : void => {
if(result == "ok") {
this.getRecords();
}
}
super._deleteRecord(this.userService, this.currentUser.user_name, callback);
}
openAddModal(){
super.openAddModal();
this.checkboxControl = new FormControl(false);
}
openDelModal(obj){
this.currentUser = _.cloneDeep(obj);
}
onEdit(row, col, obj){
super.onEdit(row, col, obj);
this.admin = obj.admin? "true": "false";
this.currentUser = _.cloneDeep(obj);
this.oldUser = _.cloneDeep(obj);
}
}
| {
for( var i = 0; i < this.users.length; i++){
if (this.users[i].user_name == this.oldUser.user_name)
{
// this.users[r + this.itemNumPerPage * (this.curentP -1)] = _.cloneDeep(this.currentUser); //if don't clone, when click add user, the record editted last time will be set as empty
this.users[i] = _.cloneDeep(this.currentUser); //if don't clone, when click, the record editted last time will be set as empty
}
}
} | conditional_block |
user.component.ts | import { Component, OnInit } from "@angular/core";
import { CommonComponent } from "./common.component";
import { UserService } from "../services/resource.service";
import { MessageService } from "../services/message";
import { FormControl, Validators, FormGroup, FormBuilder } from "@angular/forms";
import { User, Message } from '../model';
import * as com from "../common";
import * as _ from 'lodash';
declare var $;
@Component({
selector: 'user',
templateUrl: '../../assets/templates/user.component.html',
providers: [UserService, MessageService]
})
export class UserComponent extends CommonComponent{
admin: string = ""; // used for select ele
users: User[];
currentUser: User = new User();
oldUser: User = new User();
constructor(public messageService: MessageService, public fb: FormBuilder, private userService: UserService){
super(messageService, fb, userService, "user");
this.form = fb.group({
"userName": this.nameCtl,
"groupName": this.groupCtl,
"appTeamName": this.appTeamCtl,
"serviceID": this.serviceIDCtl,
"email": this.emailCtl,
"emailForEmg": this.emailForEmgCtl,
"password": this.passwordCtl
});
}
ngOnInit(): void {
super.ngOnInit();
this.getRecords(); | getRecords(){
var callback = (result: any[]) : void => {
this.users = result;
this.eleActive = [];
this.eleHovered = [];
for (var i = 0; i < this.users.length; i++){
this.users[i].last_login_at = com.formatTime(this.users[i].last_login_at);
this.users[i].created_at = com.formatTime(this.users[i].created_at);
this.users[i].updated_at = com.formatTime(this.users[i].updated_at);
this.eleActive.push(new Array<boolean>());
this.eleHovered.push(new Array<boolean>());
for(var j = 0; j < 5; j++){
this.eleActive[i].push(false);
this.eleHovered[i].push(false);
}
}
}
super._getRecords(this.userService, callback);
}
addRecord(){
this.currentUser.admin = false;
var callback = (result: any) : void => {
if(result == "ok") {
this.getRecords();
}
}
super._addRecord(this.userService, this.currentUser.user_name, this.currentUser, callback);
}
editRecord(param?:any){
super.submitEdit();
this.currentUser.admin = this.admin == "true"? true: false;
var callback = (result: any) : void => {
if(result == "ok") {
for( var i = 0; i < this.users.length; i++){
if (this.users[i].user_name == this.oldUser.user_name)
{
// this.users[r + this.itemNumPerPage * (this.curentP -1)] = _.cloneDeep(this.currentUser); //if don't clone, when click add user, the record editted last time will be set as empty
this.users[i] = _.cloneDeep(this.currentUser); //if don't clone, when click, the record editted last time will be set as empty
}
}
}
}
super._editRecord(this.userService, this.currentUser.user_name, this.oldUser, this.currentUser, callback, true, param);
}
deleteRecord(){
var callback = (result: any) : void => {
if(result == "ok") {
this.getRecords();
}
}
super._deleteRecord(this.userService, this.currentUser.user_name, callback);
}
openAddModal(){
super.openAddModal();
this.checkboxControl = new FormControl(false);
}
openDelModal(obj){
this.currentUser = _.cloneDeep(obj);
}
onEdit(row, col, obj){
super.onEdit(row, col, obj);
this.admin = obj.admin? "true": "false";
this.currentUser = _.cloneDeep(obj);
this.oldUser = _.cloneDeep(obj);
}
} | }
| random_line_split |
sr_mulher.py | # !/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
ERP+
"""
__author__ = 'CVtek dev'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "CVTek dev"
__status__ = "Development"
__model_name__ = 'sr_mulher.SRMulher'
import auth, base_models
from orm import *
from form import *
class SRMulher(Model, View):
def | (self, **kargs):
Model.__init__(self, **kargs)
self.__name__ = 'sr_mulher'
self.__title__ ='Inscrição e Identificação da Mulher'
self.__model_name__ = __model_name__
self.__list_edit_mode__ = 'edit'
self.__get_options__ = ['nome'] # define tambem o campo a ser mostrado no m2m, independentemente da descricao no field do m2m
self.__order_by__ = 'sr_mulher.nome'
#choice field com a estrutura de saude
self.numero_inscricao = integer_field(view_order = 1, name = 'Nº de Inscrição', size = 40)
self.nome = string_field(view_order = 2, name = 'Nome Completo', size = 70, onlist = True)
self.data_nascimento = date_field(view_order = 3, name = 'Data Nascimento', size=40, args = 'required', onlist = True)
self.escolaridade = combo_field(view_order = 4, name = 'Escolaridade', size = 40, default = '', options = [('analfabeta','Analfabeta'), ('primaria','Primária'), ('secundaria','Secundária'), ('mais','Mais')], onlist = True)
self.telefone = string_field(view_order = 5, name = 'Telefone', size = 40, onlist = True)
self.endereco_familia = text_field(view_order=6, name='Endereço Familia', size=70, args="rows=30", onlist=False, search=False)
self.endereco_actual = text_field(view_order=7, name='Endereço Fixo Actual', size=70, args="rows=30", onlist=False, search=False)
self.observacoes = text_field(view_order=8, name='Observações', size=80, args="rows=30", onlist=False, search=False)
self.estado = combo_field(view_order = 9, name = 'Estado', size = 40, default = 'active', options = [('active','Activo'), ('canceled','Cancelado')], onlist = True)
| __init__ | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.