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
accessibilityHelp.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./accessibilityHelp'; import * as nls from 'vs/nls'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { Disposable } from 'vs/base/common/lifecycle'; import * as strings from 'vs/base/common/strings'; import * as dom from 'vs/base/browser/dom'; import { renderFormattedText } from 'vs/base/browser/htmlContentRenderer'; import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; import { Widget } from 'vs/base/browser/ui/widget'; import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ICommonCodeEditor, IEditorContribution } from 'vs/editor/common/editorCommon'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { editorAction, CommonEditorRegistry, EditorAction, EditorCommand } from 'vs/editor/common/editorCommonExtensions'; import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { editorContribution } from 'vs/editor/browser/editorBrowserExtensions'; import { ToggleTabFocusModeAction } from 'vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { editorWidgetBackground, widgetShadow, contrastBorder } from 'vs/platform/theme/common/colorRegistry'; import * as platform from 'vs/base/common/platform'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import URI from 'vs/base/common/uri'; import { Selection } from 'vs/editor/common/core/selection'; import * as browser from 'vs/base/browser/browser'; import { IEditorConstructionOptions } from 'vs/editor/standalone/browser/standaloneCodeEditor'; const CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE = new RawContextKey<boolean>('accessibilityHelpWidgetVisible', false); @editorContribution class AccessibilityHelpController extends Disposable implements IEditorContribution { private static ID = 'editor.contrib.accessibilityHelpController'; public static get(editor: ICommonCodeEditor): AccessibilityHelpController { return editor.getContribution<AccessibilityHelpController>( AccessibilityHelpController.ID ); } private _editor: ICodeEditor; private _widget: AccessibilityHelpWidget; constructor( editor: ICodeEditor, @IInstantiationService instantiationService: IInstantiationService ) { super(); this._editor = editor; this._widget = this._register( instantiationService.createInstance(AccessibilityHelpWidget, this._editor) ); } public getId(): string { return AccessibilityHelpController.ID; } public show(): void { this._widget.show(); } public hide(): void { this._widget.hide(); } } const nlsNoSelection = nls.localize("noSelection", "No selection"); const nlsSingleSelectionRange = nls.localize("singleSelectionRange", "Line {0}, Column {1} ({2} selected)"); const nlsSingleSelection = nls.localize("singleSelection", "Line {0}, Column {1}"); const nlsMultiSelectionRange = nls.localize("multiSelectionRange", "{0} selections ({1} characters selected)"); const nlsMultiSelection = nls.localize("multiSelection", "{0} selections"); function getSelectionLabel(selections: Selection[], charactersSelected: number): string { if (!selections || selections.length === 0) { return nlsNoSelection; } if (selections.length === 1) { if (charactersSelected) { return strings.format(nlsSingleSelectionRange, selections[0].positionLineNumber, selections[0].positionColumn, charactersSelected); } return strings.format(nlsSingleSelection, selections[0].positionLineNumber, selections[0].positionColumn); } if (charactersSelected) { return strings.format(nlsMultiSelectionRange, selections.length, charactersSelected); } if (selections.length > 0) { return strings.format(nlsMultiSelection, selections.length); } return null; } class AccessibilityHelpWidget extends Widget implements IOverlayWidget { private static ID = 'editor.contrib.accessibilityHelpWidget'; private static WIDTH = 500; private static HEIGHT = 300; private _editor: ICodeEditor; private _domNode: FastDomNode<HTMLElement>; private _contentDomNode: FastDomNode<HTMLElement>; private _isVisible: boolean; private _isVisibleKey: IContextKey<boolean>; constructor( editor: ICodeEditor, @IContextKeyService private _contextKeyService: IContextKeyService, @IKeybindingService private _keybindingService: IKeybindingService, @IOpenerService private _openerService: IOpenerService ) { super(); this._editor = editor; this._isVisibleKey = CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE.bindTo( this._contextKeyService ); this._domNode = createFastDomNode(document.createElement('div')); this._domNode.setClassName('accessibilityHelpWidget'); this._domNode.setDisplay('none'); this._domNode.setAttribute('role', 'dialog'); this._domNode.setAttribute('aria-hidden', 'true'); this._contentDomNode = createFastDomNode(document.createElement('div')); this._contentDomNode.setAttribute('role', 'document'); this._domNode.appendChild(this._contentDomNode); this._isVisible = false; this._register(this._editor.onDidLayoutChange(() => { if (this._isVisible) { this._layout(); } })); // Intentionally not configurable! this._register(dom.addStandardDisposableListener(this._contentDomNode.domNode, 'keydown', (e) => { if (!this._isVisible) { return; } if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_E)) { alert(nls.localize("emergencyConfOn", "Now changing the setting `accessibilitySupport` to 'on'.")); this._editor.updateOptions({ accessibilitySupport: 'on' }); dom.clearNode(this._contentDomNode.domNode); this._buildContent(); this._contentDomNode.domNode.focus(); e.preventDefault(); e.stopPropagation(); } if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_H)) { alert(nls.localize("openingDocs", "Now opening the Editor Accessibility documentation page.")); let url = (<IEditorConstructionOptions>this._editor.getRawConfiguration()).accessibilityHelpUrl; if (typeof url === 'undefined') { url = 'https://go.microsoft.com/fwlink/?linkid=852450'; } this._openerService.open(URI.parse(url)); e.preventDefault(); e.stopPropagation(); } })); this.onblur(this._contentDomNode.domNode, () => { this.hide(); }); this._editor.addOverlayWidget(this); } public dispose(): void { this._editor.removeOverlayWidget(this); super.dispose(); } public getId(): string { return AccessibilityHelpWidget.ID; } public getDomNode(): HTMLElement { return this._domNode.domNode; } public getPosition(): IOverlayWidgetPosition { return { preference: null }; } public show(): void { if (this._isVisible) { return; } this._isVisible = true; this._isVisibleKey.set(true); this._layout(); this._domNode.setDisplay('block'); this._domNode.setAttribute('aria-hidden', 'false'); this._contentDomNode.domNode.tabIndex = 0; this._buildContent(); this._contentDomNode.domNode.focus(); } private _descriptionForCommand(commandId: string, msg: string, noKbMsg: string): string { let kb = this._keybindingService.lookupKeybinding(commandId); if (kb) { return strings.format(msg, kb.getAriaLabel()); } return strings.format(noKbMsg, commandId); } private _buildContent() { let opts = this._editor.getConfiguration(); const selections = this._editor.getSelections(); let charactersSelected = 0; if (selections) { const model = this._editor.getModel(); if (model) { selections.forEach((selection) => { charactersSelected += model.getValueLengthInRange(selection); }); } } let text = getSelectionLabel(selections, charactersSelected); if (opts.wrappingInfo.inDiffEditor) { if (opts.readOnly) { text += nls.localize("readonlyDiffEditor", " in a read-only pane of a diff editor."); } else { text += nls.localize("editableDiffEditor", " in a pane of a diff editor."); } } else { if (opts.readOnly) { text += nls.localize("readonlyEditor", " in a read-only code editor"); } else { text += nls.localize("editableEditor", " in a code editor"); } } switch (opts.accessibilitySupport) { case platform.AccessibilitySupport.Unknown: const turnOnMessage = ( platform.isMacintosh ? nls.localize("changeConfigToOnMac", "To configure the editor to be optimized for usage with a Screen Reader press Command+E now.") : nls.localize("changeConfigToOnWinLinux", "To configure the editor to be optimized for usage with a Screen Reader press Control+E now.") ); text += '\n\n - ' + turnOnMessage; break; case platform.AccessibilitySupport.Enabled: text += '\n\n - ' + nls.localize("auto_on", "The editor is configured to be optimized for usage with a Screen Reader."); break; case platform.AccessibilitySupport.Disabled: text += '\n\n - ' + nls.localize("auto_off", "The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time."); text += ' ' + turnOnMessage; break; } const NLS_TAB_FOCUS_MODE_ON = nls.localize("tabFocusModeOnMsg", "Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}."); const NLS_TAB_FOCUS_MODE_ON_NO_KB = nls.localize("tabFocusModeOnMsgNoKb", "Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding."); const NLS_TAB_FOCUS_MODE_OFF = nls.localize("tabFocusModeOffMsg", "Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}."); const NLS_TAB_FOCUS_MODE_OFF_NO_KB = nls.localize("tabFocusModeOffMsgNoKb", "Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding."); if (opts.tabFocusMode) { text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_ON, NLS_TAB_FOCUS_MODE_ON_NO_KB); } else { text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_OFF, NLS_TAB_FOCUS_MODE_OFF_NO_KB); } const openDocMessage = ( platform.isMacintosh ? nls.localize("openDocMac", "Press Command+H now to open a browser window with more information related to editor accessibility.") : nls.localize("openDocWinLinux", "Press Control+H now to open a browser window with more information related to editor accessibility.") ); text += '\n\n - ' + openDocMessage; text += '\n\n' + nls.localize("outroMsg", "You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape."); this._contentDomNode.domNode.appendChild(renderFormattedText(text)); // Per https://www.w3.org/TR/wai-aria/roles#document, Authors SHOULD provide a title or label for documents this._contentDomNode.domNode.setAttribute('aria-label', text); } public hide(): void { if (!this._isVisible) { return; } this._isVisible = false; this._isVisibleKey.reset(); this._domNode.setDisplay('none'); this._domNode.setAttribute('aria-hidden', 'true'); this._contentDomNode.domNode.tabIndex = -1; dom.clearNode(this._contentDomNode.domNode); this._editor.focus(); } private _layout(): void { let editorLayout = this._editor.getLayoutInfo(); let w = Math.max(5, Math.min(AccessibilityHelpWidget.WIDTH, editorLayout.width - 40)); let h = Math.max(5, Math.min(AccessibilityHelpWidget.HEIGHT, editorLayout.height - 40)); this._domNode.setWidth(w); this._domNode.setHeight(h); let top = Math.round((editorLayout.height - h) / 2); this._domNode.setTop(top); let left = Math.round((editorLayout.width - w) / 2);
} @editorAction class ShowAccessibilityHelpAction extends EditorAction { constructor() { super({ id: 'editor.action.showAccessibilityHelp', label: nls.localize("ShowAccessibilityHelpAction", "Show Accessibility Help"), alias: 'Show Accessibility Help', precondition: null, kbOpts: { kbExpr: EditorContextKeys.focus, primary: (browser.isIE ? KeyMod.CtrlCmd | KeyCode.F1 : KeyMod.Alt | KeyCode.F1) } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { let controller = AccessibilityHelpController.get(editor); if (controller) { controller.show(); } } } const AccessibilityHelpCommand = EditorCommand.bindToContribution<AccessibilityHelpController>(AccessibilityHelpController.get); CommonEditorRegistry.registerEditorCommand( new AccessibilityHelpCommand({ id: 'closeAccessibilityHelp', precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE, handler: x => x.hide(), kbOpts: { weight: CommonEditorRegistry.commandWeight(100), kbExpr: EditorContextKeys.focus, primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape] } }) ); registerThemingParticipant((theme, collector) => { let widgetBackground = theme.getColor(editorWidgetBackground); if (widgetBackground) { collector.addRule(`.monaco-editor .accessibilityHelpWidget { background-color: ${widgetBackground}; }`); } let widgetShadowColor = theme.getColor(widgetShadow); if (widgetShadowColor) { collector.addRule(`.monaco-editor .accessibilityHelpWidget { box-shadow: 0 2px 8px ${widgetShadowColor}; }`); } let hcBorder = theme.getColor(contrastBorder); if (hcBorder) { collector.addRule(`.monaco-editor .accessibilityHelpWidget { border: 2px solid ${hcBorder}; }`); } });
this._domNode.setLeft(left); }
random_line_split
lexer.py
try: from pygments.lexer import bygroups, include, using from pygments.lexers.agile import PythonLexer, PythonTracebackLexer from pygments.token import Text, Name, Number, Generic, String, Operator except ImportError: # pragma: no cover # this is for nose coverage which does a recursive import on the package pass else:
BASE_NAME = r"[a-zA-Z_][a-zA-Z0-9_]*" class XPythonLexer(PythonLexer): tokens = PythonLexer.tokens.copy() tokens["classname"] = [ ("'?[a-zA-Z_][a-zA-Z0-9_.]*'?", Name.Class, "#pop") ] # Marker __repr__ ref = "(<ref offset)(=)(\-\d+)( ?)((?:name)?)(=?)((?:%s)?)(>?)" % BASE_NAME tokens["root"].insert(0, (ref, bygroups(Name.Builtin, Name.Operator, Number, Text, Name.Builtin, Name.Operator, Name.Variable, Name.Builtin))) class PythonXTracebackLexer(PythonTracebackLexer): tokens = { "root": [ include("entry"), include("exception"), (r"^.*\n", Generic.Error), ], "entry": [ (r"^Traceback \(most recent call last\):\n", Generic.Error, "frame"), # file - path is colored differently if under working directory (r'^( File )((?:"[./<][^"]+")?)((?:"[^"]+")?)' \ '(, line )(\d+)((?:, in )?)(.*)(\n)', bygroups(Generic.Error, Name.Builtin, Operator.Word, Generic.Error, Number, Generic.Error, Name.Function, Text), "frame"), ], "exception": [ (r"^(AssertionError: )(.+\n)", bygroups(Generic.Error, using(XPythonLexer))), (r"^(%s:?)(.+\n)" % BASE_NAME, bygroups(Generic.Error, String)), ], "frame": [ include("entry"), include("exception"), # line of python code (r"^((?:-+>)?)( +)(\d+)(.+\n)", bygroups(Generic.Error, Text, Number, using(XPythonLexer))), # variable continuation (r"^([ ]+)('[^']+')(: )(.*)([,}]?\n)", bygroups(Text, String, Name.Operator, using(XPythonLexer), Text)), # variable (r"^([ ]+)((?:g:)?)(\**%s)( = )(.+\n)" % BASE_NAME, bygroups(Text, Name.Builtin, Name.Variable, Name.Operator, using(XPythonLexer))), # plain python (r"^( )(.+)(\n)", bygroups(Text, using(XPythonLexer), Text)), ], }
conditional_block
lexer.py
try: from pygments.lexer import bygroups, include, using from pygments.lexers.agile import PythonLexer, PythonTracebackLexer from pygments.token import Text, Name, Number, Generic, String, Operator except ImportError: # pragma: no cover # this is for nose coverage which does a recursive import on the package pass else: BASE_NAME = r"[a-zA-Z_][a-zA-Z0-9_]*" class XPythonLexer(PythonLexer): tokens = PythonLexer.tokens.copy() tokens["classname"] = [ ("'?[a-zA-Z_][a-zA-Z0-9_.]*'?", Name.Class, "#pop") ] # Marker __repr__ ref = "(<ref offset)(=)(\-\d+)( ?)((?:name)?)(=?)((?:%s)?)(>?)" % BASE_NAME tokens["root"].insert(0, (ref, bygroups(Name.Builtin, Name.Operator, Number, Text, Name.Builtin, Name.Operator, Name.Variable, Name.Builtin))) class
(PythonTracebackLexer): tokens = { "root": [ include("entry"), include("exception"), (r"^.*\n", Generic.Error), ], "entry": [ (r"^Traceback \(most recent call last\):\n", Generic.Error, "frame"), # file - path is colored differently if under working directory (r'^( File )((?:"[./<][^"]+")?)((?:"[^"]+")?)' \ '(, line )(\d+)((?:, in )?)(.*)(\n)', bygroups(Generic.Error, Name.Builtin, Operator.Word, Generic.Error, Number, Generic.Error, Name.Function, Text), "frame"), ], "exception": [ (r"^(AssertionError: )(.+\n)", bygroups(Generic.Error, using(XPythonLexer))), (r"^(%s:?)(.+\n)" % BASE_NAME, bygroups(Generic.Error, String)), ], "frame": [ include("entry"), include("exception"), # line of python code (r"^((?:-+>)?)( +)(\d+)(.+\n)", bygroups(Generic.Error, Text, Number, using(XPythonLexer))), # variable continuation (r"^([ ]+)('[^']+')(: )(.*)([,}]?\n)", bygroups(Text, String, Name.Operator, using(XPythonLexer), Text)), # variable (r"^([ ]+)((?:g:)?)(\**%s)( = )(.+\n)" % BASE_NAME, bygroups(Text, Name.Builtin, Name.Variable, Name.Operator, using(XPythonLexer))), # plain python (r"^( )(.+)(\n)", bygroups(Text, using(XPythonLexer), Text)), ], }
PythonXTracebackLexer
identifier_name
lexer.py
try: from pygments.lexer import bygroups, include, using from pygments.lexers.agile import PythonLexer, PythonTracebackLexer from pygments.token import Text, Name, Number, Generic, String, Operator except ImportError: # pragma: no cover # this is for nose coverage which does a recursive import on the package pass else: BASE_NAME = r"[a-zA-Z_][a-zA-Z0-9_]*" class XPythonLexer(PythonLexer): tokens = PythonLexer.tokens.copy() tokens["classname"] = [ ("'?[a-zA-Z_][a-zA-Z0-9_.]*'?", Name.Class, "#pop") ] # Marker __repr__ ref = "(<ref offset)(=)(\-\d+)( ?)((?:name)?)(=?)((?:%s)?)(>?)" % BASE_NAME tokens["root"].insert(0, (ref, bygroups(Name.Builtin, Name.Operator, Number, Text, Name.Builtin, Name.Operator, Name.Variable, Name.Builtin))) class PythonXTracebackLexer(PythonTracebackLexer): tokens = { "root": [ include("entry"), include("exception"), (r"^.*\n", Generic.Error), ], "entry": [ (r"^Traceback \(most recent call last\):\n", Generic.Error,
bygroups(Generic.Error, Name.Builtin, Operator.Word, Generic.Error, Number, Generic.Error, Name.Function, Text), "frame"), ], "exception": [ (r"^(AssertionError: )(.+\n)", bygroups(Generic.Error, using(XPythonLexer))), (r"^(%s:?)(.+\n)" % BASE_NAME, bygroups(Generic.Error, String)), ], "frame": [ include("entry"), include("exception"), # line of python code (r"^((?:-+>)?)( +)(\d+)(.+\n)", bygroups(Generic.Error, Text, Number, using(XPythonLexer))), # variable continuation (r"^([ ]+)('[^']+')(: )(.*)([,}]?\n)", bygroups(Text, String, Name.Operator, using(XPythonLexer), Text)), # variable (r"^([ ]+)((?:g:)?)(\**%s)( = )(.+\n)" % BASE_NAME, bygroups(Text, Name.Builtin, Name.Variable, Name.Operator, using(XPythonLexer))), # plain python (r"^( )(.+)(\n)", bygroups(Text, using(XPythonLexer), Text)), ], }
"frame"), # file - path is colored differently if under working directory (r'^( File )((?:"[./<][^"]+")?)((?:"[^"]+")?)' \ '(, line )(\d+)((?:, in )?)(.*)(\n)',
random_line_split
lexer.py
try: from pygments.lexer import bygroups, include, using from pygments.lexers.agile import PythonLexer, PythonTracebackLexer from pygments.token import Text, Name, Number, Generic, String, Operator except ImportError: # pragma: no cover # this is for nose coverage which does a recursive import on the package pass else: BASE_NAME = r"[a-zA-Z_][a-zA-Z0-9_]*" class XPythonLexer(PythonLexer): tokens = PythonLexer.tokens.copy() tokens["classname"] = [ ("'?[a-zA-Z_][a-zA-Z0-9_.]*'?", Name.Class, "#pop") ] # Marker __repr__ ref = "(<ref offset)(=)(\-\d+)( ?)((?:name)?)(=?)((?:%s)?)(>?)" % BASE_NAME tokens["root"].insert(0, (ref, bygroups(Name.Builtin, Name.Operator, Number, Text, Name.Builtin, Name.Operator, Name.Variable, Name.Builtin))) class PythonXTracebackLexer(PythonTracebackLexer):
tokens = { "root": [ include("entry"), include("exception"), (r"^.*\n", Generic.Error), ], "entry": [ (r"^Traceback \(most recent call last\):\n", Generic.Error, "frame"), # file - path is colored differently if under working directory (r'^( File )((?:"[./<][^"]+")?)((?:"[^"]+")?)' \ '(, line )(\d+)((?:, in )?)(.*)(\n)', bygroups(Generic.Error, Name.Builtin, Operator.Word, Generic.Error, Number, Generic.Error, Name.Function, Text), "frame"), ], "exception": [ (r"^(AssertionError: )(.+\n)", bygroups(Generic.Error, using(XPythonLexer))), (r"^(%s:?)(.+\n)" % BASE_NAME, bygroups(Generic.Error, String)), ], "frame": [ include("entry"), include("exception"), # line of python code (r"^((?:-+>)?)( +)(\d+)(.+\n)", bygroups(Generic.Error, Text, Number, using(XPythonLexer))), # variable continuation (r"^([ ]+)('[^']+')(: )(.*)([,}]?\n)", bygroups(Text, String, Name.Operator, using(XPythonLexer), Text)), # variable (r"^([ ]+)((?:g:)?)(\**%s)( = )(.+\n)" % BASE_NAME, bygroups(Text, Name.Builtin, Name.Variable, Name.Operator, using(XPythonLexer))), # plain python (r"^( )(.+)(\n)", bygroups(Text, using(XPythonLexer), Text)), ], }
identifier_body
searchService.js
/* * *************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * * *************************************************** */ angular.module( 'de.cismet.sip-html5-resource-registration.services' ).factory('de.cismet.sip-html5-resource-registration.services.searchService', ['$resource', 'de.cismet.sip-html5-resource-registration.services.Base64', 'AppConfig', function ($resource, Base64, AppConfig) { 'use strict'; var config, authdata, searchResource, searchFunction; config = AppConfig.searchService; authdata = Base64.encode(config.username + ':' + config.password); searchResource = $resource(config.host + '/searches/SWITCHON.de.cismet.cids.custom.switchon.search.server.ResourceContentLocationSearch/results', { limit: 1, offset: 0, omitNullValues: true, deduplicate: true }, { search: { method: 'POST', params: { limit: '@limit', offset: '@offset' }, isArray: false, headers: { 'Authorization': 'Basic ' + authdata } } }); searchFunction = function (url) { var queryObject, searchResult; queryObject = { 'list': [{'key': 'url', 'value': url}] }; // result of the remote search operation (promise) // starting the search! searchResult = searchResource.search( { limit: 1, offset: 0 }, queryObject ); return searchResult; }; return { search: searchFunction }; } ]) .factory('de.cismet.sip-html5-resource-registration.services.Base64', function () { /* jshint ignore:start */ var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return { encode: function (input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; do { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; }, decode: function (input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = "";
console.error("There were invalid base64 characters in the input text.\n" + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" + "Expect errors in decoding."); } input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } }; /* jshint ignore:end */ });
var i = 0; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = var base64test = /[^A-Za-z0-9\+\/\=]/g; if (base64test.exec(input)) {
random_line_split
angular-file-upload-shim.js
/**! * AngularJS file upload shim for HTML5 FormData * @author Danial <danial.farid@gmail.com> * @version <%= pkg.version %> */ (function() { var hasFlash = function() { try { var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); if (fo) return true; } catch(e) { if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined) return true; } return false; }; if (window.XMLHttpRequest) { if (window.FormData) { // allow access to Angular XHR private field: https://github.com/angular/angular.js/issues/1934 window.XMLHttpRequest = (function(origXHR) { return function() { var xhr = new origXHR(); xhr.setRequestHeader = (function(orig) { return function(header, value) { if (header === '__setXHR_') { var val = value(xhr); // fix for angular < 1.2.0 if (val instanceof Function) { val(xhr); } } else { orig.apply(xhr, arguments); } }; })(xhr.setRequestHeader); return xhr; }; })(window.XMLHttpRequest); } else { window.XMLHttpRequest = (function(origXHR) { return function() { var xhr = new origXHR(); var origSend = xhr.send; xhr.__requestHeaders = []; xhr.open = (function(orig) { if (!xhr.upload) xhr.upload = {}; xhr.upload.addEventListener = function(t, fn, b) { if (t === 'progress') { xhr.__progress = fn; } if (t === 'load') { xhr.__load = fn; } }; return function(m, url, b) { orig.apply(xhr, [m, url, b]); xhr.__url = url; }; })(xhr.open); xhr.getResponseHeader = (function(orig) { return function(h) { return xhr.__fileApiXHR ? xhr.__fileApiXHR.getResponseHeader(h) : orig.apply(xhr, [h]); }; })(xhr.getResponseHeader); xhr.getAllResponseHeaders = (function(orig) { return function() { return xhr.__fileApiXHR ? xhr.__fileApiXHR.getAllResponseHeaders() : orig.apply(xhr); }; })(xhr.getAllResponseHeaders); xhr.abort = (function(orig) { return function() { return xhr.__fileApiXHR ? xhr.__fileApiXHR.abort() : (orig == null ? null : orig.apply(xhr)); }; })(xhr.abort); xhr.setRequestHeader = (function(orig) { return function(header, value) { if (header === '__setXHR_') { var val = value(xhr); // fix for angular < 1.2.0 if (val instanceof Function) { val(xhr); } } else { orig.apply(xhr, arguments); } }; })(xhr.setRequestHeader); xhr.send = function() { if (arguments[0] && arguments[0].__isShim) { var formData = arguments[0]; var config = { url: xhr.__url, complete: function(err, fileApiXHR) { if (!err) xhr.__load({type: 'load', loaded: xhr.__total, total: xhr.__total, target: xhr, lengthComputable: true}); if (fileApiXHR.status !== undefined) Object.defineProperty(xhr, 'status', {get: function() {return fileApiXHR.status}}); if (fileApiXHR.statusText !== undefined) Object.defineProperty(xhr, 'statusText', {get: function() {return fileApiXHR.statusText}}); Object.defineProperty(xhr, 'readyState', {get: function() {return 4}}); if (fileApiXHR.response !== undefined) Object.defineProperty(xhr, 'response', {get: function() {return fileApiXHR.response}}); Object.defineProperty(xhr, 'responseText', {get: function() {return fileApiXHR.responseText}}); xhr.__fileApiXHR = fileApiXHR; xhr.onreadystatechange(); }, progress: function(e) { e.target = xhr; xhr.__progress(e); xhr.__total = e.total; }, headers: xhr.__requestHeaders } config.data = {}; config.files = {} for (var i = 0; i < formData.data.length; i++) { var item = formData.data[i]; if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) { config.files[item.key] = item.val; } else { config.data[item.key] = item.val; } } setTimeout(function() { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } xhr.__fileApiXHR = FileAPI.upload(config); }, 1); } else { origSend.apply(xhr, arguments); } } return xhr; } })(window.XMLHttpRequest); window.XMLHttpRequest.__hasFlash = hasFlash(); } window.XMLHttpRequest.__isShim = true; } if (!window.FormData) { var wrapFileApi = function(elem) { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } if (!elem.__isWrapped && (elem.getAttribute('ng-file-select') != null || elem.getAttribute('data-ng-file-select') != null)) { var wrap = document.createElement('div'); wrap.innerHTML = '<div class="js-fileapi-wrapper" style="position:relative; overflow:hidden"></div>'; wrap = wrap.firstChild; var parent = elem.parentNode; parent.insertBefore(wrap, elem); parent.removeChild(elem); wrap.appendChild(elem); elem.__isWrapped = true; } }; var changeFnWrapper = function(fn) { return function(evt) { var files = FileAPI.getFiles(evt); if (!evt.target) { evt.target = {}; } evt.target.files = files; evt.target.files.item = function(i) { return evt.target.files[i] || null; } fn(evt); }; }; var isFileChange = function(elem, e) { return (e.toLowerCase() === 'change' || e.toLowerCase() === 'onchange') && elem.getAttribute('type') == 'file'; } if (HTMLInputElement.prototype.addEventListener) { HTMLInputElement.prototype.addEventListener = (function(origAddEventListener) { return function(e, fn, b, d) { if (isFileChange(this, e)) { wrapFileApi(this); origAddEventListener.apply(this, [e, changeFnWrapper(fn), b, d]); } else { origAddEventListener.apply(this, [e, fn, b, d]); } } })(HTMLInputElement.prototype.addEventListener); } if (HTMLInputElement.prototype.attachEvent) { HTMLInputElement.prototype.attachEvent = (function(origAttachEvent) { return function(e, fn) { if (isFileChange(this, e)) { wrapFileApi(this); origAttachEvent.apply(this, [e, changeFnWrapper(fn)]); } else { origAttachEvent.apply(this, [e, fn]); } } })(HTMLInputElement.prototype.attachEvent); } window.FormData = FormData = function() { return { append: function(key, val, name) { this.data.push({ key: key, val: val, name: name }); }, data: [], __isShim: true }; }; (function () { //load FileAPI if (!window.FileAPI) { window.FileAPI = {}; } if (!FileAPI.upload) { var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src; if (window.FileAPI.jsUrl) { jsUrl = window.FileAPI.jsUrl; } else if (window.FileAPI.jsPath) { basePath = window.FileAPI.jsPath; } else { for (i = 0; i < allScripts.length; i++) { src = allScripts[i].src; index = src.indexOf('angular-file-upload-shim.js') if (index == -1) { index = src.indexOf('angular-file-upload-shim.min.js'); } if (index > -1) { basePath = src.substring(0, index); break; } } } if (FileAPI.staticPath == null) FileAPI.staticPath = basePath; script.setAttribute('src', jsUrl || basePath + "FileAPI.min.js"); document.getElementsByTagName('head')[0].appendChild(script); FileAPI.hasFlash = hasFlash(); } })(); } if (!window.FileReader) { window.FileReader = function() { var _this = this, loadStarted = false; this.listeners = {}; this.addEventListener = function(type, fn) { _this.listeners[type] = _this.listeners[type] || []; _this.listeners[type].push(fn); }; this.removeEventListener = function(type, fn) { _this.listeners[type] && _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1); }; this.dispatchEvent = function(evt) { var list = _this.listeners[evt.type]; if (list) { for (var i = 0; i < list.length; i++) { list[i].call(_this, evt); } } }; this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null; function constructEvent(type, evt)
; var listener = function(evt) { if (!loadStarted) { loadStarted = true; _this.onloadstart && this.onloadstart(constructEvent('loadstart', evt)); } if (evt.type === 'load') { _this.onloadend && _this.onloadend(constructEvent('loadend', evt)); var e = constructEvent('load', evt); _this.onload && _this.onload(e); _this.dispatchEvent(e); } else if (evt.type === 'progress') { var e = constructEvent('progress', evt); _this.onprogress && _this.onprogress(e); _this.dispatchEvent(e); } else { var e = constructEvent('error', evt); _this.onerror && _this.onerror(e); _this.dispatchEvent(e); } }; this.readAsArrayBuffer = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsBinaryString = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsDataURL = function(file) { FileAPI.readAsDataURL(file, listener); } this.readAsText = function(file) { FileAPI.readAsText(file, listener); } } } })();
{ var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error}; if (evt.result != null) e.target.result = evt.result; return e; }
identifier_body
angular-file-upload-shim.js
/**! * AngularJS file upload shim for HTML5 FormData * @author Danial <danial.farid@gmail.com> * @version <%= pkg.version %> */ (function() { var hasFlash = function() { try { var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); if (fo) return true; } catch(e) { if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined) return true; } return false; }; if (window.XMLHttpRequest) { if (window.FormData) { // allow access to Angular XHR private field: https://github.com/angular/angular.js/issues/1934
return function() { var xhr = new origXHR(); xhr.setRequestHeader = (function(orig) { return function(header, value) { if (header === '__setXHR_') { var val = value(xhr); // fix for angular < 1.2.0 if (val instanceof Function) { val(xhr); } } else { orig.apply(xhr, arguments); } }; })(xhr.setRequestHeader); return xhr; }; })(window.XMLHttpRequest); } else { window.XMLHttpRequest = (function(origXHR) { return function() { var xhr = new origXHR(); var origSend = xhr.send; xhr.__requestHeaders = []; xhr.open = (function(orig) { if (!xhr.upload) xhr.upload = {}; xhr.upload.addEventListener = function(t, fn, b) { if (t === 'progress') { xhr.__progress = fn; } if (t === 'load') { xhr.__load = fn; } }; return function(m, url, b) { orig.apply(xhr, [m, url, b]); xhr.__url = url; }; })(xhr.open); xhr.getResponseHeader = (function(orig) { return function(h) { return xhr.__fileApiXHR ? xhr.__fileApiXHR.getResponseHeader(h) : orig.apply(xhr, [h]); }; })(xhr.getResponseHeader); xhr.getAllResponseHeaders = (function(orig) { return function() { return xhr.__fileApiXHR ? xhr.__fileApiXHR.getAllResponseHeaders() : orig.apply(xhr); }; })(xhr.getAllResponseHeaders); xhr.abort = (function(orig) { return function() { return xhr.__fileApiXHR ? xhr.__fileApiXHR.abort() : (orig == null ? null : orig.apply(xhr)); }; })(xhr.abort); xhr.setRequestHeader = (function(orig) { return function(header, value) { if (header === '__setXHR_') { var val = value(xhr); // fix for angular < 1.2.0 if (val instanceof Function) { val(xhr); } } else { orig.apply(xhr, arguments); } }; })(xhr.setRequestHeader); xhr.send = function() { if (arguments[0] && arguments[0].__isShim) { var formData = arguments[0]; var config = { url: xhr.__url, complete: function(err, fileApiXHR) { if (!err) xhr.__load({type: 'load', loaded: xhr.__total, total: xhr.__total, target: xhr, lengthComputable: true}); if (fileApiXHR.status !== undefined) Object.defineProperty(xhr, 'status', {get: function() {return fileApiXHR.status}}); if (fileApiXHR.statusText !== undefined) Object.defineProperty(xhr, 'statusText', {get: function() {return fileApiXHR.statusText}}); Object.defineProperty(xhr, 'readyState', {get: function() {return 4}}); if (fileApiXHR.response !== undefined) Object.defineProperty(xhr, 'response', {get: function() {return fileApiXHR.response}}); Object.defineProperty(xhr, 'responseText', {get: function() {return fileApiXHR.responseText}}); xhr.__fileApiXHR = fileApiXHR; xhr.onreadystatechange(); }, progress: function(e) { e.target = xhr; xhr.__progress(e); xhr.__total = e.total; }, headers: xhr.__requestHeaders } config.data = {}; config.files = {} for (var i = 0; i < formData.data.length; i++) { var item = formData.data[i]; if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) { config.files[item.key] = item.val; } else { config.data[item.key] = item.val; } } setTimeout(function() { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } xhr.__fileApiXHR = FileAPI.upload(config); }, 1); } else { origSend.apply(xhr, arguments); } } return xhr; } })(window.XMLHttpRequest); window.XMLHttpRequest.__hasFlash = hasFlash(); } window.XMLHttpRequest.__isShim = true; } if (!window.FormData) { var wrapFileApi = function(elem) { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } if (!elem.__isWrapped && (elem.getAttribute('ng-file-select') != null || elem.getAttribute('data-ng-file-select') != null)) { var wrap = document.createElement('div'); wrap.innerHTML = '<div class="js-fileapi-wrapper" style="position:relative; overflow:hidden"></div>'; wrap = wrap.firstChild; var parent = elem.parentNode; parent.insertBefore(wrap, elem); parent.removeChild(elem); wrap.appendChild(elem); elem.__isWrapped = true; } }; var changeFnWrapper = function(fn) { return function(evt) { var files = FileAPI.getFiles(evt); if (!evt.target) { evt.target = {}; } evt.target.files = files; evt.target.files.item = function(i) { return evt.target.files[i] || null; } fn(evt); }; }; var isFileChange = function(elem, e) { return (e.toLowerCase() === 'change' || e.toLowerCase() === 'onchange') && elem.getAttribute('type') == 'file'; } if (HTMLInputElement.prototype.addEventListener) { HTMLInputElement.prototype.addEventListener = (function(origAddEventListener) { return function(e, fn, b, d) { if (isFileChange(this, e)) { wrapFileApi(this); origAddEventListener.apply(this, [e, changeFnWrapper(fn), b, d]); } else { origAddEventListener.apply(this, [e, fn, b, d]); } } })(HTMLInputElement.prototype.addEventListener); } if (HTMLInputElement.prototype.attachEvent) { HTMLInputElement.prototype.attachEvent = (function(origAttachEvent) { return function(e, fn) { if (isFileChange(this, e)) { wrapFileApi(this); origAttachEvent.apply(this, [e, changeFnWrapper(fn)]); } else { origAttachEvent.apply(this, [e, fn]); } } })(HTMLInputElement.prototype.attachEvent); } window.FormData = FormData = function() { return { append: function(key, val, name) { this.data.push({ key: key, val: val, name: name }); }, data: [], __isShim: true }; }; (function () { //load FileAPI if (!window.FileAPI) { window.FileAPI = {}; } if (!FileAPI.upload) { var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src; if (window.FileAPI.jsUrl) { jsUrl = window.FileAPI.jsUrl; } else if (window.FileAPI.jsPath) { basePath = window.FileAPI.jsPath; } else { for (i = 0; i < allScripts.length; i++) { src = allScripts[i].src; index = src.indexOf('angular-file-upload-shim.js') if (index == -1) { index = src.indexOf('angular-file-upload-shim.min.js'); } if (index > -1) { basePath = src.substring(0, index); break; } } } if (FileAPI.staticPath == null) FileAPI.staticPath = basePath; script.setAttribute('src', jsUrl || basePath + "FileAPI.min.js"); document.getElementsByTagName('head')[0].appendChild(script); FileAPI.hasFlash = hasFlash(); } })(); } if (!window.FileReader) { window.FileReader = function() { var _this = this, loadStarted = false; this.listeners = {}; this.addEventListener = function(type, fn) { _this.listeners[type] = _this.listeners[type] || []; _this.listeners[type].push(fn); }; this.removeEventListener = function(type, fn) { _this.listeners[type] && _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1); }; this.dispatchEvent = function(evt) { var list = _this.listeners[evt.type]; if (list) { for (var i = 0; i < list.length; i++) { list[i].call(_this, evt); } } }; this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null; function constructEvent(type, evt) { var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error}; if (evt.result != null) e.target.result = evt.result; return e; }; var listener = function(evt) { if (!loadStarted) { loadStarted = true; _this.onloadstart && this.onloadstart(constructEvent('loadstart', evt)); } if (evt.type === 'load') { _this.onloadend && _this.onloadend(constructEvent('loadend', evt)); var e = constructEvent('load', evt); _this.onload && _this.onload(e); _this.dispatchEvent(e); } else if (evt.type === 'progress') { var e = constructEvent('progress', evt); _this.onprogress && _this.onprogress(e); _this.dispatchEvent(e); } else { var e = constructEvent('error', evt); _this.onerror && _this.onerror(e); _this.dispatchEvent(e); } }; this.readAsArrayBuffer = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsBinaryString = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsDataURL = function(file) { FileAPI.readAsDataURL(file, listener); } this.readAsText = function(file) { FileAPI.readAsText(file, listener); } } } })();
window.XMLHttpRequest = (function(origXHR) {
random_line_split
angular-file-upload-shim.js
/**! * AngularJS file upload shim for HTML5 FormData * @author Danial <danial.farid@gmail.com> * @version <%= pkg.version %> */ (function() { var hasFlash = function() { try { var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); if (fo) return true; } catch(e) { if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined) return true; } return false; }; if (window.XMLHttpRequest) { if (window.FormData) { // allow access to Angular XHR private field: https://github.com/angular/angular.js/issues/1934 window.XMLHttpRequest = (function(origXHR) { return function() { var xhr = new origXHR(); xhr.setRequestHeader = (function(orig) { return function(header, value) { if (header === '__setXHR_') { var val = value(xhr); // fix for angular < 1.2.0 if (val instanceof Function) { val(xhr); } } else { orig.apply(xhr, arguments); } }; })(xhr.setRequestHeader); return xhr; }; })(window.XMLHttpRequest); } else { window.XMLHttpRequest = (function(origXHR) { return function() { var xhr = new origXHR(); var origSend = xhr.send; xhr.__requestHeaders = []; xhr.open = (function(orig) { if (!xhr.upload) xhr.upload = {}; xhr.upload.addEventListener = function(t, fn, b) { if (t === 'progress') { xhr.__progress = fn; } if (t === 'load') { xhr.__load = fn; } }; return function(m, url, b) { orig.apply(xhr, [m, url, b]); xhr.__url = url; }; })(xhr.open); xhr.getResponseHeader = (function(orig) { return function(h) { return xhr.__fileApiXHR ? xhr.__fileApiXHR.getResponseHeader(h) : orig.apply(xhr, [h]); }; })(xhr.getResponseHeader); xhr.getAllResponseHeaders = (function(orig) { return function() { return xhr.__fileApiXHR ? xhr.__fileApiXHR.getAllResponseHeaders() : orig.apply(xhr); }; })(xhr.getAllResponseHeaders); xhr.abort = (function(orig) { return function() { return xhr.__fileApiXHR ? xhr.__fileApiXHR.abort() : (orig == null ? null : orig.apply(xhr)); }; })(xhr.abort); xhr.setRequestHeader = (function(orig) { return function(header, value) { if (header === '__setXHR_') { var val = value(xhr); // fix for angular < 1.2.0 if (val instanceof Function) { val(xhr); } } else { orig.apply(xhr, arguments); } }; })(xhr.setRequestHeader); xhr.send = function() { if (arguments[0] && arguments[0].__isShim) { var formData = arguments[0]; var config = { url: xhr.__url, complete: function(err, fileApiXHR) { if (!err) xhr.__load({type: 'load', loaded: xhr.__total, total: xhr.__total, target: xhr, lengthComputable: true}); if (fileApiXHR.status !== undefined) Object.defineProperty(xhr, 'status', {get: function() {return fileApiXHR.status}}); if (fileApiXHR.statusText !== undefined) Object.defineProperty(xhr, 'statusText', {get: function() {return fileApiXHR.statusText}}); Object.defineProperty(xhr, 'readyState', {get: function() {return 4}}); if (fileApiXHR.response !== undefined) Object.defineProperty(xhr, 'response', {get: function() {return fileApiXHR.response}}); Object.defineProperty(xhr, 'responseText', {get: function() {return fileApiXHR.responseText}}); xhr.__fileApiXHR = fileApiXHR; xhr.onreadystatechange(); }, progress: function(e) { e.target = xhr; xhr.__progress(e); xhr.__total = e.total; }, headers: xhr.__requestHeaders } config.data = {}; config.files = {} for (var i = 0; i < formData.data.length; i++) { var item = formData.data[i]; if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) { config.files[item.key] = item.val; } else { config.data[item.key] = item.val; } } setTimeout(function() { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } xhr.__fileApiXHR = FileAPI.upload(config); }, 1); } else { origSend.apply(xhr, arguments); } } return xhr; } })(window.XMLHttpRequest); window.XMLHttpRequest.__hasFlash = hasFlash(); } window.XMLHttpRequest.__isShim = true; } if (!window.FormData) { var wrapFileApi = function(elem) { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } if (!elem.__isWrapped && (elem.getAttribute('ng-file-select') != null || elem.getAttribute('data-ng-file-select') != null)) { var wrap = document.createElement('div'); wrap.innerHTML = '<div class="js-fileapi-wrapper" style="position:relative; overflow:hidden"></div>'; wrap = wrap.firstChild; var parent = elem.parentNode; parent.insertBefore(wrap, elem); parent.removeChild(elem); wrap.appendChild(elem); elem.__isWrapped = true; } }; var changeFnWrapper = function(fn) { return function(evt) { var files = FileAPI.getFiles(evt); if (!evt.target) { evt.target = {}; } evt.target.files = files; evt.target.files.item = function(i) { return evt.target.files[i] || null; } fn(evt); }; }; var isFileChange = function(elem, e) { return (e.toLowerCase() === 'change' || e.toLowerCase() === 'onchange') && elem.getAttribute('type') == 'file'; } if (HTMLInputElement.prototype.addEventListener) { HTMLInputElement.prototype.addEventListener = (function(origAddEventListener) { return function(e, fn, b, d) { if (isFileChange(this, e)) { wrapFileApi(this); origAddEventListener.apply(this, [e, changeFnWrapper(fn), b, d]); } else { origAddEventListener.apply(this, [e, fn, b, d]); } } })(HTMLInputElement.prototype.addEventListener); } if (HTMLInputElement.prototype.attachEvent) { HTMLInputElement.prototype.attachEvent = (function(origAttachEvent) { return function(e, fn) { if (isFileChange(this, e)) { wrapFileApi(this); origAttachEvent.apply(this, [e, changeFnWrapper(fn)]); } else { origAttachEvent.apply(this, [e, fn]); } } })(HTMLInputElement.prototype.attachEvent); } window.FormData = FormData = function() { return { append: function(key, val, name) { this.data.push({ key: key, val: val, name: name }); }, data: [], __isShim: true }; }; (function () { //load FileAPI if (!window.FileAPI) { window.FileAPI = {}; } if (!FileAPI.upload) { var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src; if (window.FileAPI.jsUrl) { jsUrl = window.FileAPI.jsUrl; } else if (window.FileAPI.jsPath) { basePath = window.FileAPI.jsPath; } else { for (i = 0; i < allScripts.length; i++) { src = allScripts[i].src; index = src.indexOf('angular-file-upload-shim.js') if (index == -1) { index = src.indexOf('angular-file-upload-shim.min.js'); } if (index > -1)
} } if (FileAPI.staticPath == null) FileAPI.staticPath = basePath; script.setAttribute('src', jsUrl || basePath + "FileAPI.min.js"); document.getElementsByTagName('head')[0].appendChild(script); FileAPI.hasFlash = hasFlash(); } })(); } if (!window.FileReader) { window.FileReader = function() { var _this = this, loadStarted = false; this.listeners = {}; this.addEventListener = function(type, fn) { _this.listeners[type] = _this.listeners[type] || []; _this.listeners[type].push(fn); }; this.removeEventListener = function(type, fn) { _this.listeners[type] && _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1); }; this.dispatchEvent = function(evt) { var list = _this.listeners[evt.type]; if (list) { for (var i = 0; i < list.length; i++) { list[i].call(_this, evt); } } }; this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null; function constructEvent(type, evt) { var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error}; if (evt.result != null) e.target.result = evt.result; return e; }; var listener = function(evt) { if (!loadStarted) { loadStarted = true; _this.onloadstart && this.onloadstart(constructEvent('loadstart', evt)); } if (evt.type === 'load') { _this.onloadend && _this.onloadend(constructEvent('loadend', evt)); var e = constructEvent('load', evt); _this.onload && _this.onload(e); _this.dispatchEvent(e); } else if (evt.type === 'progress') { var e = constructEvent('progress', evt); _this.onprogress && _this.onprogress(e); _this.dispatchEvent(e); } else { var e = constructEvent('error', evt); _this.onerror && _this.onerror(e); _this.dispatchEvent(e); } }; this.readAsArrayBuffer = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsBinaryString = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsDataURL = function(file) { FileAPI.readAsDataURL(file, listener); } this.readAsText = function(file) { FileAPI.readAsText(file, listener); } } } })();
{ basePath = src.substring(0, index); break; }
conditional_block
angular-file-upload-shim.js
/**! * AngularJS file upload shim for HTML5 FormData * @author Danial <danial.farid@gmail.com> * @version <%= pkg.version %> */ (function() { var hasFlash = function() { try { var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); if (fo) return true; } catch(e) { if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined) return true; } return false; }; if (window.XMLHttpRequest) { if (window.FormData) { // allow access to Angular XHR private field: https://github.com/angular/angular.js/issues/1934 window.XMLHttpRequest = (function(origXHR) { return function() { var xhr = new origXHR(); xhr.setRequestHeader = (function(orig) { return function(header, value) { if (header === '__setXHR_') { var val = value(xhr); // fix for angular < 1.2.0 if (val instanceof Function) { val(xhr); } } else { orig.apply(xhr, arguments); } }; })(xhr.setRequestHeader); return xhr; }; })(window.XMLHttpRequest); } else { window.XMLHttpRequest = (function(origXHR) { return function() { var xhr = new origXHR(); var origSend = xhr.send; xhr.__requestHeaders = []; xhr.open = (function(orig) { if (!xhr.upload) xhr.upload = {}; xhr.upload.addEventListener = function(t, fn, b) { if (t === 'progress') { xhr.__progress = fn; } if (t === 'load') { xhr.__load = fn; } }; return function(m, url, b) { orig.apply(xhr, [m, url, b]); xhr.__url = url; }; })(xhr.open); xhr.getResponseHeader = (function(orig) { return function(h) { return xhr.__fileApiXHR ? xhr.__fileApiXHR.getResponseHeader(h) : orig.apply(xhr, [h]); }; })(xhr.getResponseHeader); xhr.getAllResponseHeaders = (function(orig) { return function() { return xhr.__fileApiXHR ? xhr.__fileApiXHR.getAllResponseHeaders() : orig.apply(xhr); }; })(xhr.getAllResponseHeaders); xhr.abort = (function(orig) { return function() { return xhr.__fileApiXHR ? xhr.__fileApiXHR.abort() : (orig == null ? null : orig.apply(xhr)); }; })(xhr.abort); xhr.setRequestHeader = (function(orig) { return function(header, value) { if (header === '__setXHR_') { var val = value(xhr); // fix for angular < 1.2.0 if (val instanceof Function) { val(xhr); } } else { orig.apply(xhr, arguments); } }; })(xhr.setRequestHeader); xhr.send = function() { if (arguments[0] && arguments[0].__isShim) { var formData = arguments[0]; var config = { url: xhr.__url, complete: function(err, fileApiXHR) { if (!err) xhr.__load({type: 'load', loaded: xhr.__total, total: xhr.__total, target: xhr, lengthComputable: true}); if (fileApiXHR.status !== undefined) Object.defineProperty(xhr, 'status', {get: function() {return fileApiXHR.status}}); if (fileApiXHR.statusText !== undefined) Object.defineProperty(xhr, 'statusText', {get: function() {return fileApiXHR.statusText}}); Object.defineProperty(xhr, 'readyState', {get: function() {return 4}}); if (fileApiXHR.response !== undefined) Object.defineProperty(xhr, 'response', {get: function() {return fileApiXHR.response}}); Object.defineProperty(xhr, 'responseText', {get: function() {return fileApiXHR.responseText}}); xhr.__fileApiXHR = fileApiXHR; xhr.onreadystatechange(); }, progress: function(e) { e.target = xhr; xhr.__progress(e); xhr.__total = e.total; }, headers: xhr.__requestHeaders } config.data = {}; config.files = {} for (var i = 0; i < formData.data.length; i++) { var item = formData.data[i]; if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) { config.files[item.key] = item.val; } else { config.data[item.key] = item.val; } } setTimeout(function() { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } xhr.__fileApiXHR = FileAPI.upload(config); }, 1); } else { origSend.apply(xhr, arguments); } } return xhr; } })(window.XMLHttpRequest); window.XMLHttpRequest.__hasFlash = hasFlash(); } window.XMLHttpRequest.__isShim = true; } if (!window.FormData) { var wrapFileApi = function(elem) { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } if (!elem.__isWrapped && (elem.getAttribute('ng-file-select') != null || elem.getAttribute('data-ng-file-select') != null)) { var wrap = document.createElement('div'); wrap.innerHTML = '<div class="js-fileapi-wrapper" style="position:relative; overflow:hidden"></div>'; wrap = wrap.firstChild; var parent = elem.parentNode; parent.insertBefore(wrap, elem); parent.removeChild(elem); wrap.appendChild(elem); elem.__isWrapped = true; } }; var changeFnWrapper = function(fn) { return function(evt) { var files = FileAPI.getFiles(evt); if (!evt.target) { evt.target = {}; } evt.target.files = files; evt.target.files.item = function(i) { return evt.target.files[i] || null; } fn(evt); }; }; var isFileChange = function(elem, e) { return (e.toLowerCase() === 'change' || e.toLowerCase() === 'onchange') && elem.getAttribute('type') == 'file'; } if (HTMLInputElement.prototype.addEventListener) { HTMLInputElement.prototype.addEventListener = (function(origAddEventListener) { return function(e, fn, b, d) { if (isFileChange(this, e)) { wrapFileApi(this); origAddEventListener.apply(this, [e, changeFnWrapper(fn), b, d]); } else { origAddEventListener.apply(this, [e, fn, b, d]); } } })(HTMLInputElement.prototype.addEventListener); } if (HTMLInputElement.prototype.attachEvent) { HTMLInputElement.prototype.attachEvent = (function(origAttachEvent) { return function(e, fn) { if (isFileChange(this, e)) { wrapFileApi(this); origAttachEvent.apply(this, [e, changeFnWrapper(fn)]); } else { origAttachEvent.apply(this, [e, fn]); } } })(HTMLInputElement.prototype.attachEvent); } window.FormData = FormData = function() { return { append: function(key, val, name) { this.data.push({ key: key, val: val, name: name }); }, data: [], __isShim: true }; }; (function () { //load FileAPI if (!window.FileAPI) { window.FileAPI = {}; } if (!FileAPI.upload) { var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src; if (window.FileAPI.jsUrl) { jsUrl = window.FileAPI.jsUrl; } else if (window.FileAPI.jsPath) { basePath = window.FileAPI.jsPath; } else { for (i = 0; i < allScripts.length; i++) { src = allScripts[i].src; index = src.indexOf('angular-file-upload-shim.js') if (index == -1) { index = src.indexOf('angular-file-upload-shim.min.js'); } if (index > -1) { basePath = src.substring(0, index); break; } } } if (FileAPI.staticPath == null) FileAPI.staticPath = basePath; script.setAttribute('src', jsUrl || basePath + "FileAPI.min.js"); document.getElementsByTagName('head')[0].appendChild(script); FileAPI.hasFlash = hasFlash(); } })(); } if (!window.FileReader) { window.FileReader = function() { var _this = this, loadStarted = false; this.listeners = {}; this.addEventListener = function(type, fn) { _this.listeners[type] = _this.listeners[type] || []; _this.listeners[type].push(fn); }; this.removeEventListener = function(type, fn) { _this.listeners[type] && _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1); }; this.dispatchEvent = function(evt) { var list = _this.listeners[evt.type]; if (list) { for (var i = 0; i < list.length; i++) { list[i].call(_this, evt); } } }; this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null; function
(type, evt) { var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error}; if (evt.result != null) e.target.result = evt.result; return e; }; var listener = function(evt) { if (!loadStarted) { loadStarted = true; _this.onloadstart && this.onloadstart(constructEvent('loadstart', evt)); } if (evt.type === 'load') { _this.onloadend && _this.onloadend(constructEvent('loadend', evt)); var e = constructEvent('load', evt); _this.onload && _this.onload(e); _this.dispatchEvent(e); } else if (evt.type === 'progress') { var e = constructEvent('progress', evt); _this.onprogress && _this.onprogress(e); _this.dispatchEvent(e); } else { var e = constructEvent('error', evt); _this.onerror && _this.onerror(e); _this.dispatchEvent(e); } }; this.readAsArrayBuffer = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsBinaryString = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsDataURL = function(file) { FileAPI.readAsDataURL(file, listener); } this.readAsText = function(file) { FileAPI.readAsText(file, listener); } } } })();
constructEvent
identifier_name
offline.interceptor.js
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ (function() { 'use strict'; /** * @ngdoc service * @name openlmis-offline.offlineInterceptor * * @description * Responsible for managing server requests while offline. */ angular .module('openlmis-offline') .factory('offlineInterceptor', factory) .config(config); config.$inject = ['$httpProvider']; factory.$inject = ['$q', '$injector', 'offlineService']; function config($httpProvider) { $httpProvider.interceptors.push('offlineInterceptor'); } function factory($q, $injector, offlineService) {
);
var canDisplayModal = true, interceptor = { request: request }; return interceptor; /** * @ngdoc method * @methodOf openlmis-offline.offlineInterceptor * @name request * * @description * Cancels request if user is offline and displays alert modal with proper message. * Passes all HTML calls. * * @param {Object} config HTTP Config object * @return {Object} A modified configuration object */ function request(config) { var canceler = $q.defer(); config.timeout = canceler.promise; // checks if calls for html file from cache if (offlineService.isOffline() && config.url.indexOf('.html') < 0) { // because all of them are getting into that method if (!config.forceHideOfflineModal) { if (canDisplayModal) { canDisplayModal = false; $injector.get('alertService') .error('openlmisOffline.actionNotAllowedOffline') .finally(function() { canDisplayModal = true; }); } } canceler.resolve(); } return config; } } })(
identifier_body
offline.interceptor.js
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ (function() { 'use strict'; /** * @ngdoc service * @name openlmis-offline.offlineInterceptor * * @description * Responsible for managing server requests while offline. */ angular .module('openlmis-offline') .factory('offlineInterceptor', factory) .config(config); config.$inject = ['$httpProvider']; factory.$inject = ['$q', '$injector', 'offlineService']; function config($httpProvider) { $httpProvider.interceptors.push('offlineInterceptor'); } function factory($q, $injector, offlineService) { var canDisplayModal = true, interceptor = { request: request }; return interceptor; /** * @ngdoc method * @methodOf openlmis-offline.offlineInterceptor * @name request * * @description * Cancels request if user is offline and displays alert modal with proper message. * Passes all HTML calls. * * @param {Object} config HTTP Config object * @return {Object} A modified configuration object */ function request(config) { var canceler = $q.defer(); config.timeout = canceler.promise; // checks if calls for html file from cache if (offlineService.isOffline() && config.url.indexOf('.html') < 0) { // because all of them are getting into that method if (!config.forceHideOfflineModal) { if (canDisplayModal) {
} canceler.resolve(); } return config; } } })();
canDisplayModal = false; $injector.get('alertService') .error('openlmisOffline.actionNotAllowedOffline') .finally(function() { canDisplayModal = true; }); }
conditional_block
offline.interceptor.js
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ (function() { 'use strict';
* @description * Responsible for managing server requests while offline. */ angular .module('openlmis-offline') .factory('offlineInterceptor', factory) .config(config); config.$inject = ['$httpProvider']; factory.$inject = ['$q', '$injector', 'offlineService']; function config($httpProvider) { $httpProvider.interceptors.push('offlineInterceptor'); } function factory($q, $injector, offlineService) { var canDisplayModal = true, interceptor = { request: request }; return interceptor; /** * @ngdoc method * @methodOf openlmis-offline.offlineInterceptor * @name request * * @description * Cancels request if user is offline and displays alert modal with proper message. * Passes all HTML calls. * * @param {Object} config HTTP Config object * @return {Object} A modified configuration object */ function request(config) { var canceler = $q.defer(); config.timeout = canceler.promise; // checks if calls for html file from cache if (offlineService.isOffline() && config.url.indexOf('.html') < 0) { // because all of them are getting into that method if (!config.forceHideOfflineModal) { if (canDisplayModal) { canDisplayModal = false; $injector.get('alertService') .error('openlmisOffline.actionNotAllowedOffline') .finally(function() { canDisplayModal = true; }); } } canceler.resolve(); } return config; } } })();
/** * @ngdoc service * @name openlmis-offline.offlineInterceptor *
random_line_split
offline.interceptor.js
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ (function() { 'use strict'; /** * @ngdoc service * @name openlmis-offline.offlineInterceptor * * @description * Responsible for managing server requests while offline. */ angular .module('openlmis-offline') .factory('offlineInterceptor', factory) .config(config); config.$inject = ['$httpProvider']; factory.$inject = ['$q', '$injector', 'offlineService']; function confi
pProvider) { $httpProvider.interceptors.push('offlineInterceptor'); } function factory($q, $injector, offlineService) { var canDisplayModal = true, interceptor = { request: request }; return interceptor; /** * @ngdoc method * @methodOf openlmis-offline.offlineInterceptor * @name request * * @description * Cancels request if user is offline and displays alert modal with proper message. * Passes all HTML calls. * * @param {Object} config HTTP Config object * @return {Object} A modified configuration object */ function request(config) { var canceler = $q.defer(); config.timeout = canceler.promise; // checks if calls for html file from cache if (offlineService.isOffline() && config.url.indexOf('.html') < 0) { // because all of them are getting into that method if (!config.forceHideOfflineModal) { if (canDisplayModal) { canDisplayModal = false; $injector.get('alertService') .error('openlmisOffline.actionNotAllowedOffline') .finally(function() { canDisplayModal = true; }); } } canceler.resolve(); } return config; } } })();
g($htt
identifier_name
env.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Runtime environment settings use libc::{size_t, c_char, c_int}; pub struct Environment { /// The number of threads to use by default num_sched_threads: size_t, /// The minimum size of a stack segment min_stack_size: size_t, /// The maximum amount of total stack per task before aborting max_stack_size: size_t, /// The default logging configuration
/// Poison allocations on free poison_on_free: bool, /// The argc value passed to main argc: c_int, /// The argv value passed to main argv: **c_char, /// Print GC debugging info debug_mem: bool } /// Get the global environment settings /// # Safety Note /// This will abort the process if run outside of task context pub fn get() -> &Environment { unsafe { rust_get_rt_env() } } extern { fn rust_get_rt_env() -> &Environment; }
logspec: *c_char, /// Record and report detailed information about memory leaks detailed_leaks: bool, /// Seed the random number generator rust_seed: *c_char,
random_line_split
env.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Runtime environment settings use libc::{size_t, c_char, c_int}; pub struct
{ /// The number of threads to use by default num_sched_threads: size_t, /// The minimum size of a stack segment min_stack_size: size_t, /// The maximum amount of total stack per task before aborting max_stack_size: size_t, /// The default logging configuration logspec: *c_char, /// Record and report detailed information about memory leaks detailed_leaks: bool, /// Seed the random number generator rust_seed: *c_char, /// Poison allocations on free poison_on_free: bool, /// The argc value passed to main argc: c_int, /// The argv value passed to main argv: **c_char, /// Print GC debugging info debug_mem: bool } /// Get the global environment settings /// # Safety Note /// This will abort the process if run outside of task context pub fn get() -> &Environment { unsafe { rust_get_rt_env() } } extern { fn rust_get_rt_env() -> &Environment; }
Environment
identifier_name
env.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Runtime environment settings use libc::{size_t, c_char, c_int}; pub struct Environment { /// The number of threads to use by default num_sched_threads: size_t, /// The minimum size of a stack segment min_stack_size: size_t, /// The maximum amount of total stack per task before aborting max_stack_size: size_t, /// The default logging configuration logspec: *c_char, /// Record and report detailed information about memory leaks detailed_leaks: bool, /// Seed the random number generator rust_seed: *c_char, /// Poison allocations on free poison_on_free: bool, /// The argc value passed to main argc: c_int, /// The argv value passed to main argv: **c_char, /// Print GC debugging info debug_mem: bool } /// Get the global environment settings /// # Safety Note /// This will abort the process if run outside of task context pub fn get() -> &Environment
extern { fn rust_get_rt_env() -> &Environment; }
{ unsafe { rust_get_rt_env() } }
identifier_body
task.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Language-level runtime services that should reasonably expected //! to be available 'everywhere'. Local heaps, GC, unwinding, //! local storage, and logging. Even a 'freestanding' Rust would likely want //! to implement this. use alloc::arc::Arc; use alloc::boxed::{BoxAny, Box}; use core::any::Any; use core::atomic::{AtomicUint, SeqCst}; use core::iter::Take; use core::kinds::marker; use core::mem; use core::prelude::{Clone, Drop, Err, Iterator, None, Ok, Option, Send, Some}; use core::prelude::{drop}; use core::raw; use local_data; use Runtime; use local::Local; use local_heap::LocalHeap; use rtio::LocalIo; use unwind; use unwind::Unwinder; use collections::str::SendStr; /// State associated with Rust tasks. /// /// Rust tasks are primarily built with two separate components. One is this /// structure which handles standard services such as TLD, unwinding support, /// naming of a task, etc. The second component is the runtime of this task, a /// `Runtime` trait object. /// /// The `Runtime` object instructs this task how it can perform critical /// operations such as blocking, rescheduling, I/O constructors, etc. The two /// halves are separately owned, but one is often found contained in the other. /// A task's runtime can be reflected upon with the `maybe_take_runtime` method, /// and otherwise its ownership is managed with `take_runtime` and /// `put_runtime`. /// /// In general, this structure should not be used. This is meant to be an /// unstable internal detail of the runtime itself. From time-to-time, however, /// it is useful to manage tasks directly. An example of this would be /// interoperating with the Rust runtime from FFI callbacks or such. For this /// reason, there are two methods of note with the `Task` structure. /// /// * `run` - This function will execute a closure inside the context of a task. /// Failure is caught and handled via the task's on_exit callback. If /// this fails, the task is still returned, but it can no longer be /// used, it is poisoned. /// /// * `destroy` - This is a required function to call to destroy a task. If a /// task falls out of scope without calling `destroy`, its /// destructor bomb will go off, aborting the process. /// /// With these two methods, tasks can be re-used to execute code inside of its /// context while having a point in the future where destruction is allowed. /// More information can be found on these specific methods. /// /// # Example /// /// ```no_run /// extern crate native; /// use std::uint; /// # fn main() { /// /// // Create a task using a native runtime /// let task = native::task::new((0, uint::MAX)); /// /// // Run some code, catching any possible failures /// let task = task.run(|| { /// // Run some code inside this task /// println!("Hello with a native runtime!"); /// }); /// /// // Run some code again, catching the failure /// let task = task.run(|| { /// fail!("oh no, what to do!"); /// }); /// /// // Now that the task is failed, it can never be used again /// assert!(task.is_destroyed()); /// /// // Deallocate the resources associated with this task /// task.destroy(); /// # } /// ``` pub struct Task { pub heap: LocalHeap, pub gc: GarbageCollector, pub storage: LocalStorage, pub unwinder: Unwinder, pub death: Death, pub name: Option<SendStr>, state: TaskState, imp: Option<Box<Runtime + Send + 'static>>, } // Once a task has entered the `Armed` state it must be destroyed via `drop`, // and no other method. This state is used to track this transition. #[deriving(PartialEq)] enum TaskState { New, Armed, Destroyed, } pub struct TaskOpts { /// Invoke this procedure with the result of the task when it finishes. pub on_exit: Option<proc(Result): Send>, /// A name for the task-to-be, for identification in failure messages pub name: Option<SendStr>, /// The size of the stack for the spawned task pub stack_size: Option<uint>, } /// Indicates the manner in which a task exited. /// /// A task that completes without failing is considered to exit successfully. /// /// If you wish for this result's delivery to block until all /// children tasks complete, recommend using a result future. pub type Result = ::core::result::Result<(), Box<Any + Send>>; pub struct GarbageCollector; pub struct LocalStorage(pub Option<local_data::Map>); /// A handle to a blocked task. Usually this means having the Box<Task> /// pointer by ownership, but if the task is killable, a killer can steal it /// at any time. pub enum BlockedTask { Owned(Box<Task>), Shared(Arc<AtomicUint>), } /// Per-task state related to task death, killing, failure, etc. pub struct Death { pub on_exit: Option<proc(Result):Send>, marker: marker::NoCopy, } pub struct BlockedTasks { inner: Arc<AtomicUint>, } impl Task { /// Creates a new uninitialized task. /// /// This method cannot be used to immediately invoke `run` because the task /// itself will likely require a runtime to be inserted via `put_runtime`. /// /// Note that you likely don't want to call this function, but rather the /// task creation functions through libnative or libgreen. pub fn new() -> Task { Task { heap: LocalHeap::new(), gc: GarbageCollector, storage: LocalStorage(None), unwinder: Unwinder::new(), death: Death::new(), state: New, name: None, imp: None, } } /// Consumes ownership of a task, runs some code, and returns the task back. /// /// This function can be used as an emulated "try/catch" to interoperate /// with the rust runtime at the outermost boundary. It is not possible to /// use this function in a nested fashion (a try/catch inside of another /// try/catch). Invoking this function is quite cheap. /// /// If the closure `f` succeeds, then the returned task can be used again /// for another invocation of `run`. If the closure `f` fails then `self` /// will be internally destroyed along with all of the other associated /// resources of this task. The `on_exit` callback is invoked with the /// cause of failure (not returned here). This can be discovered by querying /// `is_destroyed()`. /// /// Note that it is possible to view partial execution of the closure `f` /// because it is not guaranteed to run to completion, but this function is /// guaranteed to return if it fails. Care should be taken to ensure that /// stack references made by `f` are handled appropriately. /// /// It is invalid to call this function with a task that has been previously /// destroyed via a failed call to `run`. /// /// # Example /// /// ```no_run /// extern crate native; /// use std::uint; /// # fn main() { /// /// // Create a new native task /// let task = native::task::new((0, uint::MAX)); /// /// // Run some code once and then destroy this task
/// println!("Hello with a native runtime!"); /// }).destroy(); /// # } /// ``` pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> { assert!(!self.is_destroyed(), "cannot re-use a destroyed task"); // First, make sure that no one else is in TLS. This does not allow // recursive invocations of run(). If there's no one else, then // relinquish ownership of ourselves back into TLS. if Local::exists(None::<Task>) { fail!("cannot run a task recursively inside another"); } self.state = Armed; Local::put(self); // There are two primary reasons that general try/catch is unsafe. The // first is that we do not support nested try/catch. The above check for // an existing task in TLS is sufficient for this invariant to be // upheld. The second is that unwinding while unwinding is not defined. // We take care of that by having an 'unwinding' flag in the task // itself. For these reasons, this unsafety should be ok. let result = unsafe { unwind::try(f) }; // After running the closure given return the task back out if it ran // successfully, or clean up the task if it failed. let task: Box<Task> = Local::take(); match result { Ok(()) => task, Err(cause) => { task.cleanup(Err(cause)) } } } /// Destroy all associated resources of this task. /// /// This function will perform any necessary clean up to prepare the task /// for destruction. It is required that this is called before a `Task` /// falls out of scope. /// /// The returned task cannot be used for running any more code, but it may /// be used to extract the runtime as necessary. pub fn destroy(self: Box<Task>) -> Box<Task> { if self.is_destroyed() { self } else { self.cleanup(Ok(())) } } /// Cleans up a task, processing the result of the task as appropriate. /// /// This function consumes ownership of the task, deallocating it once it's /// done being processed. It is assumed that TLD and the local heap have /// already been destroyed and/or annihilated. fn cleanup(self: Box<Task>, result: Result) -> Box<Task> { // The first thing to do when cleaning up is to deallocate our local // resources, such as TLD and GC data. // // FIXME: there are a number of problems with this code // // 1. If any TLD object fails destruction, then all of TLD will leak. // This appears to be a consequence of #14875. // // 2. Failing during GC annihilation aborts the runtime #14876. // // 3. Setting a TLD key while destroying TLD or while destroying GC will // abort the runtime #14807. // // 4. Invoking GC in GC destructors will abort the runtime #6996. // // 5. The order of destruction of TLD and GC matters, but either way is // susceptible to leaks (see 3/4) #8302. // // That being said, there are a few upshots to this code // // 1. If TLD destruction fails, heap destruction will be attempted. // There is a test for this at fail-during-tld-destroy.rs. Sadly the // other way can't be tested due to point 2 above. Note that we must // immortalize the heap first because if any deallocations are // attempted while TLD is being dropped it will attempt to free the // allocation from the wrong heap (because the current one has been // replaced). // // 2. One failure in destruction is tolerable, so long as the task // didn't originally fail while it was running. // // And with all that in mind, we attempt to clean things up! let mut task = self.run(|| { let mut task = Local::borrow(None::<Task>); let tld = { let &LocalStorage(ref mut optmap) = &mut task.storage; optmap.take() }; let mut heap = mem::replace(&mut task.heap, LocalHeap::new()); unsafe { heap.immortalize() } drop(task); // First, destroy task-local storage. This may run user dtors. drop(tld); // Destroy remaining boxes. Also may run user dtors. drop(heap); }); // If the above `run` block failed, then it must be the case that the // task had previously succeeded. This also means that the code below // was recursively run via the `run` method invoking this method. In // this case, we just make sure the world is as we thought, and return. if task.is_destroyed() { rtassert!(result.is_ok()) return task } // After taking care of the data above, we need to transmit the result // of this task. let what_to_do = task.death.on_exit.take(); Local::put(task); // FIXME: this is running in a seriously constrained context. If this // allocates GC or allocates TLD then it will likely abort the // runtime. Similarly, if this fails, this will also likely abort // the runtime. // // This closure is currently limited to a channel send via the // standard library's task interface, but this needs // reconsideration to whether it's a reasonable thing to let a // task to do or not. match what_to_do { Some(f) => { f(result) } None => { drop(result) } } // Now that we're done, we remove the task from TLS and flag it for // destruction. let mut task: Box<Task> = Local::take(); task.state = Destroyed; return task; } /// Queries whether this can be destroyed or not. pub fn is_destroyed(&self) -> bool { self.state == Destroyed } /// Inserts a runtime object into this task, transferring ownership to the /// task. It is illegal to replace a previous runtime object in this task /// with this argument. pub fn put_runtime(&mut self, ops: Box<Runtime + Send + 'static>) { assert!(self.imp.is_none()); self.imp = Some(ops); } /// Removes the runtime from this task, transferring ownership to the /// caller. pub fn take_runtime(&mut self) -> Box<Runtime + Send + 'static> { assert!(self.imp.is_some()); self.imp.take().unwrap() } /// Attempts to extract the runtime as a specific type. If the runtime does /// not have the provided type, then the runtime is not removed. If the /// runtime does have the specified type, then it is removed and returned /// (transfer of ownership). /// /// It is recommended to only use this method when *absolutely necessary*. /// This function may not be available in the future. pub fn maybe_take_runtime<T: 'static>(&mut self) -> Option<Box<T>> { // This is a terrible, terrible function. The general idea here is to // take the runtime, cast it to Box<Any>, check if it has the right // type, and then re-cast it back if necessary. The method of doing // this is pretty sketchy and involves shuffling vtables of trait // objects around, but it gets the job done. // // FIXME: This function is a serious code smell and should be avoided at // all costs. I have yet to think of a method to avoid this // function, and I would be saddened if more usage of the function // crops up. unsafe { let imp = self.imp.take().unwrap(); let vtable = mem::transmute::<_, &raw::TraitObject>(&imp).vtable; match imp.wrap().downcast::<T>() { Ok(t) => Some(t), Err(t) => { let data = mem::transmute::<_, raw::TraitObject>(t).data; let obj: Box<Runtime + Send + 'static> = mem::transmute(raw::TraitObject { vtable: vtable, data: data, }); self.put_runtime(obj); None } } } } /// Spawns a sibling to this task. The newly spawned task is configured with /// the `opts` structure and will run `f` as the body of its code. pub fn spawn_sibling(mut self: Box<Task>, opts: TaskOpts, f: proc(): Send) { let ops = self.imp.take().unwrap(); ops.spawn_sibling(self, opts, f) } /// Deschedules the current task, invoking `f` `amt` times. It is not /// recommended to use this function directly, but rather communication /// primitives in `std::comm` should be used. pub fn deschedule(mut self: Box<Task>, amt: uint, f: |BlockedTask| -> ::core::result::Result<(), BlockedTask>) { let ops = self.imp.take().unwrap(); ops.deschedule(amt, self, f) } /// Wakes up a previously blocked task, optionally specifying whether the /// current task can accept a change in scheduling. This function can only /// be called on tasks that were previously blocked in `deschedule`. pub fn reawaken(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.reawaken(self); } /// Yields control of this task to another task. This function will /// eventually return, but possibly not immediately. This is used as an /// opportunity to allow other tasks a chance to run. pub fn yield_now(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.yield_now(self); } /// Similar to `yield_now`, except that this function may immediately return /// without yielding (depending on what the runtime decides to do). pub fn maybe_yield(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.maybe_yield(self); } /// Acquires a handle to the I/O factory that this task contains, normally /// stored in the task's runtime. This factory may not always be available, /// which is why the return type is `Option` pub fn local_io<'a>(&'a mut self) -> Option<LocalIo<'a>> { self.imp.as_mut().unwrap().local_io() } /// Returns the stack bounds for this task in (lo, hi) format. The stack /// bounds may not be known for all tasks, so the return value may be /// `None`. pub fn stack_bounds(&self) -> (uint, uint) { self.imp.as_ref().unwrap().stack_bounds() } /// Returns whether it is legal for this task to block the OS thread that it /// is running on. pub fn can_block(&self) -> bool { self.imp.as_ref().unwrap().can_block() } /// Consume this task, flagging it as a candidate for destruction. /// /// This function is required to be invoked to destroy a task. A task /// destroyed through a normal drop will abort. pub fn drop(mut self) { self.state = Destroyed; } } impl Drop for Task { fn drop(&mut self) { rtdebug!("called drop for a task: {}", self as *mut Task as uint); rtassert!(self.state != Armed); } } impl TaskOpts { pub fn new() -> TaskOpts { TaskOpts { on_exit: None, name: None, stack_size: None } } } impl Iterator<BlockedTask> for BlockedTasks { fn next(&mut self) -> Option<BlockedTask> { Some(Shared(self.inner.clone())) } } impl BlockedTask { /// Returns Some if the task was successfully woken; None if already killed. pub fn wake(self) -> Option<Box<Task>> { match self { Owned(task) => Some(task), Shared(arc) => { match arc.swap(0, SeqCst) { 0 => None, n => Some(unsafe { mem::transmute(n) }), } } } } /// Reawakens this task if ownership is acquired. If finer-grained control /// is desired, use `wake` instead. pub fn reawaken(self) { self.wake().map(|t| t.reawaken()); } // This assertion has two flavours because the wake involves an atomic op. // In the faster version, destructors will fail dramatically instead. #[cfg(not(test))] pub fn trash(self) { } #[cfg(test)] pub fn trash(self) { assert!(self.wake().is_none()); } /// Create a blocked task, unless the task was already killed. pub fn block(task: Box<Task>) -> BlockedTask { Owned(task) } /// Converts one blocked task handle to a list of many handles to the same. pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> { let arc = match self { Owned(task) => { let flag = unsafe { AtomicUint::new(mem::transmute(task)) }; Arc::new(flag) } Shared(arc) => arc.clone(), }; BlockedTasks{ inner: arc }.take(num_handles) } /// Convert to an unsafe uint value. Useful for storing in a pipe's state /// flag. #[inline] pub unsafe fn cast_to_uint(self) -> uint { match self { Owned(task) => { let blocked_task_ptr: uint = mem::transmute(task); rtassert!(blocked_task_ptr & 0x1 == 0); blocked_task_ptr } Shared(arc) => { let blocked_task_ptr: uint = mem::transmute(box arc); rtassert!(blocked_task_ptr & 0x1 == 0); blocked_task_ptr | 0x1 } } } /// Convert from an unsafe uint value. Useful for retrieving a pipe's state /// flag. #[inline] pub unsafe fn cast_from_uint(blocked_task_ptr: uint) -> BlockedTask { if blocked_task_ptr & 0x1 == 0 { Owned(mem::transmute(blocked_task_ptr)) } else { let ptr: Box<Arc<AtomicUint>> = mem::transmute(blocked_task_ptr & !1); Shared(*ptr) } } } impl Death { pub fn new() -> Death { Death { on_exit: None, marker: marker::NoCopy } } } #[cfg(test)] mod test { use super::*; use std::prelude::*; use std::task; use std::gc::{Gc, GC}; #[test] fn local_heap() { let a = box(GC) 5i; let b = a; assert!(*a == 5); assert!(*b == 5); } #[test] fn tls() { local_data_key!(key: Gc<String>) key.replace(Some(box(GC) "data".to_string())); assert_eq!(key.get().unwrap().as_slice(), "data"); local_data_key!(key2: Gc<String>) key2.replace(Some(box(GC) "data".to_string())); assert_eq!(key2.get().unwrap().as_slice(), "data"); } #[test] fn unwind() { let result = task::try(proc()()); rtdebug!("trying first assert"); assert!(result.is_ok()); let result = task::try::<()>(proc() fail!()); rtdebug!("trying second assert"); assert!(result.is_err()); } #[test] fn rng() { use std::rand::{StdRng, Rng}; let mut r = StdRng::new().ok().unwrap(); let _ = r.next_u32(); } #[test] fn comm_stream() { let (tx, rx) = channel(); tx.send(10i); assert!(rx.recv() == 10); } #[test] fn comm_shared_chan() { let (tx, rx) = channel(); tx.send(10i); assert!(rx.recv() == 10); } #[test] fn heap_cycles() { use std::cell::RefCell; struct List { next: Option<Gc<RefCell<List>>>, } let a = box(GC) RefCell::new(List { next: None }); let b = box(GC) RefCell::new(List { next: Some(a) }); { let mut a = a.borrow_mut(); a.next = Some(b); } } #[test] #[should_fail] fn test_begin_unwind() { use std::rt::unwind::begin_unwind; begin_unwind("cause", &(file!(), line!())) } #[test] fn drop_new_task_ok() { drop(Task::new()); } // Task blocking tests #[test] fn block_and_wake() { let task = box Task::new(); let mut task = BlockedTask::block(task).wake().unwrap(); task.drop(); } }
/// task.run(|| {
random_line_split
task.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Language-level runtime services that should reasonably expected //! to be available 'everywhere'. Local heaps, GC, unwinding, //! local storage, and logging. Even a 'freestanding' Rust would likely want //! to implement this. use alloc::arc::Arc; use alloc::boxed::{BoxAny, Box}; use core::any::Any; use core::atomic::{AtomicUint, SeqCst}; use core::iter::Take; use core::kinds::marker; use core::mem; use core::prelude::{Clone, Drop, Err, Iterator, None, Ok, Option, Send, Some}; use core::prelude::{drop}; use core::raw; use local_data; use Runtime; use local::Local; use local_heap::LocalHeap; use rtio::LocalIo; use unwind; use unwind::Unwinder; use collections::str::SendStr; /// State associated with Rust tasks. /// /// Rust tasks are primarily built with two separate components. One is this /// structure which handles standard services such as TLD, unwinding support, /// naming of a task, etc. The second component is the runtime of this task, a /// `Runtime` trait object. /// /// The `Runtime` object instructs this task how it can perform critical /// operations such as blocking, rescheduling, I/O constructors, etc. The two /// halves are separately owned, but one is often found contained in the other. /// A task's runtime can be reflected upon with the `maybe_take_runtime` method, /// and otherwise its ownership is managed with `take_runtime` and /// `put_runtime`. /// /// In general, this structure should not be used. This is meant to be an /// unstable internal detail of the runtime itself. From time-to-time, however, /// it is useful to manage tasks directly. An example of this would be /// interoperating with the Rust runtime from FFI callbacks or such. For this /// reason, there are two methods of note with the `Task` structure. /// /// * `run` - This function will execute a closure inside the context of a task. /// Failure is caught and handled via the task's on_exit callback. If /// this fails, the task is still returned, but it can no longer be /// used, it is poisoned. /// /// * `destroy` - This is a required function to call to destroy a task. If a /// task falls out of scope without calling `destroy`, its /// destructor bomb will go off, aborting the process. /// /// With these two methods, tasks can be re-used to execute code inside of its /// context while having a point in the future where destruction is allowed. /// More information can be found on these specific methods. /// /// # Example /// /// ```no_run /// extern crate native; /// use std::uint; /// # fn main() { /// /// // Create a task using a native runtime /// let task = native::task::new((0, uint::MAX)); /// /// // Run some code, catching any possible failures /// let task = task.run(|| { /// // Run some code inside this task /// println!("Hello with a native runtime!"); /// }); /// /// // Run some code again, catching the failure /// let task = task.run(|| { /// fail!("oh no, what to do!"); /// }); /// /// // Now that the task is failed, it can never be used again /// assert!(task.is_destroyed()); /// /// // Deallocate the resources associated with this task /// task.destroy(); /// # } /// ``` pub struct Task { pub heap: LocalHeap, pub gc: GarbageCollector, pub storage: LocalStorage, pub unwinder: Unwinder, pub death: Death, pub name: Option<SendStr>, state: TaskState, imp: Option<Box<Runtime + Send + 'static>>, } // Once a task has entered the `Armed` state it must be destroyed via `drop`, // and no other method. This state is used to track this transition. #[deriving(PartialEq)] enum TaskState { New, Armed, Destroyed, } pub struct TaskOpts { /// Invoke this procedure with the result of the task when it finishes. pub on_exit: Option<proc(Result): Send>, /// A name for the task-to-be, for identification in failure messages pub name: Option<SendStr>, /// The size of the stack for the spawned task pub stack_size: Option<uint>, } /// Indicates the manner in which a task exited. /// /// A task that completes without failing is considered to exit successfully. /// /// If you wish for this result's delivery to block until all /// children tasks complete, recommend using a result future. pub type Result = ::core::result::Result<(), Box<Any + Send>>; pub struct GarbageCollector; pub struct LocalStorage(pub Option<local_data::Map>); /// A handle to a blocked task. Usually this means having the Box<Task> /// pointer by ownership, but if the task is killable, a killer can steal it /// at any time. pub enum BlockedTask { Owned(Box<Task>), Shared(Arc<AtomicUint>), } /// Per-task state related to task death, killing, failure, etc. pub struct Death { pub on_exit: Option<proc(Result):Send>, marker: marker::NoCopy, } pub struct BlockedTasks { inner: Arc<AtomicUint>, } impl Task { /// Creates a new uninitialized task. /// /// This method cannot be used to immediately invoke `run` because the task /// itself will likely require a runtime to be inserted via `put_runtime`. /// /// Note that you likely don't want to call this function, but rather the /// task creation functions through libnative or libgreen. pub fn new() -> Task { Task { heap: LocalHeap::new(), gc: GarbageCollector, storage: LocalStorage(None), unwinder: Unwinder::new(), death: Death::new(), state: New, name: None, imp: None, } } /// Consumes ownership of a task, runs some code, and returns the task back. /// /// This function can be used as an emulated "try/catch" to interoperate /// with the rust runtime at the outermost boundary. It is not possible to /// use this function in a nested fashion (a try/catch inside of another /// try/catch). Invoking this function is quite cheap. /// /// If the closure `f` succeeds, then the returned task can be used again /// for another invocation of `run`. If the closure `f` fails then `self` /// will be internally destroyed along with all of the other associated /// resources of this task. The `on_exit` callback is invoked with the /// cause of failure (not returned here). This can be discovered by querying /// `is_destroyed()`. /// /// Note that it is possible to view partial execution of the closure `f` /// because it is not guaranteed to run to completion, but this function is /// guaranteed to return if it fails. Care should be taken to ensure that /// stack references made by `f` are handled appropriately. /// /// It is invalid to call this function with a task that has been previously /// destroyed via a failed call to `run`. /// /// # Example /// /// ```no_run /// extern crate native; /// use std::uint; /// # fn main() { /// /// // Create a new native task /// let task = native::task::new((0, uint::MAX)); /// /// // Run some code once and then destroy this task /// task.run(|| { /// println!("Hello with a native runtime!"); /// }).destroy(); /// # } /// ``` pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> { assert!(!self.is_destroyed(), "cannot re-use a destroyed task"); // First, make sure that no one else is in TLS. This does not allow // recursive invocations of run(). If there's no one else, then // relinquish ownership of ourselves back into TLS. if Local::exists(None::<Task>) { fail!("cannot run a task recursively inside another"); } self.state = Armed; Local::put(self); // There are two primary reasons that general try/catch is unsafe. The // first is that we do not support nested try/catch. The above check for // an existing task in TLS is sufficient for this invariant to be // upheld. The second is that unwinding while unwinding is not defined. // We take care of that by having an 'unwinding' flag in the task // itself. For these reasons, this unsafety should be ok. let result = unsafe { unwind::try(f) }; // After running the closure given return the task back out if it ran // successfully, or clean up the task if it failed. let task: Box<Task> = Local::take(); match result { Ok(()) => task, Err(cause) => { task.cleanup(Err(cause)) } } } /// Destroy all associated resources of this task. /// /// This function will perform any necessary clean up to prepare the task /// for destruction. It is required that this is called before a `Task` /// falls out of scope. /// /// The returned task cannot be used for running any more code, but it may /// be used to extract the runtime as necessary. pub fn destroy(self: Box<Task>) -> Box<Task> { if self.is_destroyed() { self } else { self.cleanup(Ok(())) } } /// Cleans up a task, processing the result of the task as appropriate. /// /// This function consumes ownership of the task, deallocating it once it's /// done being processed. It is assumed that TLD and the local heap have /// already been destroyed and/or annihilated. fn cleanup(self: Box<Task>, result: Result) -> Box<Task> { // The first thing to do when cleaning up is to deallocate our local // resources, such as TLD and GC data. // // FIXME: there are a number of problems with this code // // 1. If any TLD object fails destruction, then all of TLD will leak. // This appears to be a consequence of #14875. // // 2. Failing during GC annihilation aborts the runtime #14876. // // 3. Setting a TLD key while destroying TLD or while destroying GC will // abort the runtime #14807. // // 4. Invoking GC in GC destructors will abort the runtime #6996. // // 5. The order of destruction of TLD and GC matters, but either way is // susceptible to leaks (see 3/4) #8302. // // That being said, there are a few upshots to this code // // 1. If TLD destruction fails, heap destruction will be attempted. // There is a test for this at fail-during-tld-destroy.rs. Sadly the // other way can't be tested due to point 2 above. Note that we must // immortalize the heap first because if any deallocations are // attempted while TLD is being dropped it will attempt to free the // allocation from the wrong heap (because the current one has been // replaced). // // 2. One failure in destruction is tolerable, so long as the task // didn't originally fail while it was running. // // And with all that in mind, we attempt to clean things up! let mut task = self.run(|| { let mut task = Local::borrow(None::<Task>); let tld = { let &LocalStorage(ref mut optmap) = &mut task.storage; optmap.take() }; let mut heap = mem::replace(&mut task.heap, LocalHeap::new()); unsafe { heap.immortalize() } drop(task); // First, destroy task-local storage. This may run user dtors. drop(tld); // Destroy remaining boxes. Also may run user dtors. drop(heap); }); // If the above `run` block failed, then it must be the case that the // task had previously succeeded. This also means that the code below // was recursively run via the `run` method invoking this method. In // this case, we just make sure the world is as we thought, and return. if task.is_destroyed() { rtassert!(result.is_ok()) return task } // After taking care of the data above, we need to transmit the result // of this task. let what_to_do = task.death.on_exit.take(); Local::put(task); // FIXME: this is running in a seriously constrained context. If this // allocates GC or allocates TLD then it will likely abort the // runtime. Similarly, if this fails, this will also likely abort // the runtime. // // This closure is currently limited to a channel send via the // standard library's task interface, but this needs // reconsideration to whether it's a reasonable thing to let a // task to do or not. match what_to_do { Some(f) => { f(result) } None => { drop(result) } } // Now that we're done, we remove the task from TLS and flag it for // destruction. let mut task: Box<Task> = Local::take(); task.state = Destroyed; return task; } /// Queries whether this can be destroyed or not. pub fn is_destroyed(&self) -> bool { self.state == Destroyed } /// Inserts a runtime object into this task, transferring ownership to the /// task. It is illegal to replace a previous runtime object in this task /// with this argument. pub fn put_runtime(&mut self, ops: Box<Runtime + Send + 'static>) { assert!(self.imp.is_none()); self.imp = Some(ops); } /// Removes the runtime from this task, transferring ownership to the /// caller. pub fn take_runtime(&mut self) -> Box<Runtime + Send + 'static> { assert!(self.imp.is_some()); self.imp.take().unwrap() } /// Attempts to extract the runtime as a specific type. If the runtime does /// not have the provided type, then the runtime is not removed. If the /// runtime does have the specified type, then it is removed and returned /// (transfer of ownership). /// /// It is recommended to only use this method when *absolutely necessary*. /// This function may not be available in the future. pub fn maybe_take_runtime<T: 'static>(&mut self) -> Option<Box<T>> { // This is a terrible, terrible function. The general idea here is to // take the runtime, cast it to Box<Any>, check if it has the right // type, and then re-cast it back if necessary. The method of doing // this is pretty sketchy and involves shuffling vtables of trait // objects around, but it gets the job done. // // FIXME: This function is a serious code smell and should be avoided at // all costs. I have yet to think of a method to avoid this // function, and I would be saddened if more usage of the function // crops up. unsafe { let imp = self.imp.take().unwrap(); let vtable = mem::transmute::<_, &raw::TraitObject>(&imp).vtable; match imp.wrap().downcast::<T>() { Ok(t) => Some(t), Err(t) => { let data = mem::transmute::<_, raw::TraitObject>(t).data; let obj: Box<Runtime + Send + 'static> = mem::transmute(raw::TraitObject { vtable: vtable, data: data, }); self.put_runtime(obj); None } } } } /// Spawns a sibling to this task. The newly spawned task is configured with /// the `opts` structure and will run `f` as the body of its code. pub fn spawn_sibling(mut self: Box<Task>, opts: TaskOpts, f: proc(): Send) { let ops = self.imp.take().unwrap(); ops.spawn_sibling(self, opts, f) } /// Deschedules the current task, invoking `f` `amt` times. It is not /// recommended to use this function directly, but rather communication /// primitives in `std::comm` should be used. pub fn deschedule(mut self: Box<Task>, amt: uint, f: |BlockedTask| -> ::core::result::Result<(), BlockedTask>) { let ops = self.imp.take().unwrap(); ops.deschedule(amt, self, f) } /// Wakes up a previously blocked task, optionally specifying whether the /// current task can accept a change in scheduling. This function can only /// be called on tasks that were previously blocked in `deschedule`. pub fn reawaken(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.reawaken(self); } /// Yields control of this task to another task. This function will /// eventually return, but possibly not immediately. This is used as an /// opportunity to allow other tasks a chance to run. pub fn
(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.yield_now(self); } /// Similar to `yield_now`, except that this function may immediately return /// without yielding (depending on what the runtime decides to do). pub fn maybe_yield(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.maybe_yield(self); } /// Acquires a handle to the I/O factory that this task contains, normally /// stored in the task's runtime. This factory may not always be available, /// which is why the return type is `Option` pub fn local_io<'a>(&'a mut self) -> Option<LocalIo<'a>> { self.imp.as_mut().unwrap().local_io() } /// Returns the stack bounds for this task in (lo, hi) format. The stack /// bounds may not be known for all tasks, so the return value may be /// `None`. pub fn stack_bounds(&self) -> (uint, uint) { self.imp.as_ref().unwrap().stack_bounds() } /// Returns whether it is legal for this task to block the OS thread that it /// is running on. pub fn can_block(&self) -> bool { self.imp.as_ref().unwrap().can_block() } /// Consume this task, flagging it as a candidate for destruction. /// /// This function is required to be invoked to destroy a task. A task /// destroyed through a normal drop will abort. pub fn drop(mut self) { self.state = Destroyed; } } impl Drop for Task { fn drop(&mut self) { rtdebug!("called drop for a task: {}", self as *mut Task as uint); rtassert!(self.state != Armed); } } impl TaskOpts { pub fn new() -> TaskOpts { TaskOpts { on_exit: None, name: None, stack_size: None } } } impl Iterator<BlockedTask> for BlockedTasks { fn next(&mut self) -> Option<BlockedTask> { Some(Shared(self.inner.clone())) } } impl BlockedTask { /// Returns Some if the task was successfully woken; None if already killed. pub fn wake(self) -> Option<Box<Task>> { match self { Owned(task) => Some(task), Shared(arc) => { match arc.swap(0, SeqCst) { 0 => None, n => Some(unsafe { mem::transmute(n) }), } } } } /// Reawakens this task if ownership is acquired. If finer-grained control /// is desired, use `wake` instead. pub fn reawaken(self) { self.wake().map(|t| t.reawaken()); } // This assertion has two flavours because the wake involves an atomic op. // In the faster version, destructors will fail dramatically instead. #[cfg(not(test))] pub fn trash(self) { } #[cfg(test)] pub fn trash(self) { assert!(self.wake().is_none()); } /// Create a blocked task, unless the task was already killed. pub fn block(task: Box<Task>) -> BlockedTask { Owned(task) } /// Converts one blocked task handle to a list of many handles to the same. pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> { let arc = match self { Owned(task) => { let flag = unsafe { AtomicUint::new(mem::transmute(task)) }; Arc::new(flag) } Shared(arc) => arc.clone(), }; BlockedTasks{ inner: arc }.take(num_handles) } /// Convert to an unsafe uint value. Useful for storing in a pipe's state /// flag. #[inline] pub unsafe fn cast_to_uint(self) -> uint { match self { Owned(task) => { let blocked_task_ptr: uint = mem::transmute(task); rtassert!(blocked_task_ptr & 0x1 == 0); blocked_task_ptr } Shared(arc) => { let blocked_task_ptr: uint = mem::transmute(box arc); rtassert!(blocked_task_ptr & 0x1 == 0); blocked_task_ptr | 0x1 } } } /// Convert from an unsafe uint value. Useful for retrieving a pipe's state /// flag. #[inline] pub unsafe fn cast_from_uint(blocked_task_ptr: uint) -> BlockedTask { if blocked_task_ptr & 0x1 == 0 { Owned(mem::transmute(blocked_task_ptr)) } else { let ptr: Box<Arc<AtomicUint>> = mem::transmute(blocked_task_ptr & !1); Shared(*ptr) } } } impl Death { pub fn new() -> Death { Death { on_exit: None, marker: marker::NoCopy } } } #[cfg(test)] mod test { use super::*; use std::prelude::*; use std::task; use std::gc::{Gc, GC}; #[test] fn local_heap() { let a = box(GC) 5i; let b = a; assert!(*a == 5); assert!(*b == 5); } #[test] fn tls() { local_data_key!(key: Gc<String>) key.replace(Some(box(GC) "data".to_string())); assert_eq!(key.get().unwrap().as_slice(), "data"); local_data_key!(key2: Gc<String>) key2.replace(Some(box(GC) "data".to_string())); assert_eq!(key2.get().unwrap().as_slice(), "data"); } #[test] fn unwind() { let result = task::try(proc()()); rtdebug!("trying first assert"); assert!(result.is_ok()); let result = task::try::<()>(proc() fail!()); rtdebug!("trying second assert"); assert!(result.is_err()); } #[test] fn rng() { use std::rand::{StdRng, Rng}; let mut r = StdRng::new().ok().unwrap(); let _ = r.next_u32(); } #[test] fn comm_stream() { let (tx, rx) = channel(); tx.send(10i); assert!(rx.recv() == 10); } #[test] fn comm_shared_chan() { let (tx, rx) = channel(); tx.send(10i); assert!(rx.recv() == 10); } #[test] fn heap_cycles() { use std::cell::RefCell; struct List { next: Option<Gc<RefCell<List>>>, } let a = box(GC) RefCell::new(List { next: None }); let b = box(GC) RefCell::new(List { next: Some(a) }); { let mut a = a.borrow_mut(); a.next = Some(b); } } #[test] #[should_fail] fn test_begin_unwind() { use std::rt::unwind::begin_unwind; begin_unwind("cause", &(file!(), line!())) } #[test] fn drop_new_task_ok() { drop(Task::new()); } // Task blocking tests #[test] fn block_and_wake() { let task = box Task::new(); let mut task = BlockedTask::block(task).wake().unwrap(); task.drop(); } }
yield_now
identifier_name
task.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Language-level runtime services that should reasonably expected //! to be available 'everywhere'. Local heaps, GC, unwinding, //! local storage, and logging. Even a 'freestanding' Rust would likely want //! to implement this. use alloc::arc::Arc; use alloc::boxed::{BoxAny, Box}; use core::any::Any; use core::atomic::{AtomicUint, SeqCst}; use core::iter::Take; use core::kinds::marker; use core::mem; use core::prelude::{Clone, Drop, Err, Iterator, None, Ok, Option, Send, Some}; use core::prelude::{drop}; use core::raw; use local_data; use Runtime; use local::Local; use local_heap::LocalHeap; use rtio::LocalIo; use unwind; use unwind::Unwinder; use collections::str::SendStr; /// State associated with Rust tasks. /// /// Rust tasks are primarily built with two separate components. One is this /// structure which handles standard services such as TLD, unwinding support, /// naming of a task, etc. The second component is the runtime of this task, a /// `Runtime` trait object. /// /// The `Runtime` object instructs this task how it can perform critical /// operations such as blocking, rescheduling, I/O constructors, etc. The two /// halves are separately owned, but one is often found contained in the other. /// A task's runtime can be reflected upon with the `maybe_take_runtime` method, /// and otherwise its ownership is managed with `take_runtime` and /// `put_runtime`. /// /// In general, this structure should not be used. This is meant to be an /// unstable internal detail of the runtime itself. From time-to-time, however, /// it is useful to manage tasks directly. An example of this would be /// interoperating with the Rust runtime from FFI callbacks or such. For this /// reason, there are two methods of note with the `Task` structure. /// /// * `run` - This function will execute a closure inside the context of a task. /// Failure is caught and handled via the task's on_exit callback. If /// this fails, the task is still returned, but it can no longer be /// used, it is poisoned. /// /// * `destroy` - This is a required function to call to destroy a task. If a /// task falls out of scope without calling `destroy`, its /// destructor bomb will go off, aborting the process. /// /// With these two methods, tasks can be re-used to execute code inside of its /// context while having a point in the future where destruction is allowed. /// More information can be found on these specific methods. /// /// # Example /// /// ```no_run /// extern crate native; /// use std::uint; /// # fn main() { /// /// // Create a task using a native runtime /// let task = native::task::new((0, uint::MAX)); /// /// // Run some code, catching any possible failures /// let task = task.run(|| { /// // Run some code inside this task /// println!("Hello with a native runtime!"); /// }); /// /// // Run some code again, catching the failure /// let task = task.run(|| { /// fail!("oh no, what to do!"); /// }); /// /// // Now that the task is failed, it can never be used again /// assert!(task.is_destroyed()); /// /// // Deallocate the resources associated with this task /// task.destroy(); /// # } /// ``` pub struct Task { pub heap: LocalHeap, pub gc: GarbageCollector, pub storage: LocalStorage, pub unwinder: Unwinder, pub death: Death, pub name: Option<SendStr>, state: TaskState, imp: Option<Box<Runtime + Send + 'static>>, } // Once a task has entered the `Armed` state it must be destroyed via `drop`, // and no other method. This state is used to track this transition. #[deriving(PartialEq)] enum TaskState { New, Armed, Destroyed, } pub struct TaskOpts { /// Invoke this procedure with the result of the task when it finishes. pub on_exit: Option<proc(Result): Send>, /// A name for the task-to-be, for identification in failure messages pub name: Option<SendStr>, /// The size of the stack for the spawned task pub stack_size: Option<uint>, } /// Indicates the manner in which a task exited. /// /// A task that completes without failing is considered to exit successfully. /// /// If you wish for this result's delivery to block until all /// children tasks complete, recommend using a result future. pub type Result = ::core::result::Result<(), Box<Any + Send>>; pub struct GarbageCollector; pub struct LocalStorage(pub Option<local_data::Map>); /// A handle to a blocked task. Usually this means having the Box<Task> /// pointer by ownership, but if the task is killable, a killer can steal it /// at any time. pub enum BlockedTask { Owned(Box<Task>), Shared(Arc<AtomicUint>), } /// Per-task state related to task death, killing, failure, etc. pub struct Death { pub on_exit: Option<proc(Result):Send>, marker: marker::NoCopy, } pub struct BlockedTasks { inner: Arc<AtomicUint>, } impl Task { /// Creates a new uninitialized task. /// /// This method cannot be used to immediately invoke `run` because the task /// itself will likely require a runtime to be inserted via `put_runtime`. /// /// Note that you likely don't want to call this function, but rather the /// task creation functions through libnative or libgreen. pub fn new() -> Task { Task { heap: LocalHeap::new(), gc: GarbageCollector, storage: LocalStorage(None), unwinder: Unwinder::new(), death: Death::new(), state: New, name: None, imp: None, } } /// Consumes ownership of a task, runs some code, and returns the task back. /// /// This function can be used as an emulated "try/catch" to interoperate /// with the rust runtime at the outermost boundary. It is not possible to /// use this function in a nested fashion (a try/catch inside of another /// try/catch). Invoking this function is quite cheap. /// /// If the closure `f` succeeds, then the returned task can be used again /// for another invocation of `run`. If the closure `f` fails then `self` /// will be internally destroyed along with all of the other associated /// resources of this task. The `on_exit` callback is invoked with the /// cause of failure (not returned here). This can be discovered by querying /// `is_destroyed()`. /// /// Note that it is possible to view partial execution of the closure `f` /// because it is not guaranteed to run to completion, but this function is /// guaranteed to return if it fails. Care should be taken to ensure that /// stack references made by `f` are handled appropriately. /// /// It is invalid to call this function with a task that has been previously /// destroyed via a failed call to `run`. /// /// # Example /// /// ```no_run /// extern crate native; /// use std::uint; /// # fn main() { /// /// // Create a new native task /// let task = native::task::new((0, uint::MAX)); /// /// // Run some code once and then destroy this task /// task.run(|| { /// println!("Hello with a native runtime!"); /// }).destroy(); /// # } /// ``` pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> { assert!(!self.is_destroyed(), "cannot re-use a destroyed task"); // First, make sure that no one else is in TLS. This does not allow // recursive invocations of run(). If there's no one else, then // relinquish ownership of ourselves back into TLS. if Local::exists(None::<Task>) { fail!("cannot run a task recursively inside another"); } self.state = Armed; Local::put(self); // There are two primary reasons that general try/catch is unsafe. The // first is that we do not support nested try/catch. The above check for // an existing task in TLS is sufficient for this invariant to be // upheld. The second is that unwinding while unwinding is not defined. // We take care of that by having an 'unwinding' flag in the task // itself. For these reasons, this unsafety should be ok. let result = unsafe { unwind::try(f) }; // After running the closure given return the task back out if it ran // successfully, or clean up the task if it failed. let task: Box<Task> = Local::take(); match result { Ok(()) => task, Err(cause) => { task.cleanup(Err(cause)) } } } /// Destroy all associated resources of this task. /// /// This function will perform any necessary clean up to prepare the task /// for destruction. It is required that this is called before a `Task` /// falls out of scope. /// /// The returned task cannot be used for running any more code, but it may /// be used to extract the runtime as necessary. pub fn destroy(self: Box<Task>) -> Box<Task> { if self.is_destroyed() { self } else { self.cleanup(Ok(())) } } /// Cleans up a task, processing the result of the task as appropriate. /// /// This function consumes ownership of the task, deallocating it once it's /// done being processed. It is assumed that TLD and the local heap have /// already been destroyed and/or annihilated. fn cleanup(self: Box<Task>, result: Result) -> Box<Task> { // The first thing to do when cleaning up is to deallocate our local // resources, such as TLD and GC data. // // FIXME: there are a number of problems with this code // // 1. If any TLD object fails destruction, then all of TLD will leak. // This appears to be a consequence of #14875. // // 2. Failing during GC annihilation aborts the runtime #14876. // // 3. Setting a TLD key while destroying TLD or while destroying GC will // abort the runtime #14807. // // 4. Invoking GC in GC destructors will abort the runtime #6996. // // 5. The order of destruction of TLD and GC matters, but either way is // susceptible to leaks (see 3/4) #8302. // // That being said, there are a few upshots to this code // // 1. If TLD destruction fails, heap destruction will be attempted. // There is a test for this at fail-during-tld-destroy.rs. Sadly the // other way can't be tested due to point 2 above. Note that we must // immortalize the heap first because if any deallocations are // attempted while TLD is being dropped it will attempt to free the // allocation from the wrong heap (because the current one has been // replaced). // // 2. One failure in destruction is tolerable, so long as the task // didn't originally fail while it was running. // // And with all that in mind, we attempt to clean things up! let mut task = self.run(|| { let mut task = Local::borrow(None::<Task>); let tld = { let &LocalStorage(ref mut optmap) = &mut task.storage; optmap.take() }; let mut heap = mem::replace(&mut task.heap, LocalHeap::new()); unsafe { heap.immortalize() } drop(task); // First, destroy task-local storage. This may run user dtors. drop(tld); // Destroy remaining boxes. Also may run user dtors. drop(heap); }); // If the above `run` block failed, then it must be the case that the // task had previously succeeded. This also means that the code below // was recursively run via the `run` method invoking this method. In // this case, we just make sure the world is as we thought, and return. if task.is_destroyed() { rtassert!(result.is_ok()) return task } // After taking care of the data above, we need to transmit the result // of this task. let what_to_do = task.death.on_exit.take(); Local::put(task); // FIXME: this is running in a seriously constrained context. If this // allocates GC or allocates TLD then it will likely abort the // runtime. Similarly, if this fails, this will also likely abort // the runtime. // // This closure is currently limited to a channel send via the // standard library's task interface, but this needs // reconsideration to whether it's a reasonable thing to let a // task to do or not. match what_to_do { Some(f) => { f(result) } None => { drop(result) } } // Now that we're done, we remove the task from TLS and flag it for // destruction. let mut task: Box<Task> = Local::take(); task.state = Destroyed; return task; } /// Queries whether this can be destroyed or not. pub fn is_destroyed(&self) -> bool { self.state == Destroyed } /// Inserts a runtime object into this task, transferring ownership to the /// task. It is illegal to replace a previous runtime object in this task /// with this argument. pub fn put_runtime(&mut self, ops: Box<Runtime + Send + 'static>) { assert!(self.imp.is_none()); self.imp = Some(ops); } /// Removes the runtime from this task, transferring ownership to the /// caller. pub fn take_runtime(&mut self) -> Box<Runtime + Send + 'static> { assert!(self.imp.is_some()); self.imp.take().unwrap() } /// Attempts to extract the runtime as a specific type. If the runtime does /// not have the provided type, then the runtime is not removed. If the /// runtime does have the specified type, then it is removed and returned /// (transfer of ownership). /// /// It is recommended to only use this method when *absolutely necessary*. /// This function may not be available in the future. pub fn maybe_take_runtime<T: 'static>(&mut self) -> Option<Box<T>> { // This is a terrible, terrible function. The general idea here is to // take the runtime, cast it to Box<Any>, check if it has the right // type, and then re-cast it back if necessary. The method of doing // this is pretty sketchy and involves shuffling vtables of trait // objects around, but it gets the job done. // // FIXME: This function is a serious code smell and should be avoided at // all costs. I have yet to think of a method to avoid this // function, and I would be saddened if more usage of the function // crops up. unsafe { let imp = self.imp.take().unwrap(); let vtable = mem::transmute::<_, &raw::TraitObject>(&imp).vtable; match imp.wrap().downcast::<T>() { Ok(t) => Some(t), Err(t) => { let data = mem::transmute::<_, raw::TraitObject>(t).data; let obj: Box<Runtime + Send + 'static> = mem::transmute(raw::TraitObject { vtable: vtable, data: data, }); self.put_runtime(obj); None } } } } /// Spawns a sibling to this task. The newly spawned task is configured with /// the `opts` structure and will run `f` as the body of its code. pub fn spawn_sibling(mut self: Box<Task>, opts: TaskOpts, f: proc(): Send) { let ops = self.imp.take().unwrap(); ops.spawn_sibling(self, opts, f) } /// Deschedules the current task, invoking `f` `amt` times. It is not /// recommended to use this function directly, but rather communication /// primitives in `std::comm` should be used. pub fn deschedule(mut self: Box<Task>, amt: uint, f: |BlockedTask| -> ::core::result::Result<(), BlockedTask>) { let ops = self.imp.take().unwrap(); ops.deschedule(amt, self, f) } /// Wakes up a previously blocked task, optionally specifying whether the /// current task can accept a change in scheduling. This function can only /// be called on tasks that were previously blocked in `deschedule`. pub fn reawaken(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.reawaken(self); } /// Yields control of this task to another task. This function will /// eventually return, but possibly not immediately. This is used as an /// opportunity to allow other tasks a chance to run. pub fn yield_now(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.yield_now(self); } /// Similar to `yield_now`, except that this function may immediately return /// without yielding (depending on what the runtime decides to do). pub fn maybe_yield(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.maybe_yield(self); } /// Acquires a handle to the I/O factory that this task contains, normally /// stored in the task's runtime. This factory may not always be available, /// which is why the return type is `Option` pub fn local_io<'a>(&'a mut self) -> Option<LocalIo<'a>> { self.imp.as_mut().unwrap().local_io() } /// Returns the stack bounds for this task in (lo, hi) format. The stack /// bounds may not be known for all tasks, so the return value may be /// `None`. pub fn stack_bounds(&self) -> (uint, uint) { self.imp.as_ref().unwrap().stack_bounds() } /// Returns whether it is legal for this task to block the OS thread that it /// is running on. pub fn can_block(&self) -> bool { self.imp.as_ref().unwrap().can_block() } /// Consume this task, flagging it as a candidate for destruction. /// /// This function is required to be invoked to destroy a task. A task /// destroyed through a normal drop will abort. pub fn drop(mut self) { self.state = Destroyed; } } impl Drop for Task { fn drop(&mut self) { rtdebug!("called drop for a task: {}", self as *mut Task as uint); rtassert!(self.state != Armed); } } impl TaskOpts { pub fn new() -> TaskOpts { TaskOpts { on_exit: None, name: None, stack_size: None } } } impl Iterator<BlockedTask> for BlockedTasks { fn next(&mut self) -> Option<BlockedTask> { Some(Shared(self.inner.clone())) } } impl BlockedTask { /// Returns Some if the task was successfully woken; None if already killed. pub fn wake(self) -> Option<Box<Task>> { match self { Owned(task) => Some(task), Shared(arc) => { match arc.swap(0, SeqCst) { 0 => None, n => Some(unsafe { mem::transmute(n) }), } } } } /// Reawakens this task if ownership is acquired. If finer-grained control /// is desired, use `wake` instead. pub fn reawaken(self) { self.wake().map(|t| t.reawaken()); } // This assertion has two flavours because the wake involves an atomic op. // In the faster version, destructors will fail dramatically instead. #[cfg(not(test))] pub fn trash(self) { } #[cfg(test)] pub fn trash(self) { assert!(self.wake().is_none()); } /// Create a blocked task, unless the task was already killed. pub fn block(task: Box<Task>) -> BlockedTask { Owned(task) } /// Converts one blocked task handle to a list of many handles to the same. pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> { let arc = match self { Owned(task) => { let flag = unsafe { AtomicUint::new(mem::transmute(task)) }; Arc::new(flag) } Shared(arc) => arc.clone(), }; BlockedTasks{ inner: arc }.take(num_handles) } /// Convert to an unsafe uint value. Useful for storing in a pipe's state /// flag. #[inline] pub unsafe fn cast_to_uint(self) -> uint { match self { Owned(task) =>
Shared(arc) => { let blocked_task_ptr: uint = mem::transmute(box arc); rtassert!(blocked_task_ptr & 0x1 == 0); blocked_task_ptr | 0x1 } } } /// Convert from an unsafe uint value. Useful for retrieving a pipe's state /// flag. #[inline] pub unsafe fn cast_from_uint(blocked_task_ptr: uint) -> BlockedTask { if blocked_task_ptr & 0x1 == 0 { Owned(mem::transmute(blocked_task_ptr)) } else { let ptr: Box<Arc<AtomicUint>> = mem::transmute(blocked_task_ptr & !1); Shared(*ptr) } } } impl Death { pub fn new() -> Death { Death { on_exit: None, marker: marker::NoCopy } } } #[cfg(test)] mod test { use super::*; use std::prelude::*; use std::task; use std::gc::{Gc, GC}; #[test] fn local_heap() { let a = box(GC) 5i; let b = a; assert!(*a == 5); assert!(*b == 5); } #[test] fn tls() { local_data_key!(key: Gc<String>) key.replace(Some(box(GC) "data".to_string())); assert_eq!(key.get().unwrap().as_slice(), "data"); local_data_key!(key2: Gc<String>) key2.replace(Some(box(GC) "data".to_string())); assert_eq!(key2.get().unwrap().as_slice(), "data"); } #[test] fn unwind() { let result = task::try(proc()()); rtdebug!("trying first assert"); assert!(result.is_ok()); let result = task::try::<()>(proc() fail!()); rtdebug!("trying second assert"); assert!(result.is_err()); } #[test] fn rng() { use std::rand::{StdRng, Rng}; let mut r = StdRng::new().ok().unwrap(); let _ = r.next_u32(); } #[test] fn comm_stream() { let (tx, rx) = channel(); tx.send(10i); assert!(rx.recv() == 10); } #[test] fn comm_shared_chan() { let (tx, rx) = channel(); tx.send(10i); assert!(rx.recv() == 10); } #[test] fn heap_cycles() { use std::cell::RefCell; struct List { next: Option<Gc<RefCell<List>>>, } let a = box(GC) RefCell::new(List { next: None }); let b = box(GC) RefCell::new(List { next: Some(a) }); { let mut a = a.borrow_mut(); a.next = Some(b); } } #[test] #[should_fail] fn test_begin_unwind() { use std::rt::unwind::begin_unwind; begin_unwind("cause", &(file!(), line!())) } #[test] fn drop_new_task_ok() { drop(Task::new()); } // Task blocking tests #[test] fn block_and_wake() { let task = box Task::new(); let mut task = BlockedTask::block(task).wake().unwrap(); task.drop(); } }
{ let blocked_task_ptr: uint = mem::transmute(task); rtassert!(blocked_task_ptr & 0x1 == 0); blocked_task_ptr }
conditional_block
task.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Language-level runtime services that should reasonably expected //! to be available 'everywhere'. Local heaps, GC, unwinding, //! local storage, and logging. Even a 'freestanding' Rust would likely want //! to implement this. use alloc::arc::Arc; use alloc::boxed::{BoxAny, Box}; use core::any::Any; use core::atomic::{AtomicUint, SeqCst}; use core::iter::Take; use core::kinds::marker; use core::mem; use core::prelude::{Clone, Drop, Err, Iterator, None, Ok, Option, Send, Some}; use core::prelude::{drop}; use core::raw; use local_data; use Runtime; use local::Local; use local_heap::LocalHeap; use rtio::LocalIo; use unwind; use unwind::Unwinder; use collections::str::SendStr; /// State associated with Rust tasks. /// /// Rust tasks are primarily built with two separate components. One is this /// structure which handles standard services such as TLD, unwinding support, /// naming of a task, etc. The second component is the runtime of this task, a /// `Runtime` trait object. /// /// The `Runtime` object instructs this task how it can perform critical /// operations such as blocking, rescheduling, I/O constructors, etc. The two /// halves are separately owned, but one is often found contained in the other. /// A task's runtime can be reflected upon with the `maybe_take_runtime` method, /// and otherwise its ownership is managed with `take_runtime` and /// `put_runtime`. /// /// In general, this structure should not be used. This is meant to be an /// unstable internal detail of the runtime itself. From time-to-time, however, /// it is useful to manage tasks directly. An example of this would be /// interoperating with the Rust runtime from FFI callbacks or such. For this /// reason, there are two methods of note with the `Task` structure. /// /// * `run` - This function will execute a closure inside the context of a task. /// Failure is caught and handled via the task's on_exit callback. If /// this fails, the task is still returned, but it can no longer be /// used, it is poisoned. /// /// * `destroy` - This is a required function to call to destroy a task. If a /// task falls out of scope without calling `destroy`, its /// destructor bomb will go off, aborting the process. /// /// With these two methods, tasks can be re-used to execute code inside of its /// context while having a point in the future where destruction is allowed. /// More information can be found on these specific methods. /// /// # Example /// /// ```no_run /// extern crate native; /// use std::uint; /// # fn main() { /// /// // Create a task using a native runtime /// let task = native::task::new((0, uint::MAX)); /// /// // Run some code, catching any possible failures /// let task = task.run(|| { /// // Run some code inside this task /// println!("Hello with a native runtime!"); /// }); /// /// // Run some code again, catching the failure /// let task = task.run(|| { /// fail!("oh no, what to do!"); /// }); /// /// // Now that the task is failed, it can never be used again /// assert!(task.is_destroyed()); /// /// // Deallocate the resources associated with this task /// task.destroy(); /// # } /// ``` pub struct Task { pub heap: LocalHeap, pub gc: GarbageCollector, pub storage: LocalStorage, pub unwinder: Unwinder, pub death: Death, pub name: Option<SendStr>, state: TaskState, imp: Option<Box<Runtime + Send + 'static>>, } // Once a task has entered the `Armed` state it must be destroyed via `drop`, // and no other method. This state is used to track this transition. #[deriving(PartialEq)] enum TaskState { New, Armed, Destroyed, } pub struct TaskOpts { /// Invoke this procedure with the result of the task when it finishes. pub on_exit: Option<proc(Result): Send>, /// A name for the task-to-be, for identification in failure messages pub name: Option<SendStr>, /// The size of the stack for the spawned task pub stack_size: Option<uint>, } /// Indicates the manner in which a task exited. /// /// A task that completes without failing is considered to exit successfully. /// /// If you wish for this result's delivery to block until all /// children tasks complete, recommend using a result future. pub type Result = ::core::result::Result<(), Box<Any + Send>>; pub struct GarbageCollector; pub struct LocalStorage(pub Option<local_data::Map>); /// A handle to a blocked task. Usually this means having the Box<Task> /// pointer by ownership, but if the task is killable, a killer can steal it /// at any time. pub enum BlockedTask { Owned(Box<Task>), Shared(Arc<AtomicUint>), } /// Per-task state related to task death, killing, failure, etc. pub struct Death { pub on_exit: Option<proc(Result):Send>, marker: marker::NoCopy, } pub struct BlockedTasks { inner: Arc<AtomicUint>, } impl Task { /// Creates a new uninitialized task. /// /// This method cannot be used to immediately invoke `run` because the task /// itself will likely require a runtime to be inserted via `put_runtime`. /// /// Note that you likely don't want to call this function, but rather the /// task creation functions through libnative or libgreen. pub fn new() -> Task { Task { heap: LocalHeap::new(), gc: GarbageCollector, storage: LocalStorage(None), unwinder: Unwinder::new(), death: Death::new(), state: New, name: None, imp: None, } } /// Consumes ownership of a task, runs some code, and returns the task back. /// /// This function can be used as an emulated "try/catch" to interoperate /// with the rust runtime at the outermost boundary. It is not possible to /// use this function in a nested fashion (a try/catch inside of another /// try/catch). Invoking this function is quite cheap. /// /// If the closure `f` succeeds, then the returned task can be used again /// for another invocation of `run`. If the closure `f` fails then `self` /// will be internally destroyed along with all of the other associated /// resources of this task. The `on_exit` callback is invoked with the /// cause of failure (not returned here). This can be discovered by querying /// `is_destroyed()`. /// /// Note that it is possible to view partial execution of the closure `f` /// because it is not guaranteed to run to completion, but this function is /// guaranteed to return if it fails. Care should be taken to ensure that /// stack references made by `f` are handled appropriately. /// /// It is invalid to call this function with a task that has been previously /// destroyed via a failed call to `run`. /// /// # Example /// /// ```no_run /// extern crate native; /// use std::uint; /// # fn main() { /// /// // Create a new native task /// let task = native::task::new((0, uint::MAX)); /// /// // Run some code once and then destroy this task /// task.run(|| { /// println!("Hello with a native runtime!"); /// }).destroy(); /// # } /// ``` pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> { assert!(!self.is_destroyed(), "cannot re-use a destroyed task"); // First, make sure that no one else is in TLS. This does not allow // recursive invocations of run(). If there's no one else, then // relinquish ownership of ourselves back into TLS. if Local::exists(None::<Task>) { fail!("cannot run a task recursively inside another"); } self.state = Armed; Local::put(self); // There are two primary reasons that general try/catch is unsafe. The // first is that we do not support nested try/catch. The above check for // an existing task in TLS is sufficient for this invariant to be // upheld. The second is that unwinding while unwinding is not defined. // We take care of that by having an 'unwinding' flag in the task // itself. For these reasons, this unsafety should be ok. let result = unsafe { unwind::try(f) }; // After running the closure given return the task back out if it ran // successfully, or clean up the task if it failed. let task: Box<Task> = Local::take(); match result { Ok(()) => task, Err(cause) => { task.cleanup(Err(cause)) } } } /// Destroy all associated resources of this task. /// /// This function will perform any necessary clean up to prepare the task /// for destruction. It is required that this is called before a `Task` /// falls out of scope. /// /// The returned task cannot be used for running any more code, but it may /// be used to extract the runtime as necessary. pub fn destroy(self: Box<Task>) -> Box<Task> { if self.is_destroyed() { self } else { self.cleanup(Ok(())) } } /// Cleans up a task, processing the result of the task as appropriate. /// /// This function consumes ownership of the task, deallocating it once it's /// done being processed. It is assumed that TLD and the local heap have /// already been destroyed and/or annihilated. fn cleanup(self: Box<Task>, result: Result) -> Box<Task> { // The first thing to do when cleaning up is to deallocate our local // resources, such as TLD and GC data. // // FIXME: there are a number of problems with this code // // 1. If any TLD object fails destruction, then all of TLD will leak. // This appears to be a consequence of #14875. // // 2. Failing during GC annihilation aborts the runtime #14876. // // 3. Setting a TLD key while destroying TLD or while destroying GC will // abort the runtime #14807. // // 4. Invoking GC in GC destructors will abort the runtime #6996. // // 5. The order of destruction of TLD and GC matters, but either way is // susceptible to leaks (see 3/4) #8302. // // That being said, there are a few upshots to this code // // 1. If TLD destruction fails, heap destruction will be attempted. // There is a test for this at fail-during-tld-destroy.rs. Sadly the // other way can't be tested due to point 2 above. Note that we must // immortalize the heap first because if any deallocations are // attempted while TLD is being dropped it will attempt to free the // allocation from the wrong heap (because the current one has been // replaced). // // 2. One failure in destruction is tolerable, so long as the task // didn't originally fail while it was running. // // And with all that in mind, we attempt to clean things up! let mut task = self.run(|| { let mut task = Local::borrow(None::<Task>); let tld = { let &LocalStorage(ref mut optmap) = &mut task.storage; optmap.take() }; let mut heap = mem::replace(&mut task.heap, LocalHeap::new()); unsafe { heap.immortalize() } drop(task); // First, destroy task-local storage. This may run user dtors. drop(tld); // Destroy remaining boxes. Also may run user dtors. drop(heap); }); // If the above `run` block failed, then it must be the case that the // task had previously succeeded. This also means that the code below // was recursively run via the `run` method invoking this method. In // this case, we just make sure the world is as we thought, and return. if task.is_destroyed() { rtassert!(result.is_ok()) return task } // After taking care of the data above, we need to transmit the result // of this task. let what_to_do = task.death.on_exit.take(); Local::put(task); // FIXME: this is running in a seriously constrained context. If this // allocates GC or allocates TLD then it will likely abort the // runtime. Similarly, if this fails, this will also likely abort // the runtime. // // This closure is currently limited to a channel send via the // standard library's task interface, but this needs // reconsideration to whether it's a reasonable thing to let a // task to do or not. match what_to_do { Some(f) => { f(result) } None => { drop(result) } } // Now that we're done, we remove the task from TLS and flag it for // destruction. let mut task: Box<Task> = Local::take(); task.state = Destroyed; return task; } /// Queries whether this can be destroyed or not. pub fn is_destroyed(&self) -> bool { self.state == Destroyed } /// Inserts a runtime object into this task, transferring ownership to the /// task. It is illegal to replace a previous runtime object in this task /// with this argument. pub fn put_runtime(&mut self, ops: Box<Runtime + Send + 'static>) { assert!(self.imp.is_none()); self.imp = Some(ops); } /// Removes the runtime from this task, transferring ownership to the /// caller. pub fn take_runtime(&mut self) -> Box<Runtime + Send + 'static> { assert!(self.imp.is_some()); self.imp.take().unwrap() } /// Attempts to extract the runtime as a specific type. If the runtime does /// not have the provided type, then the runtime is not removed. If the /// runtime does have the specified type, then it is removed and returned /// (transfer of ownership). /// /// It is recommended to only use this method when *absolutely necessary*. /// This function may not be available in the future. pub fn maybe_take_runtime<T: 'static>(&mut self) -> Option<Box<T>> { // This is a terrible, terrible function. The general idea here is to // take the runtime, cast it to Box<Any>, check if it has the right // type, and then re-cast it back if necessary. The method of doing // this is pretty sketchy and involves shuffling vtables of trait // objects around, but it gets the job done. // // FIXME: This function is a serious code smell and should be avoided at // all costs. I have yet to think of a method to avoid this // function, and I would be saddened if more usage of the function // crops up. unsafe { let imp = self.imp.take().unwrap(); let vtable = mem::transmute::<_, &raw::TraitObject>(&imp).vtable; match imp.wrap().downcast::<T>() { Ok(t) => Some(t), Err(t) => { let data = mem::transmute::<_, raw::TraitObject>(t).data; let obj: Box<Runtime + Send + 'static> = mem::transmute(raw::TraitObject { vtable: vtable, data: data, }); self.put_runtime(obj); None } } } } /// Spawns a sibling to this task. The newly spawned task is configured with /// the `opts` structure and will run `f` as the body of its code. pub fn spawn_sibling(mut self: Box<Task>, opts: TaskOpts, f: proc(): Send) { let ops = self.imp.take().unwrap(); ops.spawn_sibling(self, opts, f) } /// Deschedules the current task, invoking `f` `amt` times. It is not /// recommended to use this function directly, but rather communication /// primitives in `std::comm` should be used. pub fn deschedule(mut self: Box<Task>, amt: uint, f: |BlockedTask| -> ::core::result::Result<(), BlockedTask>) { let ops = self.imp.take().unwrap(); ops.deschedule(amt, self, f) } /// Wakes up a previously blocked task, optionally specifying whether the /// current task can accept a change in scheduling. This function can only /// be called on tasks that were previously blocked in `deschedule`. pub fn reawaken(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.reawaken(self); } /// Yields control of this task to another task. This function will /// eventually return, but possibly not immediately. This is used as an /// opportunity to allow other tasks a chance to run. pub fn yield_now(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.yield_now(self); } /// Similar to `yield_now`, except that this function may immediately return /// without yielding (depending on what the runtime decides to do). pub fn maybe_yield(mut self: Box<Task>) { let ops = self.imp.take().unwrap(); ops.maybe_yield(self); } /// Acquires a handle to the I/O factory that this task contains, normally /// stored in the task's runtime. This factory may not always be available, /// which is why the return type is `Option` pub fn local_io<'a>(&'a mut self) -> Option<LocalIo<'a>> { self.imp.as_mut().unwrap().local_io() } /// Returns the stack bounds for this task in (lo, hi) format. The stack /// bounds may not be known for all tasks, so the return value may be /// `None`. pub fn stack_bounds(&self) -> (uint, uint) { self.imp.as_ref().unwrap().stack_bounds() } /// Returns whether it is legal for this task to block the OS thread that it /// is running on. pub fn can_block(&self) -> bool { self.imp.as_ref().unwrap().can_block() } /// Consume this task, flagging it as a candidate for destruction. /// /// This function is required to be invoked to destroy a task. A task /// destroyed through a normal drop will abort. pub fn drop(mut self) { self.state = Destroyed; } } impl Drop for Task { fn drop(&mut self) { rtdebug!("called drop for a task: {}", self as *mut Task as uint); rtassert!(self.state != Armed); } } impl TaskOpts { pub fn new() -> TaskOpts { TaskOpts { on_exit: None, name: None, stack_size: None } } } impl Iterator<BlockedTask> for BlockedTasks { fn next(&mut self) -> Option<BlockedTask> { Some(Shared(self.inner.clone())) } } impl BlockedTask { /// Returns Some if the task was successfully woken; None if already killed. pub fn wake(self) -> Option<Box<Task>> { match self { Owned(task) => Some(task), Shared(arc) => { match arc.swap(0, SeqCst) { 0 => None, n => Some(unsafe { mem::transmute(n) }), } } } } /// Reawakens this task if ownership is acquired. If finer-grained control /// is desired, use `wake` instead. pub fn reawaken(self) { self.wake().map(|t| t.reawaken()); } // This assertion has two flavours because the wake involves an atomic op. // In the faster version, destructors will fail dramatically instead. #[cfg(not(test))] pub fn trash(self) { } #[cfg(test)] pub fn trash(self)
/// Create a blocked task, unless the task was already killed. pub fn block(task: Box<Task>) -> BlockedTask { Owned(task) } /// Converts one blocked task handle to a list of many handles to the same. pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> { let arc = match self { Owned(task) => { let flag = unsafe { AtomicUint::new(mem::transmute(task)) }; Arc::new(flag) } Shared(arc) => arc.clone(), }; BlockedTasks{ inner: arc }.take(num_handles) } /// Convert to an unsafe uint value. Useful for storing in a pipe's state /// flag. #[inline] pub unsafe fn cast_to_uint(self) -> uint { match self { Owned(task) => { let blocked_task_ptr: uint = mem::transmute(task); rtassert!(blocked_task_ptr & 0x1 == 0); blocked_task_ptr } Shared(arc) => { let blocked_task_ptr: uint = mem::transmute(box arc); rtassert!(blocked_task_ptr & 0x1 == 0); blocked_task_ptr | 0x1 } } } /// Convert from an unsafe uint value. Useful for retrieving a pipe's state /// flag. #[inline] pub unsafe fn cast_from_uint(blocked_task_ptr: uint) -> BlockedTask { if blocked_task_ptr & 0x1 == 0 { Owned(mem::transmute(blocked_task_ptr)) } else { let ptr: Box<Arc<AtomicUint>> = mem::transmute(blocked_task_ptr & !1); Shared(*ptr) } } } impl Death { pub fn new() -> Death { Death { on_exit: None, marker: marker::NoCopy } } } #[cfg(test)] mod test { use super::*; use std::prelude::*; use std::task; use std::gc::{Gc, GC}; #[test] fn local_heap() { let a = box(GC) 5i; let b = a; assert!(*a == 5); assert!(*b == 5); } #[test] fn tls() { local_data_key!(key: Gc<String>) key.replace(Some(box(GC) "data".to_string())); assert_eq!(key.get().unwrap().as_slice(), "data"); local_data_key!(key2: Gc<String>) key2.replace(Some(box(GC) "data".to_string())); assert_eq!(key2.get().unwrap().as_slice(), "data"); } #[test] fn unwind() { let result = task::try(proc()()); rtdebug!("trying first assert"); assert!(result.is_ok()); let result = task::try::<()>(proc() fail!()); rtdebug!("trying second assert"); assert!(result.is_err()); } #[test] fn rng() { use std::rand::{StdRng, Rng}; let mut r = StdRng::new().ok().unwrap(); let _ = r.next_u32(); } #[test] fn comm_stream() { let (tx, rx) = channel(); tx.send(10i); assert!(rx.recv() == 10); } #[test] fn comm_shared_chan() { let (tx, rx) = channel(); tx.send(10i); assert!(rx.recv() == 10); } #[test] fn heap_cycles() { use std::cell::RefCell; struct List { next: Option<Gc<RefCell<List>>>, } let a = box(GC) RefCell::new(List { next: None }); let b = box(GC) RefCell::new(List { next: Some(a) }); { let mut a = a.borrow_mut(); a.next = Some(b); } } #[test] #[should_fail] fn test_begin_unwind() { use std::rt::unwind::begin_unwind; begin_unwind("cause", &(file!(), line!())) } #[test] fn drop_new_task_ok() { drop(Task::new()); } // Task blocking tests #[test] fn block_and_wake() { let task = box Task::new(); let mut task = BlockedTask::block(task).wake().unwrap(); task.drop(); } }
{ assert!(self.wake().is_none()); }
identifier_body
reducer_qos_test.ts
jest.mock("../../redux/store", () => ({ store: { dispatch: jest.fn(), getState: jest.fn(() => ({ NO: "NO" })), } })); import { connectivityReducer, DEFAULT_STATE } from "../reducer"; import { Actions } from "../../constants"; import { pingOK, pingNO } from ".."; import { store } from "../../redux/store"; import { cloneDeep } from "lodash"; describe("connectivity reducer", () => { const newState = () => { const action = { type: Actions.PING_START, payload: { id: "yep" } }; return connectivityReducer(DEFAULT_STATE, action); }; it("starts a ping", () => { const ping = newState().pings["yep"]; expect(ping?.kind).toBe("pending"); }); it("handles the PING_OK action", () => { const action = { type: Actions.PING_OK, payload: { id: "yep", at: 123 } }; const state = connectivityReducer(newState(), action); const { yep } = state.pings; expect(yep).toBeTruthy(); if (yep) { expect(yep.kind).toEqual("complete"); } }); it("broadcasts PING_OK", () => { pingOK("yep", 123); expect(store.dispatch).toHaveBeenCalledWith({ payload: { at: 123, id: "yep" }, type: "PING_OK", }); }); it("broadcasts PING_NO", () => { pingNO("yep", 123); expect(store.dispatch).toHaveBeenCalledWith({ payload: { id: "yep", at: 123 }, type: "PING_NO"
it("marks pings as failed when PING_NO is dispatched", () => { const action = { type: Actions.PING_NO, payload: { id: "yep", at: 123 } }; const state = connectivityReducer(newState(), action); const { yep } = state.pings; expect(yep).toBeTruthy(); if (yep) { expect(yep.kind).toEqual("timeout"); } }); it("doesn't bring network state down with old pings", () => { const oldState = cloneDeep(DEFAULT_STATE); oldState.pings = { "a": { kind: "pending", start: 50 }, "b": { kind: "complete", start: 100, end: 200 }, }; const action = { type: Actions.PING_NO, payload: { id: "a" } }; const state = connectivityReducer(oldState, action); expect(state.uptime["bot.mqtt"]).toEqual(undefined); }); });
}); });
random_line_split
reducer_qos_test.ts
jest.mock("../../redux/store", () => ({ store: { dispatch: jest.fn(), getState: jest.fn(() => ({ NO: "NO" })), } })); import { connectivityReducer, DEFAULT_STATE } from "../reducer"; import { Actions } from "../../constants"; import { pingOK, pingNO } from ".."; import { store } from "../../redux/store"; import { cloneDeep } from "lodash"; describe("connectivity reducer", () => { const newState = () => { const action = { type: Actions.PING_START, payload: { id: "yep" } }; return connectivityReducer(DEFAULT_STATE, action); }; it("starts a ping", () => { const ping = newState().pings["yep"]; expect(ping?.kind).toBe("pending"); }); it("handles the PING_OK action", () => { const action = { type: Actions.PING_OK, payload: { id: "yep", at: 123 } }; const state = connectivityReducer(newState(), action); const { yep } = state.pings; expect(yep).toBeTruthy(); if (yep)
}); it("broadcasts PING_OK", () => { pingOK("yep", 123); expect(store.dispatch).toHaveBeenCalledWith({ payload: { at: 123, id: "yep" }, type: "PING_OK", }); }); it("broadcasts PING_NO", () => { pingNO("yep", 123); expect(store.dispatch).toHaveBeenCalledWith({ payload: { id: "yep", at: 123 }, type: "PING_NO" }); }); it("marks pings as failed when PING_NO is dispatched", () => { const action = { type: Actions.PING_NO, payload: { id: "yep", at: 123 } }; const state = connectivityReducer(newState(), action); const { yep } = state.pings; expect(yep).toBeTruthy(); if (yep) { expect(yep.kind).toEqual("timeout"); } }); it("doesn't bring network state down with old pings", () => { const oldState = cloneDeep(DEFAULT_STATE); oldState.pings = { "a": { kind: "pending", start: 50 }, "b": { kind: "complete", start: 100, end: 200 }, }; const action = { type: Actions.PING_NO, payload: { id: "a" } }; const state = connectivityReducer(oldState, action); expect(state.uptime["bot.mqtt"]).toEqual(undefined); }); });
{ expect(yep.kind).toEqual("complete"); }
conditional_block
ymovies.py
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,hashlib,random,string,json,base64 from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import cache from resources.lib.modules import directstream class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['yesmovies.to'] self.base_link = 'https://yesmovies.to' self.info_link = '/ajax/movie_info/%s.html' self.episode_link = '/ajax/v3_movie_get_episodes/%s/%s/%s/%s.html' self.playlist_link = '/ajax/v2_get_sources/%s.html?hash=%s' def movie(self, imdb, title, localtitle, year): try: t = cleantitle.get(title) q = '/search/%s.html' % (urllib.quote_plus(cleantitle.query(title))) q = urlparse.urljoin(self.base_link, q) for i in range(3): r = client.request(q) if not r == None: break r = client.parseDOM(r, 'div', attrs = {'class': 'ml-item'}) r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title')) for i in r] r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] r = [i[0] for i in r if t == cleantitle.get(i[1])][:2] r = [(i, re.findall('(\d+)', i)[-1]) for i in r] for i in r: try: y, q = cache.get(self.ymovies_info, 9000, i[1]) if not y == year: raise Exception() return urlparse.urlparse(i[0]).path except: pass except: return def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, year): try: url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year} url = urllib.urlencode(url) return url except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode):
def ymovies_info_season(self, title, season): try: q = '%s Season %s' % (cleantitle.query(title), season) q = '/search/%s.html' % (urllib.quote_plus(q)) q = urlparse.urljoin(self.base_link, q) for i in range(3): r = client.request(q) if not r == None: break r = client.parseDOM(r, 'div', attrs = {'class': 'ml-item'}) r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title')) for i in r] r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] return r except: return def ymovies_info(self, url): try: u = urlparse.urljoin(self.base_link, self.info_link) for i in range(3): r = client.request(u % url) if not r == None: break q = client.parseDOM(r, 'div', attrs = {'class': 'jtip-quality'})[0] y = client.parseDOM(r, 'div', attrs = {'class': 'jt-info'}) y = [i.strip() for i in y if i.strip().isdigit() and len(i.strip()) == 4][0] return (y, q) except: return def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources try: url, episode = re.findall('(.+?)\?episode=(\d*)$', url)[0] except: episode = None url = urlparse.urljoin(self.base_link, url) vid_id = re.findall('-(\d+)', url)[-1] ''' quality = cache.get(self.ymovies_info, 9000, vid_id)[1].lower() if quality == 'cam' or quality == 'ts': quality = 'CAM' elif quality == 'hd': quality = 'HD' else: quality = 'SD' ''' for i in range(3): r = client.request(url) if not r == None: break ref = client.parseDOM(r, 'a', ret='href', attrs = {'class': 'mod-btn mod-btn-watch'})[0] ref = urlparse.urljoin(self.base_link, ref) for i in range(3): r = client.request(ref, referer=url) if not r == None: break c = client.parseDOM(r, 'img', ret='src', attrs = {'class': 'hidden'}) if c: cookie = client.request(c[0], referer=ref, output='cookie') else: cookie = '' server = re.findall('server\s*:\s*"(.+?)"', r)[0] type = re.findall('type\s*:\s*"(.+?)"', r)[0] episode_id = re.findall('episode_id\s*:\s*"(.+?)"', r)[0] r = self.episode_link % (vid_id, server, episode_id, type) u = urlparse.urljoin(self.base_link, r) for i in range(13): r = client.request(u, referer=ref) if not r == None: break r = re.compile('(<li.+?/li>)', re.DOTALL).findall(r) r = [(client.parseDOM(i, 'li', ret='onclick'), client.parseDOM(i, 'a', ret='title')) for i in r] if not episode == None: r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] r = [(i[0], ''.join(re.findall('(\d+)', i[1])[:1])) for i in r] r = [i[0] for i in r if '%01d' % int(i[1]) == episode] else: r = [i[0][0] for i in r if i[0]] r = [re.findall('(\d+)', i) for i in r] r = [i[:2] for i in r if len(i) > 1] r = [i[0] for i in r if 1 <= int(i[1]) <= 11][:3] for u in r: try: key = 'xwh38if39ucx' ; key2 = '8qhfm9oyq1ux' ; key3 = 'ctiw4zlrn09tau7kqvc153uo' k = u + key3 v = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6)) c = key + u + key2 + '=%s' % v c = '%s; %s' % (cookie, c) url = urllib.quote(uncensored(k, v)) url = '/ajax/v2_get_sources/%s?hash=%s' % (u, url) url = urlparse.urljoin(self.base_link, url) for i in range(3): u = client.request(url, referer=ref, cookie=c, timeout='10') if not u == None: break u = json.loads(u)['playlist'][0]['sources'] u = [i['file'] for i in u if 'file' in i] for i in u: try: sources.append({'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'en', 'url': i, 'direct': True, 'debridonly': False}) except: pass except: pass return sources except: return sources def resolve(self, url): return directstream.googlepass(url) def uncensored(a,b): x = '' ; i = 0 for i, y in enumerate(a): z = b[i % len(b) - 1] y = int(ord(str(y)[0])) + int(ord(str(z)[0])) x += chr(y) x = base64.b64encode(x) return x
try: data = urlparse.parse_qs(url) data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data]) t = cleantitle.get(data['tvshowtitle']) title = data['tvshowtitle'] season = '%01d' % int(season) ; episode = '%01d' % int(episode) year = re.findall('(\d{4})', premiered)[0] years = [str(year), str(int(year)+1), str(int(year)-1)] r = cache.get(self.ymovies_info_season, 720, title, season) r = [(i[0], re.findall('(.+?)\s+(?:-|)\s+season\s+(\d+)$', i[1].lower())) for i in r] r = [(i[0], i[1][0][0], i[1][0][1]) for i in r if i[1]] r = [i[0] for i in r if t == cleantitle.get(i[1]) and season == '%01d' % int(i[2])][:2] r = [(i, re.findall('(\d+)', i)[-1]) for i in r] for i in r: try: y, q = cache.get(self.ymovies_info, 9000, i[1]) if not y == year: raise Exception() return urlparse.urlparse(i[0]).path + '?episode=%01d' % int(episode) except: pass except: return
identifier_body
ymovies.py
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,hashlib,random,string,json,base64 from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import cache from resources.lib.modules import directstream class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['yesmovies.to'] self.base_link = 'https://yesmovies.to' self.info_link = '/ajax/movie_info/%s.html' self.episode_link = '/ajax/v3_movie_get_episodes/%s/%s/%s/%s.html' self.playlist_link = '/ajax/v2_get_sources/%s.html?hash=%s' def movie(self, imdb, title, localtitle, year): try: t = cleantitle.get(title) q = '/search/%s.html' % (urllib.quote_plus(cleantitle.query(title))) q = urlparse.urljoin(self.base_link, q) for i in range(3): r = client.request(q) if not r == None: break r = client.parseDOM(r, 'div', attrs = {'class': 'ml-item'}) r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title')) for i in r] r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] r = [i[0] for i in r if t == cleantitle.get(i[1])][:2] r = [(i, re.findall('(\d+)', i)[-1]) for i in r] for i in r: try: y, q = cache.get(self.ymovies_info, 9000, i[1]) if not y == year: raise Exception() return urlparse.urlparse(i[0]).path except: pass except: return def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, year): try: url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year} url = urllib.urlencode(url) return url except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: data = urlparse.parse_qs(url) data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data]) t = cleantitle.get(data['tvshowtitle']) title = data['tvshowtitle'] season = '%01d' % int(season) ; episode = '%01d' % int(episode) year = re.findall('(\d{4})', premiered)[0] years = [str(year), str(int(year)+1), str(int(year)-1)] r = cache.get(self.ymovies_info_season, 720, title, season) r = [(i[0], re.findall('(.+?)\s+(?:-|)\s+season\s+(\d+)$', i[1].lower())) for i in r] r = [(i[0], i[1][0][0], i[1][0][1]) for i in r if i[1]] r = [i[0] for i in r if t == cleantitle.get(i[1]) and season == '%01d' % int(i[2])][:2] r = [(i, re.findall('(\d+)', i)[-1]) for i in r] for i in r: try: y, q = cache.get(self.ymovies_info, 9000, i[1]) if not y == year: raise Exception() return urlparse.urlparse(i[0]).path + '?episode=%01d' % int(episode) except: pass except: return def ymovies_info_season(self, title, season): try: q = '%s Season %s' % (cleantitle.query(title), season) q = '/search/%s.html' % (urllib.quote_plus(q)) q = urlparse.urljoin(self.base_link, q) for i in range(3): r = client.request(q) if not r == None: break r = client.parseDOM(r, 'div', attrs = {'class': 'ml-item'}) r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title')) for i in r] r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] return r except: return def ymovies_info(self, url): try: u = urlparse.urljoin(self.base_link, self.info_link) for i in range(3): r = client.request(u % url) if not r == None: break q = client.parseDOM(r, 'div', attrs = {'class': 'jtip-quality'})[0] y = client.parseDOM(r, 'div', attrs = {'class': 'jt-info'}) y = [i.strip() for i in y if i.strip().isdigit() and len(i.strip()) == 4][0] return (y, q) except: return def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources try: url, episode = re.findall('(.+?)\?episode=(\d*)$', url)[0] except: episode = None url = urlparse.urljoin(self.base_link, url) vid_id = re.findall('-(\d+)', url)[-1] ''' quality = cache.get(self.ymovies_info, 9000, vid_id)[1].lower() if quality == 'cam' or quality == 'ts': quality = 'CAM' elif quality == 'hd': quality = 'HD' else: quality = 'SD' ''' for i in range(3): r = client.request(url) if not r == None: break ref = client.parseDOM(r, 'a', ret='href', attrs = {'class': 'mod-btn mod-btn-watch'})[0] ref = urlparse.urljoin(self.base_link, ref) for i in range(3): r = client.request(ref, referer=url) if not r == None: break c = client.parseDOM(r, 'img', ret='src', attrs = {'class': 'hidden'}) if c: cookie = client.request(c[0], referer=ref, output='cookie') else: cookie = '' server = re.findall('server\s*:\s*"(.+?)"', r)[0] type = re.findall('type\s*:\s*"(.+?)"', r)[0] episode_id = re.findall('episode_id\s*:\s*"(.+?)"', r)[0] r = self.episode_link % (vid_id, server, episode_id, type) u = urlparse.urljoin(self.base_link, r) for i in range(13): r = client.request(u, referer=ref) if not r == None: break r = re.compile('(<li.+?/li>)', re.DOTALL).findall(r) r = [(client.parseDOM(i, 'li', ret='onclick'), client.parseDOM(i, 'a', ret='title')) for i in r] if not episode == None: r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] r = [(i[0], ''.join(re.findall('(\d+)', i[1])[:1])) for i in r] r = [i[0] for i in r if '%01d' % int(i[1]) == episode] else: r = [i[0][0] for i in r if i[0]] r = [re.findall('(\d+)', i) for i in r] r = [i[:2] for i in r if len(i) > 1] r = [i[0] for i in r if 1 <= int(i[1]) <= 11][:3] for u in r: try: key = 'xwh38if39ucx' ; key2 = '8qhfm9oyq1ux' ; key3 = 'ctiw4zlrn09tau7kqvc153uo' k = u + key3 v = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6)) c = key + u + key2 + '=%s' % v c = '%s; %s' % (cookie, c) url = urllib.quote(uncensored(k, v)) url = '/ajax/v2_get_sources/%s?hash=%s' % (u, url) url = urlparse.urljoin(self.base_link, url) for i in range(3): u = client.request(url, referer=ref, cookie=c, timeout='10') if not u == None: break u = json.loads(u)['playlist'][0]['sources'] u = [i['file'] for i in u if 'file' in i] for i in u: try: sources.append({'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'en', 'url': i, 'direct': True, 'debridonly': False}) except: pass except: pass return sources except: return sources def
(self, url): return directstream.googlepass(url) def uncensored(a,b): x = '' ; i = 0 for i, y in enumerate(a): z = b[i % len(b) - 1] y = int(ord(str(y)[0])) + int(ord(str(z)[0])) x += chr(y) x = base64.b64encode(x) return x
resolve
identifier_name
ymovies.py
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,hashlib,random,string,json,base64 from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import cache from resources.lib.modules import directstream class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['yesmovies.to'] self.base_link = 'https://yesmovies.to' self.info_link = '/ajax/movie_info/%s.html' self.episode_link = '/ajax/v3_movie_get_episodes/%s/%s/%s/%s.html' self.playlist_link = '/ajax/v2_get_sources/%s.html?hash=%s' def movie(self, imdb, title, localtitle, year): try: t = cleantitle.get(title) q = '/search/%s.html' % (urllib.quote_plus(cleantitle.query(title))) q = urlparse.urljoin(self.base_link, q) for i in range(3): r = client.request(q) if not r == None: break r = client.parseDOM(r, 'div', attrs = {'class': 'ml-item'}) r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title')) for i in r] r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] r = [i[0] for i in r if t == cleantitle.get(i[1])][:2] r = [(i, re.findall('(\d+)', i)[-1]) for i in r] for i in r: try: y, q = cache.get(self.ymovies_info, 9000, i[1]) if not y == year:
return urlparse.urlparse(i[0]).path except: pass except: return def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, year): try: url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year} url = urllib.urlencode(url) return url except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: data = urlparse.parse_qs(url) data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data]) t = cleantitle.get(data['tvshowtitle']) title = data['tvshowtitle'] season = '%01d' % int(season) ; episode = '%01d' % int(episode) year = re.findall('(\d{4})', premiered)[0] years = [str(year), str(int(year)+1), str(int(year)-1)] r = cache.get(self.ymovies_info_season, 720, title, season) r = [(i[0], re.findall('(.+?)\s+(?:-|)\s+season\s+(\d+)$', i[1].lower())) for i in r] r = [(i[0], i[1][0][0], i[1][0][1]) for i in r if i[1]] r = [i[0] for i in r if t == cleantitle.get(i[1]) and season == '%01d' % int(i[2])][:2] r = [(i, re.findall('(\d+)', i)[-1]) for i in r] for i in r: try: y, q = cache.get(self.ymovies_info, 9000, i[1]) if not y == year: raise Exception() return urlparse.urlparse(i[0]).path + '?episode=%01d' % int(episode) except: pass except: return def ymovies_info_season(self, title, season): try: q = '%s Season %s' % (cleantitle.query(title), season) q = '/search/%s.html' % (urllib.quote_plus(q)) q = urlparse.urljoin(self.base_link, q) for i in range(3): r = client.request(q) if not r == None: break r = client.parseDOM(r, 'div', attrs = {'class': 'ml-item'}) r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title')) for i in r] r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] return r except: return def ymovies_info(self, url): try: u = urlparse.urljoin(self.base_link, self.info_link) for i in range(3): r = client.request(u % url) if not r == None: break q = client.parseDOM(r, 'div', attrs = {'class': 'jtip-quality'})[0] y = client.parseDOM(r, 'div', attrs = {'class': 'jt-info'}) y = [i.strip() for i in y if i.strip().isdigit() and len(i.strip()) == 4][0] return (y, q) except: return def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources try: url, episode = re.findall('(.+?)\?episode=(\d*)$', url)[0] except: episode = None url = urlparse.urljoin(self.base_link, url) vid_id = re.findall('-(\d+)', url)[-1] ''' quality = cache.get(self.ymovies_info, 9000, vid_id)[1].lower() if quality == 'cam' or quality == 'ts': quality = 'CAM' elif quality == 'hd': quality = 'HD' else: quality = 'SD' ''' for i in range(3): r = client.request(url) if not r == None: break ref = client.parseDOM(r, 'a', ret='href', attrs = {'class': 'mod-btn mod-btn-watch'})[0] ref = urlparse.urljoin(self.base_link, ref) for i in range(3): r = client.request(ref, referer=url) if not r == None: break c = client.parseDOM(r, 'img', ret='src', attrs = {'class': 'hidden'}) if c: cookie = client.request(c[0], referer=ref, output='cookie') else: cookie = '' server = re.findall('server\s*:\s*"(.+?)"', r)[0] type = re.findall('type\s*:\s*"(.+?)"', r)[0] episode_id = re.findall('episode_id\s*:\s*"(.+?)"', r)[0] r = self.episode_link % (vid_id, server, episode_id, type) u = urlparse.urljoin(self.base_link, r) for i in range(13): r = client.request(u, referer=ref) if not r == None: break r = re.compile('(<li.+?/li>)', re.DOTALL).findall(r) r = [(client.parseDOM(i, 'li', ret='onclick'), client.parseDOM(i, 'a', ret='title')) for i in r] if not episode == None: r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] r = [(i[0], ''.join(re.findall('(\d+)', i[1])[:1])) for i in r] r = [i[0] for i in r if '%01d' % int(i[1]) == episode] else: r = [i[0][0] for i in r if i[0]] r = [re.findall('(\d+)', i) for i in r] r = [i[:2] for i in r if len(i) > 1] r = [i[0] for i in r if 1 <= int(i[1]) <= 11][:3] for u in r: try: key = 'xwh38if39ucx' ; key2 = '8qhfm9oyq1ux' ; key3 = 'ctiw4zlrn09tau7kqvc153uo' k = u + key3 v = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6)) c = key + u + key2 + '=%s' % v c = '%s; %s' % (cookie, c) url = urllib.quote(uncensored(k, v)) url = '/ajax/v2_get_sources/%s?hash=%s' % (u, url) url = urlparse.urljoin(self.base_link, url) for i in range(3): u = client.request(url, referer=ref, cookie=c, timeout='10') if not u == None: break u = json.loads(u)['playlist'][0]['sources'] u = [i['file'] for i in u if 'file' in i] for i in u: try: sources.append({'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'en', 'url': i, 'direct': True, 'debridonly': False}) except: pass except: pass return sources except: return sources def resolve(self, url): return directstream.googlepass(url) def uncensored(a,b): x = '' ; i = 0 for i, y in enumerate(a): z = b[i % len(b) - 1] y = int(ord(str(y)[0])) + int(ord(str(z)[0])) x += chr(y) x = base64.b64encode(x) return x
raise Exception()
conditional_block
ymovies.py
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,hashlib,random,string,json,base64 from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import cache from resources.lib.modules import directstream class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['yesmovies.to'] self.base_link = 'https://yesmovies.to' self.info_link = '/ajax/movie_info/%s.html' self.episode_link = '/ajax/v3_movie_get_episodes/%s/%s/%s/%s.html' self.playlist_link = '/ajax/v2_get_sources/%s.html?hash=%s' def movie(self, imdb, title, localtitle, year): try: t = cleantitle.get(title) q = '/search/%s.html' % (urllib.quote_plus(cleantitle.query(title))) q = urlparse.urljoin(self.base_link, q) for i in range(3): r = client.request(q) if not r == None: break r = client.parseDOM(r, 'div', attrs = {'class': 'ml-item'}) r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title')) for i in r] r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] r = [i[0] for i in r if t == cleantitle.get(i[1])][:2] r = [(i, re.findall('(\d+)', i)[-1]) for i in r] for i in r: try: y, q = cache.get(self.ymovies_info, 9000, i[1]) if not y == year: raise Exception() return urlparse.urlparse(i[0]).path except: pass except: return def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, year): try: url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year} url = urllib.urlencode(url) return url except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: data = urlparse.parse_qs(url) data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data]) t = cleantitle.get(data['tvshowtitle']) title = data['tvshowtitle'] season = '%01d' % int(season) ; episode = '%01d' % int(episode) year = re.findall('(\d{4})', premiered)[0] years = [str(year), str(int(year)+1), str(int(year)-1)] r = cache.get(self.ymovies_info_season, 720, title, season) r = [(i[0], re.findall('(.+?)\s+(?:-|)\s+season\s+(\d+)$', i[1].lower())) for i in r] r = [(i[0], i[1][0][0], i[1][0][1]) for i in r if i[1]] r = [i[0] for i in r if t == cleantitle.get(i[1]) and season == '%01d' % int(i[2])][:2] r = [(i, re.findall('(\d+)', i)[-1]) for i in r] for i in r: try: y, q = cache.get(self.ymovies_info, 9000, i[1]) if not y == year: raise Exception() return urlparse.urlparse(i[0]).path + '?episode=%01d' % int(episode) except: pass except: return def ymovies_info_season(self, title, season): try: q = '%s Season %s' % (cleantitle.query(title), season) q = '/search/%s.html' % (urllib.quote_plus(q)) q = urlparse.urljoin(self.base_link, q) for i in range(3): r = client.request(q) if not r == None: break r = client.parseDOM(r, 'div', attrs = {'class': 'ml-item'}) r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title')) for i in r] r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] return r except: return def ymovies_info(self, url): try: u = urlparse.urljoin(self.base_link, self.info_link) for i in range(3): r = client.request(u % url) if not r == None: break q = client.parseDOM(r, 'div', attrs = {'class': 'jtip-quality'})[0] y = client.parseDOM(r, 'div', attrs = {'class': 'jt-info'}) y = [i.strip() for i in y if i.strip().isdigit() and len(i.strip()) == 4][0] return (y, q) except: return def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources try: url, episode = re.findall('(.+?)\?episode=(\d*)$', url)[0] except: episode = None url = urlparse.urljoin(self.base_link, url) vid_id = re.findall('-(\d+)', url)[-1] ''' quality = cache.get(self.ymovies_info, 9000, vid_id)[1].lower() if quality == 'cam' or quality == 'ts': quality = 'CAM' elif quality == 'hd': quality = 'HD' else: quality = 'SD' ''' for i in range(3): r = client.request(url) if not r == None: break ref = client.parseDOM(r, 'a', ret='href', attrs = {'class': 'mod-btn mod-btn-watch'})[0] ref = urlparse.urljoin(self.base_link, ref) for i in range(3): r = client.request(ref, referer=url) if not r == None: break c = client.parseDOM(r, 'img', ret='src', attrs = {'class': 'hidden'}) if c: cookie = client.request(c[0], referer=ref, output='cookie') else: cookie = '' server = re.findall('server\s*:\s*"(.+?)"', r)[0] type = re.findall('type\s*:\s*"(.+?)"', r)[0] episode_id = re.findall('episode_id\s*:\s*"(.+?)"', r)[0] r = self.episode_link % (vid_id, server, episode_id, type)
for i in range(13): r = client.request(u, referer=ref) if not r == None: break r = re.compile('(<li.+?/li>)', re.DOTALL).findall(r) r = [(client.parseDOM(i, 'li', ret='onclick'), client.parseDOM(i, 'a', ret='title')) for i in r] if not episode == None: r = [(i[0][0], i[1][0]) for i in r if i[0] and i[1]] r = [(i[0], ''.join(re.findall('(\d+)', i[1])[:1])) for i in r] r = [i[0] for i in r if '%01d' % int(i[1]) == episode] else: r = [i[0][0] for i in r if i[0]] r = [re.findall('(\d+)', i) for i in r] r = [i[:2] for i in r if len(i) > 1] r = [i[0] for i in r if 1 <= int(i[1]) <= 11][:3] for u in r: try: key = 'xwh38if39ucx' ; key2 = '8qhfm9oyq1ux' ; key3 = 'ctiw4zlrn09tau7kqvc153uo' k = u + key3 v = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6)) c = key + u + key2 + '=%s' % v c = '%s; %s' % (cookie, c) url = urllib.quote(uncensored(k, v)) url = '/ajax/v2_get_sources/%s?hash=%s' % (u, url) url = urlparse.urljoin(self.base_link, url) for i in range(3): u = client.request(url, referer=ref, cookie=c, timeout='10') if not u == None: break u = json.loads(u)['playlist'][0]['sources'] u = [i['file'] for i in u if 'file' in i] for i in u: try: sources.append({'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'en', 'url': i, 'direct': True, 'debridonly': False}) except: pass except: pass return sources except: return sources def resolve(self, url): return directstream.googlepass(url) def uncensored(a,b): x = '' ; i = 0 for i, y in enumerate(a): z = b[i % len(b) - 1] y = int(ord(str(y)[0])) + int(ord(str(z)[0])) x += chr(y) x = base64.b64encode(x) return x
u = urlparse.urljoin(self.base_link, r)
random_line_split
htmlmodelement.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::HTMLModElementBinding; use dom::bindings::codegen::InheritTypes::HTMLModElementDerived;
use dom::document::Document; use dom::element::HTMLModElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[dom_struct] pub struct HTMLModElement { htmlelement: HTMLElement } impl HTMLModElementDerived for EventTarget { fn is_htmlmodelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLModElementTypeId)) } } impl HTMLModElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLModElement { HTMLModElement { htmlelement: HTMLElement::new_inherited(HTMLModElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLModElement> { let element = HTMLModElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLModElementBinding::Wrap) } } impl Reflectable for HTMLModElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector};
random_line_split
htmlmodelement.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::HTMLModElementBinding; use dom::bindings::codegen::InheritTypes::HTMLModElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLModElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[dom_struct] pub struct HTMLModElement { htmlelement: HTMLElement } impl HTMLModElementDerived for EventTarget { fn is_htmlmodelement(&self) -> bool
} impl HTMLModElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLModElement { HTMLModElement { htmlelement: HTMLElement::new_inherited(HTMLModElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLModElement> { let element = HTMLModElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLModElementBinding::Wrap) } } impl Reflectable for HTMLModElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
{ *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLModElementTypeId)) }
identifier_body
htmlmodelement.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::HTMLModElementBinding; use dom::bindings::codegen::InheritTypes::HTMLModElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLModElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[dom_struct] pub struct HTMLModElement { htmlelement: HTMLElement } impl HTMLModElementDerived for EventTarget { fn is_htmlmodelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLModElementTypeId)) } } impl HTMLModElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLModElement { HTMLModElement { htmlelement: HTMLElement::new_inherited(HTMLModElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn
(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLModElement> { let element = HTMLModElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLModElementBinding::Wrap) } } impl Reflectable for HTMLModElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
new
identifier_name
react-dom-unstable-fizz.node.production.min.js
/** @license React v16.8.2 * react-dom-unstable-fizz.node.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';function
(a,b){var c="<"+a+">";"string"===typeof b.children&&(c+=b.children);return Buffer.from(c+("</"+a+">"),"utf8")}var e="function"===typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function f(a){var b=a.destination,c=a.completedChunks;a.completedChunks=[];b.cork();try{for(a=0;a<c.length;a++)b.write(c[a])}finally{b.uncork()}b.end()} function g(a){a.flowing=!0;setImmediate(function(){var b=a.children;a.children=null;if(!b||b.$$typeof===e){var c=b.type;b=b.props;"string"===typeof c&&(a.completedChunks.push(d(c,b)),a.flowing&&f(a),c=a.destination,"function"===typeof c.flush&&c.flush())}})}function h(a,b){return function(){b.flowing=!1;f(b)}}var k={pipeToNodeWritable:function(a,b){a={destination:b,children:a,completedChunks:[],flowing:!1};b.on("drain",h(b,a));g(a)}},l={default:k},m=l&&k||l;module.exports=m.default||m;
d
identifier_name
react-dom-unstable-fizz.node.production.min.js
* * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';function d(a,b){var c="<"+a+">";"string"===typeof b.children&&(c+=b.children);return Buffer.from(c+("</"+a+">"),"utf8")}var e="function"===typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function f(a){var b=a.destination,c=a.completedChunks;a.completedChunks=[];b.cork();try{for(a=0;a<c.length;a++)b.write(c[a])}finally{b.uncork()}b.end()} function g(a){a.flowing=!0;setImmediate(function(){var b=a.children;a.children=null;if(!b||b.$$typeof===e){var c=b.type;b=b.props;"string"===typeof c&&(a.completedChunks.push(d(c,b)),a.flowing&&f(a),c=a.destination,"function"===typeof c.flush&&c.flush())}})}function h(a,b){return function(){b.flowing=!1;f(b)}}var k={pipeToNodeWritable:function(a,b){a={destination:b,children:a,completedChunks:[],flowing:!1};b.on("drain",h(b,a));g(a)}},l={default:k},m=l&&k||l;module.exports=m.default||m;
/** @license React v16.8.2 * react-dom-unstable-fizz.node.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates.
random_line_split
react-dom-unstable-fizz.node.production.min.js
/** @license React v16.8.2 * react-dom-unstable-fizz.node.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';function d(a,b){var c="<"+a+">";"string"===typeof b.children&&(c+=b.children);return Buffer.from(c+("</"+a+">"),"utf8")}var e="function"===typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function f(a){var b=a.destination,c=a.completedChunks;a.completedChunks=[];b.cork();try{for(a=0;a<c.length;a++)b.write(c[a])}finally{b.uncork()}b.end()} function g(a)
function h(a,b){return function(){b.flowing=!1;f(b)}}var k={pipeToNodeWritable:function(a,b){a={destination:b,children:a,completedChunks:[],flowing:!1};b.on("drain",h(b,a));g(a)}},l={default:k},m=l&&k||l;module.exports=m.default||m;
{a.flowing=!0;setImmediate(function(){var b=a.children;a.children=null;if(!b||b.$$typeof===e){var c=b.type;b=b.props;"string"===typeof c&&(a.completedChunks.push(d(c,b)),a.flowing&&f(a),c=a.destination,"function"===typeof c.flush&&c.flush())}})}
identifier_body
react-dom-unstable-fizz.node.production.min.js
/** @license React v16.8.2 * react-dom-unstable-fizz.node.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';function d(a,b){var c="<"+a+">";"string"===typeof b.children&&(c+=b.children);return Buffer.from(c+("</"+a+">"),"utf8")}var e="function"===typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function f(a){var b=a.destination,c=a.completedChunks;a.completedChunks=[];b.cork();try{for(a=0;a<c.length;a++)b.write(c[a])}finally{b.uncork()}b.end()} function g(a){a.flowing=!0;setImmediate(function(){var b=a.children;a.children=null;if(!b||b.$$typeof===e)
})}function h(a,b){return function(){b.flowing=!1;f(b)}}var k={pipeToNodeWritable:function(a,b){a={destination:b,children:a,completedChunks:[],flowing:!1};b.on("drain",h(b,a));g(a)}},l={default:k},m=l&&k||l;module.exports=m.default||m;
{var c=b.type;b=b.props;"string"===typeof c&&(a.completedChunks.push(d(c,b)),a.flowing&&f(a),c=a.destination,"function"===typeof c.flush&&c.flush())}
conditional_block
ui.rs
// Copyright 2016 Matthew Collins // // 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. use std::sync::{Arc, RwLock}; use std::collections::HashMap; use resources; use gl; use render; use render::glsl; use render::shaders; use byteorder::{WriteBytesExt, NativeEndian}; use image; use image::GenericImage; const UI_WIDTH: f64 = 854.0; const UI_HEIGHT: f64 = 480.0; pub struct UIState { textures: Arc<RwLock<render::TextureManager>>, resources: Arc<RwLock<resources::Manager>>, pub version: usize, data: Vec<u8>, prev_size: usize, count: usize, array: gl::VertexArray, buffer: gl::Buffer, index_buffer: gl::Buffer, index_type: gl::Type, max_index: usize, shader: UIShader, // Font font_pages: Vec<Option<render::Texture>>, font_character_info: Vec<(i32, i32)>, char_map: HashMap<char, char>, page_width: f64, page_height: f64, } init_shader! { Program UIShader { vert = "ui_vertex", frag = "ui_frag", attribute = { required position => "aPosition", required texture_info => "aTextureInfo", required texture_offset => "aTextureOffset", required color => "aColor", }, uniform = { required texture => "textures", required screensize => "screenSize", }, } } impl UIState { pub fn new(glsl: &glsl::Registry, textures: Arc<RwLock<render::TextureManager>>, res: Arc<RwLock<resources::Manager>>) -> UIState { let shader = UIShader::new(glsl); let array = gl::VertexArray::new(); array.bind(); let buffer = gl::Buffer::new(); buffer.bind(gl::ARRAY_BUFFER); shader.position.enable(); shader.texture_info.enable(); shader.texture_offset.enable(); shader.color.enable(); shader.position.vertex_pointer_int(3, gl::SHORT, 28, 0); shader.texture_info.vertex_pointer(4, gl::UNSIGNED_SHORT, false, 28, 8); shader.texture_offset.vertex_pointer_int(3, gl::SHORT, 28, 16); shader.color.vertex_pointer(4, gl::UNSIGNED_BYTE, true, 28, 24); let index_buffer = gl::Buffer::new(); index_buffer.bind(gl::ELEMENT_ARRAY_BUFFER); let mut pages = Vec::with_capacity(0x100); for _ in 0..0x100 { pages.push(Option::None); } let mut char_map = HashMap::new(); let ascii_chars = "ÀÁÂÈÊËÍÓÔÕÚßãõğİıŒœŞşŴŵžȇ \ !\"#$%&'()*+,-./0123456789:;\ <=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ \ ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞\ ╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αβΓπΣσμτΦΘΩδ∞∅∈∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■"; for (pos, c) in ascii_chars.chars().enumerate() { char_map.insert(c, ::std::char::from_u32(pos as u32).unwrap()); } let mut state = UIState { textures: textures, resources: res, version: 0xFFFF, data: Vec::new(), count: 0, prev_size: 0, index_type: gl::UNSIGNED_BYTE, array: array, buffer: buffer, index_buffer: index_buffer, max_index: 0, shader: shader, // Font font_pages: pages, font_character_info: vec![(0, 0); 0x10000], char_map: char_map, page_width: 0.0, page_height: 0.0, }; state.load_font(); state } pub fn tick(&mut self, width: u32, height: u32) { { let version = self.resources.read().unwrap().version(); if self.version != version { self.version = version; self.load_font(); } } // Prevent clipping with the world gl::clear(gl::ClearFlags::Depth); gl::enable(gl::BLEND); gl::blend_func(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); self.shader.program.use_program(); self.shader.texture.set_int(0); if self.count > 0 { self.array.bind(); if self.max_index < self.count { let (data, ty) = render::generate_element_buffer(self.count); self.index_type = ty; self.index_buffer.bind(gl::ELEMENT_ARRAY_BUFFER); self.index_buffer.set_data(gl::ELEMENT_ARRAY_BUFFER, &data, gl::DYNAMIC_DRAW); self.max_index = self.count; } self.shader.screensize.set_float2(width as f32, height as f32); self.buffer.bind(gl::ARRAY_BUFFER); self.index_buffer.bind(gl::ELEMENT_ARRAY_BUFFER); if self.data.len() > self.prev_size { self.prev_size = self.data.len(); self.buffer.set_data(gl::ARRAY_BUFFER, &self.data, gl::STREAM_DRAW); } else { self.buffer.re_set_data(gl::ARRAY_BUFFER, &self.data); } gl::draw_elements(gl::TRIANGLES, self.count as i32, self.index_type, 0); } gl::disable(gl::BLEND); self.data.clear(); self.count = 0; } pub fn add_bytes(&mut self, data: &[u8]) { self.data.extend_from_slice(data); self.count += (data.len() / (28 * 4)) * 6; } pub fn character_texture(&mut self, c: char) -> render::Texture { let raw = c as u32; let page = raw >> 8; // Lazy load fonts to size memory if self.font_pages[page as usize].is_none() { let name = if page == 0 { "font/ascii".to_owned() } else { format!("font/unicode_page_{:02X}", page) }; let textures = self.textures.clone(); self.font_pages[page as usize] = Some(render::Renderer::get_texture(&textures, &name)); } let p = self.font_pages[page as usize].clone().unwrap(); let raw = if page == 0 { (*self.char_map.get(&c).unwrap_or(&c)) as u32 } else { raw }; let ch = raw & 0xFF; let cx = ch & 0xF; let cy = ch >> 4; let info = self.font_character_info[raw as usize]; if page == 0 { let sw = (self.page_width / 16.0) as u32; let sh = (self.page_height / 16.0) as u32; return p.relative((cx * sw + info.0 as u32) as f32 / (self.page_width as f32), (cy * sh) as f32 / (self.page_height as f32), (info.1 - info.0) as f32 / (self.page_width as f32), (sh as f32) / (self.page_height as f32)) } p.relative((cx * 16 + info.0 as u32) as f32 / 256.0, (cy * 16) as f32 / 256.0, (info.1 - info.0) as f32 / 256.0, 16.0 / 256.0) } pub fn size_of_string(&self, val: &str) -> f64 { let mut size = 0.0; for c in val.chars() { size += self.size_of_char(c) + 2.0; } size - 2.0 } pub fn size_of_char(&self, c: char) -> f64 { if c == ' ' { return 4.0; } let r = c as u32; if r >> 8 == 0 { let r = (*self.char_map.get(&c).unwrap_or(&c)) as u32; let info = self.font_character_info[r as usize]; let sw = self.page_width / 16.0; return (((info.1 - info.0) as f64) / sw) * 16.0; } let info = self.font_character_info[c as usize]; (info.1 - info.0) as f64 } fn load_font(&mut self) { for page in &mut self.font_pages { *page = None; } let res = self.resources.read().unwrap(); if let Some(mut info) = res.open("minecraft", "font/glyph_sizes.bin") { let mut data = Vec::with_capacity(0x10000); info.read_to_end(&mut data).unwrap(); for (i, info) in self.font_character_info.iter_mut().enumerate() { // Top nibble - start position // Bottom nibble - end position info.0 = (data[i] >> 4) as i32; info.1 = (data[i] & 0xF) as i32 + 1; } } if let Some(mut val) = res.open("minecraft", "textures/font/ascii.png") { let mut data = Vec::new(); val.read_to_end(&mut data).unwrap(); if let Ok(img) = image::load_from_memory(&data) { let (width, height) = img.dimensions(); self.page_width = width as f64; self.page_height = height as f64; let sw = width / 16; let sh = height / 16; for i in 0..256 { let cx = (i & 0xF) * sw; let cy = (i >> 4) * sh; let mut start = true; 'x_loop: for x in 0..sw { for y in 0..sh { let a = img.get_pixel(cx + x, cy + y).data[3]; if start && a != 0 { self.font_character_info[i as usize].0 = x as i32; start = false; continue 'x_loop; } else if !start && a != 0 { continue 'x_loop; } } if !start { self.font_character_info[i as usize].1 = x as i32; break; } } } } } } pub fn new_text(&mut self, val: &str, x: f64, y: f64, r: u8, g: u8, b: u8) -> UIText { self.new_text_scaled(val, x, y, 1.0, 1.0, r, g, b) } pub fn new_text_scaled(&mut self, val: &str, x: f64, y: f64, sx: f64, sy: f64,
r: u8, g: u8, b: u8) -> UIText { self.create_text(val, x, y, sx, sy, 0.0, r, g, b) } pub fn new_text_rotated(&mut self, val: &str, x: f64, y: f64, sx: f64, sy: f64, rotation: f64, r: u8, g: u8, b: u8) -> UIText { self.create_text(val, x, y, sx, sy, rotation, r, g, b) } fn create_text(&mut self, val: &str, x: f64, y: f64, sx: f64, sy: f64, rotation: f64, r: u8, g: u8, b: u8) -> UIText { let mut elements = Vec::new(); let mut offset = 0.0; for ch in val.chars() { if ch == ' ' { offset += 6.0; continue; } let texture = self.character_texture(ch); let w = self.size_of_char(ch); let mut dsx = offset + 2.0; let mut dsy = 2.0; let mut dx = offset; let mut dy = 0.0; if rotation != 0.0 { let c = rotation.cos(); let s = rotation.sin(); let tmpx = dsx - (w * 0.5); let tmpy = dsy - (16.0 * 0.5); dsx = (w * 0.5) + (tmpx * c - tmpy * s); dsy = (16.0 * 0.5) + (tmpy * c + tmpx * s); let tmpx = dx - (w * 0.5); let tmpy = dy - (16.0 * 0.5); dx = (w * 0.5) + (tmpx * c - tmpy * s); dy = (16.0 * 0.5) + (tmpy * c + tmpx * s); } let mut shadow = UIElement::new(&texture, x + dsx * sx, y + dsy * sy, w * sx, 16.0 * sy, 0.0, 0.0, 1.0, 1.0); shadow.r = ((r as f64) * 0.25) as u8; shadow.g = ((g as f64) * 0.25) as u8; shadow.b = ((b as f64) * 0.25) as u8; shadow.rotation = rotation; elements.push(shadow); let mut text = UIElement::new(&texture, x + dx * sx, y + dy * sy, w * sx, 16.0 * sy, 0.0, 0.0, 1.0, 1.0); text.r = r; text.g = g; text.b = b; text.rotation = rotation; elements.push(text); offset += w + 2.0; } UIText { elements: elements, width: (offset - 2.0) * sx, } } } pub struct UIText { pub elements: Vec<UIElement>, pub width: f64, } impl UIText { pub fn bytes(&self, width: f64, height: f64) -> Vec<u8> { let mut buf = Vec::with_capacity(28 * 4 * self.elements.len()); for e in &self.elements { buf.extend(e.bytes(width, height)); } buf } } pub struct UIElement { pub x: f64, pub y: f64, pub w: f64, pub h: f64, pub layer: isize, pub t_x: u16, pub t_y: u16, pub t_w: u16, pub t_h: u16, pub t_offsetx: i16, pub t_offsety: i16, pub t_atlas: i16, pub t_sizew: i16, pub t_sizeh: i16, pub r: u8, pub g: u8, pub b: u8, pub a: u8, pub rotation: f64, } impl UIElement { pub fn new(tex: &render::Texture, x: f64, y: f64, width: f64, height: f64, tx: f64, ty: f64, tw: f64, th: f64) -> UIElement { let twidth = tex.get_width(); let theight = tex.get_height(); UIElement { x: x / UI_WIDTH, y: y / UI_HEIGHT, w: width / UI_WIDTH, h: height / UI_HEIGHT, layer: 0, t_x: tex.get_x() as u16, t_y: tex.get_y() as u16, t_w: twidth as u16, t_h: theight as u16, t_atlas: tex.atlas as i16, t_offsetx: (tx * (twidth as f64) * 16.0) as i16, t_offsety: (ty * (theight as f64) * 16.0) as i16, t_sizew: (tw * (twidth as f64) * 16.0) as i16, t_sizeh: (th * (theight as f64) * 16.0) as i16, r: 255, g: 255, b: 255, a: 255, rotation: 0.0, } } pub fn bytes(&self, width: f64, height: f64) -> Vec<u8> { let mut buf = Vec::with_capacity(28 * 4); self.append_vertex(&mut buf, self.x, self.y, self.t_offsetx, self.t_offsety, width, height); self.append_vertex(&mut buf, self.x + self.w, self.y, self.t_offsetx + self.t_sizew, self.t_offsety, width, height); self.append_vertex(&mut buf, self.x, self.y + self.h, self.t_offsetx, self.t_offsety + self.t_sizeh, width, height); self.append_vertex(&mut buf, self.x + self.w, self.y + self.h, self.t_offsetx + self.t_sizew, self.t_offsety + self.t_sizeh, width, height); buf } #[allow(unused_must_use)] pub fn append_vertex(&self, buf: &mut Vec<u8>, x: f64, y: f64, tx: i16, ty: i16, width: f64, height: f64) { let mut dx = x as f64; let mut dy = y as f64; if self.rotation != 0.0 { let c = self.rotation.cos(); let s = self.rotation.sin(); let tmpx = dx - self.x - (self.w / 2.0); let tmpy = dy - self.y - (self.h / 2.0); dx = (self.w / 2.0) + (tmpx * c - tmpy * s) + self.x; dy = (self.h / 2.0) + (tmpy * c + tmpx * s) + self.y; } buf.write_i16::<NativeEndian>((dx * width + 0.5).floor() as i16); buf.write_i16::<NativeEndian>((dy * height + 0.5).floor() as i16); buf.write_i16::<NativeEndian>((self.layer * 256) as i16); buf.write_i16::<NativeEndian>(0); buf.write_u16::<NativeEndian>(self.t_x); buf.write_u16::<NativeEndian>(self.t_y); buf.write_u16::<NativeEndian>(self.t_w); buf.write_u16::<NativeEndian>(self.t_h); buf.write_i16::<NativeEndian>(tx); buf.write_i16::<NativeEndian>(ty); buf.write_i16::<NativeEndian>(self.t_atlas); buf.write_i16::<NativeEndian>(0); buf.write_u8(self.r); buf.write_u8(self.g); buf.write_u8(self.b); buf.write_u8(self.a); } }
identifier_name
ui.rs
// Copyright 2016 Matthew Collins // // 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. use std::sync::{Arc, RwLock}; use std::collections::HashMap; use resources; use gl; use render; use render::glsl; use render::shaders; use byteorder::{WriteBytesExt, NativeEndian}; use image; use image::GenericImage; const UI_WIDTH: f64 = 854.0; const UI_HEIGHT: f64 = 480.0; pub struct UIState { textures: Arc<RwLock<render::TextureManager>>, resources: Arc<RwLock<resources::Manager>>, pub version: usize, data: Vec<u8>, prev_size: usize, count: usize, array: gl::VertexArray, buffer: gl::Buffer, index_buffer: gl::Buffer, index_type: gl::Type, max_index: usize, shader: UIShader, // Font font_pages: Vec<Option<render::Texture>>, font_character_info: Vec<(i32, i32)>, char_map: HashMap<char, char>, page_width: f64, page_height: f64, } init_shader! { Program UIShader { vert = "ui_vertex", frag = "ui_frag", attribute = { required position => "aPosition", required texture_info => "aTextureInfo", required texture_offset => "aTextureOffset", required color => "aColor", }, uniform = { required texture => "textures", required screensize => "screenSize", }, } } impl UIState { pub fn new(glsl: &glsl::Registry, textures: Arc<RwLock<render::TextureManager>>, res: Arc<RwLock<resources::Manager>>) -> UIState { let shader = UIShader::new(glsl); let array = gl::VertexArray::new(); array.bind(); let buffer = gl::Buffer::new(); buffer.bind(gl::ARRAY_BUFFER); shader.position.enable(); shader.texture_info.enable(); shader.texture_offset.enable(); shader.color.enable(); shader.position.vertex_pointer_int(3, gl::SHORT, 28, 0); shader.texture_info.vertex_pointer(4, gl::UNSIGNED_SHORT, false, 28, 8); shader.texture_offset.vertex_pointer_int(3, gl::SHORT, 28, 16); shader.color.vertex_pointer(4, gl::UNSIGNED_BYTE, true, 28, 24); let index_buffer = gl::Buffer::new(); index_buffer.bind(gl::ELEMENT_ARRAY_BUFFER); let mut pages = Vec::with_capacity(0x100); for _ in 0..0x100 { pages.push(Option::None); } let mut char_map = HashMap::new(); let ascii_chars = "ÀÁÂÈÊËÍÓÔÕÚßãõğİıŒœŞşŴŵžȇ \ !\"#$%&'()*+,-./0123456789:;\ <=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ \ ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞\ ╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αβΓπΣσμτΦΘΩδ∞∅∈∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■"; for (pos, c) in ascii_chars.chars().enumerate() { char_map.insert(c, ::std::char::from_u32(pos as u32).unwrap()); } let mut state = UIState { textures: textures, resources: res, version: 0xFFFF, data: Vec::new(), count: 0, prev_size: 0, index_type: gl::UNSIGNED_BYTE, array: array, buffer: buffer, index_buffer: index_buffer, max_index: 0, shader: shader, // Font font_pages: pages, font_character_info: vec![(0, 0); 0x10000], char_map: char_map, page_width: 0.0, page_height: 0.0, }; state.load_font(); state } pub fn tick(&mut self, width: u32, height: u32) { { let version = self.resources.read().unwrap().version(); if self.version != version { self.version = version; self.load_font(); } } // Prevent clipping with the world gl::clear(gl::ClearFlags::Depth); gl::enable(gl::BLEND); gl::blend_func(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); self.shader.program.use_program(); self.shader.texture.set_int(0); if self.count > 0 { self.array.bind(); if self.max_index < self.count { let (data, ty) = render::generate_element_buffer(self.count); self.index_type = ty; self.index_buffer.bind(gl::ELEMENT_ARRAY_BUFFER); self.index_buffer.set_data(gl::ELEMENT_ARRAY_BUFFER, &data, gl::DYNAMIC_DRAW); self.max_index = self.count; } self.shader.screensize.set_float2(width as f32, height as f32); self.buffer.bind(gl::ARRAY_BUFFER); self.index_buffer.bind(gl::ELEMENT_ARRAY_BUFFER); if self.data.len() > self.prev_size { self.prev_size = self.data.len(); self.buffer.set_data(gl::ARRAY_BUFFER, &self.data, gl::STREAM_DRAW); } else { self.buffer.re_set_data(gl::ARRAY_BUFFER, &self.data); } gl::draw_elements(gl::TRIANGLES, self.count as i32, self.index_type, 0); } gl::disable(gl::BLEND); self.data.clear(); self.count = 0; } pub fn add_bytes(&mut self, data: &[u8]) { self.data.extend_from_slice(data); self.count += (data.len() / (28 * 4)) * 6; } pub fn character_texture(&mut self, c: char) -> render::Texture { let raw = c as u32; let page = raw >> 8; // Lazy load fonts to size memory if self.font_pages[page as usize].is_none() { let name = if page == 0 { "font/ascii".to_owned() } else { format!("font/unicode_page_{:02X}", page) }; let textures = self.textures.clone(); self.font_pages[page as usize] = Some(render::Renderer::get_texture(&textures, &name)); } let p = self.font_pages[page as usize].clone().unwrap(); let raw = if page == 0 { (*self.char_map.get(&c).unwrap_or(&c)) as u32 } else { raw }; let ch = raw & 0xFF; let cx = ch & 0xF; let cy = ch >> 4; let info = self.font_character_info[raw as usize]; if page == 0 { let sw = (self.page_width / 16.0) as u32; let sh = (self.page_height / 16.0) as u32; return p.relative((cx * sw + info.0 as u32) as f32 / (self.page_width as f32), (cy * sh) as f32 / (self.page_height as f32), (info.1 - info.0) as f32 / (self.page_width as f32), (sh as f32) / (self.page_height as f32)) } p.relative((cx * 16 + info.0 as u32) as f32 / 256.0, (cy * 16) as f32 / 256.0, (info.1 - info.0) as f32 / 256.0, 16.0 / 256.0) } pub fn size_of_string(&self, val: &str) -> f64 { let mut size = 0.0; for c in val.chars() { size += self.size_of_char(c) + 2.0; } size - 2.0 } pub fn size_of_char(&self, c: char) -> f64 { if c == ' ' { return 4.0; } let r = c as u32; if r >> 8 == 0 { let r = (*self.char_map.get(&c).unwrap_or(&c)) as u32; let info = self.font_character_info[r as usize]; let sw = self.page_width / 16.0; return (((info.1 - info.0) as f64) / sw) * 16.0; } let info = self.font_character_info[c as usize]; (info.1 - info.0) as f64 } fn load_font(&mut self) { for page in &mut self.font_pages { *page = None; } let res = self.resources.read().unwrap(); if let Some(mut info) = res.open("minecraft", "font/glyph_sizes.bin") { let mut data = Vec::with_capacity(0x10000); info.read_to_end(&mut data).unwrap(); for (i, info) in self.font_character_info.iter_mut().enumerate() { // Top nibble - start position // Bottom nibble - end position info.0 = (data[i] >> 4) as i32; info.1 = (data[i] & 0xF) as i32 + 1; } } if let Some(mut val) = res.open("minecraft", "textures/font/ascii.png") { let mut data = Vec::new(); val.read_to_end(&mut data).unwrap(); if let Ok(img) = image::load_from_memory(&data) { let (width, height) = img.dimensions(); self.page_width = width as f64; self.page_height = height as f64; let sw = width / 16; let sh = height / 16; for i in 0..256 { let cx = (i & 0xF) * sw; let cy = (i >> 4) * sh; let mut start = true; 'x_loop: for x in 0..sw { for y in 0..sh { let a = img.get_pixel(cx + x, cy + y).data[3]; if start && a != 0 { self.font_character_info[i as usize].0 = x as i32; start = false; continue 'x_loop; } else if !start && a != 0 { continue 'x_loop; } } if !start { self.font_character_info[i as usize].1 = x as i32; break; } } } } } } pub fn new_text(&mut self, val: &str, x: f64, y: f64, r: u8, g: u8, b: u8) -> UIText { self.new_text_scaled(val, x, y, 1.0, 1.0, r, g, b) } pub fn new_text_scaled(&mut self, val: &str, x: f64, y: f64, sx: f64, sy: f64, r: u8, g: u8, b: u8) -> UIText { self.create_text(val, x, y, sx, sy, 0.0, r, g, b) } pub fn new_text_rotated(&mut self, val: &str, x: f64, y: f64, sx: f64, sy: f64, rotation: f64, r: u8,
g: u8, b: u8) -> UIText { self.create_text(val, x, y, sx, sy, rotation, r, g, b) } fn create_text(&mut self, val: &str, x: f64, y: f64, sx: f64, sy: f64, rotation: f64, r: u8, g: u8, b: u8) -> UIText { let mut elements = Vec::new(); let mut offset = 0.0; for ch in val.chars() { if ch == ' ' { offset += 6.0; continue; } let texture = self.character_texture(ch); let w = self.size_of_char(ch); let mut dsx = offset + 2.0; let mut dsy = 2.0; let mut dx = offset; let mut dy = 0.0; if rotation != 0.0 { let c = rotation.cos(); let s = rotation.sin(); let tmpx = dsx - (w * 0.5); let tmpy = dsy - (16.0 * 0.5); dsx = (w * 0.5) + (tmpx * c - tmpy * s); dsy = (16.0 * 0.5) + (tmpy * c + tmpx * s); let tmpx = dx - (w * 0.5); let tmpy = dy - (16.0 * 0.5); dx = (w * 0.5) + (tmpx * c - tmpy * s); dy = (16.0 * 0.5) + (tmpy * c + tmpx * s); } let mut shadow = UIElement::new(&texture, x + dsx * sx, y + dsy * sy, w * sx, 16.0 * sy, 0.0, 0.0, 1.0, 1.0); shadow.r = ((r as f64) * 0.25) as u8; shadow.g = ((g as f64) * 0.25) as u8; shadow.b = ((b as f64) * 0.25) as u8; shadow.rotation = rotation; elements.push(shadow); let mut text = UIElement::new(&texture, x + dx * sx, y + dy * sy, w * sx, 16.0 * sy, 0.0, 0.0, 1.0, 1.0); text.r = r; text.g = g; text.b = b; text.rotation = rotation; elements.push(text); offset += w + 2.0; } UIText { elements: elements, width: (offset - 2.0) * sx, } } } pub struct UIText { pub elements: Vec<UIElement>, pub width: f64, } impl UIText { pub fn bytes(&self, width: f64, height: f64) -> Vec<u8> { let mut buf = Vec::with_capacity(28 * 4 * self.elements.len()); for e in &self.elements { buf.extend(e.bytes(width, height)); } buf } } pub struct UIElement { pub x: f64, pub y: f64, pub w: f64, pub h: f64, pub layer: isize, pub t_x: u16, pub t_y: u16, pub t_w: u16, pub t_h: u16, pub t_offsetx: i16, pub t_offsety: i16, pub t_atlas: i16, pub t_sizew: i16, pub t_sizeh: i16, pub r: u8, pub g: u8, pub b: u8, pub a: u8, pub rotation: f64, } impl UIElement { pub fn new(tex: &render::Texture, x: f64, y: f64, width: f64, height: f64, tx: f64, ty: f64, tw: f64, th: f64) -> UIElement { let twidth = tex.get_width(); let theight = tex.get_height(); UIElement { x: x / UI_WIDTH, y: y / UI_HEIGHT, w: width / UI_WIDTH, h: height / UI_HEIGHT, layer: 0, t_x: tex.get_x() as u16, t_y: tex.get_y() as u16, t_w: twidth as u16, t_h: theight as u16, t_atlas: tex.atlas as i16, t_offsetx: (tx * (twidth as f64) * 16.0) as i16, t_offsety: (ty * (theight as f64) * 16.0) as i16, t_sizew: (tw * (twidth as f64) * 16.0) as i16, t_sizeh: (th * (theight as f64) * 16.0) as i16, r: 255, g: 255, b: 255, a: 255, rotation: 0.0, } } pub fn bytes(&self, width: f64, height: f64) -> Vec<u8> { let mut buf = Vec::with_capacity(28 * 4); self.append_vertex(&mut buf, self.x, self.y, self.t_offsetx, self.t_offsety, width, height); self.append_vertex(&mut buf, self.x + self.w, self.y, self.t_offsetx + self.t_sizew, self.t_offsety, width, height); self.append_vertex(&mut buf, self.x, self.y + self.h, self.t_offsetx, self.t_offsety + self.t_sizeh, width, height); self.append_vertex(&mut buf, self.x + self.w, self.y + self.h, self.t_offsetx + self.t_sizew, self.t_offsety + self.t_sizeh, width, height); buf } #[allow(unused_must_use)] pub fn append_vertex(&self, buf: &mut Vec<u8>, x: f64, y: f64, tx: i16, ty: i16, width: f64, height: f64) { let mut dx = x as f64; let mut dy = y as f64; if self.rotation != 0.0 { let c = self.rotation.cos(); let s = self.rotation.sin(); let tmpx = dx - self.x - (self.w / 2.0); let tmpy = dy - self.y - (self.h / 2.0); dx = (self.w / 2.0) + (tmpx * c - tmpy * s) + self.x; dy = (self.h / 2.0) + (tmpy * c + tmpx * s) + self.y; } buf.write_i16::<NativeEndian>((dx * width + 0.5).floor() as i16); buf.write_i16::<NativeEndian>((dy * height + 0.5).floor() as i16); buf.write_i16::<NativeEndian>((self.layer * 256) as i16); buf.write_i16::<NativeEndian>(0); buf.write_u16::<NativeEndian>(self.t_x); buf.write_u16::<NativeEndian>(self.t_y); buf.write_u16::<NativeEndian>(self.t_w); buf.write_u16::<NativeEndian>(self.t_h); buf.write_i16::<NativeEndian>(tx); buf.write_i16::<NativeEndian>(ty); buf.write_i16::<NativeEndian>(self.t_atlas); buf.write_i16::<NativeEndian>(0); buf.write_u8(self.r); buf.write_u8(self.g); buf.write_u8(self.b); buf.write_u8(self.a); } }
random_line_split
ui.rs
// Copyright 2016 Matthew Collins // // 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. use std::sync::{Arc, RwLock}; use std::collections::HashMap; use resources; use gl; use render; use render::glsl; use render::shaders; use byteorder::{WriteBytesExt, NativeEndian}; use image; use image::GenericImage; const UI_WIDTH: f64 = 854.0; const UI_HEIGHT: f64 = 480.0; pub struct UIState { textures: Arc<RwLock<render::TextureManager>>, resources: Arc<RwLock<resources::Manager>>, pub version: usize, data: Vec<u8>, prev_size: usize, count: usize, array: gl::VertexArray, buffer: gl::Buffer, index_buffer: gl::Buffer, index_type: gl::Type, max_index: usize, shader: UIShader, // Font font_pages: Vec<Option<render::Texture>>, font_character_info: Vec<(i32, i32)>, char_map: HashMap<char, char>, page_width: f64, page_height: f64, } init_shader! { Program UIShader { vert = "ui_vertex", frag = "ui_frag", attribute = { required position => "aPosition", required texture_info => "aTextureInfo", required texture_offset => "aTextureOffset", required color => "aColor", }, uniform = { required texture => "textures", required screensize => "screenSize", }, } } impl UIState { pub fn new(glsl: &glsl::Registry, textures: Arc<RwLock<render::TextureManager>>, res: Arc<RwLock<resources::Manager>>) -> UIState { let shader = UIShader::new(glsl); let array = gl::VertexArray::new(); array.bind(); let buffer = gl::Buffer::new(); buffer.bind(gl::ARRAY_BUFFER); shader.position.enable(); shader.texture_info.enable(); shader.texture_offset.enable(); shader.color.enable(); shader.position.vertex_pointer_int(3, gl::SHORT, 28, 0); shader.texture_info.vertex_pointer(4, gl::UNSIGNED_SHORT, false, 28, 8); shader.texture_offset.vertex_pointer_int(3, gl::SHORT, 28, 16); shader.color.vertex_pointer(4, gl::UNSIGNED_BYTE, true, 28, 24); let index_buffer = gl::Buffer::new(); index_buffer.bind(gl::ELEMENT_ARRAY_BUFFER); let mut pages = Vec::with_capacity(0x100); for _ in 0..0x100 { pages.push(Option::None); } let mut char_map = HashMap::new(); let ascii_chars = "ÀÁÂÈÊËÍÓÔÕÚßãõğİıŒœŞşŴŵžȇ \ !\"#$%&'()*+,-./0123456789:;\ <=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ \ ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞\ ╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αβΓπΣσμτΦΘΩδ∞∅∈∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■"; for (pos, c) in ascii_chars.chars().enumerate() { char_map.insert(c, ::std::char::from_u32(pos as u32).unwrap()); } let mut state = UIState { textures: textures, resources: res, version: 0xFFFF, data: Vec::new(), count: 0, prev_size: 0, index_type: gl::UNSIGNED_BYTE, array: array, buffer: buffer, index_buffer: index_buffer, max_index: 0, shader: shader, // Font font_pages: pages, font_character_info: vec![(0, 0); 0x10000], char_map: char_map, page_width: 0.0, page_height: 0.0, }; state.load_font(); state } pub fn tick(&mut self, width: u32, height: u32) { { let version = self.resources.read().unwrap().version(); if self.version != version { self.version = version; self.load_font(); } } // Prevent clipping with the world gl::clear(gl::ClearFlags::Depth); gl::enable(gl::BLEND); gl::blend_func(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); self.shader.program.use_program(); self.shader.texture.set_int(0); if self.count > 0 { self.array.bind(); if self.max_index < self.count { let (data, ty) = render::generate_element_buffer(self.count); self.index_type = ty; self.index_buffer.bind(gl::ELEMENT_ARRAY_BUFFER); self.index_buffer.set_data(gl::ELEMENT_ARRAY_BUFFER, &data, gl::DYNAMIC_DRAW); self.max_index = self.count; } self.shader.screensize.set_float2(width as f32, height as f32); self.buffer.bind(gl::ARRAY_BUFFER); self.index_buffer.bind(gl::ELEMENT_ARRAY_BUFFER); if self.data.len() > self.prev_size { self.prev_size = self.data.len(); self.buffer.set_data(gl::ARRAY_BUFFER, &self.data, gl::STREAM_DRAW); } else { self.buffer.re_set_data(gl::ARRAY_BUFFER, &self.data); } gl::draw_elements(gl::TRIANGLES, self.count as i32, self.index_type, 0); } gl::disable(gl::BLEND); self.data.clear(); self.count = 0; } pub fn add_bytes(&mut self, data: &[u8]) { self.data.extend_from_slice(data); self.count += (data.len() / (28 * 4)) * 6; } pub fn character_texture(&mut self, c: char) -> render::Texture { let raw = c as u32; let page = raw >> 8; // Lazy load fonts to size memory if self.font_pages[page as usize].is_none() { let name = if page == 0 { "font/ascii".to_owned() } else { format!("font/unicode_page_{:02X}", page) }; let textures = self.textures.clone(); self.font_pages[page as usize] = Some(render::Renderer::get_texture(&textures, &name)); } let p = self.font_pages[page as usize].clone().unwrap(); let raw = if page == 0 { (*self.char_map.get(&c).unwrap_or(&c)) as u32 } else { raw }; let ch = raw & 0xFF; let cx = ch & 0xF; let cy = ch >> 4; let info = self.font
sw = (self.page_width / 16.0) as u32; let sh = (self.page_height / 16.0) as u32; return p.relative((cx * sw + info.0 as u32) as f32 / (self.page_width as f32), (cy * sh) as f32 / (self.page_height as f32), (info.1 - info.0) as f32 / (self.page_width as f32), (sh as f32) / (self.page_height as f32)) } p.relative((cx * 16 + info.0 as u32) as f32 / 256.0, (cy * 16) as f32 / 256.0, (info.1 - info.0) as f32 / 256.0, 16.0 / 256.0) } pub fn size_of_string(&self, val: &str) -> f64 { let mut size = 0.0; for c in val.chars() { size += self.size_of_char(c) + 2.0; } size - 2.0 } pub fn size_of_char(&self, c: char) -> f64 { if c == ' ' { return 4.0; } let r = c as u32; if r >> 8 == 0 { let r = (*self.char_map.get(&c).unwrap_or(&c)) as u32; let info = self.font_character_info[r as usize]; let sw = self.page_width / 16.0; return (((info.1 - info.0) as f64) / sw) * 16.0; } let info = self.font_character_info[c as usize]; (info.1 - info.0) as f64 } fn load_font(&mut self) { for page in &mut self.font_pages { *page = None; } let res = self.resources.read().unwrap(); if let Some(mut info) = res.open("minecraft", "font/glyph_sizes.bin") { let mut data = Vec::with_capacity(0x10000); info.read_to_end(&mut data).unwrap(); for (i, info) in self.font_character_info.iter_mut().enumerate() { // Top nibble - start position // Bottom nibble - end position info.0 = (data[i] >> 4) as i32; info.1 = (data[i] & 0xF) as i32 + 1; } } if let Some(mut val) = res.open("minecraft", "textures/font/ascii.png") { let mut data = Vec::new(); val.read_to_end(&mut data).unwrap(); if let Ok(img) = image::load_from_memory(&data) { let (width, height) = img.dimensions(); self.page_width = width as f64; self.page_height = height as f64; let sw = width / 16; let sh = height / 16; for i in 0..256 { let cx = (i & 0xF) * sw; let cy = (i >> 4) * sh; let mut start = true; 'x_loop: for x in 0..sw { for y in 0..sh { let a = img.get_pixel(cx + x, cy + y).data[3]; if start && a != 0 { self.font_character_info[i as usize].0 = x as i32; start = false; continue 'x_loop; } else if !start && a != 0 { continue 'x_loop; } } if !start { self.font_character_info[i as usize].1 = x as i32; break; } } } } } } pub fn new_text(&mut self, val: &str, x: f64, y: f64, r: u8, g: u8, b: u8) -> UIText { self.new_text_scaled(val, x, y, 1.0, 1.0, r, g, b) } pub fn new_text_scaled(&mut self, val: &str, x: f64, y: f64, sx: f64, sy: f64, r: u8, g: u8, b: u8) -> UIText { self.create_text(val, x, y, sx, sy, 0.0, r, g, b) } pub fn new_text_rotated(&mut self, val: &str, x: f64, y: f64, sx: f64, sy: f64, rotation: f64, r: u8, g: u8, b: u8) -> UIText { self.create_text(val, x, y, sx, sy, rotation, r, g, b) } fn create_text(&mut self, val: &str, x: f64, y: f64, sx: f64, sy: f64, rotation: f64, r: u8, g: u8, b: u8) -> UIText { let mut elements = Vec::new(); let mut offset = 0.0; for ch in val.chars() { if ch == ' ' { offset += 6.0; continue; } let texture = self.character_texture(ch); let w = self.size_of_char(ch); let mut dsx = offset + 2.0; let mut dsy = 2.0; let mut dx = offset; let mut dy = 0.0; if rotation != 0.0 { let c = rotation.cos(); let s = rotation.sin(); let tmpx = dsx - (w * 0.5); let tmpy = dsy - (16.0 * 0.5); dsx = (w * 0.5) + (tmpx * c - tmpy * s); dsy = (16.0 * 0.5) + (tmpy * c + tmpx * s); let tmpx = dx - (w * 0.5); let tmpy = dy - (16.0 * 0.5); dx = (w * 0.5) + (tmpx * c - tmpy * s); dy = (16.0 * 0.5) + (tmpy * c + tmpx * s); } let mut shadow = UIElement::new(&texture, x + dsx * sx, y + dsy * sy, w * sx, 16.0 * sy, 0.0, 0.0, 1.0, 1.0); shadow.r = ((r as f64) * 0.25) as u8; shadow.g = ((g as f64) * 0.25) as u8; shadow.b = ((b as f64) * 0.25) as u8; shadow.rotation = rotation; elements.push(shadow); let mut text = UIElement::new(&texture, x + dx * sx, y + dy * sy, w * sx, 16.0 * sy, 0.0, 0.0, 1.0, 1.0); text.r = r; text.g = g; text.b = b; text.rotation = rotation; elements.push(text); offset += w + 2.0; } UIText { elements: elements, width: (offset - 2.0) * sx, } } } pub struct UIText { pub elements: Vec<UIElement>, pub width: f64, } impl UIText { pub fn bytes(&self, width: f64, height: f64) -> Vec<u8> { let mut buf = Vec::with_capacity(28 * 4 * self.elements.len()); for e in &self.elements { buf.extend(e.bytes(width, height)); } buf } } pub struct UIElement { pub x: f64, pub y: f64, pub w: f64, pub h: f64, pub layer: isize, pub t_x: u16, pub t_y: u16, pub t_w: u16, pub t_h: u16, pub t_offsetx: i16, pub t_offsety: i16, pub t_atlas: i16, pub t_sizew: i16, pub t_sizeh: i16, pub r: u8, pub g: u8, pub b: u8, pub a: u8, pub rotation: f64, } impl UIElement { pub fn new(tex: &render::Texture, x: f64, y: f64, width: f64, height: f64, tx: f64, ty: f64, tw: f64, th: f64) -> UIElement { let twidth = tex.get_width(); let theight = tex.get_height(); UIElement { x: x / UI_WIDTH, y: y / UI_HEIGHT, w: width / UI_WIDTH, h: height / UI_HEIGHT, layer: 0, t_x: tex.get_x() as u16, t_y: tex.get_y() as u16, t_w: twidth as u16, t_h: theight as u16, t_atlas: tex.atlas as i16, t_offsetx: (tx * (twidth as f64) * 16.0) as i16, t_offsety: (ty * (theight as f64) * 16.0) as i16, t_sizew: (tw * (twidth as f64) * 16.0) as i16, t_sizeh: (th * (theight as f64) * 16.0) as i16, r: 255, g: 255, b: 255, a: 255, rotation: 0.0, } } pub fn bytes(&self, width: f64, height: f64) -> Vec<u8> { let mut buf = Vec::with_capacity(28 * 4); self.append_vertex(&mut buf, self.x, self.y, self.t_offsetx, self.t_offsety, width, height); self.append_vertex(&mut buf, self.x + self.w, self.y, self.t_offsetx + self.t_sizew, self.t_offsety, width, height); self.append_vertex(&mut buf, self.x, self.y + self.h, self.t_offsetx, self.t_offsety + self.t_sizeh, width, height); self.append_vertex(&mut buf, self.x + self.w, self.y + self.h, self.t_offsetx + self.t_sizew, self.t_offsety + self.t_sizeh, width, height); buf } #[allow(unused_must_use)] pub fn append_vertex(&self, buf: &mut Vec<u8>, x: f64, y: f64, tx: i16, ty: i16, width: f64, height: f64) { let mut dx = x as f64; let mut dy = y as f64; if self.rotation != 0.0 { let c = self.rotation.cos(); let s = self.rotation.sin(); let tmpx = dx - self.x - (self.w / 2.0); let tmpy = dy - self.y - (self.h / 2.0); dx = (self.w / 2.0) + (tmpx * c - tmpy * s) + self.x; dy = (self.h / 2.0) + (tmpy * c + tmpx * s) + self.y; } buf.write_i16::<NativeEndian>((dx * width + 0.5).floor() as i16); buf.write_i16::<NativeEndian>((dy * height + 0.5).floor() as i16); buf.write_i16::<NativeEndian>((self.layer * 256) as i16); buf.write_i16::<NativeEndian>(0); buf.write_u16::<NativeEndian>(self.t_x); buf.write_u16::<NativeEndian>(self.t_y); buf.write_u16::<NativeEndian>(self.t_w); buf.write_u16::<NativeEndian>(self.t_h); buf.write_i16::<NativeEndian>(tx); buf.write_i16::<NativeEndian>(ty); buf.write_i16::<NativeEndian>(self.t_atlas); buf.write_i16::<NativeEndian>(0); buf.write_u8(self.r); buf.write_u8(self.g); buf.write_u8(self.b); buf.write_u8(self.a); } }
_character_info[raw as usize]; if page == 0 { let
conditional_block
streakgaming.py
# !/usr/bin/python # -*- coding: cp1252 -*- # ################################################################################## # # Copyright 2016 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com) # # This program is part of OSRFramework. You can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################## __author__ = "Yaiza Rubio and Félix Brezo <contacto@i3visio.com>" __version__ = "1.1" import argparse import json import re import sys import urllib2 import osrframework.utils.browser as browser from osrframework.utils.platforms import Platform class Streakgaming(Platform): """ A <Platform> object for Streakgaming. """ def __init__(self): ""
" Constructor... """ self.platformName = "Streakgaming" self.tags = ["social", "news", "gaming"] ######################## # Defining valid modes # ######################## self.isValidMode = {} self.isValidMode["phonefy"] = False self.isValidMode["usufy"] = True self.isValidMode["searchfy"] = False ###################################### # Search URL for the different modes # ###################################### # Strings with the URL for each and every mode self.url = {} #self.url["phonefy"] = "http://anyurl.com//phone/" + "<phonefy>" self.url["usufy"] = "http://www.streakgaming.com/forum/members/" + "<usufy>" + ".html" #self.url["searchfy"] = "http://anyurl.com/search/" + "<searchfy>" ###################################### # Whether the user needs credentials # ###################################### self.needsCredentials = {} #self.needsCredentials["phonefy"] = False self.needsCredentials["usufy"] = False #self.needsCredentials["searchfy"] = False ################# # Valid queries # ################# # Strings that will imply that the query number is not appearing self.validQuery = {} # The regular expression '.+' will match any query. #self.validQuery["phonefy"] = ".*" self.validQuery["usufy"] = ".+" #self.validQuery["searchfy"] = ".*" ################### # Not_found clues # ################### # Strings that will imply that the query number is not appearing self.notFoundText = {} #self.notFoundText["phonefy"] = [] self.notFoundText["usufy"] = ["<title>Streak Gaming Online Gambling Forum</title>"] #self.notFoundText["searchfy"] = [] ######################### # Fields to be searched # ######################### self.fieldsRegExp = {} # Definition of regular expressions to be searched in phonefy mode #self.fieldsRegExp["phonefy"] = {} # Example of fields: #self.fieldsRegExp["phonefy"]["i3visio.location"] = "" # Definition of regular expressions to be searched in usufy mode self.fieldsRegExp["usufy"] = {} # Example of fields: #self.fieldsRegExp["usufy"]["i3visio.location"] = "" # Definition of regular expressions to be searched in searchfy mode #self.fieldsRegExp["searchfy"] = {} # Example of fields: #self.fieldsRegExp["searchfy"]["i3visio.location"] = "" ################ # Fields found # ################ # This attribute will be feeded when running the program. self.foundFields = {}
identifier_body
streakgaming.py
# !/usr/bin/python # -*- coding: cp1252 -*- # ################################################################################## # # Copyright 2016 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com) # # This program is part of OSRFramework. You can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version.
# 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, see <http://www.gnu.org/licenses/>. # ################################################################################## __author__ = "Yaiza Rubio and Félix Brezo <contacto@i3visio.com>" __version__ = "1.1" import argparse import json import re import sys import urllib2 import osrframework.utils.browser as browser from osrframework.utils.platforms import Platform class Streakgaming(Platform): """ A <Platform> object for Streakgaming. """ def __init__(self): """ Constructor... """ self.platformName = "Streakgaming" self.tags = ["social", "news", "gaming"] ######################## # Defining valid modes # ######################## self.isValidMode = {} self.isValidMode["phonefy"] = False self.isValidMode["usufy"] = True self.isValidMode["searchfy"] = False ###################################### # Search URL for the different modes # ###################################### # Strings with the URL for each and every mode self.url = {} #self.url["phonefy"] = "http://anyurl.com//phone/" + "<phonefy>" self.url["usufy"] = "http://www.streakgaming.com/forum/members/" + "<usufy>" + ".html" #self.url["searchfy"] = "http://anyurl.com/search/" + "<searchfy>" ###################################### # Whether the user needs credentials # ###################################### self.needsCredentials = {} #self.needsCredentials["phonefy"] = False self.needsCredentials["usufy"] = False #self.needsCredentials["searchfy"] = False ################# # Valid queries # ################# # Strings that will imply that the query number is not appearing self.validQuery = {} # The regular expression '.+' will match any query. #self.validQuery["phonefy"] = ".*" self.validQuery["usufy"] = ".+" #self.validQuery["searchfy"] = ".*" ################### # Not_found clues # ################### # Strings that will imply that the query number is not appearing self.notFoundText = {} #self.notFoundText["phonefy"] = [] self.notFoundText["usufy"] = ["<title>Streak Gaming Online Gambling Forum</title>"] #self.notFoundText["searchfy"] = [] ######################### # Fields to be searched # ######################### self.fieldsRegExp = {} # Definition of regular expressions to be searched in phonefy mode #self.fieldsRegExp["phonefy"] = {} # Example of fields: #self.fieldsRegExp["phonefy"]["i3visio.location"] = "" # Definition of regular expressions to be searched in usufy mode self.fieldsRegExp["usufy"] = {} # Example of fields: #self.fieldsRegExp["usufy"]["i3visio.location"] = "" # Definition of regular expressions to be searched in searchfy mode #self.fieldsRegExp["searchfy"] = {} # Example of fields: #self.fieldsRegExp["searchfy"]["i3visio.location"] = "" ################ # Fields found # ################ # This attribute will be feeded when running the program. self.foundFields = {}
# # 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
random_line_split
streakgaming.py
# !/usr/bin/python # -*- coding: cp1252 -*- # ################################################################################## # # Copyright 2016 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com) # # This program is part of OSRFramework. You can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################## __author__ = "Yaiza Rubio and Félix Brezo <contacto@i3visio.com>" __version__ = "1.1" import argparse import json import re import sys import urllib2 import osrframework.utils.browser as browser from osrframework.utils.platforms import Platform class St
latform): """ A <Platform> object for Streakgaming. """ def __init__(self): """ Constructor... """ self.platformName = "Streakgaming" self.tags = ["social", "news", "gaming"] ######################## # Defining valid modes # ######################## self.isValidMode = {} self.isValidMode["phonefy"] = False self.isValidMode["usufy"] = True self.isValidMode["searchfy"] = False ###################################### # Search URL for the different modes # ###################################### # Strings with the URL for each and every mode self.url = {} #self.url["phonefy"] = "http://anyurl.com//phone/" + "<phonefy>" self.url["usufy"] = "http://www.streakgaming.com/forum/members/" + "<usufy>" + ".html" #self.url["searchfy"] = "http://anyurl.com/search/" + "<searchfy>" ###################################### # Whether the user needs credentials # ###################################### self.needsCredentials = {} #self.needsCredentials["phonefy"] = False self.needsCredentials["usufy"] = False #self.needsCredentials["searchfy"] = False ################# # Valid queries # ################# # Strings that will imply that the query number is not appearing self.validQuery = {} # The regular expression '.+' will match any query. #self.validQuery["phonefy"] = ".*" self.validQuery["usufy"] = ".+" #self.validQuery["searchfy"] = ".*" ################### # Not_found clues # ################### # Strings that will imply that the query number is not appearing self.notFoundText = {} #self.notFoundText["phonefy"] = [] self.notFoundText["usufy"] = ["<title>Streak Gaming Online Gambling Forum</title>"] #self.notFoundText["searchfy"] = [] ######################### # Fields to be searched # ######################### self.fieldsRegExp = {} # Definition of regular expressions to be searched in phonefy mode #self.fieldsRegExp["phonefy"] = {} # Example of fields: #self.fieldsRegExp["phonefy"]["i3visio.location"] = "" # Definition of regular expressions to be searched in usufy mode self.fieldsRegExp["usufy"] = {} # Example of fields: #self.fieldsRegExp["usufy"]["i3visio.location"] = "" # Definition of regular expressions to be searched in searchfy mode #self.fieldsRegExp["searchfy"] = {} # Example of fields: #self.fieldsRegExp["searchfy"]["i3visio.location"] = "" ################ # Fields found # ################ # This attribute will be feeded when running the program. self.foundFields = {}
reakgaming(P
identifier_name
load_test.py
import re from threading import Thread import time from django.core.management.base import BaseCommand import requests from mittab.apps.tab.models import Round, TabSettings from mittab.apps.tab.management.commands import utils class Command(BaseCommand): help = "Load test the tournament, connecting via localhost and hitting the server" def add_arguments(self, parser): parser.add_argument( "--host", dest="host", help="The hostname of the server to hit", nargs="?", default="localhost:8000") parser.add_argument( "--connections", dest="connections", help="The number of concurrent connections to open", nargs="?", default=10, type=int) def handle(self, *args, **options): cur_round = TabSettings.get("cur_round") - 1 host = options["host"] csrf_threads = [] rounds = Round.objects.filter(round_number=cur_round, victor=Round.NONE) for round_obj in rounds: judge = round_obj.chair csrf_threads.append(GetCsrfThread(host, judge.ballot_code, round_obj)) num_errors = 0 while csrf_threads: cur_csrf_threads = [] for _ in range(min(len(csrf_threads), options["connections"])): cur_csrf_threads.append(csrf_threads.pop()) for thr in cur_csrf_threads: thr.start() for thr in cur_csrf_threads: thr.join() result_threads = [] for thr in cur_csrf_threads: num_errors += num_errors csrf_token, num_errors = thr.result if csrf_token is None: print("no csrf token") result_thread = SubmitResultThread( thr.host, thr.ballot_code, csrf_token, thr.round_obj) result_threads.append(result_thread) for thr in result_threads: thr.start() for thr in result_threads: thr.join() for thr in result_threads: num_errors += thr.num_errors print("Done with one batch! Sleeping!") time.sleep(2) print("Done!") print("Total errors: %s" % num_errors) class SubmitResultThread(Thread): MAX_ERRORS = 10 def __init__(self, host, ballot_code, csrf_token, round_obj): super(SubmitResultThread, self).__init__() self.host = host self.ballot_code = ballot_code self.csrf_token = csrf_token self.round_obj = round_obj self.num_errors = 0 self.resp = None
def run(self): self.resp = self.get_resp() def get_resp(self): if self.num_errors >= self.MAX_ERRORS: return None result = utils.generate_random_results(self.round_obj, self.ballot_code) result["csrfmiddlewaretoken"] = self.csrf_token resp = requests.post("http://%s/e_ballots/%s/" % (self.host, self.ballot_code), result, cookies={"csrftoken": self.csrf_token}) if resp.status_code > 299: self.num_errors += 1 return self.get_resp() else: return resp.text class GetCsrfThread(Thread): REGEX = "name=\"csrfmiddlewaretoken\" value=\"([^\"]+)\"" MAX_ERRORS = 10 def __init__(self, host, ballot_code, round_obj): super(GetCsrfThread, self).__init__() self.num_errors = 0 self.host = host self.ballot_code = ballot_code self.round_obj = round_obj self.result = (None, None) def run(self): resp = self.get_resp() if resp is None: self.result = (None, self.num_errors) else: csrf = re.search(self.REGEX, resp).group(1) self.result = (csrf, self.num_errors) def get_resp(self): if self.num_errors >= self.MAX_ERRORS: return None resp = requests.get("http://%s/e_ballots/%s" % (self.host, self.ballot_code)) if resp.status_code > 299: self.num_errors += 1 return self.get_resp() else: return resp.text
random_line_split
load_test.py
import re from threading import Thread import time from django.core.management.base import BaseCommand import requests from mittab.apps.tab.models import Round, TabSettings from mittab.apps.tab.management.commands import utils class Command(BaseCommand): help = "Load test the tournament, connecting via localhost and hitting the server" def add_arguments(self, parser): parser.add_argument( "--host", dest="host", help="The hostname of the server to hit", nargs="?", default="localhost:8000") parser.add_argument( "--connections", dest="connections", help="The number of concurrent connections to open", nargs="?", default=10, type=int) def handle(self, *args, **options): cur_round = TabSettings.get("cur_round") - 1 host = options["host"] csrf_threads = [] rounds = Round.objects.filter(round_number=cur_round, victor=Round.NONE) for round_obj in rounds: judge = round_obj.chair csrf_threads.append(GetCsrfThread(host, judge.ballot_code, round_obj)) num_errors = 0 while csrf_threads: cur_csrf_threads = [] for _ in range(min(len(csrf_threads), options["connections"])): cur_csrf_threads.append(csrf_threads.pop()) for thr in cur_csrf_threads: thr.start() for thr in cur_csrf_threads: thr.join() result_threads = [] for thr in cur_csrf_threads: num_errors += num_errors csrf_token, num_errors = thr.result if csrf_token is None: print("no csrf token") result_thread = SubmitResultThread( thr.host, thr.ballot_code, csrf_token, thr.round_obj) result_threads.append(result_thread) for thr in result_threads: thr.start() for thr in result_threads: thr.join() for thr in result_threads: num_errors += thr.num_errors print("Done with one batch! Sleeping!") time.sleep(2) print("Done!") print("Total errors: %s" % num_errors) class SubmitResultThread(Thread): MAX_ERRORS = 10 def __init__(self, host, ballot_code, csrf_token, round_obj): super(SubmitResultThread, self).__init__() self.host = host self.ballot_code = ballot_code self.csrf_token = csrf_token self.round_obj = round_obj self.num_errors = 0 self.resp = None def run(self): self.resp = self.get_resp() def get_resp(self): if self.num_errors >= self.MAX_ERRORS: return None result = utils.generate_random_results(self.round_obj, self.ballot_code) result["csrfmiddlewaretoken"] = self.csrf_token resp = requests.post("http://%s/e_ballots/%s/" % (self.host, self.ballot_code), result, cookies={"csrftoken": self.csrf_token}) if resp.status_code > 299: self.num_errors += 1 return self.get_resp() else: return resp.text class GetCsrfThread(Thread): REGEX = "name=\"csrfmiddlewaretoken\" value=\"([^\"]+)\"" MAX_ERRORS = 10 def
(self, host, ballot_code, round_obj): super(GetCsrfThread, self).__init__() self.num_errors = 0 self.host = host self.ballot_code = ballot_code self.round_obj = round_obj self.result = (None, None) def run(self): resp = self.get_resp() if resp is None: self.result = (None, self.num_errors) else: csrf = re.search(self.REGEX, resp).group(1) self.result = (csrf, self.num_errors) def get_resp(self): if self.num_errors >= self.MAX_ERRORS: return None resp = requests.get("http://%s/e_ballots/%s" % (self.host, self.ballot_code)) if resp.status_code > 299: self.num_errors += 1 return self.get_resp() else: return resp.text
__init__
identifier_name
load_test.py
import re from threading import Thread import time from django.core.management.base import BaseCommand import requests from mittab.apps.tab.models import Round, TabSettings from mittab.apps.tab.management.commands import utils class Command(BaseCommand): help = "Load test the tournament, connecting via localhost and hitting the server" def add_arguments(self, parser): parser.add_argument( "--host", dest="host", help="The hostname of the server to hit", nargs="?", default="localhost:8000") parser.add_argument( "--connections", dest="connections", help="The number of concurrent connections to open", nargs="?", default=10, type=int) def handle(self, *args, **options): cur_round = TabSettings.get("cur_round") - 1 host = options["host"] csrf_threads = [] rounds = Round.objects.filter(round_number=cur_round, victor=Round.NONE) for round_obj in rounds: judge = round_obj.chair csrf_threads.append(GetCsrfThread(host, judge.ballot_code, round_obj)) num_errors = 0 while csrf_threads: cur_csrf_threads = [] for _ in range(min(len(csrf_threads), options["connections"])): cur_csrf_threads.append(csrf_threads.pop()) for thr in cur_csrf_threads: thr.start() for thr in cur_csrf_threads: thr.join() result_threads = [] for thr in cur_csrf_threads: num_errors += num_errors csrf_token, num_errors = thr.result if csrf_token is None: print("no csrf token") result_thread = SubmitResultThread( thr.host, thr.ballot_code, csrf_token, thr.round_obj) result_threads.append(result_thread) for thr in result_threads: thr.start() for thr in result_threads: thr.join() for thr in result_threads: num_errors += thr.num_errors print("Done with one batch! Sleeping!") time.sleep(2) print("Done!") print("Total errors: %s" % num_errors) class SubmitResultThread(Thread): MAX_ERRORS = 10 def __init__(self, host, ballot_code, csrf_token, round_obj): super(SubmitResultThread, self).__init__() self.host = host self.ballot_code = ballot_code self.csrf_token = csrf_token self.round_obj = round_obj self.num_errors = 0 self.resp = None def run(self): self.resp = self.get_resp() def get_resp(self):
class GetCsrfThread(Thread): REGEX = "name=\"csrfmiddlewaretoken\" value=\"([^\"]+)\"" MAX_ERRORS = 10 def __init__(self, host, ballot_code, round_obj): super(GetCsrfThread, self).__init__() self.num_errors = 0 self.host = host self.ballot_code = ballot_code self.round_obj = round_obj self.result = (None, None) def run(self): resp = self.get_resp() if resp is None: self.result = (None, self.num_errors) else: csrf = re.search(self.REGEX, resp).group(1) self.result = (csrf, self.num_errors) def get_resp(self): if self.num_errors >= self.MAX_ERRORS: return None resp = requests.get("http://%s/e_ballots/%s" % (self.host, self.ballot_code)) if resp.status_code > 299: self.num_errors += 1 return self.get_resp() else: return resp.text
if self.num_errors >= self.MAX_ERRORS: return None result = utils.generate_random_results(self.round_obj, self.ballot_code) result["csrfmiddlewaretoken"] = self.csrf_token resp = requests.post("http://%s/e_ballots/%s/" % (self.host, self.ballot_code), result, cookies={"csrftoken": self.csrf_token}) if resp.status_code > 299: self.num_errors += 1 return self.get_resp() else: return resp.text
identifier_body
load_test.py
import re from threading import Thread import time from django.core.management.base import BaseCommand import requests from mittab.apps.tab.models import Round, TabSettings from mittab.apps.tab.management.commands import utils class Command(BaseCommand): help = "Load test the tournament, connecting via localhost and hitting the server" def add_arguments(self, parser): parser.add_argument( "--host", dest="host", help="The hostname of the server to hit", nargs="?", default="localhost:8000") parser.add_argument( "--connections", dest="connections", help="The number of concurrent connections to open", nargs="?", default=10, type=int) def handle(self, *args, **options): cur_round = TabSettings.get("cur_round") - 1 host = options["host"] csrf_threads = [] rounds = Round.objects.filter(round_number=cur_round, victor=Round.NONE) for round_obj in rounds: judge = round_obj.chair csrf_threads.append(GetCsrfThread(host, judge.ballot_code, round_obj)) num_errors = 0 while csrf_threads: cur_csrf_threads = [] for _ in range(min(len(csrf_threads), options["connections"])): cur_csrf_threads.append(csrf_threads.pop()) for thr in cur_csrf_threads: thr.start() for thr in cur_csrf_threads: thr.join() result_threads = [] for thr in cur_csrf_threads: num_errors += num_errors csrf_token, num_errors = thr.result if csrf_token is None: print("no csrf token") result_thread = SubmitResultThread( thr.host, thr.ballot_code, csrf_token, thr.round_obj) result_threads.append(result_thread) for thr in result_threads: thr.start() for thr in result_threads: thr.join() for thr in result_threads: num_errors += thr.num_errors print("Done with one batch! Sleeping!") time.sleep(2) print("Done!") print("Total errors: %s" % num_errors) class SubmitResultThread(Thread): MAX_ERRORS = 10 def __init__(self, host, ballot_code, csrf_token, round_obj): super(SubmitResultThread, self).__init__() self.host = host self.ballot_code = ballot_code self.csrf_token = csrf_token self.round_obj = round_obj self.num_errors = 0 self.resp = None def run(self): self.resp = self.get_resp() def get_resp(self): if self.num_errors >= self.MAX_ERRORS: return None result = utils.generate_random_results(self.round_obj, self.ballot_code) result["csrfmiddlewaretoken"] = self.csrf_token resp = requests.post("http://%s/e_ballots/%s/" % (self.host, self.ballot_code), result, cookies={"csrftoken": self.csrf_token}) if resp.status_code > 299:
else: return resp.text class GetCsrfThread(Thread): REGEX = "name=\"csrfmiddlewaretoken\" value=\"([^\"]+)\"" MAX_ERRORS = 10 def __init__(self, host, ballot_code, round_obj): super(GetCsrfThread, self).__init__() self.num_errors = 0 self.host = host self.ballot_code = ballot_code self.round_obj = round_obj self.result = (None, None) def run(self): resp = self.get_resp() if resp is None: self.result = (None, self.num_errors) else: csrf = re.search(self.REGEX, resp).group(1) self.result = (csrf, self.num_errors) def get_resp(self): if self.num_errors >= self.MAX_ERRORS: return None resp = requests.get("http://%s/e_ballots/%s" % (self.host, self.ballot_code)) if resp.status_code > 299: self.num_errors += 1 return self.get_resp() else: return resp.text
self.num_errors += 1 return self.get_resp()
conditional_block
executors.py
# -*- coding:utf-8 -*- import copy from zope.interface import implementer from .interfaces import ( IExecutor, ISchemaValidation, IDataValidation, ICreate, IDelete, IEdit ) from alchemyjsonschema.dictify import ( normalize, validate_all, ErrorFound ) from jsonschema import FormatChecker from jsonschema.validators import Draft4Validator class ValidationError(Exception): pass @implementer(IExecutor) class Executor(object): def __init__(self, context, params): self.context = context self.raw_params = params self.params = None def validation(self, ob=None): raise NotImplemented def execute(self, ob=None): raise NotImplemented def default_validation(self, iface, ob=None, name=""): fn = self.context.customized_or_default(iface, ISchemaValidation, name=name) params = fn(self.context, self.raw_params) fn2 = self.context.customized_or_default(iface, IDataValidation, name=name) fn2(self.context, params, ob) return params class CreateExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, ICreate, ob) def execute(self, ob=None): if self.params is None:
ob = self.context.modelclass(**self.params) self.context.session.add(ob) self.context.session.flush() return ob class EditExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, IEdit, ob) def execute(self, ob): if self.params is None: raise RuntimeError("execute after validation") for k, v in self.params.items(): setattr(ob, k, v) self.context.session.add(ob) return ob class DeleteExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, IDelete, ob) def execute(self, ob): self.context.session.delete(ob) return ob def create_jsonschema_validation(context, params, ob=None): def customize_schema(schema): schema = copy.deepcopy(schema) # when creating model, id is not needed. if "id" in schema["required"]: schema["required"].remove("id") if "id" in schema["properties"]: schema["properties"].pop("id") return schema schema = customize_schema(context.schema) schema_validator = Draft4Validator(schema, format_checker=FormatChecker()) try: validate_all(params, schema_validator) except ErrorFound as err: raise ValidationError({e.path[0]: e.message for e in err.errors}) return normalize(params, schema) def edit_jsonschema_validation(context, params): schema = context.schema schema_validator = Draft4Validator(schema, format_checker=FormatChecker()) try: validate_all(params, schema_validator) except ErrorFound as err: raise ValidationError({e.path[0]: e.message for e in err.errors}) return normalize(params, schema) def delete_jsonschema_validation(context, params): return params
raise RuntimeError("execute after validation")
conditional_block
executors.py
# -*- coding:utf-8 -*- import copy from zope.interface import implementer from .interfaces import ( IExecutor, ISchemaValidation, IDataValidation, ICreate, IDelete, IEdit ) from alchemyjsonschema.dictify import ( normalize, validate_all, ErrorFound ) from jsonschema import FormatChecker from jsonschema.validators import Draft4Validator class ValidationError(Exception): pass @implementer(IExecutor) class Executor(object): def __init__(self, context, params): self.context = context self.raw_params = params self.params = None def validation(self, ob=None): raise NotImplemented def execute(self, ob=None): raise NotImplemented def default_validation(self, iface, ob=None, name=""): fn = self.context.customized_or_default(iface, ISchemaValidation, name=name) params = fn(self.context, self.raw_params) fn2 = self.context.customized_or_default(iface, IDataValidation, name=name) fn2(self.context, params, ob) return params class CreateExecutor(Executor): def validation(self, ob=None):
def execute(self, ob=None): if self.params is None: raise RuntimeError("execute after validation") ob = self.context.modelclass(**self.params) self.context.session.add(ob) self.context.session.flush() return ob class EditExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, IEdit, ob) def execute(self, ob): if self.params is None: raise RuntimeError("execute after validation") for k, v in self.params.items(): setattr(ob, k, v) self.context.session.add(ob) return ob class DeleteExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, IDelete, ob) def execute(self, ob): self.context.session.delete(ob) return ob def create_jsonschema_validation(context, params, ob=None): def customize_schema(schema): schema = copy.deepcopy(schema) # when creating model, id is not needed. if "id" in schema["required"]: schema["required"].remove("id") if "id" in schema["properties"]: schema["properties"].pop("id") return schema schema = customize_schema(context.schema) schema_validator = Draft4Validator(schema, format_checker=FormatChecker()) try: validate_all(params, schema_validator) except ErrorFound as err: raise ValidationError({e.path[0]: e.message for e in err.errors}) return normalize(params, schema) def edit_jsonschema_validation(context, params): schema = context.schema schema_validator = Draft4Validator(schema, format_checker=FormatChecker()) try: validate_all(params, schema_validator) except ErrorFound as err: raise ValidationError({e.path[0]: e.message for e in err.errors}) return normalize(params, schema) def delete_jsonschema_validation(context, params): return params
self.params = default_validation(self, ICreate, ob)
identifier_body
executors.py
# -*- coding:utf-8 -*- import copy from zope.interface import implementer from .interfaces import ( IExecutor, ISchemaValidation, IDataValidation, ICreate, IDelete, IEdit ) from alchemyjsonschema.dictify import ( normalize, validate_all, ErrorFound ) from jsonschema import FormatChecker from jsonschema.validators import Draft4Validator class ValidationError(Exception): pass @implementer(IExecutor) class Executor(object): def __init__(self, context, params): self.context = context self.raw_params = params self.params = None def validation(self, ob=None): raise NotImplemented def execute(self, ob=None): raise NotImplemented def default_validation(self, iface, ob=None, name=""): fn = self.context.customized_or_default(iface, ISchemaValidation, name=name) params = fn(self.context, self.raw_params) fn2 = self.context.customized_or_default(iface, IDataValidation, name=name) fn2(self.context, params, ob) return params class CreateExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, ICreate, ob) def execute(self, ob=None): if self.params is None: raise RuntimeError("execute after validation") ob = self.context.modelclass(**self.params) self.context.session.add(ob) self.context.session.flush() return ob class EditExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, IEdit, ob) def execute(self, ob): if self.params is None: raise RuntimeError("execute after validation") for k, v in self.params.items(): setattr(ob, k, v) self.context.session.add(ob) return ob class DeleteExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, IDelete, ob) def
(self, ob): self.context.session.delete(ob) return ob def create_jsonschema_validation(context, params, ob=None): def customize_schema(schema): schema = copy.deepcopy(schema) # when creating model, id is not needed. if "id" in schema["required"]: schema["required"].remove("id") if "id" in schema["properties"]: schema["properties"].pop("id") return schema schema = customize_schema(context.schema) schema_validator = Draft4Validator(schema, format_checker=FormatChecker()) try: validate_all(params, schema_validator) except ErrorFound as err: raise ValidationError({e.path[0]: e.message for e in err.errors}) return normalize(params, schema) def edit_jsonschema_validation(context, params): schema = context.schema schema_validator = Draft4Validator(schema, format_checker=FormatChecker()) try: validate_all(params, schema_validator) except ErrorFound as err: raise ValidationError({e.path[0]: e.message for e in err.errors}) return normalize(params, schema) def delete_jsonschema_validation(context, params): return params
execute
identifier_name
executors.py
# -*- coding:utf-8 -*- import copy from zope.interface import implementer from .interfaces import ( IExecutor, ISchemaValidation, IDataValidation, ICreate, IDelete, IEdit ) from alchemyjsonschema.dictify import ( normalize, validate_all, ErrorFound ) from jsonschema import FormatChecker from jsonschema.validators import Draft4Validator class ValidationError(Exception): pass @implementer(IExecutor) class Executor(object): def __init__(self, context, params): self.context = context self.raw_params = params self.params = None def validation(self, ob=None): raise NotImplemented def execute(self, ob=None): raise NotImplemented def default_validation(self, iface, ob=None, name=""): fn = self.context.customized_or_default(iface, ISchemaValidation, name=name) params = fn(self.context, self.raw_params) fn2 = self.context.customized_or_default(iface, IDataValidation, name=name) fn2(self.context, params, ob) return params class CreateExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, ICreate, ob) def execute(self, ob=None): if self.params is None: raise RuntimeError("execute after validation") ob = self.context.modelclass(**self.params) self.context.session.add(ob) self.context.session.flush() return ob class EditExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, IEdit, ob) def execute(self, ob): if self.params is None: raise RuntimeError("execute after validation") for k, v in self.params.items(): setattr(ob, k, v) self.context.session.add(ob) return ob class DeleteExecutor(Executor): def validation(self, ob=None): self.params = default_validation(self, IDelete, ob) def execute(self, ob): self.context.session.delete(ob) return ob def create_jsonschema_validation(context, params, ob=None): def customize_schema(schema): schema = copy.deepcopy(schema) # when creating model, id is not needed. if "id" in schema["required"]: schema["required"].remove("id") if "id" in schema["properties"]: schema["properties"].pop("id") return schema schema = customize_schema(context.schema) schema_validator = Draft4Validator(schema, format_checker=FormatChecker()) try: validate_all(params, schema_validator) except ErrorFound as err: raise ValidationError({e.path[0]: e.message for e in err.errors}) return normalize(params, schema) def edit_jsonschema_validation(context, params): schema = context.schema schema_validator = Draft4Validator(schema, format_checker=FormatChecker())
validate_all(params, schema_validator) except ErrorFound as err: raise ValidationError({e.path[0]: e.message for e in err.errors}) return normalize(params, schema) def delete_jsonschema_validation(context, params): return params
try:
random_line_split
font_context.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 freetype::freetype::FT_Add_Default_Modules; use freetype::freetype::FT_Done_Library; use freetype::freetype::FT_Library; use freetype::freetype::FT_Memory; use freetype::freetype::FT_MemoryRec_; use freetype::freetype::FT_New_Library; use freetype::succeeded; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use servo_allocator::libc_compat::{malloc, realloc, free}; use servo_allocator::usable_size; use std::os::raw::{c_long, c_void}; use std::ptr; use std::rc::Rc; // We pass a |User| struct -- via an opaque |void*| -- to FreeType each time a new instance is // created. FreeType passes it back to the ft_alloc/ft_realloc/ft_free callbacks. We use it to // record the memory usage of each FreeType instance. pub struct User { size: usize, } extern "C" fn ft_alloc(mem: FT_Memory, req_size: c_long) -> *mut c_void { unsafe { let ptr = malloc(req_size as usize); let ptr = ptr as *mut c_void; // libc::c_void vs std::os::raw::c_void let actual_size = usable_size(ptr); let user = (*mem).user as *mut User; (*user).size += actual_size; ptr } } extern "C" fn ft_free(mem: FT_Memory, ptr: *mut c_void) { unsafe { let actual_size = usable_size(ptr); let user = (*mem).user as *mut User; (*user).size -= actual_size; free(ptr as *mut _); } } extern "C" fn ft_realloc( mem: FT_Memory, _old_size: c_long, new_req_size: c_long, old_ptr: *mut c_void, ) -> *mut c_void { unsafe { let old_actual_size = usable_size(old_ptr); let new_ptr = realloc(old_ptr as *mut _, new_req_size as usize); let new_ptr = new_ptr as *mut c_void; let new_actual_size = usable_size(new_ptr); let user = (*mem).user as *mut User; (*user).size += new_actual_size; (*user).size -= old_actual_size; new_ptr } } // A |*mut User| field in a struct triggers a "use of `#[derive]` with a raw pointer" warning from // rustc. But using a typedef avoids this, so... pub type UserPtr = *mut User; // WARNING: We need to be careful how we use this struct. See the comment about Rc<> in // FontContextHandle. #[derive(Clone, Debug)] pub struct FreeTypeLibraryHandle { pub ctx: FT_Library, mem: FT_Memory, user: UserPtr, } impl Drop for FreeTypeLibraryHandle { fn drop(&mut self) { assert!(!self.ctx.is_null()); unsafe { FT_Done_Library(self.ctx); Box::from_raw(self.mem); Box::from_raw(self.user); } } } impl MallocSizeOf for FreeTypeLibraryHandle { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { unsafe { (*self.user).size + ops.malloc_size_of(self.ctx as *const _) + ops.malloc_size_of(self.mem as *const _) + ops.malloc_size_of(self.user as *const _) } } } #[derive(Clone, Debug)] pub struct FontContextHandle { // WARNING: FreeTypeLibraryHandle contains raw pointers, is clonable, and also implements // `Drop`. This field needs to be Rc<> to make sure that the `drop` function is only called // once, otherwise we'll get crashes. Yuk. pub ctx: Rc<FreeTypeLibraryHandle>, } impl MallocSizeOf for FontContextHandle { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { self.ctx.size_of(ops) } } impl FontContextHandle { pub fn new() -> FontContextHandle { let user = Box::into_raw(Box::new(User { size: 0 })); let mem = Box::into_raw(Box::new(FT_MemoryRec_ { user: user as *mut c_void, alloc: Some(ft_alloc), free: Some(ft_free), realloc: Some(ft_realloc), })); unsafe { let mut ctx: FT_Library = ptr::null_mut(); let result = FT_New_Library(mem, &mut ctx); if !succeeded(result)
FT_Add_Default_Modules(ctx); FontContextHandle { ctx: Rc::new(FreeTypeLibraryHandle { ctx: ctx, mem: mem, user: user, }), } } } }
{ panic!("Unable to initialize FreeType library"); }
conditional_block
font_context.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 freetype::freetype::FT_Add_Default_Modules; use freetype::freetype::FT_Done_Library; use freetype::freetype::FT_Library; use freetype::freetype::FT_Memory; use freetype::freetype::FT_MemoryRec_; use freetype::freetype::FT_New_Library; use freetype::succeeded; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use servo_allocator::libc_compat::{malloc, realloc, free}; use servo_allocator::usable_size; use std::os::raw::{c_long, c_void}; use std::ptr; use std::rc::Rc; // We pass a |User| struct -- via an opaque |void*| -- to FreeType each time a new instance is // created. FreeType passes it back to the ft_alloc/ft_realloc/ft_free callbacks. We use it to // record the memory usage of each FreeType instance. pub struct User { size: usize, } extern "C" fn ft_alloc(mem: FT_Memory, req_size: c_long) -> *mut c_void { unsafe { let ptr = malloc(req_size as usize); let ptr = ptr as *mut c_void; // libc::c_void vs std::os::raw::c_void let actual_size = usable_size(ptr); let user = (*mem).user as *mut User; (*user).size += actual_size; ptr } } extern "C" fn ft_free(mem: FT_Memory, ptr: *mut c_void) { unsafe { let actual_size = usable_size(ptr); let user = (*mem).user as *mut User; (*user).size -= actual_size; free(ptr as *mut _); } } extern "C" fn ft_realloc( mem: FT_Memory, _old_size: c_long, new_req_size: c_long, old_ptr: *mut c_void, ) -> *mut c_void { unsafe { let old_actual_size = usable_size(old_ptr); let new_ptr = realloc(old_ptr as *mut _, new_req_size as usize); let new_ptr = new_ptr as *mut c_void; let new_actual_size = usable_size(new_ptr); let user = (*mem).user as *mut User; (*user).size += new_actual_size; (*user).size -= old_actual_size; new_ptr } } // A |*mut User| field in a struct triggers a "use of `#[derive]` with a raw pointer" warning from // rustc. But using a typedef avoids this, so... pub type UserPtr = *mut User; // WARNING: We need to be careful how we use this struct. See the comment about Rc<> in // FontContextHandle. #[derive(Clone, Debug)] pub struct FreeTypeLibraryHandle { pub ctx: FT_Library, mem: FT_Memory, user: UserPtr, } impl Drop for FreeTypeLibraryHandle { fn drop(&mut self) { assert!(!self.ctx.is_null()); unsafe { FT_Done_Library(self.ctx); Box::from_raw(self.mem); Box::from_raw(self.user); } } } impl MallocSizeOf for FreeTypeLibraryHandle { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { unsafe { (*self.user).size + ops.malloc_size_of(self.ctx as *const _) + ops.malloc_size_of(self.mem as *const _) + ops.malloc_size_of(self.user as *const _) } } } #[derive(Clone, Debug)] pub struct FontContextHandle { // WARNING: FreeTypeLibraryHandle contains raw pointers, is clonable, and also implements // `Drop`. This field needs to be Rc<> to make sure that the `drop` function is only called // once, otherwise we'll get crashes. Yuk. pub ctx: Rc<FreeTypeLibraryHandle>, } impl MallocSizeOf for FontContextHandle { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { self.ctx.size_of(ops)
} impl FontContextHandle { pub fn new() -> FontContextHandle { let user = Box::into_raw(Box::new(User { size: 0 })); let mem = Box::into_raw(Box::new(FT_MemoryRec_ { user: user as *mut c_void, alloc: Some(ft_alloc), free: Some(ft_free), realloc: Some(ft_realloc), })); unsafe { let mut ctx: FT_Library = ptr::null_mut(); let result = FT_New_Library(mem, &mut ctx); if !succeeded(result) { panic!("Unable to initialize FreeType library"); } FT_Add_Default_Modules(ctx); FontContextHandle { ctx: Rc::new(FreeTypeLibraryHandle { ctx: ctx, mem: mem, user: user, }), } } } }
}
random_line_split
font_context.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 freetype::freetype::FT_Add_Default_Modules; use freetype::freetype::FT_Done_Library; use freetype::freetype::FT_Library; use freetype::freetype::FT_Memory; use freetype::freetype::FT_MemoryRec_; use freetype::freetype::FT_New_Library; use freetype::succeeded; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use servo_allocator::libc_compat::{malloc, realloc, free}; use servo_allocator::usable_size; use std::os::raw::{c_long, c_void}; use std::ptr; use std::rc::Rc; // We pass a |User| struct -- via an opaque |void*| -- to FreeType each time a new instance is // created. FreeType passes it back to the ft_alloc/ft_realloc/ft_free callbacks. We use it to // record the memory usage of each FreeType instance. pub struct User { size: usize, } extern "C" fn ft_alloc(mem: FT_Memory, req_size: c_long) -> *mut c_void { unsafe { let ptr = malloc(req_size as usize); let ptr = ptr as *mut c_void; // libc::c_void vs std::os::raw::c_void let actual_size = usable_size(ptr); let user = (*mem).user as *mut User; (*user).size += actual_size; ptr } } extern "C" fn ft_free(mem: FT_Memory, ptr: *mut c_void) { unsafe { let actual_size = usable_size(ptr); let user = (*mem).user as *mut User; (*user).size -= actual_size; free(ptr as *mut _); } } extern "C" fn ft_realloc( mem: FT_Memory, _old_size: c_long, new_req_size: c_long, old_ptr: *mut c_void, ) -> *mut c_void { unsafe { let old_actual_size = usable_size(old_ptr); let new_ptr = realloc(old_ptr as *mut _, new_req_size as usize); let new_ptr = new_ptr as *mut c_void; let new_actual_size = usable_size(new_ptr); let user = (*mem).user as *mut User; (*user).size += new_actual_size; (*user).size -= old_actual_size; new_ptr } } // A |*mut User| field in a struct triggers a "use of `#[derive]` with a raw pointer" warning from // rustc. But using a typedef avoids this, so... pub type UserPtr = *mut User; // WARNING: We need to be careful how we use this struct. See the comment about Rc<> in // FontContextHandle. #[derive(Clone, Debug)] pub struct FreeTypeLibraryHandle { pub ctx: FT_Library, mem: FT_Memory, user: UserPtr, } impl Drop for FreeTypeLibraryHandle { fn drop(&mut self) { assert!(!self.ctx.is_null()); unsafe { FT_Done_Library(self.ctx); Box::from_raw(self.mem); Box::from_raw(self.user); } } } impl MallocSizeOf for FreeTypeLibraryHandle { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { unsafe { (*self.user).size + ops.malloc_size_of(self.ctx as *const _) + ops.malloc_size_of(self.mem as *const _) + ops.malloc_size_of(self.user as *const _) } } } #[derive(Clone, Debug)] pub struct FontContextHandle { // WARNING: FreeTypeLibraryHandle contains raw pointers, is clonable, and also implements // `Drop`. This field needs to be Rc<> to make sure that the `drop` function is only called // once, otherwise we'll get crashes. Yuk. pub ctx: Rc<FreeTypeLibraryHandle>, } impl MallocSizeOf for FontContextHandle { fn
(&self, ops: &mut MallocSizeOfOps) -> usize { self.ctx.size_of(ops) } } impl FontContextHandle { pub fn new() -> FontContextHandle { let user = Box::into_raw(Box::new(User { size: 0 })); let mem = Box::into_raw(Box::new(FT_MemoryRec_ { user: user as *mut c_void, alloc: Some(ft_alloc), free: Some(ft_free), realloc: Some(ft_realloc), })); unsafe { let mut ctx: FT_Library = ptr::null_mut(); let result = FT_New_Library(mem, &mut ctx); if !succeeded(result) { panic!("Unable to initialize FreeType library"); } FT_Add_Default_Modules(ctx); FontContextHandle { ctx: Rc::new(FreeTypeLibraryHandle { ctx: ctx, mem: mem, user: user, }), } } } }
size_of
identifier_name
config.rs
use std::io::{Read, Write}; use std::fs::{self, File}; use std::path::PathBuf; use std::env::home_dir; use error::*; use serde_json; lazy_static! { pub static ref CONFIG: Config = read_config().expect("Failed to read configuration."); } #[derive(Debug, Serialize, Deserialize)] pub struct Config { pub host: String, pub key: String } fn config_path() -> PathBuf { home_dir() .expect("Failed to locate home directory.") .join(".config") .join("ComfyPush") .join("client-config.json") } pub fn read_config() -> ComfyResult<Config> { let mut body = String::new(); let mut file = File::open(config_path())?; file.read_to_string(&mut body)?; serde_json::from_str(&body) .map_err(ComfyError::from) } pub fn write_config(host: &str, key: &str) -> ComfyResult<Config>
{ let path = config_path(); fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics let mut file = File::open(path)?; let body = serde_json::to_string(&Config { host: host.to_string(), key: key.to_string() })?; serde_json::from_str(&body) .map_err(ComfyError::from) }
identifier_body
config.rs
use std::io::{Read, Write}; use std::fs::{self, File}; use std::path::PathBuf; use std::env::home_dir; use error::*; use serde_json; lazy_static! { pub static ref CONFIG: Config = read_config().expect("Failed to read configuration."); } #[derive(Debug, Serialize, Deserialize)] pub struct Config { pub host: String, pub key: String } fn config_path() -> PathBuf { home_dir() .expect("Failed to locate home directory.") .join(".config") .join("ComfyPush") .join("client-config.json") } pub fn read_config() -> ComfyResult<Config> { let mut body = String::new(); let mut file = File::open(config_path())?; file.read_to_string(&mut body)?; serde_json::from_str(&body)
pub fn write_config(host: &str, key: &str) -> ComfyResult<Config> { let path = config_path(); fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics let mut file = File::open(path)?; let body = serde_json::to_string(&Config { host: host.to_string(), key: key.to_string() })?; serde_json::from_str(&body) .map_err(ComfyError::from) }
.map_err(ComfyError::from) }
random_line_split
config.rs
use std::io::{Read, Write}; use std::fs::{self, File}; use std::path::PathBuf; use std::env::home_dir; use error::*; use serde_json; lazy_static! { pub static ref CONFIG: Config = read_config().expect("Failed to read configuration."); } #[derive(Debug, Serialize, Deserialize)] pub struct Config { pub host: String, pub key: String } fn config_path() -> PathBuf { home_dir() .expect("Failed to locate home directory.") .join(".config") .join("ComfyPush") .join("client-config.json") } pub fn read_config() -> ComfyResult<Config> { let mut body = String::new(); let mut file = File::open(config_path())?; file.read_to_string(&mut body)?; serde_json::from_str(&body) .map_err(ComfyError::from) } pub fn
(host: &str, key: &str) -> ComfyResult<Config> { let path = config_path(); fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics let mut file = File::open(path)?; let body = serde_json::to_string(&Config { host: host.to_string(), key: key.to_string() })?; serde_json::from_str(&body) .map_err(ComfyError::from) }
write_config
identifier_name
buddy.rs
//! An implementation of a buddy allocator. use core::ptr; use core::mem; use core::cmp; use intrusive::link::Link; use intrusive::list::{List, Node}; use Allocator; pub type FreeBlock = PhantomNode; pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>; #[allow(dead_code)] pub struct Buddy<'a> { min_block_size: usize, min_block_order: u32, max_order: u32, free_lists: &'a mut [FreeList] } impl<'a> Buddy<'a> { pub fn new(min_block_size: usize, max_order: u32, free_lists: &'a mut [FreeList]) -> Self { assert!(min_block_size >= ::core::mem::size_of::<FreeBlock>()); Buddy { min_block_size: min_block_size, min_block_order: Buddy::log2(min_block_size) as u32, max_order: max_order, free_lists: free_lists, } } #[allow(exceeding_bitshifts)] pub fn next_power_of_two(mut num: usize) -> usize { if num == 0 { return 1; } num -= 1; num |= num >> 1; num |= num >> 2; num |= num >> 4; num |= num >> 8; num |= num >> 16; if mem::size_of::<usize>() == mem::size_of::<u64>() { num |= num >> 32; } num + 1 } pub fn log2(mut num: usize) -> usize { let mut res = 0; loop { num >>= 1; if num == 0 { break; } res += 1; } res } /// Add a block of max order pub unsafe fn add_block(&mut self, start: *mut u8) { let order = self.max_order; self.add_block_order(order, start); } unsafe fn add_block_order(&mut self, order: u32, start: *mut u8) { let link = ptr::Unique::new(start as *mut FreeBlock); self.free_lists[order as usize].push_front(link); } unsafe fn split_block(&mut self, block: *mut u8, mut order: u32, target_order: u32) { while order > target_order { order -= 1; let buddy_offset = self.get_size_from_order(order); let buddy_ptr = block.offset(buddy_offset as isize); self.add_block_order(order, buddy_ptr); } } unsafe fn find_and_pop_buddy(&mut self, ptr: *mut u8, order: u32) -> *mut u8 { // Max order blocks are not merged if order == self.max_order { return ptr::null_mut(); } let size = self.get_size_from_order(order); let buddy_ptr = (ptr as usize ^ size) as *mut u8; let mut cursor = self.free_lists[order as usize].cursor(); let mut found = false; loop { match cursor.next_peek() { None => break, Some(blk) => { if blk as *const FreeBlock as *const u8 == buddy_ptr
} } cursor.next(); } if found { cursor.remove(); return buddy_ptr } ptr::null_mut() } fn get_order_from_size(&self, mut size: usize, _align: usize) -> u32 { size = Buddy::next_power_of_two(size); size = cmp::max(size, self.min_block_size); Buddy::log2(size) as u32 - self.min_block_order } fn get_size_from_order(&self, order: u32) -> usize { self.min_block_size * 2usize.pow(order) } } impl<'a> Allocator for Buddy<'a> { unsafe fn allocate(&mut self, size: usize, align: usize) -> *mut u8 { let order = self.get_order_from_size(size, align); if order > self.max_order { return ptr::null_mut(); } for i in order..(self.max_order + 1) { let mut tmp = self.free_lists[i as usize].pop_front(); if let Some(block) = tmp.as_mut() { let ptr = block.get_mut() as *mut FreeBlock as *mut u8; if i > order { self.split_block(ptr, i, order); } return ptr } } ptr::null_mut() } unsafe fn deallocate(&mut self, mut ptr: *mut u8, old_size: usize, align: usize) { let mut order = self.get_order_from_size(old_size, align); loop { let buddy = self.find_and_pop_buddy(ptr, order); if buddy == ptr::null_mut() { break; } ptr = cmp::min(ptr, buddy); order += 1; } self.add_block_order(order, ptr); } } pub struct PhantomNode { prev: Link<PhantomNode>, next: Link<PhantomNode>, } impl Node for PhantomNode { fn prev(&self) -> &Link<PhantomNode> { &self.prev } fn next(&self) -> &Link<PhantomNode> { &self.next } fn prev_mut(&mut self) -> &mut Link<PhantomNode> { &mut self.prev } fn next_mut(&mut self) -> &mut Link<PhantomNode> { &mut self.next } } #[cfg(test)] mod test { use core::mem; use core::ptr; use Allocator; use super::{Buddy, FreeList}; const HEAP_ALIGN: usize = 4096; const HEAP_SIZE: usize = 4096; // HEAP_ORDER = 5 & MIN_BLOCK_SIZE = 32 => max alloc 1024 const HEAP_ORDER: u32 = 5; const MIN_BLOCK_SIZE: usize = 32; extern "C" { fn memalign(alignment: usize, size: usize) -> *mut u8; fn free(ptr: *mut u8); } #[test] fn test_buddy_next_power_of_two() { assert_eq!(Buddy::next_power_of_two(0), 1); assert_eq!(Buddy::next_power_of_two(2), 2); assert_eq!(Buddy::next_power_of_two(3), 4); assert_eq!(Buddy::next_power_of_two(5678), 8192); assert_eq!(Buddy::next_power_of_two(8192), 8192); } #[test] fn test_buddy_log2() { assert_eq!(Buddy::log2(0), 0); assert_eq!(Buddy::log2(1), 0); assert_eq!(Buddy::log2(2), 1); assert_eq!(Buddy::log2(4), 2); assert_eq!(Buddy::log2(8), 3); assert_eq!(Buddy::log2(16), 4); assert_eq!(Buddy::log2(0x87654321), 31); } #[test] fn test_buddy_alloc_dealloc() { unsafe { let heap = memalign(HEAP_ALIGN, HEAP_SIZE); let mut free_lists: [_; (HEAP_ORDER + 1) as usize]; free_lists = mem::uninitialized(); for i in 0..(HEAP_ORDER + 1) { free_lists[i as usize] = FreeList::new(); } let max_size = MIN_BLOCK_SIZE * 2usize.pow(HEAP_ORDER); let mut alloc = Buddy::new(MIN_BLOCK_SIZE, HEAP_ORDER, &mut free_lists[..]); // Heap is 4Kb in 4 * 1Kb alloc.add_block(heap.offset(0)); alloc.add_block(heap.offset(1024)); alloc.add_block(heap.offset(2048)); alloc.add_block(heap.offset(3072)); // Allocation is too big assert_eq!(alloc.allocate(max_size + 1, 1), ptr::null_mut()); { let max_blk = alloc.allocate(max_size, 1); let last_blk_offset = ((HEAP_SIZE / max_size) - 1) * max_size; // Due to Buddy::new using push front, the first allocated block // is gonna be the last pushed assert_eq!(max_blk, heap.offset(last_blk_offset as isize)); alloc.deallocate(max_blk, max_size, 1); } let blk_32_1 = alloc.allocate(32, 1); let blk_32_2 = alloc.allocate(32, 1); assert_eq!(blk_32_1.offset(32), blk_32_2); let blk_64_1 = alloc.allocate(64, 1); assert_eq!(blk_32_1.offset(64), blk_64_1); alloc.deallocate(blk_32_1, 32, 1); alloc.deallocate(blk_32_2, 32, 1); let blk_32_1_1 = alloc.allocate(32, 1); let blk_32_2_1 = alloc.allocate(32, 1); assert_eq!(blk_32_1_1, blk_32_1); assert_eq!(blk_32_2_1, blk_32_2); alloc.deallocate(blk_32_2_1, 32, 1); alloc.deallocate(blk_32_1_1, 32, 1); let blk_64_2 = alloc.allocate(64, 1); assert_eq!(blk_64_2, blk_32_1); let blk_128 = alloc.allocate(128, 1); assert_eq!(blk_128, blk_64_1.offset(64)); alloc.deallocate(blk_64_1, 64, 1); alloc.deallocate(blk_64_2, 64, 1); alloc.deallocate(blk_128, 128, 1); free(heap); } } }
{ found = true; break; }
conditional_block
buddy.rs
//! An implementation of a buddy allocator. use core::ptr; use core::mem; use core::cmp; use intrusive::link::Link; use intrusive::list::{List, Node}; use Allocator; pub type FreeBlock = PhantomNode; pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>; #[allow(dead_code)] pub struct Buddy<'a> { min_block_size: usize, min_block_order: u32, max_order: u32, free_lists: &'a mut [FreeList] } impl<'a> Buddy<'a> { pub fn new(min_block_size: usize, max_order: u32, free_lists: &'a mut [FreeList]) -> Self { assert!(min_block_size >= ::core::mem::size_of::<FreeBlock>()); Buddy { min_block_size: min_block_size, min_block_order: Buddy::log2(min_block_size) as u32, max_order: max_order, free_lists: free_lists, }
} #[allow(exceeding_bitshifts)] pub fn next_power_of_two(mut num: usize) -> usize { if num == 0 { return 1; } num -= 1; num |= num >> 1; num |= num >> 2; num |= num >> 4; num |= num >> 8; num |= num >> 16; if mem::size_of::<usize>() == mem::size_of::<u64>() { num |= num >> 32; } num + 1 } pub fn log2(mut num: usize) -> usize { let mut res = 0; loop { num >>= 1; if num == 0 { break; } res += 1; } res } /// Add a block of max order pub unsafe fn add_block(&mut self, start: *mut u8) { let order = self.max_order; self.add_block_order(order, start); } unsafe fn add_block_order(&mut self, order: u32, start: *mut u8) { let link = ptr::Unique::new(start as *mut FreeBlock); self.free_lists[order as usize].push_front(link); } unsafe fn split_block(&mut self, block: *mut u8, mut order: u32, target_order: u32) { while order > target_order { order -= 1; let buddy_offset = self.get_size_from_order(order); let buddy_ptr = block.offset(buddy_offset as isize); self.add_block_order(order, buddy_ptr); } } unsafe fn find_and_pop_buddy(&mut self, ptr: *mut u8, order: u32) -> *mut u8 { // Max order blocks are not merged if order == self.max_order { return ptr::null_mut(); } let size = self.get_size_from_order(order); let buddy_ptr = (ptr as usize ^ size) as *mut u8; let mut cursor = self.free_lists[order as usize].cursor(); let mut found = false; loop { match cursor.next_peek() { None => break, Some(blk) => { if blk as *const FreeBlock as *const u8 == buddy_ptr { found = true; break; } } } cursor.next(); } if found { cursor.remove(); return buddy_ptr } ptr::null_mut() } fn get_order_from_size(&self, mut size: usize, _align: usize) -> u32 { size = Buddy::next_power_of_two(size); size = cmp::max(size, self.min_block_size); Buddy::log2(size) as u32 - self.min_block_order } fn get_size_from_order(&self, order: u32) -> usize { self.min_block_size * 2usize.pow(order) } } impl<'a> Allocator for Buddy<'a> { unsafe fn allocate(&mut self, size: usize, align: usize) -> *mut u8 { let order = self.get_order_from_size(size, align); if order > self.max_order { return ptr::null_mut(); } for i in order..(self.max_order + 1) { let mut tmp = self.free_lists[i as usize].pop_front(); if let Some(block) = tmp.as_mut() { let ptr = block.get_mut() as *mut FreeBlock as *mut u8; if i > order { self.split_block(ptr, i, order); } return ptr } } ptr::null_mut() } unsafe fn deallocate(&mut self, mut ptr: *mut u8, old_size: usize, align: usize) { let mut order = self.get_order_from_size(old_size, align); loop { let buddy = self.find_and_pop_buddy(ptr, order); if buddy == ptr::null_mut() { break; } ptr = cmp::min(ptr, buddy); order += 1; } self.add_block_order(order, ptr); } } pub struct PhantomNode { prev: Link<PhantomNode>, next: Link<PhantomNode>, } impl Node for PhantomNode { fn prev(&self) -> &Link<PhantomNode> { &self.prev } fn next(&self) -> &Link<PhantomNode> { &self.next } fn prev_mut(&mut self) -> &mut Link<PhantomNode> { &mut self.prev } fn next_mut(&mut self) -> &mut Link<PhantomNode> { &mut self.next } } #[cfg(test)] mod test { use core::mem; use core::ptr; use Allocator; use super::{Buddy, FreeList}; const HEAP_ALIGN: usize = 4096; const HEAP_SIZE: usize = 4096; // HEAP_ORDER = 5 & MIN_BLOCK_SIZE = 32 => max alloc 1024 const HEAP_ORDER: u32 = 5; const MIN_BLOCK_SIZE: usize = 32; extern "C" { fn memalign(alignment: usize, size: usize) -> *mut u8; fn free(ptr: *mut u8); } #[test] fn test_buddy_next_power_of_two() { assert_eq!(Buddy::next_power_of_two(0), 1); assert_eq!(Buddy::next_power_of_two(2), 2); assert_eq!(Buddy::next_power_of_two(3), 4); assert_eq!(Buddy::next_power_of_two(5678), 8192); assert_eq!(Buddy::next_power_of_two(8192), 8192); } #[test] fn test_buddy_log2() { assert_eq!(Buddy::log2(0), 0); assert_eq!(Buddy::log2(1), 0); assert_eq!(Buddy::log2(2), 1); assert_eq!(Buddy::log2(4), 2); assert_eq!(Buddy::log2(8), 3); assert_eq!(Buddy::log2(16), 4); assert_eq!(Buddy::log2(0x87654321), 31); } #[test] fn test_buddy_alloc_dealloc() { unsafe { let heap = memalign(HEAP_ALIGN, HEAP_SIZE); let mut free_lists: [_; (HEAP_ORDER + 1) as usize]; free_lists = mem::uninitialized(); for i in 0..(HEAP_ORDER + 1) { free_lists[i as usize] = FreeList::new(); } let max_size = MIN_BLOCK_SIZE * 2usize.pow(HEAP_ORDER); let mut alloc = Buddy::new(MIN_BLOCK_SIZE, HEAP_ORDER, &mut free_lists[..]); // Heap is 4Kb in 4 * 1Kb alloc.add_block(heap.offset(0)); alloc.add_block(heap.offset(1024)); alloc.add_block(heap.offset(2048)); alloc.add_block(heap.offset(3072)); // Allocation is too big assert_eq!(alloc.allocate(max_size + 1, 1), ptr::null_mut()); { let max_blk = alloc.allocate(max_size, 1); let last_blk_offset = ((HEAP_SIZE / max_size) - 1) * max_size; // Due to Buddy::new using push front, the first allocated block // is gonna be the last pushed assert_eq!(max_blk, heap.offset(last_blk_offset as isize)); alloc.deallocate(max_blk, max_size, 1); } let blk_32_1 = alloc.allocate(32, 1); let blk_32_2 = alloc.allocate(32, 1); assert_eq!(blk_32_1.offset(32), blk_32_2); let blk_64_1 = alloc.allocate(64, 1); assert_eq!(blk_32_1.offset(64), blk_64_1); alloc.deallocate(blk_32_1, 32, 1); alloc.deallocate(blk_32_2, 32, 1); let blk_32_1_1 = alloc.allocate(32, 1); let blk_32_2_1 = alloc.allocate(32, 1); assert_eq!(blk_32_1_1, blk_32_1); assert_eq!(blk_32_2_1, blk_32_2); alloc.deallocate(blk_32_2_1, 32, 1); alloc.deallocate(blk_32_1_1, 32, 1); let blk_64_2 = alloc.allocate(64, 1); assert_eq!(blk_64_2, blk_32_1); let blk_128 = alloc.allocate(128, 1); assert_eq!(blk_128, blk_64_1.offset(64)); alloc.deallocate(blk_64_1, 64, 1); alloc.deallocate(blk_64_2, 64, 1); alloc.deallocate(blk_128, 128, 1); free(heap); } } }
random_line_split
buddy.rs
//! An implementation of a buddy allocator. use core::ptr; use core::mem; use core::cmp; use intrusive::link::Link; use intrusive::list::{List, Node}; use Allocator; pub type FreeBlock = PhantomNode; pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>; #[allow(dead_code)] pub struct Buddy<'a> { min_block_size: usize, min_block_order: u32, max_order: u32, free_lists: &'a mut [FreeList] } impl<'a> Buddy<'a> { pub fn new(min_block_size: usize, max_order: u32, free_lists: &'a mut [FreeList]) -> Self
#[allow(exceeding_bitshifts)] pub fn next_power_of_two(mut num: usize) -> usize { if num == 0 { return 1; } num -= 1; num |= num >> 1; num |= num >> 2; num |= num >> 4; num |= num >> 8; num |= num >> 16; if mem::size_of::<usize>() == mem::size_of::<u64>() { num |= num >> 32; } num + 1 } pub fn log2(mut num: usize) -> usize { let mut res = 0; loop { num >>= 1; if num == 0 { break; } res += 1; } res } /// Add a block of max order pub unsafe fn add_block(&mut self, start: *mut u8) { let order = self.max_order; self.add_block_order(order, start); } unsafe fn add_block_order(&mut self, order: u32, start: *mut u8) { let link = ptr::Unique::new(start as *mut FreeBlock); self.free_lists[order as usize].push_front(link); } unsafe fn split_block(&mut self, block: *mut u8, mut order: u32, target_order: u32) { while order > target_order { order -= 1; let buddy_offset = self.get_size_from_order(order); let buddy_ptr = block.offset(buddy_offset as isize); self.add_block_order(order, buddy_ptr); } } unsafe fn find_and_pop_buddy(&mut self, ptr: *mut u8, order: u32) -> *mut u8 { // Max order blocks are not merged if order == self.max_order { return ptr::null_mut(); } let size = self.get_size_from_order(order); let buddy_ptr = (ptr as usize ^ size) as *mut u8; let mut cursor = self.free_lists[order as usize].cursor(); let mut found = false; loop { match cursor.next_peek() { None => break, Some(blk) => { if blk as *const FreeBlock as *const u8 == buddy_ptr { found = true; break; } } } cursor.next(); } if found { cursor.remove(); return buddy_ptr } ptr::null_mut() } fn get_order_from_size(&self, mut size: usize, _align: usize) -> u32 { size = Buddy::next_power_of_two(size); size = cmp::max(size, self.min_block_size); Buddy::log2(size) as u32 - self.min_block_order } fn get_size_from_order(&self, order: u32) -> usize { self.min_block_size * 2usize.pow(order) } } impl<'a> Allocator for Buddy<'a> { unsafe fn allocate(&mut self, size: usize, align: usize) -> *mut u8 { let order = self.get_order_from_size(size, align); if order > self.max_order { return ptr::null_mut(); } for i in order..(self.max_order + 1) { let mut tmp = self.free_lists[i as usize].pop_front(); if let Some(block) = tmp.as_mut() { let ptr = block.get_mut() as *mut FreeBlock as *mut u8; if i > order { self.split_block(ptr, i, order); } return ptr } } ptr::null_mut() } unsafe fn deallocate(&mut self, mut ptr: *mut u8, old_size: usize, align: usize) { let mut order = self.get_order_from_size(old_size, align); loop { let buddy = self.find_and_pop_buddy(ptr, order); if buddy == ptr::null_mut() { break; } ptr = cmp::min(ptr, buddy); order += 1; } self.add_block_order(order, ptr); } } pub struct PhantomNode { prev: Link<PhantomNode>, next: Link<PhantomNode>, } impl Node for PhantomNode { fn prev(&self) -> &Link<PhantomNode> { &self.prev } fn next(&self) -> &Link<PhantomNode> { &self.next } fn prev_mut(&mut self) -> &mut Link<PhantomNode> { &mut self.prev } fn next_mut(&mut self) -> &mut Link<PhantomNode> { &mut self.next } } #[cfg(test)] mod test { use core::mem; use core::ptr; use Allocator; use super::{Buddy, FreeList}; const HEAP_ALIGN: usize = 4096; const HEAP_SIZE: usize = 4096; // HEAP_ORDER = 5 & MIN_BLOCK_SIZE = 32 => max alloc 1024 const HEAP_ORDER: u32 = 5; const MIN_BLOCK_SIZE: usize = 32; extern "C" { fn memalign(alignment: usize, size: usize) -> *mut u8; fn free(ptr: *mut u8); } #[test] fn test_buddy_next_power_of_two() { assert_eq!(Buddy::next_power_of_two(0), 1); assert_eq!(Buddy::next_power_of_two(2), 2); assert_eq!(Buddy::next_power_of_two(3), 4); assert_eq!(Buddy::next_power_of_two(5678), 8192); assert_eq!(Buddy::next_power_of_two(8192), 8192); } #[test] fn test_buddy_log2() { assert_eq!(Buddy::log2(0), 0); assert_eq!(Buddy::log2(1), 0); assert_eq!(Buddy::log2(2), 1); assert_eq!(Buddy::log2(4), 2); assert_eq!(Buddy::log2(8), 3); assert_eq!(Buddy::log2(16), 4); assert_eq!(Buddy::log2(0x87654321), 31); } #[test] fn test_buddy_alloc_dealloc() { unsafe { let heap = memalign(HEAP_ALIGN, HEAP_SIZE); let mut free_lists: [_; (HEAP_ORDER + 1) as usize]; free_lists = mem::uninitialized(); for i in 0..(HEAP_ORDER + 1) { free_lists[i as usize] = FreeList::new(); } let max_size = MIN_BLOCK_SIZE * 2usize.pow(HEAP_ORDER); let mut alloc = Buddy::new(MIN_BLOCK_SIZE, HEAP_ORDER, &mut free_lists[..]); // Heap is 4Kb in 4 * 1Kb alloc.add_block(heap.offset(0)); alloc.add_block(heap.offset(1024)); alloc.add_block(heap.offset(2048)); alloc.add_block(heap.offset(3072)); // Allocation is too big assert_eq!(alloc.allocate(max_size + 1, 1), ptr::null_mut()); { let max_blk = alloc.allocate(max_size, 1); let last_blk_offset = ((HEAP_SIZE / max_size) - 1) * max_size; // Due to Buddy::new using push front, the first allocated block // is gonna be the last pushed assert_eq!(max_blk, heap.offset(last_blk_offset as isize)); alloc.deallocate(max_blk, max_size, 1); } let blk_32_1 = alloc.allocate(32, 1); let blk_32_2 = alloc.allocate(32, 1); assert_eq!(blk_32_1.offset(32), blk_32_2); let blk_64_1 = alloc.allocate(64, 1); assert_eq!(blk_32_1.offset(64), blk_64_1); alloc.deallocate(blk_32_1, 32, 1); alloc.deallocate(blk_32_2, 32, 1); let blk_32_1_1 = alloc.allocate(32, 1); let blk_32_2_1 = alloc.allocate(32, 1); assert_eq!(blk_32_1_1, blk_32_1); assert_eq!(blk_32_2_1, blk_32_2); alloc.deallocate(blk_32_2_1, 32, 1); alloc.deallocate(blk_32_1_1, 32, 1); let blk_64_2 = alloc.allocate(64, 1); assert_eq!(blk_64_2, blk_32_1); let blk_128 = alloc.allocate(128, 1); assert_eq!(blk_128, blk_64_1.offset(64)); alloc.deallocate(blk_64_1, 64, 1); alloc.deallocate(blk_64_2, 64, 1); alloc.deallocate(blk_128, 128, 1); free(heap); } } }
{ assert!(min_block_size >= ::core::mem::size_of::<FreeBlock>()); Buddy { min_block_size: min_block_size, min_block_order: Buddy::log2(min_block_size) as u32, max_order: max_order, free_lists: free_lists, } }
identifier_body
buddy.rs
//! An implementation of a buddy allocator. use core::ptr; use core::mem; use core::cmp; use intrusive::link::Link; use intrusive::list::{List, Node}; use Allocator; pub type FreeBlock = PhantomNode; pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>; #[allow(dead_code)] pub struct Buddy<'a> { min_block_size: usize, min_block_order: u32, max_order: u32, free_lists: &'a mut [FreeList] } impl<'a> Buddy<'a> { pub fn new(min_block_size: usize, max_order: u32, free_lists: &'a mut [FreeList]) -> Self { assert!(min_block_size >= ::core::mem::size_of::<FreeBlock>()); Buddy { min_block_size: min_block_size, min_block_order: Buddy::log2(min_block_size) as u32, max_order: max_order, free_lists: free_lists, } } #[allow(exceeding_bitshifts)] pub fn next_power_of_two(mut num: usize) -> usize { if num == 0 { return 1; } num -= 1; num |= num >> 1; num |= num >> 2; num |= num >> 4; num |= num >> 8; num |= num >> 16; if mem::size_of::<usize>() == mem::size_of::<u64>() { num |= num >> 32; } num + 1 } pub fn log2(mut num: usize) -> usize { let mut res = 0; loop { num >>= 1; if num == 0 { break; } res += 1; } res } /// Add a block of max order pub unsafe fn add_block(&mut self, start: *mut u8) { let order = self.max_order; self.add_block_order(order, start); } unsafe fn
(&mut self, order: u32, start: *mut u8) { let link = ptr::Unique::new(start as *mut FreeBlock); self.free_lists[order as usize].push_front(link); } unsafe fn split_block(&mut self, block: *mut u8, mut order: u32, target_order: u32) { while order > target_order { order -= 1; let buddy_offset = self.get_size_from_order(order); let buddy_ptr = block.offset(buddy_offset as isize); self.add_block_order(order, buddy_ptr); } } unsafe fn find_and_pop_buddy(&mut self, ptr: *mut u8, order: u32) -> *mut u8 { // Max order blocks are not merged if order == self.max_order { return ptr::null_mut(); } let size = self.get_size_from_order(order); let buddy_ptr = (ptr as usize ^ size) as *mut u8; let mut cursor = self.free_lists[order as usize].cursor(); let mut found = false; loop { match cursor.next_peek() { None => break, Some(blk) => { if blk as *const FreeBlock as *const u8 == buddy_ptr { found = true; break; } } } cursor.next(); } if found { cursor.remove(); return buddy_ptr } ptr::null_mut() } fn get_order_from_size(&self, mut size: usize, _align: usize) -> u32 { size = Buddy::next_power_of_two(size); size = cmp::max(size, self.min_block_size); Buddy::log2(size) as u32 - self.min_block_order } fn get_size_from_order(&self, order: u32) -> usize { self.min_block_size * 2usize.pow(order) } } impl<'a> Allocator for Buddy<'a> { unsafe fn allocate(&mut self, size: usize, align: usize) -> *mut u8 { let order = self.get_order_from_size(size, align); if order > self.max_order { return ptr::null_mut(); } for i in order..(self.max_order + 1) { let mut tmp = self.free_lists[i as usize].pop_front(); if let Some(block) = tmp.as_mut() { let ptr = block.get_mut() as *mut FreeBlock as *mut u8; if i > order { self.split_block(ptr, i, order); } return ptr } } ptr::null_mut() } unsafe fn deallocate(&mut self, mut ptr: *mut u8, old_size: usize, align: usize) { let mut order = self.get_order_from_size(old_size, align); loop { let buddy = self.find_and_pop_buddy(ptr, order); if buddy == ptr::null_mut() { break; } ptr = cmp::min(ptr, buddy); order += 1; } self.add_block_order(order, ptr); } } pub struct PhantomNode { prev: Link<PhantomNode>, next: Link<PhantomNode>, } impl Node for PhantomNode { fn prev(&self) -> &Link<PhantomNode> { &self.prev } fn next(&self) -> &Link<PhantomNode> { &self.next } fn prev_mut(&mut self) -> &mut Link<PhantomNode> { &mut self.prev } fn next_mut(&mut self) -> &mut Link<PhantomNode> { &mut self.next } } #[cfg(test)] mod test { use core::mem; use core::ptr; use Allocator; use super::{Buddy, FreeList}; const HEAP_ALIGN: usize = 4096; const HEAP_SIZE: usize = 4096; // HEAP_ORDER = 5 & MIN_BLOCK_SIZE = 32 => max alloc 1024 const HEAP_ORDER: u32 = 5; const MIN_BLOCK_SIZE: usize = 32; extern "C" { fn memalign(alignment: usize, size: usize) -> *mut u8; fn free(ptr: *mut u8); } #[test] fn test_buddy_next_power_of_two() { assert_eq!(Buddy::next_power_of_two(0), 1); assert_eq!(Buddy::next_power_of_two(2), 2); assert_eq!(Buddy::next_power_of_two(3), 4); assert_eq!(Buddy::next_power_of_two(5678), 8192); assert_eq!(Buddy::next_power_of_two(8192), 8192); } #[test] fn test_buddy_log2() { assert_eq!(Buddy::log2(0), 0); assert_eq!(Buddy::log2(1), 0); assert_eq!(Buddy::log2(2), 1); assert_eq!(Buddy::log2(4), 2); assert_eq!(Buddy::log2(8), 3); assert_eq!(Buddy::log2(16), 4); assert_eq!(Buddy::log2(0x87654321), 31); } #[test] fn test_buddy_alloc_dealloc() { unsafe { let heap = memalign(HEAP_ALIGN, HEAP_SIZE); let mut free_lists: [_; (HEAP_ORDER + 1) as usize]; free_lists = mem::uninitialized(); for i in 0..(HEAP_ORDER + 1) { free_lists[i as usize] = FreeList::new(); } let max_size = MIN_BLOCK_SIZE * 2usize.pow(HEAP_ORDER); let mut alloc = Buddy::new(MIN_BLOCK_SIZE, HEAP_ORDER, &mut free_lists[..]); // Heap is 4Kb in 4 * 1Kb alloc.add_block(heap.offset(0)); alloc.add_block(heap.offset(1024)); alloc.add_block(heap.offset(2048)); alloc.add_block(heap.offset(3072)); // Allocation is too big assert_eq!(alloc.allocate(max_size + 1, 1), ptr::null_mut()); { let max_blk = alloc.allocate(max_size, 1); let last_blk_offset = ((HEAP_SIZE / max_size) - 1) * max_size; // Due to Buddy::new using push front, the first allocated block // is gonna be the last pushed assert_eq!(max_blk, heap.offset(last_blk_offset as isize)); alloc.deallocate(max_blk, max_size, 1); } let blk_32_1 = alloc.allocate(32, 1); let blk_32_2 = alloc.allocate(32, 1); assert_eq!(blk_32_1.offset(32), blk_32_2); let blk_64_1 = alloc.allocate(64, 1); assert_eq!(blk_32_1.offset(64), blk_64_1); alloc.deallocate(blk_32_1, 32, 1); alloc.deallocate(blk_32_2, 32, 1); let blk_32_1_1 = alloc.allocate(32, 1); let blk_32_2_1 = alloc.allocate(32, 1); assert_eq!(blk_32_1_1, blk_32_1); assert_eq!(blk_32_2_1, blk_32_2); alloc.deallocate(blk_32_2_1, 32, 1); alloc.deallocate(blk_32_1_1, 32, 1); let blk_64_2 = alloc.allocate(64, 1); assert_eq!(blk_64_2, blk_32_1); let blk_128 = alloc.allocate(128, 1); assert_eq!(blk_128, blk_64_1.offset(64)); alloc.deallocate(blk_64_1, 64, 1); alloc.deallocate(blk_64_2, 64, 1); alloc.deallocate(blk_128, 128, 1); free(heap); } } }
add_block_order
identifier_name
mod.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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. use middle::typing::inference::*; use middle::typing::bottom_up_unit::*; use middle::typing::top_down_unit::*; use middle::typing::bottom_up_tuple::*; // use middle::typing::printer::*; use middle::typing::ast::*; use middle::typing::recursive_type::*; use monad::partial::Partial; pub mod ast; mod inference; mod bottom_up_tuple;
pub fn type_inference(cx: &ExtCtxt, agrammar: AGrammar) -> Partial<Grammar> { let mut grammar = Grammar { name: agrammar.name, rules: HashMap::with_capacity(agrammar.rules.len()), rust_functions: agrammar.rust_functions, rust_items: agrammar.rust_items, attributes: agrammar.attributes }; InferenceEngine::infer(&mut grammar, agrammar.rules); bottom_up_unit_inference(&mut grammar); top_down_unit_inference(&mut grammar); // print_annotated_rules(&grammar); recursive_type_analysis(cx, grammar) .and_then(|grammar| bottom_up_tuple_inference(grammar)) }
mod bottom_up_unit; mod top_down_unit; mod recursive_type; // mod printer;
random_line_split
mod.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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. use middle::typing::inference::*; use middle::typing::bottom_up_unit::*; use middle::typing::top_down_unit::*; use middle::typing::bottom_up_tuple::*; // use middle::typing::printer::*; use middle::typing::ast::*; use middle::typing::recursive_type::*; use monad::partial::Partial; pub mod ast; mod inference; mod bottom_up_tuple; mod bottom_up_unit; mod top_down_unit; mod recursive_type; // mod printer; pub fn type_inference(cx: &ExtCtxt, agrammar: AGrammar) -> Partial<Grammar>
{ let mut grammar = Grammar { name: agrammar.name, rules: HashMap::with_capacity(agrammar.rules.len()), rust_functions: agrammar.rust_functions, rust_items: agrammar.rust_items, attributes: agrammar.attributes }; InferenceEngine::infer(&mut grammar, agrammar.rules); bottom_up_unit_inference(&mut grammar); top_down_unit_inference(&mut grammar); // print_annotated_rules(&grammar); recursive_type_analysis(cx, grammar) .and_then(|grammar| bottom_up_tuple_inference(grammar)) }
identifier_body
mod.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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. use middle::typing::inference::*; use middle::typing::bottom_up_unit::*; use middle::typing::top_down_unit::*; use middle::typing::bottom_up_tuple::*; // use middle::typing::printer::*; use middle::typing::ast::*; use middle::typing::recursive_type::*; use monad::partial::Partial; pub mod ast; mod inference; mod bottom_up_tuple; mod bottom_up_unit; mod top_down_unit; mod recursive_type; // mod printer; pub fn
(cx: &ExtCtxt, agrammar: AGrammar) -> Partial<Grammar> { let mut grammar = Grammar { name: agrammar.name, rules: HashMap::with_capacity(agrammar.rules.len()), rust_functions: agrammar.rust_functions, rust_items: agrammar.rust_items, attributes: agrammar.attributes }; InferenceEngine::infer(&mut grammar, agrammar.rules); bottom_up_unit_inference(&mut grammar); top_down_unit_inference(&mut grammar); // print_annotated_rules(&grammar); recursive_type_analysis(cx, grammar) .and_then(|grammar| bottom_up_tuple_inference(grammar)) }
type_inference
identifier_name
rapidgator.py
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para rapidgator # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core import scrapertools from core import logger from core import config def test_video_exists( page_url ): return True,"" def
( page_url , premium = False , user="" , password="", video_password="" ): logger.info("[rapidgator.py] get_video_url(page_url='%s')" % page_url) video_urls = [] return video_urls # Encuentra vídeos del servidor en el texto pasado def find_videos(data): encontrados = set() devuelve = [] #http://rapidgator.net/file/10126555/ElBatallon-byjerobien.avi.html #http://rapidgator.net/file/15437757 patronvideos = '(rapidgator.net/file/\d+)' logger.info("[rapidgator.py] find_videos #"+patronvideos+"#") matches = re.compile(patronvideos,re.DOTALL).findall(data) for match in matches: titulo = "[rapidgator]" url = "http://"+match if url not in encontrados: logger.info(" url="+url) devuelve.append( [ titulo , url , 'rapidgator' ] ) encontrados.add(url) else: logger.info(" url duplicada="+url) return devuelve
get_video_url
identifier_name
rapidgator.py
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para rapidgator # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core import scrapertools from core import logger from core import config def test_video_exists( page_url ): return True,""
return video_urls # Encuentra vídeos del servidor en el texto pasado def find_videos(data): encontrados = set() devuelve = [] #http://rapidgator.net/file/10126555/ElBatallon-byjerobien.avi.html #http://rapidgator.net/file/15437757 patronvideos = '(rapidgator.net/file/\d+)' logger.info("[rapidgator.py] find_videos #"+patronvideos+"#") matches = re.compile(patronvideos,re.DOTALL).findall(data) for match in matches: titulo = "[rapidgator]" url = "http://"+match if url not in encontrados: logger.info(" url="+url) devuelve.append( [ titulo , url , 'rapidgator' ] ) encontrados.add(url) else: logger.info(" url duplicada="+url) return devuelve
def get_video_url( page_url , premium = False , user="" , password="", video_password="" ): logger.info("[rapidgator.py] get_video_url(page_url='%s')" % page_url) video_urls = []
random_line_split
rapidgator.py
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para rapidgator # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core import scrapertools from core import logger from core import config def test_video_exists( page_url ): return True,"" def get_video_url( page_url , premium = False , user="" , password="", video_password="" ):
# Encuentra vídeos del servidor en el texto pasado def find_videos(data): encontrados = set() devuelve = [] #http://rapidgator.net/file/10126555/ElBatallon-byjerobien.avi.html #http://rapidgator.net/file/15437757 patronvideos = '(rapidgator.net/file/\d+)' logger.info("[rapidgator.py] find_videos #"+patronvideos+"#") matches = re.compile(patronvideos,re.DOTALL).findall(data) for match in matches: titulo = "[rapidgator]" url = "http://"+match if url not in encontrados: logger.info(" url="+url) devuelve.append( [ titulo , url , 'rapidgator' ] ) encontrados.add(url) else: logger.info(" url duplicada="+url) return devuelve
logger.info("[rapidgator.py] get_video_url(page_url='%s')" % page_url) video_urls = [] return video_urls
identifier_body
rapidgator.py
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para rapidgator # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core import scrapertools from core import logger from core import config def test_video_exists( page_url ): return True,"" def get_video_url( page_url , premium = False , user="" , password="", video_password="" ): logger.info("[rapidgator.py] get_video_url(page_url='%s')" % page_url) video_urls = [] return video_urls # Encuentra vídeos del servidor en el texto pasado def find_videos(data): encontrados = set() devuelve = [] #http://rapidgator.net/file/10126555/ElBatallon-byjerobien.avi.html #http://rapidgator.net/file/15437757 patronvideos = '(rapidgator.net/file/\d+)' logger.info("[rapidgator.py] find_videos #"+patronvideos+"#") matches = re.compile(patronvideos,re.DOTALL).findall(data) for match in matches: titulo = "[rapidgator]" url = "http://"+match if url not in encontrados: l
else: logger.info(" url duplicada="+url) return devuelve
ogger.info(" url="+url) devuelve.append( [ titulo , url , 'rapidgator' ] ) encontrados.add(url)
conditional_block
focusPointsContainer.tsx
import * as React from 'react'; import { connect } from 'react-redux'; import * as _ from 'underscore'; import { EditorState, ContentState } from 'draft-js' import { TextEditor } from '../../../Shared/index'; import * as questionActions from '../../actions/questions'; import { hashToCollection, SortableList, } from '../../../Shared/index' export class FocusPointsContainer extends React.Component { constructor(props) { super(props); this.deleteFocusPoint = this.deleteFocusPoint.bind(this); this.sortCallback = this.sortCallback.bind(this); this.updatefpOrder = this.updatefpOrder.bind(this); const question = this.props.questions.data[this.props.match.params.questionID] const focusPoints = this.getFocusPoints(question) this.state = { fpOrderedIds: null, focusPoints: focusPoints }; } getFocusPoints(question) { return question.focusPoints; } deleteFocusPoint(focusPointID) { const { focusPoints } = this.state if (confirm('⚠️ Are you sure you want to delete this? 😱')) { this.props.dispatch(questionActions.deleteFocusPoint(this.props.match.params.questionID, focusPointID)); delete focusPoints[focusPointID] this.setState({focusPoints: focusPoints}) } } deleteConceptResult(conceptResultKey, focusPointKey) { const { focusPoints } = this.state if (confirm('⚠️ Are you sure you want to delete this? 😱')) { const data = focusPoints[focusPointKey]; delete data.conceptResults[conceptResultKey]; this.props.dispatch(questionActions.submitEditedFocusPoint(this.props.match.params.questionID, data, focusPointKey)); } } // fPsortedByOrder() { const { focusPoints } = this.state if (this.state.fpOrderedIds) { const focusPointsCollection = hashToCollection(focusPoints) return this.state.fpOrderedIds.map(id => focusPointsCollection.find(fp => fp.key === id)) } else { return hashToCollection(focusPoints).sort((a, b) => a.order - b.order); } } saveFocusPointsAndFeedback = (key) => { const { actionFile } = this.state const { dispatch, match } = this.props const { params } = match const { questionID } = params const { focusPoints } = this.state const filteredFocusPoints = this.removeEmptyFocusPoints(focusPoints) let data = filteredFocusPoints[key] delete data.conceptResults.null; if (data.text === '') { delete filteredFocusPoints[key] dispatch(questionActions.deleteFocusPoint(questionID, key)); } else { dispatch(questionActions.submitEditedFocusPoint(questionID, data, key)); } this.setState({focusPoints: filteredFocusPoints}) } removeEmptyFocusPoints = (focusPoints) => { return _.mapObject(focusPoints, (val) => ( Object.assign({}, val, { text: val.text.split(/\|{3}(?!\|)/).filter(val => val !== '').join('|||') }) ) ); } addNewFocusPoint = (e, key) => { const { focusPoints } = this.state const className = `regex-${key}` const value = `${Array.from(document.getElementsByClassName(className)).map(i => i.value).filter(val => val !== '').join('|||')}|||`; focusPoints[key].text = value; this.setState({focusPoints: focusPoints}) } handleNameChange = (e, key) => { const { focusPoints } = this.state focusPoints[key].name = e.target.value this.setState({focusPoints: focusPoints}) } handleFocusPointChange = (e, key) => { const { focusPoints } = this.state const className = `regex-${key}` const value = `${Array.from(document.getElementsByClassName(className)).map(i => i.value).filter(val => val !== '').join('|||')}`; if (value === '') { if (!confirm("Deleting this regex will delete the whole incorrect sequence. Are you sure you want that?")) { return } } focusPoints[key].text = value; this.setState({focusPoints: focusPoints}) } handleFeedbackChange = (e, key) => { const { focusPoints } = this.state focusPoints[key].feedback = e this.setState({focusPoints: focusPoints}) } sortCallback(sortInfo) { const fpOrderedIds = sortInfo.map(item => item.key); this.setState({ fpOrderedIds, }); } updatefpOrder() { const {
sPointsList() { const components = this.fPsortedByOrder().map((fp) => { return ( <div className="card is-fullwidth has-bottom-margin" key={fp.key}> <header className="card-header"> <input className="regex-name" onChange={(e) => this.handleNameChange(e, fp.key)} placeholder="Name" type="text" value={fp.name || ''} /> </header> <header className="card-header"> <p className="card-header-title" style={{ display: 'inline-block', }}> {this.renderTextInputFields(fp.text, fp.key)} <button className="add-regex-button" onClick={(e) => this.addNewFocusPoint(e, fp.key)} type="button">+</button> </p> <p className="card-header-icon"> {fp.order} </p> </header> <div className="card-content"> <label className="label" htmlFor="feedback" style={{ marginTop: 10, }}>Feedback</label> <TextEditor ContentState={ContentState} EditorState={EditorState} handleTextChange={(e) => this.handleFeedbackChange(e, fp.key)} key="feedback" text={fp.feedback} /> {this.renderConceptResults(fp.conceptResults, fp.key)} </div> <footer className="card-footer"> <a className="card-footer-item" href={`/grammar/#/admin/questions/${this.props.match.params.questionID}/focus-points/${fp.key}/edit`}>Edit</a> <a className="card-footer-item" onClick={() => this.deleteFocusPoint(fp.key)}>Delete</a> <a className="card-footer-item" onClick={() => this.saveFocusPointsAndFeedback(fp.key)}>Save</a> </footer> </div> ); }); return <SortableList data={_.values(components)} key={_.values(components).length} sortCallback={this.sortCallback} />; } renderTextInputFields = (sequenceString, key) => { let className = `input regex-inline-edit regex-${key}` return sequenceString.split(/\|{3}(?!\|)/).map(text => ( <input className={className} onChange={(e) => this.handleFocusPointChange(e, key)} style={{ marginBottom: 5, minWidth: `${(text.length + 1) * 8}px`}} type="text" value={text || ''} /> )); } renderfPButton() { return ( this.state.fpOrderedIds ? <button className="button is-outlined is-primary" onClick={this.updatefpOrder} style={{ float: 'right', }}>Save FP Order</button> : null ); } renderConceptResults(concepts, focusPointKey) { if (concepts) { const components = _.mapObject(concepts, (val, key) => ( <p className="control sub-title is-6" key={`${val.name}`}>{val.name} {val.correct ? <span className="tag is-small is-success" style={{ marginLeft: 5, }}>Correct</span> : <span className="tag is-small is-danger" style={{ marginLeft: 5, }}>Incorrect</span> } <span className="tag is-small is-warning" onClick={() => this.deleteConceptResult(key, focusPointKey)} style={{ cursor: 'pointer', marginLeft: 5, }}>Delete</span> </p> ) ); return _.values(components); } } render() { return ( <div> <div className="has-top-margin"> <h1 className="title is-3" style={{ display: 'inline-block', }}>Focus Points</h1> <a className="button is-outlined is-primary" href={`/grammar/#/admin/questions/${this.props.match.params.questionID}/focus-points/new`} rel="noopener noreferrer" style={{ float: 'right', }} target="_blank">Add Focus Point</a> {this.renderfPButton()} </div> {this.renderFocusPointsList()} {this.props.children} </div> ); } } function select(props) { return { questions: props.questions }; } export default connect(select)(FocusPointsContainer);
focusPoints } = this.state if (this.state.fpOrderedIds) { const focusPoints = focusPoints; const newFp = {}; this.state.fpOrderedIds.forEach((id, index) => { const fp = Object.assign({}, focusPoints[id]); fp.order = index + 1; newFp[id] = fp; }); this.props.dispatch(questionActions.submitBatchEditedFocusPoint(this.props.match.params.questionID, newFp)); this.setState({ focusPoints: newFp}) alert('saved!'); } else { alert('no changes to focus points have been made'); } } renderFocu
identifier_body
focusPointsContainer.tsx
import * as React from 'react'; import { connect } from 'react-redux'; import * as _ from 'underscore'; import { EditorState, ContentState } from 'draft-js' import { TextEditor } from '../../../Shared/index'; import * as questionActions from '../../actions/questions'; import { hashToCollection, SortableList, } from '../../../Shared/index' export class FocusPointsContainer extends React.Component { constructor(props) { super(props); this.deleteFocusPoint = this.deleteFocusPoint.bind(this); this.sortCallback = this.sortCallback.bind(this); this.updatefpOrder = this.updatefpOrder.bind(this); const question = this.props.questions.data[this.props.match.params.questionID] const focusPoints = this.getFocusPoints(question) this.state = { fpOrderedIds: null, focusPoints: focusPoints }; } getFocusPoints(question) { return question.focusPoints; } deleteFocusPoint(focusPointID) { const { focusPoints } = this.state if (confirm('⚠️ Are you sure you want to delete this? 😱')) {
deleteConceptResult(conceptResultKey, focusPointKey) { const { focusPoints } = this.state if (confirm('⚠️ Are you sure you want to delete this? 😱')) { const data = focusPoints[focusPointKey]; delete data.conceptResults[conceptResultKey]; this.props.dispatch(questionActions.submitEditedFocusPoint(this.props.match.params.questionID, data, focusPointKey)); } } // fPsortedByOrder() { const { focusPoints } = this.state if (this.state.fpOrderedIds) { const focusPointsCollection = hashToCollection(focusPoints) return this.state.fpOrderedIds.map(id => focusPointsCollection.find(fp => fp.key === id)) } else { return hashToCollection(focusPoints).sort((a, b) => a.order - b.order); } } saveFocusPointsAndFeedback = (key) => { const { actionFile } = this.state const { dispatch, match } = this.props const { params } = match const { questionID } = params const { focusPoints } = this.state const filteredFocusPoints = this.removeEmptyFocusPoints(focusPoints) let data = filteredFocusPoints[key] delete data.conceptResults.null; if (data.text === '') { delete filteredFocusPoints[key] dispatch(questionActions.deleteFocusPoint(questionID, key)); } else { dispatch(questionActions.submitEditedFocusPoint(questionID, data, key)); } this.setState({focusPoints: filteredFocusPoints}) } removeEmptyFocusPoints = (focusPoints) => { return _.mapObject(focusPoints, (val) => ( Object.assign({}, val, { text: val.text.split(/\|{3}(?!\|)/).filter(val => val !== '').join('|||') }) ) ); } addNewFocusPoint = (e, key) => { const { focusPoints } = this.state const className = `regex-${key}` const value = `${Array.from(document.getElementsByClassName(className)).map(i => i.value).filter(val => val !== '').join('|||')}|||`; focusPoints[key].text = value; this.setState({focusPoints: focusPoints}) } handleNameChange = (e, key) => { const { focusPoints } = this.state focusPoints[key].name = e.target.value this.setState({focusPoints: focusPoints}) } handleFocusPointChange = (e, key) => { const { focusPoints } = this.state const className = `regex-${key}` const value = `${Array.from(document.getElementsByClassName(className)).map(i => i.value).filter(val => val !== '').join('|||')}`; if (value === '') { if (!confirm("Deleting this regex will delete the whole incorrect sequence. Are you sure you want that?")) { return } } focusPoints[key].text = value; this.setState({focusPoints: focusPoints}) } handleFeedbackChange = (e, key) => { const { focusPoints } = this.state focusPoints[key].feedback = e this.setState({focusPoints: focusPoints}) } sortCallback(sortInfo) { const fpOrderedIds = sortInfo.map(item => item.key); this.setState({ fpOrderedIds, }); } updatefpOrder() { const { focusPoints } = this.state if (this.state.fpOrderedIds) { const focusPoints = focusPoints; const newFp = {}; this.state.fpOrderedIds.forEach((id, index) => { const fp = Object.assign({}, focusPoints[id]); fp.order = index + 1; newFp[id] = fp; }); this.props.dispatch(questionActions.submitBatchEditedFocusPoint(this.props.match.params.questionID, newFp)); this.setState({ focusPoints: newFp}) alert('saved!'); } else { alert('no changes to focus points have been made'); } } renderFocusPointsList() { const components = this.fPsortedByOrder().map((fp) => { return ( <div className="card is-fullwidth has-bottom-margin" key={fp.key}> <header className="card-header"> <input className="regex-name" onChange={(e) => this.handleNameChange(e, fp.key)} placeholder="Name" type="text" value={fp.name || ''} /> </header> <header className="card-header"> <p className="card-header-title" style={{ display: 'inline-block', }}> {this.renderTextInputFields(fp.text, fp.key)} <button className="add-regex-button" onClick={(e) => this.addNewFocusPoint(e, fp.key)} type="button">+</button> </p> <p className="card-header-icon"> {fp.order} </p> </header> <div className="card-content"> <label className="label" htmlFor="feedback" style={{ marginTop: 10, }}>Feedback</label> <TextEditor ContentState={ContentState} EditorState={EditorState} handleTextChange={(e) => this.handleFeedbackChange(e, fp.key)} key="feedback" text={fp.feedback} /> {this.renderConceptResults(fp.conceptResults, fp.key)} </div> <footer className="card-footer"> <a className="card-footer-item" href={`/grammar/#/admin/questions/${this.props.match.params.questionID}/focus-points/${fp.key}/edit`}>Edit</a> <a className="card-footer-item" onClick={() => this.deleteFocusPoint(fp.key)}>Delete</a> <a className="card-footer-item" onClick={() => this.saveFocusPointsAndFeedback(fp.key)}>Save</a> </footer> </div> ); }); return <SortableList data={_.values(components)} key={_.values(components).length} sortCallback={this.sortCallback} />; } renderTextInputFields = (sequenceString, key) => { let className = `input regex-inline-edit regex-${key}` return sequenceString.split(/\|{3}(?!\|)/).map(text => ( <input className={className} onChange={(e) => this.handleFocusPointChange(e, key)} style={{ marginBottom: 5, minWidth: `${(text.length + 1) * 8}px`}} type="text" value={text || ''} /> )); } renderfPButton() { return ( this.state.fpOrderedIds ? <button className="button is-outlined is-primary" onClick={this.updatefpOrder} style={{ float: 'right', }}>Save FP Order</button> : null ); } renderConceptResults(concepts, focusPointKey) { if (concepts) { const components = _.mapObject(concepts, (val, key) => ( <p className="control sub-title is-6" key={`${val.name}`}>{val.name} {val.correct ? <span className="tag is-small is-success" style={{ marginLeft: 5, }}>Correct</span> : <span className="tag is-small is-danger" style={{ marginLeft: 5, }}>Incorrect</span> } <span className="tag is-small is-warning" onClick={() => this.deleteConceptResult(key, focusPointKey)} style={{ cursor: 'pointer', marginLeft: 5, }}>Delete</span> </p> ) ); return _.values(components); } } render() { return ( <div> <div className="has-top-margin"> <h1 className="title is-3" style={{ display: 'inline-block', }}>Focus Points</h1> <a className="button is-outlined is-primary" href={`/grammar/#/admin/questions/${this.props.match.params.questionID}/focus-points/new`} rel="noopener noreferrer" style={{ float: 'right', }} target="_blank">Add Focus Point</a> {this.renderfPButton()} </div> {this.renderFocusPointsList()} {this.props.children} </div> ); } } function select(props) { return { questions: props.questions }; } export default connect(select)(FocusPointsContainer);
this.props.dispatch(questionActions.deleteFocusPoint(this.props.match.params.questionID, focusPointID)); delete focusPoints[focusPointID] this.setState({focusPoints: focusPoints}) } }
conditional_block
focusPointsContainer.tsx
import * as React from 'react'; import { connect } from 'react-redux'; import * as _ from 'underscore'; import { EditorState, ContentState } from 'draft-js' import { TextEditor } from '../../../Shared/index'; import * as questionActions from '../../actions/questions'; import { hashToCollection, SortableList, } from '../../../Shared/index' export class FocusPointsContainer extends React.Component { constructor(props) { super(props); this.deleteFocusPoint = this.deleteFocusPoint.bind(this); this.sortCallback = this.sortCallback.bind(this); this.updatefpOrder = this.updatefpOrder.bind(this); const question = this.props.questions.data[this.props.match.params.questionID] const focusPoints = this.getFocusPoints(question) this.state = { fpOrderedIds: null, focusPoints: focusPoints }; } getFocusPoints(question) { return question.focusPoints; } deleteFocusPoint(focusPointID) { const { focusPoints } = this.state if (confirm('⚠️ Are you sure you want to delete this? 😱')) { this.props.dispatch(questionActions.deleteFocusPoint(this.props.match.params.questionID, focusPointID)); delete focusPoints[focusPointID] this.setState({focusPoints: focusPoints}) } } deleteConceptResult(conceptResultKey, focusPointKey) { const { focusPoints } = this.state if (confirm('⚠️ Are you sure you want to delete this? 😱')) { const data = focusPoints[focusPointKey]; delete data.conceptResults[conceptResultKey]; this.props.dispatch(questionActions.submitEditedFocusPoint(this.props.match.params.questionID, data, focusPointKey)); } } // fPsortedByOrde
{ focusPoints } = this.state if (this.state.fpOrderedIds) { const focusPointsCollection = hashToCollection(focusPoints) return this.state.fpOrderedIds.map(id => focusPointsCollection.find(fp => fp.key === id)) } else { return hashToCollection(focusPoints).sort((a, b) => a.order - b.order); } } saveFocusPointsAndFeedback = (key) => { const { actionFile } = this.state const { dispatch, match } = this.props const { params } = match const { questionID } = params const { focusPoints } = this.state const filteredFocusPoints = this.removeEmptyFocusPoints(focusPoints) let data = filteredFocusPoints[key] delete data.conceptResults.null; if (data.text === '') { delete filteredFocusPoints[key] dispatch(questionActions.deleteFocusPoint(questionID, key)); } else { dispatch(questionActions.submitEditedFocusPoint(questionID, data, key)); } this.setState({focusPoints: filteredFocusPoints}) } removeEmptyFocusPoints = (focusPoints) => { return _.mapObject(focusPoints, (val) => ( Object.assign({}, val, { text: val.text.split(/\|{3}(?!\|)/).filter(val => val !== '').join('|||') }) ) ); } addNewFocusPoint = (e, key) => { const { focusPoints } = this.state const className = `regex-${key}` const value = `${Array.from(document.getElementsByClassName(className)).map(i => i.value).filter(val => val !== '').join('|||')}|||`; focusPoints[key].text = value; this.setState({focusPoints: focusPoints}) } handleNameChange = (e, key) => { const { focusPoints } = this.state focusPoints[key].name = e.target.value this.setState({focusPoints: focusPoints}) } handleFocusPointChange = (e, key) => { const { focusPoints } = this.state const className = `regex-${key}` const value = `${Array.from(document.getElementsByClassName(className)).map(i => i.value).filter(val => val !== '').join('|||')}`; if (value === '') { if (!confirm("Deleting this regex will delete the whole incorrect sequence. Are you sure you want that?")) { return } } focusPoints[key].text = value; this.setState({focusPoints: focusPoints}) } handleFeedbackChange = (e, key) => { const { focusPoints } = this.state focusPoints[key].feedback = e this.setState({focusPoints: focusPoints}) } sortCallback(sortInfo) { const fpOrderedIds = sortInfo.map(item => item.key); this.setState({ fpOrderedIds, }); } updatefpOrder() { const { focusPoints } = this.state if (this.state.fpOrderedIds) { const focusPoints = focusPoints; const newFp = {}; this.state.fpOrderedIds.forEach((id, index) => { const fp = Object.assign({}, focusPoints[id]); fp.order = index + 1; newFp[id] = fp; }); this.props.dispatch(questionActions.submitBatchEditedFocusPoint(this.props.match.params.questionID, newFp)); this.setState({ focusPoints: newFp}) alert('saved!'); } else { alert('no changes to focus points have been made'); } } renderFocusPointsList() { const components = this.fPsortedByOrder().map((fp) => { return ( <div className="card is-fullwidth has-bottom-margin" key={fp.key}> <header className="card-header"> <input className="regex-name" onChange={(e) => this.handleNameChange(e, fp.key)} placeholder="Name" type="text" value={fp.name || ''} /> </header> <header className="card-header"> <p className="card-header-title" style={{ display: 'inline-block', }}> {this.renderTextInputFields(fp.text, fp.key)} <button className="add-regex-button" onClick={(e) => this.addNewFocusPoint(e, fp.key)} type="button">+</button> </p> <p className="card-header-icon"> {fp.order} </p> </header> <div className="card-content"> <label className="label" htmlFor="feedback" style={{ marginTop: 10, }}>Feedback</label> <TextEditor ContentState={ContentState} EditorState={EditorState} handleTextChange={(e) => this.handleFeedbackChange(e, fp.key)} key="feedback" text={fp.feedback} /> {this.renderConceptResults(fp.conceptResults, fp.key)} </div> <footer className="card-footer"> <a className="card-footer-item" href={`/grammar/#/admin/questions/${this.props.match.params.questionID}/focus-points/${fp.key}/edit`}>Edit</a> <a className="card-footer-item" onClick={() => this.deleteFocusPoint(fp.key)}>Delete</a> <a className="card-footer-item" onClick={() => this.saveFocusPointsAndFeedback(fp.key)}>Save</a> </footer> </div> ); }); return <SortableList data={_.values(components)} key={_.values(components).length} sortCallback={this.sortCallback} />; } renderTextInputFields = (sequenceString, key) => { let className = `input regex-inline-edit regex-${key}` return sequenceString.split(/\|{3}(?!\|)/).map(text => ( <input className={className} onChange={(e) => this.handleFocusPointChange(e, key)} style={{ marginBottom: 5, minWidth: `${(text.length + 1) * 8}px`}} type="text" value={text || ''} /> )); } renderfPButton() { return ( this.state.fpOrderedIds ? <button className="button is-outlined is-primary" onClick={this.updatefpOrder} style={{ float: 'right', }}>Save FP Order</button> : null ); } renderConceptResults(concepts, focusPointKey) { if (concepts) { const components = _.mapObject(concepts, (val, key) => ( <p className="control sub-title is-6" key={`${val.name}`}>{val.name} {val.correct ? <span className="tag is-small is-success" style={{ marginLeft: 5, }}>Correct</span> : <span className="tag is-small is-danger" style={{ marginLeft: 5, }}>Incorrect</span> } <span className="tag is-small is-warning" onClick={() => this.deleteConceptResult(key, focusPointKey)} style={{ cursor: 'pointer', marginLeft: 5, }}>Delete</span> </p> ) ); return _.values(components); } } render() { return ( <div> <div className="has-top-margin"> <h1 className="title is-3" style={{ display: 'inline-block', }}>Focus Points</h1> <a className="button is-outlined is-primary" href={`/grammar/#/admin/questions/${this.props.match.params.questionID}/focus-points/new`} rel="noopener noreferrer" style={{ float: 'right', }} target="_blank">Add Focus Point</a> {this.renderfPButton()} </div> {this.renderFocusPointsList()} {this.props.children} </div> ); } } function select(props) { return { questions: props.questions }; } export default connect(select)(FocusPointsContainer);
r() { const
identifier_name
focusPointsContainer.tsx
import * as React from 'react'; import { connect } from 'react-redux'; import * as _ from 'underscore'; import { EditorState, ContentState } from 'draft-js' import { TextEditor } from '../../../Shared/index'; import * as questionActions from '../../actions/questions'; import { hashToCollection, SortableList, } from '../../../Shared/index' export class FocusPointsContainer extends React.Component { constructor(props) { super(props); this.deleteFocusPoint = this.deleteFocusPoint.bind(this); this.sortCallback = this.sortCallback.bind(this); this.updatefpOrder = this.updatefpOrder.bind(this); const question = this.props.questions.data[this.props.match.params.questionID] const focusPoints = this.getFocusPoints(question) this.state = { fpOrderedIds: null, focusPoints: focusPoints }; } getFocusPoints(question) { return question.focusPoints; } deleteFocusPoint(focusPointID) { const { focusPoints } = this.state if (confirm('⚠️ Are you sure you want to delete this? 😱')) { this.props.dispatch(questionActions.deleteFocusPoint(this.props.match.params.questionID, focusPointID)); delete focusPoints[focusPointID] this.setState({focusPoints: focusPoints}) } } deleteConceptResult(conceptResultKey, focusPointKey) { const { focusPoints } = this.state if (confirm('⚠️ Are you sure you want to delete this? 😱')) { const data = focusPoints[focusPointKey]; delete data.conceptResults[conceptResultKey]; this.props.dispatch(questionActions.submitEditedFocusPoint(this.props.match.params.questionID, data, focusPointKey)); } } // fPsortedByOrder() { const { focusPoints } = this.state if (this.state.fpOrderedIds) { const focusPointsCollection = hashToCollection(focusPoints) return this.state.fpOrderedIds.map(id => focusPointsCollection.find(fp => fp.key === id)) } else { return hashToCollection(focusPoints).sort((a, b) => a.order - b.order); } } saveFocusPointsAndFeedback = (key) => { const { actionFile } = this.state const { dispatch, match } = this.props const { params } = match const { questionID } = params const { focusPoints } = this.state const filteredFocusPoints = this.removeEmptyFocusPoints(focusPoints) let data = filteredFocusPoints[key] delete data.conceptResults.null; if (data.text === '') { delete filteredFocusPoints[key] dispatch(questionActions.deleteFocusPoint(questionID, key)); } else { dispatch(questionActions.submitEditedFocusPoint(questionID, data, key)); } this.setState({focusPoints: filteredFocusPoints}) } removeEmptyFocusPoints = (focusPoints) => { return _.mapObject(focusPoints, (val) => ( Object.assign({}, val, { text: val.text.split(/\|{3}(?!\|)/).filter(val => val !== '').join('|||') }) ) ); } addNewFocusPoint = (e, key) => { const { focusPoints } = this.state const className = `regex-${key}` const value = `${Array.from(document.getElementsByClassName(className)).map(i => i.value).filter(val => val !== '').join('|||')}|||`; focusPoints[key].text = value; this.setState({focusPoints: focusPoints}) } handleNameChange = (e, key) => { const { focusPoints } = this.state focusPoints[key].name = e.target.value this.setState({focusPoints: focusPoints}) } handleFocusPointChange = (e, key) => { const { focusPoints } = this.state const className = `regex-${key}` const value = `${Array.from(document.getElementsByClassName(className)).map(i => i.value).filter(val => val !== '').join('|||')}`; if (value === '') { if (!confirm("Deleting this regex will delete the whole incorrect sequence. Are you sure you want that?")) { return } } focusPoints[key].text = value; this.setState({focusPoints: focusPoints}) } handleFeedbackChange = (e, key) => { const { focusPoints } = this.state focusPoints[key].feedback = e this.setState({focusPoints: focusPoints}) } sortCallback(sortInfo) { const fpOrderedIds = sortInfo.map(item => item.key); this.setState({ fpOrderedIds, }); } updatefpOrder() { const { focusPoints } = this.state if (this.state.fpOrderedIds) { const focusPoints = focusPoints; const newFp = {}; this.state.fpOrderedIds.forEach((id, index) => { const fp = Object.assign({}, focusPoints[id]); fp.order = index + 1; newFp[id] = fp; }); this.props.dispatch(questionActions.submitBatchEditedFocusPoint(this.props.match.params.questionID, newFp)); this.setState({ focusPoints: newFp}) alert('saved!'); } else { alert('no changes to focus points have been made'); } } renderFocusPointsList() { const components = this.fPsortedByOrder().map((fp) => { return ( <div className="card is-fullwidth has-bottom-margin" key={fp.key}> <header className="card-header"> <input className="regex-name" onChange={(e) => this.handleNameChange(e, fp.key)} placeholder="Name" type="text" value={fp.name || ''} /> </header> <header className="card-header"> <p className="card-header-title" style={{ display: 'inline-block', }}> {this.renderTextInputFields(fp.text, fp.key)} <button className="add-regex-button" onClick={(e) => this.addNewFocusPoint(e, fp.key)} type="button">+</button> </p> <p className="card-header-icon"> {fp.order} </p> </header> <div className="card-content"> <label className="label" htmlFor="feedback" style={{ marginTop: 10, }}>Feedback</label> <TextEditor ContentState={ContentState} EditorState={EditorState} handleTextChange={(e) => this.handleFeedbackChange(e, fp.key)} key="feedback" text={fp.feedback} /> {this.renderConceptResults(fp.conceptResults, fp.key)} </div> <footer className="card-footer"> <a className="card-footer-item" href={`/grammar/#/admin/questions/${this.props.match.params.questionID}/focus-points/${fp.key}/edit`}>Edit</a> <a className="card-footer-item" onClick={() => this.deleteFocusPoint(fp.key)}>Delete</a> <a className="card-footer-item" onClick={() => this.saveFocusPointsAndFeedback(fp.key)}>Save</a> </footer> </div> ); }); return <SortableList data={_.values(components)} key={_.values(components).length} sortCallback={this.sortCallback} />; } renderTextInputFields = (sequenceString, key) => { let className = `input regex-inline-edit regex-${key}` return sequenceString.split(/\|{3}(?!\|)/).map(text => ( <input className={className} onChange={(e) => this.handleFocusPointChange(e, key)} style={{ marginBottom: 5, minWidth: `${(text.length + 1) * 8}px`}} type="text" value={text || ''} /> )); } renderfPButton() { return ( this.state.fpOrderedIds ? <button className="button is-outlined is-primary" onClick={this.updatefpOrder} style={{ float: 'right', }}>Save FP Order</button> : null ); } renderConceptResults(concepts, focusPointKey) { if (concepts) { const components = _.mapObject(concepts, (val, key) => ( <p className="control sub-title is-6" key={`${val.name}`}>{val.name} {val.correct ? <span className="tag is-small is-success" style={{ marginLeft: 5, }}>Correct</span> : <span className="tag is-small is-danger" style={{ marginLeft: 5, }}>Incorrect</span> } <span className="tag is-small is-warning" onClick={() => this.deleteConceptResult(key, focusPointKey)} style={{ cursor: 'pointer', marginLeft: 5, }}>Delete</span> </p> ) ); return _.values(components); } } render() { return ( <div> <div className="has-top-margin"> <h1 className="title is-3" style={{ display: 'inline-block', }}>Focus Points</h1> <a className="button is-outlined is-primary" href={`/grammar/#/admin/questions/${this.props.match.params.questionID}/focus-points/new`} rel="noopener noreferrer" style={{ float: 'right', }} target="_blank">Add Focus Point</a> {this.renderfPButton()}
); } } function select(props) { return { questions: props.questions }; } export default connect(select)(FocusPointsContainer);
</div> {this.renderFocusPointsList()} {this.props.children} </div>
random_line_split
estimator.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. #
# # 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. # ============================================================================== """Functions to bridge `Distribution`s and `tf.contrib.learn.estimator` APIs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators.head import _compute_weighted_loss from tensorflow.contrib.learn.python.learn.estimators.head import _RegressionHead from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops __all__ = [ "estimator_head_distribution_regression", ] def estimator_head_distribution_regression(make_distribution_fn, label_dimension=1, logits_dimension=None, label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None): """Creates a `Head` for regression under a generic distribution. Args: make_distribution_fn: Python `callable` which returns a `tf.Distribution` instance created using only logits. label_dimension: Number of regression labels per example. This is the size of the last dimension of the labels `Tensor` (typically, this has shape `[batch_size, label_dimension]`). logits_dimension: Number of logits per example. This is the size of the last dimension of the logits `Tensor` (typically, this has shape `[batch_size, logits_dimension]`). Default value: `label_dimension`. label_name: Python `str`, name of the key in label `dict`. Can be `None` if label is a `Tensor` (single headed models). weight_column_name: Python `str` defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: Python `bool`. If `True`, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: Python `str`, name of the head. Predictions, summary and metrics keys are suffixed by `"/" + head_name` and the default variable scope is `head_name`. Returns: An instance of `Head` for generic regression. """ return _DistributionRegressionHead( make_distribution_fn=make_distribution_fn, label_dimension=label_dimension, logits_dimension=logits_dimension, label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name) class _DistributionRegressionHead(_RegressionHead): """Creates a _RegressionHead instance from an arbitrary `Distribution`.""" def __init__(self, make_distribution_fn, label_dimension, logits_dimension=None, label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None): """`Head` for regression. Args: make_distribution_fn: Python `callable` which returns a `tf.Distribution` instance created using only logits. label_dimension: Number of regression labels per example. This is the size of the last dimension of the labels `Tensor` (typically, this has shape `[batch_size, label_dimension]`). logits_dimension: Number of logits per example. This is the size of the last dimension of the logits `Tensor` (typically, this has shape `[batch_size, logits_dimension]`). Default value: `label_dimension`. label_name: Python `str`, name of the key in label `dict`. Can be `None` if label is a tensor (single headed models). weight_column_name: Python `str` defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: Python `bool`. If `True`, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: Python `str`, name of the head. Predictions, summary and metrics keys are suffixed by `"/" + head_name` and the default variable scope is `head_name`. Raises: TypeError: if `make_distribution_fn` is not `callable`. """ if not callable(make_distribution_fn): raise TypeError("`make_distribution_fn` must be a callable function.") self._distributions = {} self._make_distribution_fn = make_distribution_fn def static_value(x): """Returns the static value of a `Tensor` or `None`.""" return tensor_util.constant_value(ops.convert_to_tensor(x)) def concat_vectors(*args): """Concatenates input vectors, statically if possible.""" args_ = [static_value(x) for x in args] if any(vec is None for vec in args_): return array_ops.concat(args, axis=0) return [val for vec in args_ for val in vec] def loss_fn(labels, logits, weights=None): """Returns the loss of using `logits` to predict `labels`.""" d = self.distribution(logits) labels_batch_shape = labels.shape.with_rank_at_least(1)[:-1] labels_batch_shape = ( labels_batch_shape.as_list() if labels_batch_shape.is_fully_defined() else array_ops.shape(labels)[:-1]) labels = array_ops.reshape( labels, shape=concat_vectors(labels_batch_shape, d.event_shape_tensor())) return _compute_weighted_loss( loss_unweighted=-d.log_prob(labels), weight=weights) def link_fn(logits): """Returns the inverse link function at `logits`.""" # Note: What the API calls a "link function" is really the inverse-link # function, i.e., the "mean". d = self.distribution(logits) return d.mean() super(_DistributionRegressionHead, self).__init__( label_dimension=label_dimension, loss_fn=loss_fn, link_fn=link_fn, logits_dimension=logits_dimension, label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name) @property def distributions(self): """Returns all distributions created by `DistributionRegressionHead`.""" return self._distributions def distribution(self, logits, name=None): """Retrieves a distribution instance, parameterized by `logits`. Args: logits: `float`-like `Tensor` representing the parameters of the underlying distribution. name: The Python `str` name to given to this op. Default value: "distribution". Returns: distribution: `tf.Distribution` instance parameterized by `logits`. """ with ops.name_scope(name, "distribution", [logits]): d = self._distributions.get(logits, None) if d is None: d = self._make_distribution_fn(logits) self._distributions[logits] = d return d
# 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
random_line_split
estimator.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions to bridge `Distribution`s and `tf.contrib.learn.estimator` APIs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators.head import _compute_weighted_loss from tensorflow.contrib.learn.python.learn.estimators.head import _RegressionHead from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops __all__ = [ "estimator_head_distribution_regression", ] def estimator_head_distribution_regression(make_distribution_fn, label_dimension=1, logits_dimension=None, label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None): """Creates a `Head` for regression under a generic distribution. Args: make_distribution_fn: Python `callable` which returns a `tf.Distribution` instance created using only logits. label_dimension: Number of regression labels per example. This is the size of the last dimension of the labels `Tensor` (typically, this has shape `[batch_size, label_dimension]`). logits_dimension: Number of logits per example. This is the size of the last dimension of the logits `Tensor` (typically, this has shape `[batch_size, logits_dimension]`). Default value: `label_dimension`. label_name: Python `str`, name of the key in label `dict`. Can be `None` if label is a `Tensor` (single headed models). weight_column_name: Python `str` defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: Python `bool`. If `True`, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: Python `str`, name of the head. Predictions, summary and metrics keys are suffixed by `"/" + head_name` and the default variable scope is `head_name`. Returns: An instance of `Head` for generic regression. """ return _DistributionRegressionHead( make_distribution_fn=make_distribution_fn, label_dimension=label_dimension, logits_dimension=logits_dimension, label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name) class _DistributionRegressionHead(_RegressionHead): """Creates a _RegressionHead instance from an arbitrary `Distribution`.""" def __init__(self, make_distribution_fn, label_dimension, logits_dimension=None, label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None): """`Head` for regression. Args: make_distribution_fn: Python `callable` which returns a `tf.Distribution` instance created using only logits. label_dimension: Number of regression labels per example. This is the size of the last dimension of the labels `Tensor` (typically, this has shape `[batch_size, label_dimension]`). logits_dimension: Number of logits per example. This is the size of the last dimension of the logits `Tensor` (typically, this has shape `[batch_size, logits_dimension]`). Default value: `label_dimension`. label_name: Python `str`, name of the key in label `dict`. Can be `None` if label is a tensor (single headed models). weight_column_name: Python `str` defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: Python `bool`. If `True`, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: Python `str`, name of the head. Predictions, summary and metrics keys are suffixed by `"/" + head_name` and the default variable scope is `head_name`. Raises: TypeError: if `make_distribution_fn` is not `callable`. """ if not callable(make_distribution_fn): raise TypeError("`make_distribution_fn` must be a callable function.") self._distributions = {} self._make_distribution_fn = make_distribution_fn def static_value(x): """Returns the static value of a `Tensor` or `None`.""" return tensor_util.constant_value(ops.convert_to_tensor(x)) def concat_vectors(*args): """Concatenates input vectors, statically if possible.""" args_ = [static_value(x) for x in args] if any(vec is None for vec in args_): return array_ops.concat(args, axis=0) return [val for vec in args_ for val in vec] def loss_fn(labels, logits, weights=None): """Returns the loss of using `logits` to predict `labels`.""" d = self.distribution(logits) labels_batch_shape = labels.shape.with_rank_at_least(1)[:-1] labels_batch_shape = ( labels_batch_shape.as_list() if labels_batch_shape.is_fully_defined() else array_ops.shape(labels)[:-1]) labels = array_ops.reshape( labels, shape=concat_vectors(labels_batch_shape, d.event_shape_tensor())) return _compute_weighted_loss( loss_unweighted=-d.log_prob(labels), weight=weights) def link_fn(logits): """Returns the inverse link function at `logits`.""" # Note: What the API calls a "link function" is really the inverse-link # function, i.e., the "mean". d = self.distribution(logits) return d.mean() super(_DistributionRegressionHead, self).__init__( label_dimension=label_dimension, loss_fn=loss_fn, link_fn=link_fn, logits_dimension=logits_dimension, label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name) @property def distributions(self): """Returns all distributions created by `DistributionRegressionHead`.""" return self._distributions def
(self, logits, name=None): """Retrieves a distribution instance, parameterized by `logits`. Args: logits: `float`-like `Tensor` representing the parameters of the underlying distribution. name: The Python `str` name to given to this op. Default value: "distribution". Returns: distribution: `tf.Distribution` instance parameterized by `logits`. """ with ops.name_scope(name, "distribution", [logits]): d = self._distributions.get(logits, None) if d is None: d = self._make_distribution_fn(logits) self._distributions[logits] = d return d
distribution
identifier_name
estimator.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions to bridge `Distribution`s and `tf.contrib.learn.estimator` APIs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators.head import _compute_weighted_loss from tensorflow.contrib.learn.python.learn.estimators.head import _RegressionHead from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops __all__ = [ "estimator_head_distribution_regression", ] def estimator_head_distribution_regression(make_distribution_fn, label_dimension=1, logits_dimension=None, label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None):
class _DistributionRegressionHead(_RegressionHead): """Creates a _RegressionHead instance from an arbitrary `Distribution`.""" def __init__(self, make_distribution_fn, label_dimension, logits_dimension=None, label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None): """`Head` for regression. Args: make_distribution_fn: Python `callable` which returns a `tf.Distribution` instance created using only logits. label_dimension: Number of regression labels per example. This is the size of the last dimension of the labels `Tensor` (typically, this has shape `[batch_size, label_dimension]`). logits_dimension: Number of logits per example. This is the size of the last dimension of the logits `Tensor` (typically, this has shape `[batch_size, logits_dimension]`). Default value: `label_dimension`. label_name: Python `str`, name of the key in label `dict`. Can be `None` if label is a tensor (single headed models). weight_column_name: Python `str` defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: Python `bool`. If `True`, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: Python `str`, name of the head. Predictions, summary and metrics keys are suffixed by `"/" + head_name` and the default variable scope is `head_name`. Raises: TypeError: if `make_distribution_fn` is not `callable`. """ if not callable(make_distribution_fn): raise TypeError("`make_distribution_fn` must be a callable function.") self._distributions = {} self._make_distribution_fn = make_distribution_fn def static_value(x): """Returns the static value of a `Tensor` or `None`.""" return tensor_util.constant_value(ops.convert_to_tensor(x)) def concat_vectors(*args): """Concatenates input vectors, statically if possible.""" args_ = [static_value(x) for x in args] if any(vec is None for vec in args_): return array_ops.concat(args, axis=0) return [val for vec in args_ for val in vec] def loss_fn(labels, logits, weights=None): """Returns the loss of using `logits` to predict `labels`.""" d = self.distribution(logits) labels_batch_shape = labels.shape.with_rank_at_least(1)[:-1] labels_batch_shape = ( labels_batch_shape.as_list() if labels_batch_shape.is_fully_defined() else array_ops.shape(labels)[:-1]) labels = array_ops.reshape( labels, shape=concat_vectors(labels_batch_shape, d.event_shape_tensor())) return _compute_weighted_loss( loss_unweighted=-d.log_prob(labels), weight=weights) def link_fn(logits): """Returns the inverse link function at `logits`.""" # Note: What the API calls a "link function" is really the inverse-link # function, i.e., the "mean". d = self.distribution(logits) return d.mean() super(_DistributionRegressionHead, self).__init__( label_dimension=label_dimension, loss_fn=loss_fn, link_fn=link_fn, logits_dimension=logits_dimension, label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name) @property def distributions(self): """Returns all distributions created by `DistributionRegressionHead`.""" return self._distributions def distribution(self, logits, name=None): """Retrieves a distribution instance, parameterized by `logits`. Args: logits: `float`-like `Tensor` representing the parameters of the underlying distribution. name: The Python `str` name to given to this op. Default value: "distribution". Returns: distribution: `tf.Distribution` instance parameterized by `logits`. """ with ops.name_scope(name, "distribution", [logits]): d = self._distributions.get(logits, None) if d is None: d = self._make_distribution_fn(logits) self._distributions[logits] = d return d
"""Creates a `Head` for regression under a generic distribution. Args: make_distribution_fn: Python `callable` which returns a `tf.Distribution` instance created using only logits. label_dimension: Number of regression labels per example. This is the size of the last dimension of the labels `Tensor` (typically, this has shape `[batch_size, label_dimension]`). logits_dimension: Number of logits per example. This is the size of the last dimension of the logits `Tensor` (typically, this has shape `[batch_size, logits_dimension]`). Default value: `label_dimension`. label_name: Python `str`, name of the key in label `dict`. Can be `None` if label is a `Tensor` (single headed models). weight_column_name: Python `str` defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: Python `bool`. If `True`, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: Python `str`, name of the head. Predictions, summary and metrics keys are suffixed by `"/" + head_name` and the default variable scope is `head_name`. Returns: An instance of `Head` for generic regression. """ return _DistributionRegressionHead( make_distribution_fn=make_distribution_fn, label_dimension=label_dimension, logits_dimension=logits_dimension, label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name)
identifier_body
estimator.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions to bridge `Distribution`s and `tf.contrib.learn.estimator` APIs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators.head import _compute_weighted_loss from tensorflow.contrib.learn.python.learn.estimators.head import _RegressionHead from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops __all__ = [ "estimator_head_distribution_regression", ] def estimator_head_distribution_regression(make_distribution_fn, label_dimension=1, logits_dimension=None, label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None): """Creates a `Head` for regression under a generic distribution. Args: make_distribution_fn: Python `callable` which returns a `tf.Distribution` instance created using only logits. label_dimension: Number of regression labels per example. This is the size of the last dimension of the labels `Tensor` (typically, this has shape `[batch_size, label_dimension]`). logits_dimension: Number of logits per example. This is the size of the last dimension of the logits `Tensor` (typically, this has shape `[batch_size, logits_dimension]`). Default value: `label_dimension`. label_name: Python `str`, name of the key in label `dict`. Can be `None` if label is a `Tensor` (single headed models). weight_column_name: Python `str` defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: Python `bool`. If `True`, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: Python `str`, name of the head. Predictions, summary and metrics keys are suffixed by `"/" + head_name` and the default variable scope is `head_name`. Returns: An instance of `Head` for generic regression. """ return _DistributionRegressionHead( make_distribution_fn=make_distribution_fn, label_dimension=label_dimension, logits_dimension=logits_dimension, label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name) class _DistributionRegressionHead(_RegressionHead): """Creates a _RegressionHead instance from an arbitrary `Distribution`.""" def __init__(self, make_distribution_fn, label_dimension, logits_dimension=None, label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None): """`Head` for regression. Args: make_distribution_fn: Python `callable` which returns a `tf.Distribution` instance created using only logits. label_dimension: Number of regression labels per example. This is the size of the last dimension of the labels `Tensor` (typically, this has shape `[batch_size, label_dimension]`). logits_dimension: Number of logits per example. This is the size of the last dimension of the logits `Tensor` (typically, this has shape `[batch_size, logits_dimension]`). Default value: `label_dimension`. label_name: Python `str`, name of the key in label `dict`. Can be `None` if label is a tensor (single headed models). weight_column_name: Python `str` defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: Python `bool`. If `True`, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: Python `str`, name of the head. Predictions, summary and metrics keys are suffixed by `"/" + head_name` and the default variable scope is `head_name`. Raises: TypeError: if `make_distribution_fn` is not `callable`. """ if not callable(make_distribution_fn): raise TypeError("`make_distribution_fn` must be a callable function.") self._distributions = {} self._make_distribution_fn = make_distribution_fn def static_value(x): """Returns the static value of a `Tensor` or `None`.""" return tensor_util.constant_value(ops.convert_to_tensor(x)) def concat_vectors(*args): """Concatenates input vectors, statically if possible.""" args_ = [static_value(x) for x in args] if any(vec is None for vec in args_): return array_ops.concat(args, axis=0) return [val for vec in args_ for val in vec] def loss_fn(labels, logits, weights=None): """Returns the loss of using `logits` to predict `labels`.""" d = self.distribution(logits) labels_batch_shape = labels.shape.with_rank_at_least(1)[:-1] labels_batch_shape = ( labels_batch_shape.as_list() if labels_batch_shape.is_fully_defined() else array_ops.shape(labels)[:-1]) labels = array_ops.reshape( labels, shape=concat_vectors(labels_batch_shape, d.event_shape_tensor())) return _compute_weighted_loss( loss_unweighted=-d.log_prob(labels), weight=weights) def link_fn(logits): """Returns the inverse link function at `logits`.""" # Note: What the API calls a "link function" is really the inverse-link # function, i.e., the "mean". d = self.distribution(logits) return d.mean() super(_DistributionRegressionHead, self).__init__( label_dimension=label_dimension, loss_fn=loss_fn, link_fn=link_fn, logits_dimension=logits_dimension, label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name) @property def distributions(self): """Returns all distributions created by `DistributionRegressionHead`.""" return self._distributions def distribution(self, logits, name=None): """Retrieves a distribution instance, parameterized by `logits`. Args: logits: `float`-like `Tensor` representing the parameters of the underlying distribution. name: The Python `str` name to given to this op. Default value: "distribution". Returns: distribution: `tf.Distribution` instance parameterized by `logits`. """ with ops.name_scope(name, "distribution", [logits]): d = self._distributions.get(logits, None) if d is None:
return d
d = self._make_distribution_fn(logits) self._distributions[logits] = d
conditional_block
sso.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """External user authentication for CERN NICE/CRA Invenio.""" __revision__ = \ "$Id$" import re from invenio.legacy.external_authentication import ExternalAuth # Tunable list of settings to be hidden ## e.g.: CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS = ('auth', 'respccid', 'personid') CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS = () # Tunable list of groups to be hidden CFG_EXTERNAL_AUTH_HIDDEN_GROUPS = ( 'All Exchange People', 'CERN Users', 'cern-computing-postmasters', 'cern-nice2000-postmasters', 'CMF FrontEnd Users', 'CMF_NSC_259_NSU', 'Domain Users', 'GP Apply Favorites Redirection', 'GP Apply NoAdmin', 'info-terminalservices', 'info-terminalservices-members', 'IT Web IT', 'NICE Deny Enforce Password-protected Screensaver', 'NICE Enforce Password-protected Screensaver', 'NICE LightWeight Authentication WS Users', 'NICE MyDocuments Redirection (New)', 'NICE Profile Redirection', 'NICE Terminal Services Users', 'NICE Users', 'NICE VPN Users', ) CFG_EXTERNAL_AUTH_HIDDEN_GROUPS_RE = ( re.compile(r'Users by Letter [A-Z]'), re.compile(r'building-[\d]+'), re.compile(r'Users by Home CERNHOME[A-Z]'), ) # Prefix name for Shibboleth variables CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES = ('ADFS_', 'Shib-') # Name of the variable containing groups CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'GROUP' # Name of the variable containing login name CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'LOGIN' # Name of the variable containing email CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'EMAIL' # Name of the variable containing groups CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'GROUP' # Separator character for group variable CFG_EXTERNAL_AUTH_SSO_GROUPS_SEPARATOR = ';' class ExternalAuthSSO(ExternalAuth): """ External authentication example for a custom SSO-based authentication service. """ def __init__(self, enforce_external_nicknames=False): """Initialize stuff here""" ExternalAuth.__init__(self, enforce_external_nicknames) self.egroup_cache = None def in_shibboleth(self, req): """ Return True if the current request handler is actually under Shibboleth control. """ return CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env def auth_user(self, username, password, req=None): """ Check USERNAME and PASSWORD against the SSO system. Return (None, None) if authentication failed, or the (email address, nickname) of the person if the authentication was successful. In order to do this you may perhaps have to keep a translation table between usernames and email addresses. If it is the first time the user logs in Invenio the nickname is stored alongside the email. If this nickname is unfortunatly already in use it is discarded. Otherwise it is ignored. Raise InvenioWebAccessExternalAuthError in case of external troubles. Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env: return req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE], req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE] return None, None #def user_exists(self, email, req=None): #"""Checks against CERN NICE/CRA for existance of email. #@return: True if the user exists, False otherwise #""" #users = self._try_twice(funct=AuthCernWrapper.list_users, \ #params={"display_name":email}) #return email.upper() in [user['email'].upper() for user in users] def fetch_user_groups_membership(self, email, password=None, req=None): """Fetch user groups membership from the SSO system. @return: a dictionary of groupname, group description Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ return self._fetch_egroups(req) def fetch_user_nickname(self, username, password=None, req=None): """Given a username and a password, returns the right nickname belonging to that user (username could be an email). Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE in req.subprocess_env: return req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE] else: return None def _fetch_egroups(self, req=None): if False: #self.egroup_cache is not None: return self.egroup_cache elif req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE in req.subprocess_env:
return {} def _fetch_particular_preferences(self, req=None): """This hidden method is there to be overwritten in order to get some particular value from non standard variables. """ if req: ret = {} req.add_common_vars() if 'HTTP_SHIB_AUTHENTICATION_METHOD' in req.subprocess_env: ret['authmethod'] = req.subprocess_env['HTTP_SHIB_AUTHENTICATION_METHOD'] ret['external'] = '1' if 'ADFS_IDENTITYCLASS' in req.subprocess_env and \ req.subprocess_env['ADFS_IDENTITYCLASS'] in ('CERN Registered', 'CERN Shared'): ret['external'] = '0' return ret return {} def fetch_user_preferences(self, username, password=None, req=None): """Fetch user preferences/settings from the SSO account. the external key will be '1' if the account is external to SSO, otherwise 0 @return: a dictionary. Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() ret = {} prefs = self._fetch_particular_preferences(req) for key, value in req.subprocess_env.items(): for prefix in CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES: if key.startswith(prefix) and not key == CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE: prefs[key[len(prefix):].lower()] = value break for key, value in prefs.items(): if key in CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS: ret['HIDDEN_' + key] = value else: ret[key] = value return ret return {}
groups = req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE].split(CFG_EXTERNAL_AUTH_SSO_GROUPS_SEPARATOR) # Filtering out uncomfortable groups groups = [group for group in groups if group not in CFG_EXTERNAL_AUTH_HIDDEN_GROUPS] for regexp in CFG_EXTERNAL_AUTH_HIDDEN_GROUPS_RE: for group in groups: if regexp.match(group): groups.remove(group) self.egroup_cache = dict(map(lambda x: (x, '@' in x and x + ' (Mailing list)' \ or x + ' (Group)'), groups)) return self.egroup_cache
conditional_block
sso.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """External user authentication for CERN NICE/CRA Invenio.""" __revision__ = \ "$Id$" import re from invenio.legacy.external_authentication import ExternalAuth # Tunable list of settings to be hidden ## e.g.: CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS = ('auth', 'respccid', 'personid') CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS = () # Tunable list of groups to be hidden CFG_EXTERNAL_AUTH_HIDDEN_GROUPS = ( 'All Exchange People', 'CERN Users', 'cern-computing-postmasters', 'cern-nice2000-postmasters', 'CMF FrontEnd Users', 'CMF_NSC_259_NSU', 'Domain Users', 'GP Apply Favorites Redirection', 'GP Apply NoAdmin', 'info-terminalservices', 'info-terminalservices-members', 'IT Web IT', 'NICE Deny Enforce Password-protected Screensaver', 'NICE Enforce Password-protected Screensaver', 'NICE LightWeight Authentication WS Users', 'NICE MyDocuments Redirection (New)', 'NICE Profile Redirection', 'NICE Terminal Services Users', 'NICE Users', 'NICE VPN Users', ) CFG_EXTERNAL_AUTH_HIDDEN_GROUPS_RE = ( re.compile(r'Users by Letter [A-Z]'), re.compile(r'building-[\d]+'), re.compile(r'Users by Home CERNHOME[A-Z]'), ) # Prefix name for Shibboleth variables CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES = ('ADFS_', 'Shib-') # Name of the variable containing groups CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'GROUP' # Name of the variable containing login name CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'LOGIN' # Name of the variable containing email CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'EMAIL' # Name of the variable containing groups CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'GROUP' # Separator character for group variable CFG_EXTERNAL_AUTH_SSO_GROUPS_SEPARATOR = ';' class ExternalAuthSSO(ExternalAuth): """ External authentication example for a custom SSO-based authentication service. """ def __init__(self, enforce_external_nicknames=False): """Initialize stuff here""" ExternalAuth.__init__(self, enforce_external_nicknames) self.egroup_cache = None
def in_shibboleth(self, req): """ Return True if the current request handler is actually under Shibboleth control. """ return CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env def auth_user(self, username, password, req=None): """ Check USERNAME and PASSWORD against the SSO system. Return (None, None) if authentication failed, or the (email address, nickname) of the person if the authentication was successful. In order to do this you may perhaps have to keep a translation table between usernames and email addresses. If it is the first time the user logs in Invenio the nickname is stored alongside the email. If this nickname is unfortunatly already in use it is discarded. Otherwise it is ignored. Raise InvenioWebAccessExternalAuthError in case of external troubles. Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env: return req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE], req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE] return None, None #def user_exists(self, email, req=None): #"""Checks against CERN NICE/CRA for existance of email. #@return: True if the user exists, False otherwise #""" #users = self._try_twice(funct=AuthCernWrapper.list_users, \ #params={"display_name":email}) #return email.upper() in [user['email'].upper() for user in users] def fetch_user_groups_membership(self, email, password=None, req=None): """Fetch user groups membership from the SSO system. @return: a dictionary of groupname, group description Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ return self._fetch_egroups(req) def fetch_user_nickname(self, username, password=None, req=None): """Given a username and a password, returns the right nickname belonging to that user (username could be an email). Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE in req.subprocess_env: return req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE] else: return None def _fetch_egroups(self, req=None): if False: #self.egroup_cache is not None: return self.egroup_cache elif req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE in req.subprocess_env: groups = req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE].split(CFG_EXTERNAL_AUTH_SSO_GROUPS_SEPARATOR) # Filtering out uncomfortable groups groups = [group for group in groups if group not in CFG_EXTERNAL_AUTH_HIDDEN_GROUPS] for regexp in CFG_EXTERNAL_AUTH_HIDDEN_GROUPS_RE: for group in groups: if regexp.match(group): groups.remove(group) self.egroup_cache = dict(map(lambda x: (x, '@' in x and x + ' (Mailing list)' \ or x + ' (Group)'), groups)) return self.egroup_cache return {} def _fetch_particular_preferences(self, req=None): """This hidden method is there to be overwritten in order to get some particular value from non standard variables. """ if req: ret = {} req.add_common_vars() if 'HTTP_SHIB_AUTHENTICATION_METHOD' in req.subprocess_env: ret['authmethod'] = req.subprocess_env['HTTP_SHIB_AUTHENTICATION_METHOD'] ret['external'] = '1' if 'ADFS_IDENTITYCLASS' in req.subprocess_env and \ req.subprocess_env['ADFS_IDENTITYCLASS'] in ('CERN Registered', 'CERN Shared'): ret['external'] = '0' return ret return {} def fetch_user_preferences(self, username, password=None, req=None): """Fetch user preferences/settings from the SSO account. the external key will be '1' if the account is external to SSO, otherwise 0 @return: a dictionary. Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() ret = {} prefs = self._fetch_particular_preferences(req) for key, value in req.subprocess_env.items(): for prefix in CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES: if key.startswith(prefix) and not key == CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE: prefs[key[len(prefix):].lower()] = value break for key, value in prefs.items(): if key in CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS: ret['HIDDEN_' + key] = value else: ret[key] = value return ret return {}
random_line_split
sso.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """External user authentication for CERN NICE/CRA Invenio.""" __revision__ = \ "$Id$" import re from invenio.legacy.external_authentication import ExternalAuth # Tunable list of settings to be hidden ## e.g.: CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS = ('auth', 'respccid', 'personid') CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS = () # Tunable list of groups to be hidden CFG_EXTERNAL_AUTH_HIDDEN_GROUPS = ( 'All Exchange People', 'CERN Users', 'cern-computing-postmasters', 'cern-nice2000-postmasters', 'CMF FrontEnd Users', 'CMF_NSC_259_NSU', 'Domain Users', 'GP Apply Favorites Redirection', 'GP Apply NoAdmin', 'info-terminalservices', 'info-terminalservices-members', 'IT Web IT', 'NICE Deny Enforce Password-protected Screensaver', 'NICE Enforce Password-protected Screensaver', 'NICE LightWeight Authentication WS Users', 'NICE MyDocuments Redirection (New)', 'NICE Profile Redirection', 'NICE Terminal Services Users', 'NICE Users', 'NICE VPN Users', ) CFG_EXTERNAL_AUTH_HIDDEN_GROUPS_RE = ( re.compile(r'Users by Letter [A-Z]'), re.compile(r'building-[\d]+'), re.compile(r'Users by Home CERNHOME[A-Z]'), ) # Prefix name for Shibboleth variables CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES = ('ADFS_', 'Shib-') # Name of the variable containing groups CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'GROUP' # Name of the variable containing login name CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'LOGIN' # Name of the variable containing email CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'EMAIL' # Name of the variable containing groups CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'GROUP' # Separator character for group variable CFG_EXTERNAL_AUTH_SSO_GROUPS_SEPARATOR = ';' class ExternalAuthSSO(ExternalAuth): """ External authentication example for a custom SSO-based authentication service. """ def __init__(self, enforce_external_nicknames=False): """Initialize stuff here""" ExternalAuth.__init__(self, enforce_external_nicknames) self.egroup_cache = None def in_shibboleth(self, req): """ Return True if the current request handler is actually under Shibboleth control. """ return CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env def
(self, username, password, req=None): """ Check USERNAME and PASSWORD against the SSO system. Return (None, None) if authentication failed, or the (email address, nickname) of the person if the authentication was successful. In order to do this you may perhaps have to keep a translation table between usernames and email addresses. If it is the first time the user logs in Invenio the nickname is stored alongside the email. If this nickname is unfortunatly already in use it is discarded. Otherwise it is ignored. Raise InvenioWebAccessExternalAuthError in case of external troubles. Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env: return req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE], req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE] return None, None #def user_exists(self, email, req=None): #"""Checks against CERN NICE/CRA for existance of email. #@return: True if the user exists, False otherwise #""" #users = self._try_twice(funct=AuthCernWrapper.list_users, \ #params={"display_name":email}) #return email.upper() in [user['email'].upper() for user in users] def fetch_user_groups_membership(self, email, password=None, req=None): """Fetch user groups membership from the SSO system. @return: a dictionary of groupname, group description Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ return self._fetch_egroups(req) def fetch_user_nickname(self, username, password=None, req=None): """Given a username and a password, returns the right nickname belonging to that user (username could be an email). Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE in req.subprocess_env: return req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE] else: return None def _fetch_egroups(self, req=None): if False: #self.egroup_cache is not None: return self.egroup_cache elif req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE in req.subprocess_env: groups = req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE].split(CFG_EXTERNAL_AUTH_SSO_GROUPS_SEPARATOR) # Filtering out uncomfortable groups groups = [group for group in groups if group not in CFG_EXTERNAL_AUTH_HIDDEN_GROUPS] for regexp in CFG_EXTERNAL_AUTH_HIDDEN_GROUPS_RE: for group in groups: if regexp.match(group): groups.remove(group) self.egroup_cache = dict(map(lambda x: (x, '@' in x and x + ' (Mailing list)' \ or x + ' (Group)'), groups)) return self.egroup_cache return {} def _fetch_particular_preferences(self, req=None): """This hidden method is there to be overwritten in order to get some particular value from non standard variables. """ if req: ret = {} req.add_common_vars() if 'HTTP_SHIB_AUTHENTICATION_METHOD' in req.subprocess_env: ret['authmethod'] = req.subprocess_env['HTTP_SHIB_AUTHENTICATION_METHOD'] ret['external'] = '1' if 'ADFS_IDENTITYCLASS' in req.subprocess_env and \ req.subprocess_env['ADFS_IDENTITYCLASS'] in ('CERN Registered', 'CERN Shared'): ret['external'] = '0' return ret return {} def fetch_user_preferences(self, username, password=None, req=None): """Fetch user preferences/settings from the SSO account. the external key will be '1' if the account is external to SSO, otherwise 0 @return: a dictionary. Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() ret = {} prefs = self._fetch_particular_preferences(req) for key, value in req.subprocess_env.items(): for prefix in CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES: if key.startswith(prefix) and not key == CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE: prefs[key[len(prefix):].lower()] = value break for key, value in prefs.items(): if key in CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS: ret['HIDDEN_' + key] = value else: ret[key] = value return ret return {}
auth_user
identifier_name
sso.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """External user authentication for CERN NICE/CRA Invenio.""" __revision__ = \ "$Id$" import re from invenio.legacy.external_authentication import ExternalAuth # Tunable list of settings to be hidden ## e.g.: CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS = ('auth', 'respccid', 'personid') CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS = () # Tunable list of groups to be hidden CFG_EXTERNAL_AUTH_HIDDEN_GROUPS = ( 'All Exchange People', 'CERN Users', 'cern-computing-postmasters', 'cern-nice2000-postmasters', 'CMF FrontEnd Users', 'CMF_NSC_259_NSU', 'Domain Users', 'GP Apply Favorites Redirection', 'GP Apply NoAdmin', 'info-terminalservices', 'info-terminalservices-members', 'IT Web IT', 'NICE Deny Enforce Password-protected Screensaver', 'NICE Enforce Password-protected Screensaver', 'NICE LightWeight Authentication WS Users', 'NICE MyDocuments Redirection (New)', 'NICE Profile Redirection', 'NICE Terminal Services Users', 'NICE Users', 'NICE VPN Users', ) CFG_EXTERNAL_AUTH_HIDDEN_GROUPS_RE = ( re.compile(r'Users by Letter [A-Z]'), re.compile(r'building-[\d]+'), re.compile(r'Users by Home CERNHOME[A-Z]'), ) # Prefix name for Shibboleth variables CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES = ('ADFS_', 'Shib-') # Name of the variable containing groups CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'GROUP' # Name of the variable containing login name CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'LOGIN' # Name of the variable containing email CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'EMAIL' # Name of the variable containing groups CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE = CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES[0] + 'GROUP' # Separator character for group variable CFG_EXTERNAL_AUTH_SSO_GROUPS_SEPARATOR = ';' class ExternalAuthSSO(ExternalAuth): """ External authentication example for a custom SSO-based authentication service. """ def __init__(self, enforce_external_nicknames=False): """Initialize stuff here""" ExternalAuth.__init__(self, enforce_external_nicknames) self.egroup_cache = None def in_shibboleth(self, req):
def auth_user(self, username, password, req=None): """ Check USERNAME and PASSWORD against the SSO system. Return (None, None) if authentication failed, or the (email address, nickname) of the person if the authentication was successful. In order to do this you may perhaps have to keep a translation table between usernames and email addresses. If it is the first time the user logs in Invenio the nickname is stored alongside the email. If this nickname is unfortunatly already in use it is discarded. Otherwise it is ignored. Raise InvenioWebAccessExternalAuthError in case of external troubles. Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env: return req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE], req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE] return None, None #def user_exists(self, email, req=None): #"""Checks against CERN NICE/CRA for existance of email. #@return: True if the user exists, False otherwise #""" #users = self._try_twice(funct=AuthCernWrapper.list_users, \ #params={"display_name":email}) #return email.upper() in [user['email'].upper() for user in users] def fetch_user_groups_membership(self, email, password=None, req=None): """Fetch user groups membership from the SSO system. @return: a dictionary of groupname, group description Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ return self._fetch_egroups(req) def fetch_user_nickname(self, username, password=None, req=None): """Given a username and a password, returns the right nickname belonging to that user (username could be an email). Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE in req.subprocess_env: return req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_LOGIN_VARIABLE] else: return None def _fetch_egroups(self, req=None): if False: #self.egroup_cache is not None: return self.egroup_cache elif req: req.add_common_vars() if CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE in req.subprocess_env: groups = req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE].split(CFG_EXTERNAL_AUTH_SSO_GROUPS_SEPARATOR) # Filtering out uncomfortable groups groups = [group for group in groups if group not in CFG_EXTERNAL_AUTH_HIDDEN_GROUPS] for regexp in CFG_EXTERNAL_AUTH_HIDDEN_GROUPS_RE: for group in groups: if regexp.match(group): groups.remove(group) self.egroup_cache = dict(map(lambda x: (x, '@' in x and x + ' (Mailing list)' \ or x + ' (Group)'), groups)) return self.egroup_cache return {} def _fetch_particular_preferences(self, req=None): """This hidden method is there to be overwritten in order to get some particular value from non standard variables. """ if req: ret = {} req.add_common_vars() if 'HTTP_SHIB_AUTHENTICATION_METHOD' in req.subprocess_env: ret['authmethod'] = req.subprocess_env['HTTP_SHIB_AUTHENTICATION_METHOD'] ret['external'] = '1' if 'ADFS_IDENTITYCLASS' in req.subprocess_env and \ req.subprocess_env['ADFS_IDENTITYCLASS'] in ('CERN Registered', 'CERN Shared'): ret['external'] = '0' return ret return {} def fetch_user_preferences(self, username, password=None, req=None): """Fetch user preferences/settings from the SSO account. the external key will be '1' if the account is external to SSO, otherwise 0 @return: a dictionary. Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req: req.add_common_vars() ret = {} prefs = self._fetch_particular_preferences(req) for key, value in req.subprocess_env.items(): for prefix in CFG_EXTERNAL_AUTH_SSO_PREFIX_NAMES: if key.startswith(prefix) and not key == CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE: prefs[key[len(prefix):].lower()] = value break for key, value in prefs.items(): if key in CFG_EXTERNAL_AUTH_HIDDEN_SETTINGS: ret['HIDDEN_' + key] = value else: ret[key] = value return ret return {}
""" Return True if the current request handler is actually under Shibboleth control. """ return CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env
identifier_body
get-latest-version.js
// Copyright 2019 Google Inc. // // 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 // <https://apache.org/licenses/LICENSE-2.0>. // // Unless required by applicable law or agreed to in writing, software
// 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. 'use strict'; const get = require('../../shared/get.js'); const predictFileName = require('./predict-file-name.js'); const getLatestVersion = (os) => { const fileName = predictFileName(os); const url = `https://storage.googleapis.com/chromium-v8/official/canary/v8-${ fileName}-rel-latest.json`; return new Promise(async (resolve, reject) => { try { const response = await get(url, { json: true, }); const data = response.body; const version = data.version; resolve(version); } catch (error) { reject(error); } }); }; module.exports = getLatestVersion;
// distributed under the License is distributed on an “AS IS” BASIS,
random_line_split
buffer.rs
use std::io; use crossbeam::sync::MsQueue; // Ensures that we have enough buffers to keep workers busy. const TOTAL_BUFFERS_MULTIPLICATIVE: usize = 2; const TOTAL_BUFFERS_ADDITIVE: usize = 0; /// Stores a set number of piece buffers to be used and re-used. pub struct PieceBuffers { piece_queue: MsQueue<PieceBuffer>, } impl PieceBuffers { /// Create a new queue filled with a number of piece buffers based on the number of workers. pub fn new(piece_length: usize, num_workers: usize) -> PieceBuffers { let piece_queue = MsQueue::new(); let total_buffers = calculate_total_buffers(num_workers); for _ in 0..total_buffers { piece_queue.push(PieceBuffer::new(piece_length)); } PieceBuffers { piece_queue: piece_queue } } /// Checkin the given piece buffer to be re-used. pub fn checkin(&self, mut buffer: PieceBuffer) { buffer.bytes_read = 0; self.piece_queue.push(buffer); } /// Checkout a piece buffer (possibly blocking) to be used. pub fn checkout(&self) -> PieceBuffer { self.piece_queue.pop() } } /// Calculates the optimal number of piece buffers given the number of workers. fn
(num_workers: usize) -> usize { num_workers * TOTAL_BUFFERS_MULTIPLICATIVE + TOTAL_BUFFERS_ADDITIVE } // ----------------------------------------------------------------------------// /// Piece buffer that can be filled up until it contains a full piece. #[derive(PartialEq, Eq)] pub struct PieceBuffer { buffer: Vec<u8>, bytes_read: usize, } impl PieceBuffer { /// Create a new piece buffer. fn new(piece_length: usize) -> PieceBuffer { PieceBuffer { buffer: vec![0u8; piece_length], bytes_read: 0, } } pub fn write_bytes<C>(&mut self, mut callback: C) -> io::Result<usize> where C: FnMut(&mut [u8]) -> io::Result<usize> { let new_bytes_read = try!(callback(&mut self.buffer[self.bytes_read..])); self.bytes_read += new_bytes_read; Ok(new_bytes_read) } /// Whether or not the given piece buffer is full. pub fn is_whole(&self) -> bool { self.bytes_read == self.buffer.len() } /// Whether or not the given piece buffer is empty. pub fn is_empty(&self) -> bool { self.bytes_read == 0 } /// Access the piece buffer as a byte slice. pub fn as_slice(&self) -> &[u8] { &self.buffer[..self.bytes_read] } }
calculate_total_buffers
identifier_name
buffer.rs
use std::io; use crossbeam::sync::MsQueue; // Ensures that we have enough buffers to keep workers busy. const TOTAL_BUFFERS_MULTIPLICATIVE: usize = 2; const TOTAL_BUFFERS_ADDITIVE: usize = 0; /// Stores a set number of piece buffers to be used and re-used. pub struct PieceBuffers { piece_queue: MsQueue<PieceBuffer>, } impl PieceBuffers { /// Create a new queue filled with a number of piece buffers based on the number of workers. pub fn new(piece_length: usize, num_workers: usize) -> PieceBuffers { let piece_queue = MsQueue::new(); let total_buffers = calculate_total_buffers(num_workers); for _ in 0..total_buffers { piece_queue.push(PieceBuffer::new(piece_length)); } PieceBuffers { piece_queue: piece_queue } } /// Checkin the given piece buffer to be re-used. pub fn checkin(&self, mut buffer: PieceBuffer) { buffer.bytes_read = 0; self.piece_queue.push(buffer); } /// Checkout a piece buffer (possibly blocking) to be used. pub fn checkout(&self) -> PieceBuffer
} /// Calculates the optimal number of piece buffers given the number of workers. fn calculate_total_buffers(num_workers: usize) -> usize { num_workers * TOTAL_BUFFERS_MULTIPLICATIVE + TOTAL_BUFFERS_ADDITIVE } // ----------------------------------------------------------------------------// /// Piece buffer that can be filled up until it contains a full piece. #[derive(PartialEq, Eq)] pub struct PieceBuffer { buffer: Vec<u8>, bytes_read: usize, } impl PieceBuffer { /// Create a new piece buffer. fn new(piece_length: usize) -> PieceBuffer { PieceBuffer { buffer: vec![0u8; piece_length], bytes_read: 0, } } pub fn write_bytes<C>(&mut self, mut callback: C) -> io::Result<usize> where C: FnMut(&mut [u8]) -> io::Result<usize> { let new_bytes_read = try!(callback(&mut self.buffer[self.bytes_read..])); self.bytes_read += new_bytes_read; Ok(new_bytes_read) } /// Whether or not the given piece buffer is full. pub fn is_whole(&self) -> bool { self.bytes_read == self.buffer.len() } /// Whether or not the given piece buffer is empty. pub fn is_empty(&self) -> bool { self.bytes_read == 0 } /// Access the piece buffer as a byte slice. pub fn as_slice(&self) -> &[u8] { &self.buffer[..self.bytes_read] } }
{ self.piece_queue.pop() }
identifier_body
buffer.rs
use std::io; use crossbeam::sync::MsQueue; // Ensures that we have enough buffers to keep workers busy. const TOTAL_BUFFERS_MULTIPLICATIVE: usize = 2; const TOTAL_BUFFERS_ADDITIVE: usize = 0; /// Stores a set number of piece buffers to be used and re-used. pub struct PieceBuffers { piece_queue: MsQueue<PieceBuffer>, } impl PieceBuffers { /// Create a new queue filled with a number of piece buffers based on the number of workers. pub fn new(piece_length: usize, num_workers: usize) -> PieceBuffers { let piece_queue = MsQueue::new(); let total_buffers = calculate_total_buffers(num_workers); for _ in 0..total_buffers { piece_queue.push(PieceBuffer::new(piece_length));
PieceBuffers { piece_queue: piece_queue } } /// Checkin the given piece buffer to be re-used. pub fn checkin(&self, mut buffer: PieceBuffer) { buffer.bytes_read = 0; self.piece_queue.push(buffer); } /// Checkout a piece buffer (possibly blocking) to be used. pub fn checkout(&self) -> PieceBuffer { self.piece_queue.pop() } } /// Calculates the optimal number of piece buffers given the number of workers. fn calculate_total_buffers(num_workers: usize) -> usize { num_workers * TOTAL_BUFFERS_MULTIPLICATIVE + TOTAL_BUFFERS_ADDITIVE } // ----------------------------------------------------------------------------// /// Piece buffer that can be filled up until it contains a full piece. #[derive(PartialEq, Eq)] pub struct PieceBuffer { buffer: Vec<u8>, bytes_read: usize, } impl PieceBuffer { /// Create a new piece buffer. fn new(piece_length: usize) -> PieceBuffer { PieceBuffer { buffer: vec![0u8; piece_length], bytes_read: 0, } } pub fn write_bytes<C>(&mut self, mut callback: C) -> io::Result<usize> where C: FnMut(&mut [u8]) -> io::Result<usize> { let new_bytes_read = try!(callback(&mut self.buffer[self.bytes_read..])); self.bytes_read += new_bytes_read; Ok(new_bytes_read) } /// Whether or not the given piece buffer is full. pub fn is_whole(&self) -> bool { self.bytes_read == self.buffer.len() } /// Whether or not the given piece buffer is empty. pub fn is_empty(&self) -> bool { self.bytes_read == 0 } /// Access the piece buffer as a byte slice. pub fn as_slice(&self) -> &[u8] { &self.buffer[..self.bytes_read] } }
}
random_line_split
make.py
#!/usr/bin/python import os import shutil import zipfile import zlib import os.path def _ignore(src, name ): if src == './UPLOAD/': print name return ['RESTDIR', 'conf.inc.php', 'Nuked-Klan.zip', '.hg', 'make.py'] else: return [] def _RecImport(src, dst, zip):
elements.remove(delete) except ValueError: pass for ele in elements: if os.path.isfile(src + ele): zip.write(src + ele, dst + ele) print dst + ele elif os.path.isdir(src + ele): _RecImport(src + ele + '/', dst + ele + '/', zip) try: shutil.rmtree('tmp') except OSError: pass file = 'Nuked-Klan.zip' try: os.remove(file) except OSError: pass zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED, False) _RecImport('RESTDIR/', '/', zip) _RecImport('./', '/UPLOAD/', zip)
elements = os.listdir(src) ignored = _ignore('.' + dst, elements) for delete in ignored: try:
random_line_split
make.py
#!/usr/bin/python import os import shutil import zipfile import zlib import os.path def _ignore(src, name ): if src == './UPLOAD/': print name return ['RESTDIR', 'conf.inc.php', 'Nuked-Klan.zip', '.hg', 'make.py'] else: return [] def _RecImport(src, dst, zip): elements = os.listdir(src) ignored = _ignore('.' + dst, elements) for delete in ignored: try: elements.remove(delete) except ValueError: pass for ele in elements: if os.path.isfile(src + ele): zip.write(src + ele, dst + ele) print dst + ele elif os.path.isdir(src + ele):
try: shutil.rmtree('tmp') except OSError: pass file = 'Nuked-Klan.zip' try: os.remove(file) except OSError: pass zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED, False) _RecImport('RESTDIR/', '/', zip) _RecImport('./', '/UPLOAD/', zip)
_RecImport(src + ele + '/', dst + ele + '/', zip)
conditional_block
make.py
#!/usr/bin/python import os import shutil import zipfile import zlib import os.path def _ignore(src, name ): if src == './UPLOAD/': print name return ['RESTDIR', 'conf.inc.php', 'Nuked-Klan.zip', '.hg', 'make.py'] else: return [] def _RecImport(src, dst, zip):
try: shutil.rmtree('tmp') except OSError: pass file = 'Nuked-Klan.zip' try: os.remove(file) except OSError: pass zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED, False) _RecImport('RESTDIR/', '/', zip) _RecImport('./', '/UPLOAD/', zip)
elements = os.listdir(src) ignored = _ignore('.' + dst, elements) for delete in ignored: try: elements.remove(delete) except ValueError: pass for ele in elements: if os.path.isfile(src + ele): zip.write(src + ele, dst + ele) print dst + ele elif os.path.isdir(src + ele): _RecImport(src + ele + '/', dst + ele + '/', zip)
identifier_body
make.py
#!/usr/bin/python import os import shutil import zipfile import zlib import os.path def _ignore(src, name ): if src == './UPLOAD/': print name return ['RESTDIR', 'conf.inc.php', 'Nuked-Klan.zip', '.hg', 'make.py'] else: return [] def
(src, dst, zip): elements = os.listdir(src) ignored = _ignore('.' + dst, elements) for delete in ignored: try: elements.remove(delete) except ValueError: pass for ele in elements: if os.path.isfile(src + ele): zip.write(src + ele, dst + ele) print dst + ele elif os.path.isdir(src + ele): _RecImport(src + ele + '/', dst + ele + '/', zip) try: shutil.rmtree('tmp') except OSError: pass file = 'Nuked-Klan.zip' try: os.remove(file) except OSError: pass zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED, False) _RecImport('RESTDIR/', '/', zip) _RecImport('./', '/UPLOAD/', zip)
_RecImport
identifier_name
morautils.py
# Utility functions for OpenMORA scripts # # Part of OpenMora - https://github.com/OpenMORA import os, sys, string import platform import yaml def get_mora_paths(): """ Returns a list of paths with MORA modules, from the env var MORA_PATH """ if not 'MORA_PATH' in os.environ: print('**ERROR** Environment variable MORA_PATH not set') sys.exit(1) sMoraPaths=os.environ['MORA_PATH']; if platform.system()=="Windows": sPathDelim = ";" else: sPathDelim = ":" morabase_dir=""; return sMoraPaths.split(sPathDelim) def
(): """ Returns the path of "mora-base" pkg """ mora_paths = get_mora_paths() # Get env vars for p in mora_paths: tstPath = os.path.normpath(p + "/mora-base") if os.path.exists(tstPath): morabase_dir = tstPath if (len(morabase_dir)==0) or (not os.path.exists(morabase_dir)): print("Couldn't detect mora-base in MORA_PATH!!") sys.exit(1) return morabase_dir import sys, math def progress(percent): ''' source: http://gunslingerc0de.wordpress.com/2010/08/13/python-command-line-progress-bar/ ''' width = 74 marks = math.floor(width * (percent / 100.0)) spaces = math.floor(width - marks) loader = '[' + ('=' * int(marks)) + (' ' * int(spaces)) + ']' if percent >= 100: percent = 100 sys.stdout.write("%s %d%%\r" % (loader, percent)) if percent >= 100: pass sys.stdout.write("\n") sys.stdout.flush() def get_pkgs_root(): '''Returns the path to the parent directory of mora-base''' morabase_dir = get_morabase_dir() pkgs_root = os.path.dirname(morabase_dir) return pkgs_root def read_distro_file(): '''Returns the yaml contents of the distro file''' morabase_dir = get_morabase_dir() pkgs_root = os.path.dirname(morabase_dir) sDistroFile = os.path.normpath( morabase_dir + "/distro/openmora-pkgs.yaml") assert os.path.exists(sDistroFile) assert os.path.exists(pkgs_root + "/mora-base") # Parse distro file: fil = open(sDistroFile, 'r') distro = yaml.load(fil) fil.close() #print distro return distro
get_morabase_dir
identifier_name
morautils.py
# Utility functions for OpenMORA scripts # # Part of OpenMora - https://github.com/OpenMORA import os, sys, string import platform import yaml def get_mora_paths(): """ Returns a list of paths with MORA modules, from the env var MORA_PATH """ if not 'MORA_PATH' in os.environ: print('**ERROR** Environment variable MORA_PATH not set') sys.exit(1) sMoraPaths=os.environ['MORA_PATH']; if platform.system()=="Windows": sPathDelim = ";" else: sPathDelim = ":" morabase_dir=""; return sMoraPaths.split(sPathDelim) def get_morabase_dir(): """ Returns the path of "mora-base" pkg """ mora_paths = get_mora_paths() # Get env vars for p in mora_paths: tstPath = os.path.normpath(p + "/mora-base") if os.path.exists(tstPath): morabase_dir = tstPath if (len(morabase_dir)==0) or (not os.path.exists(morabase_dir)): print("Couldn't detect mora-base in MORA_PATH!!") sys.exit(1) return morabase_dir import sys, math def progress(percent): ''' source: http://gunslingerc0de.wordpress.com/2010/08/13/python-command-line-progress-bar/ ''' width = 74 marks = math.floor(width * (percent / 100.0))
if percent >= 100: percent = 100 sys.stdout.write("%s %d%%\r" % (loader, percent)) if percent >= 100: pass sys.stdout.write("\n") sys.stdout.flush() def get_pkgs_root(): '''Returns the path to the parent directory of mora-base''' morabase_dir = get_morabase_dir() pkgs_root = os.path.dirname(morabase_dir) return pkgs_root def read_distro_file(): '''Returns the yaml contents of the distro file''' morabase_dir = get_morabase_dir() pkgs_root = os.path.dirname(morabase_dir) sDistroFile = os.path.normpath( morabase_dir + "/distro/openmora-pkgs.yaml") assert os.path.exists(sDistroFile) assert os.path.exists(pkgs_root + "/mora-base") # Parse distro file: fil = open(sDistroFile, 'r') distro = yaml.load(fil) fil.close() #print distro return distro
spaces = math.floor(width - marks) loader = '[' + ('=' * int(marks)) + (' ' * int(spaces)) + ']'
random_line_split
morautils.py
# Utility functions for OpenMORA scripts # # Part of OpenMora - https://github.com/OpenMORA import os, sys, string import platform import yaml def get_mora_paths(): """ Returns a list of paths with MORA modules, from the env var MORA_PATH """ if not 'MORA_PATH' in os.environ: print('**ERROR** Environment variable MORA_PATH not set') sys.exit(1) sMoraPaths=os.environ['MORA_PATH']; if platform.system()=="Windows": sPathDelim = ";" else: sPathDelim = ":" morabase_dir=""; return sMoraPaths.split(sPathDelim) def get_morabase_dir(): """ Returns the path of "mora-base" pkg """ mora_paths = get_mora_paths() # Get env vars for p in mora_paths: tstPath = os.path.normpath(p + "/mora-base") if os.path.exists(tstPath): morabase_dir = tstPath if (len(morabase_dir)==0) or (not os.path.exists(morabase_dir)): print("Couldn't detect mora-base in MORA_PATH!!") sys.exit(1) return morabase_dir import sys, math def progress(percent): ''' source: http://gunslingerc0de.wordpress.com/2010/08/13/python-command-line-progress-bar/ ''' width = 74 marks = math.floor(width * (percent / 100.0)) spaces = math.floor(width - marks) loader = '[' + ('=' * int(marks)) + (' ' * int(spaces)) + ']' if percent >= 100: percent = 100 sys.stdout.write("%s %d%%\r" % (loader, percent)) if percent >= 100: pass sys.stdout.write("\n") sys.stdout.flush() def get_pkgs_root():
def read_distro_file(): '''Returns the yaml contents of the distro file''' morabase_dir = get_morabase_dir() pkgs_root = os.path.dirname(morabase_dir) sDistroFile = os.path.normpath( morabase_dir + "/distro/openmora-pkgs.yaml") assert os.path.exists(sDistroFile) assert os.path.exists(pkgs_root + "/mora-base") # Parse distro file: fil = open(sDistroFile, 'r') distro = yaml.load(fil) fil.close() #print distro return distro
'''Returns the path to the parent directory of mora-base''' morabase_dir = get_morabase_dir() pkgs_root = os.path.dirname(morabase_dir) return pkgs_root
identifier_body
morautils.py
# Utility functions for OpenMORA scripts # # Part of OpenMora - https://github.com/OpenMORA import os, sys, string import platform import yaml def get_mora_paths(): """ Returns a list of paths with MORA modules, from the env var MORA_PATH """ if not 'MORA_PATH' in os.environ: print('**ERROR** Environment variable MORA_PATH not set') sys.exit(1) sMoraPaths=os.environ['MORA_PATH']; if platform.system()=="Windows": sPathDelim = ";" else: sPathDelim = ":" morabase_dir=""; return sMoraPaths.split(sPathDelim) def get_morabase_dir(): """ Returns the path of "mora-base" pkg """ mora_paths = get_mora_paths() # Get env vars for p in mora_paths: tstPath = os.path.normpath(p + "/mora-base") if os.path.exists(tstPath): morabase_dir = tstPath if (len(morabase_dir)==0) or (not os.path.exists(morabase_dir)):
return morabase_dir import sys, math def progress(percent): ''' source: http://gunslingerc0de.wordpress.com/2010/08/13/python-command-line-progress-bar/ ''' width = 74 marks = math.floor(width * (percent / 100.0)) spaces = math.floor(width - marks) loader = '[' + ('=' * int(marks)) + (' ' * int(spaces)) + ']' if percent >= 100: percent = 100 sys.stdout.write("%s %d%%\r" % (loader, percent)) if percent >= 100: pass sys.stdout.write("\n") sys.stdout.flush() def get_pkgs_root(): '''Returns the path to the parent directory of mora-base''' morabase_dir = get_morabase_dir() pkgs_root = os.path.dirname(morabase_dir) return pkgs_root def read_distro_file(): '''Returns the yaml contents of the distro file''' morabase_dir = get_morabase_dir() pkgs_root = os.path.dirname(morabase_dir) sDistroFile = os.path.normpath( morabase_dir + "/distro/openmora-pkgs.yaml") assert os.path.exists(sDistroFile) assert os.path.exists(pkgs_root + "/mora-base") # Parse distro file: fil = open(sDistroFile, 'r') distro = yaml.load(fil) fil.close() #print distro return distro
print("Couldn't detect mora-base in MORA_PATH!!") sys.exit(1)
conditional_block
app.module.ts
import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { File } from '@ionic-native/file'; import { AboutPage } from '../pages/about/about'; import { ContactPage } from '../pages/contact/contact'; import { Inicio } from '../pages/inicio/inicio'; import { TabsPage } from '../pages/tabs/tabs'; import { NativeAudio } from '@ionic-native/native-audio'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; @NgModule({ declarations: [ MyApp, AboutPage, ContactPage, Inicio, TabsPage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, AboutPage, ContactPage, Inicio, TabsPage ], providers: [ StatusBar, SplashScreen, File, NativeAudio, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class
{}
AppModule
identifier_name
app.module.ts
import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { File } from '@ionic-native/file'; import { AboutPage } from '../pages/about/about'; import { ContactPage } from '../pages/contact/contact'; import { Inicio } from '../pages/inicio/inicio'; import { TabsPage } from '../pages/tabs/tabs'; import { NativeAudio } from '@ionic-native/native-audio'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; @NgModule({ declarations: [ MyApp, AboutPage, ContactPage, Inicio, TabsPage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, AboutPage, ContactPage, Inicio, TabsPage ],
providers: [ StatusBar, SplashScreen, File, NativeAudio, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {}
random_line_split
consts.py
#!/usr/bin/python # # Copyright (C) 2006-2018 Wyplay, All Rights Reserved. # This file is part of xbuilder. # # xbuilder is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # xbuilder 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; see file COPYING. # If not, see <http://www.gnu.org/licenses/>. # # import os XBUILDER_SYS_CFG = '/etc/xbuilder.conf' XBUILDER_USER_CFG = os.path.expanduser('~/.xbuilder.conf') XBUILDER_LOGFILE = 'build.log' XBUILDER_REPORT_FILE = 'report.xml.bz2' XBUILDER_DEFTYPE = 'beta' XBUILDER_TARGET_COMMIT = False # Default values that can be modified in the config file # Keep only N beta releases, put 0 to disable XBUILDER_MAX_BETA_TARGETS = 5 XBUILDER_CLEAN_WORKDIR = True XBUILDER_TARGET_COMMIT = True XBUILDER_FEATURES = '' XBUILDER_WORKDIR = '/usr/targets/xbuilder' XBUILDER_ARCHIVE_DIR = '/opt/xbuilder' XBUILDER_COMPRESSION = 'xz' XBUILDER_MAIL_FROM = 'builder@wyplay.com' XBUILDER_MAIL_TO = 'integration@wyplay.com' XBUILDER_MAIL_SMTP = 'localhost' XBUILDER_MAIL_LOG_SIZE = 20 * 1024 XBUILDER_MAIL_URI = 'http://localhost/genbox-ng/xbuilder' XBUILDER_NOTIFIER_URI = 'http://localhost:9999/xbuilder' XBUILDER_TYPES = ['beta', 'release']
XBUILDER_GPG_LOGFILE = 'gpg.log' XBUILDER_GPG_LOGLEVEL = 20 # logging.INFO
random_line_split
257. Binary Tree Paths.js
/* Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-leaf paths are: ["1->2->5", "1->3"] Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. */ /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {string[]} */ var binaryTreePaths = function(root) { var result = []; if(!root){ return []; } traverseTree(root,""); return result; function traverseTree(node,str){ if( node.left === null && node.right === null ){ result.push( str+node.val ); } else
} }; //tag: Google Facebook Apple
{ if( node.left !== null ){ traverseTree( node.left, str + node.val + '->' ); } if( node.right !== null ){ traverseTree( node.right, str + node.val + '->' ); } }
conditional_block
257. Binary Tree Paths.js
/* Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-leaf paths are: ["1->2->5", "1->3"] Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. */ /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {string[]} */ var binaryTreePaths = function(root) { var result = []; if(!root){ return []; } traverseTree(root,""); return result; function
(node,str){ if( node.left === null && node.right === null ){ result.push( str+node.val ); } else{ if( node.left !== null ){ traverseTree( node.left, str + node.val + '->' ); } if( node.right !== null ){ traverseTree( node.right, str + node.val + '->' ); } } } }; //tag: Google Facebook Apple
traverseTree
identifier_name
257. Binary Tree Paths.js
/* Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-leaf paths are: ["1->2->5", "1->3"] Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. */ /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {string[]} */ var binaryTreePaths = function(root) { var result = []; if(!root){ return []; } traverseTree(root,""); return result; function traverseTree(node,str)
}; //tag: Google Facebook Apple
{ if( node.left === null && node.right === null ){ result.push( str+node.val ); } else{ if( node.left !== null ){ traverseTree( node.left, str + node.val + '->' ); } if( node.right !== null ){ traverseTree( node.right, str + node.val + '->' ); } } }
identifier_body
257. Binary Tree Paths.js
/* Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1
/ \ 2 3 \ 5 All root-to-leaf paths are: ["1->2->5", "1->3"] Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. */ /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {string[]} */ var binaryTreePaths = function(root) { var result = []; if(!root){ return []; } traverseTree(root,""); return result; function traverseTree(node,str){ if( node.left === null && node.right === null ){ result.push( str+node.val ); } else{ if( node.left !== null ){ traverseTree( node.left, str + node.val + '->' ); } if( node.right !== null ){ traverseTree( node.right, str + node.val + '->' ); } } } }; //tag: Google Facebook Apple
random_line_split
console.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <alberto@migasfree.org> # Copyright (c) 2015-2016 Jose Antonio Chavarría <jachavar@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window):
sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): self.hide() return True
def __init__(self): super(Console, self).__init__()
random_line_split
console.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <alberto@migasfree.org> # Copyright (c) 2015-2016 Jose Antonio Chavarría <jachavar@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): se
lf.hide() return True
identifier_body
console.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <alberto@migasfree.org> # Copyright (c) 2015-2016 Jose Antonio Chavarría <jachavar@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on
elf, widget, data=None): self.hide() return True
_click_hide(s
identifier_name
day_10.rs
pub use tdd_kata::stack_kata::day_10::Stack; describe! stack_tests { before_each { let mut stack: Stack<i32> = Stack::new(20); } it "should create a new empty stack" { assert_eq!(stack.size(), 0); assert!(stack.is_empty()); } it "should increase stack size when push into it" { let old_size = stack.size(); stack.push(10); assert_eq!(stack.size(), old_size + 1); assert!(!stack.is_empty());
it "should decrease stack size when pop from it" { stack.push(20); let old_size = stack.size(); stack.pop(); assert_eq!(stack.size(), old_size - 1); } it "should pop value that was pushed into the stack" { stack.push(20); assert_eq!(stack.pop(), Some(20)); stack.push(10); assert_eq!(stack.pop(), Some(10)); } it "should pop value last that was pushed first into the stack" { stack.push(10); stack.push(20); stack.push(30); stack.push(40); stack.push(50); assert_eq!(stack.pop(), Some(50)); assert_eq!(stack.pop(), Some(40)); assert_eq!(stack.pop(), Some(30)); assert_eq!(stack.pop(), Some(20)); assert_eq!(stack.pop(), Some(10)); } }
}
random_line_split