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
game.gb.integration.js
import {DisassembleBytesWithRecursiveTraversalIntoOptimizedArray, DisassembleBytesWithRecursiveTraversalFormatted, DisassembleBytesWithRecursiveTraversalFormattedWithHeader} from '../../disassembler/recursiveTraversalDisassembler/RecursiveTraversalDisassembler'; import * as assert from 'assert'; import {describe, it, before, beforeEach} from 'mocha'; import * as fs from 'fs'; import {expect, use} from 'chai'; import chaiJestSnapshot from 'chai-jest-snapshot';
import {getRomTitle, parseGBHeader} from '../../disassembler/romInformation/romInformation' use(chaiJestSnapshot); const romPath = './roms/game/'; const romData = fs.readFileSync(`${romPath}/game.gb`); const romName = 'game.gb'; before(function () { chaiJestSnapshot.resetSnapshotRegistry(); }); beforeEach(function () { chaiJestSnapshot.configureUsingMochaContext(this); }); describe(`Integration tests for Recursive disassembling of ${romName}.js`, function () { it('should generate assembly output for helicopter.gb with traversal', function () { const resultingAssembly = DisassembleBytesWithRecursiveTraversalFormattedWithHeader(romData, 0x100, true); fs.writeFileSync(`${romPath}/${romName}.generated.s`, resultingAssembly); const gbdisOutput = fs.readFileSync(`${romPath}/${romName}.gbdis.s`); assert.deepEqual(resultingAssembly, gbdisOutput.toString()); }); }); describe('Rom Information', function () { it('should be able to get the Title of the rom', function () { const gbGameHeader = parseGBHeader(romData); const result = getRomTitle(gbGameHeader); assert.deepEqual(result, 'TEST'); }); });
random_line_split
List.py
# -*- coding: utf-8 -*- # # CTK: Cherokee Toolkit # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2010-2014 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free Software Foundation. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # from Widget import Widget from Container import Container from util import props_to_str ENTRY_HTML = '<%(tag)s id="%(id)s" %(props)s>%(content)s</%(tag)s>' class ListEntry (Container): def __init__ (self, _props={}, tag='li'): Container.__init__ (self) self.tag = tag self.props = _props.copy() def Render (self): render = Container.Render (self) if 'id' in self.props: self.id = self.props['id'] props = {'id': self.id, 'tag': self.tag, 'props': props_to_str(self.props), 'content': render.html} render.html = ENTRY_HTML %(props) return render class List (Container): """ Widget for lists of elements. The list can grow dynamically, and accept any kind of CTK widget as listed element. Arguments are optional. Arguments: _props: dictionary with properties for the HTML element, such as {'name': 'foo', 'id': 'bar', 'class': 'baz'} tag: tag to use for the element, either 'ul' for unordered lists, or 'ol' for ordered lists. By default, 'ul' is used. Examples: lst = CTK.List() lst.Add (CTK.RawHTML('One') lst.Add (CTK.Image({'src': '/foo/bar/baz.png'}) """ def __init__ (self, _props={}, tag='ul'): Container.__init__ (self) self.tag = tag self.props = _props.copy() def Add (self, widget, props={}): assert isinstance(widget, Widget) or widget is None or type(widget) is list entry = ListEntry (props.copy()) if widget: if type(widget) == list: for w in widget: entry += w else:
entry += widget Container.__iadd__ (self, entry) def __iadd__ (self, widget): self.Add (widget) return self def Render (self): render = Container.Render (self) props = {'id': self.id, 'tag': self.tag, 'props': props_to_str(self.props), 'content': render.html} render.html = ENTRY_HTML %(props) return render
random_line_split
List.py
# -*- coding: utf-8 -*- # # CTK: Cherokee Toolkit # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2010-2014 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free Software Foundation. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # from Widget import Widget from Container import Container from util import props_to_str ENTRY_HTML = '<%(tag)s id="%(id)s" %(props)s>%(content)s</%(tag)s>' class ListEntry (Container): def __init__ (self, _props={}, tag='li'): Container.__init__ (self) self.tag = tag self.props = _props.copy() def Render (self): render = Container.Render (self) if 'id' in self.props: self.id = self.props['id'] props = {'id': self.id, 'tag': self.tag, 'props': props_to_str(self.props), 'content': render.html} render.html = ENTRY_HTML %(props) return render class List (Container): """ Widget for lists of elements. The list can grow dynamically, and accept any kind of CTK widget as listed element. Arguments are optional. Arguments: _props: dictionary with properties for the HTML element, such as {'name': 'foo', 'id': 'bar', 'class': 'baz'} tag: tag to use for the element, either 'ul' for unordered lists, or 'ol' for ordered lists. By default, 'ul' is used. Examples: lst = CTK.List() lst.Add (CTK.RawHTML('One') lst.Add (CTK.Image({'src': '/foo/bar/baz.png'}) """ def __init__ (self, _props={}, tag='ul'): Container.__init__ (self) self.tag = tag self.props = _props.copy() def Add (self, widget, props={}): assert isinstance(widget, Widget) or widget is None or type(widget) is list entry = ListEntry (props.copy()) if widget: if type(widget) == list: for w in widget:
else: entry += widget Container.__iadd__ (self, entry) def __iadd__ (self, widget): self.Add (widget) return self def Render (self): render = Container.Render (self) props = {'id': self.id, 'tag': self.tag, 'props': props_to_str(self.props), 'content': render.html} render.html = ENTRY_HTML %(props) return render
entry += w
conditional_block
List.py
# -*- coding: utf-8 -*- # # CTK: Cherokee Toolkit # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2010-2014 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free Software Foundation. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # from Widget import Widget from Container import Container from util import props_to_str ENTRY_HTML = '<%(tag)s id="%(id)s" %(props)s>%(content)s</%(tag)s>' class
(Container): def __init__ (self, _props={}, tag='li'): Container.__init__ (self) self.tag = tag self.props = _props.copy() def Render (self): render = Container.Render (self) if 'id' in self.props: self.id = self.props['id'] props = {'id': self.id, 'tag': self.tag, 'props': props_to_str(self.props), 'content': render.html} render.html = ENTRY_HTML %(props) return render class List (Container): """ Widget for lists of elements. The list can grow dynamically, and accept any kind of CTK widget as listed element. Arguments are optional. Arguments: _props: dictionary with properties for the HTML element, such as {'name': 'foo', 'id': 'bar', 'class': 'baz'} tag: tag to use for the element, either 'ul' for unordered lists, or 'ol' for ordered lists. By default, 'ul' is used. Examples: lst = CTK.List() lst.Add (CTK.RawHTML('One') lst.Add (CTK.Image({'src': '/foo/bar/baz.png'}) """ def __init__ (self, _props={}, tag='ul'): Container.__init__ (self) self.tag = tag self.props = _props.copy() def Add (self, widget, props={}): assert isinstance(widget, Widget) or widget is None or type(widget) is list entry = ListEntry (props.copy()) if widget: if type(widget) == list: for w in widget: entry += w else: entry += widget Container.__iadd__ (self, entry) def __iadd__ (self, widget): self.Add (widget) return self def Render (self): render = Container.Render (self) props = {'id': self.id, 'tag': self.tag, 'props': props_to_str(self.props), 'content': render.html} render.html = ENTRY_HTML %(props) return render
ListEntry
identifier_name
List.py
# -*- coding: utf-8 -*- # # CTK: Cherokee Toolkit # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2010-2014 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free Software Foundation. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # from Widget import Widget from Container import Container from util import props_to_str ENTRY_HTML = '<%(tag)s id="%(id)s" %(props)s>%(content)s</%(tag)s>' class ListEntry (Container): def __init__ (self, _props={}, tag='li'): Container.__init__ (self) self.tag = tag self.props = _props.copy() def Render (self): render = Container.Render (self) if 'id' in self.props: self.id = self.props['id'] props = {'id': self.id, 'tag': self.tag, 'props': props_to_str(self.props), 'content': render.html} render.html = ENTRY_HTML %(props) return render class List (Container):
""" Widget for lists of elements. The list can grow dynamically, and accept any kind of CTK widget as listed element. Arguments are optional. Arguments: _props: dictionary with properties for the HTML element, such as {'name': 'foo', 'id': 'bar', 'class': 'baz'} tag: tag to use for the element, either 'ul' for unordered lists, or 'ol' for ordered lists. By default, 'ul' is used. Examples: lst = CTK.List() lst.Add (CTK.RawHTML('One') lst.Add (CTK.Image({'src': '/foo/bar/baz.png'}) """ def __init__ (self, _props={}, tag='ul'): Container.__init__ (self) self.tag = tag self.props = _props.copy() def Add (self, widget, props={}): assert isinstance(widget, Widget) or widget is None or type(widget) is list entry = ListEntry (props.copy()) if widget: if type(widget) == list: for w in widget: entry += w else: entry += widget Container.__iadd__ (self, entry) def __iadd__ (self, widget): self.Add (widget) return self def Render (self): render = Container.Render (self) props = {'id': self.id, 'tag': self.tag, 'props': props_to_str(self.props), 'content': render.html} render.html = ENTRY_HTML %(props) return render
identifier_body
todos.ts
export interface TodoItem { id: number; completed: boolean; text: string; } export const ADD_TODO = 'ADD_TODO'; export const COMPLETE_TODO = 'COMPLETE_TODO'; export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; export const COMPLETE_ALL_TODOS = 'COMPLETE_ALL_TODOS'; let _id = 0; export const VisibilityFilters = { SHOW_ALL: 'SHOW_ALL', SHOW_COMPLETED: 'SHOW_COMPLETED', SHOW_ACTIVE: 'SHOW_ACTIVE', }; export function visibilityFilter( state = VisibilityFilters.SHOW_ALL, { type, payload }: any ) { switch (type) { case SET_VISIBILITY_FILTER: return payload; default: return state; } } export function todos( state: TodoItem[] = [], { type, payload }: any ): TodoItem[] { switch (type) { case ADD_TODO: return [ ...state, { id: ++_id, text: payload.text, completed: false, }, ]; case COMPLETE_ALL_TODOS: return state.map(todo => ({ ...todo, completed: true })); case COMPLETE_TODO: return state.map(
); default: return state; } }
todo => (todo.id === payload.id ? { ...todo, completed: true } : todo)
random_line_split
todos.ts
export interface TodoItem { id: number; completed: boolean; text: string; } export const ADD_TODO = 'ADD_TODO'; export const COMPLETE_TODO = 'COMPLETE_TODO'; export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; export const COMPLETE_ALL_TODOS = 'COMPLETE_ALL_TODOS'; let _id = 0; export const VisibilityFilters = { SHOW_ALL: 'SHOW_ALL', SHOW_COMPLETED: 'SHOW_COMPLETED', SHOW_ACTIVE: 'SHOW_ACTIVE', }; export function visibilityFilter( state = VisibilityFilters.SHOW_ALL, { type, payload }: any ) { switch (type) { case SET_VISIBILITY_FILTER: return payload; default: return state; } } export function
( state: TodoItem[] = [], { type, payload }: any ): TodoItem[] { switch (type) { case ADD_TODO: return [ ...state, { id: ++_id, text: payload.text, completed: false, }, ]; case COMPLETE_ALL_TODOS: return state.map(todo => ({ ...todo, completed: true })); case COMPLETE_TODO: return state.map( todo => (todo.id === payload.id ? { ...todo, completed: true } : todo) ); default: return state; } }
todos
identifier_name
todos.ts
export interface TodoItem { id: number; completed: boolean; text: string; } export const ADD_TODO = 'ADD_TODO'; export const COMPLETE_TODO = 'COMPLETE_TODO'; export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; export const COMPLETE_ALL_TODOS = 'COMPLETE_ALL_TODOS'; let _id = 0; export const VisibilityFilters = { SHOW_ALL: 'SHOW_ALL', SHOW_COMPLETED: 'SHOW_COMPLETED', SHOW_ACTIVE: 'SHOW_ACTIVE', }; export function visibilityFilter( state = VisibilityFilters.SHOW_ALL, { type, payload }: any ) { switch (type) { case SET_VISIBILITY_FILTER: return payload; default: return state; } } export function todos( state: TodoItem[] = [], { type, payload }: any ): TodoItem[]
{ switch (type) { case ADD_TODO: return [ ...state, { id: ++_id, text: payload.text, completed: false, }, ]; case COMPLETE_ALL_TODOS: return state.map(todo => ({ ...todo, completed: true })); case COMPLETE_TODO: return state.map( todo => (todo.id === payload.id ? { ...todo, completed: true } : todo) ); default: return state; } }
identifier_body
djvutext.py
#!/usr/bin/python3 """ This bot uploads text from djvu files onto pages in the "Page" namespace. It is intended to be used for Wikisource. The following parameters are supported: -index:... name of the index page (without the Index: prefix) -djvu:... path to the djvu file, it shall be: - path to a file name - dir where a djvu file name as index is located optional, by default is current dir '.' -pages:<start>-<end>,...<start>-<end>,<start>-<end> Page range to upload; optional, start=1, end=djvu file number of images. Page ranges can be specified as: A-B -> pages A until B A- -> pages A until number of images A -> just page A -B -> pages 1 until B This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`. The following options can be set within a settings file which is scripts.ini by default: -summary: custom edit summary. Use quotes if edit summary contains spaces. -force overwrites existing text optional, default False -always do not bother asking to confirm any of the changes. """ # # (C) Pywikibot team, 2008-2022 # # Distributed under the terms of the MIT license. # import os.path from typing import Optional import pywikibot from pywikibot import i18n from pywikibot.bot import SingleSiteBot from pywikibot.exceptions import NoPageError from pywikibot.proofreadpage import ProofreadPage from pywikibot.tools.djvu import DjVuFile class DjVuTextBot(SingleSiteBot):
def main(*args: str) -> None: """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. :param args: command line arguments """ index = None djvu_path = '.' # default djvu file directory pages = '1-' options = {} # Parse command line arguments. local_args = pywikibot.handle_args(args) for arg in local_args: opt, _, value = arg.partition(':') if opt == '-index': index = value elif opt == '-djvu': djvu_path = value elif opt == '-pages': pages = value elif opt == '-summary': options['summary'] = value elif opt in ('-force', '-always'): options[opt[1:]] = True else: pywikibot.output('Unknown argument ' + arg) # index is mandatory. if not index: pywikibot.bot.suggest_help(missing_parameters=['-index']) return # If djvu_path is not a file, build djvu_path from dir+index. djvu_path = os.path.expanduser(djvu_path) djvu_path = os.path.abspath(djvu_path) if not os.path.exists(djvu_path): pywikibot.error('No such file or directory: ' + djvu_path) return if os.path.isdir(djvu_path): djvu_path = os.path.join(djvu_path, index) # Check the djvu file exists and, if so, create the DjVuFile wrapper. djvu = DjVuFile(djvu_path) if not djvu.has_text(): pywikibot.error('No text layer in djvu file {}'.format(djvu.file)) return # Parse pages param. pages = pages.split(',') for i, page_interval in enumerate(pages): start, sep, end = page_interval.partition('-') start = int(start or 1) end = int(end or djvu.number_of_images()) if sep else start pages[i] = (start, end) site = pywikibot.Site() if not site.has_extension('ProofreadPage'): pywikibot.error('Site {} must have ProofreadPage extension.' .format(site)) return index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns) if not index_page.exists(): raise NoPageError(index) pywikibot.output('uploading text from {} to {}' .format(djvu.file, index_page.title(as_link=True))) bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options) bot.run() if __name__ == '__main__': try: main() except Exception: pywikibot.error('Fatal error:', exc_info=True)
""" A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot """ update_options = { 'force': False, 'summary': '', } def __init__( self, djvu, index, pages: Optional[tuple] = None, **kwargs ) -> None: """ Initializer. :param djvu: djvu from where to fetch the text layer :type djvu: DjVuFile object :param index: index page in the Index: namespace :type index: Page object :param pages: page interval to upload (start, end) """ super().__init__(**kwargs) self._djvu = djvu self._index = index self._prefix = self._index.title(with_ns=False) self._page_ns = self.site._proofread_page_ns.custom_name if not pages: self._pages = (1, self._djvu.number_of_images()) else: self._pages = pages # Get edit summary message if it's empty. if not self.opt.summary: self.opt.summary = i18n.twtranslate(self._index.site, 'djvutext-creating') def page_number_gen(self): """Generate pages numbers from specified page intervals.""" last = 0 for start, end in sorted(self._pages): start = max(last, start) last = end + 1 yield from range(start, last) @property def generator(self): """Generate pages from specified page interval.""" for page_number in self.page_number_gen(): title = '{page_ns}:{prefix}/{number}'.format( page_ns=self._page_ns, prefix=self._prefix, number=page_number) page = ProofreadPage(self._index.site, title) page.page_number = page_number # remember page number in djvu file yield page def treat(self, page) -> None: """Process one page.""" old_text = page.text # Overwrite body of the page with content from djvu page.body = self._djvu.get_page(page.page_number) new_text = page.text if page.exists() and not self.opt.force: pywikibot.output( 'Page {} already exists, not adding!\n' 'Use -force option to overwrite the output page.' .format(page)) else: self.userPut(page, old_text, new_text, summary=self.opt.summary)
identifier_body
djvutext.py
#!/usr/bin/python3 """ This bot uploads text from djvu files onto pages in the "Page" namespace. It is intended to be used for Wikisource. The following parameters are supported: -index:... name of the index page (without the Index: prefix) -djvu:... path to the djvu file, it shall be: - path to a file name - dir where a djvu file name as index is located optional, by default is current dir '.' -pages:<start>-<end>,...<start>-<end>,<start>-<end> Page range to upload; optional, start=1, end=djvu file number of images. Page ranges can be specified as: A-B -> pages A until B A- -> pages A until number of images A -> just page A -B -> pages 1 until B This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`. The following options can be set within a settings file which is scripts.ini by default: -summary: custom edit summary. Use quotes if edit summary contains spaces. -force overwrites existing text optional, default False -always do not bother asking to confirm any of the changes. """ # # (C) Pywikibot team, 2008-2022 # # Distributed under the terms of the MIT license. # import os.path from typing import Optional import pywikibot from pywikibot import i18n from pywikibot.bot import SingleSiteBot from pywikibot.exceptions import NoPageError from pywikibot.proofreadpage import ProofreadPage from pywikibot.tools.djvu import DjVuFile class DjVuTextBot(SingleSiteBot): """ A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot """ update_options = { 'force': False, 'summary': '', } def __init__( self, djvu, index, pages: Optional[tuple] = None, **kwargs ) -> None: """ Initializer. :param djvu: djvu from where to fetch the text layer :type djvu: DjVuFile object :param index: index page in the Index: namespace :type index: Page object :param pages: page interval to upload (start, end) """ super().__init__(**kwargs) self._djvu = djvu self._index = index self._prefix = self._index.title(with_ns=False) self._page_ns = self.site._proofread_page_ns.custom_name if not pages: self._pages = (1, self._djvu.number_of_images()) else: self._pages = pages # Get edit summary message if it's empty. if not self.opt.summary: self.opt.summary = i18n.twtranslate(self._index.site, 'djvutext-creating') def page_number_gen(self): """Generate pages numbers from specified page intervals.""" last = 0 for start, end in sorted(self._pages): start = max(last, start) last = end + 1 yield from range(start, last) @property def generator(self): """Generate pages from specified page interval.""" for page_number in self.page_number_gen(): title = '{page_ns}:{prefix}/{number}'.format( page_ns=self._page_ns, prefix=self._prefix, number=page_number) page = ProofreadPage(self._index.site, title) page.page_number = page_number # remember page number in djvu file yield page def treat(self, page) -> None: """Process one page.""" old_text = page.text # Overwrite body of the page with content from djvu page.body = self._djvu.get_page(page.page_number) new_text = page.text if page.exists() and not self.opt.force: pywikibot.output( 'Page {} already exists, not adding!\n' 'Use -force option to overwrite the output page.' .format(page)) else: self.userPut(page, old_text, new_text, summary=self.opt.summary) def main(*args: str) -> None: """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. :param args: command line arguments """ index = None djvu_path = '.' # default djvu file directory pages = '1-' options = {} # Parse command line arguments. local_args = pywikibot.handle_args(args) for arg in local_args: opt, _, value = arg.partition(':') if opt == '-index': index = value elif opt == '-djvu': djvu_path = value elif opt == '-pages': pages = value elif opt == '-summary': options['summary'] = value elif opt in ('-force', '-always'): options[opt[1:]] = True else: pywikibot.output('Unknown argument ' + arg) # index is mandatory. if not index: pywikibot.bot.suggest_help(missing_parameters=['-index']) return # If djvu_path is not a file, build djvu_path from dir+index. djvu_path = os.path.expanduser(djvu_path) djvu_path = os.path.abspath(djvu_path) if not os.path.exists(djvu_path): pywikibot.error('No such file or directory: ' + djvu_path) return if os.path.isdir(djvu_path):
# Check the djvu file exists and, if so, create the DjVuFile wrapper. djvu = DjVuFile(djvu_path) if not djvu.has_text(): pywikibot.error('No text layer in djvu file {}'.format(djvu.file)) return # Parse pages param. pages = pages.split(',') for i, page_interval in enumerate(pages): start, sep, end = page_interval.partition('-') start = int(start or 1) end = int(end or djvu.number_of_images()) if sep else start pages[i] = (start, end) site = pywikibot.Site() if not site.has_extension('ProofreadPage'): pywikibot.error('Site {} must have ProofreadPage extension.' .format(site)) return index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns) if not index_page.exists(): raise NoPageError(index) pywikibot.output('uploading text from {} to {}' .format(djvu.file, index_page.title(as_link=True))) bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options) bot.run() if __name__ == '__main__': try: main() except Exception: pywikibot.error('Fatal error:', exc_info=True)
djvu_path = os.path.join(djvu_path, index)
conditional_block
djvutext.py
#!/usr/bin/python3 """ This bot uploads text from djvu files onto pages in the "Page" namespace. It is intended to be used for Wikisource. The following parameters are supported: -index:... name of the index page (without the Index: prefix) -djvu:... path to the djvu file, it shall be: - path to a file name - dir where a djvu file name as index is located optional, by default is current dir '.' -pages:<start>-<end>,...<start>-<end>,<start>-<end> Page range to upload; optional, start=1, end=djvu file number of images. Page ranges can be specified as: A-B -> pages A until B A- -> pages A until number of images A -> just page A -B -> pages 1 until B This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`. The following options can be set within a settings file which is scripts.ini by default: -summary: custom edit summary. Use quotes if edit summary contains spaces. -force overwrites existing text optional, default False -always do not bother asking to confirm any of the changes. """ # # (C) Pywikibot team, 2008-2022 # # Distributed under the terms of the MIT license. # import os.path from typing import Optional import pywikibot from pywikibot import i18n from pywikibot.bot import SingleSiteBot from pywikibot.exceptions import NoPageError from pywikibot.proofreadpage import ProofreadPage from pywikibot.tools.djvu import DjVuFile class DjVuTextBot(SingleSiteBot): """ A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot """ update_options = { 'force': False, 'summary': '', } def __init__( self, djvu, index, pages: Optional[tuple] = None, **kwargs ) -> None: """ Initializer. :param djvu: djvu from where to fetch the text layer :type djvu: DjVuFile object :param index: index page in the Index: namespace :type index: Page object :param pages: page interval to upload (start, end) """ super().__init__(**kwargs) self._djvu = djvu self._index = index self._prefix = self._index.title(with_ns=False) self._page_ns = self.site._proofread_page_ns.custom_name if not pages: self._pages = (1, self._djvu.number_of_images()) else: self._pages = pages # Get edit summary message if it's empty. if not self.opt.summary: self.opt.summary = i18n.twtranslate(self._index.site, 'djvutext-creating') def page_number_gen(self): """Generate pages numbers from specified page intervals.""" last = 0 for start, end in sorted(self._pages): start = max(last, start) last = end + 1 yield from range(start, last) @property def generator(self): """Generate pages from specified page interval.""" for page_number in self.page_number_gen(): title = '{page_ns}:{prefix}/{number}'.format( page_ns=self._page_ns, prefix=self._prefix, number=page_number) page = ProofreadPage(self._index.site, title) page.page_number = page_number # remember page number in djvu file yield page def treat(self, page) -> None: """Process one page.""" old_text = page.text # Overwrite body of the page with content from djvu page.body = self._djvu.get_page(page.page_number) new_text = page.text if page.exists() and not self.opt.force: pywikibot.output( 'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.' .format(page)) else: self.userPut(page, old_text, new_text, summary=self.opt.summary) def main(*args: str) -> None: """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. :param args: command line arguments """ index = None djvu_path = '.' # default djvu file directory pages = '1-' options = {} # Parse command line arguments. local_args = pywikibot.handle_args(args) for arg in local_args: opt, _, value = arg.partition(':') if opt == '-index': index = value elif opt == '-djvu': djvu_path = value elif opt == '-pages': pages = value elif opt == '-summary': options['summary'] = value elif opt in ('-force', '-always'): options[opt[1:]] = True else: pywikibot.output('Unknown argument ' + arg) # index is mandatory. if not index: pywikibot.bot.suggest_help(missing_parameters=['-index']) return # If djvu_path is not a file, build djvu_path from dir+index. djvu_path = os.path.expanduser(djvu_path) djvu_path = os.path.abspath(djvu_path) if not os.path.exists(djvu_path): pywikibot.error('No such file or directory: ' + djvu_path) return if os.path.isdir(djvu_path): djvu_path = os.path.join(djvu_path, index) # Check the djvu file exists and, if so, create the DjVuFile wrapper. djvu = DjVuFile(djvu_path) if not djvu.has_text(): pywikibot.error('No text layer in djvu file {}'.format(djvu.file)) return # Parse pages param. pages = pages.split(',') for i, page_interval in enumerate(pages): start, sep, end = page_interval.partition('-') start = int(start or 1) end = int(end or djvu.number_of_images()) if sep else start pages[i] = (start, end) site = pywikibot.Site() if not site.has_extension('ProofreadPage'): pywikibot.error('Site {} must have ProofreadPage extension.' .format(site)) return index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns) if not index_page.exists(): raise NoPageError(index) pywikibot.output('uploading text from {} to {}' .format(djvu.file, index_page.title(as_link=True))) bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options) bot.run() if __name__ == '__main__': try: main() except Exception: pywikibot.error('Fatal error:', exc_info=True)
random_line_split
djvutext.py
#!/usr/bin/python3 """ This bot uploads text from djvu files onto pages in the "Page" namespace. It is intended to be used for Wikisource. The following parameters are supported: -index:... name of the index page (without the Index: prefix) -djvu:... path to the djvu file, it shall be: - path to a file name - dir where a djvu file name as index is located optional, by default is current dir '.' -pages:<start>-<end>,...<start>-<end>,<start>-<end> Page range to upload; optional, start=1, end=djvu file number of images. Page ranges can be specified as: A-B -> pages A until B A- -> pages A until number of images A -> just page A -B -> pages 1 until B This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`. The following options can be set within a settings file which is scripts.ini by default: -summary: custom edit summary. Use quotes if edit summary contains spaces. -force overwrites existing text optional, default False -always do not bother asking to confirm any of the changes. """ # # (C) Pywikibot team, 2008-2022 # # Distributed under the terms of the MIT license. # import os.path from typing import Optional import pywikibot from pywikibot import i18n from pywikibot.bot import SingleSiteBot from pywikibot.exceptions import NoPageError from pywikibot.proofreadpage import ProofreadPage from pywikibot.tools.djvu import DjVuFile class DjVuTextBot(SingleSiteBot): """ A bot that uploads text-layer from djvu files to Page:namespace. Works only on sites with Proofread Page extension installed. .. versionchanged:: 7.0 CheckerBot is a ConfigParserBot """ update_options = { 'force': False, 'summary': '', } def __init__( self, djvu, index, pages: Optional[tuple] = None, **kwargs ) -> None: """ Initializer. :param djvu: djvu from where to fetch the text layer :type djvu: DjVuFile object :param index: index page in the Index: namespace :type index: Page object :param pages: page interval to upload (start, end) """ super().__init__(**kwargs) self._djvu = djvu self._index = index self._prefix = self._index.title(with_ns=False) self._page_ns = self.site._proofread_page_ns.custom_name if not pages: self._pages = (1, self._djvu.number_of_images()) else: self._pages = pages # Get edit summary message if it's empty. if not self.opt.summary: self.opt.summary = i18n.twtranslate(self._index.site, 'djvutext-creating') def page_number_gen(self): """Generate pages numbers from specified page intervals.""" last = 0 for start, end in sorted(self._pages): start = max(last, start) last = end + 1 yield from range(start, last) @property def generator(self): """Generate pages from specified page interval.""" for page_number in self.page_number_gen(): title = '{page_ns}:{prefix}/{number}'.format( page_ns=self._page_ns, prefix=self._prefix, number=page_number) page = ProofreadPage(self._index.site, title) page.page_number = page_number # remember page number in djvu file yield page def
(self, page) -> None: """Process one page.""" old_text = page.text # Overwrite body of the page with content from djvu page.body = self._djvu.get_page(page.page_number) new_text = page.text if page.exists() and not self.opt.force: pywikibot.output( 'Page {} already exists, not adding!\n' 'Use -force option to overwrite the output page.' .format(page)) else: self.userPut(page, old_text, new_text, summary=self.opt.summary) def main(*args: str) -> None: """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. :param args: command line arguments """ index = None djvu_path = '.' # default djvu file directory pages = '1-' options = {} # Parse command line arguments. local_args = pywikibot.handle_args(args) for arg in local_args: opt, _, value = arg.partition(':') if opt == '-index': index = value elif opt == '-djvu': djvu_path = value elif opt == '-pages': pages = value elif opt == '-summary': options['summary'] = value elif opt in ('-force', '-always'): options[opt[1:]] = True else: pywikibot.output('Unknown argument ' + arg) # index is mandatory. if not index: pywikibot.bot.suggest_help(missing_parameters=['-index']) return # If djvu_path is not a file, build djvu_path from dir+index. djvu_path = os.path.expanduser(djvu_path) djvu_path = os.path.abspath(djvu_path) if not os.path.exists(djvu_path): pywikibot.error('No such file or directory: ' + djvu_path) return if os.path.isdir(djvu_path): djvu_path = os.path.join(djvu_path, index) # Check the djvu file exists and, if so, create the DjVuFile wrapper. djvu = DjVuFile(djvu_path) if not djvu.has_text(): pywikibot.error('No text layer in djvu file {}'.format(djvu.file)) return # Parse pages param. pages = pages.split(',') for i, page_interval in enumerate(pages): start, sep, end = page_interval.partition('-') start = int(start or 1) end = int(end or djvu.number_of_images()) if sep else start pages[i] = (start, end) site = pywikibot.Site() if not site.has_extension('ProofreadPage'): pywikibot.error('Site {} must have ProofreadPage extension.' .format(site)) return index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns) if not index_page.exists(): raise NoPageError(index) pywikibot.output('uploading text from {} to {}' .format(djvu.file, index_page.title(as_link=True))) bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options) bot.run() if __name__ == '__main__': try: main() except Exception: pywikibot.error('Fatal error:', exc_info=True)
treat
identifier_name
list_funds.js
dojo.require("dijit.Dialog"); dojo.require("dijit.form.FilteringSelect"); dojo.require('dijit.form.Button'); dojo.require('dijit.TooltipDialog'); dojo.require('dijit.form.DropDownButton'); dojo.require('dijit.form.CheckBox'); dojo.require('dojox.grid.DataGrid'); dojo.require('dojo.data.ItemFileWriteStore'); dojo.require('openils.widget.OrgUnitFilteringSelect'); dojo.require('openils.acq.CurrencyType'); dojo.require('openils.Event'); dojo.require('openils.Util'); dojo.require('openils.User'); dojo.require('openils.CGI'); dojo.require('openils.PermaCrud'); dojo.require('openils.widget.AutoGrid'); dojo.require('openils.widget.ProgressDialog'); dojo.require('fieldmapper.OrgUtils'); dojo.requireLocalization('openils.acq', 'acq'); var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq'); var contextOrg; var rolloverResponses; var rolloverMode = false; var fundFleshFields = [ 'spent_balance', 'combined_balance', 'spent_total', 'encumbrance_total', 'debit_total', 'allocation_total' ]; var adminPermOrgs = []; var cachedFunds = []; function
() { contextOrg = openils.User.user.ws_ou(); /* Reveal controls for rollover without money if org units say ok. * Actual ability to do the operation is controlled in the database, of * course. */ var ouSettings = fieldmapper.aou.fetchOrgSettingBatch( openils.User.user.ws_ou(), ["acq.fund.allow_rollover_without_money"] ); if ( ouSettings["acq.fund.allow_rollover_without_money"] && ouSettings["acq.fund.allow_rollover_without_money"].value ) { dojo.query(".encumb_only").forEach( function(o) { openils.Util.show(o, "table-row"); } ); } var connect = function() { dojo.connect(contextOrgSelector, 'onChange', function() { contextOrg = this.attr('value'); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); rolloverMode = false; gridDataLoader(); } ); }; dojo.connect(refreshButton, 'onClick', function() { rolloverMode = false; gridDataLoader(); }); new openils.User().buildPermOrgSelector( ['ADMIN_ACQ_FUND', 'VIEW_FUND'], contextOrgSelector, contextOrg, connect); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); loadYearSelector(); lfGrid.onItemReceived = function(item) {cachedFunds.push(item)}; new openils.User().getPermOrgList( 'ADMIN_ACQ_FUND', function(list) { adminPermOrgs = list; loadFundGrid( new openils.CGI().param('year') || new Date().getFullYear().toString()); }, true, true ); } function gridDataLoader() { lfGrid.resetStore(); if(rolloverMode) { var offset = lfGrid.displayOffset; for(var i = offset; i < (offset + lfGrid.displayLimit - 1); i++) { var fund = rolloverResponses[i]; if(!fund) break; lfGrid.store.newItem(fieldmapper.acqf.toStoreItem(fund)); } } else { loadFundGrid(); } } function getBalanceInfo(rowIdx, item) { if (!item) return ''; var fundId = this.grid.store.getValue(item, 'id'); var fund = cachedFunds.filter(function(f) { return f.id() == fundId })[0]; var cb = fund.combined_balance(); return cb ? cb.amount() : '0'; } function loadFundGrid(year) { openils.Util.hide('acq-fund-list-rollover-summary'); year = year || fundFilterYearSelect.attr('value'); cachedFunds = []; lfGrid.loadAll( { flesh : 1, flesh_fields : {acqf : fundFleshFields}, // by default, sort funds I can edit to the front order_by : [ { 'class' : 'acqf', field : 'org', compare : {'in' : adminPermOrgs}, direction : 'desc' }, { 'class' : 'acqf', field : 'name' } ] }, { year : year, org : fieldmapper.aou.descendantNodeList(contextOrg, true) } ); } function loadYearSelector() { fieldmapper.standardRequest( ['open-ils.acq', 'open-ils.acq.fund.org.years.retrieve'], { async : true, params : [openils.User.authtoken, {}, {limit_perm : 'VIEW_FUND'}], oncomplete : function(r) { var yearList = openils.Util.readResponse(r); if(!yearList) return; yearList = yearList.map(function(year){return {year:year+''};}); // dojo wants strings var yearStore = {identifier:'year', name:'year', items:yearList}; yearStore.items = yearStore.items.sort().reverse(); fundFilterYearSelect.store = new dojo.data.ItemFileWriteStore({data:yearStore}); // default to this year fundFilterYearSelect.setValue(new Date().getFullYear().toString()); dojo.connect( fundFilterYearSelect, 'onChange', function() { rolloverMode = false; gridDataLoader(); } ); } } ); } function performRollover(args) { rolloverMode = true; progressDialog.show(true, "Processing..."); rolloverResponses = []; var method = 'open-ils.acq.fiscal_rollover'; if(args.rollover[0] == 'on') { method += '.combined'; } else { method += '.propagate'; } var dryRun = args.dry_run[0] == 'on'; if(dryRun) method += '.dry_run'; var encumbOnly = args.encumb_only[0] == 'on'; var count = 0; var amount_rolled = 0; var year = fundFilterYearSelect.attr('value'); // TODO alternate selector? fieldmapper.standardRequest( ['open-ils.acq', method], { async : true, params : [ openils.User.authtoken, year, contextOrg, (args.child_orgs[0] == 'on'), { encumb_only : encumbOnly } ], onresponse : function(r) { var resp = openils.Util.readResponse(r); rolloverResponses.push(resp.fund); count += 1; amount_rolled += Number(resp.rollover_amount); }, oncomplete : function() { var nextYear = Number(year) + 1; rolloverResponses = rolloverResponses.sort( function(a, b) { if(a.code() > b.code()) return 1; return -1; } ) // add the new, rolled funds to the cache. Note that in dry-run // mode, these are ephemeral and no longer exist on the server. cachedFunds = cachedFunds.concat(rolloverResponses); dojo.byId('acq-fund-list-rollover-summary-header').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY, [nextYear] ); dojo.byId('acq-fund-list-rollover-summary-funds').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_FUNDS, [nextYear, count] ); dojo.byId('acq-fund-list-rollover-summary-rollover-amount').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_ROLLOVER_AMOUNT, [nextYear, amount_rolled] ); if(!dryRun) { openils.Util.hide('acq-fund-list-rollover-summary-dry-run'); // add the new year to the year selector if it's not already there fundFilterYearSelect.store.fetch({ query : {year : nextYear}, onComplete: function(list) { if(list && list.length > 0) return; fundFilterYearSelect.store.newItem({year : nextYear}); } }); } openils.Util.show('acq-fund-list-rollover-summary'); progressDialog.hide(); gridDataLoader(); } } ); } openils.Util.addOnLoad(initPage);
initPage
identifier_name
list_funds.js
dojo.require("dijit.Dialog"); dojo.require("dijit.form.FilteringSelect"); dojo.require('dijit.form.Button'); dojo.require('dijit.TooltipDialog'); dojo.require('dijit.form.DropDownButton'); dojo.require('dijit.form.CheckBox'); dojo.require('dojox.grid.DataGrid'); dojo.require('dojo.data.ItemFileWriteStore'); dojo.require('openils.widget.OrgUnitFilteringSelect'); dojo.require('openils.acq.CurrencyType'); dojo.require('openils.Event'); dojo.require('openils.Util'); dojo.require('openils.User'); dojo.require('openils.CGI'); dojo.require('openils.PermaCrud'); dojo.require('openils.widget.AutoGrid'); dojo.require('openils.widget.ProgressDialog'); dojo.require('fieldmapper.OrgUtils'); dojo.requireLocalization('openils.acq', 'acq'); var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq'); var contextOrg; var rolloverResponses; var rolloverMode = false; var fundFleshFields = [ 'spent_balance', 'combined_balance', 'spent_total', 'encumbrance_total', 'debit_total', 'allocation_total' ]; var adminPermOrgs = []; var cachedFunds = []; function initPage() { contextOrg = openils.User.user.ws_ou(); /* Reveal controls for rollover without money if org units say ok. * Actual ability to do the operation is controlled in the database, of * course. */ var ouSettings = fieldmapper.aou.fetchOrgSettingBatch( openils.User.user.ws_ou(), ["acq.fund.allow_rollover_without_money"] ); if ( ouSettings["acq.fund.allow_rollover_without_money"] && ouSettings["acq.fund.allow_rollover_without_money"].value ) { dojo.query(".encumb_only").forEach( function(o) { openils.Util.show(o, "table-row"); } ); } var connect = function() { dojo.connect(contextOrgSelector, 'onChange', function() { contextOrg = this.attr('value'); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); rolloverMode = false; gridDataLoader(); } ); }; dojo.connect(refreshButton, 'onClick', function() { rolloverMode = false; gridDataLoader(); }); new openils.User().buildPermOrgSelector( ['ADMIN_ACQ_FUND', 'VIEW_FUND'], contextOrgSelector, contextOrg, connect); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); loadYearSelector(); lfGrid.onItemReceived = function(item) {cachedFunds.push(item)}; new openils.User().getPermOrgList( 'ADMIN_ACQ_FUND', function(list) { adminPermOrgs = list; loadFundGrid( new openils.CGI().param('year') || new Date().getFullYear().toString()); }, true, true ); } function gridDataLoader() { lfGrid.resetStore(); if(rolloverMode) { var offset = lfGrid.displayOffset; for(var i = offset; i < (offset + lfGrid.displayLimit - 1); i++) { var fund = rolloverResponses[i]; if(!fund) break; lfGrid.store.newItem(fieldmapper.acqf.toStoreItem(fund)); } } else { loadFundGrid(); } } function getBalanceInfo(rowIdx, item) { if (!item) return ''; var fundId = this.grid.store.getValue(item, 'id'); var fund = cachedFunds.filter(function(f) { return f.id() == fundId })[0]; var cb = fund.combined_balance(); return cb ? cb.amount() : '0'; } function loadFundGrid(year) { openils.Util.hide('acq-fund-list-rollover-summary'); year = year || fundFilterYearSelect.attr('value'); cachedFunds = []; lfGrid.loadAll( { flesh : 1, flesh_fields : {acqf : fundFleshFields}, // by default, sort funds I can edit to the front order_by : [ { 'class' : 'acqf', field : 'org', compare : {'in' : adminPermOrgs}, direction : 'desc' }, { 'class' : 'acqf', field : 'name' } ] }, { year : year, org : fieldmapper.aou.descendantNodeList(contextOrg, true) } ); } function loadYearSelector() { fieldmapper.standardRequest( ['open-ils.acq', 'open-ils.acq.fund.org.years.retrieve'], { async : true, params : [openils.User.authtoken, {}, {limit_perm : 'VIEW_FUND'}], oncomplete : function(r) { var yearList = openils.Util.readResponse(r); if(!yearList) return; yearList = yearList.map(function(year){return {year:year+''};}); // dojo wants strings var yearStore = {identifier:'year', name:'year', items:yearList}; yearStore.items = yearStore.items.sort().reverse(); fundFilterYearSelect.store = new dojo.data.ItemFileWriteStore({data:yearStore}); // default to this year fundFilterYearSelect.setValue(new Date().getFullYear().toString()); dojo.connect( fundFilterYearSelect, 'onChange', function() { rolloverMode = false; gridDataLoader(); } ); } } ); } function performRollover(args) { rolloverMode = true; progressDialog.show(true, "Processing..."); rolloverResponses = []; var method = 'open-ils.acq.fiscal_rollover'; if(args.rollover[0] == 'on')
else { method += '.propagate'; } var dryRun = args.dry_run[0] == 'on'; if(dryRun) method += '.dry_run'; var encumbOnly = args.encumb_only[0] == 'on'; var count = 0; var amount_rolled = 0; var year = fundFilterYearSelect.attr('value'); // TODO alternate selector? fieldmapper.standardRequest( ['open-ils.acq', method], { async : true, params : [ openils.User.authtoken, year, contextOrg, (args.child_orgs[0] == 'on'), { encumb_only : encumbOnly } ], onresponse : function(r) { var resp = openils.Util.readResponse(r); rolloverResponses.push(resp.fund); count += 1; amount_rolled += Number(resp.rollover_amount); }, oncomplete : function() { var nextYear = Number(year) + 1; rolloverResponses = rolloverResponses.sort( function(a, b) { if(a.code() > b.code()) return 1; return -1; } ) // add the new, rolled funds to the cache. Note that in dry-run // mode, these are ephemeral and no longer exist on the server. cachedFunds = cachedFunds.concat(rolloverResponses); dojo.byId('acq-fund-list-rollover-summary-header').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY, [nextYear] ); dojo.byId('acq-fund-list-rollover-summary-funds').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_FUNDS, [nextYear, count] ); dojo.byId('acq-fund-list-rollover-summary-rollover-amount').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_ROLLOVER_AMOUNT, [nextYear, amount_rolled] ); if(!dryRun) { openils.Util.hide('acq-fund-list-rollover-summary-dry-run'); // add the new year to the year selector if it's not already there fundFilterYearSelect.store.fetch({ query : {year : nextYear}, onComplete: function(list) { if(list && list.length > 0) return; fundFilterYearSelect.store.newItem({year : nextYear}); } }); } openils.Util.show('acq-fund-list-rollover-summary'); progressDialog.hide(); gridDataLoader(); } } ); } openils.Util.addOnLoad(initPage);
{ method += '.combined'; }
conditional_block
list_funds.js
dojo.require("dijit.Dialog"); dojo.require("dijit.form.FilteringSelect"); dojo.require('dijit.form.Button'); dojo.require('dijit.TooltipDialog'); dojo.require('dijit.form.DropDownButton'); dojo.require('dijit.form.CheckBox'); dojo.require('dojox.grid.DataGrid'); dojo.require('dojo.data.ItemFileWriteStore'); dojo.require('openils.widget.OrgUnitFilteringSelect'); dojo.require('openils.acq.CurrencyType'); dojo.require('openils.Event'); dojo.require('openils.Util'); dojo.require('openils.User'); dojo.require('openils.CGI'); dojo.require('openils.PermaCrud'); dojo.require('openils.widget.AutoGrid'); dojo.require('openils.widget.ProgressDialog'); dojo.require('fieldmapper.OrgUtils'); dojo.requireLocalization('openils.acq', 'acq'); var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq'); var contextOrg; var rolloverResponses; var rolloverMode = false; var fundFleshFields = [ 'spent_balance', 'combined_balance', 'spent_total', 'encumbrance_total', 'debit_total', 'allocation_total' ]; var adminPermOrgs = []; var cachedFunds = []; function initPage()
function gridDataLoader() { lfGrid.resetStore(); if(rolloverMode) { var offset = lfGrid.displayOffset; for(var i = offset; i < (offset + lfGrid.displayLimit - 1); i++) { var fund = rolloverResponses[i]; if(!fund) break; lfGrid.store.newItem(fieldmapper.acqf.toStoreItem(fund)); } } else { loadFundGrid(); } } function getBalanceInfo(rowIdx, item) { if (!item) return ''; var fundId = this.grid.store.getValue(item, 'id'); var fund = cachedFunds.filter(function(f) { return f.id() == fundId })[0]; var cb = fund.combined_balance(); return cb ? cb.amount() : '0'; } function loadFundGrid(year) { openils.Util.hide('acq-fund-list-rollover-summary'); year = year || fundFilterYearSelect.attr('value'); cachedFunds = []; lfGrid.loadAll( { flesh : 1, flesh_fields : {acqf : fundFleshFields}, // by default, sort funds I can edit to the front order_by : [ { 'class' : 'acqf', field : 'org', compare : {'in' : adminPermOrgs}, direction : 'desc' }, { 'class' : 'acqf', field : 'name' } ] }, { year : year, org : fieldmapper.aou.descendantNodeList(contextOrg, true) } ); } function loadYearSelector() { fieldmapper.standardRequest( ['open-ils.acq', 'open-ils.acq.fund.org.years.retrieve'], { async : true, params : [openils.User.authtoken, {}, {limit_perm : 'VIEW_FUND'}], oncomplete : function(r) { var yearList = openils.Util.readResponse(r); if(!yearList) return; yearList = yearList.map(function(year){return {year:year+''};}); // dojo wants strings var yearStore = {identifier:'year', name:'year', items:yearList}; yearStore.items = yearStore.items.sort().reverse(); fundFilterYearSelect.store = new dojo.data.ItemFileWriteStore({data:yearStore}); // default to this year fundFilterYearSelect.setValue(new Date().getFullYear().toString()); dojo.connect( fundFilterYearSelect, 'onChange', function() { rolloverMode = false; gridDataLoader(); } ); } } ); } function performRollover(args) { rolloverMode = true; progressDialog.show(true, "Processing..."); rolloverResponses = []; var method = 'open-ils.acq.fiscal_rollover'; if(args.rollover[0] == 'on') { method += '.combined'; } else { method += '.propagate'; } var dryRun = args.dry_run[0] == 'on'; if(dryRun) method += '.dry_run'; var encumbOnly = args.encumb_only[0] == 'on'; var count = 0; var amount_rolled = 0; var year = fundFilterYearSelect.attr('value'); // TODO alternate selector? fieldmapper.standardRequest( ['open-ils.acq', method], { async : true, params : [ openils.User.authtoken, year, contextOrg, (args.child_orgs[0] == 'on'), { encumb_only : encumbOnly } ], onresponse : function(r) { var resp = openils.Util.readResponse(r); rolloverResponses.push(resp.fund); count += 1; amount_rolled += Number(resp.rollover_amount); }, oncomplete : function() { var nextYear = Number(year) + 1; rolloverResponses = rolloverResponses.sort( function(a, b) { if(a.code() > b.code()) return 1; return -1; } ) // add the new, rolled funds to the cache. Note that in dry-run // mode, these are ephemeral and no longer exist on the server. cachedFunds = cachedFunds.concat(rolloverResponses); dojo.byId('acq-fund-list-rollover-summary-header').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY, [nextYear] ); dojo.byId('acq-fund-list-rollover-summary-funds').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_FUNDS, [nextYear, count] ); dojo.byId('acq-fund-list-rollover-summary-rollover-amount').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_ROLLOVER_AMOUNT, [nextYear, amount_rolled] ); if(!dryRun) { openils.Util.hide('acq-fund-list-rollover-summary-dry-run'); // add the new year to the year selector if it's not already there fundFilterYearSelect.store.fetch({ query : {year : nextYear}, onComplete: function(list) { if(list && list.length > 0) return; fundFilterYearSelect.store.newItem({year : nextYear}); } }); } openils.Util.show('acq-fund-list-rollover-summary'); progressDialog.hide(); gridDataLoader(); } } ); } openils.Util.addOnLoad(initPage);
{ contextOrg = openils.User.user.ws_ou(); /* Reveal controls for rollover without money if org units say ok. * Actual ability to do the operation is controlled in the database, of * course. */ var ouSettings = fieldmapper.aou.fetchOrgSettingBatch( openils.User.user.ws_ou(), ["acq.fund.allow_rollover_without_money"] ); if ( ouSettings["acq.fund.allow_rollover_without_money"] && ouSettings["acq.fund.allow_rollover_without_money"].value ) { dojo.query(".encumb_only").forEach( function(o) { openils.Util.show(o, "table-row"); } ); } var connect = function() { dojo.connect(contextOrgSelector, 'onChange', function() { contextOrg = this.attr('value'); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); rolloverMode = false; gridDataLoader(); } ); }; dojo.connect(refreshButton, 'onClick', function() { rolloverMode = false; gridDataLoader(); }); new openils.User().buildPermOrgSelector( ['ADMIN_ACQ_FUND', 'VIEW_FUND'], contextOrgSelector, contextOrg, connect); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); loadYearSelector(); lfGrid.onItemReceived = function(item) {cachedFunds.push(item)}; new openils.User().getPermOrgList( 'ADMIN_ACQ_FUND', function(list) { adminPermOrgs = list; loadFundGrid( new openils.CGI().param('year') || new Date().getFullYear().toString()); }, true, true ); }
identifier_body
list_funds.js
dojo.require("dijit.Dialog"); dojo.require("dijit.form.FilteringSelect"); dojo.require('dijit.form.Button'); dojo.require('dijit.TooltipDialog'); dojo.require('dijit.form.DropDownButton'); dojo.require('dijit.form.CheckBox'); dojo.require('dojox.grid.DataGrid'); dojo.require('dojo.data.ItemFileWriteStore'); dojo.require('openils.widget.OrgUnitFilteringSelect'); dojo.require('openils.acq.CurrencyType'); dojo.require('openils.Event'); dojo.require('openils.Util'); dojo.require('openils.User'); dojo.require('openils.CGI'); dojo.require('openils.PermaCrud'); dojo.require('openils.widget.AutoGrid'); dojo.require('openils.widget.ProgressDialog'); dojo.require('fieldmapper.OrgUtils'); dojo.requireLocalization('openils.acq', 'acq'); var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq'); var contextOrg; var rolloverResponses; var rolloverMode = false; var fundFleshFields = [ 'spent_balance', 'combined_balance', 'spent_total', 'encumbrance_total', 'debit_total', 'allocation_total' ]; var adminPermOrgs = []; var cachedFunds = []; function initPage() { contextOrg = openils.User.user.ws_ou(); /* Reveal controls for rollover without money if org units say ok. * Actual ability to do the operation is controlled in the database, of * course. */ var ouSettings = fieldmapper.aou.fetchOrgSettingBatch( openils.User.user.ws_ou(), ["acq.fund.allow_rollover_without_money"] ); if ( ouSettings["acq.fund.allow_rollover_without_money"] &&
dojo.query(".encumb_only").forEach( function(o) { openils.Util.show(o, "table-row"); } ); } var connect = function() { dojo.connect(contextOrgSelector, 'onChange', function() { contextOrg = this.attr('value'); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); rolloverMode = false; gridDataLoader(); } ); }; dojo.connect(refreshButton, 'onClick', function() { rolloverMode = false; gridDataLoader(); }); new openils.User().buildPermOrgSelector( ['ADMIN_ACQ_FUND', 'VIEW_FUND'], contextOrgSelector, contextOrg, connect); dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = fieldmapper.aou.findOrgUnit(contextOrg).shortname(); loadYearSelector(); lfGrid.onItemReceived = function(item) {cachedFunds.push(item)}; new openils.User().getPermOrgList( 'ADMIN_ACQ_FUND', function(list) { adminPermOrgs = list; loadFundGrid( new openils.CGI().param('year') || new Date().getFullYear().toString()); }, true, true ); } function gridDataLoader() { lfGrid.resetStore(); if(rolloverMode) { var offset = lfGrid.displayOffset; for(var i = offset; i < (offset + lfGrid.displayLimit - 1); i++) { var fund = rolloverResponses[i]; if(!fund) break; lfGrid.store.newItem(fieldmapper.acqf.toStoreItem(fund)); } } else { loadFundGrid(); } } function getBalanceInfo(rowIdx, item) { if (!item) return ''; var fundId = this.grid.store.getValue(item, 'id'); var fund = cachedFunds.filter(function(f) { return f.id() == fundId })[0]; var cb = fund.combined_balance(); return cb ? cb.amount() : '0'; } function loadFundGrid(year) { openils.Util.hide('acq-fund-list-rollover-summary'); year = year || fundFilterYearSelect.attr('value'); cachedFunds = []; lfGrid.loadAll( { flesh : 1, flesh_fields : {acqf : fundFleshFields}, // by default, sort funds I can edit to the front order_by : [ { 'class' : 'acqf', field : 'org', compare : {'in' : adminPermOrgs}, direction : 'desc' }, { 'class' : 'acqf', field : 'name' } ] }, { year : year, org : fieldmapper.aou.descendantNodeList(contextOrg, true) } ); } function loadYearSelector() { fieldmapper.standardRequest( ['open-ils.acq', 'open-ils.acq.fund.org.years.retrieve'], { async : true, params : [openils.User.authtoken, {}, {limit_perm : 'VIEW_FUND'}], oncomplete : function(r) { var yearList = openils.Util.readResponse(r); if(!yearList) return; yearList = yearList.map(function(year){return {year:year+''};}); // dojo wants strings var yearStore = {identifier:'year', name:'year', items:yearList}; yearStore.items = yearStore.items.sort().reverse(); fundFilterYearSelect.store = new dojo.data.ItemFileWriteStore({data:yearStore}); // default to this year fundFilterYearSelect.setValue(new Date().getFullYear().toString()); dojo.connect( fundFilterYearSelect, 'onChange', function() { rolloverMode = false; gridDataLoader(); } ); } } ); } function performRollover(args) { rolloverMode = true; progressDialog.show(true, "Processing..."); rolloverResponses = []; var method = 'open-ils.acq.fiscal_rollover'; if(args.rollover[0] == 'on') { method += '.combined'; } else { method += '.propagate'; } var dryRun = args.dry_run[0] == 'on'; if(dryRun) method += '.dry_run'; var encumbOnly = args.encumb_only[0] == 'on'; var count = 0; var amount_rolled = 0; var year = fundFilterYearSelect.attr('value'); // TODO alternate selector? fieldmapper.standardRequest( ['open-ils.acq', method], { async : true, params : [ openils.User.authtoken, year, contextOrg, (args.child_orgs[0] == 'on'), { encumb_only : encumbOnly } ], onresponse : function(r) { var resp = openils.Util.readResponse(r); rolloverResponses.push(resp.fund); count += 1; amount_rolled += Number(resp.rollover_amount); }, oncomplete : function() { var nextYear = Number(year) + 1; rolloverResponses = rolloverResponses.sort( function(a, b) { if(a.code() > b.code()) return 1; return -1; } ) // add the new, rolled funds to the cache. Note that in dry-run // mode, these are ephemeral and no longer exist on the server. cachedFunds = cachedFunds.concat(rolloverResponses); dojo.byId('acq-fund-list-rollover-summary-header').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY, [nextYear] ); dojo.byId('acq-fund-list-rollover-summary-funds').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_FUNDS, [nextYear, count] ); dojo.byId('acq-fund-list-rollover-summary-rollover-amount').innerHTML = dojo.string.substitute( localeStrings.FUND_LIST_ROLLOVER_SUMMARY_ROLLOVER_AMOUNT, [nextYear, amount_rolled] ); if(!dryRun) { openils.Util.hide('acq-fund-list-rollover-summary-dry-run'); // add the new year to the year selector if it's not already there fundFilterYearSelect.store.fetch({ query : {year : nextYear}, onComplete: function(list) { if(list && list.length > 0) return; fundFilterYearSelect.store.newItem({year : nextYear}); } }); } openils.Util.show('acq-fund-list-rollover-summary'); progressDialog.hide(); gridDataLoader(); } } ); } openils.Util.addOnLoad(initPage);
ouSettings["acq.fund.allow_rollover_without_money"].value ) {
random_line_split
robots_txt.rs
use crate::model::Path; use crate::model::RequestRate; use crate::model::RobotsTxt; use crate::service::RobotsTxtService; use std::time::Duration; use url::Url; impl RobotsTxtService for RobotsTxt { fn can_fetch(&self, user_agent: &str, url: &Url) -> bool { if url.origin() != *self.get_origin() { return false; } let path = Path::from_url(url); let rule_decision = self.find_in_group(user_agent, |group| { let rules = group.get_rules_sorted_by_path_len_desc(); for rule in rules.iter() { if rule.applies_to(&path) { return Some(rule.get_allowance()); } } None }); if let Some(rule_decision) = rule_decision { return rule_decision; } // Empty robots.txt allows crawling. Everything that was not denied must be allowed. true } fn get_crawl_delay(&self, user_agent: &str) -> Option<Duration> { self.find_in_group(user_agent, |group| group.get_crawl_delay()) } fn normalize_url(&self, url: &mut Url) -> bool
fn normalize_url_ignore_origin(&self, url: &mut Url) { if url.query().is_none() { return; } let mut query_params_to_filter = Vec::new(); let path = Path::from_url(url); for clean_params in self.get_clean_params().iter() { if clean_params.get_path_pattern().applies_to(&path) { query_params_to_filter.extend_from_slice(clean_params.get_params()) } } let mut pairs: Vec<(String, String)> = url .query_pairs() .map(|(key, value)| (key.into(), value.into())) .collect(); { let mut query_pairs_mut = url.query_pairs_mut(); query_pairs_mut.clear(); for (key, value) in pairs.drain(..) { if !query_params_to_filter.contains(&key) { query_pairs_mut.append_pair(&key, &value); } } } if url.query() == Some("") { url.set_query(None); } } fn get_sitemaps(&self) -> &[Url] { self.get_sitemaps_slice() } fn get_req_rate(&self, user_agent: &str) -> Option<RequestRate> { self.find_in_group(user_agent, |group| group.get_req_rate()) } }
{ if url.origin() != *self.get_origin() { return false; } self.normalize_url_ignore_origin(url); true }
identifier_body
robots_txt.rs
use crate::model::Path; use crate::model::RequestRate; use crate::model::RobotsTxt; use crate::service::RobotsTxtService; use std::time::Duration; use url::Url; impl RobotsTxtService for RobotsTxt { fn can_fetch(&self, user_agent: &str, url: &Url) -> bool { if url.origin() != *self.get_origin() { return false; } let path = Path::from_url(url); let rule_decision = self.find_in_group(user_agent, |group| { let rules = group.get_rules_sorted_by_path_len_desc(); for rule in rules.iter() { if rule.applies_to(&path) { return Some(rule.get_allowance()); } } None }); if let Some(rule_decision) = rule_decision { return rule_decision; } // Empty robots.txt allows crawling. Everything that was not denied must be allowed. true } fn get_crawl_delay(&self, user_agent: &str) -> Option<Duration> { self.find_in_group(user_agent, |group| group.get_crawl_delay()) } fn normalize_url(&self, url: &mut Url) -> bool { if url.origin() != *self.get_origin() { return false; } self.normalize_url_ignore_origin(url); true } fn
(&self, url: &mut Url) { if url.query().is_none() { return; } let mut query_params_to_filter = Vec::new(); let path = Path::from_url(url); for clean_params in self.get_clean_params().iter() { if clean_params.get_path_pattern().applies_to(&path) { query_params_to_filter.extend_from_slice(clean_params.get_params()) } } let mut pairs: Vec<(String, String)> = url .query_pairs() .map(|(key, value)| (key.into(), value.into())) .collect(); { let mut query_pairs_mut = url.query_pairs_mut(); query_pairs_mut.clear(); for (key, value) in pairs.drain(..) { if !query_params_to_filter.contains(&key) { query_pairs_mut.append_pair(&key, &value); } } } if url.query() == Some("") { url.set_query(None); } } fn get_sitemaps(&self) -> &[Url] { self.get_sitemaps_slice() } fn get_req_rate(&self, user_agent: &str) -> Option<RequestRate> { self.find_in_group(user_agent, |group| group.get_req_rate()) } }
normalize_url_ignore_origin
identifier_name
robots_txt.rs
use crate::model::Path; use crate::model::RequestRate; use crate::model::RobotsTxt; use crate::service::RobotsTxtService; use std::time::Duration; use url::Url; impl RobotsTxtService for RobotsTxt { fn can_fetch(&self, user_agent: &str, url: &Url) -> bool { if url.origin() != *self.get_origin() { return false; } let path = Path::from_url(url); let rule_decision = self.find_in_group(user_agent, |group| { let rules = group.get_rules_sorted_by_path_len_desc(); for rule in rules.iter() { if rule.applies_to(&path) { return Some(rule.get_allowance()); } } None }); if let Some(rule_decision) = rule_decision { return rule_decision; } // Empty robots.txt allows crawling. Everything that was not denied must be allowed. true } fn get_crawl_delay(&self, user_agent: &str) -> Option<Duration> { self.find_in_group(user_agent, |group| group.get_crawl_delay()) } fn normalize_url(&self, url: &mut Url) -> bool { if url.origin() != *self.get_origin() { return false; } self.normalize_url_ignore_origin(url); true } fn normalize_url_ignore_origin(&self, url: &mut Url) { if url.query().is_none() { return; } let mut query_params_to_filter = Vec::new(); let path = Path::from_url(url); for clean_params in self.get_clean_params().iter() { if clean_params.get_path_pattern().applies_to(&path)
} let mut pairs: Vec<(String, String)> = url .query_pairs() .map(|(key, value)| (key.into(), value.into())) .collect(); { let mut query_pairs_mut = url.query_pairs_mut(); query_pairs_mut.clear(); for (key, value) in pairs.drain(..) { if !query_params_to_filter.contains(&key) { query_pairs_mut.append_pair(&key, &value); } } } if url.query() == Some("") { url.set_query(None); } } fn get_sitemaps(&self) -> &[Url] { self.get_sitemaps_slice() } fn get_req_rate(&self, user_agent: &str) -> Option<RequestRate> { self.find_in_group(user_agent, |group| group.get_req_rate()) } }
{ query_params_to_filter.extend_from_slice(clean_params.get_params()) }
conditional_block
robots_txt.rs
use crate::model::Path; use crate::model::RequestRate; use crate::model::RobotsTxt; use crate::service::RobotsTxtService; use std::time::Duration; use url::Url; impl RobotsTxtService for RobotsTxt { fn can_fetch(&self, user_agent: &str, url: &Url) -> bool { if url.origin() != *self.get_origin() { return false; } let path = Path::from_url(url); let rule_decision = self.find_in_group(user_agent, |group| { let rules = group.get_rules_sorted_by_path_len_desc(); for rule in rules.iter() { if rule.applies_to(&path) {
} None }); if let Some(rule_decision) = rule_decision { return rule_decision; } // Empty robots.txt allows crawling. Everything that was not denied must be allowed. true } fn get_crawl_delay(&self, user_agent: &str) -> Option<Duration> { self.find_in_group(user_agent, |group| group.get_crawl_delay()) } fn normalize_url(&self, url: &mut Url) -> bool { if url.origin() != *self.get_origin() { return false; } self.normalize_url_ignore_origin(url); true } fn normalize_url_ignore_origin(&self, url: &mut Url) { if url.query().is_none() { return; } let mut query_params_to_filter = Vec::new(); let path = Path::from_url(url); for clean_params in self.get_clean_params().iter() { if clean_params.get_path_pattern().applies_to(&path) { query_params_to_filter.extend_from_slice(clean_params.get_params()) } } let mut pairs: Vec<(String, String)> = url .query_pairs() .map(|(key, value)| (key.into(), value.into())) .collect(); { let mut query_pairs_mut = url.query_pairs_mut(); query_pairs_mut.clear(); for (key, value) in pairs.drain(..) { if !query_params_to_filter.contains(&key) { query_pairs_mut.append_pair(&key, &value); } } } if url.query() == Some("") { url.set_query(None); } } fn get_sitemaps(&self) -> &[Url] { self.get_sitemaps_slice() } fn get_req_rate(&self, user_agent: &str) -> Option<RequestRate> { self.find_in_group(user_agent, |group| group.get_req_rate()) } }
return Some(rule.get_allowance()); }
random_line_split
hygiene_example_codegen.rs
// force-host // no-prefer-dynamic #![feature(proc_macro_quote)] #![crate_type = "proc-macro"] extern crate proc_macro as proc_macro_renamed; // This does not break `quote!` use proc_macro_renamed::{TokenStream, quote}; #[proc_macro] pub fn
(input: TokenStream) -> TokenStream { quote!(hello_helper!($input)) //^ `hello_helper!` always resolves to the following proc macro, //| no matter where `hello!` is used. } #[proc_macro] pub fn hello_helper(input: TokenStream) -> TokenStream { quote! { extern crate hygiene_example; // This is never a conflict error let string = format!("hello {}", $input); //^ `format!` always resolves to the prelude macro, //| even if a different `format!` is in scope where `hello!` is used. hygiene_example::print(&string) } }
hello
identifier_name
hygiene_example_codegen.rs
// force-host
#![feature(proc_macro_quote)] #![crate_type = "proc-macro"] extern crate proc_macro as proc_macro_renamed; // This does not break `quote!` use proc_macro_renamed::{TokenStream, quote}; #[proc_macro] pub fn hello(input: TokenStream) -> TokenStream { quote!(hello_helper!($input)) //^ `hello_helper!` always resolves to the following proc macro, //| no matter where `hello!` is used. } #[proc_macro] pub fn hello_helper(input: TokenStream) -> TokenStream { quote! { extern crate hygiene_example; // This is never a conflict error let string = format!("hello {}", $input); //^ `format!` always resolves to the prelude macro, //| even if a different `format!` is in scope where `hello!` is used. hygiene_example::print(&string) } }
// no-prefer-dynamic
random_line_split
hygiene_example_codegen.rs
// force-host // no-prefer-dynamic #![feature(proc_macro_quote)] #![crate_type = "proc-macro"] extern crate proc_macro as proc_macro_renamed; // This does not break `quote!` use proc_macro_renamed::{TokenStream, quote}; #[proc_macro] pub fn hello(input: TokenStream) -> TokenStream { quote!(hello_helper!($input)) //^ `hello_helper!` always resolves to the following proc macro, //| no matter where `hello!` is used. } #[proc_macro] pub fn hello_helper(input: TokenStream) -> TokenStream
{ quote! { extern crate hygiene_example; // This is never a conflict error let string = format!("hello {}", $input); //^ `format!` always resolves to the prelude macro, //| even if a different `format!` is in scope where `hello!` is used. hygiene_example::print(&string) } }
identifier_body
test_something.py
# Copyright <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import HttpCase, TransactionCase class SomethingCase(TransactionCase): def setUp(self, *args, **kwargs): super(SomethingCase, self).setUp(*args, **kwargs) # TODO Replace this for something useful or delete this method self.do_something_before_all_tests() def tearDown(self, *args, **kwargs): # TODO Replace this for something useful or delete this method self.do_something_after_all_tests() return super(SomethingCase, self).tearDown(*args, **kwargs) def test_something(self): """First line of docstring appears in test logs. Other lines do not. Any method starting with ``test_`` will be tested. """
post_install = True at_install = False def test_ui_web(self): """Test backend tests.""" self.phantom_js( "/web/tests?debug=assets&module=module_name", "", login="admin", ) def test_ui_website(self): """Test frontend tour.""" self.phantom_js( url_path="/?debug=assets", code="odoo.__DEBUG__.services['web.Tour']" ".run('test_module_name', 'test')", ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name", login="admin")
pass class UICase(HttpCase):
random_line_split
test_something.py
# Copyright <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import HttpCase, TransactionCase class SomethingCase(TransactionCase): def setUp(self, *args, **kwargs): super(SomethingCase, self).setUp(*args, **kwargs) # TODO Replace this for something useful or delete this method self.do_something_before_all_tests() def tearDown(self, *args, **kwargs): # TODO Replace this for something useful or delete this method self.do_something_after_all_tests() return super(SomethingCase, self).tearDown(*args, **kwargs) def test_something(self): """First line of docstring appears in test logs. Other lines do not. Any method starting with ``test_`` will be tested. """ pass class UICase(HttpCase): post_install = True at_install = False def
(self): """Test backend tests.""" self.phantom_js( "/web/tests?debug=assets&module=module_name", "", login="admin", ) def test_ui_website(self): """Test frontend tour.""" self.phantom_js( url_path="/?debug=assets", code="odoo.__DEBUG__.services['web.Tour']" ".run('test_module_name', 'test')", ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name", login="admin")
test_ui_web
identifier_name
test_something.py
# Copyright <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import HttpCase, TransactionCase class SomethingCase(TransactionCase): def setUp(self, *args, **kwargs): super(SomethingCase, self).setUp(*args, **kwargs) # TODO Replace this for something useful or delete this method self.do_something_before_all_tests() def tearDown(self, *args, **kwargs): # TODO Replace this for something useful or delete this method self.do_something_after_all_tests() return super(SomethingCase, self).tearDown(*args, **kwargs) def test_something(self): """First line of docstring appears in test logs. Other lines do not. Any method starting with ``test_`` will be tested. """ pass class UICase(HttpCase): post_install = True at_install = False def test_ui_web(self):
def test_ui_website(self): """Test frontend tour.""" self.phantom_js( url_path="/?debug=assets", code="odoo.__DEBUG__.services['web.Tour']" ".run('test_module_name', 'test')", ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name", login="admin")
"""Test backend tests.""" self.phantom_js( "/web/tests?debug=assets&module=module_name", "", login="admin", )
identifier_body
sync_rando.py
from django.conf import settings from django.utils import translation from geotrek.tourism import models as tourism_models from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand # Register mapentity models
class Command(BaseCommand): def sync_content(self, lang, content): self.sync_pdf(lang, content) for picture, resized in content.resized_pictures: self.sync_media_file(lang, resized) def sync_event(self, lang, event): self.sync_pdf(lang, event) for picture, resized in event.resized_pictures: self.sync_media_file(lang, resized) def sync_tourism(self, lang): self.sync_geojson(lang, TouristicContentViewSet, 'touristiccontents') self.sync_geojson(lang, TouristicEventViewSet, 'touristicevents') contents = tourism_models.TouristicContent.objects.existing().order_by('pk') contents = contents.filter(**{'published_{lang}'.format(lang=lang): True}) for content in contents: self.sync_content(lang, content) events = tourism_models.TouristicEvent.objects.existing().order_by('pk') events = events.filter(**{'published_{lang}'.format(lang=lang): True}) for event in events: self.sync_event(lang, event) def sync(self): super(Command, self).sync() self.sync_static_file('**', 'tourism/touristicevent.svg') self.sync_pictograms('**', tourism_models.InformationDeskType) self.sync_pictograms('**', tourism_models.TouristicContentCategory) self.sync_pictograms('**', tourism_models.TouristicContentType) self.sync_pictograms('**', tourism_models.TouristicEventType) for lang in settings.MODELTRANSLATION_LANGUAGES: translation.activate(lang) self.sync_tourism(lang)
from geotrek.tourism import urls # NOQA
random_line_split
sync_rando.py
from django.conf import settings from django.utils import translation from geotrek.tourism import models as tourism_models from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand # Register mapentity models from geotrek.tourism import urls # NOQA class Command(BaseCommand): def sync_content(self, lang, content): self.sync_pdf(lang, content) for picture, resized in content.resized_pictures: self.sync_media_file(lang, resized) def sync_event(self, lang, event): self.sync_pdf(lang, event) for picture, resized in event.resized_pictures: self.sync_media_file(lang, resized) def sync_tourism(self, lang):
def sync(self): super(Command, self).sync() self.sync_static_file('**', 'tourism/touristicevent.svg') self.sync_pictograms('**', tourism_models.InformationDeskType) self.sync_pictograms('**', tourism_models.TouristicContentCategory) self.sync_pictograms('**', tourism_models.TouristicContentType) self.sync_pictograms('**', tourism_models.TouristicEventType) for lang in settings.MODELTRANSLATION_LANGUAGES: translation.activate(lang) self.sync_tourism(lang)
self.sync_geojson(lang, TouristicContentViewSet, 'touristiccontents') self.sync_geojson(lang, TouristicEventViewSet, 'touristicevents') contents = tourism_models.TouristicContent.objects.existing().order_by('pk') contents = contents.filter(**{'published_{lang}'.format(lang=lang): True}) for content in contents: self.sync_content(lang, content) events = tourism_models.TouristicEvent.objects.existing().order_by('pk') events = events.filter(**{'published_{lang}'.format(lang=lang): True}) for event in events: self.sync_event(lang, event)
identifier_body
sync_rando.py
from django.conf import settings from django.utils import translation from geotrek.tourism import models as tourism_models from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand # Register mapentity models from geotrek.tourism import urls # NOQA class Command(BaseCommand): def sync_content(self, lang, content): self.sync_pdf(lang, content) for picture, resized in content.resized_pictures: self.sync_media_file(lang, resized) def
(self, lang, event): self.sync_pdf(lang, event) for picture, resized in event.resized_pictures: self.sync_media_file(lang, resized) def sync_tourism(self, lang): self.sync_geojson(lang, TouristicContentViewSet, 'touristiccontents') self.sync_geojson(lang, TouristicEventViewSet, 'touristicevents') contents = tourism_models.TouristicContent.objects.existing().order_by('pk') contents = contents.filter(**{'published_{lang}'.format(lang=lang): True}) for content in contents: self.sync_content(lang, content) events = tourism_models.TouristicEvent.objects.existing().order_by('pk') events = events.filter(**{'published_{lang}'.format(lang=lang): True}) for event in events: self.sync_event(lang, event) def sync(self): super(Command, self).sync() self.sync_static_file('**', 'tourism/touristicevent.svg') self.sync_pictograms('**', tourism_models.InformationDeskType) self.sync_pictograms('**', tourism_models.TouristicContentCategory) self.sync_pictograms('**', tourism_models.TouristicContentType) self.sync_pictograms('**', tourism_models.TouristicEventType) for lang in settings.MODELTRANSLATION_LANGUAGES: translation.activate(lang) self.sync_tourism(lang)
sync_event
identifier_name
sync_rando.py
from django.conf import settings from django.utils import translation from geotrek.tourism import models as tourism_models from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand # Register mapentity models from geotrek.tourism import urls # NOQA class Command(BaseCommand): def sync_content(self, lang, content): self.sync_pdf(lang, content) for picture, resized in content.resized_pictures: self.sync_media_file(lang, resized) def sync_event(self, lang, event): self.sync_pdf(lang, event) for picture, resized in event.resized_pictures: self.sync_media_file(lang, resized) def sync_tourism(self, lang): self.sync_geojson(lang, TouristicContentViewSet, 'touristiccontents') self.sync_geojson(lang, TouristicEventViewSet, 'touristicevents') contents = tourism_models.TouristicContent.objects.existing().order_by('pk') contents = contents.filter(**{'published_{lang}'.format(lang=lang): True}) for content in contents:
events = tourism_models.TouristicEvent.objects.existing().order_by('pk') events = events.filter(**{'published_{lang}'.format(lang=lang): True}) for event in events: self.sync_event(lang, event) def sync(self): super(Command, self).sync() self.sync_static_file('**', 'tourism/touristicevent.svg') self.sync_pictograms('**', tourism_models.InformationDeskType) self.sync_pictograms('**', tourism_models.TouristicContentCategory) self.sync_pictograms('**', tourism_models.TouristicContentType) self.sync_pictograms('**', tourism_models.TouristicEventType) for lang in settings.MODELTRANSLATION_LANGUAGES: translation.activate(lang) self.sync_tourism(lang)
self.sync_content(lang, content)
conditional_block
_logs.service.ts
<%#
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. -%> import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { SERVER_API_URL } from '../../app.constants'; import { Log } from './log.model'; @Injectable() export class LogsService { constructor(private http: Http) { } changeLevel(log: Log): Observable<Response> { return this.http.put(SERVER_API_URL + 'management/logs', log); } findAll(): Observable<Log[]> { return this.http.get(SERVER_API_URL + 'management/logs').map((res: Response) => res.json()); } }
Copyright 2013-2018 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information.
random_line_split
_logs.service.ts
<%# Copyright 2013-2018 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. 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. -%> import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { SERVER_API_URL } from '../../app.constants'; import { Log } from './log.model'; @Injectable() export class
{ constructor(private http: Http) { } changeLevel(log: Log): Observable<Response> { return this.http.put(SERVER_API_URL + 'management/logs', log); } findAll(): Observable<Log[]> { return this.http.get(SERVER_API_URL + 'management/logs').map((res: Response) => res.json()); } }
LogsService
identifier_name
_logs.service.ts
<%# Copyright 2013-2018 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. 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. -%> import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { SERVER_API_URL } from '../../app.constants'; import { Log } from './log.model'; @Injectable() export class LogsService { constructor(private http: Http) { } changeLevel(log: Log): Observable<Response>
findAll(): Observable<Log[]> { return this.http.get(SERVER_API_URL + 'management/logs').map((res: Response) => res.json()); } }
{ return this.http.put(SERVER_API_URL + 'management/logs', log); }
identifier_body
wineryDuplicateValidator.directive.ts
/** * Copyright (c) 2017 University of Stuttgart. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and the Apache License 2.0 which both accompany this distribution, * and are available at http://www.eclipse.org/legal/epl-v10.html * and http://www.apache.org/licenses/LICENSE-2.0 * * Contributors: * Niko Stadelmaier - initial API and implementation */ import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core'; import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms'; import { isNullOrUndefined } from 'util'; export class WineryValidatorObject { list: Array<any>; property?: string; constructor(list: Array<any>, property?: string) { this.list = list; this.property = property; } validate(compareObject: WineryValidatorObject): ValidatorFn { return (control: AbstractControl): { [key: string]: any } => { if (isNullOrUndefined(compareObject) || isNullOrUndefined(compareObject.list)) { return null; } const name = control.value; let no = false; if (isNullOrUndefined(compareObject.property))
else { no = compareObject.list.find(item => item[compareObject.property] === name); } return no ? {'wineryDuplicateValidator': {name}} : null; }; } } @Directive({ selector: '[wineryDuplicateValidator]', providers: [{provide: NG_VALIDATORS, useExisting: WineryDuplicateValidatorDirective, multi: true}] }) export class WineryDuplicateValidatorDirective implements Validator, OnChanges { @Input() wineryDuplicateValidator: WineryValidatorObject; private valFn = Validators.nullValidator; ngOnChanges(changes: SimpleChanges): void { const change = changes['wineryDuplicateValidator']; if (change && !isNullOrUndefined(this.wineryDuplicateValidator)) { const val: WineryValidatorObject = change.currentValue; this.valFn = this.wineryDuplicateValidator.validate(val); } else { this.valFn = Validators.nullValidator; } } validate(control: AbstractControl): { [key: string]: any } { return this.valFn(control); } }
{ no = compareObject.list.find(item => item === name); }
conditional_block
wineryDuplicateValidator.directive.ts
/** * Copyright (c) 2017 University of Stuttgart. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and the Apache License 2.0 which both accompany this distribution, * and are available at http://www.eclipse.org/legal/epl-v10.html * and http://www.apache.org/licenses/LICENSE-2.0 * * Contributors: * Niko Stadelmaier - initial API and implementation */ import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core'; import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms'; import { isNullOrUndefined } from 'util'; export class WineryValidatorObject { list: Array<any>; property?: string; constructor(list: Array<any>, property?: string) { this.list = list; this.property = property; } validate(compareObject: WineryValidatorObject): ValidatorFn { return (control: AbstractControl): { [key: string]: any } => { if (isNullOrUndefined(compareObject) || isNullOrUndefined(compareObject.list)) { return null; } const name = control.value; let no = false; if (isNullOrUndefined(compareObject.property)) { no = compareObject.list.find(item => item === name); } else { no = compareObject.list.find(item => item[compareObject.property] === name); } return no ? {'wineryDuplicateValidator': {name}} : null; }; } } @Directive({ selector: '[wineryDuplicateValidator]',
@Input() wineryDuplicateValidator: WineryValidatorObject; private valFn = Validators.nullValidator; ngOnChanges(changes: SimpleChanges): void { const change = changes['wineryDuplicateValidator']; if (change && !isNullOrUndefined(this.wineryDuplicateValidator)) { const val: WineryValidatorObject = change.currentValue; this.valFn = this.wineryDuplicateValidator.validate(val); } else { this.valFn = Validators.nullValidator; } } validate(control: AbstractControl): { [key: string]: any } { return this.valFn(control); } }
providers: [{provide: NG_VALIDATORS, useExisting: WineryDuplicateValidatorDirective, multi: true}] }) export class WineryDuplicateValidatorDirective implements Validator, OnChanges {
random_line_split
wineryDuplicateValidator.directive.ts
/** * Copyright (c) 2017 University of Stuttgart. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and the Apache License 2.0 which both accompany this distribution, * and are available at http://www.eclipse.org/legal/epl-v10.html * and http://www.apache.org/licenses/LICENSE-2.0 * * Contributors: * Niko Stadelmaier - initial API and implementation */ import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core'; import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms'; import { isNullOrUndefined } from 'util'; export class WineryValidatorObject { list: Array<any>; property?: string; constructor(list: Array<any>, property?: string) { this.list = list; this.property = property; } validate(compareObject: WineryValidatorObject): ValidatorFn { return (control: AbstractControl): { [key: string]: any } => { if (isNullOrUndefined(compareObject) || isNullOrUndefined(compareObject.list)) { return null; } const name = control.value; let no = false; if (isNullOrUndefined(compareObject.property)) { no = compareObject.list.find(item => item === name); } else { no = compareObject.list.find(item => item[compareObject.property] === name); } return no ? {'wineryDuplicateValidator': {name}} : null; }; } } @Directive({ selector: '[wineryDuplicateValidator]', providers: [{provide: NG_VALIDATORS, useExisting: WineryDuplicateValidatorDirective, multi: true}] }) export class WineryDuplicateValidatorDirective implements Validator, OnChanges { @Input() wineryDuplicateValidator: WineryValidatorObject; private valFn = Validators.nullValidator; ngOnChanges(changes: SimpleChanges): void { const change = changes['wineryDuplicateValidator']; if (change && !isNullOrUndefined(this.wineryDuplicateValidator)) { const val: WineryValidatorObject = change.currentValue; this.valFn = this.wineryDuplicateValidator.validate(val); } else { this.valFn = Validators.nullValidator; } } validate(control: AbstractControl): { [key: string]: any }
}
{ return this.valFn(control); }
identifier_body
wineryDuplicateValidator.directive.ts
/** * Copyright (c) 2017 University of Stuttgart. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and the Apache License 2.0 which both accompany this distribution, * and are available at http://www.eclipse.org/legal/epl-v10.html * and http://www.apache.org/licenses/LICENSE-2.0 * * Contributors: * Niko Stadelmaier - initial API and implementation */ import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core'; import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms'; import { isNullOrUndefined } from 'util'; export class WineryValidatorObject { list: Array<any>; property?: string; constructor(list: Array<any>, property?: string) { this.list = list; this.property = property; } validate(compareObject: WineryValidatorObject): ValidatorFn { return (control: AbstractControl): { [key: string]: any } => { if (isNullOrUndefined(compareObject) || isNullOrUndefined(compareObject.list)) { return null; } const name = control.value; let no = false; if (isNullOrUndefined(compareObject.property)) { no = compareObject.list.find(item => item === name); } else { no = compareObject.list.find(item => item[compareObject.property] === name); } return no ? {'wineryDuplicateValidator': {name}} : null; }; } } @Directive({ selector: '[wineryDuplicateValidator]', providers: [{provide: NG_VALIDATORS, useExisting: WineryDuplicateValidatorDirective, multi: true}] }) export class WineryDuplicateValidatorDirective implements Validator, OnChanges { @Input() wineryDuplicateValidator: WineryValidatorObject; private valFn = Validators.nullValidator;
(changes: SimpleChanges): void { const change = changes['wineryDuplicateValidator']; if (change && !isNullOrUndefined(this.wineryDuplicateValidator)) { const val: WineryValidatorObject = change.currentValue; this.valFn = this.wineryDuplicateValidator.validate(val); } else { this.valFn = Validators.nullValidator; } } validate(control: AbstractControl): { [key: string]: any } { return this.valFn(control); } }
ngOnChanges
identifier_name
lightbot.js
var keypress = require("keypress"); // var Spark = require("spark-io"); var Spark = require("../"); var five = require("johnny-five"); var Sumobot = require("sumobot")(five); keypress(process.stdin); var board = new five.Board({ io: new Spark({ token: process.env.SPARK_TOKEN, deviceId: process.env.SPARK_DEVICE_2 }) }); board.on("ready", function() { console.log("Welcome to Sumobot Jr: Light Bot!"); var bot = new Sumobot({ left: "D0", right: "D1", speed: 0.50 }); var light = new five.Sensor("A0"); var isQuitting = false; light.on("change", function() { if (isQuitting || this.value === null) { return; } if (this.value < 512)
else { bot.rev(); } }); // Ensure the bot is stopped bot.stop(); });
{ bot.fwd(); }
conditional_block
lightbot.js
var keypress = require("keypress"); // var Spark = require("spark-io"); var Spark = require("../"); var five = require("johnny-five"); var Sumobot = require("sumobot")(five); keypress(process.stdin); var board = new five.Board({ io: new Spark({ token: process.env.SPARK_TOKEN, deviceId: process.env.SPARK_DEVICE_2 }) }); board.on("ready", function() { console.log("Welcome to Sumobot Jr: Light Bot!");
}); var light = new five.Sensor("A0"); var isQuitting = false; light.on("change", function() { if (isQuitting || this.value === null) { return; } if (this.value < 512) { bot.fwd(); } else { bot.rev(); } }); // Ensure the bot is stopped bot.stop(); });
var bot = new Sumobot({ left: "D0", right: "D1", speed: 0.50
random_line_split
req_handler_unary.rs
use crate::error; use crate::result; use crate::server::req_handler::ServerRequestStreamHandler; use crate::server::req_handler::ServerRequestUnaryHandler; use httpbis::IncreaseInWindow; use std::marker; pub(crate) struct RequestHandlerUnaryToStream<M, H> where H: ServerRequestUnaryHandler<M>, M: Send + 'static, { pub(crate) increase_in_window: IncreaseInWindow, pub(crate) handler: H, pub(crate) message: Option<M>, pub(crate) _marker: marker::PhantomData<M>, } impl<M, H> ServerRequestStreamHandler<M> for RequestHandlerUnaryToStream<M, H> where H: ServerRequestUnaryHandler<M>, M: Send + 'static, { fn grpc_message(&mut self, message: M, frame_size: usize) -> result::Result<()> { self.increase_in_window.data_frame_processed(frame_size); self.increase_in_window.increase_window_auto()?; if let Some(_) = self.message { return Err(error::Error::Other("more than one message in a stream")); } self.message = Some(message); Ok(()) } fn end_stream(&mut self) -> result::Result<()> { match self.message.take() { Some(message) => self.handler.grpc_message(message), None => Err(error::Error::Other("no message, end of stream")), } } fn buffer_processed(&mut self, buffered: usize) -> result::Result<()>
}
{ // TODO: overflow check self.increase_in_window .increase_window_auto_above(buffered as u32)?; Ok(()) }
identifier_body
req_handler_unary.rs
use crate::error; use crate::result; use crate::server::req_handler::ServerRequestStreamHandler; use crate::server::req_handler::ServerRequestUnaryHandler; use httpbis::IncreaseInWindow; use std::marker; pub(crate) struct RequestHandlerUnaryToStream<M, H> where H: ServerRequestUnaryHandler<M>, M: Send + 'static, { pub(crate) increase_in_window: IncreaseInWindow, pub(crate) handler: H, pub(crate) message: Option<M>, pub(crate) _marker: marker::PhantomData<M>, } impl<M, H> ServerRequestStreamHandler<M> for RequestHandlerUnaryToStream<M, H> where H: ServerRequestUnaryHandler<M>, M: Send + 'static, { fn grpc_message(&mut self, message: M, frame_size: usize) -> result::Result<()> { self.increase_in_window.data_frame_processed(frame_size); self.increase_in_window.increase_window_auto()?; if let Some(_) = self.message
self.message = Some(message); Ok(()) } fn end_stream(&mut self) -> result::Result<()> { match self.message.take() { Some(message) => self.handler.grpc_message(message), None => Err(error::Error::Other("no message, end of stream")), } } fn buffer_processed(&mut self, buffered: usize) -> result::Result<()> { // TODO: overflow check self.increase_in_window .increase_window_auto_above(buffered as u32)?; Ok(()) } }
{ return Err(error::Error::Other("more than one message in a stream")); }
conditional_block
req_handler_unary.rs
use crate::error; use crate::result; use crate::server::req_handler::ServerRequestStreamHandler; use crate::server::req_handler::ServerRequestUnaryHandler; use httpbis::IncreaseInWindow; use std::marker; pub(crate) struct
<M, H> where H: ServerRequestUnaryHandler<M>, M: Send + 'static, { pub(crate) increase_in_window: IncreaseInWindow, pub(crate) handler: H, pub(crate) message: Option<M>, pub(crate) _marker: marker::PhantomData<M>, } impl<M, H> ServerRequestStreamHandler<M> for RequestHandlerUnaryToStream<M, H> where H: ServerRequestUnaryHandler<M>, M: Send + 'static, { fn grpc_message(&mut self, message: M, frame_size: usize) -> result::Result<()> { self.increase_in_window.data_frame_processed(frame_size); self.increase_in_window.increase_window_auto()?; if let Some(_) = self.message { return Err(error::Error::Other("more than one message in a stream")); } self.message = Some(message); Ok(()) } fn end_stream(&mut self) -> result::Result<()> { match self.message.take() { Some(message) => self.handler.grpc_message(message), None => Err(error::Error::Other("no message, end of stream")), } } fn buffer_processed(&mut self, buffered: usize) -> result::Result<()> { // TODO: overflow check self.increase_in_window .increase_window_auto_above(buffered as u32)?; Ok(()) } }
RequestHandlerUnaryToStream
identifier_name
req_handler_unary.rs
use crate::error; use crate::result; use crate::server::req_handler::ServerRequestStreamHandler; use crate::server::req_handler::ServerRequestUnaryHandler; use httpbis::IncreaseInWindow; use std::marker; pub(crate) struct RequestHandlerUnaryToStream<M, H> where H: ServerRequestUnaryHandler<M>, M: Send + 'static, { pub(crate) increase_in_window: IncreaseInWindow, pub(crate) handler: H, pub(crate) message: Option<M>, pub(crate) _marker: marker::PhantomData<M>, } impl<M, H> ServerRequestStreamHandler<M> for RequestHandlerUnaryToStream<M, H> where H: ServerRequestUnaryHandler<M>, M: Send + 'static, { fn grpc_message(&mut self, message: M, frame_size: usize) -> result::Result<()> { self.increase_in_window.data_frame_processed(frame_size); self.increase_in_window.increase_window_auto()?; if let Some(_) = self.message { return Err(error::Error::Other("more than one message in a stream")); } self.message = Some(message); Ok(()) } fn end_stream(&mut self) -> result::Result<()> { match self.message.take() {
fn buffer_processed(&mut self, buffered: usize) -> result::Result<()> { // TODO: overflow check self.increase_in_window .increase_window_auto_above(buffered as u32)?; Ok(()) } }
Some(message) => self.handler.grpc_message(message), None => Err(error::Error::Other("no message, end of stream")), } }
random_line_split
class-add.tsx
import { connect } from 'react-redux' import { State} from '../../control/reducers' import { User, Roles } from '../../control/user' import * as React from "react"; import {Course, Class} from "../../control/class" import {DropdownStringInput} from '../utilities/dropdown-string-input' import {Input} from '../utilities/input' import {IntInput} from '../utilities/int-input' import {DepartmentDropdown} from '../department-dropdown' import {WeekView} from "../utilities/week-view" export interface ClassAdd { user: User, course: Course } export const ClassAdd = connect( (state: State) => ({user: state.user})) (class extends React.Component<ClassAdd, {}> { state: Class; constructor(props: ClassAdd)
render() { if (this.props.user.role === Roles.student || this.props.user.role === Roles.teacher) { return <div/> } return <tr className={"class-add" + (this.state.syllabus?" link":"")} > <td> <IntInput value={this.state.section} label="section" onChange={v => this.setState({section: v})} /> </td> <td> {this.state.term} <IntInput value={this.state.year} label="year" onChange={v => this.setState({year: v})} /> </td> <td> <IntInput value={this.state.CRN} label="CRN" onChange={v => this.setState({CRN: v})} /> </td> <td> <WeekView days={this.state.days}/> </td> <td> <Input value={this.state.CRN} label="Start" onChange={v => this.setState({start: new Date(v)})} /> </td> <td> {Math.floor(this.state.length/60)}:{("0" + this.state.length%60).slice(-2)} </td> </tr> } })
{ super(props); this.state = { section: undefined, semester: undefined, term: "", year: undefined, teacher: props.user, CRN: undefined, days: {sun: false, mon: false, tue: false, thu: false, wed: false, fri: false, sat: false, id: undefined}, syllabus: undefined, time: undefined, length: undefined } }
identifier_body
class-add.tsx
import { connect } from 'react-redux' import { State} from '../../control/reducers' import { User, Roles } from '../../control/user' import * as React from "react"; import {Course, Class} from "../../control/class" import {DropdownStringInput} from '../utilities/dropdown-string-input' import {Input} from '../utilities/input' import {IntInput} from '../utilities/int-input'
user: User, course: Course } export const ClassAdd = connect( (state: State) => ({user: state.user})) (class extends React.Component<ClassAdd, {}> { state: Class; constructor(props: ClassAdd) { super(props); this.state = { section: undefined, semester: undefined, term: "", year: undefined, teacher: props.user, CRN: undefined, days: {sun: false, mon: false, tue: false, thu: false, wed: false, fri: false, sat: false, id: undefined}, syllabus: undefined, time: undefined, length: undefined } } render() { if (this.props.user.role === Roles.student || this.props.user.role === Roles.teacher) { return <div/> } return <tr className={"class-add" + (this.state.syllabus?" link":"")} > <td> <IntInput value={this.state.section} label="section" onChange={v => this.setState({section: v})} /> </td> <td> {this.state.term} <IntInput value={this.state.year} label="year" onChange={v => this.setState({year: v})} /> </td> <td> <IntInput value={this.state.CRN} label="CRN" onChange={v => this.setState({CRN: v})} /> </td> <td> <WeekView days={this.state.days}/> </td> <td> <Input value={this.state.CRN} label="Start" onChange={v => this.setState({start: new Date(v)})} /> </td> <td> {Math.floor(this.state.length/60)}:{("0" + this.state.length%60).slice(-2)} </td> </tr> } })
import {DepartmentDropdown} from '../department-dropdown' import {WeekView} from "../utilities/week-view" export interface ClassAdd {
random_line_split
class-add.tsx
import { connect } from 'react-redux' import { State} from '../../control/reducers' import { User, Roles } from '../../control/user' import * as React from "react"; import {Course, Class} from "../../control/class" import {DropdownStringInput} from '../utilities/dropdown-string-input' import {Input} from '../utilities/input' import {IntInput} from '../utilities/int-input' import {DepartmentDropdown} from '../department-dropdown' import {WeekView} from "../utilities/week-view" export interface ClassAdd { user: User, course: Course } export const ClassAdd = connect( (state: State) => ({user: state.user})) (class extends React.Component<ClassAdd, {}> { state: Class;
(props: ClassAdd) { super(props); this.state = { section: undefined, semester: undefined, term: "", year: undefined, teacher: props.user, CRN: undefined, days: {sun: false, mon: false, tue: false, thu: false, wed: false, fri: false, sat: false, id: undefined}, syllabus: undefined, time: undefined, length: undefined } } render() { if (this.props.user.role === Roles.student || this.props.user.role === Roles.teacher) { return <div/> } return <tr className={"class-add" + (this.state.syllabus?" link":"")} > <td> <IntInput value={this.state.section} label="section" onChange={v => this.setState({section: v})} /> </td> <td> {this.state.term} <IntInput value={this.state.year} label="year" onChange={v => this.setState({year: v})} /> </td> <td> <IntInput value={this.state.CRN} label="CRN" onChange={v => this.setState({CRN: v})} /> </td> <td> <WeekView days={this.state.days}/> </td> <td> <Input value={this.state.CRN} label="Start" onChange={v => this.setState({start: new Date(v)})} /> </td> <td> {Math.floor(this.state.length/60)}:{("0" + this.state.length%60).slice(-2)} </td> </tr> } })
constructor
identifier_name
class-add.tsx
import { connect } from 'react-redux' import { State} from '../../control/reducers' import { User, Roles } from '../../control/user' import * as React from "react"; import {Course, Class} from "../../control/class" import {DropdownStringInput} from '../utilities/dropdown-string-input' import {Input} from '../utilities/input' import {IntInput} from '../utilities/int-input' import {DepartmentDropdown} from '../department-dropdown' import {WeekView} from "../utilities/week-view" export interface ClassAdd { user: User, course: Course } export const ClassAdd = connect( (state: State) => ({user: state.user})) (class extends React.Component<ClassAdd, {}> { state: Class; constructor(props: ClassAdd) { super(props); this.state = { section: undefined, semester: undefined, term: "", year: undefined, teacher: props.user, CRN: undefined, days: {sun: false, mon: false, tue: false, thu: false, wed: false, fri: false, sat: false, id: undefined}, syllabus: undefined, time: undefined, length: undefined } } render() { if (this.props.user.role === Roles.student || this.props.user.role === Roles.teacher)
return <tr className={"class-add" + (this.state.syllabus?" link":"")} > <td> <IntInput value={this.state.section} label="section" onChange={v => this.setState({section: v})} /> </td> <td> {this.state.term} <IntInput value={this.state.year} label="year" onChange={v => this.setState({year: v})} /> </td> <td> <IntInput value={this.state.CRN} label="CRN" onChange={v => this.setState({CRN: v})} /> </td> <td> <WeekView days={this.state.days}/> </td> <td> <Input value={this.state.CRN} label="Start" onChange={v => this.setState({start: new Date(v)})} /> </td> <td> {Math.floor(this.state.length/60)}:{("0" + this.state.length%60).slice(-2)} </td> </tr> } })
{ return <div/> }
conditional_block
mkfs.py
# -*- coding: utf8 -*- """ @todo: Update argument parser options """ # Imports. {{{1 import sys # Try to load the required modules from Python's standard library. try: import os import argparse from time import time import hashlib except ImportError as e: msg = "Error: Failed to load one of the required Python modules! (%s)\n" sys.stderr.write(msg % str(e)) sys.exit(1) from dedupsqlfs.log import logging from dedupsqlfs.lib import constants from dedupsqlfs.db import check_engines import dedupsqlfs def mkfs(options, compression_methods=None, hash_functions=None):
def main(): # {{{1 """ This function enables using mkfs.dedupsqlfs.py as a shell script that creates FUSE mount points. Execute "mkfs.dedupsqlfs -h" for a list of valid command line options. """ logger = logging.getLogger("mkfs.dedupsqlfs/main") logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stderr)) parser = argparse.ArgumentParser( prog="%s/%s mkfs/%s python/%s" % (dedupsqlfs.__name__, dedupsqlfs.__version__, dedupsqlfs.__fsversion__, sys.version.split()[0]), conflict_handler="resolve") # Register some custom command line options with the option parser. option_stored_in_db = " (this option is only useful when creating a new database, because your choice is stored in the database and can't be changed after that)" parser.add_argument('-h', '--help', action='help', help="show this help message followed by the command line options defined by the Python FUSE binding and exit") parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help="increase verbosity: 0 - error, 1 - warning, 2 - info, 3 - debug, 4 - verbose") parser.add_argument('--log-file', dest='log_file', help="specify log file location") parser.add_argument('--log-file-only', dest='log_file_only', action='store_true', help="Don't send log messages to stderr.") parser.add_argument('--data', dest='data', metavar='DIRECTORY', default="~/data", help="Specify the base location for the files in which metadata and blocks data is stored. Defaults to ~/data") parser.add_argument('--name', dest='name', metavar='DATABASE', default="dedupsqlfs", help="Specify the name for the database directory in which metadata and blocks data is stored. Defaults to dedupsqlfs") parser.add_argument('--temp', dest='temp', metavar='DIRECTORY', help="Specify the location for the files in which temporary data is stored. By default honour TMPDIR environment variable value.") parser.add_argument('-b', '--block-size', dest='block_size', metavar='BYTES', default=1024*128, type=int, help="Specify the maximum block size in bytes" + option_stored_in_db + ". Defaults to 128kB.") parser.add_argument('--memory-limit', dest='memory_limit', action='store_true', help="Use some lower values for less memory consumption.") parser.add_argument('--cpu-limit', dest='cpu_limit', metavar='NUMBER', default=0, type=int, help="Specify the maximum CPU count to use in multiprocess compression. Defaults to 0 (auto).") engines, msg = check_engines() if not engines: logger.error("No storage engines available! Please install sqlite or pymysql python module!") return 1 parser.add_argument('--storage-engine', dest='storage_engine', metavar='ENGINE', choices=engines, default=engines[0], help=msg) if "mysql" in engines: from dedupsqlfs.db.mysql import get_table_engines table_engines = get_table_engines() msg = "One of MySQL table engines: "+", ".join(table_engines)+". Default: %r. Aria and TokuDB engine can be used only with MariaDB or Percona server." % table_engines[0] parser.add_argument('--table-engine', dest='table_engine', metavar='ENGINE', choices=table_engines, default=table_engines[0], help=msg) parser.add_argument('--no-cache', dest='use_cache', action='store_false', help="Don't use cache in memory and delayed write to storage.") parser.add_argument('--no-transactions', dest='use_transactions', action='store_false', help="Don't use transactions when making multiple related changes, this might make the file system faster or slower (?).") parser.add_argument('--no-sync', dest='synchronous', action='store_false', help="Disable SQLite's normal synchronous behavior which guarantees that data is written to disk immediately, because it slows down the file system too much (this means you might lose data when the mount point isn't cleanly unmounted).") # Dynamically check for supported hashing algorithms. msg = "Specify the hashing algorithm that will be used to recognize duplicate data blocks: one of %s. Choose wisely - it can't be changed on the fly." hash_functions = list({}.fromkeys([h.lower() for h in hashlib.algorithms_available]).keys()) hash_functions.sort() work_hash_funcs = set(hash_functions) & constants.WANTED_HASH_FUCTIONS msg %= ', '.join('%r' % fun for fun in work_hash_funcs) defHash = 'md5' # Hope it will be there always. Stupid. msg += ". Defaults to %r." % defHash parser.add_argument('--hash', dest='hash_function', metavar='FUNCTION', choices=work_hash_funcs, default=defHash, help=msg) # Dynamically check for supported compression methods. compression_methods = [constants.COMPRESSION_TYPE_NONE] compression_methods_cmd = [constants.COMPRESSION_TYPE_NONE] for modname in constants.COMPRESSION_SUPPORTED: try: module = __import__(modname) if hasattr(module, 'compress') and hasattr(module, 'decompress'): compression_methods.append(modname) if modname not in constants.COMPRESSION_READONLY: compression_methods_cmd.append(modname) except ImportError: pass if len(compression_methods) > 1: compression_methods_cmd.append(constants.COMPRESSION_TYPE_BEST) compression_methods_cmd.append(constants.COMPRESSION_TYPE_CUSTOM) msg = "Enable compression of data blocks using one of the supported compression methods: one of %s" msg %= ', '.join('%r' % mth for mth in compression_methods_cmd) msg += ". Defaults to %r." % constants.COMPRESSION_TYPE_NONE msg += " You can use <method>:<level> syntax, <level> can be integer or value from --compression-level." if len(compression_methods_cmd) > 1: msg += " %r will try all compression methods and choose one with smaller result data." % constants.COMPRESSION_TYPE_BEST msg += " %r will try selected compression methods (--custom-compress) and choose one with smaller result data." % constants.COMPRESSION_TYPE_CUSTOM msg += "\nDefaults to %r." % constants.COMPRESSION_TYPE_NONE parser.add_argument('--compress', dest='compression', metavar='METHOD', action="append", default=[constants.COMPRESSION_TYPE_NONE], help=msg) msg = "Enable compression of data blocks using one or more of the supported compression methods: %s" msg %= ', '.join('%r' % mth for mth in compression_methods_cmd[:-2]) msg += ". To use two or more methods select this option in command line for each compression method." msg += " You can use <method>=<level> syntax, <level> can be integer or value from --compression-level." parser.add_argument('--force-compress', dest='compression_forced', action="store_true", help="Force compression even if resulting data is bigger than original.") parser.add_argument('--minimal-compress-size', dest='compression_minimal_size', metavar='BYTES', type=int, default=1024, help="Minimal block data size for compression. Defaults to 1024 bytes. Value -1 means auto - per method absolute minimum. Not compress if data size is less then BYTES long. If not forced to.") parser.add_argument('--minimal-compress-ratio', dest='compression_minimal_ratio', metavar='RATIO', type=float, default=0.05, help="Minimal data compression ratio. Defaults to 0.05 (5%%). Do not compress if ratio is less than RATIO. If not forced to.") levels = (constants.COMPRESSION_LEVEL_DEFAULT, constants.COMPRESSION_LEVEL_FAST, constants.COMPRESSION_LEVEL_NORM, constants.COMPRESSION_LEVEL_BEST) parser.add_argument('--compression-level', dest='compression_level', metavar="LEVEL", default=constants.COMPRESSION_LEVEL_DEFAULT, help="Compression level ratio: one of %s; or INT. Defaults to %r. Not all methods support this option." % ( ', '.join('%r' % lvl for lvl in levels), constants.COMPRESSION_LEVEL_DEFAULT )) # Dynamically check for profiling support. try: # Using __import__() here because of pyflakes. for p in 'cProfile', 'pstats': __import__(p) parser.add_argument('--profile', action='store_true', default=False, help="Use the Python modules cProfile and pstats to create a profile of time spent in various function calls and print out a table of the slowest functions at exit (of course this slows everything down but it can nevertheless give a good indication of the hot spots).") except ImportError: logger.warning("No profiling support available, --profile option disabled.") logger.warning("If you're on Ubuntu try 'sudo apt-get install python-profiler'.") args = parser.parse_args() if args.profile: sys.stderr.write("Enabling profiling..\n") import cProfile, pstats profile = '.dedupsqlfs.cprofile-%i' % time() profiler = cProfile.Profile() result = profiler.runcall(mkfs, args, compression_methods, hash_functions) profiler.dump_stats(profile) sys.stderr.write("\n Profiling statistics:\n\n") s = pstats.Stats(profile) s.sort_stats('calls').print_stats(0.1) s.sort_stats('cumtime').print_stats(0.1) s.sort_stats('tottime').print_stats(0.1) os.unlink(profile) else: result = mkfs(args, compression_methods, hash_functions) return result # vim: ts=4 sw=4 et
from dedupsqlfs.fuse.dedupfs import DedupFS from dedupsqlfs.fuse.operations import DedupOperations ops = None ret = 0 try: ops = DedupOperations() _fuse = DedupFS( ops, None, options, fsname="dedupsqlfs", allow_root=True) if not _fuse.checkIfLocked(): _fuse.saveCompressionMethods(compression_methods) for modname in compression_methods: _fuse.appendCompression(modname) _fuse.setOption("gc_umount_enabled", False) _fuse.setOption("gc_vacuum_enabled", False) _fuse.setOption("gc_enabled", False) _fuse.operations.init() _fuse.operations.destroy() except Exception: import traceback print(traceback.format_exc()) ret = -1 if ops: ops.getManager().close() return ret
identifier_body
mkfs.py
# -*- coding: utf8 -*- """ @todo: Update argument parser options """ # Imports. {{{1 import sys # Try to load the required modules from Python's standard library. try: import os import argparse from time import time import hashlib except ImportError as e: msg = "Error: Failed to load one of the required Python modules! (%s)\n" sys.stderr.write(msg % str(e)) sys.exit(1) from dedupsqlfs.log import logging from dedupsqlfs.lib import constants from dedupsqlfs.db import check_engines import dedupsqlfs def
(options, compression_methods=None, hash_functions=None): from dedupsqlfs.fuse.dedupfs import DedupFS from dedupsqlfs.fuse.operations import DedupOperations ops = None ret = 0 try: ops = DedupOperations() _fuse = DedupFS( ops, None, options, fsname="dedupsqlfs", allow_root=True) if not _fuse.checkIfLocked(): _fuse.saveCompressionMethods(compression_methods) for modname in compression_methods: _fuse.appendCompression(modname) _fuse.setOption("gc_umount_enabled", False) _fuse.setOption("gc_vacuum_enabled", False) _fuse.setOption("gc_enabled", False) _fuse.operations.init() _fuse.operations.destroy() except Exception: import traceback print(traceback.format_exc()) ret = -1 if ops: ops.getManager().close() return ret def main(): # {{{1 """ This function enables using mkfs.dedupsqlfs.py as a shell script that creates FUSE mount points. Execute "mkfs.dedupsqlfs -h" for a list of valid command line options. """ logger = logging.getLogger("mkfs.dedupsqlfs/main") logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stderr)) parser = argparse.ArgumentParser( prog="%s/%s mkfs/%s python/%s" % (dedupsqlfs.__name__, dedupsqlfs.__version__, dedupsqlfs.__fsversion__, sys.version.split()[0]), conflict_handler="resolve") # Register some custom command line options with the option parser. option_stored_in_db = " (this option is only useful when creating a new database, because your choice is stored in the database and can't be changed after that)" parser.add_argument('-h', '--help', action='help', help="show this help message followed by the command line options defined by the Python FUSE binding and exit") parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help="increase verbosity: 0 - error, 1 - warning, 2 - info, 3 - debug, 4 - verbose") parser.add_argument('--log-file', dest='log_file', help="specify log file location") parser.add_argument('--log-file-only', dest='log_file_only', action='store_true', help="Don't send log messages to stderr.") parser.add_argument('--data', dest='data', metavar='DIRECTORY', default="~/data", help="Specify the base location for the files in which metadata and blocks data is stored. Defaults to ~/data") parser.add_argument('--name', dest='name', metavar='DATABASE', default="dedupsqlfs", help="Specify the name for the database directory in which metadata and blocks data is stored. Defaults to dedupsqlfs") parser.add_argument('--temp', dest='temp', metavar='DIRECTORY', help="Specify the location for the files in which temporary data is stored. By default honour TMPDIR environment variable value.") parser.add_argument('-b', '--block-size', dest='block_size', metavar='BYTES', default=1024*128, type=int, help="Specify the maximum block size in bytes" + option_stored_in_db + ". Defaults to 128kB.") parser.add_argument('--memory-limit', dest='memory_limit', action='store_true', help="Use some lower values for less memory consumption.") parser.add_argument('--cpu-limit', dest='cpu_limit', metavar='NUMBER', default=0, type=int, help="Specify the maximum CPU count to use in multiprocess compression. Defaults to 0 (auto).") engines, msg = check_engines() if not engines: logger.error("No storage engines available! Please install sqlite or pymysql python module!") return 1 parser.add_argument('--storage-engine', dest='storage_engine', metavar='ENGINE', choices=engines, default=engines[0], help=msg) if "mysql" in engines: from dedupsqlfs.db.mysql import get_table_engines table_engines = get_table_engines() msg = "One of MySQL table engines: "+", ".join(table_engines)+". Default: %r. Aria and TokuDB engine can be used only with MariaDB or Percona server." % table_engines[0] parser.add_argument('--table-engine', dest='table_engine', metavar='ENGINE', choices=table_engines, default=table_engines[0], help=msg) parser.add_argument('--no-cache', dest='use_cache', action='store_false', help="Don't use cache in memory and delayed write to storage.") parser.add_argument('--no-transactions', dest='use_transactions', action='store_false', help="Don't use transactions when making multiple related changes, this might make the file system faster or slower (?).") parser.add_argument('--no-sync', dest='synchronous', action='store_false', help="Disable SQLite's normal synchronous behavior which guarantees that data is written to disk immediately, because it slows down the file system too much (this means you might lose data when the mount point isn't cleanly unmounted).") # Dynamically check for supported hashing algorithms. msg = "Specify the hashing algorithm that will be used to recognize duplicate data blocks: one of %s. Choose wisely - it can't be changed on the fly." hash_functions = list({}.fromkeys([h.lower() for h in hashlib.algorithms_available]).keys()) hash_functions.sort() work_hash_funcs = set(hash_functions) & constants.WANTED_HASH_FUCTIONS msg %= ', '.join('%r' % fun for fun in work_hash_funcs) defHash = 'md5' # Hope it will be there always. Stupid. msg += ". Defaults to %r." % defHash parser.add_argument('--hash', dest='hash_function', metavar='FUNCTION', choices=work_hash_funcs, default=defHash, help=msg) # Dynamically check for supported compression methods. compression_methods = [constants.COMPRESSION_TYPE_NONE] compression_methods_cmd = [constants.COMPRESSION_TYPE_NONE] for modname in constants.COMPRESSION_SUPPORTED: try: module = __import__(modname) if hasattr(module, 'compress') and hasattr(module, 'decompress'): compression_methods.append(modname) if modname not in constants.COMPRESSION_READONLY: compression_methods_cmd.append(modname) except ImportError: pass if len(compression_methods) > 1: compression_methods_cmd.append(constants.COMPRESSION_TYPE_BEST) compression_methods_cmd.append(constants.COMPRESSION_TYPE_CUSTOM) msg = "Enable compression of data blocks using one of the supported compression methods: one of %s" msg %= ', '.join('%r' % mth for mth in compression_methods_cmd) msg += ". Defaults to %r." % constants.COMPRESSION_TYPE_NONE msg += " You can use <method>:<level> syntax, <level> can be integer or value from --compression-level." if len(compression_methods_cmd) > 1: msg += " %r will try all compression methods and choose one with smaller result data." % constants.COMPRESSION_TYPE_BEST msg += " %r will try selected compression methods (--custom-compress) and choose one with smaller result data." % constants.COMPRESSION_TYPE_CUSTOM msg += "\nDefaults to %r." % constants.COMPRESSION_TYPE_NONE parser.add_argument('--compress', dest='compression', metavar='METHOD', action="append", default=[constants.COMPRESSION_TYPE_NONE], help=msg) msg = "Enable compression of data blocks using one or more of the supported compression methods: %s" msg %= ', '.join('%r' % mth for mth in compression_methods_cmd[:-2]) msg += ". To use two or more methods select this option in command line for each compression method." msg += " You can use <method>=<level> syntax, <level> can be integer or value from --compression-level." parser.add_argument('--force-compress', dest='compression_forced', action="store_true", help="Force compression even if resulting data is bigger than original.") parser.add_argument('--minimal-compress-size', dest='compression_minimal_size', metavar='BYTES', type=int, default=1024, help="Minimal block data size for compression. Defaults to 1024 bytes. Value -1 means auto - per method absolute minimum. Not compress if data size is less then BYTES long. If not forced to.") parser.add_argument('--minimal-compress-ratio', dest='compression_minimal_ratio', metavar='RATIO', type=float, default=0.05, help="Minimal data compression ratio. Defaults to 0.05 (5%%). Do not compress if ratio is less than RATIO. If not forced to.") levels = (constants.COMPRESSION_LEVEL_DEFAULT, constants.COMPRESSION_LEVEL_FAST, constants.COMPRESSION_LEVEL_NORM, constants.COMPRESSION_LEVEL_BEST) parser.add_argument('--compression-level', dest='compression_level', metavar="LEVEL", default=constants.COMPRESSION_LEVEL_DEFAULT, help="Compression level ratio: one of %s; or INT. Defaults to %r. Not all methods support this option." % ( ', '.join('%r' % lvl for lvl in levels), constants.COMPRESSION_LEVEL_DEFAULT )) # Dynamically check for profiling support. try: # Using __import__() here because of pyflakes. for p in 'cProfile', 'pstats': __import__(p) parser.add_argument('--profile', action='store_true', default=False, help="Use the Python modules cProfile and pstats to create a profile of time spent in various function calls and print out a table of the slowest functions at exit (of course this slows everything down but it can nevertheless give a good indication of the hot spots).") except ImportError: logger.warning("No profiling support available, --profile option disabled.") logger.warning("If you're on Ubuntu try 'sudo apt-get install python-profiler'.") args = parser.parse_args() if args.profile: sys.stderr.write("Enabling profiling..\n") import cProfile, pstats profile = '.dedupsqlfs.cprofile-%i' % time() profiler = cProfile.Profile() result = profiler.runcall(mkfs, args, compression_methods, hash_functions) profiler.dump_stats(profile) sys.stderr.write("\n Profiling statistics:\n\n") s = pstats.Stats(profile) s.sort_stats('calls').print_stats(0.1) s.sort_stats('cumtime').print_stats(0.1) s.sort_stats('tottime').print_stats(0.1) os.unlink(profile) else: result = mkfs(args, compression_methods, hash_functions) return result # vim: ts=4 sw=4 et
mkfs
identifier_name
mkfs.py
# -*- coding: utf8 -*- """ @todo: Update argument parser options """ # Imports. {{{1 import sys # Try to load the required modules from Python's standard library. try: import os import argparse from time import time import hashlib except ImportError as e: msg = "Error: Failed to load one of the required Python modules! (%s)\n" sys.stderr.write(msg % str(e)) sys.exit(1) from dedupsqlfs.log import logging from dedupsqlfs.lib import constants from dedupsqlfs.db import check_engines import dedupsqlfs def mkfs(options, compression_methods=None, hash_functions=None): from dedupsqlfs.fuse.dedupfs import DedupFS from dedupsqlfs.fuse.operations import DedupOperations ops = None ret = 0 try: ops = DedupOperations() _fuse = DedupFS( ops, None, options, fsname="dedupsqlfs", allow_root=True) if not _fuse.checkIfLocked(): _fuse.saveCompressionMethods(compression_methods) for modname in compression_methods: _fuse.appendCompression(modname) _fuse.setOption("gc_umount_enabled", False) _fuse.setOption("gc_vacuum_enabled", False) _fuse.setOption("gc_enabled", False) _fuse.operations.init() _fuse.operations.destroy() except Exception: import traceback print(traceback.format_exc()) ret = -1 if ops: ops.getManager().close() return ret def main(): # {{{1 """ This function enables using mkfs.dedupsqlfs.py as a shell script that creates FUSE mount points. Execute "mkfs.dedupsqlfs -h" for a list of valid command line options. """ logger = logging.getLogger("mkfs.dedupsqlfs/main") logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stderr)) parser = argparse.ArgumentParser( prog="%s/%s mkfs/%s python/%s" % (dedupsqlfs.__name__, dedupsqlfs.__version__, dedupsqlfs.__fsversion__, sys.version.split()[0]), conflict_handler="resolve") # Register some custom command line options with the option parser. option_stored_in_db = " (this option is only useful when creating a new database, because your choice is stored in the database and can't be changed after that)" parser.add_argument('-h', '--help', action='help', help="show this help message followed by the command line options defined by the Python FUSE binding and exit") parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help="increase verbosity: 0 - error, 1 - warning, 2 - info, 3 - debug, 4 - verbose") parser.add_argument('--log-file', dest='log_file', help="specify log file location") parser.add_argument('--log-file-only', dest='log_file_only', action='store_true', help="Don't send log messages to stderr.") parser.add_argument('--data', dest='data', metavar='DIRECTORY', default="~/data", help="Specify the base location for the files in which metadata and blocks data is stored. Defaults to ~/data") parser.add_argument('--name', dest='name', metavar='DATABASE', default="dedupsqlfs", help="Specify the name for the database directory in which metadata and blocks data is stored. Defaults to dedupsqlfs") parser.add_argument('--temp', dest='temp', metavar='DIRECTORY', help="Specify the location for the files in which temporary data is stored. By default honour TMPDIR environment variable value.") parser.add_argument('-b', '--block-size', dest='block_size', metavar='BYTES', default=1024*128, type=int, help="Specify the maximum block size in bytes" + option_stored_in_db + ". Defaults to 128kB.") parser.add_argument('--memory-limit', dest='memory_limit', action='store_true', help="Use some lower values for less memory consumption.") parser.add_argument('--cpu-limit', dest='cpu_limit', metavar='NUMBER', default=0, type=int, help="Specify the maximum CPU count to use in multiprocess compression. Defaults to 0 (auto).") engines, msg = check_engines() if not engines: logger.error("No storage engines available! Please install sqlite or pymysql python module!") return 1 parser.add_argument('--storage-engine', dest='storage_engine', metavar='ENGINE', choices=engines, default=engines[0], help=msg) if "mysql" in engines: from dedupsqlfs.db.mysql import get_table_engines table_engines = get_table_engines() msg = "One of MySQL table engines: "+", ".join(table_engines)+". Default: %r. Aria and TokuDB engine can be used only with MariaDB or Percona server." % table_engines[0] parser.add_argument('--table-engine', dest='table_engine', metavar='ENGINE', choices=table_engines, default=table_engines[0], help=msg) parser.add_argument('--no-cache', dest='use_cache', action='store_false', help="Don't use cache in memory and delayed write to storage.") parser.add_argument('--no-transactions', dest='use_transactions', action='store_false', help="Don't use transactions when making multiple related changes, this might make the file system faster or slower (?).") parser.add_argument('--no-sync', dest='synchronous', action='store_false', help="Disable SQLite's normal synchronous behavior which guarantees that data is written to disk immediately, because it slows down the file system too much (this means you might lose data when the mount point isn't cleanly unmounted).") # Dynamically check for supported hashing algorithms. msg = "Specify the hashing algorithm that will be used to recognize duplicate data blocks: one of %s. Choose wisely - it can't be changed on the fly." hash_functions = list({}.fromkeys([h.lower() for h in hashlib.algorithms_available]).keys()) hash_functions.sort() work_hash_funcs = set(hash_functions) & constants.WANTED_HASH_FUCTIONS msg %= ', '.join('%r' % fun for fun in work_hash_funcs) defHash = 'md5' # Hope it will be there always. Stupid. msg += ". Defaults to %r." % defHash parser.add_argument('--hash', dest='hash_function', metavar='FUNCTION', choices=work_hash_funcs, default=defHash, help=msg) # Dynamically check for supported compression methods. compression_methods = [constants.COMPRESSION_TYPE_NONE] compression_methods_cmd = [constants.COMPRESSION_TYPE_NONE] for modname in constants.COMPRESSION_SUPPORTED: try: module = __import__(modname) if hasattr(module, 'compress') and hasattr(module, 'decompress'): compression_methods.append(modname) if modname not in constants.COMPRESSION_READONLY: compression_methods_cmd.append(modname) except ImportError: pass if len(compression_methods) > 1: compression_methods_cmd.append(constants.COMPRESSION_TYPE_BEST) compression_methods_cmd.append(constants.COMPRESSION_TYPE_CUSTOM) msg = "Enable compression of data blocks using one of the supported compression methods: one of %s" msg %= ', '.join('%r' % mth for mth in compression_methods_cmd) msg += ". Defaults to %r." % constants.COMPRESSION_TYPE_NONE msg += " You can use <method>:<level> syntax, <level> can be integer or value from --compression-level." if len(compression_methods_cmd) > 1: msg += " %r will try all compression methods and choose one with smaller result data." % constants.COMPRESSION_TYPE_BEST msg += " %r will try selected compression methods (--custom-compress) and choose one with smaller result data." % constants.COMPRESSION_TYPE_CUSTOM msg += "\nDefaults to %r." % constants.COMPRESSION_TYPE_NONE parser.add_argument('--compress', dest='compression', metavar='METHOD', action="append", default=[constants.COMPRESSION_TYPE_NONE], help=msg) msg = "Enable compression of data blocks using one or more of the supported compression methods: %s" msg %= ', '.join('%r' % mth for mth in compression_methods_cmd[:-2]) msg += ". To use two or more methods select this option in command line for each compression method." msg += " You can use <method>=<level> syntax, <level> can be integer or value from --compression-level." parser.add_argument('--force-compress', dest='compression_forced', action="store_true", help="Force compression even if resulting data is bigger than original.") parser.add_argument('--minimal-compress-size', dest='compression_minimal_size', metavar='BYTES', type=int, default=1024, help="Minimal block data size for compression. Defaults to 1024 bytes. Value -1 means auto - per method absolute minimum. Not compress if data size is less then BYTES long. If not forced to.") parser.add_argument('--minimal-compress-ratio', dest='compression_minimal_ratio', metavar='RATIO', type=float, default=0.05, help="Minimal data compression ratio. Defaults to 0.05 (5%%). Do not compress if ratio is less than RATIO. If not forced to.") levels = (constants.COMPRESSION_LEVEL_DEFAULT, constants.COMPRESSION_LEVEL_FAST, constants.COMPRESSION_LEVEL_NORM, constants.COMPRESSION_LEVEL_BEST) parser.add_argument('--compression-level', dest='compression_level', metavar="LEVEL", default=constants.COMPRESSION_LEVEL_DEFAULT, help="Compression level ratio: one of %s; or INT. Defaults to %r. Not all methods support this option." % ( ', '.join('%r' % lvl for lvl in levels), constants.COMPRESSION_LEVEL_DEFAULT )) # Dynamically check for profiling support. try: # Using __import__() here because of pyflakes. for p in 'cProfile', 'pstats': __import__(p) parser.add_argument('--profile', action='store_true', default=False, help="Use the Python modules cProfile and pstats to create a profile of time spent in various function calls and print out a table of the slowest functions at exit (of course this slows everything down but it can nevertheless give a good indication of the hot spots).") except ImportError: logger.warning("No profiling support available, --profile option disabled.") logger.warning("If you're on Ubuntu try 'sudo apt-get install python-profiler'.") args = parser.parse_args() if args.profile: sys.stderr.write("Enabling profiling..\n") import cProfile, pstats
result = profiler.runcall(mkfs, args, compression_methods, hash_functions) profiler.dump_stats(profile) sys.stderr.write("\n Profiling statistics:\n\n") s = pstats.Stats(profile) s.sort_stats('calls').print_stats(0.1) s.sort_stats('cumtime').print_stats(0.1) s.sort_stats('tottime').print_stats(0.1) os.unlink(profile) else: result = mkfs(args, compression_methods, hash_functions) return result # vim: ts=4 sw=4 et
profile = '.dedupsqlfs.cprofile-%i' % time() profiler = cProfile.Profile()
random_line_split
mkfs.py
# -*- coding: utf8 -*- """ @todo: Update argument parser options """ # Imports. {{{1 import sys # Try to load the required modules from Python's standard library. try: import os import argparse from time import time import hashlib except ImportError as e: msg = "Error: Failed to load one of the required Python modules! (%s)\n" sys.stderr.write(msg % str(e)) sys.exit(1) from dedupsqlfs.log import logging from dedupsqlfs.lib import constants from dedupsqlfs.db import check_engines import dedupsqlfs def mkfs(options, compression_methods=None, hash_functions=None): from dedupsqlfs.fuse.dedupfs import DedupFS from dedupsqlfs.fuse.operations import DedupOperations ops = None ret = 0 try: ops = DedupOperations() _fuse = DedupFS( ops, None, options, fsname="dedupsqlfs", allow_root=True) if not _fuse.checkIfLocked(): _fuse.saveCompressionMethods(compression_methods) for modname in compression_methods: _fuse.appendCompression(modname) _fuse.setOption("gc_umount_enabled", False) _fuse.setOption("gc_vacuum_enabled", False) _fuse.setOption("gc_enabled", False) _fuse.operations.init() _fuse.operations.destroy() except Exception: import traceback print(traceback.format_exc()) ret = -1 if ops: ops.getManager().close() return ret def main(): # {{{1 """ This function enables using mkfs.dedupsqlfs.py as a shell script that creates FUSE mount points. Execute "mkfs.dedupsqlfs -h" for a list of valid command line options. """ logger = logging.getLogger("mkfs.dedupsqlfs/main") logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stderr)) parser = argparse.ArgumentParser( prog="%s/%s mkfs/%s python/%s" % (dedupsqlfs.__name__, dedupsqlfs.__version__, dedupsqlfs.__fsversion__, sys.version.split()[0]), conflict_handler="resolve") # Register some custom command line options with the option parser. option_stored_in_db = " (this option is only useful when creating a new database, because your choice is stored in the database and can't be changed after that)" parser.add_argument('-h', '--help', action='help', help="show this help message followed by the command line options defined by the Python FUSE binding and exit") parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help="increase verbosity: 0 - error, 1 - warning, 2 - info, 3 - debug, 4 - verbose") parser.add_argument('--log-file', dest='log_file', help="specify log file location") parser.add_argument('--log-file-only', dest='log_file_only', action='store_true', help="Don't send log messages to stderr.") parser.add_argument('--data', dest='data', metavar='DIRECTORY', default="~/data", help="Specify the base location for the files in which metadata and blocks data is stored. Defaults to ~/data") parser.add_argument('--name', dest='name', metavar='DATABASE', default="dedupsqlfs", help="Specify the name for the database directory in which metadata and blocks data is stored. Defaults to dedupsqlfs") parser.add_argument('--temp', dest='temp', metavar='DIRECTORY', help="Specify the location for the files in which temporary data is stored. By default honour TMPDIR environment variable value.") parser.add_argument('-b', '--block-size', dest='block_size', metavar='BYTES', default=1024*128, type=int, help="Specify the maximum block size in bytes" + option_stored_in_db + ". Defaults to 128kB.") parser.add_argument('--memory-limit', dest='memory_limit', action='store_true', help="Use some lower values for less memory consumption.") parser.add_argument('--cpu-limit', dest='cpu_limit', metavar='NUMBER', default=0, type=int, help="Specify the maximum CPU count to use in multiprocess compression. Defaults to 0 (auto).") engines, msg = check_engines() if not engines: logger.error("No storage engines available! Please install sqlite or pymysql python module!") return 1 parser.add_argument('--storage-engine', dest='storage_engine', metavar='ENGINE', choices=engines, default=engines[0], help=msg) if "mysql" in engines: from dedupsqlfs.db.mysql import get_table_engines table_engines = get_table_engines() msg = "One of MySQL table engines: "+", ".join(table_engines)+". Default: %r. Aria and TokuDB engine can be used only with MariaDB or Percona server." % table_engines[0] parser.add_argument('--table-engine', dest='table_engine', metavar='ENGINE', choices=table_engines, default=table_engines[0], help=msg) parser.add_argument('--no-cache', dest='use_cache', action='store_false', help="Don't use cache in memory and delayed write to storage.") parser.add_argument('--no-transactions', dest='use_transactions', action='store_false', help="Don't use transactions when making multiple related changes, this might make the file system faster or slower (?).") parser.add_argument('--no-sync', dest='synchronous', action='store_false', help="Disable SQLite's normal synchronous behavior which guarantees that data is written to disk immediately, because it slows down the file system too much (this means you might lose data when the mount point isn't cleanly unmounted).") # Dynamically check for supported hashing algorithms. msg = "Specify the hashing algorithm that will be used to recognize duplicate data blocks: one of %s. Choose wisely - it can't be changed on the fly." hash_functions = list({}.fromkeys([h.lower() for h in hashlib.algorithms_available]).keys()) hash_functions.sort() work_hash_funcs = set(hash_functions) & constants.WANTED_HASH_FUCTIONS msg %= ', '.join('%r' % fun for fun in work_hash_funcs) defHash = 'md5' # Hope it will be there always. Stupid. msg += ". Defaults to %r." % defHash parser.add_argument('--hash', dest='hash_function', metavar='FUNCTION', choices=work_hash_funcs, default=defHash, help=msg) # Dynamically check for supported compression methods. compression_methods = [constants.COMPRESSION_TYPE_NONE] compression_methods_cmd = [constants.COMPRESSION_TYPE_NONE] for modname in constants.COMPRESSION_SUPPORTED: try: module = __import__(modname) if hasattr(module, 'compress') and hasattr(module, 'decompress'): compression_methods.append(modname) if modname not in constants.COMPRESSION_READONLY: compression_methods_cmd.append(modname) except ImportError: pass if len(compression_methods) > 1: compression_methods_cmd.append(constants.COMPRESSION_TYPE_BEST) compression_methods_cmd.append(constants.COMPRESSION_TYPE_CUSTOM) msg = "Enable compression of data blocks using one of the supported compression methods: one of %s" msg %= ', '.join('%r' % mth for mth in compression_methods_cmd) msg += ". Defaults to %r." % constants.COMPRESSION_TYPE_NONE msg += " You can use <method>:<level> syntax, <level> can be integer or value from --compression-level." if len(compression_methods_cmd) > 1: msg += " %r will try all compression methods and choose one with smaller result data." % constants.COMPRESSION_TYPE_BEST msg += " %r will try selected compression methods (--custom-compress) and choose one with smaller result data." % constants.COMPRESSION_TYPE_CUSTOM msg += "\nDefaults to %r." % constants.COMPRESSION_TYPE_NONE parser.add_argument('--compress', dest='compression', metavar='METHOD', action="append", default=[constants.COMPRESSION_TYPE_NONE], help=msg) msg = "Enable compression of data blocks using one or more of the supported compression methods: %s" msg %= ', '.join('%r' % mth for mth in compression_methods_cmd[:-2]) msg += ". To use two or more methods select this option in command line for each compression method." msg += " You can use <method>=<level> syntax, <level> can be integer or value from --compression-level." parser.add_argument('--force-compress', dest='compression_forced', action="store_true", help="Force compression even if resulting data is bigger than original.") parser.add_argument('--minimal-compress-size', dest='compression_minimal_size', metavar='BYTES', type=int, default=1024, help="Minimal block data size for compression. Defaults to 1024 bytes. Value -1 means auto - per method absolute minimum. Not compress if data size is less then BYTES long. If not forced to.") parser.add_argument('--minimal-compress-ratio', dest='compression_minimal_ratio', metavar='RATIO', type=float, default=0.05, help="Minimal data compression ratio. Defaults to 0.05 (5%%). Do not compress if ratio is less than RATIO. If not forced to.") levels = (constants.COMPRESSION_LEVEL_DEFAULT, constants.COMPRESSION_LEVEL_FAST, constants.COMPRESSION_LEVEL_NORM, constants.COMPRESSION_LEVEL_BEST) parser.add_argument('--compression-level', dest='compression_level', metavar="LEVEL", default=constants.COMPRESSION_LEVEL_DEFAULT, help="Compression level ratio: one of %s; or INT. Defaults to %r. Not all methods support this option." % ( ', '.join('%r' % lvl for lvl in levels), constants.COMPRESSION_LEVEL_DEFAULT )) # Dynamically check for profiling support. try: # Using __import__() here because of pyflakes. for p in 'cProfile', 'pstats': __import__(p) parser.add_argument('--profile', action='store_true', default=False, help="Use the Python modules cProfile and pstats to create a profile of time spent in various function calls and print out a table of the slowest functions at exit (of course this slows everything down but it can nevertheless give a good indication of the hot spots).") except ImportError: logger.warning("No profiling support available, --profile option disabled.") logger.warning("If you're on Ubuntu try 'sudo apt-get install python-profiler'.") args = parser.parse_args() if args.profile: sys.stderr.write("Enabling profiling..\n") import cProfile, pstats profile = '.dedupsqlfs.cprofile-%i' % time() profiler = cProfile.Profile() result = profiler.runcall(mkfs, args, compression_methods, hash_functions) profiler.dump_stats(profile) sys.stderr.write("\n Profiling statistics:\n\n") s = pstats.Stats(profile) s.sort_stats('calls').print_stats(0.1) s.sort_stats('cumtime').print_stats(0.1) s.sort_stats('tottime').print_stats(0.1) os.unlink(profile) else:
return result # vim: ts=4 sw=4 et
result = mkfs(args, compression_methods, hash_functions)
conditional_block
gonzo.py
# GONZO: A PYTHON SCRIPT TO RECORD PHP ERRORS INTO MONGO # Michael Vendivel - vendivel@gmail.com import subprocess import datetime from pymongo import MongoClient # where's the log file filename = '/path/to/php/logs.log' # set up mongo client client = MongoClient('mongo.server.address', 27017) # which DB db = client.logs # which Collection php_logs = db.php_logs # open a subprocess to tail (and follow) the log file f = subprocess.Popen(['tail','-f',filename],\ stdout=subprocess.PIPE,stderr=subprocess.PIPE) # continue to read the file and record lines into mongo while True: # read line by line
line = f.stdout.readline() # compose the document to be inserted post = {"line": line, "created": datetime.datetime.utcnow() } # insert the document into the Collection post_id = php_logs.insert(post) # output the line for visual debugging (optional) print line
conditional_block
gonzo.py
# GONZO: A PYTHON SCRIPT TO RECORD PHP ERRORS INTO MONGO # Michael Vendivel - vendivel@gmail.com import subprocess import datetime from pymongo import MongoClient # where's the log file filename = '/path/to/php/logs.log' # set up mongo client client = MongoClient('mongo.server.address', 27017) # which DB db = client.logs # which Collection php_logs = db.php_logs # open a subprocess to tail (and follow) the log file f = subprocess.Popen(['tail','-f',filename],\ stdout=subprocess.PIPE,stderr=subprocess.PIPE) # continue to read the file and record lines into mongo while True:
# read line by line line = f.stdout.readline() # compose the document to be inserted post = {"line": line, "created": datetime.datetime.utcnow() } # insert the document into the Collection post_id = php_logs.insert(post) # output the line for visual debugging (optional) print line
random_line_split
storage.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/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{JSRef, Temporary, Rootable, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::event::{Event, EventHelpers, EventBubbles, EventCancelable}; use dom::eventtarget::{EventTarget}; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; use dom::window::WindowHelpers; use util::str::DOMString; use page::IterablePage; use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType}; use std::sync::mpsc::channel; use url::Url; use script_task::{ScriptTask, ScriptMsg, MainThreadRunnable}; use collections::borrow::ToOwned; #[dom_struct] pub struct Storage { reflector_: Reflector, global: GlobalField, storage_type: StorageType } impl Storage { fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage { Storage { reflector_: Reflector::new(), global: GlobalField::from_rooted(global), storage_type: storage_type } } pub fn new(global: &GlobalRef, storage_type: StorageType) -> Temporary<Storage> { reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap) } fn get_url(&self) -> Url { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() } fn get_storage_task(&self) -> StorageTask { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.as_window().storage_task() } } impl<'a> StorageMethods for JSRef<'a, Storage> { fn Length(self) -> u32 { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); receiver.recv().unwrap() as u32 } fn Key(self, index: u32) -> Option<DOMString> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); receiver.recv().unwrap() } fn GetItem(self, name: DOMString) -> Option<DOMString> { let (sender, receiver) = channel(); let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name); self.get_storage_task().send(msg).unwrap(); receiver.recv().unwrap() } fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option<DOMString> { let item = self.GetItem(name); *found = item.is_some(); item } fn SetItem(self, name: DOMString, value: DOMString) { let (sender, receiver) = channel(); let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); self.get_storage_task().send(msg).unwrap(); let (changed, old_value) = receiver.recv().unwrap(); if changed { self.broadcast_change_notification(Some(name), old_value, Some(value)); } } fn NamedSetter(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedCreator(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn RemoveItem(self, name: DOMString) { let (sender, receiver) = channel(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_task().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap() { self.broadcast_change_notification(Some(name), Some(old_value), None); } } fn NamedDeleter(self, name: DOMString) { self.RemoveItem(name); } fn Clear(self) { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } } } trait PrivateStorageHelpers { fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>); } impl<'a> PrivateStorageHelpers for JSRef<'a, Storage> { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>){ let global_root = self.global.root(); let global_ref = global_root.r(); let script_chan = global_ref.script_chan(); let trusted_storage = Trusted::new(global_ref.get_cx(), self, script_chan.clone()); script_chan.send(ScriptMsg::MainThreadRunnableMsg( box StorageEventRunnable::new(trusted_storage, key, old_value, new_value))).unwrap(); } } pub struct StorageEventRunnable { element: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString> }
new_value: Option<DOMString>) -> StorageEventRunnable { StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value } } } impl MainThreadRunnable for StorageEventRunnable { fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) { let this = *self; let storage_root = this.element.to_temporary().root(); let storage = storage_root.r(); let global_root = storage.global.root(); let global_ref = global_root.r(); let ev_window = global_ref.as_window(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( global_ref, "storage".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key, this.old_value, this.new_value, ev_url.to_string(), Some(storage) ).root(); let event: JSRef<Event> = EventCast::from_ref(storage_event.r()); let root_page = script_task.root_page(); for it_page in root_page.iter() { let it_window_root = it_page.window().root(); let it_window = it_window_root.r(); assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. if ev_window.pipeline() != it_window.pipeline() { let target: JSRef<EventTarget> = EventTargetCast::from_ref(it_window); event.fire(target); } } } }
impl StorageEventRunnable { fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>,
random_line_split
storage.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/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{JSRef, Temporary, Rootable, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::event::{Event, EventHelpers, EventBubbles, EventCancelable}; use dom::eventtarget::{EventTarget}; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; use dom::window::WindowHelpers; use util::str::DOMString; use page::IterablePage; use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType}; use std::sync::mpsc::channel; use url::Url; use script_task::{ScriptTask, ScriptMsg, MainThreadRunnable}; use collections::borrow::ToOwned; #[dom_struct] pub struct Storage { reflector_: Reflector, global: GlobalField, storage_type: StorageType } impl Storage { fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage { Storage { reflector_: Reflector::new(), global: GlobalField::from_rooted(global), storage_type: storage_type } } pub fn new(global: &GlobalRef, storage_type: StorageType) -> Temporary<Storage> { reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap) } fn get_url(&self) -> Url { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() } fn get_storage_task(&self) -> StorageTask { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.as_window().storage_task() } } impl<'a> StorageMethods for JSRef<'a, Storage> { fn Length(self) -> u32
fn Key(self, index: u32) -> Option<DOMString> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); receiver.recv().unwrap() } fn GetItem(self, name: DOMString) -> Option<DOMString> { let (sender, receiver) = channel(); let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name); self.get_storage_task().send(msg).unwrap(); receiver.recv().unwrap() } fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option<DOMString> { let item = self.GetItem(name); *found = item.is_some(); item } fn SetItem(self, name: DOMString, value: DOMString) { let (sender, receiver) = channel(); let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); self.get_storage_task().send(msg).unwrap(); let (changed, old_value) = receiver.recv().unwrap(); if changed { self.broadcast_change_notification(Some(name), old_value, Some(value)); } } fn NamedSetter(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedCreator(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn RemoveItem(self, name: DOMString) { let (sender, receiver) = channel(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_task().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap() { self.broadcast_change_notification(Some(name), Some(old_value), None); } } fn NamedDeleter(self, name: DOMString) { self.RemoveItem(name); } fn Clear(self) { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } } } trait PrivateStorageHelpers { fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>); } impl<'a> PrivateStorageHelpers for JSRef<'a, Storage> { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>){ let global_root = self.global.root(); let global_ref = global_root.r(); let script_chan = global_ref.script_chan(); let trusted_storage = Trusted::new(global_ref.get_cx(), self, script_chan.clone()); script_chan.send(ScriptMsg::MainThreadRunnableMsg( box StorageEventRunnable::new(trusted_storage, key, old_value, new_value))).unwrap(); } } pub struct StorageEventRunnable { element: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString> } impl StorageEventRunnable { fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) -> StorageEventRunnable { StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value } } } impl MainThreadRunnable for StorageEventRunnable { fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) { let this = *self; let storage_root = this.element.to_temporary().root(); let storage = storage_root.r(); let global_root = storage.global.root(); let global_ref = global_root.r(); let ev_window = global_ref.as_window(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( global_ref, "storage".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key, this.old_value, this.new_value, ev_url.to_string(), Some(storage) ).root(); let event: JSRef<Event> = EventCast::from_ref(storage_event.r()); let root_page = script_task.root_page(); for it_page in root_page.iter() { let it_window_root = it_page.window().root(); let it_window = it_window_root.r(); assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. if ev_window.pipeline() != it_window.pipeline() { let target: JSRef<EventTarget> = EventTargetCast::from_ref(it_window); event.fire(target); } } } }
{ let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); receiver.recv().unwrap() as u32 }
identifier_body
storage.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/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{JSRef, Temporary, Rootable, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::event::{Event, EventHelpers, EventBubbles, EventCancelable}; use dom::eventtarget::{EventTarget}; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; use dom::window::WindowHelpers; use util::str::DOMString; use page::IterablePage; use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType}; use std::sync::mpsc::channel; use url::Url; use script_task::{ScriptTask, ScriptMsg, MainThreadRunnable}; use collections::borrow::ToOwned; #[dom_struct] pub struct Storage { reflector_: Reflector, global: GlobalField, storage_type: StorageType } impl Storage { fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage { Storage { reflector_: Reflector::new(), global: GlobalField::from_rooted(global), storage_type: storage_type } } pub fn
(global: &GlobalRef, storage_type: StorageType) -> Temporary<Storage> { reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap) } fn get_url(&self) -> Url { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() } fn get_storage_task(&self) -> StorageTask { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.as_window().storage_task() } } impl<'a> StorageMethods for JSRef<'a, Storage> { fn Length(self) -> u32 { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); receiver.recv().unwrap() as u32 } fn Key(self, index: u32) -> Option<DOMString> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); receiver.recv().unwrap() } fn GetItem(self, name: DOMString) -> Option<DOMString> { let (sender, receiver) = channel(); let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name); self.get_storage_task().send(msg).unwrap(); receiver.recv().unwrap() } fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option<DOMString> { let item = self.GetItem(name); *found = item.is_some(); item } fn SetItem(self, name: DOMString, value: DOMString) { let (sender, receiver) = channel(); let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); self.get_storage_task().send(msg).unwrap(); let (changed, old_value) = receiver.recv().unwrap(); if changed { self.broadcast_change_notification(Some(name), old_value, Some(value)); } } fn NamedSetter(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedCreator(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn RemoveItem(self, name: DOMString) { let (sender, receiver) = channel(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_task().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap() { self.broadcast_change_notification(Some(name), Some(old_value), None); } } fn NamedDeleter(self, name: DOMString) { self.RemoveItem(name); } fn Clear(self) { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } } } trait PrivateStorageHelpers { fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>); } impl<'a> PrivateStorageHelpers for JSRef<'a, Storage> { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>){ let global_root = self.global.root(); let global_ref = global_root.r(); let script_chan = global_ref.script_chan(); let trusted_storage = Trusted::new(global_ref.get_cx(), self, script_chan.clone()); script_chan.send(ScriptMsg::MainThreadRunnableMsg( box StorageEventRunnable::new(trusted_storage, key, old_value, new_value))).unwrap(); } } pub struct StorageEventRunnable { element: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString> } impl StorageEventRunnable { fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) -> StorageEventRunnable { StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value } } } impl MainThreadRunnable for StorageEventRunnable { fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) { let this = *self; let storage_root = this.element.to_temporary().root(); let storage = storage_root.r(); let global_root = storage.global.root(); let global_ref = global_root.r(); let ev_window = global_ref.as_window(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( global_ref, "storage".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key, this.old_value, this.new_value, ev_url.to_string(), Some(storage) ).root(); let event: JSRef<Event> = EventCast::from_ref(storage_event.r()); let root_page = script_task.root_page(); for it_page in root_page.iter() { let it_window_root = it_page.window().root(); let it_window = it_window_root.r(); assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. if ev_window.pipeline() != it_window.pipeline() { let target: JSRef<EventTarget> = EventTargetCast::from_ref(it_window); event.fire(target); } } } }
new
identifier_name
storage.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/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{JSRef, Temporary, Rootable, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; use dom::event::{Event, EventHelpers, EventBubbles, EventCancelable}; use dom::eventtarget::{EventTarget}; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; use dom::window::WindowHelpers; use util::str::DOMString; use page::IterablePage; use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType}; use std::sync::mpsc::channel; use url::Url; use script_task::{ScriptTask, ScriptMsg, MainThreadRunnable}; use collections::borrow::ToOwned; #[dom_struct] pub struct Storage { reflector_: Reflector, global: GlobalField, storage_type: StorageType } impl Storage { fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage { Storage { reflector_: Reflector::new(), global: GlobalField::from_rooted(global), storage_type: storage_type } } pub fn new(global: &GlobalRef, storage_type: StorageType) -> Temporary<Storage> { reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap) } fn get_url(&self) -> Url { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() } fn get_storage_task(&self) -> StorageTask { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.as_window().storage_task() } } impl<'a> StorageMethods for JSRef<'a, Storage> { fn Length(self) -> u32 { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); receiver.recv().unwrap() as u32 } fn Key(self, index: u32) -> Option<DOMString> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); receiver.recv().unwrap() } fn GetItem(self, name: DOMString) -> Option<DOMString> { let (sender, receiver) = channel(); let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name); self.get_storage_task().send(msg).unwrap(); receiver.recv().unwrap() } fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option<DOMString> { let item = self.GetItem(name); *found = item.is_some(); item } fn SetItem(self, name: DOMString, value: DOMString) { let (sender, receiver) = channel(); let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); self.get_storage_task().send(msg).unwrap(); let (changed, old_value) = receiver.recv().unwrap(); if changed { self.broadcast_change_notification(Some(name), old_value, Some(value)); } } fn NamedSetter(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedCreator(self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn RemoveItem(self, name: DOMString) { let (sender, receiver) = channel(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_task().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap() { self.broadcast_change_notification(Some(name), Some(old_value), None); } } fn NamedDeleter(self, name: DOMString) { self.RemoveItem(name); } fn Clear(self) { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } } } trait PrivateStorageHelpers { fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>); } impl<'a> PrivateStorageHelpers for JSRef<'a, Storage> { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>){ let global_root = self.global.root(); let global_ref = global_root.r(); let script_chan = global_ref.script_chan(); let trusted_storage = Trusted::new(global_ref.get_cx(), self, script_chan.clone()); script_chan.send(ScriptMsg::MainThreadRunnableMsg( box StorageEventRunnable::new(trusted_storage, key, old_value, new_value))).unwrap(); } } pub struct StorageEventRunnable { element: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString> } impl StorageEventRunnable { fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, new_value: Option<DOMString>) -> StorageEventRunnable { StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value } } } impl MainThreadRunnable for StorageEventRunnable { fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) { let this = *self; let storage_root = this.element.to_temporary().root(); let storage = storage_root.r(); let global_root = storage.global.root(); let global_ref = global_root.r(); let ev_window = global_ref.as_window(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( global_ref, "storage".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key, this.old_value, this.new_value, ev_url.to_string(), Some(storage) ).root(); let event: JSRef<Event> = EventCast::from_ref(storage_event.r()); let root_page = script_task.root_page(); for it_page in root_page.iter() { let it_window_root = it_page.window().root(); let it_window = it_window_root.r(); assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. if ev_window.pipeline() != it_window.pipeline()
} } }
{ let target: JSRef<EventTarget> = EventTargetCast::from_ref(it_window); event.fire(target); }
conditional_block
color.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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. //! Color-related constants and functions. /// Colors that work with `graphics` functions, which want color as vectors of f32. #[derive(Debug, Clone, Copy, PartialEq)] pub struct ColorF32(pub [f32; 4]); /// Colors that work with `image` functions, which want color as vectors of u8. #[derive(Debug, Clone, Copy, PartialEq)] pub struct
(pub [u8; 4]); /// Black for use with `graphics`' functions pub const BLACK_F32: ColorF32 = ColorF32([0.0, 0.0, 0.0, 1.0]); /// Grey for use with `graphics`' functions pub const GREY_F32: ColorF32 = ColorF32([0.5, 0.5, 0.5, 1.0]); /// White for use with `graphics`' functions pub const WHITE_F32: ColorF32 = ColorF32([1.0, 1.0, 1.0, 1.0]); /// Dark blue for use with `image`' functions pub const AEBLUE_U8: ColorU8 = ColorU8([0, 0, 48, 255]); /// Black for use with `image`' functions pub const BLACK_U8: ColorU8 = ColorU8([0, 0, 0, 255]); /// White for use with `image`' functions pub const WHITE_U8: ColorU8 = ColorU8([255, 255, 255, 255]); /// Generates a linear range of RGBA colors from a start color to a final color. /// /// /// Eg, to create a spectrum from white to black: /// /// ``` /// use fractal_lib::color::{ColorU8, color_range_linear}; /// /// let black = ColorU8([0,0,0,255]); /// let white = ColorU8([255,255,255,255]); /// /// let range = color_range_linear(black, white, 256); /// /// assert_eq!(range[0], black); /// assert_eq!(range[255], white); /// assert_eq!(range[10], ColorU8([10,10,10,255])); /// ``` /// /// If you want to simulate a cutoff/saturation point where the gradients reach the peak color /// before some maximium index value, then you can use `std::cmp::min` to prevent an out of bounds /// error: /// /// ``` /// use fractal_lib::color::{ColorU8, color_range_linear}; /// use std::cmp::min; /// /// let black = ColorU8([0,0,0,255]); /// let white = ColorU8([255,255,255,255]); /// let gradient_count = 128; /// let range = color_range_linear(black, white, gradient_count); /// /// assert_eq!(range[min(gradient_count-1, 0)], black); /// assert_eq!(range[min(gradient_count-1, gradient_count-1)], white); /// assert_eq!(range[min(gradient_count-1, 255)], white); /// assert_eq!(range[min(gradient_count-1, 127)], white); /// assert_eq!(range[min(gradient_count-1, 10)], ColorU8([20,20,20,255])); /// ``` pub fn color_range_linear(first: ColorU8, last: ColorU8, count: usize) -> Vec<ColorU8> { if count < 2 { panic!("Count must be 2 or more: {}", count); } let deltas = [ (f32::from(last.0[0]) - f32::from(first.0[0])) / f32::from((count as u16) - 1), (f32::from(last.0[1]) - f32::from(first.0[1])) / f32::from((count as u16) - 1), (f32::from(last.0[2]) - f32::from(first.0[2])) / f32::from((count as u16) - 1), (f32::from(last.0[3]) - f32::from(first.0[3])) / f32::from((count as u16) - 1), ]; (0..count) .map(|i| { ColorU8([ (f32::from(first.0[0]) + f32::from(i as u16) * deltas[0]) as u8, (f32::from(first.0[1]) + f32::from(i as u16) * deltas[1]) as u8, (f32::from(first.0[2]) + f32::from(i as u16) * deltas[2]) as u8, (f32::from(first.0[3]) + f32::from(i as u16) * deltas[3]) as u8, ]) }) .collect() } #[cfg(test)] mod test { use super::*; #[test] #[should_panic(expected = "Count must be 2 or more")] fn test_linear_zero() { let black = ColorU8([0, 0, 0, 255]); let white = ColorU8([255, 255, 255, 255]); let range = color_range_linear(black, white, 0); assert!(range.len() == 0); } #[test] #[should_panic(expected = "Count must be 2 or more")] fn test_linear_one() { let black = ColorU8([0, 0, 0, 255]); let white = ColorU8([255, 255, 255, 255]); let range = color_range_linear(black, white, 1); assert!(range.len() == 1); } #[test] fn test_linear_two() { let black = ColorU8([0, 0, 0, 255]); let white = ColorU8([255, 255, 255, 255]); let range = color_range_linear(black, white, 2); assert_eq!(black, range[0]); assert_eq!(white, range[1]); } }
ColorU8
identifier_name
color.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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. //! Color-related constants and functions. /// Colors that work with `graphics` functions, which want color as vectors of f32. #[derive(Debug, Clone, Copy, PartialEq)] pub struct ColorF32(pub [f32; 4]); /// Colors that work with `image` functions, which want color as vectors of u8. #[derive(Debug, Clone, Copy, PartialEq)] pub struct ColorU8(pub [u8; 4]); /// Black for use with `graphics`' functions pub const BLACK_F32: ColorF32 = ColorF32([0.0, 0.0, 0.0, 1.0]); /// Grey for use with `graphics`' functions pub const GREY_F32: ColorF32 = ColorF32([0.5, 0.5, 0.5, 1.0]); /// White for use with `graphics`' functions pub const WHITE_F32: ColorF32 = ColorF32([1.0, 1.0, 1.0, 1.0]); /// Dark blue for use with `image`' functions pub const AEBLUE_U8: ColorU8 = ColorU8([0, 0, 48, 255]); /// Black for use with `image`' functions pub const BLACK_U8: ColorU8 = ColorU8([0, 0, 0, 255]); /// White for use with `image`' functions pub const WHITE_U8: ColorU8 = ColorU8([255, 255, 255, 255]); /// Generates a linear range of RGBA colors from a start color to a final color. /// /// /// Eg, to create a spectrum from white to black: /// /// ``` /// use fractal_lib::color::{ColorU8, color_range_linear}; /// /// let black = ColorU8([0,0,0,255]); /// let white = ColorU8([255,255,255,255]); /// /// let range = color_range_linear(black, white, 256); /// /// assert_eq!(range[0], black); /// assert_eq!(range[255], white); /// assert_eq!(range[10], ColorU8([10,10,10,255])); /// ``` /// /// If you want to simulate a cutoff/saturation point where the gradients reach the peak color /// before some maximium index value, then you can use `std::cmp::min` to prevent an out of bounds
/// /// ``` /// use fractal_lib::color::{ColorU8, color_range_linear}; /// use std::cmp::min; /// /// let black = ColorU8([0,0,0,255]); /// let white = ColorU8([255,255,255,255]); /// let gradient_count = 128; /// let range = color_range_linear(black, white, gradient_count); /// /// assert_eq!(range[min(gradient_count-1, 0)], black); /// assert_eq!(range[min(gradient_count-1, gradient_count-1)], white); /// assert_eq!(range[min(gradient_count-1, 255)], white); /// assert_eq!(range[min(gradient_count-1, 127)], white); /// assert_eq!(range[min(gradient_count-1, 10)], ColorU8([20,20,20,255])); /// ``` pub fn color_range_linear(first: ColorU8, last: ColorU8, count: usize) -> Vec<ColorU8> { if count < 2 { panic!("Count must be 2 or more: {}", count); } let deltas = [ (f32::from(last.0[0]) - f32::from(first.0[0])) / f32::from((count as u16) - 1), (f32::from(last.0[1]) - f32::from(first.0[1])) / f32::from((count as u16) - 1), (f32::from(last.0[2]) - f32::from(first.0[2])) / f32::from((count as u16) - 1), (f32::from(last.0[3]) - f32::from(first.0[3])) / f32::from((count as u16) - 1), ]; (0..count) .map(|i| { ColorU8([ (f32::from(first.0[0]) + f32::from(i as u16) * deltas[0]) as u8, (f32::from(first.0[1]) + f32::from(i as u16) * deltas[1]) as u8, (f32::from(first.0[2]) + f32::from(i as u16) * deltas[2]) as u8, (f32::from(first.0[3]) + f32::from(i as u16) * deltas[3]) as u8, ]) }) .collect() } #[cfg(test)] mod test { use super::*; #[test] #[should_panic(expected = "Count must be 2 or more")] fn test_linear_zero() { let black = ColorU8([0, 0, 0, 255]); let white = ColorU8([255, 255, 255, 255]); let range = color_range_linear(black, white, 0); assert!(range.len() == 0); } #[test] #[should_panic(expected = "Count must be 2 or more")] fn test_linear_one() { let black = ColorU8([0, 0, 0, 255]); let white = ColorU8([255, 255, 255, 255]); let range = color_range_linear(black, white, 1); assert!(range.len() == 1); } #[test] fn test_linear_two() { let black = ColorU8([0, 0, 0, 255]); let white = ColorU8([255, 255, 255, 255]); let range = color_range_linear(black, white, 2); assert_eq!(black, range[0]); assert_eq!(white, range[1]); } }
/// error:
random_line_split
color.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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. //! Color-related constants and functions. /// Colors that work with `graphics` functions, which want color as vectors of f32. #[derive(Debug, Clone, Copy, PartialEq)] pub struct ColorF32(pub [f32; 4]); /// Colors that work with `image` functions, which want color as vectors of u8. #[derive(Debug, Clone, Copy, PartialEq)] pub struct ColorU8(pub [u8; 4]); /// Black for use with `graphics`' functions pub const BLACK_F32: ColorF32 = ColorF32([0.0, 0.0, 0.0, 1.0]); /// Grey for use with `graphics`' functions pub const GREY_F32: ColorF32 = ColorF32([0.5, 0.5, 0.5, 1.0]); /// White for use with `graphics`' functions pub const WHITE_F32: ColorF32 = ColorF32([1.0, 1.0, 1.0, 1.0]); /// Dark blue for use with `image`' functions pub const AEBLUE_U8: ColorU8 = ColorU8([0, 0, 48, 255]); /// Black for use with `image`' functions pub const BLACK_U8: ColorU8 = ColorU8([0, 0, 0, 255]); /// White for use with `image`' functions pub const WHITE_U8: ColorU8 = ColorU8([255, 255, 255, 255]); /// Generates a linear range of RGBA colors from a start color to a final color. /// /// /// Eg, to create a spectrum from white to black: /// /// ``` /// use fractal_lib::color::{ColorU8, color_range_linear}; /// /// let black = ColorU8([0,0,0,255]); /// let white = ColorU8([255,255,255,255]); /// /// let range = color_range_linear(black, white, 256); /// /// assert_eq!(range[0], black); /// assert_eq!(range[255], white); /// assert_eq!(range[10], ColorU8([10,10,10,255])); /// ``` /// /// If you want to simulate a cutoff/saturation point where the gradients reach the peak color /// before some maximium index value, then you can use `std::cmp::min` to prevent an out of bounds /// error: /// /// ``` /// use fractal_lib::color::{ColorU8, color_range_linear}; /// use std::cmp::min; /// /// let black = ColorU8([0,0,0,255]); /// let white = ColorU8([255,255,255,255]); /// let gradient_count = 128; /// let range = color_range_linear(black, white, gradient_count); /// /// assert_eq!(range[min(gradient_count-1, 0)], black); /// assert_eq!(range[min(gradient_count-1, gradient_count-1)], white); /// assert_eq!(range[min(gradient_count-1, 255)], white); /// assert_eq!(range[min(gradient_count-1, 127)], white); /// assert_eq!(range[min(gradient_count-1, 10)], ColorU8([20,20,20,255])); /// ``` pub fn color_range_linear(first: ColorU8, last: ColorU8, count: usize) -> Vec<ColorU8> { if count < 2
let deltas = [ (f32::from(last.0[0]) - f32::from(first.0[0])) / f32::from((count as u16) - 1), (f32::from(last.0[1]) - f32::from(first.0[1])) / f32::from((count as u16) - 1), (f32::from(last.0[2]) - f32::from(first.0[2])) / f32::from((count as u16) - 1), (f32::from(last.0[3]) - f32::from(first.0[3])) / f32::from((count as u16) - 1), ]; (0..count) .map(|i| { ColorU8([ (f32::from(first.0[0]) + f32::from(i as u16) * deltas[0]) as u8, (f32::from(first.0[1]) + f32::from(i as u16) * deltas[1]) as u8, (f32::from(first.0[2]) + f32::from(i as u16) * deltas[2]) as u8, (f32::from(first.0[3]) + f32::from(i as u16) * deltas[3]) as u8, ]) }) .collect() } #[cfg(test)] mod test { use super::*; #[test] #[should_panic(expected = "Count must be 2 or more")] fn test_linear_zero() { let black = ColorU8([0, 0, 0, 255]); let white = ColorU8([255, 255, 255, 255]); let range = color_range_linear(black, white, 0); assert!(range.len() == 0); } #[test] #[should_panic(expected = "Count must be 2 or more")] fn test_linear_one() { let black = ColorU8([0, 0, 0, 255]); let white = ColorU8([255, 255, 255, 255]); let range = color_range_linear(black, white, 1); assert!(range.len() == 1); } #[test] fn test_linear_two() { let black = ColorU8([0, 0, 0, 255]); let white = ColorU8([255, 255, 255, 255]); let range = color_range_linear(black, white, 2); assert_eq!(black, range[0]); assert_eq!(white, range[1]); } }
{ panic!("Count must be 2 or more: {}", count); }
conditional_block
dumpAST-baselining.ts
// // Copyright (c) Microsoft Corporation. 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. // /// <reference path='harness.ts'/> /// <reference path='external\json2.ts'/> module DumpAST { class DumpEntry { public nodeType: string; public minChar: number; public limChar: number; public startLine: number; public startCol: number; public endLine: number; public endCol: number; public children: DumpEntry[]; constructor () { this.children = []; } } function getOutputPath() { return Harness.userSpecifiedroot + 'tests/cases/unittests/services/dumpAST/baselines'; } function getInputPath() { return Harness.userSpecifiedroot + 'tests/cases/unittests/services/testCode'; } function getExistingTestCodeFileNames(): string[] {
function deleteExistingBaselineFiles() { var outputPath = getOutputPath(); // Might need to create this IO.createDirectory(outputPath); // Delete any old reports from the local path var localFiles = IO.dir(outputPath); for (var i = 0; i < localFiles.length; i++) { var localFilename = localFiles[i]; if (localFilename.indexOf('.html') > 0) { IO.deleteFile(localFilename); } } } function createDumpTree(script: TypeScript.Script): DumpEntry { var entries = new DumpEntry[]; var root: DumpEntry = null; var pre = (cur: TypeScript.AST, parent: TypeScript.AST): TypeScript.AST => { //verifyAstNodePositions(script, cur); var parent = (entries.length == 0 ? null : entries[entries.length - 1]); var newEntry = createDumpEntry(script, cur, parent); if (entries.length == 0) { root = newEntry; } var dumpComments = function (comments: TypeScript.Comment[]): void { if (comments) { for (var i = 0; i < comments.length; i++) { entries.push(createDumpEntry(script, comments[i], parent)); } } } dumpComments(cur.preComments); entries.push(newEntry); dumpComments(cur.postComments); return cur; }; var post = (cur, parent) => { entries.pop(); return cur; }; TypeScript.getAstWalkerFactory().walk(script, pre, post); return root; } function createDumpEntry(script: TypeScript.Script, ast: TypeScript.AST, parent: DumpEntry): DumpEntry { var entry = new DumpEntry(); entry.nodeType = (<any>TypeScript.NodeType)._map[ast.nodeType]; entry.minChar = ast.minChar; entry.limChar = ast.limChar; entry.startLine = TypeScript.getLineColumnFromPosition(script, ast.minChar).line; entry.startCol = TypeScript.getLineColumnFromPosition(script, ast.minChar).col; entry.endLine = TypeScript.getLineColumnFromPosition(script, ast.limChar).line; entry.endCol = TypeScript.getLineColumnFromPosition(script, ast.limChar).col; if (parent) parent.children.push(entry); return entry; } function verifyAstNodePositions(script: TypeScript.Script, ast: TypeScript.AST): void { var fileName = script.locationInfo.filename; var maxLimChar = script.limChar; var minChar = ast.minChar; if (minChar < 0) { assert.is(minChar === -1, "file \"" + fileName + "\": " + "The only valid nagative value for minChar is '-1'"); } assert.is(minChar <= maxLimChar, "file \"" + fileName + "\": " + "minChar value " + minChar + " is greater than the length of the source file " + maxLimChar); var limChar = ast.limChar; if (limChar < 0) { assert.is(limChar === -1, "file \"" + fileName + "\": " + "The only valid nagative value for limChar is '-1'"); } assert.is(limChar <= maxLimChar, "file \"" + fileName + "\": " + "limChar value " + limChar + " is greater than the length of the source file " + maxLimChar); if (minChar < 0) { assert.is(limChar < 0, "file \"" + fileName + "\": " + "minChar value is '-1' but limChar value '" + limChar + "' is not"); } if (limChar < 0) { assert.is(minChar < 0, "file \"" + fileName + "\": " + "limChar value is '-1' but minChar value '" + minChar + "' is not"); } assert.is(minChar <= limChar, "file \"" + fileName + "\": " + "minChar value " + minChar + " is greater the limChar value " + limChar); } function getBaselineFileName(fileName: string): string { fileName = switchToForwardSlashes(fileName); var nameIndex = fileName.lastIndexOf("/") + 1; return getOutputPath() + "/" + fileName.substring(nameIndex) + ".json"; } var addKey = function (key: string): string { return JSON2.stringify(key); } var addString = function (key: string, value: string): string { return addKey(key) + ": " + JSON2.stringify(value); } var addNumber = function (key: string, value: number): string { return addKey(key) + ": " + JSON2.stringify(value); } function dumpEntries(entry: DumpEntry, indent: number): string { var indentStr = ""; for (var i = 0; i < indent; i++) { indentStr += " "; } if (entry === null) return ""; var result = indentStr; result += "{"; result += addString("nodeType", entry.nodeType) + ", "; result += addNumber("minChar", entry.minChar) + ", "; result += addNumber("limChar", entry.limChar) + ", "; result += addNumber("startLine", entry.startLine) + ", "; result += addNumber("startCol", entry.startCol) + ", "; result += addNumber("endLine", entry.endLine) + ", "; result += addNumber("endCol", entry.endCol) + ", "; result += addKey("children") + ": ["; if (entry.children !== null && entry.children.length > 0) { result += "\r\n"; for (var i = 0; i < entry.children.length; i++) { result += dumpEntries(entry.children[i], indent + 1); if (i < entry.children.length - 1) { result += ","; result += "\r\n"; } } } result += "]"; result += "}"; return result; } function createDumpContentForFile(typescriptLS: Harness.TypeScriptLS, fileName: string): string { var sourceText = new TypeScript.StringSourceText(IO.readFile(fileName)) var script = typescriptLS.parseSourceText(fileName, sourceText); // Dump source text (as JS comments) var indentStr = " "; var text = "{\r\n"; text += indentStr; text += addKey("sourceText"); text += ": [\r\n"; for (var i = 1; i < script.locationInfo.lineMap.length; i++) { if (i > 1) { text += ",\r\n"; } var start = script.locationInfo.lineMap[i]; var end = (i < script.locationInfo.lineMap.length - 1 ? script.locationInfo.lineMap[i + 1] : sourceText.getLength()); text += indentStr + indentStr + JSON2.stringify(sourceText.getText(start, end)); } text += "],"; text += "\r\n"; // Dump source locations (as JSON entries) text += indentStr; text += addKey("ast"); text += ":\r\n"; var entry = createDumpTree(script); text += dumpEntries(entry, 2); text += "\r\n}\r\n"; return text; } export function compareDumpFilesWithBaseline() { var typescriptLS = new Harness.TypeScriptLS(); var fileNames = getExistingTestCodeFileNames(); for (var i = 0; i < fileNames.length; i++) { var fileName = switchToForwardSlashes(fileNames[i]); var nameOnly = fileName.substr(fileName.lastIndexOf('/') + 1); var run = (fn) => { Harness.Baseline.runBaseline('AST data for ' + fn, nameOnly.replace(/\.ts/, '.ast'), function () { return createDumpContentForFile(typescriptLS, fn); } ); } run(fileName); } } }
var inputPath = getInputPath(); return IO.dir(inputPath, null, { recursive: true }); }
identifier_body
dumpAST-baselining.ts
// // Copyright (c) Microsoft Corporation. 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. // /// <reference path='harness.ts'/> /// <reference path='external\json2.ts'/> module DumpAST { class DumpEntry { public nodeType: string; public minChar: number; public limChar: number; public startLine: number; public startCol: number; public endLine: number; public endCol: number; public children: DumpEntry[]; constructor () { this.children = []; } } function getOutputPath() { return Harness.userSpecifiedroot + 'tests/cases/unittests/services/dumpAST/baselines'; } function getInputPath() { return Harness.userSpecifiedroot + 'tests/cases/unittests/services/testCode'; } function getExistingTestCodeFileNames(): string[] { var inputPath = getInputPath(); return IO.dir(inputPath, null, { recursive: true }); } function deleteExistingBaselineFiles() { var outputPath = getOutputPath(); // Might need to create this IO.createDirectory(outputPath); // Delete any old reports from the local path var localFiles = IO.dir(outputPath); for (var i = 0; i < localFiles.length; i++) { var localFilename = localFiles[i]; if (localFilename.indexOf('.html') > 0) { IO.deleteFile(localFilename); } } } function createDumpTree(script: TypeScript.Script): DumpEntry { var entries = new DumpEntry[]; var root: DumpEntry = null; var pre = (cur: TypeScript.AST, parent: TypeScript.AST): TypeScript.AST => { //verifyAstNodePositions(script, cur); var parent = (entries.length == 0 ? null : entries[entries.length - 1]); var newEntry = createDumpEntry(script, cur, parent); if (entries.length == 0) { root = newEntry; } var dumpComments = function (comments: TypeScript.Comment[]): void { if (comments) { for (var i = 0; i < comments.length; i++) { entries.push(createDumpEntry(script, comments[i], parent)); } } } dumpComments(cur.preComments); entries.push(newEntry); dumpComments(cur.postComments); return cur; }; var post = (cur, parent) => { entries.pop(); return cur; }; TypeScript.getAstWalkerFactory().walk(script, pre, post); return root; } function createDumpEntry(script: TypeScript.Script, ast: TypeScript.AST, parent: DumpEntry): DumpEntry { var entry = new DumpEntry(); entry.nodeType = (<any>TypeScript.NodeType)._map[ast.nodeType]; entry.minChar = ast.minChar; entry.limChar = ast.limChar; entry.startLine = TypeScript.getLineColumnFromPosition(script, ast.minChar).line; entry.startCol = TypeScript.getLineColumnFromPosition(script, ast.minChar).col; entry.endLine = TypeScript.getLineColumnFromPosition(script, ast.limChar).line; entry.endCol = TypeScript.getLineColumnFromPosition(script, ast.limChar).col; if (parent) parent.children.push(entry); return entry; } function verifyAstNodePositions(script: TypeScript.Script, ast: TypeScript.AST): void { var fileName = script.locationInfo.filename; var maxLimChar = script.limChar; var minChar = ast.minChar; if (minChar < 0) { assert.is(minChar === -1, "file \"" + fileName + "\": " + "The only valid nagative value for minChar is '-1'"); } assert.is(minChar <= maxLimChar, "file \"" + fileName + "\": " + "minChar value " + minChar + " is greater than the length of the source file " + maxLimChar); var limChar = ast.limChar; if (limChar < 0) { assert.is(limChar === -1, "file \"" + fileName + "\": " + "The only valid nagative value for limChar is '-1'"); } assert.is(limChar <= maxLimChar, "file \"" + fileName + "\": " + "limChar value " + limChar + " is greater than the length of the source file " + maxLimChar); if (minChar < 0) { assert.is(limChar < 0, "file \"" + fileName + "\": " + "minChar value is '-1' but limChar value '" + limChar + "' is not"); } if (limChar < 0) { assert.is(minChar < 0, "file \"" + fileName + "\": " + "limChar value is '-1' but minChar value '" + minChar + "' is not"); } assert.is(minChar <= limChar, "file \"" + fileName + "\": " + "minChar value " + minChar + " is greater the limChar value " + limChar); } function getBaselineFileName(fileName: string): string { fileName = switchToForwardSlashes(fileName); var nameIndex = fileName.lastIndexOf("/") + 1; return getOutputPath() + "/" + fileName.substring(nameIndex) + ".json"; } var addKey = function (key: string): string { return JSON2.stringify(key); } var addString = function (key: string, value: string): string { return addKey(key) + ": " + JSON2.stringify(value); } var addNumber = function (key: string, value: number): string { return addKey(key) + ": " + JSON2.stringify(value); } function dumpEntries(entry: DumpEntry, indent: number): string { var indentStr = ""; for (var i = 0; i < indent; i++) { indentStr += " "; } if (entry === null) return ""; var result = indentStr; result += "{"; result += addString("nodeType", entry.nodeType) + ", "; result += addNumber("minChar", entry.minChar) + ", "; result += addNumber("limChar", entry.limChar) + ", "; result += addNumber("startLine", entry.startLine) + ", "; result += addNumber("startCol", entry.startCol) + ", "; result += addNumber("endLine", entry.endLine) + ", "; result += addNumber("endCol", entry.endCol) + ", "; result += addKey("children") + ": ["; if (entry.children !== null && entry.children.length > 0) { result += "\r\n"; for (var i = 0; i < entry.children.length; i++) { result += dumpEntries(entry.children[i], indent + 1); if (i < entry.children.length - 1) { result += ","; result += "\r\n"; } } } result += "]"; result += "}"; return result; }
var script = typescriptLS.parseSourceText(fileName, sourceText); // Dump source text (as JS comments) var indentStr = " "; var text = "{\r\n"; text += indentStr; text += addKey("sourceText"); text += ": [\r\n"; for (var i = 1; i < script.locationInfo.lineMap.length; i++) { if (i > 1) { text += ",\r\n"; } var start = script.locationInfo.lineMap[i]; var end = (i < script.locationInfo.lineMap.length - 1 ? script.locationInfo.lineMap[i + 1] : sourceText.getLength()); text += indentStr + indentStr + JSON2.stringify(sourceText.getText(start, end)); } text += "],"; text += "\r\n"; // Dump source locations (as JSON entries) text += indentStr; text += addKey("ast"); text += ":\r\n"; var entry = createDumpTree(script); text += dumpEntries(entry, 2); text += "\r\n}\r\n"; return text; } export function compareDumpFilesWithBaseline() { var typescriptLS = new Harness.TypeScriptLS(); var fileNames = getExistingTestCodeFileNames(); for (var i = 0; i < fileNames.length; i++) { var fileName = switchToForwardSlashes(fileNames[i]); var nameOnly = fileName.substr(fileName.lastIndexOf('/') + 1); var run = (fn) => { Harness.Baseline.runBaseline('AST data for ' + fn, nameOnly.replace(/\.ts/, '.ast'), function () { return createDumpContentForFile(typescriptLS, fn); } ); } run(fileName); } } }
function createDumpContentForFile(typescriptLS: Harness.TypeScriptLS, fileName: string): string { var sourceText = new TypeScript.StringSourceText(IO.readFile(fileName))
random_line_split
dumpAST-baselining.ts
// // Copyright (c) Microsoft Corporation. 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. // /// <reference path='harness.ts'/> /// <reference path='external\json2.ts'/> module DumpAST { class DumpEntry { public nodeType: string; public minChar: number; public limChar: number; public startLine: number; public startCol: number; public endLine: number; public endCol: number; public children: DumpEntry[]; constructor () { this.children = []; } } function getOutputPath() { return Harness.userSpecifiedroot + 'tests/cases/unittests/services/dumpAST/baselines'; } function getInputPath() { return Harness.userSpecifiedroot + 'tests/cases/unittests/services/testCode'; } function getExistingTestCodeFileNames(): string[] { var inputPath = getInputPath(); return IO.dir(inputPath, null, { recursive: true }); } function deleteExistingBaselineFiles() { var outputPath = getOutputPath(); // Might need to create this IO.createDirectory(outputPath); // Delete any old reports from the local path var localFiles = IO.dir(outputPath); for (var i = 0; i < localFiles.length; i++) { var localFilename = localFiles[i]; if (localFilename.indexOf('.html') > 0) { IO.deleteFile(localFilename); } } } function createDumpTree(script: TypeScript.Script): DumpEntry { var entries = new DumpEntry[]; var root: DumpEntry = null; var pre = (cur: TypeScript.AST, parent: TypeScript.AST): TypeScript.AST => { //verifyAstNodePositions(script, cur); var parent = (entries.length == 0 ? null : entries[entries.length - 1]); var newEntry = createDumpEntry(script, cur, parent); if (entries.length == 0) { root = newEntry; } var dumpComments = function (comments: TypeScript.Comment[]): void { if (comments) { for (var i = 0; i < comments.length; i++) { entries.push(createDumpEntry(script, comments[i], parent)); } } } dumpComments(cur.preComments); entries.push(newEntry); dumpComments(cur.postComments); return cur; }; var post = (cur, parent) => { entries.pop(); return cur; }; TypeScript.getAstWalkerFactory().walk(script, pre, post); return root; } function createDumpEntry(script: TypeScript.Script, ast: TypeScript.AST, parent: DumpEntry): DumpEntry { var entry = new DumpEntry(); entry.nodeType = (<any>TypeScript.NodeType)._map[ast.nodeType]; entry.minChar = ast.minChar; entry.limChar = ast.limChar; entry.startLine = TypeScript.getLineColumnFromPosition(script, ast.minChar).line; entry.startCol = TypeScript.getLineColumnFromPosition(script, ast.minChar).col; entry.endLine = TypeScript.getLineColumnFromPosition(script, ast.limChar).line; entry.endCol = TypeScript.getLineColumnFromPosition(script, ast.limChar).col; if (parent) parent.children.push(entry); return entry; } function verifyAstNodePositions(script: TypeScript.Script, ast: TypeScript.AST): void { var fileName = script.locationInfo.filename; var maxLimChar = script.limChar; var minChar = ast.minChar; if (minChar < 0) { assert.is(minChar === -1, "file \"" + fileName + "\": " + "The only valid nagative value for minChar is '-1'"); } assert.is(minChar <= maxLimChar, "file \"" + fileName + "\": " + "minChar value " + minChar + " is greater than the length of the source file " + maxLimChar); var limChar = ast.limChar; if (limChar < 0) { assert.is(limChar === -1, "file \"" + fileName + "\": " + "The only valid nagative value for limChar is '-1'"); } assert.is(limChar <= maxLimChar, "file \"" + fileName + "\": " + "limChar value " + limChar + " is greater than the length of the source file " + maxLimChar); if (minChar < 0) { assert.is(limChar < 0, "file \"" + fileName + "\": " + "minChar value is '-1' but limChar value '" + limChar + "' is not"); } if (limChar < 0) { assert.is(minChar < 0, "file \"" + fileName + "\": " + "limChar value is '-1' but minChar value '" + minChar + "' is not"); } assert.is(minChar <= limChar, "file \"" + fileName + "\": " + "minChar value " + minChar + " is greater the limChar value " + limChar); } function getB
eName: string): string { fileName = switchToForwardSlashes(fileName); var nameIndex = fileName.lastIndexOf("/") + 1; return getOutputPath() + "/" + fileName.substring(nameIndex) + ".json"; } var addKey = function (key: string): string { return JSON2.stringify(key); } var addString = function (key: string, value: string): string { return addKey(key) + ": " + JSON2.stringify(value); } var addNumber = function (key: string, value: number): string { return addKey(key) + ": " + JSON2.stringify(value); } function dumpEntries(entry: DumpEntry, indent: number): string { var indentStr = ""; for (var i = 0; i < indent; i++) { indentStr += " "; } if (entry === null) return ""; var result = indentStr; result += "{"; result += addString("nodeType", entry.nodeType) + ", "; result += addNumber("minChar", entry.minChar) + ", "; result += addNumber("limChar", entry.limChar) + ", "; result += addNumber("startLine", entry.startLine) + ", "; result += addNumber("startCol", entry.startCol) + ", "; result += addNumber("endLine", entry.endLine) + ", "; result += addNumber("endCol", entry.endCol) + ", "; result += addKey("children") + ": ["; if (entry.children !== null && entry.children.length > 0) { result += "\r\n"; for (var i = 0; i < entry.children.length; i++) { result += dumpEntries(entry.children[i], indent + 1); if (i < entry.children.length - 1) { result += ","; result += "\r\n"; } } } result += "]"; result += "}"; return result; } function createDumpContentForFile(typescriptLS: Harness.TypeScriptLS, fileName: string): string { var sourceText = new TypeScript.StringSourceText(IO.readFile(fileName)) var script = typescriptLS.parseSourceText(fileName, sourceText); // Dump source text (as JS comments) var indentStr = " "; var text = "{\r\n"; text += indentStr; text += addKey("sourceText"); text += ": [\r\n"; for (var i = 1; i < script.locationInfo.lineMap.length; i++) { if (i > 1) { text += ",\r\n"; } var start = script.locationInfo.lineMap[i]; var end = (i < script.locationInfo.lineMap.length - 1 ? script.locationInfo.lineMap[i + 1] : sourceText.getLength()); text += indentStr + indentStr + JSON2.stringify(sourceText.getText(start, end)); } text += "],"; text += "\r\n"; // Dump source locations (as JSON entries) text += indentStr; text += addKey("ast"); text += ":\r\n"; var entry = createDumpTree(script); text += dumpEntries(entry, 2); text += "\r\n}\r\n"; return text; } export function compareDumpFilesWithBaseline() { var typescriptLS = new Harness.TypeScriptLS(); var fileNames = getExistingTestCodeFileNames(); for (var i = 0; i < fileNames.length; i++) { var fileName = switchToForwardSlashes(fileNames[i]); var nameOnly = fileName.substr(fileName.lastIndexOf('/') + 1); var run = (fn) => { Harness.Baseline.runBaseline('AST data for ' + fn, nameOnly.replace(/\.ts/, '.ast'), function () { return createDumpContentForFile(typescriptLS, fn); } ); } run(fileName); } } }
aselineFileName(fil
identifier_name
dumpAST-baselining.ts
// // Copyright (c) Microsoft Corporation. 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. // /// <reference path='harness.ts'/> /// <reference path='external\json2.ts'/> module DumpAST { class DumpEntry { public nodeType: string; public minChar: number; public limChar: number; public startLine: number; public startCol: number; public endLine: number; public endCol: number; public children: DumpEntry[]; constructor () { this.children = []; } } function getOutputPath() { return Harness.userSpecifiedroot + 'tests/cases/unittests/services/dumpAST/baselines'; } function getInputPath() { return Harness.userSpecifiedroot + 'tests/cases/unittests/services/testCode'; } function getExistingTestCodeFileNames(): string[] { var inputPath = getInputPath(); return IO.dir(inputPath, null, { recursive: true }); } function deleteExistingBaselineFiles() { var outputPath = getOutputPath(); // Might need to create this IO.createDirectory(outputPath); // Delete any old reports from the local path var localFiles = IO.dir(outputPath); for (var i = 0; i < localFiles.length; i++) { var localFilename = localFiles[i]; if (localFilename.indexOf('.html') > 0) { IO.deleteFile(localFilename); } } } function createDumpTree(script: TypeScript.Script): DumpEntry { var entries = new DumpEntry[]; var root: DumpEntry = null; var pre = (cur: TypeScript.AST, parent: TypeScript.AST): TypeScript.AST => { //verifyAstNodePositions(script, cur); var parent = (entries.length == 0 ? null : entries[entries.length - 1]); var newEntry = createDumpEntry(script, cur, parent); if (entries.length == 0) { root = newEntry; } var dumpComments = function (comments: TypeScript.Comment[]): void { if (comments) { for (var i = 0; i < comments.length; i++) { entries.push(createDumpEntry(script, comments[i], parent)); } } } dumpComments(cur.preComments); entries.push(newEntry); dumpComments(cur.postComments); return cur; }; var post = (cur, parent) => { entries.pop(); return cur; }; TypeScript.getAstWalkerFactory().walk(script, pre, post); return root; } function createDumpEntry(script: TypeScript.Script, ast: TypeScript.AST, parent: DumpEntry): DumpEntry { var entry = new DumpEntry(); entry.nodeType = (<any>TypeScript.NodeType)._map[ast.nodeType]; entry.minChar = ast.minChar; entry.limChar = ast.limChar; entry.startLine = TypeScript.getLineColumnFromPosition(script, ast.minChar).line; entry.startCol = TypeScript.getLineColumnFromPosition(script, ast.minChar).col; entry.endLine = TypeScript.getLineColumnFromPosition(script, ast.limChar).line; entry.endCol = TypeScript.getLineColumnFromPosition(script, ast.limChar).col; if (parent) parent.children.push(entry); return entry; } function verifyAstNodePositions(script: TypeScript.Script, ast: TypeScript.AST): void { var fileName = script.locationInfo.filename; var maxLimChar = script.limChar; var minChar = ast.minChar; if (minChar < 0) { assert.is(minChar === -1, "file \"" + fileName + "\": " + "The only valid nagative value for minChar is '-1'"); } assert.is(minChar <= maxLimChar, "file \"" + fileName + "\": " + "minChar value " + minChar + " is greater than the length of the source file " + maxLimChar); var limChar = ast.limChar; if (limChar < 0) { assert.is(limChar === -1, "file \"" + fileName + "\": " + "The only valid nagative value for limChar is '-1'"); } assert.is(limChar <= maxLimChar, "file \"" + fileName + "\": " + "limChar value " + limChar + " is greater than the length of the source file " + maxLimChar); if (minChar < 0) { assert.is(limChar < 0, "file \"" + fileName + "\": " + "minChar value is '-1' but limChar value '" + limChar + "' is not"); } if (limChar < 0) { assert.is(minChar < 0, "file \"" + fileName + "\": " + "limChar value is '-1' but minChar value '" + minChar + "' is not"); } assert.is(minChar <= limChar, "file \"" + fileName + "\": " + "minChar value " + minChar + " is greater the limChar value " + limChar); } function getBaselineFileName(fileName: string): string { fileName = switchToForwardSlashes(fileName); var nameIndex = fileName.lastIndexOf("/") + 1; return getOutputPath() + "/" + fileName.substring(nameIndex) + ".json"; } var addKey = function (key: string): string { return JSON2.stringify(key); } var addString = function (key: string, value: string): string { return addKey(key) + ": " + JSON2.stringify(value); } var addNumber = function (key: string, value: number): string { return addKey(key) + ": " + JSON2.stringify(value); } function dumpEntries(entry: DumpEntry, indent: number): string { var indentStr = ""; for (var i = 0; i < indent; i++) { indentStr += " "; } if (entry === null) return ""; var result = indentStr; result += "{"; result += addString("nodeType", entry.nodeType) + ", "; result += addNumber("minChar", entry.minChar) + ", "; result += addNumber("limChar", entry.limChar) + ", "; result += addNumber("startLine", entry.startLine) + ", "; result += addNumber("startCol", entry.startCol) + ", "; result += addNumber("endLine", entry.endLine) + ", "; result += addNumber("endCol", entry.endCol) + ", "; result += addKey("children") + ": ["; if (entry.children !== null && entry.children.length > 0) { result += "\r\n"; for (var i = 0; i < entry.children.length; i++) { result += dumpEntries(entry.children[i], indent + 1); if (i < entry.children.length - 1) { result += ","; result += "\r\n"; } } } result += "]"; result += "}"; return result; } function createDumpContentForFile(typescriptLS: Harness.TypeScriptLS, fileName: string): string { var sourceText = new TypeScript.StringSourceText(IO.readFile(fileName)) var script = typescriptLS.parseSourceText(fileName, sourceText); // Dump source text (as JS comments) var indentStr = " "; var text = "{\r\n"; text += indentStr; text += addKey("sourceText"); text += ": [\r\n"; for (var i = 1; i < script.locationInfo.lineMap.length; i++) { if (i > 1) {
var start = script.locationInfo.lineMap[i]; var end = (i < script.locationInfo.lineMap.length - 1 ? script.locationInfo.lineMap[i + 1] : sourceText.getLength()); text += indentStr + indentStr + JSON2.stringify(sourceText.getText(start, end)); } text += "],"; text += "\r\n"; // Dump source locations (as JSON entries) text += indentStr; text += addKey("ast"); text += ":\r\n"; var entry = createDumpTree(script); text += dumpEntries(entry, 2); text += "\r\n}\r\n"; return text; } export function compareDumpFilesWithBaseline() { var typescriptLS = new Harness.TypeScriptLS(); var fileNames = getExistingTestCodeFileNames(); for (var i = 0; i < fileNames.length; i++) { var fileName = switchToForwardSlashes(fileNames[i]); var nameOnly = fileName.substr(fileName.lastIndexOf('/') + 1); var run = (fn) => { Harness.Baseline.runBaseline('AST data for ' + fn, nameOnly.replace(/\.ts/, '.ast'), function () { return createDumpContentForFile(typescriptLS, fn); } ); } run(fileName); } } }
text += ",\r\n"; }
conditional_block
txtPipe.ts
import * as fs from "fs-extra"; import { IPipe, IPipeItems } from "../interfaces"; export interface ITxtPipeOpts { name: string; path: string; items: IPipeItems; } class TxtPipe { public name: string; public items: IPipeItems; private stream: fs.WriteStream; private isFirst: boolean; constructor(opts: ITxtPipeOpts) { this.name = opts.name; this.items = opts.items; this.stream = fs.createWriteStream(opts.path); this.isFirst = true; } /** * 根据表头写入新数据 * @param {Object} data */ public write(data: any[]) { let chunk =
this.stream.end(); } } export default function txtPipe(opts: ITxtPipeOpts): IPipe { return new TxtPipe(opts); }
""; if (this.isFirst) { this.isFirst = false; const headers = (Array.isArray(this.items)) ? this.items : Object.keys(this.items); chunk += headers.reduce((str, c) => `${str}\t${c}`) + "\n"; } chunk += data.reduce((str, c) => `${str}\t${c}`) + "\n"; this.stream.write(chunk); } public end() {
identifier_body
txtPipe.ts
import * as fs from "fs-extra"; import { IPipe, IPipeItems } from "../interfaces"; export interface ITxtPipeOpts { name: string; path: string; items: IPipeItems; } class TxtPipe { public name: string; public items: IPipeItems; private stream: fs.WriteStream; private isFirst: boolean; constructor(opts: ITxtPipeOpts) { this.name = opts.name; this.items = opts.items; this.stream = fs.createWriteStream(opts.path); this.isFirst = true; } /** * 根据表头写入新数据 * @param {Object} data */ public write(data: any[]) { let chunk = ""; if (this.isFirst) { this.isFir
.reduce((str, c) => `${str}\t${c}`) + "\n"; this.stream.write(chunk); } public end() { this.stream.end(); } } export default function txtPipe(opts: ITxtPipeOpts): IPipe { return new TxtPipe(opts); }
st = false; const headers = (Array.isArray(this.items)) ? this.items : Object.keys(this.items); chunk += headers.reduce((str, c) => `${str}\t${c}`) + "\n"; } chunk += data
conditional_block
txtPipe.ts
import * as fs from "fs-extra"; import { IPipe, IPipeItems } from "../interfaces"; export interface ITxtPipeOpts { name: string; path: string; items: IPipeItems; } class
{ public name: string; public items: IPipeItems; private stream: fs.WriteStream; private isFirst: boolean; constructor(opts: ITxtPipeOpts) { this.name = opts.name; this.items = opts.items; this.stream = fs.createWriteStream(opts.path); this.isFirst = true; } /** * 根据表头写入新数据 * @param {Object} data */ public write(data: any[]) { let chunk = ""; if (this.isFirst) { this.isFirst = false; const headers = (Array.isArray(this.items)) ? this.items : Object.keys(this.items); chunk += headers.reduce((str, c) => `${str}\t${c}`) + "\n"; } chunk += data.reduce((str, c) => `${str}\t${c}`) + "\n"; this.stream.write(chunk); } public end() { this.stream.end(); } } export default function txtPipe(opts: ITxtPipeOpts): IPipe { return new TxtPipe(opts); }
TxtPipe
identifier_name
txtPipe.ts
import * as fs from "fs-extra"; import { IPipe, IPipeItems } from "../interfaces";
name: string; path: string; items: IPipeItems; } class TxtPipe { public name: string; public items: IPipeItems; private stream: fs.WriteStream; private isFirst: boolean; constructor(opts: ITxtPipeOpts) { this.name = opts.name; this.items = opts.items; this.stream = fs.createWriteStream(opts.path); this.isFirst = true; } /** * 根据表头写入新数据 * @param {Object} data */ public write(data: any[]) { let chunk = ""; if (this.isFirst) { this.isFirst = false; const headers = (Array.isArray(this.items)) ? this.items : Object.keys(this.items); chunk += headers.reduce((str, c) => `${str}\t${c}`) + "\n"; } chunk += data.reduce((str, c) => `${str}\t${c}`) + "\n"; this.stream.write(chunk); } public end() { this.stream.end(); } } export default function txtPipe(opts: ITxtPipeOpts): IPipe { return new TxtPipe(opts); }
export interface ITxtPipeOpts {
random_line_split
data.ioos.us-pycsw.py
# coding: utf-8 # # Query `apiso:ServiceType` # In[43]: from owslib.csw import CatalogueServiceWeb from owslib import fes import numpy as np # The GetCaps request for these services looks like this: # http://catalog.data.gov/csw-all/csw?SERVICE=CSW&VERSION=2.0.2&REQUEST=GetCapabilities # In[56]: endpoint = 'http://data.ioos.us/csw' # FAILS apiso:ServiceType #endpoint = 'http://catalog.data.gov/csw-all' # FAILS apiso:ServiceType #endpoint = 'http://geoport.whoi.edu/csw' # SUCCEEDS apiso:ServiceType csw = CatalogueServiceWeb(endpoint,timeout=60) print csw.version # In[57]: csw.get_operation_by_name('GetRecords').constraints # Search first for records containing the text "COAWST" and "experimental". # In[45]: val = 'coawst' filter1 = fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val), escapeChar='\\',wildCard='*',singleChar='?') filter_list = [ filter1 ] # In[46]: val = 'experimental' filter2 = fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val), escapeChar='\\',wildCard='*',singleChar='?') filter_list = [fes.And([filter1, filter2])] # In[47]: csw.getrecords2(constraints=filter_list,maxrecords=100,esn='full') print len(csw.records.keys()) for rec in list(csw.records.keys()): print csw.records[rec].title # Now let's print out the references (service endpoints) to see what types of services are available # In[48]: choice=np.random.choice(list(csw.records.keys())) print(csw.records[choice].title) csw.records[choice].references # In[49]: csw.records[choice].xml # We see that the `OPeNDAP` service is available, so let's see if we can add that to the query, returning only datasets that have text "COAWST" and "experimental" and that have an "opendap" service available. # # We should get the same number of records, as all COAWST records have OPeNDAP service endpoints. If we get no records, something is wrong with the CSW server.
escapeChar='\\',wildCard='*',singleChar='?') filter_list = [fes.And([filter1, filter2, filter3])] csw.getrecords2(constraints=filter_list, maxrecords=1000) # In[51]: print(len(csw.records.keys())) for rec in list(csw.records.keys()): print('title:'+csw.records[rec].title) print('identifier:'+csw.records[rec].identifier) print('modified:'+csw.records[rec].modified) print(' ') # In[53]: print(csw.request) # In[ ]:
# In[50]: val = 'OPeNDAP' filter3 = fes.PropertyIsLike(propertyname='apiso:ServiceType',literal=('*%s*' % val),
random_line_split
data.ioos.us-pycsw.py
# coding: utf-8 # # Query `apiso:ServiceType` # In[43]: from owslib.csw import CatalogueServiceWeb from owslib import fes import numpy as np # The GetCaps request for these services looks like this: # http://catalog.data.gov/csw-all/csw?SERVICE=CSW&VERSION=2.0.2&REQUEST=GetCapabilities # In[56]: endpoint = 'http://data.ioos.us/csw' # FAILS apiso:ServiceType #endpoint = 'http://catalog.data.gov/csw-all' # FAILS apiso:ServiceType #endpoint = 'http://geoport.whoi.edu/csw' # SUCCEEDS apiso:ServiceType csw = CatalogueServiceWeb(endpoint,timeout=60) print csw.version # In[57]: csw.get_operation_by_name('GetRecords').constraints # Search first for records containing the text "COAWST" and "experimental". # In[45]: val = 'coawst' filter1 = fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val), escapeChar='\\',wildCard='*',singleChar='?') filter_list = [ filter1 ] # In[46]: val = 'experimental' filter2 = fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val), escapeChar='\\',wildCard='*',singleChar='?') filter_list = [fes.And([filter1, filter2])] # In[47]: csw.getrecords2(constraints=filter_list,maxrecords=100,esn='full') print len(csw.records.keys()) for rec in list(csw.records.keys()):
# Now let's print out the references (service endpoints) to see what types of services are available # In[48]: choice=np.random.choice(list(csw.records.keys())) print(csw.records[choice].title) csw.records[choice].references # In[49]: csw.records[choice].xml # We see that the `OPeNDAP` service is available, so let's see if we can add that to the query, returning only datasets that have text "COAWST" and "experimental" and that have an "opendap" service available. # # We should get the same number of records, as all COAWST records have OPeNDAP service endpoints. If we get no records, something is wrong with the CSW server. # In[50]: val = 'OPeNDAP' filter3 = fes.PropertyIsLike(propertyname='apiso:ServiceType',literal=('*%s*' % val), escapeChar='\\',wildCard='*',singleChar='?') filter_list = [fes.And([filter1, filter2, filter3])] csw.getrecords2(constraints=filter_list, maxrecords=1000) # In[51]: print(len(csw.records.keys())) for rec in list(csw.records.keys()): print('title:'+csw.records[rec].title) print('identifier:'+csw.records[rec].identifier) print('modified:'+csw.records[rec].modified) print(' ') # In[53]: print(csw.request) # In[ ]:
print csw.records[rec].title
conditional_block
test_auto_ApplyTOPUP.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..epi import ApplyTOPUP def test_ApplyTOPUP_inputs(): input_map = dict(args=dict(argstr='%s', ), datatype=dict(argstr='-d=%s', ), encoding_file=dict(argstr='--datain=%s', mandatory=True, ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), in_files=dict(argstr='--imain=%s', mandatory=True, sep=',', ), in_index=dict(argstr='--inindex=%s', sep=',', ), in_topup_fieldcoef=dict(argstr='--topup=%s', copyfile=False, requires=['in_topup_movpar'], ), in_topup_movpar=dict(copyfile=False, requires=['in_topup_fieldcoef'], ), interp=dict(argstr='--interp=%s', ), method=dict(argstr='--method=%s', ), out_corrected=dict(argstr='--out=%s', name_source=['in_files'], name_template='%s_corrected', ), output_type=dict(), terminal_output=dict(deprecated='1.0.0', nohash=True, ), ) inputs = ApplyTOPUP.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value
def test_ApplyTOPUP_outputs(): output_map = dict(out_corrected=dict(), ) outputs = ApplyTOPUP.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
random_line_split
test_auto_ApplyTOPUP.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..epi import ApplyTOPUP def test_ApplyTOPUP_inputs(): input_map = dict(args=dict(argstr='%s', ), datatype=dict(argstr='-d=%s', ), encoding_file=dict(argstr='--datain=%s', mandatory=True, ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), in_files=dict(argstr='--imain=%s', mandatory=True, sep=',', ), in_index=dict(argstr='--inindex=%s', sep=',', ), in_topup_fieldcoef=dict(argstr='--topup=%s', copyfile=False, requires=['in_topup_movpar'], ), in_topup_movpar=dict(copyfile=False, requires=['in_topup_fieldcoef'], ), interp=dict(argstr='--interp=%s', ), method=dict(argstr='--method=%s', ), out_corrected=dict(argstr='--out=%s', name_source=['in_files'], name_template='%s_corrected', ), output_type=dict(), terminal_output=dict(deprecated='1.0.0', nohash=True, ), ) inputs = ApplyTOPUP.input_spec() for key, metadata in list(input_map.items()):
def test_ApplyTOPUP_outputs(): output_map = dict(out_corrected=dict(), ) outputs = ApplyTOPUP.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value
conditional_block
test_auto_ApplyTOPUP.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..epi import ApplyTOPUP def test_ApplyTOPUP_inputs():
def test_ApplyTOPUP_outputs(): output_map = dict(out_corrected=dict(), ) outputs = ApplyTOPUP.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
input_map = dict(args=dict(argstr='%s', ), datatype=dict(argstr='-d=%s', ), encoding_file=dict(argstr='--datain=%s', mandatory=True, ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), in_files=dict(argstr='--imain=%s', mandatory=True, sep=',', ), in_index=dict(argstr='--inindex=%s', sep=',', ), in_topup_fieldcoef=dict(argstr='--topup=%s', copyfile=False, requires=['in_topup_movpar'], ), in_topup_movpar=dict(copyfile=False, requires=['in_topup_fieldcoef'], ), interp=dict(argstr='--interp=%s', ), method=dict(argstr='--method=%s', ), out_corrected=dict(argstr='--out=%s', name_source=['in_files'], name_template='%s_corrected', ), output_type=dict(), terminal_output=dict(deprecated='1.0.0', nohash=True, ), ) inputs = ApplyTOPUP.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value
identifier_body
test_auto_ApplyTOPUP.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..epi import ApplyTOPUP def
(): input_map = dict(args=dict(argstr='%s', ), datatype=dict(argstr='-d=%s', ), encoding_file=dict(argstr='--datain=%s', mandatory=True, ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), in_files=dict(argstr='--imain=%s', mandatory=True, sep=',', ), in_index=dict(argstr='--inindex=%s', sep=',', ), in_topup_fieldcoef=dict(argstr='--topup=%s', copyfile=False, requires=['in_topup_movpar'], ), in_topup_movpar=dict(copyfile=False, requires=['in_topup_fieldcoef'], ), interp=dict(argstr='--interp=%s', ), method=dict(argstr='--method=%s', ), out_corrected=dict(argstr='--out=%s', name_source=['in_files'], name_template='%s_corrected', ), output_type=dict(), terminal_output=dict(deprecated='1.0.0', nohash=True, ), ) inputs = ApplyTOPUP.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value def test_ApplyTOPUP_outputs(): output_map = dict(out_corrected=dict(), ) outputs = ApplyTOPUP.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
test_ApplyTOPUP_inputs
identifier_name
preprocess_trace.py
#! /usr/bin/env python # Copyright (c) 2014 Quanta Research Cambridge, Inc # Original author John Ankcorn # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # 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. from __future__ import print_function import sys print('preprocess_trace.py:', sys.argv) cppind = [] bsvind = [] for filename in sys.argv[2:]: data = open(filename).readlines() hasdisplay = False hasdispind = False for line in data: if line.find('$display') >= 0: hasdisplay = True if line.find('printfInd') >= 0: hasdispind = True if hasdisplay and hasdispind: fname = sys.argv[1] + '/generatedbsv/' + filename fh = open(fname, 'w') for line in data: ind = line.find('$display') if ind >= 0: param = line[ind+8:].strip()[1:][:-2].strip() formatstr = '' pitem = '' level = 0 informat = True pactual = [] for ch in param[1:]: if informat: if ch == '"': if level == 0: informat = False else: formatstr = formatstr + ch elif ch == ',': if pitem != '': pactual.append(pitem.strip()) pitem = '' else: pitem = pitem + ch pactual.append(pitem.strip()) freplace = 'printfind_' lastch = '' plist = [] for ch in formatstr: if lastch == '%': if ch == 'x': plist.append('Bit#(32)') else: print('unknown format char', ch) if ch == '-':
lastch = ch line = line[:ind] + 'printfInd.' + freplace + '(' + ','.join(pactual) + ');\n' pformal = '' pactual = '' pbsv = '' pcount = 1 for item in plist: if pcount > 1: pformal = pformal + ', ' pactual = pactual + ', ' pbsv = pbsv + ', ' pvar = 'v%d' % pcount pcount = pcount + 1 if item == 'Bit#(32)': pformal = pformal + 'uint32_t ' + pvar pactual = pactual + pvar pbsv = pbsv + item + ' ' + pvar cppind.append(' void ' + freplace + '(' + pformal + ') { printf("' + formatstr + '\\n", ' + pactual + '); }\n') bsvind.append(' method Action ' + freplace + '(' + pbsv + ');\n') fh.write(line) fh.close() if cppind != []: fname = sys.argv[1] + '/jni/printfInd.h' fh = open(fname, 'w') fh.write('class DisplayInd : public DisplayIndWrapper\n') fh.write('{\n') fh.write('public:\n') fh.write(' DisplayInd(unsigned int id, PortalPoller *poller) : DisplayIndWrapper(id, poller) {}\n') for item in cppind: fh.write(item) fh.write('};\n') fh.close() if bsvind != []: fname = sys.argv[1] + '/generatedbsv/DisplayInd.bsv' fh = open(fname, 'w') fh.write('interface DisplayInd;\n') for item in bsvind: fh.write(item) fh.write('endinterface\n') fh.close() sys.exit(0)
freplace = freplace + '__' elif (ch >= 'A' and ch <= 'Z') or (ch >= 'a' and ch <= 'z') or (ch >= '0' and ch <= '9'): freplace = freplace + ch else: freplace = freplace + '_' + '{:02x}'.format(ord(ch))
random_line_split
preprocess_trace.py
#! /usr/bin/env python # Copyright (c) 2014 Quanta Research Cambridge, Inc # Original author John Ankcorn # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # 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. from __future__ import print_function import sys print('preprocess_trace.py:', sys.argv) cppind = [] bsvind = [] for filename in sys.argv[2:]: data = open(filename).readlines() hasdisplay = False hasdispind = False for line in data: if line.find('$display') >= 0: hasdisplay = True if line.find('printfInd') >= 0: hasdispind = True if hasdisplay and hasdispind: fname = sys.argv[1] + '/generatedbsv/' + filename fh = open(fname, 'w') for line in data: ind = line.find('$display') if ind >= 0: param = line[ind+8:].strip()[1:][:-2].strip() formatstr = '' pitem = '' level = 0 informat = True pactual = [] for ch in param[1:]: if informat: if ch == '"': if level == 0:
else: formatstr = formatstr + ch elif ch == ',': if pitem != '': pactual.append(pitem.strip()) pitem = '' else: pitem = pitem + ch pactual.append(pitem.strip()) freplace = 'printfind_' lastch = '' plist = [] for ch in formatstr: if lastch == '%': if ch == 'x': plist.append('Bit#(32)') else: print('unknown format char', ch) if ch == '-': freplace = freplace + '__' elif (ch >= 'A' and ch <= 'Z') or (ch >= 'a' and ch <= 'z') or (ch >= '0' and ch <= '9'): freplace = freplace + ch else: freplace = freplace + '_' + '{:02x}'.format(ord(ch)) lastch = ch line = line[:ind] + 'printfInd.' + freplace + '(' + ','.join(pactual) + ');\n' pformal = '' pactual = '' pbsv = '' pcount = 1 for item in plist: if pcount > 1: pformal = pformal + ', ' pactual = pactual + ', ' pbsv = pbsv + ', ' pvar = 'v%d' % pcount pcount = pcount + 1 if item == 'Bit#(32)': pformal = pformal + 'uint32_t ' + pvar pactual = pactual + pvar pbsv = pbsv + item + ' ' + pvar cppind.append(' void ' + freplace + '(' + pformal + ') { printf("' + formatstr + '\\n", ' + pactual + '); }\n') bsvind.append(' method Action ' + freplace + '(' + pbsv + ');\n') fh.write(line) fh.close() if cppind != []: fname = sys.argv[1] + '/jni/printfInd.h' fh = open(fname, 'w') fh.write('class DisplayInd : public DisplayIndWrapper\n') fh.write('{\n') fh.write('public:\n') fh.write(' DisplayInd(unsigned int id, PortalPoller *poller) : DisplayIndWrapper(id, poller) {}\n') for item in cppind: fh.write(item) fh.write('};\n') fh.close() if bsvind != []: fname = sys.argv[1] + '/generatedbsv/DisplayInd.bsv' fh = open(fname, 'w') fh.write('interface DisplayInd;\n') for item in bsvind: fh.write(item) fh.write('endinterface\n') fh.close() sys.exit(0)
informat = False
conditional_block
inline-nested.tsx
/** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../../../..' export const input = ( <editor> <block> one <inline> two<inline>three</inline>four </inline> five </block> </editor> ) export const test = editor => {
} export const output = [ [input, []], [ <block> one <inline> two<inline>three</inline>four </inline> five </block>, [0], ], [<text>one</text>, [0, 0]], [ <inline> two<inline>three</inline>four </inline>, [0, 1], ], [<text>two</text>, [0, 1, 0]], [<inline>three</inline>, [0, 1, 1]], [<text>three</text>, [0, 1, 1, 0]], [<text>four</text>, [0, 1, 2]], [<text>five</text>, [0, 2]], ]
return Array.from(Editor.nodes(editor, { at: [] }))
random_line_split
or-patterns-syntactic-fail.rs
// Test some cases where or-patterns may ostensibly be allowed but are in fact not. // This is not a semantic test. We only test parsing. fn
() {} enum E { A, B } use E::*; fn no_top_level_or_patterns() { // We do *not* allow or-patterns at the top level of lambdas... let _ = |A | B: E| (); //~ ERROR no implementation for `E | ()` // -------- This looks like an or-pattern but is in fact `|A| (B: E | ())`. // ...and for now neither do we allow or-patterns at the top level of functions. fn fun1(A | B: E) {} //~^ ERROR top-level or-patterns are not allowed fn fun2(| A | B: E) {} //~^ ERROR top-level or-patterns are not allowed // We don't allow top-level or-patterns before type annotation in let-statements because we // want to reserve this syntactic space for possible future type ascription. let A | B: E = A; //~^ ERROR top-level or-patterns are not allowed let | A | B: E = A; //~^ ERROR top-level or-patterns are not allowed let (A | B): E = A; // ok -- wrapped in parens }
main
identifier_name
or-patterns-syntactic-fail.rs
// Test some cases where or-patterns may ostensibly be allowed but are in fact not. // This is not a semantic test. We only test parsing. fn main() {} enum E { A, B } use E::*; fn no_top_level_or_patterns() { // We do *not* allow or-patterns at the top level of lambdas... let _ = |A | B: E| (); //~ ERROR no implementation for `E | ()` // -------- This looks like an or-pattern but is in fact `|A| (B: E | ())`. // ...and for now neither do we allow or-patterns at the top level of functions. fn fun1(A | B: E)
//~^ ERROR top-level or-patterns are not allowed fn fun2(| A | B: E) {} //~^ ERROR top-level or-patterns are not allowed // We don't allow top-level or-patterns before type annotation in let-statements because we // want to reserve this syntactic space for possible future type ascription. let A | B: E = A; //~^ ERROR top-level or-patterns are not allowed let | A | B: E = A; //~^ ERROR top-level or-patterns are not allowed let (A | B): E = A; // ok -- wrapped in parens }
{}
identifier_body
or-patterns-syntactic-fail.rs
// Test some cases where or-patterns may ostensibly be allowed but are in fact not. // This is not a semantic test. We only test parsing. fn main() {} enum E { A, B }
// We do *not* allow or-patterns at the top level of lambdas... let _ = |A | B: E| (); //~ ERROR no implementation for `E | ()` // -------- This looks like an or-pattern but is in fact `|A| (B: E | ())`. // ...and for now neither do we allow or-patterns at the top level of functions. fn fun1(A | B: E) {} //~^ ERROR top-level or-patterns are not allowed fn fun2(| A | B: E) {} //~^ ERROR top-level or-patterns are not allowed // We don't allow top-level or-patterns before type annotation in let-statements because we // want to reserve this syntactic space for possible future type ascription. let A | B: E = A; //~^ ERROR top-level or-patterns are not allowed let | A | B: E = A; //~^ ERROR top-level or-patterns are not allowed let (A | B): E = A; // ok -- wrapped in parens }
use E::*; fn no_top_level_or_patterns() {
random_line_split
array_slice.rs
// 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. #[macro_use] extern crate criterion; use criterion::Criterion; extern crate arrow; use arrow::array::*; use std::sync::Arc; fn create_array_slice(array: &ArrayRef, length: usize) -> ArrayRef { array.slice(0, length) } fn create_array_with_nulls(size: usize) -> ArrayRef { let array: Float64Array = (0..size) .map(|i| if i % 2 == 0 { Some(1.0) } else
) .collect(); Arc::new(array) } fn array_slice_benchmark(c: &mut Criterion) { let array = create_array_with_nulls(4096); c.bench_function("array_slice 128", |b| { b.iter(|| create_array_slice(&array, 128)) }); c.bench_function("array_slice 512", |b| { b.iter(|| create_array_slice(&array, 512)) }); c.bench_function("array_slice 2048", |b| { b.iter(|| create_array_slice(&array, 2048)) }); } criterion_group!(benches, array_slice_benchmark); criterion_main!(benches);
{ None }
conditional_block
array_slice.rs
// 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. #[macro_use] extern crate criterion; use criterion::Criterion; extern crate arrow; use arrow::array::*; use std::sync::Arc; fn create_array_slice(array: &ArrayRef, length: usize) -> ArrayRef { array.slice(0, length) } fn create_array_with_nulls(size: usize) -> ArrayRef { let array: Float64Array = (0..size) .map(|i| if i % 2 == 0 { Some(1.0) } else { None }) .collect(); Arc::new(array) } fn array_slice_benchmark(c: &mut Criterion) { let array = create_array_with_nulls(4096); c.bench_function("array_slice 128", |b| { b.iter(|| create_array_slice(&array, 128)) }); c.bench_function("array_slice 512", |b| {
}); c.bench_function("array_slice 2048", |b| { b.iter(|| create_array_slice(&array, 2048)) }); } criterion_group!(benches, array_slice_benchmark); criterion_main!(benches);
b.iter(|| create_array_slice(&array, 512))
random_line_split
array_slice.rs
// 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. #[macro_use] extern crate criterion; use criterion::Criterion; extern crate arrow; use arrow::array::*; use std::sync::Arc; fn create_array_slice(array: &ArrayRef, length: usize) -> ArrayRef
fn create_array_with_nulls(size: usize) -> ArrayRef { let array: Float64Array = (0..size) .map(|i| if i % 2 == 0 { Some(1.0) } else { None }) .collect(); Arc::new(array) } fn array_slice_benchmark(c: &mut Criterion) { let array = create_array_with_nulls(4096); c.bench_function("array_slice 128", |b| { b.iter(|| create_array_slice(&array, 128)) }); c.bench_function("array_slice 512", |b| { b.iter(|| create_array_slice(&array, 512)) }); c.bench_function("array_slice 2048", |b| { b.iter(|| create_array_slice(&array, 2048)) }); } criterion_group!(benches, array_slice_benchmark); criterion_main!(benches);
{ array.slice(0, length) }
identifier_body
array_slice.rs
// 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. #[macro_use] extern crate criterion; use criterion::Criterion; extern crate arrow; use arrow::array::*; use std::sync::Arc; fn create_array_slice(array: &ArrayRef, length: usize) -> ArrayRef { array.slice(0, length) } fn create_array_with_nulls(size: usize) -> ArrayRef { let array: Float64Array = (0..size) .map(|i| if i % 2 == 0 { Some(1.0) } else { None }) .collect(); Arc::new(array) } fn
(c: &mut Criterion) { let array = create_array_with_nulls(4096); c.bench_function("array_slice 128", |b| { b.iter(|| create_array_slice(&array, 128)) }); c.bench_function("array_slice 512", |b| { b.iter(|| create_array_slice(&array, 512)) }); c.bench_function("array_slice 2048", |b| { b.iter(|| create_array_slice(&array, 2048)) }); } criterion_group!(benches, array_slice_benchmark); criterion_main!(benches);
array_slice_benchmark
identifier_name
vscode-vim.d.ts
interface IEditor { // Status CloseCommandStatus(); ShowCommandStatus(text: string); ShowModeStatus(mode: Mode); SetModeStatusVisibility(visible: boolean); // Edit InsertTextAtCurrentPosition(text: string); Insert(position: IPosition, text: string); DeleteRange(range: IRange); ReplaceRange(range: IRange, text: string); // Read Line ReadLineAtCurrentPosition(): string; ReadLine(line: number): string; // Read Range ReadRange(range: IRange): string; // Position GetCurrentPosition(): IPosition; SetPosition(position: IPosition); GetLastPosition(): IPosition; // Document Info GetLastLineNum(): number; dispose(): void; } interface IVSCodeEditorOptions { showMode?: boolean; } interface ICommandFactory { PushKey(key: Key): IAction; Clear(): void; GetCommandString(): string; } interface IMotion { SetCount(count: number); CalculateSelectionRange(editor: IEditor, start: IPosition): IRange; CalculateEnd(editor: IEditor, start: IPosition): IPosition; } interface IRegisterItem { Type: RegisterType; Body: string; } interface IRegister { Set(key: Key, value: IRegisterItem): void; SetYank(value: IRegisterItem): void; SetRoll(value: IRegisterItem): void; Get(key: Key): IRegisterItem; GetUnName(): IRegisterItem; GetRollFirst(value: IRegisterItem): IRegisterItem; } interface IPosition { line: number; char: number; IsEqual(position: IPosition): boolean; } interface IRange { start: IPosition; end: IPosition; Sort(): void; } interface IAction { Execute(editor: IEditor, vim: IVimStyle); } interface IRequireMotionAction extends IAction { SetMotion(motion: IMotion); SetLineOption(); SetSmallOption(); } interface IMotion {
interface IVimStyle { Register: IRegister; PushKey(key: Key): void; PushEscKey(): void; ApplyInsertMode(): void; } declare const enum Key { a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, Space, Exclamation, Quotation, Doller, Sharp, Percent, Ampersand, Apostrophe, LeftParenthesis, RightParenthesis, Asterisk, Plus, Comma, Hyphen, Period, Solidus, Colon, Semicolon, LessThan, Equals, GreaterThan, Question, AtMark, LeftSquareBracket, ReverseSolidus, RightSquareBracket, CircumflexAccent, LowLine, GraveAccent, LeftCurlyBracket, VerticalLine, RightCurlyBracket, Tilde, Esc } declare const enum KeyType { Number, Charactor, Mark } declare const enum RegisterType { Text, LineText } declare const enum ActionType { Combination, Delete, FirstInsert, Insert, Move, Paste } declare const enum Direction { Right, Left } declare const enum CharGroup { AlphabetAndNumber, Marks, Spaces, Hiragana, Katakana, Other } declare const enum CommandStatus { None, FirstNum, RequireMotion, RequireMotionNum, RequireCharForMotion } declare const enum KeyClass { // 1 2 3 4 5 6 7 8 9 NumWithoutZero, // 0 Zero, // w b h j k l $ Motion, // x s I A p P C D S SingleAction, // i a TextObjectOrSingleAction, // d y c RequireMotionAction, // f t F T RequireCharMotion } declare const enum Mode { Normal, Insert }
SetCount(count: number); CalculateEnd(editor: IEditor, start: IPosition): IPosition; }
random_line_split
urls.py
from cl.api import views from cl.audio import api_views as audio_views from cl.people_db import api_views as judge_views from cl.search import api_views as search_views from django.conf.urls import url, include
router.register(r'dockets', search_views.DocketViewSet) router.register(r'courts', search_views.CourtViewSet) router.register(r'audio', audio_views.AudioViewSet) router.register(r'clusters', search_views.OpinionClusterViewSet) router.register(r'opinions', search_views.OpinionViewSet) router.register(r'opinions-cited', search_views.OpinionsCitedViewSet) router.register(r'search', search_views.SearchViewSet, base_name='search') # Judges router.register(r'people', judge_views.PersonViewSet) router.register(r'positions', judge_views.PositionViewSet) router.register(r'retention-events', judge_views.RetentionEventViewSet) router.register(r'educations', judge_views.EducationViewSet) router.register(r'schools', judge_views.SchoolViewSet) router.register(r'political-affiliations', judge_views.PoliticalAffiliationViewSet) router.register(r'sources', judge_views.SourceViewSet) router.register(r'aba-ratings', judge_views.ABARatingViewSet) urlpatterns = [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/rest/(?P<version>[v3]+)/', include(router.urls)), # Documentation url(r'^api/$', views.api_index, name='api_index'), url(r'^api/jurisdictions/$', views.court_index, name='court_index'), url(r'^api/rest-info/(?P<version>v[123])?/?$', views.rest_docs, name='rest_docs'), url(r'^api/bulk-info/$', views.bulk_data_index, name='bulk_data_index'), url(r'^api/rest/v(?P<version>[123])/coverage/(?P<court>.+)/$', views.coverage_data, name='coverage_data'), # Pagerank file url(r'^api/bulk/external_pagerank/$', views.serve_pagerank_file, name='pagerank_file'), # Deprecation Dates: # v1: 2016-04-01 # v2: 2016-04-01 url(r'^api/rest/v(?P<v>[12])/.*', views.deprecated_api, name='deprecated_api'), ]
from rest_framework.routers import DefaultRouter router = DefaultRouter() # Search & Audio
random_line_split
sha256_bench.rs
#![cfg_attr(all(feature = "nightly", test), feature(test))] #![cfg(all(feature = "nightly", test))] extern crate test; extern crate cxema; #[cfg(test)] use cxema::sha2::{Sha256}; use cxema::digest::Digest; use test::Bencher; #[bench] pub fn sha256_10(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 10]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn
(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 1024]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn sha256_64k(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 65536]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; }
sha256_1k
identifier_name
sha256_bench.rs
#![cfg_attr(all(feature = "nightly", test), feature(test))] #![cfg(all(feature = "nightly", test))] extern crate test; extern crate cxema; #[cfg(test)] use cxema::sha2::{Sha256}; use cxema::digest::Digest; use test::Bencher; #[bench] pub fn sha256_10(bh: &mut Bencher) { let mut sh = Sha256::new();
bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn sha256_1k(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 1024]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn sha256_64k(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 65536]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; }
let bytes = [1u8; 10];
random_line_split
sha256_bench.rs
#![cfg_attr(all(feature = "nightly", test), feature(test))] #![cfg(all(feature = "nightly", test))] extern crate test; extern crate cxema; #[cfg(test)] use cxema::sha2::{Sha256}; use cxema::digest::Digest; use test::Bencher; #[bench] pub fn sha256_10(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 10]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn sha256_1k(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 1024]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn sha256_64k(bh: &mut Bencher)
{ let mut sh = Sha256::new(); let bytes = [1u8; 65536]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; }
identifier_body
ngx-admin-lte.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { ToastrModule, ToastrService } from 'ngx-toastr'; // import ngx-translate and the http loader import {TranslateLoader, TranslateModule} from '@ngx-translate/core'; import {TranslateHttpLoader} from '@ngx-translate/http-loader'; import {HttpClient, HttpClientModule} from '@angular/common/http'; // AoT requires an exported function for factories export function HttpLoaderFactory (httpClient)
// Pipes import { SafeHtmlPipe } from './pipes/safe-html.pipes'; // Widgets import { AppHeaderComponent } from './widgets/app-header/app-header.component'; import { LogoComponent } from './widgets/logo/logo.component'; import { AppFooterComponent } from './widgets/app-footer/app-footer.component'; import { MenuAsideComponent } from './widgets/menu-aside/menu-aside.component'; import { ControlSidebarComponent } from './widgets/control-sidebar/control-sidebar.component'; import { MessagesBoxComponent } from './widgets/messages-box/messages-box.component'; import { NotificationBoxComponent } from './widgets/notification-box/notification-box.component'; import { TasksBoxComponent } from './widgets/tasks-box/tasks-box.component'; import { UserBoxComponent } from './widgets/user-box/user-box.component'; import { BreadcrumbComponent } from './widgets/breadcrumb/breadcrumb.component'; import { ComponentLoaderComponent } from './widgets/component-loader/component-loader.component'; // Services import { UserService } from './services/user.service'; import { MenuService } from './services/menu.service'; import { LogoService } from './services/logo.service'; import { FooterService } from './services/footer.service'; import { MessagesService } from './services/messages.service'; import { CanActivateGuard } from './services/can-activate-guard.service'; import { NotificationsService } from './services/notifications.service'; import { BreadcrumbService } from './services/breadcrumb.service'; import { TranslateService } from './services/translate.service'; import { LoggerService } from './services/logger.service'; import { ControlSidebarService } from './services/control-sidebar.service'; // Layouts import { LayoutAuthComponent } from './layouts/auth/auth'; import { LayoutLoginComponent } from './layouts/login/login.component'; import { LayoutRegisterComponent } from './layouts/register/register.component'; @NgModule({ declarations: [ // PIPES SafeHtmlPipe, // WIDGETS BreadcrumbComponent, AppHeaderComponent, LogoComponent, AppFooterComponent, MenuAsideComponent, ControlSidebarComponent, MessagesBoxComponent, NotificationBoxComponent, TasksBoxComponent, UserBoxComponent, ComponentLoaderComponent, // LAYOUTS LayoutAuthComponent, LayoutLoginComponent, LayoutRegisterComponent ], imports: [ BrowserModule, RouterModule, ToastrModule.forRoot({ timeOut: 10000, positionClass: 'toast-top-right', preventDuplicates: true, tapToDismiss: false, newestOnTop: true }), HttpClientModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }), ], exports: [ SafeHtmlPipe, ], providers: [ // SERVICES UserService, MenuService, LogoService, FooterService, BreadcrumbService, MessagesService, CanActivateGuard, NotificationsService, TranslateService, LoggerService, ControlSidebarService, ToastrService ] }) export class NgxAdminLteModule { }
{ return new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json'); }
identifier_body
ngx-admin-lte.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { ToastrModule, ToastrService } from 'ngx-toastr'; // import ngx-translate and the http loader import {TranslateLoader, TranslateModule} from '@ngx-translate/core'; import {TranslateHttpLoader} from '@ngx-translate/http-loader'; import {HttpClient, HttpClientModule} from '@angular/common/http'; // AoT requires an exported function for factories export function HttpLoaderFactory (httpClient) { return new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json'); } // Pipes import { SafeHtmlPipe } from './pipes/safe-html.pipes'; // Widgets import { AppHeaderComponent } from './widgets/app-header/app-header.component'; import { LogoComponent } from './widgets/logo/logo.component'; import { AppFooterComponent } from './widgets/app-footer/app-footer.component'; import { MenuAsideComponent } from './widgets/menu-aside/menu-aside.component'; import { ControlSidebarComponent } from './widgets/control-sidebar/control-sidebar.component'; import { MessagesBoxComponent } from './widgets/messages-box/messages-box.component'; import { NotificationBoxComponent } from './widgets/notification-box/notification-box.component'; import { TasksBoxComponent } from './widgets/tasks-box/tasks-box.component'; import { UserBoxComponent } from './widgets/user-box/user-box.component'; import { BreadcrumbComponent } from './widgets/breadcrumb/breadcrumb.component'; import { ComponentLoaderComponent } from './widgets/component-loader/component-loader.component'; // Services import { UserService } from './services/user.service'; import { MenuService } from './services/menu.service'; import { LogoService } from './services/logo.service'; import { FooterService } from './services/footer.service'; import { MessagesService } from './services/messages.service'; import { CanActivateGuard } from './services/can-activate-guard.service'; import { NotificationsService } from './services/notifications.service'; import { BreadcrumbService } from './services/breadcrumb.service'; import { TranslateService } from './services/translate.service'; import { LoggerService } from './services/logger.service'; import { ControlSidebarService } from './services/control-sidebar.service'; // Layouts import { LayoutAuthComponent } from './layouts/auth/auth'; import { LayoutLoginComponent } from './layouts/login/login.component'; import { LayoutRegisterComponent } from './layouts/register/register.component'; @NgModule({ declarations: [ // PIPES SafeHtmlPipe, // WIDGETS BreadcrumbComponent, AppHeaderComponent, LogoComponent, AppFooterComponent, MenuAsideComponent, ControlSidebarComponent, MessagesBoxComponent, NotificationBoxComponent, TasksBoxComponent, UserBoxComponent, ComponentLoaderComponent, // LAYOUTS LayoutAuthComponent, LayoutLoginComponent, LayoutRegisterComponent ], imports: [ BrowserModule, RouterModule, ToastrModule.forRoot({ timeOut: 10000, positionClass: 'toast-top-right', preventDuplicates: true, tapToDismiss: false, newestOnTop: true }), HttpClientModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }), ], exports: [ SafeHtmlPipe, ], providers: [ // SERVICES UserService, MenuService, LogoService,
CanActivateGuard, NotificationsService, TranslateService, LoggerService, ControlSidebarService, ToastrService ] }) export class NgxAdminLteModule { }
FooterService, BreadcrumbService, MessagesService,
random_line_split
ngx-admin-lte.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { ToastrModule, ToastrService } from 'ngx-toastr'; // import ngx-translate and the http loader import {TranslateLoader, TranslateModule} from '@ngx-translate/core'; import {TranslateHttpLoader} from '@ngx-translate/http-loader'; import {HttpClient, HttpClientModule} from '@angular/common/http'; // AoT requires an exported function for factories export function
(httpClient) { return new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json'); } // Pipes import { SafeHtmlPipe } from './pipes/safe-html.pipes'; // Widgets import { AppHeaderComponent } from './widgets/app-header/app-header.component'; import { LogoComponent } from './widgets/logo/logo.component'; import { AppFooterComponent } from './widgets/app-footer/app-footer.component'; import { MenuAsideComponent } from './widgets/menu-aside/menu-aside.component'; import { ControlSidebarComponent } from './widgets/control-sidebar/control-sidebar.component'; import { MessagesBoxComponent } from './widgets/messages-box/messages-box.component'; import { NotificationBoxComponent } from './widgets/notification-box/notification-box.component'; import { TasksBoxComponent } from './widgets/tasks-box/tasks-box.component'; import { UserBoxComponent } from './widgets/user-box/user-box.component'; import { BreadcrumbComponent } from './widgets/breadcrumb/breadcrumb.component'; import { ComponentLoaderComponent } from './widgets/component-loader/component-loader.component'; // Services import { UserService } from './services/user.service'; import { MenuService } from './services/menu.service'; import { LogoService } from './services/logo.service'; import { FooterService } from './services/footer.service'; import { MessagesService } from './services/messages.service'; import { CanActivateGuard } from './services/can-activate-guard.service'; import { NotificationsService } from './services/notifications.service'; import { BreadcrumbService } from './services/breadcrumb.service'; import { TranslateService } from './services/translate.service'; import { LoggerService } from './services/logger.service'; import { ControlSidebarService } from './services/control-sidebar.service'; // Layouts import { LayoutAuthComponent } from './layouts/auth/auth'; import { LayoutLoginComponent } from './layouts/login/login.component'; import { LayoutRegisterComponent } from './layouts/register/register.component'; @NgModule({ declarations: [ // PIPES SafeHtmlPipe, // WIDGETS BreadcrumbComponent, AppHeaderComponent, LogoComponent, AppFooterComponent, MenuAsideComponent, ControlSidebarComponent, MessagesBoxComponent, NotificationBoxComponent, TasksBoxComponent, UserBoxComponent, ComponentLoaderComponent, // LAYOUTS LayoutAuthComponent, LayoutLoginComponent, LayoutRegisterComponent ], imports: [ BrowserModule, RouterModule, ToastrModule.forRoot({ timeOut: 10000, positionClass: 'toast-top-right', preventDuplicates: true, tapToDismiss: false, newestOnTop: true }), HttpClientModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }), ], exports: [ SafeHtmlPipe, ], providers: [ // SERVICES UserService, MenuService, LogoService, FooterService, BreadcrumbService, MessagesService, CanActivateGuard, NotificationsService, TranslateService, LoggerService, ControlSidebarService, ToastrService ] }) export class NgxAdminLteModule { }
HttpLoaderFactory
identifier_name
webpack.config.js
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: { styles: './content/styles/app.scss', image: './content/images/awesome.jpg', app: path.join(__dirname, './src/app.ts'), vendor: ['jquery', 'popper.js', 'bootstrap'] }, output: { filename: '[name].js', path: path.join(__dirname, 'build') }, resolve: { extensions: ['.js', '.ts'] }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify('prod'), VER: JSON.stringify('0.0.0.1') }), new webpack.ProvidePlugin({//need for bootstrap
jQuery: "jquery", tether: 'tether', Tether: 'tether', 'window.Tether': 'tether', 'Popper': 'popper.js' }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity, // (with more entries, this ensures that no other module // goes into the vendor chunk) }), new HtmlWebpackPlugin({ filename: 'index.html', template: 'content/views/index.html', hash: true }), new ExtractTextPlugin('styles.css', { allChunks: true }) ], module: { rules: [{ test: /\.ts$/, loader: 'awesome-typescript-loader', query: { useCache: true } }, { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'resolve-url-loader'] }) }, { test: /\.scss$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', //resolve-url-loader may be chained before sass-loader if necessary use: ['css-loader', 'resolve-url-loader', 'sass-loader'] }) }, { test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/, loader: 'file-loader', options: { name: '[name].[ext]', outputPath: '/fonts/' } }, { test: /\.png|\.jpe?g|\.gif$/, loader: 'file-loader', options: { name: '[name].[ext]', outputPath: '/images/' } }] } };
$: "jquery", jquery: "jquery", "window.jQuery": "jquery",
random_line_split
Tracker.ts
import { Queue } from "../Queue/Queue"; import { EventHandler } from "../Event/Handler/EventHandler"; import { ObjectMerger } from "../Common/ObjectMerger"; export class Tracker { public static get SEND_COMMAND(): string { return "send"; } constructor(private global: any, private eventHandler: EventHandler, private objectMerger: ObjectMerger)
public run() { if (this.global !== undefined) { let dataLayerCallback = this.global; let queue = dataLayerCallback.q; let push = dataLayerCallback.q.push; this.process(new Queue(queue)); queue.push = (...dataLayerElements) => { push.apply(queue, Array.prototype.slice.call(dataLayerElements, 0)); this.process(new Queue(queue)); }; } } private process(queue: Queue) { let dataLayerElementPayload: any = {}; queue.consume((index, dataLayerElement) => { if (dataLayerElement.length >= 2) { dataLayerElementPayload = this.objectMerger.merge(dataLayerElementPayload, dataLayerElement[1]); if (dataLayerElement[0] === Tracker.SEND_COMMAND) { this.global.q.splice(index, 1); this.eventHandler.handle(dataLayerElementPayload); } } }); } }
{}
identifier_body
Tracker.ts
import { Queue } from "../Queue/Queue"; import { EventHandler } from "../Event/Handler/EventHandler"; import { ObjectMerger } from "../Common/ObjectMerger"; export class Tracker { public static get SEND_COMMAND(): string { return "send"; } constructor(private global: any, private eventHandler: EventHandler, private objectMerger: ObjectMerger) {} public run() { if (this.global !== undefined)
} private process(queue: Queue) { let dataLayerElementPayload: any = {}; queue.consume((index, dataLayerElement) => { if (dataLayerElement.length >= 2) { dataLayerElementPayload = this.objectMerger.merge(dataLayerElementPayload, dataLayerElement[1]); if (dataLayerElement[0] === Tracker.SEND_COMMAND) { this.global.q.splice(index, 1); this.eventHandler.handle(dataLayerElementPayload); } } }); } }
{ let dataLayerCallback = this.global; let queue = dataLayerCallback.q; let push = dataLayerCallback.q.push; this.process(new Queue(queue)); queue.push = (...dataLayerElements) => { push.apply(queue, Array.prototype.slice.call(dataLayerElements, 0)); this.process(new Queue(queue)); }; }
conditional_block
Tracker.ts
import { Queue } from "../Queue/Queue"; import { EventHandler } from "../Event/Handler/EventHandler"; import { ObjectMerger } from "../Common/ObjectMerger"; export class Tracker { public static get SEND_COMMAND(): string { return "send"; } constructor(private global: any, private eventHandler: EventHandler, private objectMerger: ObjectMerger) {} public
() { if (this.global !== undefined) { let dataLayerCallback = this.global; let queue = dataLayerCallback.q; let push = dataLayerCallback.q.push; this.process(new Queue(queue)); queue.push = (...dataLayerElements) => { push.apply(queue, Array.prototype.slice.call(dataLayerElements, 0)); this.process(new Queue(queue)); }; } } private process(queue: Queue) { let dataLayerElementPayload: any = {}; queue.consume((index, dataLayerElement) => { if (dataLayerElement.length >= 2) { dataLayerElementPayload = this.objectMerger.merge(dataLayerElementPayload, dataLayerElement[1]); if (dataLayerElement[0] === Tracker.SEND_COMMAND) { this.global.q.splice(index, 1); this.eventHandler.handle(dataLayerElementPayload); } } }); } }
run
identifier_name
Tracker.ts
import { Queue } from "../Queue/Queue"; import { EventHandler } from "../Event/Handler/EventHandler"; import { ObjectMerger } from "../Common/ObjectMerger"; export class Tracker {
public static get SEND_COMMAND(): string { return "send"; } constructor(private global: any, private eventHandler: EventHandler, private objectMerger: ObjectMerger) {} public run() { if (this.global !== undefined) { let dataLayerCallback = this.global; let queue = dataLayerCallback.q; let push = dataLayerCallback.q.push; this.process(new Queue(queue)); queue.push = (...dataLayerElements) => { push.apply(queue, Array.prototype.slice.call(dataLayerElements, 0)); this.process(new Queue(queue)); }; } } private process(queue: Queue) { let dataLayerElementPayload: any = {}; queue.consume((index, dataLayerElement) => { if (dataLayerElement.length >= 2) { dataLayerElementPayload = this.objectMerger.merge(dataLayerElementPayload, dataLayerElement[1]); if (dataLayerElement[0] === Tracker.SEND_COMMAND) { this.global.q.splice(index, 1); this.eventHandler.handle(dataLayerElementPayload); } } }); } }
random_line_split
require-sri-for.js
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var config_1 = __importDefault(require("../../config")); var is_function_1 = __importDefault(require("../../is-function")); module.exports = function requireSriForCheck(key, value) { if (!Array.isArray(value)) { throw new Error("\"" + value + "\" is not a valid value for " + key + ". Use an array of strings."); } if (value.length === 0) { throw new Error(key + " must have at least one value. To require nothing, omit the directive."); } value.forEach(function (expression) { if (is_function_1.default(expression)) { return; } if (config_1.default.requireSriForValues.indexOf(expression) === -1) {
}); };
throw new Error("\"" + expression + "\" is not a valid " + key + " value. Remove it."); }
random_line_split
require-sri-for.js
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var config_1 = __importDefault(require("../../config")); var is_function_1 = __importDefault(require("../../is-function")); module.exports = function requireSriForCheck(key, value) { if (!Array.isArray(value))
if (value.length === 0) { throw new Error(key + " must have at least one value. To require nothing, omit the directive."); } value.forEach(function (expression) { if (is_function_1.default(expression)) { return; } if (config_1.default.requireSriForValues.indexOf(expression) === -1) { throw new Error("\"" + expression + "\" is not a valid " + key + " value. Remove it."); } }); };
{ throw new Error("\"" + value + "\" is not a valid value for " + key + ". Use an array of strings."); }
conditional_block
RadioButton-test.js
import React from 'react'; import RadioButton from '../RadioButton'; import { mount } from 'enzyme'; const render = (props) => mount( <RadioButton {...props} className="extra-class" name="test-name" value="test-value" /> ); describe('RadioButton', () => { describe('renders as expected', () => { const wrapper = render({ checked: true, }); const input = wrapper.find('input'); const label = wrapper.find('label'); const div = wrapper.find('div'); describe('input', () => { it('is of type radio', () => { expect(input.props().type).toEqual('radio'); }); it('has the expected class', () => { expect(input.hasClass('bx--radio-button')).toEqual(true); }); it('has a unique id set by default', () => { expect(input.props().id).toBeDefined(); }); it('should have checked set when checked is passed', () => { wrapper.setProps({ checked: true }); expect(input.props().checked).toEqual(true); }); it('should set the name prop as expected', () => { expect(input.props().name).toEqual('test-name'); }); }); describe('label', () => { it('should set htmlFor', () => { expect(label.props().htmlFor) .toEqual(input.props().id); }); it('should set the correct class', () => { expect(label.props().className).toEqual('bx--radio-button__label'); }); it('should render a span with the correct class', () => { const span = label.find('span'); expect(span.hasClass('bx--radio-button__appearance')).toEqual(true); }); it('should render label text', () => { wrapper.setProps({ labelText: 'test label text' }); expect(label.text()).toMatch(/test label text/); }); }); describe('wrapper', () => { it('should have the correct class', () => { expect(div.hasClass('radioButtonWrapper')).toEqual(true); }); it('should have extra classes applied', () => { expect(div.hasClass('extra-class')).toEqual(true); }); }); }); it('should set defaultChecked as expected', () => { const wrapper = render({ defaultChecked: true, }); const input = wrapper.find('input'); expect(input.props().defaultChecked).toEqual(true); wrapper.setProps({ defaultChecked: false }); expect(input.props().defaultChecked).toEqual(false); }); it('should set id if one is passed in', () => { const wrapper = render({ id: 'unique-id', }); const input = wrapper.find('input'); expect(input.props().id).toEqual('unique-id'); }); describe('events', () => { it('should invoke onChange with expected arguments', () => { const onChange = jest.fn(); const wrapper = render({ onChange }); const input = wrapper.find('input');
const inputElement = input.get(0); inputElement.checked = true; wrapper.find('input').simulate('change'); const call = onChange.mock.calls[0]; expect(call[0]).toEqual('test-value'); expect(call[1]).toEqual('test-name'); expect(call[2].target).toBe(inputElement); }); }); });
random_line_split