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
Layout.js
// Generated by CoffeeScript 1.9.3 var Block, Layout, SpecialString, fn, i, len, object, prop, ref, terminalWidth;
object = require('utila').object; SpecialString = require('./layout/SpecialString'); terminalWidth = require('./tools').getCols(); module.exports = Layout = (function() { var self; self = Layout; Layout._rootBlockDefaultConfig = { linePrependor: { options: { amount: 0 } }, lineAppendor: { options: { amount: 0 } }, blockPrependor: { options: { amount: 0 } }, blockAppendor: { options: { amount: 0 } } }; Layout._defaultConfig = { terminalWidth: terminalWidth }; function Layout(config, rootBlockConfig) { var rootConfig; if (config == null) { config = {}; } if (rootBlockConfig == null) { rootBlockConfig = {}; } this._written = []; this._activeBlock = null; this._config = object.append(self._defaultConfig, config); rootConfig = object.append(self._rootBlockDefaultConfig, rootBlockConfig); this._root = new Block(this, null, rootConfig, '__root'); this._root._open(); } Layout.prototype.getRootBlock = function() { return this._root; }; Layout.prototype._append = function(text) { return this._written.push(text); }; Layout.prototype._appendLine = function(text) { var s; this._append(text); s = SpecialString(text); if (s.length < this._config.terminalWidth) { this._append('<none>\n</none>'); } return this; }; Layout.prototype.get = function() { this._ensureClosed(); if (this._written[this._written.length - 1] === '<none>\n</none>') { this._written.pop(); } return this._written.join(""); }; Layout.prototype._ensureClosed = function() { if (this._activeBlock !== this._root) { throw Error("Not all the blocks have been closed. Please call block.close() on all open blocks."); } if (this._root.isOpen()) { this._root.close(); } }; return Layout; })(); ref = ['openBlock', 'write']; fn = function() { var method; method = prop; return Layout.prototype[method] = function() { return this._root[method].apply(this._root, arguments); }; }; for (i = 0, len = ref.length; i < len; i++) { prop = ref[i]; fn(); }
Block = require('./layout/Block');
random_line_split
Layout.js
// Generated by CoffeeScript 1.9.3 var Block, Layout, SpecialString, fn, i, len, object, prop, ref, terminalWidth; Block = require('./layout/Block'); object = require('utila').object; SpecialString = require('./layout/SpecialString'); terminalWidth = require('./tools').getCols(); module.exports = Layout = (function() { var self; self = Layout; Layout._rootBlockDefaultConfig = { linePrependor: { options: { amount: 0 } }, lineAppendor: { options: { amount: 0 } }, blockPrependor: { options: { amount: 0 } }, blockAppendor: { options: { amount: 0 } } }; Layout._defaultConfig = { terminalWidth: terminalWidth }; function Layout(config, rootBlockConfig) { var rootConfig; if (config == null) { config = {}; } if (rootBlockConfig == null)
this._written = []; this._activeBlock = null; this._config = object.append(self._defaultConfig, config); rootConfig = object.append(self._rootBlockDefaultConfig, rootBlockConfig); this._root = new Block(this, null, rootConfig, '__root'); this._root._open(); } Layout.prototype.getRootBlock = function() { return this._root; }; Layout.prototype._append = function(text) { return this._written.push(text); }; Layout.prototype._appendLine = function(text) { var s; this._append(text); s = SpecialString(text); if (s.length < this._config.terminalWidth) { this._append('<none>\n</none>'); } return this; }; Layout.prototype.get = function() { this._ensureClosed(); if (this._written[this._written.length - 1] === '<none>\n</none>') { this._written.pop(); } return this._written.join(""); }; Layout.prototype._ensureClosed = function() { if (this._activeBlock !== this._root) { throw Error("Not all the blocks have been closed. Please call block.close() on all open blocks."); } if (this._root.isOpen()) { this._root.close(); } }; return Layout; })(); ref = ['openBlock', 'write']; fn = function() { var method; method = prop; return Layout.prototype[method] = function() { return this._root[method].apply(this._root, arguments); }; }; for (i = 0, len = ref.length; i < len; i++) { prop = ref[i]; fn(); }
{ rootBlockConfig = {}; }
conditional_block
lib.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> /*! Bindings and wrappers for __GTK__ To implement __GTK+__ inheritance in rust, we implemented gtk superclasses as traits located in `rgtk::self::traits::*`. The various widgets implement these traits and live in `rgtk::gtk::widgets::*` and are rexported into `rgtk::gtk::*`. GTK Inheritance in rgtk ====================== You probably know but __Gtk+__ uses its own GObject system: inherited class and interface. To respect this design I follow a special design on __rgtk__: * Interface -> Implement them on a trait with only default methods. * Class -> Implement the construct on the class impl and other methods on a traits. * Sub-class -> Implement all the methods on the class. Exemple for GtkOrientable, GtkBox, GtkButtonBox: GtkOrientable is an interface with all the methods implemented as default method of the trait self::traits::Orientable. GtkBox is a class with constructors implemented on the struct `gtk::Box`, and the other method as default methods of the trait `self::traits::Box`. So `gtk::Box` implements `self::traits::Orientable` and `self::traits::Box`. GtkButtonBox is a sub-class of GtkBox, the struct `gtk::ButtonBox` implements all the methods of GtkButtonBox and the traits `self::traits::Orientable` and `self::traits::Box`. Finally all the gtk widgets implement the trait self::traits::Widget. */ //#![macro_use] #![allow(dead_code)] // TODO: drop this #![allow(raw_pointer_derive)] extern crate libc; extern crate glib_sys as glib_ffi; extern crate gobject_sys as gobject_ffi; extern crate gio_sys as gio_ffi; extern crate gdk_sys as gdk_ffi; extern crate gdk_pixbuf_sys as gdk_pixbuf_ffi; extern crate gtk_sys as ffi; extern crate cairo_sys as cairo_ffi; extern crate pango_sys as pango_ffi; extern crate glib; extern crate gdk; extern crate cairo; extern crate pango; pub use glib::ValuePublic; // These are/should be inlined pub use self::rt::{ init, main, main_quit, main_level, main_iteration, main_iteration_do, get_major_version, get_minor_version, get_micro_version, get_binary_age, get_interface_age, check_version, events_pending }; /// GTK Widgets for all versions pub use self::widgets::{ CssProvider, StyleContext, Widget, Window, Label, Button, Box, ButtonBox, Frame, AspectFrame, Fixed, Separator, FontButton, ToggleButton, CheckButton, ColorButton, LinkButton, Adjustment, ScaleButton, VolumeButton, Grid, EntryBuffer, Entry, Switch,
ProgressBar, Arrow, Calendar, Alignment, Expander, Paned, InfoBar, Toolbar, ToolItem, SeparatorToolItem, ToolButton, ToggleToolButton, MenuToolButton, Dialog, AboutDialog, ColorChooserDialog, FontChooserDialog, MessageDialog, NoteBook, Overlay, Layout, FileFilter, FileChooserDialog, AppInfo, AppLaunchContext, AppChooserDialog, DrawingArea, PageSetup, PaperSize, PrintSettings, RecentChooserDialog, //PageSetupUnixDialog RecentInfo, RecentFilter, RecentFilterInfo, RecentData, RecentManager, TextView, TextBuffer, TextTagTable, ScrolledWindow, RadioButton, TreeView, TreeViewColumn, TreePath, TreeIter, TreeModel, ListStore, TreeStore, MenuItem, SeparatorMenuItem, CheckMenuItem, ScrollBar, Viewport, StatusBar, CellRendererText, CellRendererToggle, LockButton, EntryCompletion, IconView, TreeSelection, RecentChooserWidget, ComboBox, //g_type, ComboBoxText, TextMark, TextTag, TextAttributes, TextIter, TextChildAnchor, ToolPalette, ToolItemGroup, SizeGroup, AppChooserWidget, FileChooserWidget, ColorChooserWidget, FontChooserWidget, EventBox }; #[cfg(target_os = "linux")] pub use self::widgets::{Socket}; #[cfg(gtk_3_6)] /// GTK Widgets for versions since GTK 3.6 pub use self::widgets::{ MenuButton, LevelBar, }; #[cfg(gtk_3_10)] /// GTK Widgets for versions since GTK 3.10 pub use self::widgets::{ SearchEntry, SearchBar, Stack, StackSwitcher, Revealer, HeaderBar, ListBox, ListBoxRow, PlacesSidebar }; #[cfg(gtk_3_12)] /// GTK Widgets for versions since GTK 3.12 pub use self::widgets::{ FlowBox, FlowBoxChild, ActionBar, Popover }; /// GTK Enum types pub use ffi::GtkAccelFlags as AccelFlags; pub use ffi::GtkAlign as Align; pub use ffi::GtkArrowPlacement as ArrowPlacement; pub use ffi::GtkArrowType as ArrowType; pub use ffi::GtkAttachOptions as AttachOptions; pub use ffi::GtkBorderStyle as BorderStyle; pub use ffi::GtkBuilderError as BuilderError; pub use ffi::GtkButtonBoxStyle as ButtonBoxStyle; pub use ffi::GtkButtonsType as ButtonsType; pub use ffi::GtkCalendarDisplayOptions as CalendarDisplayOptions; pub use ffi::GtkCellRendererState as CellRendererState; pub use ffi::GtkCornerType as CornerType; pub use ffi::GtkDeleteType as DeleteType; pub use ffi::GtkDestDefaults as DestDefaults; pub use ffi::GtkDialogFlags as DialogFlags; pub use ffi::GtkDirectionType as DirectionType; pub use ffi::GtkDragResult as DragResult; pub use ffi::GtkEntryIconPosition as EntryIconPosition; pub use ffi::GtkExpanderStyle as ExpanderStyle; pub use ffi::GtkFileChooserAction as FileChooserAction; pub use ffi::GtkFileFilterFlags as FileFilterFlags; pub use ffi::GtkIMPreeditStyle as IMPreeditStyle; pub use ffi::GtkIMStatusStyle as IMStatusStyle; pub use ffi::GtkIconSize as IconSize; pub use ffi::GtkIconViewDropPosition as IconViewDropPosition; pub use ffi::GtkImageType as ImageType; pub use ffi::GtkInputHints as InputHints; pub use ffi::GtkInputPurpose as InputPurpose; pub use ffi::GtkJunctionSides as JunctionSides; pub use ffi::GtkJustification as Justification; pub use ffi::GtkLevelBarMode as LevelBarMode; pub use ffi::GtkLicense as License; pub use ffi::GtkMessageType as MessageType; pub use ffi::GtkMovementStep as MovementStep; pub use ffi::GtkNumberUpLayout as NumberUpLayout; pub use ffi::GtkOrientation as Orientation; pub use ffi::GtkPackType as PackType; pub use ffi::GtkPageOrientation as PageOrientation; pub use ffi::GtkPageSet as PageSet; pub use ffi::GtkPathPriorityType as PathPriorityType; pub use ffi::GtkPathType as PathType; pub use ffi::GtkPlacesOpenFlags as PlacesOpenFlags; pub use ffi::GtkPolicyType as PolicyType; pub use ffi::GtkPositionType as PositionType; pub use ffi::GtkPrintPages as PrintPages; pub use ffi::GtkRecentFilterFlags as RecentFilterFlags; pub use ffi::GtkRecentSortType as RecentSortType; pub use ffi::GtkRegionFlags as RegionFlags; pub use ffi::GtkReliefStyle as ReliefStyle; pub use ffi::GtkResizeMode as ResizeMode; pub use ffi::GtkResponseType as ResponseType; pub use ffi::GtkRevealerTransitionType as RevealerTransitionType; pub use ffi::GtkScrollStep as ScrollStep; pub use ffi::GtkScrollType as ScrollType; pub use ffi::GtkScrollablePolicy as ScrollablePolicy; pub use ffi::GtkSelectionMode as SelectionMode; pub use ffi::GtkSensitivityType as SensitivityType; pub use ffi::GtkShadowType as ShadowType; pub use ffi::GtkSizeGroupMode as SizeGroupMode; pub use ffi::GtkSizeRequestMode as SizeRequestMode; pub use ffi::GtkSortType as SortType; pub use ffi::GtkSpinButtonUpdatePolicy as SpinButtonUpdatePolicy; pub use ffi::GtkSpinType as SpinType; pub use ffi::GtkStackTransitionType as StackTransitionType; pub use ffi::GtkStateFlags as StateFlags; pub use ffi::GtkStateType as StateType; pub use ffi::GtkTextDirection as TextDirection; pub use ffi::GtkTextSearchFlags as TextSearchFlags; pub use ffi::GtkTextWindowType as TextWindowType; pub use ffi::GtkToolPaletteDragTargets as ToolPaletteDragTargets; pub use ffi::GtkToolbarStyle as ToolbarStyle; pub use ffi::GtkTreeModelFlags as TreeModelFlags; pub use ffi::GtkTreeViewColumnSizing as TreeViewColumnSizing; pub use ffi::GtkTreeViewGridLines as TreeViewGridLines; pub use ffi::GtkUnit as Unit; pub use ffi::GtkWidgetHelpType as WidgetHelpType; pub use ffi::GtkWindowPosition as WindowPosition; pub use ffi::GtkWindowType as WindowType; pub use ffi::GtkWrapMode as WrapMode; /// Gtk Traits pub use self::traits::FFIWidget; pub use self::traits::StyleProviderTrait; pub use self::traits::GObjectTrait; pub use self::traits::BoxTrait; pub use self::traits::ActionableTrait; pub use self::traits::AppChooserTrait; pub use self::traits::BinTrait; pub use self::traits::ButtonTrait; pub use self::traits::ButtonSignals; pub use self::traits::CellEditableTrait; pub use self::traits::CellLayoutTrait; pub use self::traits::CellRendererTrait; pub use self::traits::CheckMenuItemTrait; pub use self::traits::ColorChooserTrait; pub use self::traits::ComboBoxTrait; pub use self::traits::ContainerTrait; pub use self::traits::DialogButtons; pub use self::traits::DialogTrait; pub use self::traits::EditableTrait; pub use self::traits::EntryTrait; pub use self::traits::FileChooserTrait; pub use self::traits::FontChooserTrait; pub use self::traits::FrameTrait; pub use self::traits::LabelTrait; pub use self::traits::MenuItemTrait; pub use self::traits::MenuShellTrait; pub use self::traits::MiscTrait; pub use self::traits::OrientableTrait; pub use self::traits::RangeTrait; pub use self::traits::RecentChooserTrait; pub use self::traits::ScaleButtonTrait; pub use self::traits::ScrollableTrait; pub use self::traits::ScrolledWindowTrait; pub use self::traits::TextBufferTrait; pub use self::traits::ToggleButtonTrait; pub use self::traits::ToggleToolButtonTrait; pub use self::traits::ToolButtonTrait; pub use self::traits::ToolButtonSignals; pub use self::traits::ToolItemTrait; pub use self::traits::ToolShellTrait; pub use self::traits::WidgetTrait; pub use self::traits::WidgetSignals; pub use self::traits::WindowTrait; pub use self::traits::style_provider::{ STYLE_PROVIDER_PRIORITY_FALLBACK, STYLE_PROVIDER_PRIORITY_THEME, STYLE_PROVIDER_PRIORITY_SETTINGS, STYLE_PROVIDER_PRIORITY_APPLICATION, STYLE_PROVIDER_PRIORITY_USER }; pub const DIALOG_MODAL: DialogFlags = ffi::GTK_DIALOG_MODAL; /// GTK various struct pub use self::types::{ Tooltip, }; mod macros; mod cast; mod rt; pub mod traits; pub mod signal; pub mod widgets; pub mod types;
Range, Scale, SpinButton, Spinner, Image,
random_line_split
json_utils.ts
/* * Copyright 2019 ThoughtWorks, 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {mixins as s} from "helpers/string-plus"; export class JsonUtils { static
(o: object): any { return JSON.parse(this.toSnakeCasedJSON(o)); } static toSnakeCasedJSON(o: object): string { return JSON.stringify(o, s.snakeCaser); } static toCamelCasedObject(o: object): any { return JSON.parse(this.toCamelCasedJSON(o)); } static toCamelCasedJSON(o: object): string { return JSON.stringify(o, s.camelCaser); } }
toSnakeCasedObject
identifier_name
json_utils.ts
/* * Copyright 2019 ThoughtWorks, 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 * * 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. */
export class JsonUtils { static toSnakeCasedObject(o: object): any { return JSON.parse(this.toSnakeCasedJSON(o)); } static toSnakeCasedJSON(o: object): string { return JSON.stringify(o, s.snakeCaser); } static toCamelCasedObject(o: object): any { return JSON.parse(this.toCamelCasedJSON(o)); } static toCamelCasedJSON(o: object): string { return JSON.stringify(o, s.camelCaser); } }
import {mixins as s} from "helpers/string-plus";
random_line_split
json_utils.ts
/* * Copyright 2019 ThoughtWorks, 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {mixins as s} from "helpers/string-plus"; export class JsonUtils { static toSnakeCasedObject(o: object): any { return JSON.parse(this.toSnakeCasedJSON(o)); } static toSnakeCasedJSON(o: object): string { return JSON.stringify(o, s.snakeCaser); } static toCamelCasedObject(o: object): any
static toCamelCasedJSON(o: object): string { return JSON.stringify(o, s.camelCaser); } }
{ return JSON.parse(this.toCamelCasedJSON(o)); }
identifier_body
ListNoSelectSample.js
enyo.kind({ name: "enyo.sample.ListNoSelectSample", classes: "list-sample enyo-fit", components: [ {name: "list", kind: "List", count: 20000, noSelect: true, multiSelect: false, classes: "enyo-fit list-sample-list", onSetupItem: "setupItem", components: [ {name: "item", classes: "list-sample-item enyo-border-box", components: [ {name: "index", classes: "list-sample-index"}, {name: "name"} ]} ]} ], names: [],
// make some mock data if we have none for this row if (!this.names[i]) { this.names[i] = makeName(5, 10, '', ''); } var n = this.names[i]; var ni = ("00000000" + i).slice(-7); this.$.name.setContent(n); this.$.index.setContent(ni); } });
setupItem: function(inSender, inEvent) { // this is the row we're setting up var i = inEvent.index;
random_line_split
ListNoSelectSample.js
enyo.kind({ name: "enyo.sample.ListNoSelectSample", classes: "list-sample enyo-fit", components: [ {name: "list", kind: "List", count: 20000, noSelect: true, multiSelect: false, classes: "enyo-fit list-sample-list", onSetupItem: "setupItem", components: [ {name: "item", classes: "list-sample-item enyo-border-box", components: [ {name: "index", classes: "list-sample-index"}, {name: "name"} ]} ]} ], names: [], setupItem: function(inSender, inEvent) { // this is the row we're setting up var i = inEvent.index; // make some mock data if we have none for this row if (!this.names[i])
var n = this.names[i]; var ni = ("00000000" + i).slice(-7); this.$.name.setContent(n); this.$.index.setContent(ni); } });
{ this.names[i] = makeName(5, 10, '', ''); }
conditional_block
C.controller.js
sap.ui.define([ 'jquery.sap.global', 'sap/ui/core/Fragment', 'sap/ui/core/mvc/Controller', 'sap/ui/model/Filter', 'sap/ui/model/json/JSONModel' ], function(jQuery, Fragment, Controller, Filter, JSONModel) { "use strict"; var CController = Controller.extend("sap.m.sample.InputAssistedTwoValues.C", { inputId: '', onInit: function () { // set explored app's demo model on this sample var oModel = new JSONModel(jQuery.sap.getModulePath("sap.ui.demo.mock", "/products.json")); this.getView().setModel(oModel); }, handleValueHelp : function (oController) { this.inputId = oController.oSource.sId; // create value help dialog if (!this._valueHelpDialog) { this._valueHelpDialog = sap.ui.xmlfragment( "sap.m.sample.InputAssistedTwoValues.Dialog", this ); this.getView().addDependent(this._valueHelpDialog); } // open value help dialog this._valueHelpDialog.open(); }, _handleValueHelpSearch : function (evt) { var sValue = evt.getParameter("value"); var oFilter = new Filter( "Name", sap.ui.model.FilterOperator.Contains, sValue ); evt.getSource().getBinding("items").filter([oFilter]); }, _handleValueHelpClose : function (evt) { var oSelectedItem = evt.getParameter("selectedItem"); if (oSelectedItem) { var productInput = this.byId(this.inputId); productInput.setValue(oSelectedItem.getTitle()); } evt.getSource().getBinding("items").filter([]); } }); return CController;
});
random_line_split
C.controller.js
sap.ui.define([ 'jquery.sap.global', 'sap/ui/core/Fragment', 'sap/ui/core/mvc/Controller', 'sap/ui/model/Filter', 'sap/ui/model/json/JSONModel' ], function(jQuery, Fragment, Controller, Filter, JSONModel) { "use strict"; var CController = Controller.extend("sap.m.sample.InputAssistedTwoValues.C", { inputId: '', onInit: function () { // set explored app's demo model on this sample var oModel = new JSONModel(jQuery.sap.getModulePath("sap.ui.demo.mock", "/products.json")); this.getView().setModel(oModel); }, handleValueHelp : function (oController) { this.inputId = oController.oSource.sId; // create value help dialog if (!this._valueHelpDialog)
// open value help dialog this._valueHelpDialog.open(); }, _handleValueHelpSearch : function (evt) { var sValue = evt.getParameter("value"); var oFilter = new Filter( "Name", sap.ui.model.FilterOperator.Contains, sValue ); evt.getSource().getBinding("items").filter([oFilter]); }, _handleValueHelpClose : function (evt) { var oSelectedItem = evt.getParameter("selectedItem"); if (oSelectedItem) { var productInput = this.byId(this.inputId); productInput.setValue(oSelectedItem.getTitle()); } evt.getSource().getBinding("items").filter([]); } }); return CController; });
{ this._valueHelpDialog = sap.ui.xmlfragment( "sap.m.sample.InputAssistedTwoValues.Dialog", this ); this.getView().addDependent(this._valueHelpDialog); }
conditional_block
long-stack-trace.ts
'use strict'; (function() { const NEWLINE = '\n'; const SEP = ' ------------- '; const IGNORE_FRAMES = []; const creationTrace = '__creationTrace__'; class LongStackTrace { error: Error = getStacktrace(); timestamp: Date = new Date(); } function getStacktraceWithUncaughtError (): Error { return new Error('STACKTRACE TRACKING'); } function getStacktraceWithCaughtError(): Error { try { throw getStacktraceWithUncaughtError(); } catch (e) { return e; } } // Some implementations of exception handling don't create a stack trace if the exception // isn't thrown, however it's faster not to actually throw the exception. const error = getStacktraceWithUncaughtError(); const coughtError = getStacktraceWithCaughtError(); const getStacktrace = error.stack ? getStacktraceWithUncaughtError : (coughtError.stack ? getStacktraceWithCaughtError: getStacktraceWithUncaughtError); function getFrames(error: Error): string[] { return error.stack ? error.stack.split(NEWLINE) : []; } function addErrorStack(lines:string[], error:Error):void { let trace: string[] = getFrames(error); for (let i = 0; i < trace.length; i++) { const frame = trace[i]; // Filter out the Frames which are part of stack capturing. if (! (i < IGNORE_FRAMES.length && IGNORE_FRAMES[i] === frame)) { lines.push(trace[i]); } } } function renderLongStackTrace(frames: LongStackTrace[], stack: string): string { const longTrace: string[] = [stack]; if (frames) { let timestamp = new Date().getTime(); for (let i = 0; i < frames.length; i++) { const traceFrames: LongStackTrace = frames[i]; const lastTime = traceFrames.timestamp; longTrace.push(`${SEP} Elapsed: ${timestamp - lastTime.getTime()} ms; At: ${lastTime} ${SEP}`); addErrorStack(longTrace, traceFrames.error); timestamp = lastTime.getTime(); } } return longTrace.join(NEWLINE); } Zone['longStackTraceZoneSpec'] = <ZoneSpec>{ name: 'long-stack-trace', longStackTraceLimit: 10, // Max number of task to keep the stack trace for. onScheduleTask: function(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any { const currentTask = Zone.currentTask; let trace = currentTask && currentTask.data && currentTask.data[creationTrace] || []; trace = [new LongStackTrace()].concat(trace); if (trace.length > this.longStackTraceLimit) { trace.length = this.longStackTraceLimit; } if (!task.data) task.data = {}; task.data[creationTrace] = trace; return parentZoneDelegate.scheduleTask(targetZone, task); }, onHandleError: function(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any): any { const parentTask = Zone.currentTask || error.task; if (error instanceof Error && parentTask) { var stackSetSucceded: string|boolean = null; try { let descriptor = Object.getOwnPropertyDescriptor(error, 'stack'); if (descriptor && descriptor.configurable) { const delegateGet = descriptor.get; const value = descriptor.value; descriptor = { get: function () { return renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], delegateGet ? delegateGet.apply(this) : value); } }; Object.defineProperty(error, 'stack', descriptor); stackSetSucceded = true; } } catch (e) { } var longStack: string = stackSetSucceded ? null : renderLongStackTrace( parentTask.data && parentTask.data[creationTrace], error.stack); if (!stackSetSucceded) { try { stackSetSucceded = error.stack = longStack; } catch (e) { } } if (!stackSetSucceded) { try { stackSetSucceded = (error as any).longStack = longStack; } catch (e) { } } } return parentZoneDelegate.handleError(targetZone, error); } }; function captureStackTraces(stackTraces: string[][], count: number): void { if (count > 0) { stackTraces.push(getFrames((new LongStackTrace()).error)); captureStackTraces(stackTraces, count - 1); } } function computeIgnoreFrames() { const frames: string[][] = []; captureStackTraces(frames, 2); const frames1 = frames[0]; const frames2 = frames[1]; for (let i = 0; i < frames1.length; i++) { const frame1 = frames1[i]; const frame2 = frames2[i]; if (frame1 === frame2) { IGNORE_FRAMES.push(frame1); } else { break; }
} computeIgnoreFrames(); })();
}
random_line_split
long-stack-trace.ts
'use strict'; (function() { const NEWLINE = '\n'; const SEP = ' ------------- '; const IGNORE_FRAMES = []; const creationTrace = '__creationTrace__'; class LongStackTrace { error: Error = getStacktrace(); timestamp: Date = new Date(); } function getStacktraceWithUncaughtError (): Error { return new Error('STACKTRACE TRACKING'); } function getStacktraceWithCaughtError(): Error { try { throw getStacktraceWithUncaughtError(); } catch (e) { return e; } } // Some implementations of exception handling don't create a stack trace if the exception // isn't thrown, however it's faster not to actually throw the exception. const error = getStacktraceWithUncaughtError(); const coughtError = getStacktraceWithCaughtError(); const getStacktrace = error.stack ? getStacktraceWithUncaughtError : (coughtError.stack ? getStacktraceWithCaughtError: getStacktraceWithUncaughtError); function getFrames(error: Error): string[] { return error.stack ? error.stack.split(NEWLINE) : []; } function addErrorStack(lines:string[], error:Error):void { let trace: string[] = getFrames(error); for (let i = 0; i < trace.length; i++) { const frame = trace[i]; // Filter out the Frames which are part of stack capturing. if (! (i < IGNORE_FRAMES.length && IGNORE_FRAMES[i] === frame)) { lines.push(trace[i]); } } } function renderLongStackTrace(frames: LongStackTrace[], stack: string): string { const longTrace: string[] = [stack]; if (frames) { let timestamp = new Date().getTime(); for (let i = 0; i < frames.length; i++) { const traceFrames: LongStackTrace = frames[i]; const lastTime = traceFrames.timestamp; longTrace.push(`${SEP} Elapsed: ${timestamp - lastTime.getTime()} ms; At: ${lastTime} ${SEP}`); addErrorStack(longTrace, traceFrames.error); timestamp = lastTime.getTime(); } } return longTrace.join(NEWLINE); } Zone['longStackTraceZoneSpec'] = <ZoneSpec>{ name: 'long-stack-trace', longStackTraceLimit: 10, // Max number of task to keep the stack trace for. onScheduleTask: function(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any { const currentTask = Zone.currentTask; let trace = currentTask && currentTask.data && currentTask.data[creationTrace] || []; trace = [new LongStackTrace()].concat(trace); if (trace.length > this.longStackTraceLimit) { trace.length = this.longStackTraceLimit; } if (!task.data) task.data = {}; task.data[creationTrace] = trace; return parentZoneDelegate.scheduleTask(targetZone, task); }, onHandleError: function(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any): any { const parentTask = Zone.currentTask || error.task; if (error instanceof Error && parentTask) { var stackSetSucceded: string|boolean = null; try { let descriptor = Object.getOwnPropertyDescriptor(error, 'stack'); if (descriptor && descriptor.configurable) { const delegateGet = descriptor.get; const value = descriptor.value; descriptor = { get: function () { return renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], delegateGet ? delegateGet.apply(this) : value); } }; Object.defineProperty(error, 'stack', descriptor); stackSetSucceded = true; } } catch (e) { } var longStack: string = stackSetSucceded ? null : renderLongStackTrace( parentTask.data && parentTask.data[creationTrace], error.stack); if (!stackSetSucceded) { try { stackSetSucceded = error.stack = longStack; } catch (e) { } } if (!stackSetSucceded) { try { stackSetSucceded = (error as any).longStack = longStack; } catch (e) { } } } return parentZoneDelegate.handleError(targetZone, error); } }; function captureStackTraces(stackTraces: string[][], count: number): void { if (count > 0)
} function computeIgnoreFrames() { const frames: string[][] = []; captureStackTraces(frames, 2); const frames1 = frames[0]; const frames2 = frames[1]; for (let i = 0; i < frames1.length; i++) { const frame1 = frames1[i]; const frame2 = frames2[i]; if (frame1 === frame2) { IGNORE_FRAMES.push(frame1); } else { break; } } } computeIgnoreFrames(); })();
{ stackTraces.push(getFrames((new LongStackTrace()).error)); captureStackTraces(stackTraces, count - 1); }
conditional_block
long-stack-trace.ts
'use strict'; (function() { const NEWLINE = '\n'; const SEP = ' ------------- '; const IGNORE_FRAMES = []; const creationTrace = '__creationTrace__'; class
{ error: Error = getStacktrace(); timestamp: Date = new Date(); } function getStacktraceWithUncaughtError (): Error { return new Error('STACKTRACE TRACKING'); } function getStacktraceWithCaughtError(): Error { try { throw getStacktraceWithUncaughtError(); } catch (e) { return e; } } // Some implementations of exception handling don't create a stack trace if the exception // isn't thrown, however it's faster not to actually throw the exception. const error = getStacktraceWithUncaughtError(); const coughtError = getStacktraceWithCaughtError(); const getStacktrace = error.stack ? getStacktraceWithUncaughtError : (coughtError.stack ? getStacktraceWithCaughtError: getStacktraceWithUncaughtError); function getFrames(error: Error): string[] { return error.stack ? error.stack.split(NEWLINE) : []; } function addErrorStack(lines:string[], error:Error):void { let trace: string[] = getFrames(error); for (let i = 0; i < trace.length; i++) { const frame = trace[i]; // Filter out the Frames which are part of stack capturing. if (! (i < IGNORE_FRAMES.length && IGNORE_FRAMES[i] === frame)) { lines.push(trace[i]); } } } function renderLongStackTrace(frames: LongStackTrace[], stack: string): string { const longTrace: string[] = [stack]; if (frames) { let timestamp = new Date().getTime(); for (let i = 0; i < frames.length; i++) { const traceFrames: LongStackTrace = frames[i]; const lastTime = traceFrames.timestamp; longTrace.push(`${SEP} Elapsed: ${timestamp - lastTime.getTime()} ms; At: ${lastTime} ${SEP}`); addErrorStack(longTrace, traceFrames.error); timestamp = lastTime.getTime(); } } return longTrace.join(NEWLINE); } Zone['longStackTraceZoneSpec'] = <ZoneSpec>{ name: 'long-stack-trace', longStackTraceLimit: 10, // Max number of task to keep the stack trace for. onScheduleTask: function(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any { const currentTask = Zone.currentTask; let trace = currentTask && currentTask.data && currentTask.data[creationTrace] || []; trace = [new LongStackTrace()].concat(trace); if (trace.length > this.longStackTraceLimit) { trace.length = this.longStackTraceLimit; } if (!task.data) task.data = {}; task.data[creationTrace] = trace; return parentZoneDelegate.scheduleTask(targetZone, task); }, onHandleError: function(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any): any { const parentTask = Zone.currentTask || error.task; if (error instanceof Error && parentTask) { var stackSetSucceded: string|boolean = null; try { let descriptor = Object.getOwnPropertyDescriptor(error, 'stack'); if (descriptor && descriptor.configurable) { const delegateGet = descriptor.get; const value = descriptor.value; descriptor = { get: function () { return renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], delegateGet ? delegateGet.apply(this) : value); } }; Object.defineProperty(error, 'stack', descriptor); stackSetSucceded = true; } } catch (e) { } var longStack: string = stackSetSucceded ? null : renderLongStackTrace( parentTask.data && parentTask.data[creationTrace], error.stack); if (!stackSetSucceded) { try { stackSetSucceded = error.stack = longStack; } catch (e) { } } if (!stackSetSucceded) { try { stackSetSucceded = (error as any).longStack = longStack; } catch (e) { } } } return parentZoneDelegate.handleError(targetZone, error); } }; function captureStackTraces(stackTraces: string[][], count: number): void { if (count > 0) { stackTraces.push(getFrames((new LongStackTrace()).error)); captureStackTraces(stackTraces, count - 1); } } function computeIgnoreFrames() { const frames: string[][] = []; captureStackTraces(frames, 2); const frames1 = frames[0]; const frames2 = frames[1]; for (let i = 0; i < frames1.length; i++) { const frame1 = frames1[i]; const frame2 = frames2[i]; if (frame1 === frame2) { IGNORE_FRAMES.push(frame1); } else { break; } } } computeIgnoreFrames(); })();
LongStackTrace
identifier_name
testOnlyTheRequired.py
''' <TBTAF> <TestID>2021</TestID> <Tags>TBTAF,Discoverer,Textbook</Tags> </TBTAF> ''' ''' Created on 06/11/2015 @author: Nander ''' from common.test import TBTestCase from common.result import TBTAFResult from common.trace import TBTAFTrace from common.event import TBTAFEvent from common.enums.verdict_type import TBTAFVerdictType from common.enums.event_type import TBTAFEventType class DiscovererOnlyTheRequiredTest(TBTestCase):
''' classdocs ''' def __init__(self): ''' Constructor ''' self.testTimeout = 1984 def setup(self): TBTestCase.setup(self) print "Setup performed from DiscovererOnlyTheRequiredTest" self.testTrace = TBTAFTrace("DiscovererOnlyTheRequiredTest") self.testTrace.addEvent(TBTAFEvent(TBTAFEventType.INFO,"Setup performed from DiscovererOnlyTheRequiredTest",self.testTrace.getTraceSource())) def execute(self): TBTestCase.execute(self) print "Execute performed from DiscovererOnlyTheRequiredTest" self.testResult = TBTAFResult(TBTAFVerdictType.PASS,"DiscovererOnlyTheRequiredTest") def cleanup(self): TBTestCase.cleanup(self) print "Cleanup performed from DiscovererOnlyTheRequiredTest"
random_line_split
testOnlyTheRequired.py
''' <TBTAF> <TestID>2021</TestID> <Tags>TBTAF,Discoverer,Textbook</Tags> </TBTAF> ''' ''' Created on 06/11/2015 @author: Nander ''' from common.test import TBTestCase from common.result import TBTAFResult from common.trace import TBTAFTrace from common.event import TBTAFEvent from common.enums.verdict_type import TBTAFVerdictType from common.enums.event_type import TBTAFEventType class DiscovererOnlyTheRequiredTest(TBTestCase): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.testTimeout = 1984 def setup(self): TBTestCase.setup(self) print "Setup performed from DiscovererOnlyTheRequiredTest" self.testTrace = TBTAFTrace("DiscovererOnlyTheRequiredTest") self.testTrace.addEvent(TBTAFEvent(TBTAFEventType.INFO,"Setup performed from DiscovererOnlyTheRequiredTest",self.testTrace.getTraceSource())) def
(self): TBTestCase.execute(self) print "Execute performed from DiscovererOnlyTheRequiredTest" self.testResult = TBTAFResult(TBTAFVerdictType.PASS,"DiscovererOnlyTheRequiredTest") def cleanup(self): TBTestCase.cleanup(self) print "Cleanup performed from DiscovererOnlyTheRequiredTest"
execute
identifier_name
testOnlyTheRequired.py
''' <TBTAF> <TestID>2021</TestID> <Tags>TBTAF,Discoverer,Textbook</Tags> </TBTAF> ''' ''' Created on 06/11/2015 @author: Nander ''' from common.test import TBTestCase from common.result import TBTAFResult from common.trace import TBTAFTrace from common.event import TBTAFEvent from common.enums.verdict_type import TBTAFVerdictType from common.enums.event_type import TBTAFEventType class DiscovererOnlyTheRequiredTest(TBTestCase):
''' classdocs ''' def __init__(self): ''' Constructor ''' self.testTimeout = 1984 def setup(self): TBTestCase.setup(self) print "Setup performed from DiscovererOnlyTheRequiredTest" self.testTrace = TBTAFTrace("DiscovererOnlyTheRequiredTest") self.testTrace.addEvent(TBTAFEvent(TBTAFEventType.INFO,"Setup performed from DiscovererOnlyTheRequiredTest",self.testTrace.getTraceSource())) def execute(self): TBTestCase.execute(self) print "Execute performed from DiscovererOnlyTheRequiredTest" self.testResult = TBTAFResult(TBTAFVerdictType.PASS,"DiscovererOnlyTheRequiredTest") def cleanup(self): TBTestCase.cleanup(self) print "Cleanup performed from DiscovererOnlyTheRequiredTest"
identifier_body
rpg_operation.py
#!/usr/bin/env python """ RPG: Operation These are any operations we want to carry out from our YAML files. Operations are strings that are tied to Python code, to carry out things that arent possible to easily make YAML tags for directly. """ from rpg_log import Log import rpg_combat def HandleOperation(game, operation, data): """Handle the operation. Args: game: Game object operation: string, name of the operation to look up data: dict, data at the level the operation was specified in, which may contain information the operation needs to operate. Operation specific. """ # Pay for a room's night sleep if operation == 'RoomSleepPay': Log('RoomSleepPay: You are rested!') # Max up the player's current health #NOTE(g): Uses a percentage based increase from the game data. If not # present, assume full recovery. modifier = game.data['game'].get('sleep_regeneration_percent', 1.0) # Add the modified version of the full health game.player.health_current += game.player.attributes['health'] * modifier # Max out at full health if game.player.health_current > game.player.attributes['health']: game.player.health_current = game.player.attributes['health'] # No longer fatigued (running and such) game.player.fatigued = False # Combat with the Player elif operation == 'CombatPlayer': if game.dialogue: # If a map is specified for the encouter, then fight
else: Log('Operatino: CombatPlayer: Not initiated from Dialogue. Unknown actor.') # Close the Dialogue if operation == 'CloseDialogue': game.dialogue = None
map = data.get('map', None) # Set combat to be with the given actor game.combat = rpg_combat.Combat(game, [game.dialogue.actor], map=map) # Clear the dialogue. The time for talking is OVER! game.dialogue = None
conditional_block
rpg_operation.py
These are any operations we want to carry out from our YAML files. Operations are strings that are tied to Python code, to carry out things that arent possible to easily make YAML tags for directly. """ from rpg_log import Log import rpg_combat def HandleOperation(game, operation, data): """Handle the operation. Args: game: Game object operation: string, name of the operation to look up data: dict, data at the level the operation was specified in, which may contain information the operation needs to operate. Operation specific. """ # Pay for a room's night sleep if operation == 'RoomSleepPay': Log('RoomSleepPay: You are rested!') # Max up the player's current health #NOTE(g): Uses a percentage based increase from the game data. If not # present, assume full recovery. modifier = game.data['game'].get('sleep_regeneration_percent', 1.0) # Add the modified version of the full health game.player.health_current += game.player.attributes['health'] * modifier # Max out at full health if game.player.health_current > game.player.attributes['health']: game.player.health_current = game.player.attributes['health'] # No longer fatigued (running and such) game.player.fatigued = False # Combat with the Player elif operation == 'CombatPlayer': if game.dialogue: # If a map is specified for the encouter, then fight map = data.get('map', None) # Set combat to be with the given actor game.combat = rpg_combat.Combat(game, [game.dialogue.actor], map=map) # Clear the dialogue. The time for talking is OVER! game.dialogue = None else: Log('Operatino: CombatPlayer: Not initiated from Dialogue. Unknown actor.') # Close the Dialogue if operation == 'CloseDialogue': game.dialogue = None
#!/usr/bin/env python """ RPG: Operation
random_line_split
rpg_operation.py
#!/usr/bin/env python """ RPG: Operation These are any operations we want to carry out from our YAML files. Operations are strings that are tied to Python code, to carry out things that arent possible to easily make YAML tags for directly. """ from rpg_log import Log import rpg_combat def
(game, operation, data): """Handle the operation. Args: game: Game object operation: string, name of the operation to look up data: dict, data at the level the operation was specified in, which may contain information the operation needs to operate. Operation specific. """ # Pay for a room's night sleep if operation == 'RoomSleepPay': Log('RoomSleepPay: You are rested!') # Max up the player's current health #NOTE(g): Uses a percentage based increase from the game data. If not # present, assume full recovery. modifier = game.data['game'].get('sleep_regeneration_percent', 1.0) # Add the modified version of the full health game.player.health_current += game.player.attributes['health'] * modifier # Max out at full health if game.player.health_current > game.player.attributes['health']: game.player.health_current = game.player.attributes['health'] # No longer fatigued (running and such) game.player.fatigued = False # Combat with the Player elif operation == 'CombatPlayer': if game.dialogue: # If a map is specified for the encouter, then fight map = data.get('map', None) # Set combat to be with the given actor game.combat = rpg_combat.Combat(game, [game.dialogue.actor], map=map) # Clear the dialogue. The time for talking is OVER! game.dialogue = None else: Log('Operatino: CombatPlayer: Not initiated from Dialogue. Unknown actor.') # Close the Dialogue if operation == 'CloseDialogue': game.dialogue = None
HandleOperation
identifier_name
rpg_operation.py
#!/usr/bin/env python """ RPG: Operation These are any operations we want to carry out from our YAML files. Operations are strings that are tied to Python code, to carry out things that arent possible to easily make YAML tags for directly. """ from rpg_log import Log import rpg_combat def HandleOperation(game, operation, data):
"""Handle the operation. Args: game: Game object operation: string, name of the operation to look up data: dict, data at the level the operation was specified in, which may contain information the operation needs to operate. Operation specific. """ # Pay for a room's night sleep if operation == 'RoomSleepPay': Log('RoomSleepPay: You are rested!') # Max up the player's current health #NOTE(g): Uses a percentage based increase from the game data. If not # present, assume full recovery. modifier = game.data['game'].get('sleep_regeneration_percent', 1.0) # Add the modified version of the full health game.player.health_current += game.player.attributes['health'] * modifier # Max out at full health if game.player.health_current > game.player.attributes['health']: game.player.health_current = game.player.attributes['health'] # No longer fatigued (running and such) game.player.fatigued = False # Combat with the Player elif operation == 'CombatPlayer': if game.dialogue: # If a map is specified for the encouter, then fight map = data.get('map', None) # Set combat to be with the given actor game.combat = rpg_combat.Combat(game, [game.dialogue.actor], map=map) # Clear the dialogue. The time for talking is OVER! game.dialogue = None else: Log('Operatino: CombatPlayer: Not initiated from Dialogue. Unknown actor.') # Close the Dialogue if operation == 'CloseDialogue': game.dialogue = None
identifier_body
mongolian-vowel-separator.js
// Copyright (C) 2016 André Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-white-space description: > Mongolian Vowel Separator is not recognized as white space. info: | 11.2 White Space WhiteSpace :: <TAB> <VT> <FF> <SP> <NBSP> <ZWNBSP> <USP> <USP> ::
type: SyntaxError features: [u180e] ---*/ throw "Test262: This statement should not be evaluated."; // U+180E between "var" and "foo"; UTF8(0x180E) = 0xE1 0xA0 0x8E var᠎foo;
Other category “Zs” code points General Category of U+180E is “Cf” (Format). negative: phase: parse
random_line_split
hero-detail-8.component.ts
/* tslint:disable:component-class-suffix */ // #docregion imports import { Component, Input, OnChanges } from '@angular/core'; import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Address, Hero, states } from './data-model'; // #enddocregion imports @Component({ moduleId: module.id, selector: 'hero-detail-8', templateUrl: './hero-detail-8.component.html' }) // #docregion v8 export class HeroDetailComponent8 implements OnChanges { @Input() hero: Hero; heroForm: FormGroup; states = states; // #docregion ctor constructor(private fb: FormBuilder) { this.createForm(); this.logNameChange(); } // #enddocregion ctor createForm() { // #docregion secretLairs-form-array this.heroForm = this.fb.group({ name: ['', Validators.required ], secretLairs: this.fb.array([]), // <-- secretLairs as an empty FormArray power: '', sidekick: '' }); // #enddocregion secretLairs-form-array } logNameChange() {/* Coming soon */} // #docregion onchanges ngOnChanges() { this.heroForm.reset({ name: this.hero.name }); this.setAddresses(this.hero.addresses); } // #enddocregion onchanges // #docregion get-secret-lairs get secretLairs(): FormArray
; // #enddocregion get-secret-lairs // #docregion set-addresses setAddresses(addresses: Address[]) { const addressFGs = addresses.map(address => this.fb.group(address)); const addressFormArray = this.fb.array(addressFGs); this.heroForm.setControl('secretLairs', addressFormArray); } // #enddocregion set-addresses // #docregion add-lair addLair() { this.secretLairs.push(this.fb.group(new Address())); } // #enddocregion add-lair }
{ return this.heroForm.get('secretLairs') as FormArray; }
identifier_body
hero-detail-8.component.ts
/* tslint:disable:component-class-suffix */ // #docregion imports import { Component, Input, OnChanges } from '@angular/core'; import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Address, Hero, states } from './data-model'; // #enddocregion imports @Component({ moduleId: module.id, selector: 'hero-detail-8', templateUrl: './hero-detail-8.component.html' }) // #docregion v8 export class HeroDetailComponent8 implements OnChanges { @Input() hero: Hero; heroForm: FormGroup;
this.logNameChange(); } // #enddocregion ctor createForm() { // #docregion secretLairs-form-array this.heroForm = this.fb.group({ name: ['', Validators.required ], secretLairs: this.fb.array([]), // <-- secretLairs as an empty FormArray power: '', sidekick: '' }); // #enddocregion secretLairs-form-array } logNameChange() {/* Coming soon */} // #docregion onchanges ngOnChanges() { this.heroForm.reset({ name: this.hero.name }); this.setAddresses(this.hero.addresses); } // #enddocregion onchanges // #docregion get-secret-lairs get secretLairs(): FormArray { return this.heroForm.get('secretLairs') as FormArray; }; // #enddocregion get-secret-lairs // #docregion set-addresses setAddresses(addresses: Address[]) { const addressFGs = addresses.map(address => this.fb.group(address)); const addressFormArray = this.fb.array(addressFGs); this.heroForm.setControl('secretLairs', addressFormArray); } // #enddocregion set-addresses // #docregion add-lair addLair() { this.secretLairs.push(this.fb.group(new Address())); } // #enddocregion add-lair }
states = states; // #docregion ctor constructor(private fb: FormBuilder) { this.createForm();
random_line_split
hero-detail-8.component.ts
/* tslint:disable:component-class-suffix */ // #docregion imports import { Component, Input, OnChanges } from '@angular/core'; import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Address, Hero, states } from './data-model'; // #enddocregion imports @Component({ moduleId: module.id, selector: 'hero-detail-8', templateUrl: './hero-detail-8.component.html' }) // #docregion v8 export class HeroDetailComponent8 implements OnChanges { @Input() hero: Hero; heroForm: FormGroup; states = states; // #docregion ctor constructor(private fb: FormBuilder) { this.createForm(); this.logNameChange(); } // #enddocregion ctor createForm() { // #docregion secretLairs-form-array this.heroForm = this.fb.group({ name: ['', Validators.required ], secretLairs: this.fb.array([]), // <-- secretLairs as an empty FormArray power: '', sidekick: '' }); // #enddocregion secretLairs-form-array } logNameChange() {/* Coming soon */} // #docregion onchanges ngOnChanges() { this.heroForm.reset({ name: this.hero.name }); this.setAddresses(this.hero.addresses); } // #enddocregion onchanges // #docregion get-secret-lairs get
(): FormArray { return this.heroForm.get('secretLairs') as FormArray; }; // #enddocregion get-secret-lairs // #docregion set-addresses setAddresses(addresses: Address[]) { const addressFGs = addresses.map(address => this.fb.group(address)); const addressFormArray = this.fb.array(addressFGs); this.heroForm.setControl('secretLairs', addressFormArray); } // #enddocregion set-addresses // #docregion add-lair addLair() { this.secretLairs.push(this.fb.group(new Address())); } // #enddocregion add-lair }
secretLairs
identifier_name
test-conv-tonumber.js
/* * ToNumber() (E5 Section 9.3). * * Postfix increment changes its LHS, put returns ToNumber(oldValue) as the * expression value. Use this get ToNumber() indirectly. */ function tonumber(x) { var tmp = x; return tmp++; } function zeroSign(x) { if (x !== 0) { return 'nz'; } if (1 / x > 0) { return 'pos'; } else { return 'neg'; } } function test(x) { var num = tonumber(x); print(num, zeroSign(num)); } /*=== NaN nz 0 pos 1 nz 0 pos -1 nz 0 neg 0 pos 1 nz NaN nz Infinity nz -Infinity nz ===*/ test(undefined); test(null); test(true); test(false); test(-1); test(-0); test(+0); test(1); test(NaN); test(Number.POSITIVE_INFINITY); test(Number.NEGATIVE_INFINITY); /*=== -1 nz -1 nz 0 neg 0 pos 0 pos 1 nz 17 nz 19 nz -Infinity nz Infinity nz Infinity nz 3735928559 nz 3735928559 nz 3735928559 nz NaN nz ===*/ /* String to number */ test('-1'); test(' -1 '); // whitespace is trimmed test('-0'); test('+0'); test('0'); test('1'); test('000017'); // lead zeroes allowed, not interpreted as octal! test('000019'); test(' -Infinity'); test(' +Infinity'); test(' Infinity'); test('0xdeadbeef'); test('0Xdeadbeef'); test(' \n0xdeadbeef\n'); test(' \n0xdeadbeefg\n'); // trailing garbage not allowed -> NaN /*=== 83 nz 83 nz 83 nz 83 nz NaN nz 17 nz 17 nz 17 nz 17 nz NaN nz ===*/ /* In ES6 0o123, and 0b10001 are recognized. Whitespace is also allowed. * Note that whitespace is trimmed so these forms cannot be recognized * by just peeking at the first few characters. */ test('0o123'); test('0O123'); test('\n0o123 \t');
test('0b10001'); test('0B10001'); test('\t0b10001 \r\n'); test('\t0b0000010001 \r\n'); test('\t0b00000000000100012 \r\n'); // '2' is garbage to binary /* XXX: object coercion */
test('\n0o000000123 \t'); test('\n0o000000123 x\t');
random_line_split
test-conv-tonumber.js
/* * ToNumber() (E5 Section 9.3). * * Postfix increment changes its LHS, put returns ToNumber(oldValue) as the * expression value. Use this get ToNumber() indirectly. */ function tonumber(x)
function zeroSign(x) { if (x !== 0) { return 'nz'; } if (1 / x > 0) { return 'pos'; } else { return 'neg'; } } function test(x) { var num = tonumber(x); print(num, zeroSign(num)); } /*=== NaN nz 0 pos 1 nz 0 pos -1 nz 0 neg 0 pos 1 nz NaN nz Infinity nz -Infinity nz ===*/ test(undefined); test(null); test(true); test(false); test(-1); test(-0); test(+0); test(1); test(NaN); test(Number.POSITIVE_INFINITY); test(Number.NEGATIVE_INFINITY); /*=== -1 nz -1 nz 0 neg 0 pos 0 pos 1 nz 17 nz 19 nz -Infinity nz Infinity nz Infinity nz 3735928559 nz 3735928559 nz 3735928559 nz NaN nz ===*/ /* String to number */ test('-1'); test(' -1 '); // whitespace is trimmed test('-0'); test('+0'); test('0'); test('1'); test('000017'); // lead zeroes allowed, not interpreted as octal! test('000019'); test(' -Infinity'); test(' +Infinity'); test(' Infinity'); test('0xdeadbeef'); test('0Xdeadbeef'); test(' \n0xdeadbeef\n'); test(' \n0xdeadbeefg\n'); // trailing garbage not allowed -> NaN /*=== 83 nz 83 nz 83 nz 83 nz NaN nz 17 nz 17 nz 17 nz 17 nz NaN nz ===*/ /* In ES6 0o123, and 0b10001 are recognized. Whitespace is also allowed. * Note that whitespace is trimmed so these forms cannot be recognized * by just peeking at the first few characters. */ test('0o123'); test('0O123'); test('\n0o123 \t'); test('\n0o000000123 \t'); test('\n0o000000123 x\t'); test('0b10001'); test('0B10001'); test('\t0b10001 \r\n'); test('\t0b0000010001 \r\n'); test('\t0b00000000000100012 \r\n'); // '2' is garbage to binary /* XXX: object coercion */
{ var tmp = x; return tmp++; }
identifier_body
test-conv-tonumber.js
/* * ToNumber() (E5 Section 9.3). * * Postfix increment changes its LHS, put returns ToNumber(oldValue) as the * expression value. Use this get ToNumber() indirectly. */ function tonumber(x) { var tmp = x; return tmp++; } function zeroSign(x) { if (x !== 0) { return 'nz'; } if (1 / x > 0) { return 'pos'; } else
} function test(x) { var num = tonumber(x); print(num, zeroSign(num)); } /*=== NaN nz 0 pos 1 nz 0 pos -1 nz 0 neg 0 pos 1 nz NaN nz Infinity nz -Infinity nz ===*/ test(undefined); test(null); test(true); test(false); test(-1); test(-0); test(+0); test(1); test(NaN); test(Number.POSITIVE_INFINITY); test(Number.NEGATIVE_INFINITY); /*=== -1 nz -1 nz 0 neg 0 pos 0 pos 1 nz 17 nz 19 nz -Infinity nz Infinity nz Infinity nz 3735928559 nz 3735928559 nz 3735928559 nz NaN nz ===*/ /* String to number */ test('-1'); test(' -1 '); // whitespace is trimmed test('-0'); test('+0'); test('0'); test('1'); test('000017'); // lead zeroes allowed, not interpreted as octal! test('000019'); test(' -Infinity'); test(' +Infinity'); test(' Infinity'); test('0xdeadbeef'); test('0Xdeadbeef'); test(' \n0xdeadbeef\n'); test(' \n0xdeadbeefg\n'); // trailing garbage not allowed -> NaN /*=== 83 nz 83 nz 83 nz 83 nz NaN nz 17 nz 17 nz 17 nz 17 nz NaN nz ===*/ /* In ES6 0o123, and 0b10001 are recognized. Whitespace is also allowed. * Note that whitespace is trimmed so these forms cannot be recognized * by just peeking at the first few characters. */ test('0o123'); test('0O123'); test('\n0o123 \t'); test('\n0o000000123 \t'); test('\n0o000000123 x\t'); test('0b10001'); test('0B10001'); test('\t0b10001 \r\n'); test('\t0b0000010001 \r\n'); test('\t0b00000000000100012 \r\n'); // '2' is garbage to binary /* XXX: object coercion */
{ return 'neg'; }
conditional_block
test-conv-tonumber.js
/* * ToNumber() (E5 Section 9.3). * * Postfix increment changes its LHS, put returns ToNumber(oldValue) as the * expression value. Use this get ToNumber() indirectly. */ function tonumber(x) { var tmp = x; return tmp++; } function
(x) { if (x !== 0) { return 'nz'; } if (1 / x > 0) { return 'pos'; } else { return 'neg'; } } function test(x) { var num = tonumber(x); print(num, zeroSign(num)); } /*=== NaN nz 0 pos 1 nz 0 pos -1 nz 0 neg 0 pos 1 nz NaN nz Infinity nz -Infinity nz ===*/ test(undefined); test(null); test(true); test(false); test(-1); test(-0); test(+0); test(1); test(NaN); test(Number.POSITIVE_INFINITY); test(Number.NEGATIVE_INFINITY); /*=== -1 nz -1 nz 0 neg 0 pos 0 pos 1 nz 17 nz 19 nz -Infinity nz Infinity nz Infinity nz 3735928559 nz 3735928559 nz 3735928559 nz NaN nz ===*/ /* String to number */ test('-1'); test(' -1 '); // whitespace is trimmed test('-0'); test('+0'); test('0'); test('1'); test('000017'); // lead zeroes allowed, not interpreted as octal! test('000019'); test(' -Infinity'); test(' +Infinity'); test(' Infinity'); test('0xdeadbeef'); test('0Xdeadbeef'); test(' \n0xdeadbeef\n'); test(' \n0xdeadbeefg\n'); // trailing garbage not allowed -> NaN /*=== 83 nz 83 nz 83 nz 83 nz NaN nz 17 nz 17 nz 17 nz 17 nz NaN nz ===*/ /* In ES6 0o123, and 0b10001 are recognized. Whitespace is also allowed. * Note that whitespace is trimmed so these forms cannot be recognized * by just peeking at the first few characters. */ test('0o123'); test('0O123'); test('\n0o123 \t'); test('\n0o000000123 \t'); test('\n0o000000123 x\t'); test('0b10001'); test('0B10001'); test('\t0b10001 \r\n'); test('\t0b0000010001 \r\n'); test('\t0b00000000000100012 \r\n'); // '2' is garbage to binary /* XXX: object coercion */
zeroSign
identifier_name
privacy-struct-variant.rs
// Copyright 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. // aux-build:privacy-struct-variant.rs #![feature(struct_variant)] extern crate "privacy-struct-variant" as other; mod a { pub enum Foo { Bar { baz: int } } fn
() { let foo = Bar { baz: 42 }; let Bar { baz: _ } = foo; match foo { Bar { baz: _ } => {} } } } fn main() { let foo = a::Bar { baz: 42 }; //~^ ERROR: field `baz` of variant `Bar` of enum `a::Foo` is private let a::Bar { baz: _ } = foo; //~^ ERROR: field `baz` of variant `Bar` of enum `a::Foo` is private match foo { a::Bar { baz: _ } => {} } //~^ ERROR: field `baz` of variant `Bar` of enum `a::Foo` is private // let foo = other::Bar { baz: 42 }; //~^ ERROR: field `baz` of variant `Bar` of enum `privacy-struct-variant::Foo` is private let other::Bar { baz: _ } = foo; //~^ ERROR: field `baz` of variant `Bar` of enum `privacy-struct-variant::Foo` is private match foo { other::Bar { baz: _ } => {} } //~^ ERROR: field `baz` of variant `Bar` of enum `privacy-struct-variant::Foo` is private }
test
identifier_name
privacy-struct-variant.rs
// Copyright 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. // aux-build:privacy-struct-variant.rs #![feature(struct_variant)]
extern crate "privacy-struct-variant" as other; mod a { pub enum Foo { Bar { baz: int } } fn test() { let foo = Bar { baz: 42 }; let Bar { baz: _ } = foo; match foo { Bar { baz: _ } => {} } } } fn main() { let foo = a::Bar { baz: 42 }; //~^ ERROR: field `baz` of variant `Bar` of enum `a::Foo` is private let a::Bar { baz: _ } = foo; //~^ ERROR: field `baz` of variant `Bar` of enum `a::Foo` is private match foo { a::Bar { baz: _ } => {} } //~^ ERROR: field `baz` of variant `Bar` of enum `a::Foo` is private // let foo = other::Bar { baz: 42 }; //~^ ERROR: field `baz` of variant `Bar` of enum `privacy-struct-variant::Foo` is private let other::Bar { baz: _ } = foo; //~^ ERROR: field `baz` of variant `Bar` of enum `privacy-struct-variant::Foo` is private match foo { other::Bar { baz: _ } => {} } //~^ ERROR: field `baz` of variant `Bar` of enum `privacy-struct-variant::Foo` is private }
random_line_split
privacy-struct-variant.rs
// Copyright 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. // aux-build:privacy-struct-variant.rs #![feature(struct_variant)] extern crate "privacy-struct-variant" as other; mod a { pub enum Foo { Bar { baz: int } } fn test() { let foo = Bar { baz: 42 }; let Bar { baz: _ } = foo; match foo { Bar { baz: _ } => {} } } } fn main()
{ let foo = a::Bar { baz: 42 }; //~^ ERROR: field `baz` of variant `Bar` of enum `a::Foo` is private let a::Bar { baz: _ } = foo; //~^ ERROR: field `baz` of variant `Bar` of enum `a::Foo` is private match foo { a::Bar { baz: _ } => {} } //~^ ERROR: field `baz` of variant `Bar` of enum `a::Foo` is private // let foo = other::Bar { baz: 42 }; //~^ ERROR: field `baz` of variant `Bar` of enum `privacy-struct-variant::Foo` is private let other::Bar { baz: _ } = foo; //~^ ERROR: field `baz` of variant `Bar` of enum `privacy-struct-variant::Foo` is private match foo { other::Bar { baz: _ } => {} } //~^ ERROR: field `baz` of variant `Bar` of enum `privacy-struct-variant::Foo` is private }
identifier_body
FairBooth.tsx
import { Box, Separator, Theme } from "@artsy/palette" import { FairBooth_show } from "__generated__/FairBooth_show.graphql" import SwitchBoard from "lib/NativeModules/SwitchBoard" import { Schema, screenTrack } from "lib/utils/track" import React from "react" import { FlatList } from "react-native" import { createFragmentContainer, graphql, QueryRenderer } from "react-relay"
import { ShowArtistsPreviewContainer as ShowArtistsPreview } from "lib/Components/Show/ShowArtistsPreview" import { ShowArtworksPreviewContainer as ShowArtworksPreview } from "lib/Components/Show/ShowArtworksPreview" import { defaultEnvironment } from "lib/relay/createEnvironment" import renderWithLoadProgress from "lib/utils/renderWithLoadProgress" import { FairBoothHeaderContainer as FairBoothHeader } from "../Components/FairBoothHeader" type Item = | { type: "artworks" data: { show: FairBooth_show; onViewAllArtworksPressed: () => void } } | { type: "artists" data: { show: FairBooth_show; onViewAllArtistsPressed: () => void } } interface State { sections: Item[] } interface Props { show: FairBooth_show } @screenTrack<Props>(props => ({ context_screen: Schema.PageNames.FairBoothPage, context_screen_owner_type: Schema.OwnerEntityTypes.Fair, context_screen_owner_slug: props.show.slug, context_screen_owner_id: props.show.internalID, })) export class FairBooth extends React.Component<Props, State> { state = { sections: [], } onViewFairBoothArtworksPressed() { SwitchBoard.presentNavigationViewController(this, `/show/${this.props.show.slug}/artworks`) } onViewFairBoothArtistsPressed() { SwitchBoard.presentNavigationViewController(this, `/show/${this.props.show.slug}/artists`) } componentDidMount() { const { show } = this.props const sections = [] sections.push({ type: "artworks", data: { show, onViewAllArtworksPressed: this.onViewFairBoothArtworksPressed.bind(this), }, }) sections.push({ type: "artists", data: { show, onViewAllArtistsPressed: this.onViewFairBoothArtistsPressed.bind(this), }, }) this.setState({ sections }) } renderItem = ({ item }: { item: Item }) => { switch (item.type) { case "artworks": return <ShowArtworksPreview {...item.data} /> case "artists": return <ShowArtistsPreview {...item.data} /> default: return null } } onTitlePressed = partnerId => { SwitchBoard.presentNavigationViewController(this, partnerId) } render() { const { sections } = this.state const { show } = this.props return ( <Theme> <FlatList data={sections} ListHeaderComponent={<FairBoothHeader show={show} onTitlePressed={this.onTitlePressed} />} renderItem={item => ( <Box px={2} py={2}> {this.renderItem(item)} </Box> )} ItemSeparatorComponent={() => { return ( <Box px={2} pb={2} mt={2}> <Separator /> </Box> ) }} keyExtractor={(item, index) => item.type + String(index)} /> </Theme> ) } } export const FairBoothContainer = createFragmentContainer(FairBooth, { show: graphql` fragment FairBooth_show on Show { slug internalID ...FairBoothHeader_show ...ShowArtworksPreview_show ...ShowArtistsPreview_show } `, }) export const FairBoothRenderer: React.SFC<{ showID: string }> = ({ showID }) => ( <QueryRenderer<FairBoothQuery> environment={defaultEnvironment} query={graphql` query FairBoothQuery($showID: String!) { show(id: $showID) { ...FairBooth_show } } `} variables={{ showID }} render={renderWithLoadProgress(FairBoothContainer)} /> )
import { FairBoothQuery } from "__generated__/FairBoothQuery.graphql"
random_line_split
FairBooth.tsx
import { Box, Separator, Theme } from "@artsy/palette" import { FairBooth_show } from "__generated__/FairBooth_show.graphql" import SwitchBoard from "lib/NativeModules/SwitchBoard" import { Schema, screenTrack } from "lib/utils/track" import React from "react" import { FlatList } from "react-native" import { createFragmentContainer, graphql, QueryRenderer } from "react-relay" import { FairBoothQuery } from "__generated__/FairBoothQuery.graphql" import { ShowArtistsPreviewContainer as ShowArtistsPreview } from "lib/Components/Show/ShowArtistsPreview" import { ShowArtworksPreviewContainer as ShowArtworksPreview } from "lib/Components/Show/ShowArtworksPreview" import { defaultEnvironment } from "lib/relay/createEnvironment" import renderWithLoadProgress from "lib/utils/renderWithLoadProgress" import { FairBoothHeaderContainer as FairBoothHeader } from "../Components/FairBoothHeader" type Item = | { type: "artworks" data: { show: FairBooth_show; onViewAllArtworksPressed: () => void } } | { type: "artists" data: { show: FairBooth_show; onViewAllArtistsPressed: () => void } } interface State { sections: Item[] } interface Props { show: FairBooth_show } @screenTrack<Props>(props => ({ context_screen: Schema.PageNames.FairBoothPage, context_screen_owner_type: Schema.OwnerEntityTypes.Fair, context_screen_owner_slug: props.show.slug, context_screen_owner_id: props.show.internalID, })) export class FairBooth extends React.Component<Props, State> { state = { sections: [], } onViewFairBoothArtworksPressed() { SwitchBoard.presentNavigationViewController(this, `/show/${this.props.show.slug}/artworks`) }
() { SwitchBoard.presentNavigationViewController(this, `/show/${this.props.show.slug}/artists`) } componentDidMount() { const { show } = this.props const sections = [] sections.push({ type: "artworks", data: { show, onViewAllArtworksPressed: this.onViewFairBoothArtworksPressed.bind(this), }, }) sections.push({ type: "artists", data: { show, onViewAllArtistsPressed: this.onViewFairBoothArtistsPressed.bind(this), }, }) this.setState({ sections }) } renderItem = ({ item }: { item: Item }) => { switch (item.type) { case "artworks": return <ShowArtworksPreview {...item.data} /> case "artists": return <ShowArtistsPreview {...item.data} /> default: return null } } onTitlePressed = partnerId => { SwitchBoard.presentNavigationViewController(this, partnerId) } render() { const { sections } = this.state const { show } = this.props return ( <Theme> <FlatList data={sections} ListHeaderComponent={<FairBoothHeader show={show} onTitlePressed={this.onTitlePressed} />} renderItem={item => ( <Box px={2} py={2}> {this.renderItem(item)} </Box> )} ItemSeparatorComponent={() => { return ( <Box px={2} pb={2} mt={2}> <Separator /> </Box> ) }} keyExtractor={(item, index) => item.type + String(index)} /> </Theme> ) } } export const FairBoothContainer = createFragmentContainer(FairBooth, { show: graphql` fragment FairBooth_show on Show { slug internalID ...FairBoothHeader_show ...ShowArtworksPreview_show ...ShowArtistsPreview_show } `, }) export const FairBoothRenderer: React.SFC<{ showID: string }> = ({ showID }) => ( <QueryRenderer<FairBoothQuery> environment={defaultEnvironment} query={graphql` query FairBoothQuery($showID: String!) { show(id: $showID) { ...FairBooth_show } } `} variables={{ showID }} render={renderWithLoadProgress(FairBoothContainer)} /> )
onViewFairBoothArtistsPressed
identifier_name
FairBooth.tsx
import { Box, Separator, Theme } from "@artsy/palette" import { FairBooth_show } from "__generated__/FairBooth_show.graphql" import SwitchBoard from "lib/NativeModules/SwitchBoard" import { Schema, screenTrack } from "lib/utils/track" import React from "react" import { FlatList } from "react-native" import { createFragmentContainer, graphql, QueryRenderer } from "react-relay" import { FairBoothQuery } from "__generated__/FairBoothQuery.graphql" import { ShowArtistsPreviewContainer as ShowArtistsPreview } from "lib/Components/Show/ShowArtistsPreview" import { ShowArtworksPreviewContainer as ShowArtworksPreview } from "lib/Components/Show/ShowArtworksPreview" import { defaultEnvironment } from "lib/relay/createEnvironment" import renderWithLoadProgress from "lib/utils/renderWithLoadProgress" import { FairBoothHeaderContainer as FairBoothHeader } from "../Components/FairBoothHeader" type Item = | { type: "artworks" data: { show: FairBooth_show; onViewAllArtworksPressed: () => void } } | { type: "artists" data: { show: FairBooth_show; onViewAllArtistsPressed: () => void } } interface State { sections: Item[] } interface Props { show: FairBooth_show } @screenTrack<Props>(props => ({ context_screen: Schema.PageNames.FairBoothPage, context_screen_owner_type: Schema.OwnerEntityTypes.Fair, context_screen_owner_slug: props.show.slug, context_screen_owner_id: props.show.internalID, })) export class FairBooth extends React.Component<Props, State> { state = { sections: [], } onViewFairBoothArtworksPressed() { SwitchBoard.presentNavigationViewController(this, `/show/${this.props.show.slug}/artworks`) } onViewFairBoothArtistsPressed() { SwitchBoard.presentNavigationViewController(this, `/show/${this.props.show.slug}/artists`) } componentDidMount()
renderItem = ({ item }: { item: Item }) => { switch (item.type) { case "artworks": return <ShowArtworksPreview {...item.data} /> case "artists": return <ShowArtistsPreview {...item.data} /> default: return null } } onTitlePressed = partnerId => { SwitchBoard.presentNavigationViewController(this, partnerId) } render() { const { sections } = this.state const { show } = this.props return ( <Theme> <FlatList data={sections} ListHeaderComponent={<FairBoothHeader show={show} onTitlePressed={this.onTitlePressed} />} renderItem={item => ( <Box px={2} py={2}> {this.renderItem(item)} </Box> )} ItemSeparatorComponent={() => { return ( <Box px={2} pb={2} mt={2}> <Separator /> </Box> ) }} keyExtractor={(item, index) => item.type + String(index)} /> </Theme> ) } } export const FairBoothContainer = createFragmentContainer(FairBooth, { show: graphql` fragment FairBooth_show on Show { slug internalID ...FairBoothHeader_show ...ShowArtworksPreview_show ...ShowArtistsPreview_show } `, }) export const FairBoothRenderer: React.SFC<{ showID: string }> = ({ showID }) => ( <QueryRenderer<FairBoothQuery> environment={defaultEnvironment} query={graphql` query FairBoothQuery($showID: String!) { show(id: $showID) { ...FairBooth_show } } `} variables={{ showID }} render={renderWithLoadProgress(FairBoothContainer)} /> )
{ const { show } = this.props const sections = [] sections.push({ type: "artworks", data: { show, onViewAllArtworksPressed: this.onViewFairBoothArtworksPressed.bind(this), }, }) sections.push({ type: "artists", data: { show, onViewAllArtistsPressed: this.onViewFairBoothArtistsPressed.bind(this), }, }) this.setState({ sections }) }
identifier_body
chip8.rs
extern crate sdl2; use std::fs::File; use std::io::prelude::*; use std::time::{Duration, Instant}; #[cfg(feature="debugger")] use std::process::Command; use chip8::MEMORY_SIZE; use chip8::ROM_START_ADDRESS; use chip8::keyboard::Keyboard; use chip8::display::Display; #[cfg(feature="interpreter")] use chip8::interpreter::Interpreter; #[cfg(not(feature="interpreter"))] use chip8::recompiler::Recompiler; const STACK_SIZE: usize = 16; const V_REGISTERS_COUNT: usize = 16; pub struct Chip8 { pub memory: [u8; MEMORY_SIZE], pub stack: [u16; STACK_SIZE], pub register_v: [u8; V_REGISTERS_COUNT], pub register_i: u16, pub register_dt: u8, pub register_st: u8, pub register_pc: u16, pub register_sp: u8, pub keyboard: Keyboard, pub display: Display, time_last_frame: Instant } impl Chip8 { pub fn new() -> Chip8
fn load_rom(&mut self, filename: String) { let mut file = File::open(filename).expect("file not found"); let mut buffer: Vec<u8> = Vec::new(); file.read_to_end(&mut buffer).expect("something went wrong reading the file"); self.memory[ROM_START_ADDRESS as usize..ROM_START_ADDRESS as usize + buffer.len()].copy_from_slice(&buffer); } #[cfg(feature="debugger")] fn print_registers(&self) { println!("PC= {:x}", self.register_pc); println!("I= {:x}", self.register_i); println!("DT= {:x}", self.register_dt); println!("ST= {:x}", self.register_st); println!("SP= {:x}", self.register_sp); for i in 0..16 as usize { println!("V{}= {:x}", i, self.register_v[i]); } let _ = Command::new("cmd.exe").arg("/c").arg("pause").status(); } pub extern "stdcall" fn refresh(&mut self) { // ~60Hz if self.time_last_frame.elapsed() >= Duration::from_millis(1000 / 60) { self.time_last_frame = Instant::now(); self.keyboard.update_key_states(); self.display.refresh(); if self.register_dt > 0 { self.register_dt -= 1 } if self.register_st > 0 { self.register_st -= 1; // TODO: beep } } } pub fn run(&mut self, filename: String) { self.load_rom(filename); #[cfg(not(feature="interpreter"))] let mut recompiler = Recompiler::new(&self.register_pc); loop { #[cfg(feature="debugger")] self.print_registers(); #[cfg(feature="interpreter")] Interpreter::execute_next_instruction(self); #[cfg(feature="interpreter")] self.refresh(); #[cfg(not(feature="interpreter"))] recompiler.execute_next_code_block(self); } } }
{ let sdl_context = sdl2::init().unwrap(); let mut chip8 = Chip8 { memory: [0; MEMORY_SIZE], stack: [0; STACK_SIZE], register_v: [0; V_REGISTERS_COUNT], register_i: 0, register_dt: 0, register_st: 0, register_pc: ROM_START_ADDRESS, register_sp: 0xFF, keyboard: Keyboard::new(&sdl_context), display: Display::new(&sdl_context), time_last_frame: Instant::now() }; chip8.memory[0x00] = 0xF0; chip8.memory[0x01] = 0x90; chip8.memory[0x02] = 0x90; chip8.memory[0x03] = 0x90; chip8.memory[0x04] = 0xF0; chip8.memory[0x05] = 0x20; chip8.memory[0x06] = 0x60; chip8.memory[0x07] = 0x20; chip8.memory[0x08] = 0x20; chip8.memory[0x09] = 0x70; chip8.memory[0x0A] = 0xF0; chip8.memory[0x0B] = 0x10; chip8.memory[0x0C] = 0xF0; chip8.memory[0x0D] = 0x80; chip8.memory[0x0E] = 0xF0; chip8.memory[0x0F] = 0xF0; chip8.memory[0x10] = 0x10; chip8.memory[0x11] = 0xF0; chip8.memory[0x12] = 0x10; chip8.memory[0x13] = 0xF0; chip8.memory[0x14] = 0x90; chip8.memory[0x15] = 0x90; chip8.memory[0x16] = 0xF0; chip8.memory[0x17] = 0x10; chip8.memory[0x18] = 0x10; chip8.memory[0x19] = 0xF0; chip8.memory[0x1A] = 0x80; chip8.memory[0x1B] = 0xF0; chip8.memory[0x1C] = 0x10; chip8.memory[0x1D] = 0xF0; chip8.memory[0x1E] = 0xF0; chip8.memory[0x1F] = 0x80; chip8.memory[0x20] = 0xF0; chip8.memory[0x21] = 0x90; chip8.memory[0x22] = 0xF0; chip8.memory[0x23] = 0xF0; chip8.memory[0x24] = 0x10; chip8.memory[0x25] = 0x20; chip8.memory[0x26] = 0x40; chip8.memory[0x27] = 0x40; chip8.memory[0x28] = 0xF0; chip8.memory[0x29] = 0x90; chip8.memory[0x2A] = 0xF0; chip8.memory[0x2B] = 0x90; chip8.memory[0x2C] = 0xF0; chip8.memory[0x2D] = 0xF0; chip8.memory[0x2E] = 0x90; chip8.memory[0x2F] = 0xF0; chip8.memory[0x30] = 0x10; chip8.memory[0x31] = 0xF0; chip8.memory[0x32] = 0xF0; chip8.memory[0x33] = 0x90; chip8.memory[0x34] = 0xF0; chip8.memory[0x35] = 0x90; chip8.memory[0x36] = 0x90; chip8.memory[0x37] = 0xE0; chip8.memory[0x38] = 0x90; chip8.memory[0x39] = 0xE0; chip8.memory[0x3A] = 0x90; chip8.memory[0x3B] = 0xE0; chip8.memory[0x3C] = 0xF0; chip8.memory[0x3D] = 0x80; chip8.memory[0x3E] = 0x80; chip8.memory[0x3F] = 0x80; chip8.memory[0x40] = 0xF0; chip8.memory[0x41] = 0xE0; chip8.memory[0x42] = 0x90; chip8.memory[0x43] = 0x90; chip8.memory[0x44] = 0x90; chip8.memory[0x45] = 0xE0; chip8.memory[0x46] = 0xF0; chip8.memory[0x47] = 0x80; chip8.memory[0x48] = 0xF0; chip8.memory[0x49] = 0x80; chip8.memory[0x4A] = 0xF0; chip8.memory[0x4B] = 0xF0; chip8.memory[0x4C] = 0x80; chip8.memory[0x4D] = 0xF0; chip8.memory[0x4E] = 0x80; chip8.memory[0x4F] = 0x80; chip8 }
identifier_body
chip8.rs
extern crate sdl2; use std::fs::File; use std::io::prelude::*; use std::time::{Duration, Instant}; #[cfg(feature="debugger")] use std::process::Command; use chip8::MEMORY_SIZE; use chip8::ROM_START_ADDRESS; use chip8::keyboard::Keyboard; use chip8::display::Display; #[cfg(feature="interpreter")] use chip8::interpreter::Interpreter; #[cfg(not(feature="interpreter"))] use chip8::recompiler::Recompiler; const STACK_SIZE: usize = 16; const V_REGISTERS_COUNT: usize = 16; pub struct Chip8 { pub memory: [u8; MEMORY_SIZE], pub stack: [u16; STACK_SIZE], pub register_v: [u8; V_REGISTERS_COUNT], pub register_i: u16, pub register_dt: u8, pub register_st: u8, pub register_pc: u16, pub register_sp: u8, pub keyboard: Keyboard, pub display: Display, time_last_frame: Instant } impl Chip8 { pub fn new() -> Chip8 { let sdl_context = sdl2::init().unwrap(); let mut chip8 = Chip8 { memory: [0; MEMORY_SIZE], stack: [0; STACK_SIZE], register_v: [0; V_REGISTERS_COUNT], register_i: 0, register_dt: 0, register_st: 0, register_pc: ROM_START_ADDRESS, register_sp: 0xFF, keyboard: Keyboard::new(&sdl_context), display: Display::new(&sdl_context), time_last_frame: Instant::now() }; chip8.memory[0x00] = 0xF0; chip8.memory[0x01] = 0x90; chip8.memory[0x02] = 0x90; chip8.memory[0x03] = 0x90; chip8.memory[0x04] = 0xF0; chip8.memory[0x05] = 0x20; chip8.memory[0x06] = 0x60; chip8.memory[0x07] = 0x20; chip8.memory[0x08] = 0x20; chip8.memory[0x09] = 0x70; chip8.memory[0x0A] = 0xF0; chip8.memory[0x0B] = 0x10; chip8.memory[0x0C] = 0xF0; chip8.memory[0x0D] = 0x80; chip8.memory[0x0E] = 0xF0; chip8.memory[0x0F] = 0xF0; chip8.memory[0x10] = 0x10; chip8.memory[0x11] = 0xF0; chip8.memory[0x12] = 0x10; chip8.memory[0x13] = 0xF0; chip8.memory[0x14] = 0x90; chip8.memory[0x15] = 0x90; chip8.memory[0x16] = 0xF0; chip8.memory[0x17] = 0x10; chip8.memory[0x18] = 0x10; chip8.memory[0x19] = 0xF0; chip8.memory[0x1A] = 0x80; chip8.memory[0x1B] = 0xF0; chip8.memory[0x1C] = 0x10; chip8.memory[0x1D] = 0xF0; chip8.memory[0x1E] = 0xF0; chip8.memory[0x1F] = 0x80; chip8.memory[0x20] = 0xF0; chip8.memory[0x21] = 0x90; chip8.memory[0x22] = 0xF0; chip8.memory[0x23] = 0xF0; chip8.memory[0x24] = 0x10; chip8.memory[0x25] = 0x20; chip8.memory[0x26] = 0x40; chip8.memory[0x27] = 0x40; chip8.memory[0x28] = 0xF0; chip8.memory[0x29] = 0x90; chip8.memory[0x2A] = 0xF0; chip8.memory[0x2B] = 0x90; chip8.memory[0x2C] = 0xF0; chip8.memory[0x2D] = 0xF0; chip8.memory[0x2E] = 0x90; chip8.memory[0x2F] = 0xF0; chip8.memory[0x30] = 0x10; chip8.memory[0x31] = 0xF0; chip8.memory[0x32] = 0xF0; chip8.memory[0x33] = 0x90; chip8.memory[0x34] = 0xF0; chip8.memory[0x35] = 0x90; chip8.memory[0x36] = 0x90; chip8.memory[0x37] = 0xE0; chip8.memory[0x38] = 0x90; chip8.memory[0x39] = 0xE0; chip8.memory[0x3A] = 0x90; chip8.memory[0x3B] = 0xE0; chip8.memory[0x3C] = 0xF0; chip8.memory[0x3D] = 0x80; chip8.memory[0x3E] = 0x80; chip8.memory[0x3F] = 0x80; chip8.memory[0x40] = 0xF0; chip8.memory[0x41] = 0xE0; chip8.memory[0x42] = 0x90; chip8.memory[0x43] = 0x90; chip8.memory[0x44] = 0x90; chip8.memory[0x45] = 0xE0; chip8.memory[0x46] = 0xF0; chip8.memory[0x47] = 0x80; chip8.memory[0x48] = 0xF0; chip8.memory[0x49] = 0x80; chip8.memory[0x4A] = 0xF0; chip8.memory[0x4B] = 0xF0; chip8.memory[0x4C] = 0x80; chip8.memory[0x4D] = 0xF0; chip8.memory[0x4E] = 0x80; chip8.memory[0x4F] = 0x80; chip8 } fn load_rom(&mut self, filename: String) { let mut file = File::open(filename).expect("file not found"); let mut buffer: Vec<u8> = Vec::new(); file.read_to_end(&mut buffer).expect("something went wrong reading the file"); self.memory[ROM_START_ADDRESS as usize..ROM_START_ADDRESS as usize + buffer.len()].copy_from_slice(&buffer); } #[cfg(feature="debugger")] fn
(&self) { println!("PC= {:x}", self.register_pc); println!("I= {:x}", self.register_i); println!("DT= {:x}", self.register_dt); println!("ST= {:x}", self.register_st); println!("SP= {:x}", self.register_sp); for i in 0..16 as usize { println!("V{}= {:x}", i, self.register_v[i]); } let _ = Command::new("cmd.exe").arg("/c").arg("pause").status(); } pub extern "stdcall" fn refresh(&mut self) { // ~60Hz if self.time_last_frame.elapsed() >= Duration::from_millis(1000 / 60) { self.time_last_frame = Instant::now(); self.keyboard.update_key_states(); self.display.refresh(); if self.register_dt > 0 { self.register_dt -= 1 } if self.register_st > 0 { self.register_st -= 1; // TODO: beep } } } pub fn run(&mut self, filename: String) { self.load_rom(filename); #[cfg(not(feature="interpreter"))] let mut recompiler = Recompiler::new(&self.register_pc); loop { #[cfg(feature="debugger")] self.print_registers(); #[cfg(feature="interpreter")] Interpreter::execute_next_instruction(self); #[cfg(feature="interpreter")] self.refresh(); #[cfg(not(feature="interpreter"))] recompiler.execute_next_code_block(self); } } }
print_registers
identifier_name
chip8.rs
extern crate sdl2; use std::fs::File; use std::io::prelude::*; use std::time::{Duration, Instant}; #[cfg(feature="debugger")] use std::process::Command; use chip8::MEMORY_SIZE; use chip8::ROM_START_ADDRESS; use chip8::keyboard::Keyboard; use chip8::display::Display; #[cfg(feature="interpreter")] use chip8::interpreter::Interpreter; #[cfg(not(feature="interpreter"))] use chip8::recompiler::Recompiler; const STACK_SIZE: usize = 16; const V_REGISTERS_COUNT: usize = 16; pub struct Chip8 { pub memory: [u8; MEMORY_SIZE], pub stack: [u16; STACK_SIZE], pub register_v: [u8; V_REGISTERS_COUNT], pub register_i: u16, pub register_dt: u8, pub register_st: u8, pub register_pc: u16, pub register_sp: u8, pub keyboard: Keyboard, pub display: Display, time_last_frame: Instant } impl Chip8 { pub fn new() -> Chip8 { let sdl_context = sdl2::init().unwrap(); let mut chip8 = Chip8 { memory: [0; MEMORY_SIZE], stack: [0; STACK_SIZE], register_v: [0; V_REGISTERS_COUNT], register_i: 0, register_dt: 0, register_st: 0, register_pc: ROM_START_ADDRESS, register_sp: 0xFF, keyboard: Keyboard::new(&sdl_context), display: Display::new(&sdl_context), time_last_frame: Instant::now() }; chip8.memory[0x00] = 0xF0; chip8.memory[0x01] = 0x90; chip8.memory[0x02] = 0x90; chip8.memory[0x03] = 0x90; chip8.memory[0x04] = 0xF0; chip8.memory[0x05] = 0x20; chip8.memory[0x06] = 0x60; chip8.memory[0x07] = 0x20; chip8.memory[0x08] = 0x20; chip8.memory[0x09] = 0x70; chip8.memory[0x0A] = 0xF0; chip8.memory[0x0B] = 0x10; chip8.memory[0x0C] = 0xF0; chip8.memory[0x0D] = 0x80; chip8.memory[0x0E] = 0xF0; chip8.memory[0x0F] = 0xF0; chip8.memory[0x10] = 0x10; chip8.memory[0x11] = 0xF0; chip8.memory[0x12] = 0x10; chip8.memory[0x13] = 0xF0; chip8.memory[0x14] = 0x90; chip8.memory[0x15] = 0x90; chip8.memory[0x16] = 0xF0; chip8.memory[0x17] = 0x10; chip8.memory[0x18] = 0x10; chip8.memory[0x19] = 0xF0; chip8.memory[0x1A] = 0x80; chip8.memory[0x1B] = 0xF0; chip8.memory[0x1C] = 0x10; chip8.memory[0x1D] = 0xF0; chip8.memory[0x1E] = 0xF0; chip8.memory[0x1F] = 0x80; chip8.memory[0x20] = 0xF0; chip8.memory[0x21] = 0x90; chip8.memory[0x22] = 0xF0; chip8.memory[0x23] = 0xF0; chip8.memory[0x24] = 0x10; chip8.memory[0x25] = 0x20; chip8.memory[0x26] = 0x40; chip8.memory[0x27] = 0x40; chip8.memory[0x28] = 0xF0; chip8.memory[0x29] = 0x90; chip8.memory[0x2A] = 0xF0; chip8.memory[0x2B] = 0x90; chip8.memory[0x2C] = 0xF0; chip8.memory[0x2D] = 0xF0; chip8.memory[0x2E] = 0x90; chip8.memory[0x2F] = 0xF0; chip8.memory[0x30] = 0x10; chip8.memory[0x31] = 0xF0; chip8.memory[0x32] = 0xF0; chip8.memory[0x33] = 0x90; chip8.memory[0x34] = 0xF0; chip8.memory[0x35] = 0x90; chip8.memory[0x36] = 0x90; chip8.memory[0x37] = 0xE0; chip8.memory[0x38] = 0x90; chip8.memory[0x39] = 0xE0; chip8.memory[0x3A] = 0x90; chip8.memory[0x3B] = 0xE0; chip8.memory[0x3C] = 0xF0; chip8.memory[0x3D] = 0x80; chip8.memory[0x3E] = 0x80; chip8.memory[0x3F] = 0x80; chip8.memory[0x40] = 0xF0; chip8.memory[0x41] = 0xE0; chip8.memory[0x42] = 0x90; chip8.memory[0x43] = 0x90; chip8.memory[0x44] = 0x90; chip8.memory[0x45] = 0xE0; chip8.memory[0x46] = 0xF0; chip8.memory[0x47] = 0x80; chip8.memory[0x48] = 0xF0; chip8.memory[0x49] = 0x80; chip8.memory[0x4A] = 0xF0; chip8.memory[0x4B] = 0xF0; chip8.memory[0x4C] = 0x80; chip8.memory[0x4D] = 0xF0; chip8.memory[0x4E] = 0x80; chip8.memory[0x4F] = 0x80; chip8 } fn load_rom(&mut self, filename: String) { let mut file = File::open(filename).expect("file not found"); let mut buffer: Vec<u8> = Vec::new(); file.read_to_end(&mut buffer).expect("something went wrong reading the file"); self.memory[ROM_START_ADDRESS as usize..ROM_START_ADDRESS as usize + buffer.len()].copy_from_slice(&buffer); } #[cfg(feature="debugger")] fn print_registers(&self) { println!("PC= {:x}", self.register_pc); println!("I= {:x}", self.register_i); println!("DT= {:x}", self.register_dt); println!("ST= {:x}", self.register_st); println!("SP= {:x}", self.register_sp); for i in 0..16 as usize { println!("V{}= {:x}", i, self.register_v[i]); } let _ = Command::new("cmd.exe").arg("/c").arg("pause").status(); } pub extern "stdcall" fn refresh(&mut self) { // ~60Hz if self.time_last_frame.elapsed() >= Duration::from_millis(1000 / 60)
} pub fn run(&mut self, filename: String) { self.load_rom(filename); #[cfg(not(feature="interpreter"))] let mut recompiler = Recompiler::new(&self.register_pc); loop { #[cfg(feature="debugger")] self.print_registers(); #[cfg(feature="interpreter")] Interpreter::execute_next_instruction(self); #[cfg(feature="interpreter")] self.refresh(); #[cfg(not(feature="interpreter"))] recompiler.execute_next_code_block(self); } } }
{ self.time_last_frame = Instant::now(); self.keyboard.update_key_states(); self.display.refresh(); if self.register_dt > 0 { self.register_dt -= 1 } if self.register_st > 0 { self.register_st -= 1; // TODO: beep } }
conditional_block
chip8.rs
extern crate sdl2; use std::fs::File; use std::io::prelude::*; use std::time::{Duration, Instant}; #[cfg(feature="debugger")] use std::process::Command; use chip8::MEMORY_SIZE; use chip8::ROM_START_ADDRESS; use chip8::keyboard::Keyboard; use chip8::display::Display; #[cfg(feature="interpreter")] use chip8::interpreter::Interpreter; #[cfg(not(feature="interpreter"))] use chip8::recompiler::Recompiler; const STACK_SIZE: usize = 16; const V_REGISTERS_COUNT: usize = 16; pub struct Chip8 { pub memory: [u8; MEMORY_SIZE], pub stack: [u16; STACK_SIZE], pub register_v: [u8; V_REGISTERS_COUNT], pub register_i: u16, pub register_dt: u8, pub register_st: u8, pub register_pc: u16, pub register_sp: u8, pub keyboard: Keyboard, pub display: Display, time_last_frame: Instant } impl Chip8 { pub fn new() -> Chip8 { let sdl_context = sdl2::init().unwrap(); let mut chip8 = Chip8 { memory: [0; MEMORY_SIZE], stack: [0; STACK_SIZE], register_v: [0; V_REGISTERS_COUNT], register_i: 0, register_dt: 0, register_st: 0, register_pc: ROM_START_ADDRESS, register_sp: 0xFF, keyboard: Keyboard::new(&sdl_context), display: Display::new(&sdl_context), time_last_frame: Instant::now() }; chip8.memory[0x00] = 0xF0; chip8.memory[0x01] = 0x90; chip8.memory[0x02] = 0x90; chip8.memory[0x03] = 0x90; chip8.memory[0x04] = 0xF0; chip8.memory[0x05] = 0x20; chip8.memory[0x06] = 0x60; chip8.memory[0x07] = 0x20; chip8.memory[0x08] = 0x20; chip8.memory[0x09] = 0x70; chip8.memory[0x0A] = 0xF0; chip8.memory[0x0B] = 0x10; chip8.memory[0x0C] = 0xF0; chip8.memory[0x0D] = 0x80; chip8.memory[0x0E] = 0xF0; chip8.memory[0x0F] = 0xF0; chip8.memory[0x10] = 0x10; chip8.memory[0x11] = 0xF0; chip8.memory[0x12] = 0x10; chip8.memory[0x13] = 0xF0; chip8.memory[0x14] = 0x90; chip8.memory[0x15] = 0x90; chip8.memory[0x16] = 0xF0; chip8.memory[0x17] = 0x10; chip8.memory[0x18] = 0x10; chip8.memory[0x19] = 0xF0; chip8.memory[0x1A] = 0x80; chip8.memory[0x1B] = 0xF0; chip8.memory[0x1C] = 0x10; chip8.memory[0x1D] = 0xF0; chip8.memory[0x1E] = 0xF0; chip8.memory[0x1F] = 0x80; chip8.memory[0x20] = 0xF0; chip8.memory[0x21] = 0x90; chip8.memory[0x22] = 0xF0; chip8.memory[0x23] = 0xF0; chip8.memory[0x24] = 0x10; chip8.memory[0x25] = 0x20; chip8.memory[0x26] = 0x40; chip8.memory[0x27] = 0x40; chip8.memory[0x28] = 0xF0; chip8.memory[0x29] = 0x90; chip8.memory[0x2A] = 0xF0; chip8.memory[0x2B] = 0x90; chip8.memory[0x2C] = 0xF0; chip8.memory[0x2D] = 0xF0; chip8.memory[0x2E] = 0x90; chip8.memory[0x2F] = 0xF0; chip8.memory[0x30] = 0x10; chip8.memory[0x31] = 0xF0; chip8.memory[0x32] = 0xF0; chip8.memory[0x33] = 0x90; chip8.memory[0x34] = 0xF0; chip8.memory[0x35] = 0x90; chip8.memory[0x36] = 0x90; chip8.memory[0x37] = 0xE0; chip8.memory[0x38] = 0x90; chip8.memory[0x39] = 0xE0; chip8.memory[0x3A] = 0x90; chip8.memory[0x3B] = 0xE0; chip8.memory[0x3C] = 0xF0; chip8.memory[0x3D] = 0x80; chip8.memory[0x3E] = 0x80; chip8.memory[0x3F] = 0x80; chip8.memory[0x40] = 0xF0; chip8.memory[0x41] = 0xE0; chip8.memory[0x42] = 0x90; chip8.memory[0x43] = 0x90; chip8.memory[0x44] = 0x90; chip8.memory[0x45] = 0xE0; chip8.memory[0x46] = 0xF0; chip8.memory[0x47] = 0x80; chip8.memory[0x48] = 0xF0; chip8.memory[0x49] = 0x80; chip8.memory[0x4A] = 0xF0; chip8.memory[0x4B] = 0xF0; chip8.memory[0x4C] = 0x80; chip8.memory[0x4D] = 0xF0; chip8.memory[0x4E] = 0x80; chip8.memory[0x4F] = 0x80; chip8 } fn load_rom(&mut self, filename: String) { let mut file = File::open(filename).expect("file not found"); let mut buffer: Vec<u8> = Vec::new(); file.read_to_end(&mut buffer).expect("something went wrong reading the file"); self.memory[ROM_START_ADDRESS as usize..ROM_START_ADDRESS as usize + buffer.len()].copy_from_slice(&buffer); } #[cfg(feature="debugger")] fn print_registers(&self) { println!("PC= {:x}", self.register_pc); println!("I= {:x}", self.register_i); println!("DT= {:x}", self.register_dt); println!("ST= {:x}", self.register_st); println!("SP= {:x}", self.register_sp); for i in 0..16 as usize { println!("V{}= {:x}", i, self.register_v[i]); } let _ = Command::new("cmd.exe").arg("/c").arg("pause").status(); } pub extern "stdcall" fn refresh(&mut self) { // ~60Hz if self.time_last_frame.elapsed() >= Duration::from_millis(1000 / 60) { self.time_last_frame = Instant::now(); self.keyboard.update_key_states(); self.display.refresh(); if self.register_dt > 0 { self.register_dt -= 1 } if self.register_st > 0 { self.register_st -= 1; // TODO: beep } } } pub fn run(&mut self, filename: String) { self.load_rom(filename); #[cfg(not(feature="interpreter"))] let mut recompiler = Recompiler::new(&self.register_pc); loop { #[cfg(feature="debugger")] self.print_registers();
#[cfg(not(feature="interpreter"))] recompiler.execute_next_code_block(self); } } }
#[cfg(feature="interpreter")] Interpreter::execute_next_instruction(self); #[cfg(feature="interpreter")] self.refresh();
random_line_split
parse.rs
use crate::{Error, Result}; use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree}; use quote::ToTokens; use std::iter::Peekable; pub(crate) fn parse_input( input: TokenStream, ) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> { let mut input = input.into_iter().peekable(); let mut attrs = Vec::new(); while let Some(attr) = parse_next_attr(&mut input)? { attrs.push(attr); } let sig = parse_signature(&mut input); let body = input.next().ok_or_else(|| { Error::new( Span::call_site(), "`#[proc_macro_error]` can be applied only to functions".to_string(), ) })?; Ok((attrs, sig, body)) } fn parse_next_attr( input: &mut Peekable<impl Iterator<Item = TokenTree>>, ) -> Result<Option<Attribute>> { let shebang = match input.peek() { Some(TokenTree::Punct(ref punct)) if punct.as_char() == '#' => input.next().unwrap(), _ => return Ok(None), }; let group = match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Bracket => { let res = group.clone(); input.next(); res } other => { let span = other.map_or(Span::call_site(), |tt| tt.span()); return Err(Error::new(span, "expected `[`".to_string())); } }; let path = match group.stream().into_iter().next() { Some(TokenTree::Ident(ident)) => Some(ident), _ => None, }; Ok(Some(Attribute { shebang, group: TokenTree::Group(group), path, })) } fn parse_signature(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Vec<TokenTree>
pub(crate) struct Attribute { pub(crate) shebang: TokenTree, pub(crate) group: TokenTree, pub(crate) path: Option<Ident>, } impl Attribute { pub(crate) fn path_is_ident(&self, ident: &str) -> bool { self.path.as_ref().map_or(false, |p| *p == ident) } } impl ToTokens for Attribute { fn to_tokens(&self, ts: &mut TokenStream) { self.shebang.to_tokens(ts); self.group.to_tokens(ts); } }
{ let mut sig = Vec::new(); loop { match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Brace => { return sig; } None => return sig, _ => sig.push(input.next().unwrap()), } } }
identifier_body
parse.rs
use crate::{Error, Result}; use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree}; use quote::ToTokens; use std::iter::Peekable; pub(crate) fn parse_input( input: TokenStream, ) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> { let mut input = input.into_iter().peekable(); let mut attrs = Vec::new(); while let Some(attr) = parse_next_attr(&mut input)? { attrs.push(attr); } let sig = parse_signature(&mut input); let body = input.next().ok_or_else(|| { Error::new( Span::call_site(), "`#[proc_macro_error]` can be applied only to functions".to_string(), ) })?; Ok((attrs, sig, body)) } fn parse_next_attr( input: &mut Peekable<impl Iterator<Item = TokenTree>>, ) -> Result<Option<Attribute>> { let shebang = match input.peek() { Some(TokenTree::Punct(ref punct)) if punct.as_char() == '#' => input.next().unwrap(), _ => return Ok(None), }; let group = match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Bracket => { let res = group.clone(); input.next(); res } other => { let span = other.map_or(Span::call_site(), |tt| tt.span()); return Err(Error::new(span, "expected `[`".to_string())); } }; let path = match group.stream().into_iter().next() { Some(TokenTree::Ident(ident)) => Some(ident), _ => None, };
shebang, group: TokenTree::Group(group), path, })) } fn parse_signature(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Vec<TokenTree> { let mut sig = Vec::new(); loop { match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Brace => { return sig; } None => return sig, _ => sig.push(input.next().unwrap()), } } } pub(crate) struct Attribute { pub(crate) shebang: TokenTree, pub(crate) group: TokenTree, pub(crate) path: Option<Ident>, } impl Attribute { pub(crate) fn path_is_ident(&self, ident: &str) -> bool { self.path.as_ref().map_or(false, |p| *p == ident) } } impl ToTokens for Attribute { fn to_tokens(&self, ts: &mut TokenStream) { self.shebang.to_tokens(ts); self.group.to_tokens(ts); } }
Ok(Some(Attribute {
random_line_split
parse.rs
use crate::{Error, Result}; use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree}; use quote::ToTokens; use std::iter::Peekable; pub(crate) fn parse_input( input: TokenStream, ) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> { let mut input = input.into_iter().peekable(); let mut attrs = Vec::new(); while let Some(attr) = parse_next_attr(&mut input)? { attrs.push(attr); } let sig = parse_signature(&mut input); let body = input.next().ok_or_else(|| { Error::new( Span::call_site(), "`#[proc_macro_error]` can be applied only to functions".to_string(), ) })?; Ok((attrs, sig, body)) } fn
( input: &mut Peekable<impl Iterator<Item = TokenTree>>, ) -> Result<Option<Attribute>> { let shebang = match input.peek() { Some(TokenTree::Punct(ref punct)) if punct.as_char() == '#' => input.next().unwrap(), _ => return Ok(None), }; let group = match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Bracket => { let res = group.clone(); input.next(); res } other => { let span = other.map_or(Span::call_site(), |tt| tt.span()); return Err(Error::new(span, "expected `[`".to_string())); } }; let path = match group.stream().into_iter().next() { Some(TokenTree::Ident(ident)) => Some(ident), _ => None, }; Ok(Some(Attribute { shebang, group: TokenTree::Group(group), path, })) } fn parse_signature(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Vec<TokenTree> { let mut sig = Vec::new(); loop { match input.peek() { Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Brace => { return sig; } None => return sig, _ => sig.push(input.next().unwrap()), } } } pub(crate) struct Attribute { pub(crate) shebang: TokenTree, pub(crate) group: TokenTree, pub(crate) path: Option<Ident>, } impl Attribute { pub(crate) fn path_is_ident(&self, ident: &str) -> bool { self.path.as_ref().map_or(false, |p| *p == ident) } } impl ToTokens for Attribute { fn to_tokens(&self, ts: &mut TokenStream) { self.shebang.to_tokens(ts); self.group.to_tokens(ts); } }
parse_next_attr
identifier_name
browsing_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/. */ //! Liberally derived from the [Firefox JS implementation] //! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webbrowser.js). //! Connection point for remote devtools that wish to investigate a particular Browsing Context's contents. //! Supports dynamic attaching and detaching which control notifications of navigation, etc. use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::actors::console::ConsoleActor; use crate::protocol::JsonPacketStream; use devtools_traits::DevtoolScriptControlMsg::{self, WantsLiveNotifications}; use serde_json::{Map, Value}; use std::net::TcpStream; #[derive(Serialize)] struct BrowsingContextTraits; #[derive(Serialize)] struct BrowsingContextAttachedReply { from: String, #[serde(rename = "type")] type_: String, threadActor: String, cacheDisabled: bool, javascriptEnabled: bool, traits: BrowsingContextTraits, } #[derive(Serialize)] struct BrowsingContextDetachedReply { from: String, #[serde(rename = "type")] type_: String, } #[derive(Serialize)] struct ReconfigureReply { from: String, } #[derive(Serialize)] struct ListFramesReply { from: String, frames: Vec<FrameMsg>, } #[derive(Serialize)] struct FrameMsg { id: u32, url: String, title: String, parentID: u32, } #[derive(Serialize)] struct ListWorkersReply { from: String, workers: Vec<WorkerMsg>, } #[derive(Serialize)] struct WorkerMsg { id: u32, } #[derive(Serialize)] pub struct BrowsingContextActorMsg { actor: String, title: String, url: String, outerWindowID: u32, consoleActor: String, emulationActor: String, inspectorActor: String, timelineActor: String, profilerActor: String, performanceActor: String, styleSheetsActor: String, } pub struct
{ pub name: String, pub title: String, pub url: String, pub console: String, pub emulation: String, pub inspector: String, pub timeline: String, pub profiler: String, pub performance: String, pub styleSheets: String, pub thread: String, } impl Actor for BrowsingContextActor { fn name(&self) -> String { self.name.clone() } fn handle_message( &self, registry: &ActorRegistry, msg_type: &str, msg: &Map<String, Value>, stream: &mut TcpStream, ) -> Result<ActorMessageStatus, ()> { Ok(match msg_type { "reconfigure" => { if let Some(options) = msg.get("options").and_then(|o| o.as_object()) { if let Some(val) = options.get("performReload") { if val.as_bool().unwrap_or(false) { let console_actor = registry.find::<ConsoleActor>(&self.console); let _ = console_actor .script_chan .send(DevtoolScriptControlMsg::Reload(console_actor.pipeline)); } } } stream.write_json_packet(&ReconfigureReply { from: self.name() }); ActorMessageStatus::Processed }, // https://docs.firefox-dev.tools/backend/protocol.html#listing-browser-tabs // (see "To attach to a _targetActor_") "attach" => { let msg = BrowsingContextAttachedReply { from: self.name(), type_: "targetAttached".to_owned(), threadActor: self.thread.clone(), cacheDisabled: false, javascriptEnabled: true, traits: BrowsingContextTraits, }; let console_actor = registry.find::<ConsoleActor>(&self.console); console_actor .streams .borrow_mut() .push(stream.try_clone().unwrap()); stream.write_json_packet(&msg); console_actor .script_chan .send(WantsLiveNotifications(console_actor.pipeline, true)) .unwrap(); ActorMessageStatus::Processed }, //FIXME: The current implementation won't work for multiple connections. Need to ensure 105 // that the correct stream is removed. "detach" => { let msg = BrowsingContextDetachedReply { from: self.name(), type_: "detached".to_owned(), }; let console_actor = registry.find::<ConsoleActor>(&self.console); console_actor.streams.borrow_mut().pop(); stream.write_json_packet(&msg); console_actor .script_chan .send(WantsLiveNotifications(console_actor.pipeline, false)) .unwrap(); ActorMessageStatus::Processed }, "listFrames" => { let msg = ListFramesReply { from: self.name(), frames: vec![], }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, "listWorkers" => { let msg = ListWorkersReply { from: self.name(), workers: vec![], }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, _ => ActorMessageStatus::Ignored, }) } } impl BrowsingContextActor { pub fn encodable(&self) -> BrowsingContextActorMsg { BrowsingContextActorMsg { actor: self.name(), title: self.title.clone(), url: self.url.clone(), outerWindowID: 0, //FIXME: this should probably be the pipeline id consoleActor: self.console.clone(), emulationActor: self.emulation.clone(), inspectorActor: self.inspector.clone(), timelineActor: self.timeline.clone(), profilerActor: self.profiler.clone(), performanceActor: self.performance.clone(), styleSheetsActor: self.styleSheets.clone(), } } }
BrowsingContextActor
identifier_name
browsing_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/. */ //! Liberally derived from the [Firefox JS implementation] //! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webbrowser.js). //! Connection point for remote devtools that wish to investigate a particular Browsing Context's contents. //! Supports dynamic attaching and detaching which control notifications of navigation, etc. use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::actors::console::ConsoleActor; use crate::protocol::JsonPacketStream; use devtools_traits::DevtoolScriptControlMsg::{self, WantsLiveNotifications}; use serde_json::{Map, Value}; use std::net::TcpStream; #[derive(Serialize)] struct BrowsingContextTraits; #[derive(Serialize)] struct BrowsingContextAttachedReply { from: String, #[serde(rename = "type")] type_: String, threadActor: String, cacheDisabled: bool, javascriptEnabled: bool, traits: BrowsingContextTraits, } #[derive(Serialize)] struct BrowsingContextDetachedReply { from: String, #[serde(rename = "type")] type_: String, } #[derive(Serialize)] struct ReconfigureReply { from: String, } #[derive(Serialize)] struct ListFramesReply { from: String, frames: Vec<FrameMsg>, } #[derive(Serialize)] struct FrameMsg { id: u32, url: String, title: String, parentID: u32, } #[derive(Serialize)] struct ListWorkersReply { from: String, workers: Vec<WorkerMsg>, } #[derive(Serialize)] struct WorkerMsg { id: u32, } #[derive(Serialize)] pub struct BrowsingContextActorMsg {
consoleActor: String, emulationActor: String, inspectorActor: String, timelineActor: String, profilerActor: String, performanceActor: String, styleSheetsActor: String, } pub struct BrowsingContextActor { pub name: String, pub title: String, pub url: String, pub console: String, pub emulation: String, pub inspector: String, pub timeline: String, pub profiler: String, pub performance: String, pub styleSheets: String, pub thread: String, } impl Actor for BrowsingContextActor { fn name(&self) -> String { self.name.clone() } fn handle_message( &self, registry: &ActorRegistry, msg_type: &str, msg: &Map<String, Value>, stream: &mut TcpStream, ) -> Result<ActorMessageStatus, ()> { Ok(match msg_type { "reconfigure" => { if let Some(options) = msg.get("options").and_then(|o| o.as_object()) { if let Some(val) = options.get("performReload") { if val.as_bool().unwrap_or(false) { let console_actor = registry.find::<ConsoleActor>(&self.console); let _ = console_actor .script_chan .send(DevtoolScriptControlMsg::Reload(console_actor.pipeline)); } } } stream.write_json_packet(&ReconfigureReply { from: self.name() }); ActorMessageStatus::Processed }, // https://docs.firefox-dev.tools/backend/protocol.html#listing-browser-tabs // (see "To attach to a _targetActor_") "attach" => { let msg = BrowsingContextAttachedReply { from: self.name(), type_: "targetAttached".to_owned(), threadActor: self.thread.clone(), cacheDisabled: false, javascriptEnabled: true, traits: BrowsingContextTraits, }; let console_actor = registry.find::<ConsoleActor>(&self.console); console_actor .streams .borrow_mut() .push(stream.try_clone().unwrap()); stream.write_json_packet(&msg); console_actor .script_chan .send(WantsLiveNotifications(console_actor.pipeline, true)) .unwrap(); ActorMessageStatus::Processed }, //FIXME: The current implementation won't work for multiple connections. Need to ensure 105 // that the correct stream is removed. "detach" => { let msg = BrowsingContextDetachedReply { from: self.name(), type_: "detached".to_owned(), }; let console_actor = registry.find::<ConsoleActor>(&self.console); console_actor.streams.borrow_mut().pop(); stream.write_json_packet(&msg); console_actor .script_chan .send(WantsLiveNotifications(console_actor.pipeline, false)) .unwrap(); ActorMessageStatus::Processed }, "listFrames" => { let msg = ListFramesReply { from: self.name(), frames: vec![], }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, "listWorkers" => { let msg = ListWorkersReply { from: self.name(), workers: vec![], }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, _ => ActorMessageStatus::Ignored, }) } } impl BrowsingContextActor { pub fn encodable(&self) -> BrowsingContextActorMsg { BrowsingContextActorMsg { actor: self.name(), title: self.title.clone(), url: self.url.clone(), outerWindowID: 0, //FIXME: this should probably be the pipeline id consoleActor: self.console.clone(), emulationActor: self.emulation.clone(), inspectorActor: self.inspector.clone(), timelineActor: self.timeline.clone(), profilerActor: self.profiler.clone(), performanceActor: self.performance.clone(), styleSheetsActor: self.styleSheets.clone(), } } }
actor: String, title: String, url: String, outerWindowID: u32,
random_line_split
mirror.rs
// Copyright 2016 The Gfx-rs Developers. // // 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 cocoa::base::{selector, class}; // use cocoa::foundation::{NSUInteger}; use core::{self, shade}; use metal::*; pub fn map_base_type_to_format(ty: shade::BaseType) -> MTLVertexFormat { use core::shade::BaseType::*; match ty { I32 => MTLVertexFormat::Int, U32 => MTLVertexFormat::UInt, F32 => MTLVertexFormat::Float, Bool => MTLVertexFormat::Char2, F64 => { unimplemented!() } } } pub fn populate_vertex_attributes(info: &mut shade::ProgramInfo,
desc: NSArray<MTLVertexAttribute>) { use map::{map_base_type, map_container_type}; for idx in 0..desc.count() { let attr = desc.object_at(idx); info.vertex_attributes.push(shade::AttributeVar { name: attr.name().into(), slot: attr.attribute_index() as core::AttributeSlot, base_type: map_base_type(attr.attribute_type()), container: map_container_type(attr.attribute_type()), }); } } pub fn populate_info(info: &mut shade::ProgramInfo, stage: shade::Stage, args: NSArray<MTLArgument>) { use map::{map_base_type, map_texture_type}; let usage = stage.into(); for idx in 0..args.count() { let arg = args.object_at(idx); let name = arg.name(); match arg.type_() { MTLArgumentType::Buffer => { if name.starts_with("vertexBuffer.") { continue; } info.constant_buffers.push(shade::ConstantBufferVar { name: name.into(), slot: arg.index() as core::ConstantBufferSlot, size: arg.buffer_data_size() as usize, usage: usage, elements: Vec::new(), // TODO! }); } MTLArgumentType::Texture => { info.textures.push(shade::TextureVar { name: name.into(), slot: arg.index() as core::ResourceViewSlot, base_type: map_base_type(arg.texture_data_type()), ty: map_texture_type(arg.texture_type()), usage: usage, }); } MTLArgumentType::Sampler => { let name = name.trim_right_matches('_'); info.samplers.push(shade::SamplerVar { name: name.into(), slot: arg.index() as core::SamplerSlot, ty: shade::SamplerType(shade::IsComparison::NoCompare, shade::IsRect::NoRect), usage: usage, }); } _ => {} } } }
random_line_split
mirror.rs
// Copyright 2016 The Gfx-rs Developers. // // 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 cocoa::base::{selector, class}; // use cocoa::foundation::{NSUInteger}; use core::{self, shade}; use metal::*; pub fn map_base_type_to_format(ty: shade::BaseType) -> MTLVertexFormat { use core::shade::BaseType::*; match ty { I32 => MTLVertexFormat::Int, U32 => MTLVertexFormat::UInt, F32 => MTLVertexFormat::Float, Bool => MTLVertexFormat::Char2, F64 => { unimplemented!() } } } pub fn
(info: &mut shade::ProgramInfo, desc: NSArray<MTLVertexAttribute>) { use map::{map_base_type, map_container_type}; for idx in 0..desc.count() { let attr = desc.object_at(idx); info.vertex_attributes.push(shade::AttributeVar { name: attr.name().into(), slot: attr.attribute_index() as core::AttributeSlot, base_type: map_base_type(attr.attribute_type()), container: map_container_type(attr.attribute_type()), }); } } pub fn populate_info(info: &mut shade::ProgramInfo, stage: shade::Stage, args: NSArray<MTLArgument>) { use map::{map_base_type, map_texture_type}; let usage = stage.into(); for idx in 0..args.count() { let arg = args.object_at(idx); let name = arg.name(); match arg.type_() { MTLArgumentType::Buffer => { if name.starts_with("vertexBuffer.") { continue; } info.constant_buffers.push(shade::ConstantBufferVar { name: name.into(), slot: arg.index() as core::ConstantBufferSlot, size: arg.buffer_data_size() as usize, usage: usage, elements: Vec::new(), // TODO! }); } MTLArgumentType::Texture => { info.textures.push(shade::TextureVar { name: name.into(), slot: arg.index() as core::ResourceViewSlot, base_type: map_base_type(arg.texture_data_type()), ty: map_texture_type(arg.texture_type()), usage: usage, }); } MTLArgumentType::Sampler => { let name = name.trim_right_matches('_'); info.samplers.push(shade::SamplerVar { name: name.into(), slot: arg.index() as core::SamplerSlot, ty: shade::SamplerType(shade::IsComparison::NoCompare, shade::IsRect::NoRect), usage: usage, }); } _ => {} } } }
populate_vertex_attributes
identifier_name
mirror.rs
// Copyright 2016 The Gfx-rs Developers. // // 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 cocoa::base::{selector, class}; // use cocoa::foundation::{NSUInteger}; use core::{self, shade}; use metal::*; pub fn map_base_type_to_format(ty: shade::BaseType) -> MTLVertexFormat { use core::shade::BaseType::*; match ty { I32 => MTLVertexFormat::Int, U32 => MTLVertexFormat::UInt, F32 => MTLVertexFormat::Float, Bool => MTLVertexFormat::Char2, F64 => { unimplemented!() } } } pub fn populate_vertex_attributes(info: &mut shade::ProgramInfo, desc: NSArray<MTLVertexAttribute>)
pub fn populate_info(info: &mut shade::ProgramInfo, stage: shade::Stage, args: NSArray<MTLArgument>) { use map::{map_base_type, map_texture_type}; let usage = stage.into(); for idx in 0..args.count() { let arg = args.object_at(idx); let name = arg.name(); match arg.type_() { MTLArgumentType::Buffer => { if name.starts_with("vertexBuffer.") { continue; } info.constant_buffers.push(shade::ConstantBufferVar { name: name.into(), slot: arg.index() as core::ConstantBufferSlot, size: arg.buffer_data_size() as usize, usage: usage, elements: Vec::new(), // TODO! }); } MTLArgumentType::Texture => { info.textures.push(shade::TextureVar { name: name.into(), slot: arg.index() as core::ResourceViewSlot, base_type: map_base_type(arg.texture_data_type()), ty: map_texture_type(arg.texture_type()), usage: usage, }); } MTLArgumentType::Sampler => { let name = name.trim_right_matches('_'); info.samplers.push(shade::SamplerVar { name: name.into(), slot: arg.index() as core::SamplerSlot, ty: shade::SamplerType(shade::IsComparison::NoCompare, shade::IsRect::NoRect), usage: usage, }); } _ => {} } } }
{ use map::{map_base_type, map_container_type}; for idx in 0..desc.count() { let attr = desc.object_at(idx); info.vertex_attributes.push(shade::AttributeVar { name: attr.name().into(), slot: attr.attribute_index() as core::AttributeSlot, base_type: map_base_type(attr.attribute_type()), container: map_container_type(attr.attribute_type()), }); } }
identifier_body
mirror.rs
// Copyright 2016 The Gfx-rs Developers. // // 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 cocoa::base::{selector, class}; // use cocoa::foundation::{NSUInteger}; use core::{self, shade}; use metal::*; pub fn map_base_type_to_format(ty: shade::BaseType) -> MTLVertexFormat { use core::shade::BaseType::*; match ty { I32 => MTLVertexFormat::Int, U32 => MTLVertexFormat::UInt, F32 => MTLVertexFormat::Float, Bool => MTLVertexFormat::Char2, F64 => { unimplemented!() } } } pub fn populate_vertex_attributes(info: &mut shade::ProgramInfo, desc: NSArray<MTLVertexAttribute>) { use map::{map_base_type, map_container_type}; for idx in 0..desc.count() { let attr = desc.object_at(idx); info.vertex_attributes.push(shade::AttributeVar { name: attr.name().into(), slot: attr.attribute_index() as core::AttributeSlot, base_type: map_base_type(attr.attribute_type()), container: map_container_type(attr.attribute_type()), }); } } pub fn populate_info(info: &mut shade::ProgramInfo, stage: shade::Stage, args: NSArray<MTLArgument>) { use map::{map_base_type, map_texture_type}; let usage = stage.into(); for idx in 0..args.count() { let arg = args.object_at(idx); let name = arg.name(); match arg.type_() { MTLArgumentType::Buffer => { if name.starts_with("vertexBuffer.")
info.constant_buffers.push(shade::ConstantBufferVar { name: name.into(), slot: arg.index() as core::ConstantBufferSlot, size: arg.buffer_data_size() as usize, usage: usage, elements: Vec::new(), // TODO! }); } MTLArgumentType::Texture => { info.textures.push(shade::TextureVar { name: name.into(), slot: arg.index() as core::ResourceViewSlot, base_type: map_base_type(arg.texture_data_type()), ty: map_texture_type(arg.texture_type()), usage: usage, }); } MTLArgumentType::Sampler => { let name = name.trim_right_matches('_'); info.samplers.push(shade::SamplerVar { name: name.into(), slot: arg.index() as core::SamplerSlot, ty: shade::SamplerType(shade::IsComparison::NoCompare, shade::IsRect::NoRect), usage: usage, }); } _ => {} } } }
{ continue; }
conditional_block
calculations.ts
import { DisplayObject } from 'pixi.js'; import { TPositionPair } from './map'; /** * Checks if the value existy. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param value {unknown} value to check * @return {boolean} if the value existy or not */ export const existy = (value: unknown): boolean => { return value !== null && value !== undefined; }; /** * Linear maps a given number in a source range to a target range * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param v {number} value to map * @param min1 {number} minimum value of the source range * @param max1 {number} maximum value of the source range * @param min2 {number} minimum value of the target range * @param max2 {number} maximum value of the target range * @param noOutliers {boolean} If the outlier values won't be processed, default false * @return {number} mapped value according to target range */ export const mathMap = ( v: number, min1: number, max1: number, min2: number, max2: number, noOutliers: boolean = false ): number => { if (noOutliers) { if (v < min1) { return min2; } else if (v > max1) { return max2; } } return min2 + ((max2 - min2) * (v - min1)) / (max1 - min1); }; /** * Produces dot product of two vectors. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param v1 {TPositionPair} first vector * @param v2 {TPositionPair} second vector * @return {number} dot product of two vectors */ export const dotProduct = (v1: TPositionPair, v2: TPositionPair): number => { return v1.x * v2.x + v1.y * v2.y; }; /** * Produces unit vector of a given vector. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param v {TPositionPair} source vector * @return {TPositionPair} unit vector */ export const getUnit = (v: TPositionPair): TPositionPair => { const m = Math.sqrt(v.x * v.x + v.y * v.y); return { x: v.x / m, y: v.y / m }; }; /** * Checks if the given point is the polygon defined by the vertices. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param gp {TPositionPair} point to check * @param vertices {Array(Array(Number))} array containing the vertices of the polygon * @return {boolean} if the point is inside the polygon */ export const isInPolygon = (gp: TPositionPair, vertices: number[][]): boolean => { const testY = gp.y; const testX = gp.x; const nVert = vertices.length; let i, j, c = false; for (i = 0, j = nVert - 1; i < nVert; j = i++) { if ( vertices[i][1] > testY !== vertices[j][1] > testY && testX < ((vertices[j][0] - vertices[i][0]) * (testY - vertices[i][1])) / (vertices[j][1] - vertices[i][1]) + vertices[i][0] ) { c = !c; } } return c; }; /** * Calculates the distance between two points. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param p1 {TPositionPair} first point * @param p2 {TPositionPair} second point * @return {number} the distance between two points */ export const getDist = (p1: TPositionPair, p2: TPositionPair): number => { return Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)); }; /** * Calculates the global point with respect to given local point and scope. * * @method * @function * @private * @internal * @static * * @param lp {TPositionPair} local point * @param scope {PIXI.DisplayObject} local scope * @return {TPositionPair} global point */ export const localToGlobal = (lp: TPositionPair, scope: DisplayObject): TPositionPair => { let sX = scope.position.x + lp.x; let sY = scope.position.y + lp.y; let p = scope.parent; while (p) { sX += p.position.x; sY += p.position.y; p = p.parent; } return { x: sX, y: sY, }; }; /** * Calculates the local point with respect to given global point and local scope. * * @method * @function * @private * @internal * @static * * @param gp {TPositionPair} global point * @param scope {PIXI.DisplayObject} local scope * @return {TPositionPair} local point */ export const globalToLocal = (gp: TPositionPair, scope: DisplayObject): TPositionPair => { let sX = scope.position.x; let sY = scope.position.y; let p = scope.parent; while (p)
return { x: gp.x - sX, y: gp.y - sY, }; };
{ sX += p.position.x; sY += p.position.y; p = p.parent; }
conditional_block
calculations.ts
import { DisplayObject } from 'pixi.js'; import { TPositionPair } from './map'; /** * Checks if the value existy. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param value {unknown} value to check * @return {boolean} if the value existy or not */ export const existy = (value: unknown): boolean => { return value !== null && value !== undefined; }; /** * Linear maps a given number in a source range to a target range * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param v {number} value to map * @param min1 {number} minimum value of the source range * @param max1 {number} maximum value of the source range * @param min2 {number} minimum value of the target range * @param max2 {number} maximum value of the target range * @param noOutliers {boolean} If the outlier values won't be processed, default false * @return {number} mapped value according to target range */ export const mathMap = ( v: number, min1: number, max1: number, min2: number, max2: number, noOutliers: boolean = false ): number => { if (noOutliers) { if (v < min1) { return min2; } else if (v > max1) { return max2; } } return min2 + ((max2 - min2) * (v - min1)) / (max1 - min1); }; /** * Produces dot product of two vectors. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param v1 {TPositionPair} first vector * @param v2 {TPositionPair} second vector * @return {number} dot product of two vectors */ export const dotProduct = (v1: TPositionPair, v2: TPositionPair): number => { return v1.x * v2.x + v1.y * v2.y; }; /** * Produces unit vector of a given vector. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param v {TPositionPair} source vector * @return {TPositionPair} unit vector */ export const getUnit = (v: TPositionPair): TPositionPair => { const m = Math.sqrt(v.x * v.x + v.y * v.y); return { x: v.x / m, y: v.y / m }; }; /** * Checks if the given point is the polygon defined by the vertices. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param gp {TPositionPair} point to check * @param vertices {Array(Array(Number))} array containing the vertices of the polygon * @return {boolean} if the point is inside the polygon */
const nVert = vertices.length; let i, j, c = false; for (i = 0, j = nVert - 1; i < nVert; j = i++) { if ( vertices[i][1] > testY !== vertices[j][1] > testY && testX < ((vertices[j][0] - vertices[i][0]) * (testY - vertices[i][1])) / (vertices[j][1] - vertices[i][1]) + vertices[i][0] ) { c = !c; } } return c; }; /** * Calculates the distance between two points. * * @memberof TRAVISO * @for TRAVISO * * @method * @function * @public * @static * * @param p1 {TPositionPair} first point * @param p2 {TPositionPair} second point * @return {number} the distance between two points */ export const getDist = (p1: TPositionPair, p2: TPositionPair): number => { return Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)); }; /** * Calculates the global point with respect to given local point and scope. * * @method * @function * @private * @internal * @static * * @param lp {TPositionPair} local point * @param scope {PIXI.DisplayObject} local scope * @return {TPositionPair} global point */ export const localToGlobal = (lp: TPositionPair, scope: DisplayObject): TPositionPair => { let sX = scope.position.x + lp.x; let sY = scope.position.y + lp.y; let p = scope.parent; while (p) { sX += p.position.x; sY += p.position.y; p = p.parent; } return { x: sX, y: sY, }; }; /** * Calculates the local point with respect to given global point and local scope. * * @method * @function * @private * @internal * @static * * @param gp {TPositionPair} global point * @param scope {PIXI.DisplayObject} local scope * @return {TPositionPair} local point */ export const globalToLocal = (gp: TPositionPair, scope: DisplayObject): TPositionPair => { let sX = scope.position.x; let sY = scope.position.y; let p = scope.parent; while (p) { sX += p.position.x; sY += p.position.y; p = p.parent; } return { x: gp.x - sX, y: gp.y - sY, }; };
export const isInPolygon = (gp: TPositionPair, vertices: number[][]): boolean => { const testY = gp.y; const testX = gp.x;
random_line_split
timeSeries.ts
namespace nvd3_test_timeSeries { var data = [{ values: [] }]; var i, x; var gap = false; var prevVal = 3000; var tickCount = 100; var probEnterGap = 0.1; var probExitGap = 0.2; var barTimespan = 30 * 60; // thirty minutes in seconds var startOfTime = 1425096000; for (i = 0; i < tickCount; i++) { x = startOfTime + i * barTimespan; if (!gap) { if (Math.random() > probEnterGap) { prevVal += (Math.random() - 0.5) * 500; if (prevVal <= 0) { prevVal = Math.random() * 100; } data[0].values.push({ x: x * 1000, y: prevVal }); } else { gap = true; } } else { if (Math.random() < probExitGap) { gap = false; } } } var chart; var halfBarXMin = data[0].values[0].x - barTimespan / 2 * 1000; var halfBarXMax = data[0].values[data[0].values.length - 1].x + barTimespan / 2 * 1000; function
(location, meaning) { nv.addGraph(function () { chart = nv.models.historicalBarChart(); chart .xScale(d3.time.scale()) // use a time scale instead of plain numbers in order to get nice round default values in the axis .color(['#68c']) .forceX([halfBarXMin, halfBarXMax]) // fix half-bar problem on the first and last bars .useInteractiveGuideline(true) // check out the css that turns the guideline into this nice thing .margin({ "left": 80, "right": 50, "top": 20, "bottom": 30 }) .duration(0) ; var tickMultiFormat = d3.time.format.multi([ ["%-I:%M%p", function (d) { return d.getMinutes(); }], // not the beginning of the hour ["%-I%p", function (d) { return d.getHours(); }], // not midnight ["%b %-d", function (d) { return d.getDate() != 1; }], // not the first of the month ["%b %-d", function (d) { return d.getMonth(); }], // not Jan 1st ["%Y", function () { return true; }] ]); chart.xAxis .showMaxMin(false) .tickPadding(10) .tickFormat(function (d) { return tickMultiFormat(new Date(d)); }) ; chart.yAxis .showMaxMin(false) .tickFormat(d3.format(",.0f")) ; var svgElem = d3.select(location); svgElem .datum(data) .transition() .call(chart); // make our own x-axis tick marks because NVD3 doesn't provide any var tickY2 = chart.yAxis.scale().range()[1]; var lineElems = svgElem .select('.nv-x.nv-axis.nvd3-svg') .select('.nvd3.nv-wrap.nv-axis') .select('g') .selectAll('.tick') .data(chart.xScale().ticks()) .append('line') .attr('class', 'x-axis-tick-mark') .attr('x2', 0) .attr('y1', tickY2 + 4) .attr('y2', tickY2) .attr('stroke-width', 1) ; // set up the tooltip to display full dates var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p'); var contentGenerator = chart.interactiveLayer.tooltip.contentGenerator(); var tooltip = chart.interactiveLayer.tooltip; tooltip.contentGenerator(function (d) { d.value = d.series[0].data.x; return contentGenerator(d); }); tooltip.headerFormatter(function (d) { return tsFormat(new Date(d)); }); // common stuff for the sections below var xScale = chart.xScale(); var xPixelFirstBar = xScale(data[0].values[0].x); var xPixelSecondBar = xScale(data[0].values[0].x + barTimespan * 1000); var barWidth = xPixelSecondBar - xPixelFirstBar; // number of pixels representing time delta per bar // fix the bar widths so they don't overlap when there are gaps function fixBarWidths(barSpacingFraction) { svgElem .selectAll('.nv-bars') .selectAll('rect') .attr('width', (1 - barSpacingFraction) * barWidth) .attr('transform', function (d, i) { var deltaX = xScale(data[0].values[i].x) - xPixelFirstBar; deltaX += barSpacingFraction / 2 * barWidth; return 'translate(' + deltaX + ', 0)'; }) ; } /* If you're representing sample measurements spaced a certain time apart, the tick marks should be in the middle of the bars and some spacing between bars is recommended to aid with interpretation. On the other hand, if you want to represent a quantity measured over a span of time (one bar), you're better off placing the ticks on the edge of the bar and leaving no gap in between bars. */ function shiftXAxis() { var xAxisElem = svgElem.select('.nv-axis.nv-x'); var transform = xAxisElem.attr('transform'); var xShift = -barWidth / 2; transform = transform.replace('0,', xShift + ','); xAxisElem.attr('transform', transform); } if (meaning === 'instant') { fixBarWidths(0.2); } else if (meaning === 'timespan') { fixBarWidths(0.0); shiftXAxis(); } return chart; }); } renderChart('#test1', 'instant'); renderChart('#test2', 'timespan'); window.setTimeout(function () { window.setTimeout(function () { document.getElementById('sc-one').style.display = 'block'; document.getElementById('sc-two').style.display = 'none'; }, 0); }, 0); function switchChartStyle(style) { if (style === 'instant') { document.getElementById('sc-one').style.display = 'block'; document.getElementById('sc-two').style.display = 'none'; } else if (style === 'timespan') { document.getElementById('sc-one').style.display = 'none'; document.getElementById('sc-two').style.display = 'block'; } } }
renderChart
identifier_name
timeSeries.ts
namespace nvd3_test_timeSeries { var data = [{ values: [] }]; var i, x; var gap = false; var prevVal = 3000; var tickCount = 100; var probEnterGap = 0.1; var probExitGap = 0.2; var barTimespan = 30 * 60; // thirty minutes in seconds var startOfTime = 1425096000; for (i = 0; i < tickCount; i++) { x = startOfTime + i * barTimespan; if (!gap) { if (Math.random() > probEnterGap) { prevVal += (Math.random() - 0.5) * 500; if (prevVal <= 0) { prevVal = Math.random() * 100; } data[0].values.push({ x: x * 1000, y: prevVal }); } else { gap = true; } } else { if (Math.random() < probExitGap) { gap = false; } } } var chart; var halfBarXMin = data[0].values[0].x - barTimespan / 2 * 1000; var halfBarXMax = data[0].values[data[0].values.length - 1].x + barTimespan / 2 * 1000; function renderChart(location, meaning) { nv.addGraph(function () { chart = nv.models.historicalBarChart(); chart .xScale(d3.time.scale()) // use a time scale instead of plain numbers in order to get nice round default values in the axis .color(['#68c']) .forceX([halfBarXMin, halfBarXMax]) // fix half-bar problem on the first and last bars .useInteractiveGuideline(true) // check out the css that turns the guideline into this nice thing .margin({ "left": 80, "right": 50, "top": 20, "bottom": 30 }) .duration(0) ; var tickMultiFormat = d3.time.format.multi([ ["%-I:%M%p", function (d) { return d.getMinutes(); }], // not the beginning of the hour ["%-I%p", function (d) { return d.getHours(); }], // not midnight ["%b %-d", function (d) { return d.getDate() != 1; }], // not the first of the month ["%b %-d", function (d) { return d.getMonth(); }], // not Jan 1st ["%Y", function () { return true; }] ]); chart.xAxis .showMaxMin(false) .tickPadding(10) .tickFormat(function (d) { return tickMultiFormat(new Date(d)); }) ; chart.yAxis .showMaxMin(false) .tickFormat(d3.format(",.0f")) ; var svgElem = d3.select(location); svgElem .datum(data) .transition() .call(chart); // make our own x-axis tick marks because NVD3 doesn't provide any var tickY2 = chart.yAxis.scale().range()[1]; var lineElems = svgElem .select('.nv-x.nv-axis.nvd3-svg') .select('.nvd3.nv-wrap.nv-axis') .select('g') .selectAll('.tick') .data(chart.xScale().ticks()) .append('line') .attr('class', 'x-axis-tick-mark') .attr('x2', 0) .attr('y1', tickY2 + 4) .attr('y2', tickY2) .attr('stroke-width', 1) ; // set up the tooltip to display full dates var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p'); var contentGenerator = chart.interactiveLayer.tooltip.contentGenerator(); var tooltip = chart.interactiveLayer.tooltip; tooltip.contentGenerator(function (d) { d.value = d.series[0].data.x; return contentGenerator(d); }); tooltip.headerFormatter(function (d) { return tsFormat(new Date(d)); }); // common stuff for the sections below var xScale = chart.xScale(); var xPixelFirstBar = xScale(data[0].values[0].x); var xPixelSecondBar = xScale(data[0].values[0].x + barTimespan * 1000); var barWidth = xPixelSecondBar - xPixelFirstBar; // number of pixels representing time delta per bar // fix the bar widths so they don't overlap when there are gaps function fixBarWidths(barSpacingFraction) { svgElem .selectAll('.nv-bars') .selectAll('rect') .attr('width', (1 - barSpacingFraction) * barWidth) .attr('transform', function (d, i) { var deltaX = xScale(data[0].values[i].x) - xPixelFirstBar; deltaX += barSpacingFraction / 2 * barWidth; return 'translate(' + deltaX + ', 0)'; }) ; } /* If you're representing sample measurements spaced a certain time apart, the tick marks should be in the middle of the bars and some spacing between bars is recommended to aid with interpretation. On the other hand, if you want to represent a quantity measured over a span of time (one bar), you're better off placing the ticks on the edge of the bar and leaving no gap in between bars. */ function shiftXAxis() { var xAxisElem = svgElem.select('.nv-axis.nv-x'); var transform = xAxisElem.attr('transform'); var xShift = -barWidth / 2; transform = transform.replace('0,', xShift + ','); xAxisElem.attr('transform', transform); } if (meaning === 'instant') { fixBarWidths(0.2); } else if (meaning === 'timespan') { fixBarWidths(0.0); shiftXAxis(); } return chart; }); } renderChart('#test1', 'instant'); renderChart('#test2', 'timespan'); window.setTimeout(function () { window.setTimeout(function () { document.getElementById('sc-one').style.display = 'block'; document.getElementById('sc-two').style.display = 'none'; }, 0); }, 0); function switchChartStyle(style) { if (style === 'instant')
else if (style === 'timespan') { document.getElementById('sc-one').style.display = 'none'; document.getElementById('sc-two').style.display = 'block'; } } }
{ document.getElementById('sc-one').style.display = 'block'; document.getElementById('sc-two').style.display = 'none'; }
conditional_block
timeSeries.ts
namespace nvd3_test_timeSeries { var data = [{ values: [] }]; var i, x; var gap = false; var prevVal = 3000; var tickCount = 100; var probEnterGap = 0.1; var probExitGap = 0.2; var barTimespan = 30 * 60; // thirty minutes in seconds var startOfTime = 1425096000; for (i = 0; i < tickCount; i++) { x = startOfTime + i * barTimespan; if (!gap) { if (Math.random() > probEnterGap) { prevVal += (Math.random() - 0.5) * 500; if (prevVal <= 0) { prevVal = Math.random() * 100; } data[0].values.push({ x: x * 1000, y: prevVal }); } else { gap = true; } } else { if (Math.random() < probExitGap) { gap = false; } } } var chart; var halfBarXMin = data[0].values[0].x - barTimespan / 2 * 1000; var halfBarXMax = data[0].values[data[0].values.length - 1].x + barTimespan / 2 * 1000; function renderChart(location, meaning) { nv.addGraph(function () { chart = nv.models.historicalBarChart(); chart .xScale(d3.time.scale()) // use a time scale instead of plain numbers in order to get nice round default values in the axis .color(['#68c']) .forceX([halfBarXMin, halfBarXMax]) // fix half-bar problem on the first and last bars .useInteractiveGuideline(true) // check out the css that turns the guideline into this nice thing .margin({ "left": 80, "right": 50, "top": 20, "bottom": 30 }) .duration(0) ; var tickMultiFormat = d3.time.format.multi([ ["%-I:%M%p", function (d) { return d.getMinutes(); }], // not the beginning of the hour ["%-I%p", function (d) { return d.getHours(); }], // not midnight ["%b %-d", function (d) { return d.getDate() != 1; }], // not the first of the month ["%b %-d", function (d) { return d.getMonth(); }], // not Jan 1st ["%Y", function () { return true; }] ]); chart.xAxis .showMaxMin(false) .tickPadding(10) .tickFormat(function (d) { return tickMultiFormat(new Date(d)); }) ; chart.yAxis .showMaxMin(false) .tickFormat(d3.format(",.0f")) ; var svgElem = d3.select(location); svgElem .datum(data) .transition() .call(chart); // make our own x-axis tick marks because NVD3 doesn't provide any var tickY2 = chart.yAxis.scale().range()[1]; var lineElems = svgElem .select('.nv-x.nv-axis.nvd3-svg') .select('.nvd3.nv-wrap.nv-axis') .select('g') .selectAll('.tick') .data(chart.xScale().ticks()) .append('line') .attr('class', 'x-axis-tick-mark') .attr('x2', 0) .attr('y1', tickY2 + 4) .attr('y2', tickY2) .attr('stroke-width', 1) ; // set up the tooltip to display full dates var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p'); var contentGenerator = chart.interactiveLayer.tooltip.contentGenerator(); var tooltip = chart.interactiveLayer.tooltip; tooltip.contentGenerator(function (d) { d.value = d.series[0].data.x; return contentGenerator(d); }); tooltip.headerFormatter(function (d) { return tsFormat(new Date(d)); }); // common stuff for the sections below var xScale = chart.xScale(); var xPixelFirstBar = xScale(data[0].values[0].x); var xPixelSecondBar = xScale(data[0].values[0].x + barTimespan * 1000); var barWidth = xPixelSecondBar - xPixelFirstBar; // number of pixels representing time delta per bar // fix the bar widths so they don't overlap when there are gaps function fixBarWidths(barSpacingFraction) { svgElem .selectAll('.nv-bars') .selectAll('rect') .attr('width', (1 - barSpacingFraction) * barWidth) .attr('transform', function (d, i) { var deltaX = xScale(data[0].values[i].x) - xPixelFirstBar; deltaX += barSpacingFraction / 2 * barWidth; return 'translate(' + deltaX + ', 0)'; }) ; } /* If you're representing sample measurements spaced a certain time apart, the tick marks should be in the middle of the bars and some spacing between bars is recommended to aid with interpretation. On the other hand, if you want to represent a quantity measured over a span of time (one bar), you're better off placing the ticks on the edge of the bar and leaving no gap in between bars. */ function shiftXAxis() { var xAxisElem = svgElem.select('.nv-axis.nv-x'); var transform = xAxisElem.attr('transform'); var xShift = -barWidth / 2; transform = transform.replace('0,', xShift + ','); xAxisElem.attr('transform', transform); } if (meaning === 'instant') { fixBarWidths(0.2); } else if (meaning === 'timespan') { fixBarWidths(0.0); shiftXAxis(); } return chart; }); } renderChart('#test1', 'instant'); renderChart('#test2', 'timespan'); window.setTimeout(function () { window.setTimeout(function () { document.getElementById('sc-one').style.display = 'block'; document.getElementById('sc-two').style.display = 'none'; }, 0); }, 0); function switchChartStyle(style)
}
{ if (style === 'instant') { document.getElementById('sc-one').style.display = 'block'; document.getElementById('sc-two').style.display = 'none'; } else if (style === 'timespan') { document.getElementById('sc-one').style.display = 'none'; document.getElementById('sc-two').style.display = 'block'; } }
identifier_body
timeSeries.ts
namespace nvd3_test_timeSeries { var data = [{ values: [] }]; var i, x; var gap = false; var prevVal = 3000; var tickCount = 100; var probEnterGap = 0.1; var probExitGap = 0.2; var barTimespan = 30 * 60; // thirty minutes in seconds var startOfTime = 1425096000; for (i = 0; i < tickCount; i++) { x = startOfTime + i * barTimespan; if (!gap) { if (Math.random() > probEnterGap) { prevVal += (Math.random() - 0.5) * 500; if (prevVal <= 0) { prevVal = Math.random() * 100; } data[0].values.push({ x: x * 1000, y: prevVal }); } else { gap = true; } } else { if (Math.random() < probExitGap) { gap = false; } } } var chart; var halfBarXMin = data[0].values[0].x - barTimespan / 2 * 1000; var halfBarXMax = data[0].values[data[0].values.length - 1].x + barTimespan / 2 * 1000; function renderChart(location, meaning) { nv.addGraph(function () { chart = nv.models.historicalBarChart(); chart .xScale(d3.time.scale()) // use a time scale instead of plain numbers in order to get nice round default values in the axis .color(['#68c'])
.useInteractiveGuideline(true) // check out the css that turns the guideline into this nice thing .margin({ "left": 80, "right": 50, "top": 20, "bottom": 30 }) .duration(0) ; var tickMultiFormat = d3.time.format.multi([ ["%-I:%M%p", function (d) { return d.getMinutes(); }], // not the beginning of the hour ["%-I%p", function (d) { return d.getHours(); }], // not midnight ["%b %-d", function (d) { return d.getDate() != 1; }], // not the first of the month ["%b %-d", function (d) { return d.getMonth(); }], // not Jan 1st ["%Y", function () { return true; }] ]); chart.xAxis .showMaxMin(false) .tickPadding(10) .tickFormat(function (d) { return tickMultiFormat(new Date(d)); }) ; chart.yAxis .showMaxMin(false) .tickFormat(d3.format(",.0f")) ; var svgElem = d3.select(location); svgElem .datum(data) .transition() .call(chart); // make our own x-axis tick marks because NVD3 doesn't provide any var tickY2 = chart.yAxis.scale().range()[1]; var lineElems = svgElem .select('.nv-x.nv-axis.nvd3-svg') .select('.nvd3.nv-wrap.nv-axis') .select('g') .selectAll('.tick') .data(chart.xScale().ticks()) .append('line') .attr('class', 'x-axis-tick-mark') .attr('x2', 0) .attr('y1', tickY2 + 4) .attr('y2', tickY2) .attr('stroke-width', 1) ; // set up the tooltip to display full dates var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p'); var contentGenerator = chart.interactiveLayer.tooltip.contentGenerator(); var tooltip = chart.interactiveLayer.tooltip; tooltip.contentGenerator(function (d) { d.value = d.series[0].data.x; return contentGenerator(d); }); tooltip.headerFormatter(function (d) { return tsFormat(new Date(d)); }); // common stuff for the sections below var xScale = chart.xScale(); var xPixelFirstBar = xScale(data[0].values[0].x); var xPixelSecondBar = xScale(data[0].values[0].x + barTimespan * 1000); var barWidth = xPixelSecondBar - xPixelFirstBar; // number of pixels representing time delta per bar // fix the bar widths so they don't overlap when there are gaps function fixBarWidths(barSpacingFraction) { svgElem .selectAll('.nv-bars') .selectAll('rect') .attr('width', (1 - barSpacingFraction) * barWidth) .attr('transform', function (d, i) { var deltaX = xScale(data[0].values[i].x) - xPixelFirstBar; deltaX += barSpacingFraction / 2 * barWidth; return 'translate(' + deltaX + ', 0)'; }) ; } /* If you're representing sample measurements spaced a certain time apart, the tick marks should be in the middle of the bars and some spacing between bars is recommended to aid with interpretation. On the other hand, if you want to represent a quantity measured over a span of time (one bar), you're better off placing the ticks on the edge of the bar and leaving no gap in between bars. */ function shiftXAxis() { var xAxisElem = svgElem.select('.nv-axis.nv-x'); var transform = xAxisElem.attr('transform'); var xShift = -barWidth / 2; transform = transform.replace('0,', xShift + ','); xAxisElem.attr('transform', transform); } if (meaning === 'instant') { fixBarWidths(0.2); } else if (meaning === 'timespan') { fixBarWidths(0.0); shiftXAxis(); } return chart; }); } renderChart('#test1', 'instant'); renderChart('#test2', 'timespan'); window.setTimeout(function () { window.setTimeout(function () { document.getElementById('sc-one').style.display = 'block'; document.getElementById('sc-two').style.display = 'none'; }, 0); }, 0); function switchChartStyle(style) { if (style === 'instant') { document.getElementById('sc-one').style.display = 'block'; document.getElementById('sc-two').style.display = 'none'; } else if (style === 'timespan') { document.getElementById('sc-one').style.display = 'none'; document.getElementById('sc-two').style.display = 'block'; } } }
.forceX([halfBarXMin, halfBarXMax]) // fix half-bar problem on the first and last bars
random_line_split
api.py
from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import Authorization from tastypie.resources import NamespacedModelResource, fields, ALL, ALL_WITH_RELATIONS from django.contrib.auth.models import User #BUG: Import the correct user object from settings.py from .models import Incident, Status import logging logger = logging.getLogger(__name__) class ReadOnlyFieldNamespacedModelResource(NamespacedModelResource): """ Allows you to add a 'readonly_fields' setting on a ModelResource """ def __init__(self, **kwargs): super(ReadOnlyFieldNamespacedModelResource, self).__init__(**kwargs) for fld in getattr(self.Meta, 'readonly_fields', []): self.fields[fld].readonly = True class
(ReadOnlyFieldNamespacedModelResource): class Meta: detail_uri_name = 'name' queryset = Status.objects.all() allowed_methods = ['get'] resource_name = 'status' authentication = ApiKeyAuthentication() authorization = Authorization() class IncidentResource(ReadOnlyFieldNamespacedModelResource): status = fields.ForeignKey(StatusResource, 'status', full=True, null=True, blank=True) #TODO: We need to include the related user object at some point def hydrate(self, bundle): u = User.objects.get(username=bundle.request.GET['username']) bundle.obj.user = u return bundle class Meta: readonly_fields = ['created', 'updated'] queryset = Incident.objects.all() allowed_methods = ['get', 'post', 'delete'] resource_name = 'incident' authentication = ApiKeyAuthentication() authorization = Authorization() always_return_data = True filtering = { 'created': ALL, 'updates': ALL, 'status': ALL_WITH_RELATIONS, }
StatusResource
identifier_name
api.py
from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import Authorization from tastypie.resources import NamespacedModelResource, fields, ALL, ALL_WITH_RELATIONS from django.contrib.auth.models import User #BUG: Import the correct user object from settings.py from .models import Incident, Status import logging logger = logging.getLogger(__name__) class ReadOnlyFieldNamespacedModelResource(NamespacedModelResource): """ Allows you to add a 'readonly_fields' setting on a ModelResource """ def __init__(self, **kwargs): super(ReadOnlyFieldNamespacedModelResource, self).__init__(**kwargs) for fld in getattr(self.Meta, 'readonly_fields', []): self.fields[fld].readonly = True class StatusResource(ReadOnlyFieldNamespacedModelResource): class Meta: detail_uri_name = 'name' queryset = Status.objects.all() allowed_methods = ['get'] resource_name = 'status' authentication = ApiKeyAuthentication() authorization = Authorization() class IncidentResource(ReadOnlyFieldNamespacedModelResource):
status = fields.ForeignKey(StatusResource, 'status', full=True, null=True, blank=True) #TODO: We need to include the related user object at some point def hydrate(self, bundle): u = User.objects.get(username=bundle.request.GET['username']) bundle.obj.user = u return bundle class Meta: readonly_fields = ['created', 'updated'] queryset = Incident.objects.all() allowed_methods = ['get', 'post', 'delete'] resource_name = 'incident' authentication = ApiKeyAuthentication() authorization = Authorization() always_return_data = True filtering = { 'created': ALL, 'updates': ALL, 'status': ALL_WITH_RELATIONS, }
identifier_body
api.py
from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import Authorization from tastypie.resources import NamespacedModelResource, fields, ALL, ALL_WITH_RELATIONS from django.contrib.auth.models import User #BUG: Import the correct user object from settings.py from .models import Incident, Status import logging logger = logging.getLogger(__name__) class ReadOnlyFieldNamespacedModelResource(NamespacedModelResource): """ Allows you to add a 'readonly_fields' setting on a ModelResource """ def __init__(self, **kwargs): super(ReadOnlyFieldNamespacedModelResource, self).__init__(**kwargs) for fld in getattr(self.Meta, 'readonly_fields', []): self.fields[fld].readonly = True class StatusResource(ReadOnlyFieldNamespacedModelResource): class Meta: detail_uri_name = 'name' queryset = Status.objects.all() allowed_methods = ['get'] resource_name = 'status' authentication = ApiKeyAuthentication() authorization = Authorization() class IncidentResource(ReadOnlyFieldNamespacedModelResource): status = fields.ForeignKey(StatusResource, 'status', full=True, null=True, blank=True) #TODO: We need to include the related user object at some point def hydrate(self, bundle): u = User.objects.get(username=bundle.request.GET['username']) bundle.obj.user = u return bundle class Meta: readonly_fields = ['created', 'updated']
always_return_data = True filtering = { 'created': ALL, 'updates': ALL, 'status': ALL_WITH_RELATIONS, }
queryset = Incident.objects.all() allowed_methods = ['get', 'post', 'delete'] resource_name = 'incident' authentication = ApiKeyAuthentication() authorization = Authorization()
random_line_split
api.py
from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import Authorization from tastypie.resources import NamespacedModelResource, fields, ALL, ALL_WITH_RELATIONS from django.contrib.auth.models import User #BUG: Import the correct user object from settings.py from .models import Incident, Status import logging logger = logging.getLogger(__name__) class ReadOnlyFieldNamespacedModelResource(NamespacedModelResource): """ Allows you to add a 'readonly_fields' setting on a ModelResource """ def __init__(self, **kwargs): super(ReadOnlyFieldNamespacedModelResource, self).__init__(**kwargs) for fld in getattr(self.Meta, 'readonly_fields', []):
class StatusResource(ReadOnlyFieldNamespacedModelResource): class Meta: detail_uri_name = 'name' queryset = Status.objects.all() allowed_methods = ['get'] resource_name = 'status' authentication = ApiKeyAuthentication() authorization = Authorization() class IncidentResource(ReadOnlyFieldNamespacedModelResource): status = fields.ForeignKey(StatusResource, 'status', full=True, null=True, blank=True) #TODO: We need to include the related user object at some point def hydrate(self, bundle): u = User.objects.get(username=bundle.request.GET['username']) bundle.obj.user = u return bundle class Meta: readonly_fields = ['created', 'updated'] queryset = Incident.objects.all() allowed_methods = ['get', 'post', 'delete'] resource_name = 'incident' authentication = ApiKeyAuthentication() authorization = Authorization() always_return_data = True filtering = { 'created': ALL, 'updates': ALL, 'status': ALL_WITH_RELATIONS, }
self.fields[fld].readonly = True
conditional_block
test_parser.py
""" This file is part of Maml. Maml 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. Maml 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 Maml. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Brian Hawthorne """ from unittest import TestCase from maml.parser import * example1 = """ -def A(z) %ul %li %html %body %h3 """ example2 = """ -def A(z) %ul -for x in range(z) .list-item#item_id = x foo %html %body %h3 yup = A(6) """ class TestParser (TestCase): def test_tag_attrs(self): good_results = { '()': ('(', '', ')'), '{}': ('{', '', '}'), '(borp="baz" dorp="daz" blarp="blaz")': ('(', 'borp="baz" dorp="daz" blarp="blaz"', ')'), '{borp:"baz", dorp:"daz", blarp:"blaz"}': ('{', 'borp:"baz", dorp:"daz", blarp:"blaz"', '}'), } for input, output in good_results.items(): self.assertEqual(tuple(tag_attrs.parseString(input)), output) def test_tag_decl(self): good_results = { '%html': ('%', 'html', ''), '%html foo': ('%', 'html', 'foo'), '%html= foo': ('%', 'html', '=', 'foo'), '%html()= foo': ('%', 'html', '(', '', ')', '=', 'foo'), '%html.class-name()= foo': ('%', 'html', '.', 'class-name', '(', '', ')', '=', 'foo'), '%html.class-name(borp="baz")= foo': ('%', 'html', '.', 'class-name', '(', 'borp="baz"', ')', '=', 'foo'), '#foo.boo': ('#', 'foo', '.', 'boo', ''), '.foo(){}': ('.', 'foo', '(', '', ')', '{', '', '}', ''), } for input, output in good_results.items(): self.assertEqual(tuple(tag_decl.parseString(input)), output) def test_namespace(self):
namespace_example = "-namespace(/common/defs.mak, bnorp)" assert Parser().parse(namespace_example).render_string()
identifier_body
test_parser.py
""" This file is part of Maml. Maml 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. Maml 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 Maml. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Brian Hawthorne """ from unittest import TestCase from maml.parser import * example1 = """ -def A(z) %ul %li %html %body %h3 """ example2 = """ -def A(z) %ul -for x in range(z) .list-item#item_id = x foo %html %body %h3 yup = A(6) """ class TestParser (TestCase): def test_tag_attrs(self): good_results = { '()': ('(', '', ')'), '{}': ('{', '', '}'), '(borp="baz" dorp="daz" blarp="blaz")': ('(', 'borp="baz" dorp="daz" blarp="blaz"', ')'), '{borp:"baz", dorp:"daz", blarp:"blaz"}': ('{', 'borp:"baz", dorp:"daz", blarp:"blaz"', '}'), } for input, output in good_results.items(): self.assertEqual(tuple(tag_attrs.parseString(input)), output) def test_tag_decl(self): good_results = { '%html': ('%', 'html', ''), '%html foo': ('%', 'html', 'foo'), '%html= foo': ('%', 'html', '=', 'foo'), '%html()= foo': ('%', 'html', '(', '', ')', '=', 'foo'), '%html.class-name()= foo': ('%', 'html', '.', 'class-name', '(', '', ')', '=', 'foo'), '%html.class-name(borp="baz")= foo': ('%', 'html', '.', 'class-name', '(', 'borp="baz"', ')', '=', 'foo'), '#foo.boo': ('#', 'foo', '.', 'boo', ''),
'.foo(){}': ('.', 'foo', '(', '', ')', '{', '', '}', ''), } for input, output in good_results.items(): self.assertEqual(tuple(tag_decl.parseString(input)), output) def test_namespace(self): namespace_example = "-namespace(/common/defs.mak, bnorp)" assert Parser().parse(namespace_example).render_string()
random_line_split
test_parser.py
""" This file is part of Maml. Maml 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. Maml 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 Maml. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Brian Hawthorne """ from unittest import TestCase from maml.parser import * example1 = """ -def A(z) %ul %li %html %body %h3 """ example2 = """ -def A(z) %ul -for x in range(z) .list-item#item_id = x foo %html %body %h3 yup = A(6) """ class TestParser (TestCase): def test_tag_attrs(self): good_results = { '()': ('(', '', ')'), '{}': ('{', '', '}'), '(borp="baz" dorp="daz" blarp="blaz")': ('(', 'borp="baz" dorp="daz" blarp="blaz"', ')'), '{borp:"baz", dorp:"daz", blarp:"blaz"}': ('{', 'borp:"baz", dorp:"daz", blarp:"blaz"', '}'), } for input, output in good_results.items(): self.assertEqual(tuple(tag_attrs.parseString(input)), output) def test_tag_decl(self): good_results = { '%html': ('%', 'html', ''), '%html foo': ('%', 'html', 'foo'), '%html= foo': ('%', 'html', '=', 'foo'), '%html()= foo': ('%', 'html', '(', '', ')', '=', 'foo'), '%html.class-name()= foo': ('%', 'html', '.', 'class-name', '(', '', ')', '=', 'foo'), '%html.class-name(borp="baz")= foo': ('%', 'html', '.', 'class-name', '(', 'borp="baz"', ')', '=', 'foo'), '#foo.boo': ('#', 'foo', '.', 'boo', ''), '.foo(){}': ('.', 'foo', '(', '', ')', '{', '', '}', ''), } for input, output in good_results.items(): self.assertEqual(tuple(tag_decl.parseString(input)), output) def
(self): namespace_example = "-namespace(/common/defs.mak, bnorp)" assert Parser().parse(namespace_example).render_string()
test_namespace
identifier_name
test_parser.py
""" This file is part of Maml. Maml 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. Maml 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 Maml. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Brian Hawthorne """ from unittest import TestCase from maml.parser import * example1 = """ -def A(z) %ul %li %html %body %h3 """ example2 = """ -def A(z) %ul -for x in range(z) .list-item#item_id = x foo %html %body %h3 yup = A(6) """ class TestParser (TestCase): def test_tag_attrs(self): good_results = { '()': ('(', '', ')'), '{}': ('{', '', '}'), '(borp="baz" dorp="daz" blarp="blaz")': ('(', 'borp="baz" dorp="daz" blarp="blaz"', ')'), '{borp:"baz", dorp:"daz", blarp:"blaz"}': ('{', 'borp:"baz", dorp:"daz", blarp:"blaz"', '}'), } for input, output in good_results.items():
def test_tag_decl(self): good_results = { '%html': ('%', 'html', ''), '%html foo': ('%', 'html', 'foo'), '%html= foo': ('%', 'html', '=', 'foo'), '%html()= foo': ('%', 'html', '(', '', ')', '=', 'foo'), '%html.class-name()= foo': ('%', 'html', '.', 'class-name', '(', '', ')', '=', 'foo'), '%html.class-name(borp="baz")= foo': ('%', 'html', '.', 'class-name', '(', 'borp="baz"', ')', '=', 'foo'), '#foo.boo': ('#', 'foo', '.', 'boo', ''), '.foo(){}': ('.', 'foo', '(', '', ')', '{', '', '}', ''), } for input, output in good_results.items(): self.assertEqual(tuple(tag_decl.parseString(input)), output) def test_namespace(self): namespace_example = "-namespace(/common/defs.mak, bnorp)" assert Parser().parse(namespace_example).render_string()
self.assertEqual(tuple(tag_attrs.parseString(input)), output)
conditional_block
udp_dispatcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Tamas Gal <tgal@km3net.de> # License: MIT #!/usr/bin/env python # vim: ts=4 sw=4 et """ ============================= UDP Forwarder for ControlHost ============================= A simple UDP forwarder for ControlHost messages. This application is used to forward monitoring channel data from Ligier to a given UDP address. """ import socket import sys import km3pipe as kp __author__ = "Tamas Gal" __email__ = "tgal@km3net.de" class UDPForwarder(kp.Module):
pipe = kp.Pipeline() pipe.attach( kp.io.CHPump, host="localhost", port=5553, tags="IO_MONIT", timeout=60 * 60 * 24 * 7, max_queue=1000, timeit=True, ) pipe.attach(UDPForwarder) pipe.drain()
def configure(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.counter = 0 def process(self, blob): if str(blob["CHPrefix"].tag) == "IO_MONIT": self.sock.sendto(blob["CHData"], ("127.0.0.1", 56017)) if self.counter % 100 == 0: sys.stdout.write(".") sys.stdout.flush() self.counter += 1 return blob
identifier_body
udp_dispatcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Tamas Gal <tgal@km3net.de> # License: MIT #!/usr/bin/env python # vim: ts=4 sw=4 et """ =============================
This application is used to forward monitoring channel data from Ligier to a given UDP address. """ import socket import sys import km3pipe as kp __author__ = "Tamas Gal" __email__ = "tgal@km3net.de" class UDPForwarder(kp.Module): def configure(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.counter = 0 def process(self, blob): if str(blob["CHPrefix"].tag) == "IO_MONIT": self.sock.sendto(blob["CHData"], ("127.0.0.1", 56017)) if self.counter % 100 == 0: sys.stdout.write(".") sys.stdout.flush() self.counter += 1 return blob pipe = kp.Pipeline() pipe.attach( kp.io.CHPump, host="localhost", port=5553, tags="IO_MONIT", timeout=60 * 60 * 24 * 7, max_queue=1000, timeit=True, ) pipe.attach(UDPForwarder) pipe.drain()
UDP Forwarder for ControlHost ============================= A simple UDP forwarder for ControlHost messages.
random_line_split
udp_dispatcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Tamas Gal <tgal@km3net.de> # License: MIT #!/usr/bin/env python # vim: ts=4 sw=4 et """ ============================= UDP Forwarder for ControlHost ============================= A simple UDP forwarder for ControlHost messages. This application is used to forward monitoring channel data from Ligier to a given UDP address. """ import socket import sys import km3pipe as kp __author__ = "Tamas Gal" __email__ = "tgal@km3net.de" class UDPForwarder(kp.Module): def configure(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.counter = 0 def process(self, blob): if str(blob["CHPrefix"].tag) == "IO_MONIT":
return blob pipe = kp.Pipeline() pipe.attach( kp.io.CHPump, host="localhost", port=5553, tags="IO_MONIT", timeout=60 * 60 * 24 * 7, max_queue=1000, timeit=True, ) pipe.attach(UDPForwarder) pipe.drain()
self.sock.sendto(blob["CHData"], ("127.0.0.1", 56017)) if self.counter % 100 == 0: sys.stdout.write(".") sys.stdout.flush() self.counter += 1
conditional_block
udp_dispatcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Tamas Gal <tgal@km3net.de> # License: MIT #!/usr/bin/env python # vim: ts=4 sw=4 et """ ============================= UDP Forwarder for ControlHost ============================= A simple UDP forwarder for ControlHost messages. This application is used to forward monitoring channel data from Ligier to a given UDP address. """ import socket import sys import km3pipe as kp __author__ = "Tamas Gal" __email__ = "tgal@km3net.de" class UDPForwarder(kp.Module): def
(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.counter = 0 def process(self, blob): if str(blob["CHPrefix"].tag) == "IO_MONIT": self.sock.sendto(blob["CHData"], ("127.0.0.1", 56017)) if self.counter % 100 == 0: sys.stdout.write(".") sys.stdout.flush() self.counter += 1 return blob pipe = kp.Pipeline() pipe.attach( kp.io.CHPump, host="localhost", port=5553, tags="IO_MONIT", timeout=60 * 60 * 24 * 7, max_queue=1000, timeit=True, ) pipe.attach(UDPForwarder) pipe.drain()
configure
identifier_name
l2_ofcommand_learning.py
# Copyright 2011 Kyriakos Zarifis # Copyright 2008 (C) Nicira, Inc. # # This file is part of POX. # # POX 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. # # POX 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 POX. If not, see <http://www.gnu.org/licenses/>. """ This is an L2 learning switch derived originally from NOX's pyswitch example. It is now a demonstration of the ofcommand library for constructing OpenFlow messages. """ from time import time # TODO: mac_to_str and mact_to_int aren't currently defined in packet_utils... #from pox.lib.packet.packet_utils import mac_to_str, mac_to_int from pox.lib.packet.ethernet import ethernet from pox.lib.packet.tcp import tcp from pox.lib.packet.udp import udp from pox.lib.packet.vlan import vlan from pox.lib.packet.ipv4 import ipv4 from pox.lib.packet.icmp import icmp from pox.lib.packet.ethernet import ethernet from pox.core import core from pox.lib.revent import * from pox.lib.addresses import EthAddr log = core.getLogger() import pox.openflow.ofcommand as ofcommand class dumb_l2_switch (EventMixin): def __init__ (self): log.info("Starting") self.listenTo(core) self.st = {} def _handle_GoingUpEvent (self, event): self.listenTo(core.openflow) def _handle_PacketIn (self, event): """Packet entry method. Drop LLDP packets (or we get confused) and attempt learning and forwarding """ con = event.connection dpid = event.connection.dpid inport = event.port packet = event.parse() buffer_id = event.ofp.buffer_id if not packet.parsed: log.warning("%i %i ignoring unparsed packet", dpid, inport) return if not con in self.st: log.info('registering new switch ' + str(dpid)) self.st[con] = {} # don't forward lldp packets if packet.type == ethernet.LLDP_TYPE: return # learn MAC on incoming port self.do_l2_learning(con, inport, packet) # forward packet self.forward_l2_packet(con, inport, packet, packet.arr, buffer_id)
"""Given a packet, learn the source and peg to a switch/inport """ # learn MAC on incoming port srcaddr = EthAddr(packet.src) #if ord(srcaddr[0]) & 1: # return if self.st[con].has_key(srcaddr.toStr()): # change to raw? # we had already heard from this switch dst = self.st[con][srcaddr.toStr()] # raw? if dst[0] != inport: # but from a different port log.info('MAC has moved from '+str(dst)+'to'+str(inport)) else: return else: log.info('learned MAC '+srcaddr.toStr()+' on Switch %s, Port %d'% (con.dpid,inport)) # learn or update timestamp of entry self.st[con][srcaddr.toStr()] = (inport, time(), packet) # raw? # Replace any old entry for (switch,mac). #mac = mac_to_int(packet.src) def forward_l2_packet(self, con, inport, packet, buf, bufid): """If we've learned the destination MAC set up a flow and send only out of its inport. Else, flood. """ dstaddr = EthAddr(packet.dst) #if not ord(dstaddr[0]) & 1 and # what did this do? if self.st[con].has_key(dstaddr.toStr()): # raw? prt = self.st[con][dstaddr.toStr()] # raw? if prt[0] == inport: log.warning('**warning** learned port = inport') ofcommand.floodPacket(con, inport, packet, buf, bufid) else: # We know the outport, set up a flow log.info('installing flow for ' + str(packet)) match = ofcommand.extractMatch(packet) actions = [ofcommand.Output(prt[0])] ofcommand.addFlowEntry(con, inport, match, actions, bufid) # Separate bufid, make addFlowEntry() only ADD the entry # send/wait for Barrier # sendBufferedPacket(bufid) else: # haven't learned destination MAC. Flood ofcommand.floodPacket(con, inport, packet, buf, bufid) ''' add arp cache timeout? # Timeout for cached MAC entries CACHE_TIMEOUT = 5 def timer_callback(): """Responsible for timing out cache entries. Called every 1 second. """ global st curtime = time() for con in st.keys(): for entry in st[con].keys(): if (curtime - st[con][entry][1]) > CACHE_TIMEOUT: con.msg('timing out entry '+mac_to_str(entry)+" -> "+str(st[con][entry][0])+' on switch ' + str(con)) st[con].pop(entry) '''
def do_l2_learning(self, con, inport, packet):
random_line_split
l2_ofcommand_learning.py
# Copyright 2011 Kyriakos Zarifis # Copyright 2008 (C) Nicira, Inc. # # This file is part of POX. # # POX 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. # # POX 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 POX. If not, see <http://www.gnu.org/licenses/>. """ This is an L2 learning switch derived originally from NOX's pyswitch example. It is now a demonstration of the ofcommand library for constructing OpenFlow messages. """ from time import time # TODO: mac_to_str and mact_to_int aren't currently defined in packet_utils... #from pox.lib.packet.packet_utils import mac_to_str, mac_to_int from pox.lib.packet.ethernet import ethernet from pox.lib.packet.tcp import tcp from pox.lib.packet.udp import udp from pox.lib.packet.vlan import vlan from pox.lib.packet.ipv4 import ipv4 from pox.lib.packet.icmp import icmp from pox.lib.packet.ethernet import ethernet from pox.core import core from pox.lib.revent import * from pox.lib.addresses import EthAddr log = core.getLogger() import pox.openflow.ofcommand as ofcommand class dumb_l2_switch (EventMixin): def
(self): log.info("Starting") self.listenTo(core) self.st = {} def _handle_GoingUpEvent (self, event): self.listenTo(core.openflow) def _handle_PacketIn (self, event): """Packet entry method. Drop LLDP packets (or we get confused) and attempt learning and forwarding """ con = event.connection dpid = event.connection.dpid inport = event.port packet = event.parse() buffer_id = event.ofp.buffer_id if not packet.parsed: log.warning("%i %i ignoring unparsed packet", dpid, inport) return if not con in self.st: log.info('registering new switch ' + str(dpid)) self.st[con] = {} # don't forward lldp packets if packet.type == ethernet.LLDP_TYPE: return # learn MAC on incoming port self.do_l2_learning(con, inport, packet) # forward packet self.forward_l2_packet(con, inport, packet, packet.arr, buffer_id) def do_l2_learning(self, con, inport, packet): """Given a packet, learn the source and peg to a switch/inport """ # learn MAC on incoming port srcaddr = EthAddr(packet.src) #if ord(srcaddr[0]) & 1: # return if self.st[con].has_key(srcaddr.toStr()): # change to raw? # we had already heard from this switch dst = self.st[con][srcaddr.toStr()] # raw? if dst[0] != inport: # but from a different port log.info('MAC has moved from '+str(dst)+'to'+str(inport)) else: return else: log.info('learned MAC '+srcaddr.toStr()+' on Switch %s, Port %d'% (con.dpid,inport)) # learn or update timestamp of entry self.st[con][srcaddr.toStr()] = (inport, time(), packet) # raw? # Replace any old entry for (switch,mac). #mac = mac_to_int(packet.src) def forward_l2_packet(self, con, inport, packet, buf, bufid): """If we've learned the destination MAC set up a flow and send only out of its inport. Else, flood. """ dstaddr = EthAddr(packet.dst) #if not ord(dstaddr[0]) & 1 and # what did this do? if self.st[con].has_key(dstaddr.toStr()): # raw? prt = self.st[con][dstaddr.toStr()] # raw? if prt[0] == inport: log.warning('**warning** learned port = inport') ofcommand.floodPacket(con, inport, packet, buf, bufid) else: # We know the outport, set up a flow log.info('installing flow for ' + str(packet)) match = ofcommand.extractMatch(packet) actions = [ofcommand.Output(prt[0])] ofcommand.addFlowEntry(con, inport, match, actions, bufid) # Separate bufid, make addFlowEntry() only ADD the entry # send/wait for Barrier # sendBufferedPacket(bufid) else: # haven't learned destination MAC. Flood ofcommand.floodPacket(con, inport, packet, buf, bufid) ''' add arp cache timeout? # Timeout for cached MAC entries CACHE_TIMEOUT = 5 def timer_callback(): """Responsible for timing out cache entries. Called every 1 second. """ global st curtime = time() for con in st.keys(): for entry in st[con].keys(): if (curtime - st[con][entry][1]) > CACHE_TIMEOUT: con.msg('timing out entry '+mac_to_str(entry)+" -> "+str(st[con][entry][0])+' on switch ' + str(con)) st[con].pop(entry) '''
__init__
identifier_name
l2_ofcommand_learning.py
# Copyright 2011 Kyriakos Zarifis # Copyright 2008 (C) Nicira, Inc. # # This file is part of POX. # # POX 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. # # POX 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 POX. If not, see <http://www.gnu.org/licenses/>. """ This is an L2 learning switch derived originally from NOX's pyswitch example. It is now a demonstration of the ofcommand library for constructing OpenFlow messages. """ from time import time # TODO: mac_to_str and mact_to_int aren't currently defined in packet_utils... #from pox.lib.packet.packet_utils import mac_to_str, mac_to_int from pox.lib.packet.ethernet import ethernet from pox.lib.packet.tcp import tcp from pox.lib.packet.udp import udp from pox.lib.packet.vlan import vlan from pox.lib.packet.ipv4 import ipv4 from pox.lib.packet.icmp import icmp from pox.lib.packet.ethernet import ethernet from pox.core import core from pox.lib.revent import * from pox.lib.addresses import EthAddr log = core.getLogger() import pox.openflow.ofcommand as ofcommand class dumb_l2_switch (EventMixin):
''' add arp cache timeout? # Timeout for cached MAC entries CACHE_TIMEOUT = 5 def timer_callback(): """Responsible for timing out cache entries. Called every 1 second. """ global st curtime = time() for con in st.keys(): for entry in st[con].keys(): if (curtime - st[con][entry][1]) > CACHE_TIMEOUT: con.msg('timing out entry '+mac_to_str(entry)+" -> "+str(st[con][entry][0])+' on switch ' + str(con)) st[con].pop(entry) '''
def __init__ (self): log.info("Starting") self.listenTo(core) self.st = {} def _handle_GoingUpEvent (self, event): self.listenTo(core.openflow) def _handle_PacketIn (self, event): """Packet entry method. Drop LLDP packets (or we get confused) and attempt learning and forwarding """ con = event.connection dpid = event.connection.dpid inport = event.port packet = event.parse() buffer_id = event.ofp.buffer_id if not packet.parsed: log.warning("%i %i ignoring unparsed packet", dpid, inport) return if not con in self.st: log.info('registering new switch ' + str(dpid)) self.st[con] = {} # don't forward lldp packets if packet.type == ethernet.LLDP_TYPE: return # learn MAC on incoming port self.do_l2_learning(con, inport, packet) # forward packet self.forward_l2_packet(con, inport, packet, packet.arr, buffer_id) def do_l2_learning(self, con, inport, packet): """Given a packet, learn the source and peg to a switch/inport """ # learn MAC on incoming port srcaddr = EthAddr(packet.src) #if ord(srcaddr[0]) & 1: # return if self.st[con].has_key(srcaddr.toStr()): # change to raw? # we had already heard from this switch dst = self.st[con][srcaddr.toStr()] # raw? if dst[0] != inport: # but from a different port log.info('MAC has moved from '+str(dst)+'to'+str(inport)) else: return else: log.info('learned MAC '+srcaddr.toStr()+' on Switch %s, Port %d'% (con.dpid,inport)) # learn or update timestamp of entry self.st[con][srcaddr.toStr()] = (inport, time(), packet) # raw? # Replace any old entry for (switch,mac). #mac = mac_to_int(packet.src) def forward_l2_packet(self, con, inport, packet, buf, bufid): """If we've learned the destination MAC set up a flow and send only out of its inport. Else, flood. """ dstaddr = EthAddr(packet.dst) #if not ord(dstaddr[0]) & 1 and # what did this do? if self.st[con].has_key(dstaddr.toStr()): # raw? prt = self.st[con][dstaddr.toStr()] # raw? if prt[0] == inport: log.warning('**warning** learned port = inport') ofcommand.floodPacket(con, inport, packet, buf, bufid) else: # We know the outport, set up a flow log.info('installing flow for ' + str(packet)) match = ofcommand.extractMatch(packet) actions = [ofcommand.Output(prt[0])] ofcommand.addFlowEntry(con, inport, match, actions, bufid) # Separate bufid, make addFlowEntry() only ADD the entry # send/wait for Barrier # sendBufferedPacket(bufid) else: # haven't learned destination MAC. Flood ofcommand.floodPacket(con, inport, packet, buf, bufid)
identifier_body
l2_ofcommand_learning.py
# Copyright 2011 Kyriakos Zarifis # Copyright 2008 (C) Nicira, Inc. # # This file is part of POX. # # POX 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. # # POX 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 POX. If not, see <http://www.gnu.org/licenses/>. """ This is an L2 learning switch derived originally from NOX's pyswitch example. It is now a demonstration of the ofcommand library for constructing OpenFlow messages. """ from time import time # TODO: mac_to_str and mact_to_int aren't currently defined in packet_utils... #from pox.lib.packet.packet_utils import mac_to_str, mac_to_int from pox.lib.packet.ethernet import ethernet from pox.lib.packet.tcp import tcp from pox.lib.packet.udp import udp from pox.lib.packet.vlan import vlan from pox.lib.packet.ipv4 import ipv4 from pox.lib.packet.icmp import icmp from pox.lib.packet.ethernet import ethernet from pox.core import core from pox.lib.revent import * from pox.lib.addresses import EthAddr log = core.getLogger() import pox.openflow.ofcommand as ofcommand class dumb_l2_switch (EventMixin): def __init__ (self): log.info("Starting") self.listenTo(core) self.st = {} def _handle_GoingUpEvent (self, event): self.listenTo(core.openflow) def _handle_PacketIn (self, event): """Packet entry method. Drop LLDP packets (or we get confused) and attempt learning and forwarding """ con = event.connection dpid = event.connection.dpid inport = event.port packet = event.parse() buffer_id = event.ofp.buffer_id if not packet.parsed: log.warning("%i %i ignoring unparsed packet", dpid, inport) return if not con in self.st: log.info('registering new switch ' + str(dpid)) self.st[con] = {} # don't forward lldp packets if packet.type == ethernet.LLDP_TYPE: return # learn MAC on incoming port self.do_l2_learning(con, inport, packet) # forward packet self.forward_l2_packet(con, inport, packet, packet.arr, buffer_id) def do_l2_learning(self, con, inport, packet): """Given a packet, learn the source and peg to a switch/inport """ # learn MAC on incoming port srcaddr = EthAddr(packet.src) #if ord(srcaddr[0]) & 1: # return if self.st[con].has_key(srcaddr.toStr()): # change to raw? # we had already heard from this switch dst = self.st[con][srcaddr.toStr()] # raw? if dst[0] != inport: # but from a different port log.info('MAC has moved from '+str(dst)+'to'+str(inport)) else: return else: log.info('learned MAC '+srcaddr.toStr()+' on Switch %s, Port %d'% (con.dpid,inport)) # learn or update timestamp of entry self.st[con][srcaddr.toStr()] = (inport, time(), packet) # raw? # Replace any old entry for (switch,mac). #mac = mac_to_int(packet.src) def forward_l2_packet(self, con, inport, packet, buf, bufid): """If we've learned the destination MAC set up a flow and send only out of its inport. Else, flood. """ dstaddr = EthAddr(packet.dst) #if not ord(dstaddr[0]) & 1 and # what did this do? if self.st[con].has_key(dstaddr.toStr()): # raw? prt = self.st[con][dstaddr.toStr()] # raw? if prt[0] == inport:
else: # We know the outport, set up a flow log.info('installing flow for ' + str(packet)) match = ofcommand.extractMatch(packet) actions = [ofcommand.Output(prt[0])] ofcommand.addFlowEntry(con, inport, match, actions, bufid) # Separate bufid, make addFlowEntry() only ADD the entry # send/wait for Barrier # sendBufferedPacket(bufid) else: # haven't learned destination MAC. Flood ofcommand.floodPacket(con, inport, packet, buf, bufid) ''' add arp cache timeout? # Timeout for cached MAC entries CACHE_TIMEOUT = 5 def timer_callback(): """Responsible for timing out cache entries. Called every 1 second. """ global st curtime = time() for con in st.keys(): for entry in st[con].keys(): if (curtime - st[con][entry][1]) > CACHE_TIMEOUT: con.msg('timing out entry '+mac_to_str(entry)+" -> "+str(st[con][entry][0])+' on switch ' + str(con)) st[con].pop(entry) '''
log.warning('**warning** learned port = inport') ofcommand.floodPacket(con, inport, packet, buf, bufid)
conditional_block
NavigationHome.js
CanyonRunner.NavigationHome = function (game) { this.advanceButton = null; }; CanyonRunner.NavigationHome.prototype = { create: function () { this.sound = this.game.add.audioSprite('sound'); //Show Navigation Supply Screen this.background = this.add.sprite(0, 0, 'sprites', 'navigation-home'); ///////////////////////////// //CREATE SOUND TOGGLE BUTTON ///////////////////////////// this.mute = false; this.soundButton = this.game.add.button(this.game.world.centerX + 240, this.game.world.centerY -290, 'sprites', this.toggleMute, this, 'sound-icon', 'sound-icon', 'sound-icon'); this.soundButton.fixedToCamera = true; if (!this.game.sound.mute)
else { this.soundButton.tint = 16711680; } this.advanceButton = this.add.button(320, 500, 'sprites', this.startGame, this, 'start-button', 'start-button', 'start-button'); //Set Content this.content = [ " ", "Night Falls. You Approach Your Home Sector", "There Are 50 Major Spires To Avoid Here...", "Heavy Meteor Showers Detected In This Area", "You Must Obtain a Fix On Your Home Beacon", "Navigate Through the Storm. Ping Your Home." ]; this.index = 0; this.line = ''; //Show Specific Level Objective Text this.level1ObjectiveTextStyle = { font: "35px Helvetica", fill: "#05c619", stroke: "#000", strokeThickness: 10, align: "center" }; this.text = this.game.add.text(this.game.world.centerX - 350, this.game.world.centerY -275, this.level1ObjectiveTextString, this.level1ObjectiveTextStyle); //Loop Sonar Sound on This Screen this.sound.play('sonar'); this.nextLine(); }, updateLine: function() { if (this.line.length < this.content[this.index].length) { this.line = this.content[this.index].substr(0, this.line.length + 1); this.text.setText(this.line); } else { this.game.time.events.add(Phaser.Timer.SECOND * 2, this.nextLine, this); } }, nextLine: function() { this.index++; if (this.index < this.content.length) { this.line = ''; this.game.time.events.repeat(80, this.content[this.index].length + 1, this.updateLine, this); } }, update: function () { }, toggleMute: function() { if (!this.mute) { this.game.sound.mute = true; this.mute = true; this.soundButton.tint = 16711680; } else { this.game.sound.mute = false; this.mute = false; this.soundButton.tint = 16777215; } }, startGame: function (pointer) { this.sound.stop('sonar'); this.state.start('Level3'); } };
{ this.soundButton.tint = 16777215; }
conditional_block
NavigationHome.js
CanyonRunner.NavigationHome = function (game) { this.advanceButton = null; }; CanyonRunner.NavigationHome.prototype = { create: function () { this.sound = this.game.add.audioSprite('sound'); //Show Navigation Supply Screen this.background = this.add.sprite(0, 0, 'sprites', 'navigation-home'); ///////////////////////////// //CREATE SOUND TOGGLE BUTTON
if (!this.game.sound.mute){ this.soundButton.tint = 16777215; } else { this.soundButton.tint = 16711680; } this.advanceButton = this.add.button(320, 500, 'sprites', this.startGame, this, 'start-button', 'start-button', 'start-button'); //Set Content this.content = [ " ", "Night Falls. You Approach Your Home Sector", "There Are 50 Major Spires To Avoid Here...", "Heavy Meteor Showers Detected In This Area", "You Must Obtain a Fix On Your Home Beacon", "Navigate Through the Storm. Ping Your Home." ]; this.index = 0; this.line = ''; //Show Specific Level Objective Text this.level1ObjectiveTextStyle = { font: "35px Helvetica", fill: "#05c619", stroke: "#000", strokeThickness: 10, align: "center" }; this.text = this.game.add.text(this.game.world.centerX - 350, this.game.world.centerY -275, this.level1ObjectiveTextString, this.level1ObjectiveTextStyle); //Loop Sonar Sound on This Screen this.sound.play('sonar'); this.nextLine(); }, updateLine: function() { if (this.line.length < this.content[this.index].length) { this.line = this.content[this.index].substr(0, this.line.length + 1); this.text.setText(this.line); } else { this.game.time.events.add(Phaser.Timer.SECOND * 2, this.nextLine, this); } }, nextLine: function() { this.index++; if (this.index < this.content.length) { this.line = ''; this.game.time.events.repeat(80, this.content[this.index].length + 1, this.updateLine, this); } }, update: function () { }, toggleMute: function() { if (!this.mute) { this.game.sound.mute = true; this.mute = true; this.soundButton.tint = 16711680; } else { this.game.sound.mute = false; this.mute = false; this.soundButton.tint = 16777215; } }, startGame: function (pointer) { this.sound.stop('sonar'); this.state.start('Level3'); } };
///////////////////////////// this.mute = false; this.soundButton = this.game.add.button(this.game.world.centerX + 240, this.game.world.centerY -290, 'sprites', this.toggleMute, this, 'sound-icon', 'sound-icon', 'sound-icon'); this.soundButton.fixedToCamera = true;
random_line_split
InputKeys.ts
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ */ import { Editor } from '../api/Editor'; import { normalizeNbspsInEditor } from './Nbsps'; import { PlatformDetection } from '@ephox/sand'; import { Throttler } from '@ephox/katamari'; const browser = PlatformDetection.detect().browser; const setupIeInput = (editor: Editor) => { // We need to delay this since the normalization should happen after typing a letter // for example typing a<space>b in a paragraph would otherwise result in a a&nbsp;b const keypressThrotter = Throttler.first(() => { // We only care about non composing inputs since moving the caret or modifying the text node will blow away the IME
if (!editor.composing) { normalizeNbspsInEditor(editor); } }, 0); if (browser.isIE()) { // IE doesn't have the input event so we need to fake that with a keypress on IE keypress is only fired on alpha numeric keys editor.on('keypress', (e) => { keypressThrotter.throttle(); }); editor.on('remove', (e) => { keypressThrotter.cancel(); }); } }; const setup = (editor: Editor) => { setupIeInput(editor); editor.on('input', (e) => { // We only care about non composing inputs since moving the caret or modifying the text node will blow away the IME if (e.isComposing === false) { normalizeNbspsInEditor(editor); } }); }; export { setup };
random_line_split
InputKeys.ts
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ */ import { Editor } from '../api/Editor'; import { normalizeNbspsInEditor } from './Nbsps'; import { PlatformDetection } from '@ephox/sand'; import { Throttler } from '@ephox/katamari'; const browser = PlatformDetection.detect().browser; const setupIeInput = (editor: Editor) => { // We need to delay this since the normalization should happen after typing a letter // for example typing a<space>b in a paragraph would otherwise result in a a&nbsp;b const keypressThrotter = Throttler.first(() => { // We only care about non composing inputs since moving the caret or modifying the text node will blow away the IME if (!editor.composing) { normalizeNbspsInEditor(editor); } }, 0); if (browser.isIE())
}; const setup = (editor: Editor) => { setupIeInput(editor); editor.on('input', (e) => { // We only care about non composing inputs since moving the caret or modifying the text node will blow away the IME if (e.isComposing === false) { normalizeNbspsInEditor(editor); } }); }; export { setup };
{ // IE doesn't have the input event so we need to fake that with a keypress on IE keypress is only fired on alpha numeric keys editor.on('keypress', (e) => { keypressThrotter.throttle(); }); editor.on('remove', (e) => { keypressThrotter.cancel(); }); }
conditional_block
links.ts
// https://stackoverflow.com/a/49121680 function copyMessage(val: string) { const selBox = document.createElement('textarea'); selBox.style.position = 'fixed'; selBox.style.left = '0'; selBox.style.top = '0'; selBox.style.opacity = '0'; selBox.value = val; document.body.appendChild(selBox); selBox.focus(); selBox.select(); document.execCommand('copy'); document.body.removeChild(selBox); } async function handleCopy(this: HTMLButtonElement) { copyMessage(this.dataset.link || ""); } function addLinksExpanders(): void { const expanders = document.querySelectorAll<HTMLTableRowElement>('tr.links-expander'); for (const expander of Array.from(expanders)) { expander.onclick = () => { const tbody = expander.parentElement!.nextElementSibling!; const icon = expander.querySelector('i')!; if (tbody.classList.contains('hidden-links'))
else { tbody.classList.add('hidden-links'); icon.innerText = 'expand_more'; } spyglass.contentUpdated(); }; } } window.addEventListener('load', () => { for (const button of Array.from(document.querySelectorAll<HTMLButtonElement>("button.copy"))) { button.addEventListener('click', handleCopy); } }); window.addEventListener('DOMContentLoaded', addLinksExpanders);
{ tbody.classList.remove('hidden-links'); icon.innerText = 'expand_less'; }
conditional_block
links.ts
// https://stackoverflow.com/a/49121680 function
(val: string) { const selBox = document.createElement('textarea'); selBox.style.position = 'fixed'; selBox.style.left = '0'; selBox.style.top = '0'; selBox.style.opacity = '0'; selBox.value = val; document.body.appendChild(selBox); selBox.focus(); selBox.select(); document.execCommand('copy'); document.body.removeChild(selBox); } async function handleCopy(this: HTMLButtonElement) { copyMessage(this.dataset.link || ""); } function addLinksExpanders(): void { const expanders = document.querySelectorAll<HTMLTableRowElement>('tr.links-expander'); for (const expander of Array.from(expanders)) { expander.onclick = () => { const tbody = expander.parentElement!.nextElementSibling!; const icon = expander.querySelector('i')!; if (tbody.classList.contains('hidden-links')) { tbody.classList.remove('hidden-links'); icon.innerText = 'expand_less'; } else { tbody.classList.add('hidden-links'); icon.innerText = 'expand_more'; } spyglass.contentUpdated(); }; } } window.addEventListener('load', () => { for (const button of Array.from(document.querySelectorAll<HTMLButtonElement>("button.copy"))) { button.addEventListener('click', handleCopy); } }); window.addEventListener('DOMContentLoaded', addLinksExpanders);
copyMessage
identifier_name
links.ts
// https://stackoverflow.com/a/49121680 function copyMessage(val: string)
async function handleCopy(this: HTMLButtonElement) { copyMessage(this.dataset.link || ""); } function addLinksExpanders(): void { const expanders = document.querySelectorAll<HTMLTableRowElement>('tr.links-expander'); for (const expander of Array.from(expanders)) { expander.onclick = () => { const tbody = expander.parentElement!.nextElementSibling!; const icon = expander.querySelector('i')!; if (tbody.classList.contains('hidden-links')) { tbody.classList.remove('hidden-links'); icon.innerText = 'expand_less'; } else { tbody.classList.add('hidden-links'); icon.innerText = 'expand_more'; } spyglass.contentUpdated(); }; } } window.addEventListener('load', () => { for (const button of Array.from(document.querySelectorAll<HTMLButtonElement>("button.copy"))) { button.addEventListener('click', handleCopy); } }); window.addEventListener('DOMContentLoaded', addLinksExpanders);
{ const selBox = document.createElement('textarea'); selBox.style.position = 'fixed'; selBox.style.left = '0'; selBox.style.top = '0'; selBox.style.opacity = '0'; selBox.value = val; document.body.appendChild(selBox); selBox.focus(); selBox.select(); document.execCommand('copy'); document.body.removeChild(selBox); }
identifier_body
links.ts
// https://stackoverflow.com/a/49121680 function copyMessage(val: string) { const selBox = document.createElement('textarea'); selBox.style.position = 'fixed'; selBox.style.left = '0'; selBox.style.top = '0'; selBox.style.opacity = '0'; selBox.value = val; document.body.appendChild(selBox); selBox.focus(); selBox.select(); document.execCommand('copy'); document.body.removeChild(selBox); } async function handleCopy(this: HTMLButtonElement) { copyMessage(this.dataset.link || ""); } function addLinksExpanders(): void { const expanders = document.querySelectorAll<HTMLTableRowElement>('tr.links-expander'); for (const expander of Array.from(expanders)) { expander.onclick = () => { const tbody = expander.parentElement!.nextElementSibling!; const icon = expander.querySelector('i')!; if (tbody.classList.contains('hidden-links')) { tbody.classList.remove('hidden-links'); icon.innerText = 'expand_less'; } else { tbody.classList.add('hidden-links'); icon.innerText = 'expand_more'; } spyglass.contentUpdated(); }; } } window.addEventListener('load', () => { for (const button of Array.from(document.querySelectorAll<HTMLButtonElement>("button.copy"))) { button.addEventListener('click', handleCopy); } });
window.addEventListener('DOMContentLoaded', addLinksExpanders);
random_line_split
common.d.ts
import _ = require("../index"); // tslint:disable-next-line:strict-export-declare-modifiers type GlobalPartial<T> = Partial<T>; declare module "../index" { type PartialObject<T> = GlobalPartial<T>; type Many<T> = T | ReadonlyArray<T>; interface LoDashStatic { /** * Creates a lodash object which wraps value to enable implicit method chain sequences. * Methods that operate on and return arrays, collections, and functions can be chained together. * Methods that retrieve a single value or may return a primitive value will automatically end the * chain sequence and return the unwrapped value. Otherwise, the value must be unwrapped with value(). * * Explicit chain sequences, which must be unwrapped with value(), may be enabled using _.chain. * * The execution of chained methods is lazy, that is, it's deferred until value() is * implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. Shortcut fusion * is an optimization to merge iteratee calls; this avoids the creation of intermediate * arrays and can greatly reduce the number of iteratee executions. Sections of a chain * sequence qualify for shortcut fusion if the section is applied to an array and iteratees * accept only one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the value() method is directly or * indirectly included in the build. * * In addition to lodash methods, wrappers have Array and String methods. * The wrapper Array methods are: * concat, join, pop, push, shift, sort, splice, and unshift. * The wrapper String methods are: * replace and split. * * The wrapper methods that support shortcut fusion are: * at, compact, drop, dropRight, dropWhile, filter, find, findLast, head, initial, last, * map, reject, reverse, slice, tail, take, takeRight, takeRightWhile, takeWhile, and toArray * * The chainable wrapper methods are: * after, ary, assign, assignIn, assignInWith, assignWith, at, before, bind, bindAll, bindKey, * castArray, chain, chunk, commit, compact, concat, conforms, constant, countBy, create, * curry, debounce, defaults, defaultsDeep, defer, delay, difference, differenceBy, differenceWith, * drop, dropRight, dropRightWhile, dropWhile, extend, extendWith, fill, filter, flatMap, * flatMapDeep, flatMapDepth, flatten, flattenDeep, flattenDepth, flip, flow, flowRight, * fromPairs, functions, functionsIn, groupBy, initial, intersection, intersectionBy, intersectionWith, * invert, invertBy, invokeMap, iteratee, keyBy, keys, keysIn, map, mapKeys, mapValues, * matches, matchesProperty, memoize, merge, mergeWith, method, methodOf, mixin, negate, * nthArg, omit, omitBy, once, orderBy, over, overArgs, overEvery, overSome, partial, partialRight, * partition, pick, pickBy, plant, property, propertyOf, pull, pullAll, pullAllBy, pullAllWith, pullAt, * push, range, rangeRight, rearg, reject, remove, rest, reverse, sampleSize, set, setWith, * shuffle, slice, sort, sortBy, sortedUniq, sortedUniqBy, splice, spread, tail, take, * takeRight, takeRightWhile, takeWhile, tap, throttle, thru, toArray, toPairs, toPairsIn, * toPath, toPlainObject, transform, unary, union, unionBy, unionWith, uniq, uniqBy, uniqWith, * unset, unshift, unzip, unzipWith, update, updateWith, values, valuesIn, without, wrap, * xor, xorBy, xorWith, zip, zipObject, zipObjectDeep, and zipWith. * * The wrapper methods that are not chainable by default are: * add, attempt, camelCase, capitalize, ceil, clamp, clone, cloneDeep, cloneDeepWith, cloneWith, * conformsTo, deburr, defaultTo, divide, each, eachRight, endsWith, eq, escape, escapeRegExp, * every, find, findIndex, findKey, findLast, findLastIndex, findLastKey, first, floor, forEach, * forEachRight, forIn, forInRight, forOwn, forOwnRight, get, gt, gte, has, hasIn, head, * identity, includes, indexOf, inRange, invoke, isArguments, isArray, isArrayBuffer, * isArrayLike, isArrayLikeObject, isBoolean, isBuffer, isDate, isElement, isEmpty, isEqual, isEqualWith, * isError, isFinite, isFunction, isInteger, isLength, isMap, isMatch, isMatchWith, isNaN, * isNative, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isRegExp, * isSafeInteger, isSet, isString, isUndefined, isTypedArray, isWeakMap, isWeakSet, join, * kebabCase, last, lastIndexOf, lowerCase, lowerFirst, lt, lte, max, maxBy, mean, meanBy, * min, minBy, multiply, noConflict, noop, now, nth, pad, padEnd, padStart, parseInt, pop, * random, reduce, reduceRight, repeat, result, round, runInContext, sample, shift, size, * snakeCase, some, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, startCase, * startsWith, stubArray, stubFalse, stubObject, stubString, stubTrue, subtract, sum, sumBy, * template, times, toFinite, toInteger, toJSON, toLength, toLower, toNumber, toSafeInteger, * toString, toUpper, trim, trimEnd, trimStart, truncate, unescape, uniqueId, upperCase, * upperFirst, value, and words. **/ <T>(value: T): LoDashImplicitWrapper<T>; /** * The semantic version number. **/ VERSION: string; /** * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby * (ERB). Change the following template settings to use alternative delimiters. **/ templateSettings: TemplateSettings; } /** * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby * (ERB). Change the following template settings to use alternative delimiters. **/ interface TemplateSettings { /** * The "escape" delimiter. **/ escape?: RegExp; /** * The "evaluate" delimiter. **/ evaluate?: RegExp; /** * An object to import into the template as local variables. **/ imports?: Dictionary<any>; /** * The "interpolate" delimiter. **/ interpolate?: RegExp; /** * Used to reference the data object in the template text. **/ variable?: string; } /** * Creates a cache object to store key/value pairs. */ interface MapCache { /** * Removes `key` and its value from the cache. * @param key The key of the value to remove. * @return Returns `true` if the entry was removed successfully, else `false`. */ delete(key: any): boolean; /** * Gets the cached value for `key`. * @param key The key of the value to get. * @return Returns the cached value. */ get(key: any): any; /** * Checks if a cached value for `key` exists. * @param key The key of the entry to check. * @return Returns `true` if an entry for `key` exists, else `false`. */ has(key: any): boolean; /** * Sets `value` to `key` of the cache. * @param key The key of the value to cache. * @param value The value to cache. * @return Returns the cache object. */ set(key: any, value: any): this; /** * Removes all key-value entries from the map. */ clear?: () => void; } interface MapCacheConstructor { new (): MapCache; } interface LoDashImplicitWrapper<TValue> extends LoDashWrapper<TValue> { pop<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>): T | undefined; push<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, ...items: T[]): this; shift<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>): T | undefined; sort<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, compareFn?: (a: T, b: T) => number): this; splice<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this; unshift<T>(this: LoDashImplicitWrapper<List<T> | null | undefined>, ...items: T[]): this; } interface LoDashExplicitWrapper<TValue> extends LoDashWrapper<TValue> { pop<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>): LoDashExplicitWrapper<T | undefined>; push<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, ...items: T[]): this; shift<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>): LoDashExplicitWrapper<T | undefined>; sort<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, compareFn?: (a: T, b: T) => number): this; splice<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this; unshift<T>(this: LoDashExplicitWrapper<List<T> | null | undefined>, ...items: T[]): this; } type NotVoid = {} | null | undefined; type IterateeShorthand<T> = PropertyName | [PropertyName, any] | PartialDeep<T>; type ArrayIterator<T, TResult> = (value: T, index: number, collection: T[]) => TResult; type ListIterator<T, TResult> = (value: T, index: number, collection: List<T>) => TResult; type ListIteratee<T> = ListIterator<T, NotVoid> | IterateeShorthand<T>; type ListIterateeCustom<T, TResult> = ListIterator<T, TResult> | IterateeShorthand<T>; type ListIteratorTypeGuard<T, S extends T> = (value: T, index: number, collection: List<T>) => value is S; // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. type ObjectIterator<TObject, TResult> = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; type ObjectIteratee<TObject> = ObjectIterator<TObject, NotVoid> | IterateeShorthand<TObject[keyof TObject]>; type ObjectIterateeCustom<TObject, TResult> = ObjectIterator<TObject, TResult> | IterateeShorthand<TObject[keyof TObject]>; type ObjectIteratorTypeGuard<TObject, S extends TObject[keyof TObject]> = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; type StringIterator<TResult> = (char: string, index: number, string: string) => TResult; /** @deprecated Use MemoVoidArrayIterator or MemoVoidDictionaryIterator instead. */ type MemoVoidIterator<T, TResult> = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => void; /** @deprecated Use MemoListIterator or MemoObjectIterator instead. */ type MemoIterator<T, TResult> = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => TResult; type MemoListIterator<T, TResult, TList> = (prev: TResult, curr: T, index: number, list: TList) => TResult; type MemoObjectIterator<T, TResult, TList> = (prev: TResult, curr: T, key: string, list: TList) => TResult; type MemoIteratorCapped<T, TResult> = (prev: TResult, curr: T) => TResult; type MemoIteratorCappedRight<T, TResult> = (curr: T, prev: TResult) => TResult; type MemoVoidArrayIterator<T, TResult> = (acc: TResult, curr: T, index: number, arr: T[]) => void; type MemoVoidDictionaryIterator<T, TResult> = (acc: TResult, curr: T, key: string, dict: Dictionary<T>) => void; type MemoVoidIteratorCapped<T, TResult> = (acc: TResult, curr: T) => void; type ValueIteratee<T> = ((value: T) => NotVoid) | IterateeShorthand<T>; type ValueIterateeCustom<T, TResult> = ((value: T) => TResult) | IterateeShorthand<T>; type ValueIteratorTypeGuard<T, S extends T> = (value: T) => value is S; type ValueKeyIteratee<T> = ((value: T, key: string) => NotVoid) | IterateeShorthand<T>; type ValueKeyIterateeTypeGuard<T, S extends T> = (value: T, key: string) => value is S; type Comparator<T> = (a: T, b: T) => boolean; type Comparator2<T1, T2> = (a: T1, b: T2) => boolean; type PropertyName = string | number | symbol; type PropertyPath = Many<PropertyName>; type Omit<T, K extends keyof T> = Pick<T, ({ [P in keyof T]: P } & { [P in K]: never } & { [x: string]: never })[keyof T]>; /** Common interface between Arrays and jQuery objects */ type List<T> = ArrayLike<T>; interface Dictionary<T> { [index: string]: T; } interface NumericDictionary<T> { [index: number]: T; } // Crazy typedef needed get _.omit to work properly with Dictionary and NumericDictionary type AnyKindOfDictionary = | Dictionary<{} | null | undefined> | NumericDictionary<{} | null | undefined>; interface Cancelable { cancel(): void; flush(): void; } type PartialDeep<T> = { [P in keyof T]?: PartialDeep<T[P]>; }; // For backwards compatibility type LoDashImplicitArrayWrapper<T> = LoDashImplicitWrapper<T[]>; type LoDashImplicitNillableArrayWrapper<T> = LoDashImplicitWrapper<T[] | null | undefined>; type LoDashImplicitObjectWrapper<T> = LoDashImplicitWrapper<T>; type LoDashImplicitNillableObjectWrapper<T> = LoDashImplicitWrapper<T | null | undefined>; type LoDashImplicitNumberArrayWrapper = LoDashImplicitWrapper<number[]>; type LoDashImplicitStringWrapper = LoDashImplicitWrapper<string>; type LoDashExplicitArrayWrapper<T> = LoDashExplicitWrapper<T[]>; type LoDashExplicitNillableArrayWrapper<T> = LoDashExplicitWrapper<T[] | null | undefined>; type LoDashExplicitObjectWrapper<T> = LoDashExplicitWrapper<T>; type LoDashExplicitNillableObjectWrapper<T> = LoDashExplicitWrapper<T | null | undefined>;
type DictionaryIterator<T, TResult> = ObjectIterator<Dictionary<T>, TResult>; type DictionaryIteratee<T> = ObjectIteratee<Dictionary<T>>; type DictionaryIteratorTypeGuard<T, S extends T> = ObjectIteratorTypeGuard<Dictionary<T>, S>; // NOTE: keys of objects at run time are always strings, even when a NumericDictionary is being iterated. type NumericDictionaryIterator<T, TResult> = (value: T, key: string, collection: NumericDictionary<T>) => TResult; type NumericDictionaryIteratee<T> = NumericDictionaryIterator<T, NotVoid> | IterateeShorthand<T>; type NumericDictionaryIterateeCustom<T, TResult> = NumericDictionaryIterator<T, TResult> | IterateeShorthand<T>; }
type LoDashExplicitNumberArrayWrapper = LoDashExplicitWrapper<number[]>; type LoDashExplicitStringWrapper = LoDashExplicitWrapper<string>;
random_line_split
AuthInterface.d.ts
import { EndpointOptions } from "./EndpointOptions"; import { OctokitResponse } from "./OctokitResponse"; import { RequestInterface } from "./RequestInterface"; import { RequestParameters } from "./RequestParameters"; import { Route } from "./Route"; /** * Interface to implement complex authentication strategies for Octokit. * An object Implementing the AuthInterface can directly be passed as the * `auth` option in the Octokit constructor. * * For the official implementations of the most common authentication * strategies, see https://github.com/octokit/auth.js */
* Sends a request using the passed `request` instance * * @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`. */ <T = any>(request: RequestInterface, options: EndpointOptions): Promise<OctokitResponse<T>>; /** * Sends a request using the passed `request` instance * * @param {string} route Request method + URL. Example: `'GET /orgs/:org'` * @param {object} [parameters] URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`. */ <T = any>(request: RequestInterface, route: Route, parameters?: RequestParameters): Promise<OctokitResponse<T>>; }; }
export interface AuthInterface<AuthOptions extends any[], Authentication extends any> { (...args: AuthOptions): Promise<Authentication>; hook: { /**
random_line_split
pyre.py
from .base import BaseInterface from time import sleep from pyre import Pyre from pyre import zhelper import zmq class ZyreNode (): def __init__(self, interface, netiface=None): self.interface = interface # Peers book self.book = {} self.topics = [] # Publisher self.pub_cache = {} self.publisher = Zsock.new_xpub(("tcp://*:*").encode()) # TimeServer self.timereply = Zsock.new_rep(("tcp://*:*").encode()) # Zyre self.zyre = Zyre(None) if netiface:
self.zyre.set_name(str(self.interface.hplayer.name()).encode()) self.zyre.set_header(b"TS-PORT", str(get_port(self.timereply)).encode()) self.zyre.set_header(b"PUB-PORT", str(get_port(self.publisher)).encode()) self.zyre.set_interval(PING_PEER) self.zyre.set_evasive_timeout(PING_PEER*3) self.zyre.set_silent_timeout(PING_PEER*5) self.zyre.set_expired_timeout(PING_PEER*10) self.zyre.start() self.zyre.join(b"broadcast") self.zyre.join(b"sync") # Add self to book self.book[self.zyre.uuid()] = Peer(self, { 'uuid': self.zyre.uuid(), 'name': self.zyre.name().decode(), 'ip': '127.0.0.1', 'ts_port': get_port(self.timereply), 'pub_port': get_port(self.publisher) }) self.book[self.zyre.uuid()].subscribe(self.topics) # # HPLAYER2 Pyre interface # class PyreInterface (BaseInterface): def __init__(self, hplayer, netiface=None): super().__init__(hplayer, "PYRE") self.node = ZyreNode(self, netiface) def listen(self): self.log( "interface ready") self.stopped.wait() self.log( "closing pyre...") # self.node.stop() # while not self.node.done: # sleep(0.1) self.log( "done.") def activeCount(self): return 0 #len(self.node.book) def peersList(self): return [] #self.node.book
self.zyre.set_interface( string_at(netiface) ) print("ZYRE Node forced netiface: ", string_at(netiface) )
conditional_block
pyre.py
from .base import BaseInterface from time import sleep from pyre import Pyre from pyre import zhelper import zmq class ZyreNode (): def __init__(self, interface, netiface=None): self.interface = interface # Peers book self.book = {} self.topics = [] # Publisher self.pub_cache = {} self.publisher = Zsock.new_xpub(("tcp://*:*").encode()) # TimeServer self.timereply = Zsock.new_rep(("tcp://*:*").encode()) # Zyre self.zyre = Zyre(None) if netiface: self.zyre.set_interface( string_at(netiface) ) print("ZYRE Node forced netiface: ", string_at(netiface) ) self.zyre.set_name(str(self.interface.hplayer.name()).encode()) self.zyre.set_header(b"TS-PORT", str(get_port(self.timereply)).encode()) self.zyre.set_header(b"PUB-PORT", str(get_port(self.publisher)).encode()) self.zyre.set_interval(PING_PEER) self.zyre.set_evasive_timeout(PING_PEER*3) self.zyre.set_silent_timeout(PING_PEER*5) self.zyre.set_expired_timeout(PING_PEER*10) self.zyre.start() self.zyre.join(b"broadcast") self.zyre.join(b"sync") # Add self to book self.book[self.zyre.uuid()] = Peer(self, { 'uuid': self.zyre.uuid(), 'name': self.zyre.name().decode(), 'ip': '127.0.0.1', 'ts_port': get_port(self.timereply), 'pub_port': get_port(self.publisher) }) self.book[self.zyre.uuid()].subscribe(self.topics) # # HPLAYER2 Pyre interface # class PyreInterface (BaseInterface): def __init__(self, hplayer, netiface=None): super().__init__(hplayer, "PYRE") self.node = ZyreNode(self, netiface) def listen(self): self.log( "interface ready") self.stopped.wait() self.log( "closing pyre...") # self.node.stop() # while not self.node.done: # sleep(0.1) self.log( "done.") def
(self): return 0 #len(self.node.book) def peersList(self): return [] #self.node.book
activeCount
identifier_name
pyre.py
from .base import BaseInterface from time import sleep from pyre import Pyre from pyre import zhelper import zmq class ZyreNode (): def __init__(self, interface, netiface=None): self.interface = interface # Peers book self.book = {} self.topics = [] # Publisher self.pub_cache = {} self.publisher = Zsock.new_xpub(("tcp://*:*").encode()) # TimeServer self.timereply = Zsock.new_rep(("tcp://*:*").encode()) # Zyre self.zyre = Zyre(None) if netiface: self.zyre.set_interface( string_at(netiface) ) print("ZYRE Node forced netiface: ", string_at(netiface) ) self.zyre.set_name(str(self.interface.hplayer.name()).encode()) self.zyre.set_header(b"TS-PORT", str(get_port(self.timereply)).encode()) self.zyre.set_header(b"PUB-PORT", str(get_port(self.publisher)).encode()) self.zyre.set_interval(PING_PEER) self.zyre.set_evasive_timeout(PING_PEER*3) self.zyre.set_silent_timeout(PING_PEER*5) self.zyre.set_expired_timeout(PING_PEER*10) self.zyre.start() self.zyre.join(b"broadcast") self.zyre.join(b"sync") # Add self to book self.book[self.zyre.uuid()] = Peer(self, { 'uuid': self.zyre.uuid(), 'name': self.zyre.name().decode(), 'ip': '127.0.0.1', 'ts_port': get_port(self.timereply), 'pub_port': get_port(self.publisher) }) self.book[self.zyre.uuid()].subscribe(self.topics) # # HPLAYER2 Pyre interface # class PyreInterface (BaseInterface): def __init__(self, hplayer, netiface=None): super().__init__(hplayer, "PYRE") self.node = ZyreNode(self, netiface) def listen(self): self.log( "interface ready") self.stopped.wait() self.log( "closing pyre...") # self.node.stop() # while not self.node.done: # sleep(0.1) self.log( "done.") def activeCount(self):
def peersList(self): return [] #self.node.book
return 0 #len(self.node.book)
identifier_body
pyre.py
from .base import BaseInterface from time import sleep from pyre import Pyre from pyre import zhelper import zmq class ZyreNode (): def __init__(self, interface, netiface=None): self.interface = interface # Peers book self.book = {} self.topics = [] # Publisher self.pub_cache = {} self.publisher = Zsock.new_xpub(("tcp://*:*").encode()) # TimeServer self.timereply = Zsock.new_rep(("tcp://*:*").encode()) # Zyre self.zyre = Zyre(None) if netiface: self.zyre.set_interface( string_at(netiface) ) print("ZYRE Node forced netiface: ", string_at(netiface) ) self.zyre.set_name(str(self.interface.hplayer.name()).encode()) self.zyre.set_header(b"TS-PORT", str(get_port(self.timereply)).encode()) self.zyre.set_header(b"PUB-PORT", str(get_port(self.publisher)).encode()) self.zyre.set_interval(PING_PEER) self.zyre.set_evasive_timeout(PING_PEER*3) self.zyre.set_silent_timeout(PING_PEER*5) self.zyre.set_expired_timeout(PING_PEER*10) self.zyre.start() self.zyre.join(b"broadcast") self.zyre.join(b"sync") # Add self to book self.book[self.zyre.uuid()] = Peer(self, { 'uuid': self.zyre.uuid(), 'name': self.zyre.name().decode(), 'ip': '127.0.0.1', 'ts_port': get_port(self.timereply), 'pub_port': get_port(self.publisher) }) self.book[self.zyre.uuid()].subscribe(self.topics) # # HPLAYER2 Pyre interface # class PyreInterface (BaseInterface):
def __init__(self, hplayer, netiface=None): super().__init__(hplayer, "PYRE") self.node = ZyreNode(self, netiface) def listen(self): self.log( "interface ready") self.stopped.wait() self.log( "closing pyre...") # self.node.stop() # while not self.node.done: # sleep(0.1) self.log( "done.") def activeCount(self): return 0 #len(self.node.book) def peersList(self): return [] #self.node.book
random_line_split
pyre_node.py
# Copyright (c) 2015-2020 Contributors as noted in the AUTHORS file # # 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/. # System imports import json import logging import re import uuid from threading import Event # Third-party imports from pyre import Pyre # Local imports from ..tools import zmq, green # , spy_call, w_spy_call, spy_object logger = logging.getLogger(__name__) class PyreNode(Pyre): def __init__(self, *args, **kwargs): # spy_object(self, class_=Pyre, except_=['name', 'uuid'], with_caller=False) # spy_call(self.__init__, args, kwargs, with_caller=False); print self._name = None self._uuid = None super(self.__class__, self).__init__(*args, **kwargs) self.request_results = {} # TODO: Fuse the two dicts self.request_events = {} self.poller = zmq.Poller() self.poller.register(self.inbox, zmq.POLLIN) self.join('SURVEY') def run(self): self.task = green.spawn(self._run, 100) def _run(self, timeout=None):
def _process_message(self): logger.debug('(%s) processing message', self.name()) msg = self.recv() logger.debug('(%s) received stuff: %s', self.name(), msg) msg_type = msg.pop(0) logger.debug('(%s) msg_type: %s', self.name(), msg_type) peer_id = uuid.UUID(bytes=msg.pop(0)) logger.debug('(%s) peer_id: %s', self.name(), peer_id) peer_name = msg.pop(0) logger.debug('(%s) peer_name: %s', self.name(), peer_name) if msg_type == b'ENTER': self.on_peer_enter(peer_id, peer_name, msg) elif msg_type == b'EXIT': self.on_peer_exit(peer_id, peer_name, msg) elif msg_type == b'SHOUT': self.on_peer_shout(peer_id, peer_name, msg) elif msg_type == b'WHISPER': self.on_peer_whisper(peer_id, peer_name, msg) def on_peer_enter(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE ENTER: %s, %s', self.name(), peer_name, peer_id) pub_endpoint = self.get_peer_endpoint(peer_id, 'pub') rpc_endpoint = self.get_peer_endpoint(peer_id, 'rpc') self.on_new_peer(peer_id, peer_name, pub_endpoint, rpc_endpoint) def on_new_peer(self, peer_id, peer_name, pub_endpoint, rpc_endpoint): pass def on_peer_exit(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE EXIT: %s, %s', self.name(), peer_name, peer_id) self.on_peer_gone(peer_id, peer_name) def on_peer_gone(self, peer_id, peer_name): pass def on_peer_shout(self, peer_id, peer_name, msg): group = msg.pop(0) data = msg.pop(0) logger.debug('(%s) ZRE SHOUT: %s, %s > (%s) %s', self.name(), peer_name, peer_id, group, data) if group == b'SURVEY': self.on_survey(peer_id, peer_name, json.loads(data)) elif group == b'EVENT': self.on_event(peer_id, peer_name, json.loads(data)) def on_survey(self, peer_id, peer_name, request): pass def on_event(self, peer_id, peer_name, request): pass def on_peer_whisper(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE WHISPER: %s, %s > %s', self.name(), peer_name, peer_id, msg) reply = json.loads(msg[0]) if reply['req_id'] in self.request_results: logger.debug('(%s) Received reply from %s: %s', self.name(), peer_name, reply['data']) self.request_results[reply['req_id']].append((peer_name, reply['data'])) ev, limit_peers = self.request_events[reply['req_id']] if limit_peers and (len(self.request_results[reply['req_id']]) >= limit_peers): ev.set() green.sleep(0) # Yield else: logger.warning( '(%s) Discarding reply from %s because the request ID is unknown', self.name(), peer_name ) def get_peer_endpoint(self, peer, prefix): pyre_endpoint = self.peer_address(peer) ip = re.search('.*://(.*):.*', pyre_endpoint).group(1) return '%s://%s:%s' % ( self.peer_header_value(peer, prefix + '_proto'), ip, self.peer_header_value(peer, prefix + '_port') ) def join_event(self): self.join('EVENT') def leave_event(self): self.leave('EVENT') def send_survey(self, request, timeout, limit_peers): # request['req_id'] = ('%x' % randint(0, 0xFFFFFFFF)).encode() self.request_results[request['req_id']] = [] ev = Event() self.request_events[request['req_id']] = (ev, limit_peers) self.shout('SURVEY', json.dumps(request).encode()) ev.wait(timeout) result = self.request_results[request['req_id']] del self.request_results[request['req_id']] del self.request_events[request['req_id']] return result def send_event(self, request): self.shout('EVENT', json.dumps(request).encode()) def reply_survey(self, peer_id, reply): self.whisper(peer_id, json.dumps(reply).encode()) def shutdown(self): self._running = False def name(self): if self._name is None: # f = w_spy_call(super(self.__class__, self).name, with_caller=False) f = super(self.__class__, self).name self._name = f() return self._name def uuid(self): if self._uuid is None: # f = w_spy_call(super(self.__class__, self).uuid, with_caller=False) f = super(self.__class__, self).uuid self._uuid = f() return self._uuid
self._running = True self.start() while self._running: try: # logger.debug('Polling') items = dict(self.poller.poll(timeout)) # logger.debug('polled out: %s, %s', len(items), items) while len(items) > 0: for fd, ev in items.items(): if (self.inbox == fd) and (ev == zmq.POLLIN): self._process_message() # logger.debug('quick polling') items = dict(self.poller.poll(0)) # logger.debug('qpoll: %s, %s', len(items), items) except (KeyboardInterrupt, SystemExit): logger.debug('(%s) KeyboardInterrupt or SystemExit', self.name()) break logger.debug('(%s) Exiting loop and stopping', self.name()) self.stop()
identifier_body
pyre_node.py
# Copyright (c) 2015-2020 Contributors as noted in the AUTHORS file # # 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/. # System imports import json import logging import re import uuid from threading import Event # Third-party imports from pyre import Pyre # Local imports from ..tools import zmq, green # , spy_call, w_spy_call, spy_object logger = logging.getLogger(__name__) class PyreNode(Pyre): def __init__(self, *args, **kwargs): # spy_object(self, class_=Pyre, except_=['name', 'uuid'], with_caller=False) # spy_call(self.__init__, args, kwargs, with_caller=False); print self._name = None self._uuid = None super(self.__class__, self).__init__(*args, **kwargs) self.request_results = {} # TODO: Fuse the two dicts self.request_events = {} self.poller = zmq.Poller() self.poller.register(self.inbox, zmq.POLLIN) self.join('SURVEY') def run(self): self.task = green.spawn(self._run, 100) def _run(self, timeout=None): self._running = True self.start() while self._running: try: # logger.debug('Polling') items = dict(self.poller.poll(timeout)) # logger.debug('polled out: %s, %s', len(items), items) while len(items) > 0: for fd, ev in items.items(): if (self.inbox == fd) and (ev == zmq.POLLIN): self._process_message() # logger.debug('quick polling') items = dict(self.poller.poll(0)) # logger.debug('qpoll: %s, %s', len(items), items) except (KeyboardInterrupt, SystemExit): logger.debug('(%s) KeyboardInterrupt or SystemExit', self.name()) break logger.debug('(%s) Exiting loop and stopping', self.name()) self.stop() def
(self): logger.debug('(%s) processing message', self.name()) msg = self.recv() logger.debug('(%s) received stuff: %s', self.name(), msg) msg_type = msg.pop(0) logger.debug('(%s) msg_type: %s', self.name(), msg_type) peer_id = uuid.UUID(bytes=msg.pop(0)) logger.debug('(%s) peer_id: %s', self.name(), peer_id) peer_name = msg.pop(0) logger.debug('(%s) peer_name: %s', self.name(), peer_name) if msg_type == b'ENTER': self.on_peer_enter(peer_id, peer_name, msg) elif msg_type == b'EXIT': self.on_peer_exit(peer_id, peer_name, msg) elif msg_type == b'SHOUT': self.on_peer_shout(peer_id, peer_name, msg) elif msg_type == b'WHISPER': self.on_peer_whisper(peer_id, peer_name, msg) def on_peer_enter(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE ENTER: %s, %s', self.name(), peer_name, peer_id) pub_endpoint = self.get_peer_endpoint(peer_id, 'pub') rpc_endpoint = self.get_peer_endpoint(peer_id, 'rpc') self.on_new_peer(peer_id, peer_name, pub_endpoint, rpc_endpoint) def on_new_peer(self, peer_id, peer_name, pub_endpoint, rpc_endpoint): pass def on_peer_exit(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE EXIT: %s, %s', self.name(), peer_name, peer_id) self.on_peer_gone(peer_id, peer_name) def on_peer_gone(self, peer_id, peer_name): pass def on_peer_shout(self, peer_id, peer_name, msg): group = msg.pop(0) data = msg.pop(0) logger.debug('(%s) ZRE SHOUT: %s, %s > (%s) %s', self.name(), peer_name, peer_id, group, data) if group == b'SURVEY': self.on_survey(peer_id, peer_name, json.loads(data)) elif group == b'EVENT': self.on_event(peer_id, peer_name, json.loads(data)) def on_survey(self, peer_id, peer_name, request): pass def on_event(self, peer_id, peer_name, request): pass def on_peer_whisper(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE WHISPER: %s, %s > %s', self.name(), peer_name, peer_id, msg) reply = json.loads(msg[0]) if reply['req_id'] in self.request_results: logger.debug('(%s) Received reply from %s: %s', self.name(), peer_name, reply['data']) self.request_results[reply['req_id']].append((peer_name, reply['data'])) ev, limit_peers = self.request_events[reply['req_id']] if limit_peers and (len(self.request_results[reply['req_id']]) >= limit_peers): ev.set() green.sleep(0) # Yield else: logger.warning( '(%s) Discarding reply from %s because the request ID is unknown', self.name(), peer_name ) def get_peer_endpoint(self, peer, prefix): pyre_endpoint = self.peer_address(peer) ip = re.search('.*://(.*):.*', pyre_endpoint).group(1) return '%s://%s:%s' % ( self.peer_header_value(peer, prefix + '_proto'), ip, self.peer_header_value(peer, prefix + '_port') ) def join_event(self): self.join('EVENT') def leave_event(self): self.leave('EVENT') def send_survey(self, request, timeout, limit_peers): # request['req_id'] = ('%x' % randint(0, 0xFFFFFFFF)).encode() self.request_results[request['req_id']] = [] ev = Event() self.request_events[request['req_id']] = (ev, limit_peers) self.shout('SURVEY', json.dumps(request).encode()) ev.wait(timeout) result = self.request_results[request['req_id']] del self.request_results[request['req_id']] del self.request_events[request['req_id']] return result def send_event(self, request): self.shout('EVENT', json.dumps(request).encode()) def reply_survey(self, peer_id, reply): self.whisper(peer_id, json.dumps(reply).encode()) def shutdown(self): self._running = False def name(self): if self._name is None: # f = w_spy_call(super(self.__class__, self).name, with_caller=False) f = super(self.__class__, self).name self._name = f() return self._name def uuid(self): if self._uuid is None: # f = w_spy_call(super(self.__class__, self).uuid, with_caller=False) f = super(self.__class__, self).uuid self._uuid = f() return self._uuid
_process_message
identifier_name
pyre_node.py
# Copyright (c) 2015-2020 Contributors as noted in the AUTHORS file # # 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/. # System imports import json import logging import re import uuid from threading import Event # Third-party imports from pyre import Pyre # Local imports from ..tools import zmq, green # , spy_call, w_spy_call, spy_object logger = logging.getLogger(__name__) class PyreNode(Pyre): def __init__(self, *args, **kwargs): # spy_object(self, class_=Pyre, except_=['name', 'uuid'], with_caller=False) # spy_call(self.__init__, args, kwargs, with_caller=False); print self._name = None self._uuid = None super(self.__class__, self).__init__(*args, **kwargs) self.request_results = {} # TODO: Fuse the two dicts self.request_events = {} self.poller = zmq.Poller() self.poller.register(self.inbox, zmq.POLLIN) self.join('SURVEY') def run(self): self.task = green.spawn(self._run, 100) def _run(self, timeout=None): self._running = True self.start() while self._running: try: # logger.debug('Polling') items = dict(self.poller.poll(timeout)) # logger.debug('polled out: %s, %s', len(items), items) while len(items) > 0: for fd, ev in items.items(): if (self.inbox == fd) and (ev == zmq.POLLIN): self._process_message() # logger.debug('quick polling') items = dict(self.poller.poll(0)) # logger.debug('qpoll: %s, %s', len(items), items) except (KeyboardInterrupt, SystemExit): logger.debug('(%s) KeyboardInterrupt or SystemExit', self.name()) break logger.debug('(%s) Exiting loop and stopping', self.name()) self.stop() def _process_message(self): logger.debug('(%s) processing message', self.name()) msg = self.recv() logger.debug('(%s) received stuff: %s', self.name(), msg) msg_type = msg.pop(0) logger.debug('(%s) msg_type: %s', self.name(), msg_type) peer_id = uuid.UUID(bytes=msg.pop(0)) logger.debug('(%s) peer_id: %s', self.name(), peer_id)
peer_name = msg.pop(0) logger.debug('(%s) peer_name: %s', self.name(), peer_name) if msg_type == b'ENTER': self.on_peer_enter(peer_id, peer_name, msg) elif msg_type == b'EXIT': self.on_peer_exit(peer_id, peer_name, msg) elif msg_type == b'SHOUT': self.on_peer_shout(peer_id, peer_name, msg) elif msg_type == b'WHISPER': self.on_peer_whisper(peer_id, peer_name, msg) def on_peer_enter(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE ENTER: %s, %s', self.name(), peer_name, peer_id) pub_endpoint = self.get_peer_endpoint(peer_id, 'pub') rpc_endpoint = self.get_peer_endpoint(peer_id, 'rpc') self.on_new_peer(peer_id, peer_name, pub_endpoint, rpc_endpoint) def on_new_peer(self, peer_id, peer_name, pub_endpoint, rpc_endpoint): pass def on_peer_exit(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE EXIT: %s, %s', self.name(), peer_name, peer_id) self.on_peer_gone(peer_id, peer_name) def on_peer_gone(self, peer_id, peer_name): pass def on_peer_shout(self, peer_id, peer_name, msg): group = msg.pop(0) data = msg.pop(0) logger.debug('(%s) ZRE SHOUT: %s, %s > (%s) %s', self.name(), peer_name, peer_id, group, data) if group == b'SURVEY': self.on_survey(peer_id, peer_name, json.loads(data)) elif group == b'EVENT': self.on_event(peer_id, peer_name, json.loads(data)) def on_survey(self, peer_id, peer_name, request): pass def on_event(self, peer_id, peer_name, request): pass def on_peer_whisper(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE WHISPER: %s, %s > %s', self.name(), peer_name, peer_id, msg) reply = json.loads(msg[0]) if reply['req_id'] in self.request_results: logger.debug('(%s) Received reply from %s: %s', self.name(), peer_name, reply['data']) self.request_results[reply['req_id']].append((peer_name, reply['data'])) ev, limit_peers = self.request_events[reply['req_id']] if limit_peers and (len(self.request_results[reply['req_id']]) >= limit_peers): ev.set() green.sleep(0) # Yield else: logger.warning( '(%s) Discarding reply from %s because the request ID is unknown', self.name(), peer_name ) def get_peer_endpoint(self, peer, prefix): pyre_endpoint = self.peer_address(peer) ip = re.search('.*://(.*):.*', pyre_endpoint).group(1) return '%s://%s:%s' % ( self.peer_header_value(peer, prefix + '_proto'), ip, self.peer_header_value(peer, prefix + '_port') ) def join_event(self): self.join('EVENT') def leave_event(self): self.leave('EVENT') def send_survey(self, request, timeout, limit_peers): # request['req_id'] = ('%x' % randint(0, 0xFFFFFFFF)).encode() self.request_results[request['req_id']] = [] ev = Event() self.request_events[request['req_id']] = (ev, limit_peers) self.shout('SURVEY', json.dumps(request).encode()) ev.wait(timeout) result = self.request_results[request['req_id']] del self.request_results[request['req_id']] del self.request_events[request['req_id']] return result def send_event(self, request): self.shout('EVENT', json.dumps(request).encode()) def reply_survey(self, peer_id, reply): self.whisper(peer_id, json.dumps(reply).encode()) def shutdown(self): self._running = False def name(self): if self._name is None: # f = w_spy_call(super(self.__class__, self).name, with_caller=False) f = super(self.__class__, self).name self._name = f() return self._name def uuid(self): if self._uuid is None: # f = w_spy_call(super(self.__class__, self).uuid, with_caller=False) f = super(self.__class__, self).uuid self._uuid = f() return self._uuid
random_line_split
pyre_node.py
# Copyright (c) 2015-2020 Contributors as noted in the AUTHORS file # # 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/. # System imports import json import logging import re import uuid from threading import Event # Third-party imports from pyre import Pyre # Local imports from ..tools import zmq, green # , spy_call, w_spy_call, spy_object logger = logging.getLogger(__name__) class PyreNode(Pyre): def __init__(self, *args, **kwargs): # spy_object(self, class_=Pyre, except_=['name', 'uuid'], with_caller=False) # spy_call(self.__init__, args, kwargs, with_caller=False); print self._name = None self._uuid = None super(self.__class__, self).__init__(*args, **kwargs) self.request_results = {} # TODO: Fuse the two dicts self.request_events = {} self.poller = zmq.Poller() self.poller.register(self.inbox, zmq.POLLIN) self.join('SURVEY') def run(self): self.task = green.spawn(self._run, 100) def _run(self, timeout=None): self._running = True self.start() while self._running: try: # logger.debug('Polling') items = dict(self.poller.poll(timeout)) # logger.debug('polled out: %s, %s', len(items), items) while len(items) > 0: for fd, ev in items.items(): if (self.inbox == fd) and (ev == zmq.POLLIN): self._process_message() # logger.debug('quick polling') items = dict(self.poller.poll(0)) # logger.debug('qpoll: %s, %s', len(items), items) except (KeyboardInterrupt, SystemExit): logger.debug('(%s) KeyboardInterrupt or SystemExit', self.name()) break logger.debug('(%s) Exiting loop and stopping', self.name()) self.stop() def _process_message(self): logger.debug('(%s) processing message', self.name()) msg = self.recv() logger.debug('(%s) received stuff: %s', self.name(), msg) msg_type = msg.pop(0) logger.debug('(%s) msg_type: %s', self.name(), msg_type) peer_id = uuid.UUID(bytes=msg.pop(0)) logger.debug('(%s) peer_id: %s', self.name(), peer_id) peer_name = msg.pop(0) logger.debug('(%s) peer_name: %s', self.name(), peer_name) if msg_type == b'ENTER': self.on_peer_enter(peer_id, peer_name, msg) elif msg_type == b'EXIT': self.on_peer_exit(peer_id, peer_name, msg) elif msg_type == b'SHOUT': self.on_peer_shout(peer_id, peer_name, msg) elif msg_type == b'WHISPER': self.on_peer_whisper(peer_id, peer_name, msg) def on_peer_enter(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE ENTER: %s, %s', self.name(), peer_name, peer_id) pub_endpoint = self.get_peer_endpoint(peer_id, 'pub') rpc_endpoint = self.get_peer_endpoint(peer_id, 'rpc') self.on_new_peer(peer_id, peer_name, pub_endpoint, rpc_endpoint) def on_new_peer(self, peer_id, peer_name, pub_endpoint, rpc_endpoint): pass def on_peer_exit(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE EXIT: %s, %s', self.name(), peer_name, peer_id) self.on_peer_gone(peer_id, peer_name) def on_peer_gone(self, peer_id, peer_name): pass def on_peer_shout(self, peer_id, peer_name, msg): group = msg.pop(0) data = msg.pop(0) logger.debug('(%s) ZRE SHOUT: %s, %s > (%s) %s', self.name(), peer_name, peer_id, group, data) if group == b'SURVEY':
elif group == b'EVENT': self.on_event(peer_id, peer_name, json.loads(data)) def on_survey(self, peer_id, peer_name, request): pass def on_event(self, peer_id, peer_name, request): pass def on_peer_whisper(self, peer_id, peer_name, msg): logger.debug('(%s) ZRE WHISPER: %s, %s > %s', self.name(), peer_name, peer_id, msg) reply = json.loads(msg[0]) if reply['req_id'] in self.request_results: logger.debug('(%s) Received reply from %s: %s', self.name(), peer_name, reply['data']) self.request_results[reply['req_id']].append((peer_name, reply['data'])) ev, limit_peers = self.request_events[reply['req_id']] if limit_peers and (len(self.request_results[reply['req_id']]) >= limit_peers): ev.set() green.sleep(0) # Yield else: logger.warning( '(%s) Discarding reply from %s because the request ID is unknown', self.name(), peer_name ) def get_peer_endpoint(self, peer, prefix): pyre_endpoint = self.peer_address(peer) ip = re.search('.*://(.*):.*', pyre_endpoint).group(1) return '%s://%s:%s' % ( self.peer_header_value(peer, prefix + '_proto'), ip, self.peer_header_value(peer, prefix + '_port') ) def join_event(self): self.join('EVENT') def leave_event(self): self.leave('EVENT') def send_survey(self, request, timeout, limit_peers): # request['req_id'] = ('%x' % randint(0, 0xFFFFFFFF)).encode() self.request_results[request['req_id']] = [] ev = Event() self.request_events[request['req_id']] = (ev, limit_peers) self.shout('SURVEY', json.dumps(request).encode()) ev.wait(timeout) result = self.request_results[request['req_id']] del self.request_results[request['req_id']] del self.request_events[request['req_id']] return result def send_event(self, request): self.shout('EVENT', json.dumps(request).encode()) def reply_survey(self, peer_id, reply): self.whisper(peer_id, json.dumps(reply).encode()) def shutdown(self): self._running = False def name(self): if self._name is None: # f = w_spy_call(super(self.__class__, self).name, with_caller=False) f = super(self.__class__, self).name self._name = f() return self._name def uuid(self): if self._uuid is None: # f = w_spy_call(super(self.__class__, self).uuid, with_caller=False) f = super(self.__class__, self).uuid self._uuid = f() return self._uuid
self.on_survey(peer_id, peer_name, json.loads(data))
conditional_block
script.js
/* 7. Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime. */ taskName = "7. Prime number"; function Main(bufferElement) { var integer = ReadLine("Enter a integer: ", GetRandomInt(1, 100)); SetSolveButton(function() { ConsoleClear(); isPrime(integer.value); }); } function isPrime(number) { var number = parseInt(number); if (!IsNumber(number)) { WriteLine("Error! Incorrect input value!"); return; } if (!number || number < 0 || number > 100) { WriteLine("Number must be positive and less than 100!"); return; }
WriteLine(Format("Number {0} is NOT prime!", number)); return; } } WriteLine(Format("Number {0} is prime!", number)); }
for (var i = 2; i <= Math.sqrt(number); i++) { if ((number % i) === 0) {
random_line_split
script.js
/* 7. Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime. */ taskName = "7. Prime number"; function Main(bufferElement) { var integer = ReadLine("Enter a integer: ", GetRandomInt(1, 100)); SetSolveButton(function() { ConsoleClear(); isPrime(integer.value); }); } function isPrime(number) { var number = parseInt(number); if (!IsNumber(number)) { WriteLine("Error! Incorrect input value!"); return; } if (!number || number < 0 || number > 100) { WriteLine("Number must be positive and less than 100!"); return; } for (var i = 2; i <= Math.sqrt(number); i++) {
WriteLine(Format("Number {0} is prime!", number)); }
if ((number % i) === 0) { WriteLine(Format("Number {0} is NOT prime!", number)); return; } }
conditional_block
script.js
/* 7. Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime. */ taskName = "7. Prime number"; function Ma
ufferElement) { var integer = ReadLine("Enter a integer: ", GetRandomInt(1, 100)); SetSolveButton(function() { ConsoleClear(); isPrime(integer.value); }); } function isPrime(number) { var number = parseInt(number); if (!IsNumber(number)) { WriteLine("Error! Incorrect input value!"); return; } if (!number || number < 0 || number > 100) { WriteLine("Number must be positive and less than 100!"); return; } for (var i = 2; i <= Math.sqrt(number); i++) { if ((number % i) === 0) { WriteLine(Format("Number {0} is NOT prime!", number)); return; } } WriteLine(Format("Number {0} is prime!", number)); }
in(b
identifier_name
script.js
/* 7. Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime. */ taskName = "7. Prime number"; function Main(bufferElement) {
function isPrime(number) { var number = parseInt(number); if (!IsNumber(number)) { WriteLine("Error! Incorrect input value!"); return; } if (!number || number < 0 || number > 100) { WriteLine("Number must be positive and less than 100!"); return; } for (var i = 2; i <= Math.sqrt(number); i++) { if ((number % i) === 0) { WriteLine(Format("Number {0} is NOT prime!", number)); return; } } WriteLine(Format("Number {0} is prime!", number)); }
var integer = ReadLine("Enter a integer: ", GetRandomInt(1, 100)); SetSolveButton(function() { ConsoleClear(); isPrime(integer.value); }); }
identifier_body
db_base_plugin_common.py
# Copyright (c) 2015 OpenStack Foundation. # 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. import functools from oslo_config import cfg from oslo_log import log as logging from sqlalchemy.orm import exc from neutron.api.v2 import attributes from neutron.common import constants from neutron.common import exceptions as n_exc from neutron.common import utils from neutron.db import common_db_mixin from neutron.db import models_v2 LOG = logging.getLogger(__name__) class DbBasePluginCommon(common_db_mixin.CommonDbMixin): """Stores getters and helper methods for db_base_plugin_v2 All private getters and simple helpers like _make_*_dict were moved from db_base_plugin_v2. More complicated logic and public methods left in db_base_plugin_v2. Main purpose of this class is to make getters accessible for Ipam backends. """ @staticmethod def _generate_mac(): return utils.get_random_mac(cfg.CONF.base_mac.split(':')) @staticmethod def _delete_ip_allocation(context, network_id, subnet_id, ip_address): # Delete the IP address from the IPAllocate table LOG.debug("Delete allocated IP %(ip_address)s " "(%(network_id)s/%(subnet_id)s)", {'ip_address': ip_address, 'network_id': network_id, 'subnet_id': subnet_id}) context.session.query(models_v2.IPAllocation).filter_by( network_id=network_id, ip_address=ip_address, subnet_id=subnet_id).delete() @staticmethod def _store_ip_allocation(context, ip_address, network_id, subnet_id, port_id): LOG.debug("Allocated IP %(ip_address)s " "(%(network_id)s/%(subnet_id)s/%(port_id)s)", {'ip_address': ip_address, 'network_id': network_id, 'subnet_id': subnet_id, 'port_id': port_id}) allocated = models_v2.IPAllocation( network_id=network_id, port_id=port_id, ip_address=ip_address, subnet_id=subnet_id ) context.session.add(allocated) def _make_subnet_dict(self, subnet, fields=None, context=None): res = {'id': subnet['id'], 'name': subnet['name'], 'tenant_id': subnet['tenant_id'], 'network_id': subnet['network_id'], 'ip_version': subnet['ip_version'], 'cidr': subnet['cidr'], 'subnetpool_id': subnet.get('subnetpool_id'), 'allocation_pools': [{'start': pool['first_ip'], 'end': pool['last_ip']} for pool in subnet['allocation_pools']], 'gateway_ip': subnet['gateway_ip'], 'enable_dhcp': subnet['enable_dhcp'], 'ipv6_ra_mode': subnet['ipv6_ra_mode'], 'ipv6_address_mode': subnet['ipv6_address_mode'], 'dns_nameservers': [dns['address'] for dns in subnet['dns_nameservers']], 'host_routes': [{'destination': route['destination'], 'nexthop': route['nexthop']} for route in subnet['routes']], } # The shared attribute for a subnet is the same as its parent network res['shared'] = self._make_network_dict(subnet.networks, context=context)['shared'] # Call auxiliary extend functions, if any self._apply_dict_extend_functions(attributes.SUBNETS, res, subnet) return self._fields(res, fields) def _make_subnetpool_dict(self, subnetpool, fields=None): default_prefixlen = str(subnetpool['default_prefixlen']) min_prefixlen = str(subnetpool['min_prefixlen']) max_prefixlen = str(subnetpool['max_prefixlen']) res = {'id': subnetpool['id'], 'name': subnetpool['name'], 'tenant_id': subnetpool['tenant_id'], 'default_prefixlen': default_prefixlen, 'min_prefixlen': min_prefixlen, 'max_prefixlen': max_prefixlen, 'shared': subnetpool['shared'], 'prefixes': [prefix['cidr'] for prefix in subnetpool['prefixes']], 'ip_version': subnetpool['ip_version'], 'default_quota': subnetpool['default_quota']} return self._fields(res, fields) def _make_port_dict(self, port, fields=None, process_extensions=True): res = {"id": port["id"], 'name': port['name'], "network_id": port["network_id"], 'tenant_id': port['tenant_id'], "mac_address": port["mac_address"], "admin_state_up": port["admin_state_up"], "status": port["status"], "fixed_ips": [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in port["fixed_ips"]], "device_id": port["device_id"], "device_owner": port["device_owner"]} # Call auxiliary extend functions, if any if process_extensions: self._apply_dict_extend_functions( attributes.PORTS, res, port) return self._fields(res, fields) def _get_ipam_subnetpool_driver(self, context, subnetpool=None): if cfg.CONF.ipam_driver: return ipam_base.Pool.get_instance(subnetpool, context) else: return subnet_alloc.SubnetAllocator(subnetpool, context) def _get_network(self, context, id): try: network = self._get_by_id(context, models_v2.Network, id) except exc.NoResultFound: raise n_exc.NetworkNotFound(net_id=id) return network def _get_subnet(self, context, id): try: subnet = self._get_by_id(context, models_v2.Subnet, id) except exc.NoResultFound: raise n_exc.SubnetNotFound(subnet_id=id) return subnet def _get_subnetpool(self, context, id): try: return self._get_by_id(context, models_v2.SubnetPool, id) except exc.NoResultFound: raise n_exc.SubnetPoolNotFound(subnetpool_id=id) def _get_all_subnetpools(self, context): # NOTE(tidwellr): see note in _get_all_subnets()
def _get_port(self, context, id): try: port = self._get_by_id(context, models_v2.Port, id) except exc.NoResultFound: raise n_exc.PortNotFound(port_id=id) return port def _get_dns_by_subnet(self, context, subnet_id): dns_qry = context.session.query(models_v2.DNSNameServer) return dns_qry.filter_by(subnet_id=subnet_id).all() def _get_route_by_subnet(self, context, subnet_id): route_qry = context.session.query(models_v2.SubnetRoute) return route_qry.filter_by(subnet_id=subnet_id).all() def _get_router_gw_ports_by_network(self, context, network_id): port_qry = context.session.query(models_v2.Port) return port_qry.filter_by(network_id=network_id, device_owner=constants.DEVICE_OWNER_ROUTER_GW).all() def _get_subnets_by_network(self, context, network_id): subnet_qry = context.session.query(models_v2.Subnet) return subnet_qry.filter_by(network_id=network_id).all() def _get_subnets_by_subnetpool(self, context, subnetpool_id): subnet_qry = context.session.query(models_v2.Subnet) return subnet_qry.filter_by(subnetpool_id=subnetpool_id).all() def _get_all_subnets(self, context): # NOTE(salvatore-orlando): This query might end up putting # a lot of stress on the db. Consider adding a cache layer return context.session.query(models_v2.Subnet).all() def _get_subnets(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'subnet', limit, marker) make_subnet_dict = functools.partial(self._make_subnet_dict, context=context) return self._get_collection(context, models_v2.Subnet, make_subnet_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def _make_network_dict(self, network, fields=None, process_extensions=True, context=None): res = {'id': network['id'], 'name': network['name'], 'tenant_id': network['tenant_id'], 'admin_state_up': network['admin_state_up'], 'mtu': network.get('mtu', constants.DEFAULT_NETWORK_MTU), 'status': network['status'], 'subnets': [subnet['id'] for subnet in network['subnets']]} # The shared attribute for a network now reflects if the network # is shared to the calling tenant via an RBAC entry. shared = False matches = ('*',) + ((context.tenant_id,) if context else ()) for entry in network.rbac_entries: if (entry.action == 'access_as_shared' and entry.target_tenant in matches): shared = True break res['shared'] = shared # TODO(pritesh): Move vlan_transparent to the extension module. # vlan_transparent here is only added if the vlantransparent # extension is enabled. if ('vlan_transparent' in network and network['vlan_transparent'] != attributes.ATTR_NOT_SPECIFIED): res['vlan_transparent'] = network['vlan_transparent'] # Call auxiliary extend functions, if any if process_extensions: self._apply_dict_extend_functions( attributes.NETWORKS, res, network) return self._fields(res, fields) def _make_subnet_args(self, detail, subnet, subnetpool_id): gateway_ip = str(detail.gateway_ip) if detail.gateway_ip else None args = {'tenant_id': detail.tenant_id, 'id': subnet['id'], 'name': subnet['name'], 'network_id': subnet['network_id'], 'ip_version': subnet['ip_version'], 'cidr': str(detail.subnet_cidr), 'subnetpool_id': subnetpool_id, 'enable_dhcp': subnet['enable_dhcp'], 'gateway_ip': gateway_ip} if subnet['ip_version'] == 6 and subnet['enable_dhcp']: if attributes.is_attr_set(subnet['ipv6_ra_mode']): args['ipv6_ra_mode'] = subnet['ipv6_ra_mode'] if attributes.is_attr_set(subnet['ipv6_address_mode']): args['ipv6_address_mode'] = subnet['ipv6_address_mode'] return args def _make_fixed_ip_dict(self, ips): # Excludes from dict all keys except subnet_id and ip_address return [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in ips]
return context.session.query(models_v2.SubnetPool).all()
identifier_body
db_base_plugin_common.py
# Copyright (c) 2015 OpenStack Foundation. # 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. import functools from oslo_config import cfg from oslo_log import log as logging from sqlalchemy.orm import exc from neutron.api.v2 import attributes from neutron.common import constants from neutron.common import exceptions as n_exc from neutron.common import utils from neutron.db import common_db_mixin from neutron.db import models_v2 LOG = logging.getLogger(__name__) class DbBasePluginCommon(common_db_mixin.CommonDbMixin): """Stores getters and helper methods for db_base_plugin_v2 All private getters and simple helpers like _make_*_dict were moved from db_base_plugin_v2. More complicated logic and public methods left in db_base_plugin_v2. Main purpose of this class is to make getters accessible for Ipam backends. """ @staticmethod def _generate_mac(): return utils.get_random_mac(cfg.CONF.base_mac.split(':')) @staticmethod def _delete_ip_allocation(context, network_id, subnet_id, ip_address): # Delete the IP address from the IPAllocate table LOG.debug("Delete allocated IP %(ip_address)s " "(%(network_id)s/%(subnet_id)s)", {'ip_address': ip_address, 'network_id': network_id, 'subnet_id': subnet_id}) context.session.query(models_v2.IPAllocation).filter_by( network_id=network_id, ip_address=ip_address, subnet_id=subnet_id).delete() @staticmethod def _store_ip_allocation(context, ip_address, network_id, subnet_id, port_id): LOG.debug("Allocated IP %(ip_address)s " "(%(network_id)s/%(subnet_id)s/%(port_id)s)", {'ip_address': ip_address, 'network_id': network_id, 'subnet_id': subnet_id, 'port_id': port_id}) allocated = models_v2.IPAllocation( network_id=network_id, port_id=port_id, ip_address=ip_address, subnet_id=subnet_id ) context.session.add(allocated) def _make_subnet_dict(self, subnet, fields=None, context=None): res = {'id': subnet['id'], 'name': subnet['name'], 'tenant_id': subnet['tenant_id'], 'network_id': subnet['network_id'], 'ip_version': subnet['ip_version'], 'cidr': subnet['cidr'], 'subnetpool_id': subnet.get('subnetpool_id'), 'allocation_pools': [{'start': pool['first_ip'], 'end': pool['last_ip']} for pool in subnet['allocation_pools']], 'gateway_ip': subnet['gateway_ip'], 'enable_dhcp': subnet['enable_dhcp'], 'ipv6_ra_mode': subnet['ipv6_ra_mode'], 'ipv6_address_mode': subnet['ipv6_address_mode'], 'dns_nameservers': [dns['address'] for dns in subnet['dns_nameservers']], 'host_routes': [{'destination': route['destination'], 'nexthop': route['nexthop']} for route in subnet['routes']], } # The shared attribute for a subnet is the same as its parent network res['shared'] = self._make_network_dict(subnet.networks, context=context)['shared'] # Call auxiliary extend functions, if any self._apply_dict_extend_functions(attributes.SUBNETS, res, subnet) return self._fields(res, fields) def _make_subnetpool_dict(self, subnetpool, fields=None): default_prefixlen = str(subnetpool['default_prefixlen']) min_prefixlen = str(subnetpool['min_prefixlen']) max_prefixlen = str(subnetpool['max_prefixlen']) res = {'id': subnetpool['id'], 'name': subnetpool['name'], 'tenant_id': subnetpool['tenant_id'], 'default_prefixlen': default_prefixlen, 'min_prefixlen': min_prefixlen, 'max_prefixlen': max_prefixlen, 'shared': subnetpool['shared'], 'prefixes': [prefix['cidr'] for prefix in subnetpool['prefixes']], 'ip_version': subnetpool['ip_version'], 'default_quota': subnetpool['default_quota']} return self._fields(res, fields) def
(self, port, fields=None, process_extensions=True): res = {"id": port["id"], 'name': port['name'], "network_id": port["network_id"], 'tenant_id': port['tenant_id'], "mac_address": port["mac_address"], "admin_state_up": port["admin_state_up"], "status": port["status"], "fixed_ips": [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in port["fixed_ips"]], "device_id": port["device_id"], "device_owner": port["device_owner"]} # Call auxiliary extend functions, if any if process_extensions: self._apply_dict_extend_functions( attributes.PORTS, res, port) return self._fields(res, fields) def _get_ipam_subnetpool_driver(self, context, subnetpool=None): if cfg.CONF.ipam_driver: return ipam_base.Pool.get_instance(subnetpool, context) else: return subnet_alloc.SubnetAllocator(subnetpool, context) def _get_network(self, context, id): try: network = self._get_by_id(context, models_v2.Network, id) except exc.NoResultFound: raise n_exc.NetworkNotFound(net_id=id) return network def _get_subnet(self, context, id): try: subnet = self._get_by_id(context, models_v2.Subnet, id) except exc.NoResultFound: raise n_exc.SubnetNotFound(subnet_id=id) return subnet def _get_subnetpool(self, context, id): try: return self._get_by_id(context, models_v2.SubnetPool, id) except exc.NoResultFound: raise n_exc.SubnetPoolNotFound(subnetpool_id=id) def _get_all_subnetpools(self, context): # NOTE(tidwellr): see note in _get_all_subnets() return context.session.query(models_v2.SubnetPool).all() def _get_port(self, context, id): try: port = self._get_by_id(context, models_v2.Port, id) except exc.NoResultFound: raise n_exc.PortNotFound(port_id=id) return port def _get_dns_by_subnet(self, context, subnet_id): dns_qry = context.session.query(models_v2.DNSNameServer) return dns_qry.filter_by(subnet_id=subnet_id).all() def _get_route_by_subnet(self, context, subnet_id): route_qry = context.session.query(models_v2.SubnetRoute) return route_qry.filter_by(subnet_id=subnet_id).all() def _get_router_gw_ports_by_network(self, context, network_id): port_qry = context.session.query(models_v2.Port) return port_qry.filter_by(network_id=network_id, device_owner=constants.DEVICE_OWNER_ROUTER_GW).all() def _get_subnets_by_network(self, context, network_id): subnet_qry = context.session.query(models_v2.Subnet) return subnet_qry.filter_by(network_id=network_id).all() def _get_subnets_by_subnetpool(self, context, subnetpool_id): subnet_qry = context.session.query(models_v2.Subnet) return subnet_qry.filter_by(subnetpool_id=subnetpool_id).all() def _get_all_subnets(self, context): # NOTE(salvatore-orlando): This query might end up putting # a lot of stress on the db. Consider adding a cache layer return context.session.query(models_v2.Subnet).all() def _get_subnets(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'subnet', limit, marker) make_subnet_dict = functools.partial(self._make_subnet_dict, context=context) return self._get_collection(context, models_v2.Subnet, make_subnet_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def _make_network_dict(self, network, fields=None, process_extensions=True, context=None): res = {'id': network['id'], 'name': network['name'], 'tenant_id': network['tenant_id'], 'admin_state_up': network['admin_state_up'], 'mtu': network.get('mtu', constants.DEFAULT_NETWORK_MTU), 'status': network['status'], 'subnets': [subnet['id'] for subnet in network['subnets']]} # The shared attribute for a network now reflects if the network # is shared to the calling tenant via an RBAC entry. shared = False matches = ('*',) + ((context.tenant_id,) if context else ()) for entry in network.rbac_entries: if (entry.action == 'access_as_shared' and entry.target_tenant in matches): shared = True break res['shared'] = shared # TODO(pritesh): Move vlan_transparent to the extension module. # vlan_transparent here is only added if the vlantransparent # extension is enabled. if ('vlan_transparent' in network and network['vlan_transparent'] != attributes.ATTR_NOT_SPECIFIED): res['vlan_transparent'] = network['vlan_transparent'] # Call auxiliary extend functions, if any if process_extensions: self._apply_dict_extend_functions( attributes.NETWORKS, res, network) return self._fields(res, fields) def _make_subnet_args(self, detail, subnet, subnetpool_id): gateway_ip = str(detail.gateway_ip) if detail.gateway_ip else None args = {'tenant_id': detail.tenant_id, 'id': subnet['id'], 'name': subnet['name'], 'network_id': subnet['network_id'], 'ip_version': subnet['ip_version'], 'cidr': str(detail.subnet_cidr), 'subnetpool_id': subnetpool_id, 'enable_dhcp': subnet['enable_dhcp'], 'gateway_ip': gateway_ip} if subnet['ip_version'] == 6 and subnet['enable_dhcp']: if attributes.is_attr_set(subnet['ipv6_ra_mode']): args['ipv6_ra_mode'] = subnet['ipv6_ra_mode'] if attributes.is_attr_set(subnet['ipv6_address_mode']): args['ipv6_address_mode'] = subnet['ipv6_address_mode'] return args def _make_fixed_ip_dict(self, ips): # Excludes from dict all keys except subnet_id and ip_address return [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in ips]
_make_port_dict
identifier_name
db_base_plugin_common.py
# Copyright (c) 2015 OpenStack Foundation. # 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. import functools
from neutron.api.v2 import attributes from neutron.common import constants from neutron.common import exceptions as n_exc from neutron.common import utils from neutron.db import common_db_mixin from neutron.db import models_v2 LOG = logging.getLogger(__name__) class DbBasePluginCommon(common_db_mixin.CommonDbMixin): """Stores getters and helper methods for db_base_plugin_v2 All private getters and simple helpers like _make_*_dict were moved from db_base_plugin_v2. More complicated logic and public methods left in db_base_plugin_v2. Main purpose of this class is to make getters accessible for Ipam backends. """ @staticmethod def _generate_mac(): return utils.get_random_mac(cfg.CONF.base_mac.split(':')) @staticmethod def _delete_ip_allocation(context, network_id, subnet_id, ip_address): # Delete the IP address from the IPAllocate table LOG.debug("Delete allocated IP %(ip_address)s " "(%(network_id)s/%(subnet_id)s)", {'ip_address': ip_address, 'network_id': network_id, 'subnet_id': subnet_id}) context.session.query(models_v2.IPAllocation).filter_by( network_id=network_id, ip_address=ip_address, subnet_id=subnet_id).delete() @staticmethod def _store_ip_allocation(context, ip_address, network_id, subnet_id, port_id): LOG.debug("Allocated IP %(ip_address)s " "(%(network_id)s/%(subnet_id)s/%(port_id)s)", {'ip_address': ip_address, 'network_id': network_id, 'subnet_id': subnet_id, 'port_id': port_id}) allocated = models_v2.IPAllocation( network_id=network_id, port_id=port_id, ip_address=ip_address, subnet_id=subnet_id ) context.session.add(allocated) def _make_subnet_dict(self, subnet, fields=None, context=None): res = {'id': subnet['id'], 'name': subnet['name'], 'tenant_id': subnet['tenant_id'], 'network_id': subnet['network_id'], 'ip_version': subnet['ip_version'], 'cidr': subnet['cidr'], 'subnetpool_id': subnet.get('subnetpool_id'), 'allocation_pools': [{'start': pool['first_ip'], 'end': pool['last_ip']} for pool in subnet['allocation_pools']], 'gateway_ip': subnet['gateway_ip'], 'enable_dhcp': subnet['enable_dhcp'], 'ipv6_ra_mode': subnet['ipv6_ra_mode'], 'ipv6_address_mode': subnet['ipv6_address_mode'], 'dns_nameservers': [dns['address'] for dns in subnet['dns_nameservers']], 'host_routes': [{'destination': route['destination'], 'nexthop': route['nexthop']} for route in subnet['routes']], } # The shared attribute for a subnet is the same as its parent network res['shared'] = self._make_network_dict(subnet.networks, context=context)['shared'] # Call auxiliary extend functions, if any self._apply_dict_extend_functions(attributes.SUBNETS, res, subnet) return self._fields(res, fields) def _make_subnetpool_dict(self, subnetpool, fields=None): default_prefixlen = str(subnetpool['default_prefixlen']) min_prefixlen = str(subnetpool['min_prefixlen']) max_prefixlen = str(subnetpool['max_prefixlen']) res = {'id': subnetpool['id'], 'name': subnetpool['name'], 'tenant_id': subnetpool['tenant_id'], 'default_prefixlen': default_prefixlen, 'min_prefixlen': min_prefixlen, 'max_prefixlen': max_prefixlen, 'shared': subnetpool['shared'], 'prefixes': [prefix['cidr'] for prefix in subnetpool['prefixes']], 'ip_version': subnetpool['ip_version'], 'default_quota': subnetpool['default_quota']} return self._fields(res, fields) def _make_port_dict(self, port, fields=None, process_extensions=True): res = {"id": port["id"], 'name': port['name'], "network_id": port["network_id"], 'tenant_id': port['tenant_id'], "mac_address": port["mac_address"], "admin_state_up": port["admin_state_up"], "status": port["status"], "fixed_ips": [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in port["fixed_ips"]], "device_id": port["device_id"], "device_owner": port["device_owner"]} # Call auxiliary extend functions, if any if process_extensions: self._apply_dict_extend_functions( attributes.PORTS, res, port) return self._fields(res, fields) def _get_ipam_subnetpool_driver(self, context, subnetpool=None): if cfg.CONF.ipam_driver: return ipam_base.Pool.get_instance(subnetpool, context) else: return subnet_alloc.SubnetAllocator(subnetpool, context) def _get_network(self, context, id): try: network = self._get_by_id(context, models_v2.Network, id) except exc.NoResultFound: raise n_exc.NetworkNotFound(net_id=id) return network def _get_subnet(self, context, id): try: subnet = self._get_by_id(context, models_v2.Subnet, id) except exc.NoResultFound: raise n_exc.SubnetNotFound(subnet_id=id) return subnet def _get_subnetpool(self, context, id): try: return self._get_by_id(context, models_v2.SubnetPool, id) except exc.NoResultFound: raise n_exc.SubnetPoolNotFound(subnetpool_id=id) def _get_all_subnetpools(self, context): # NOTE(tidwellr): see note in _get_all_subnets() return context.session.query(models_v2.SubnetPool).all() def _get_port(self, context, id): try: port = self._get_by_id(context, models_v2.Port, id) except exc.NoResultFound: raise n_exc.PortNotFound(port_id=id) return port def _get_dns_by_subnet(self, context, subnet_id): dns_qry = context.session.query(models_v2.DNSNameServer) return dns_qry.filter_by(subnet_id=subnet_id).all() def _get_route_by_subnet(self, context, subnet_id): route_qry = context.session.query(models_v2.SubnetRoute) return route_qry.filter_by(subnet_id=subnet_id).all() def _get_router_gw_ports_by_network(self, context, network_id): port_qry = context.session.query(models_v2.Port) return port_qry.filter_by(network_id=network_id, device_owner=constants.DEVICE_OWNER_ROUTER_GW).all() def _get_subnets_by_network(self, context, network_id): subnet_qry = context.session.query(models_v2.Subnet) return subnet_qry.filter_by(network_id=network_id).all() def _get_subnets_by_subnetpool(self, context, subnetpool_id): subnet_qry = context.session.query(models_v2.Subnet) return subnet_qry.filter_by(subnetpool_id=subnetpool_id).all() def _get_all_subnets(self, context): # NOTE(salvatore-orlando): This query might end up putting # a lot of stress on the db. Consider adding a cache layer return context.session.query(models_v2.Subnet).all() def _get_subnets(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'subnet', limit, marker) make_subnet_dict = functools.partial(self._make_subnet_dict, context=context) return self._get_collection(context, models_v2.Subnet, make_subnet_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def _make_network_dict(self, network, fields=None, process_extensions=True, context=None): res = {'id': network['id'], 'name': network['name'], 'tenant_id': network['tenant_id'], 'admin_state_up': network['admin_state_up'], 'mtu': network.get('mtu', constants.DEFAULT_NETWORK_MTU), 'status': network['status'], 'subnets': [subnet['id'] for subnet in network['subnets']]} # The shared attribute for a network now reflects if the network # is shared to the calling tenant via an RBAC entry. shared = False matches = ('*',) + ((context.tenant_id,) if context else ()) for entry in network.rbac_entries: if (entry.action == 'access_as_shared' and entry.target_tenant in matches): shared = True break res['shared'] = shared # TODO(pritesh): Move vlan_transparent to the extension module. # vlan_transparent here is only added if the vlantransparent # extension is enabled. if ('vlan_transparent' in network and network['vlan_transparent'] != attributes.ATTR_NOT_SPECIFIED): res['vlan_transparent'] = network['vlan_transparent'] # Call auxiliary extend functions, if any if process_extensions: self._apply_dict_extend_functions( attributes.NETWORKS, res, network) return self._fields(res, fields) def _make_subnet_args(self, detail, subnet, subnetpool_id): gateway_ip = str(detail.gateway_ip) if detail.gateway_ip else None args = {'tenant_id': detail.tenant_id, 'id': subnet['id'], 'name': subnet['name'], 'network_id': subnet['network_id'], 'ip_version': subnet['ip_version'], 'cidr': str(detail.subnet_cidr), 'subnetpool_id': subnetpool_id, 'enable_dhcp': subnet['enable_dhcp'], 'gateway_ip': gateway_ip} if subnet['ip_version'] == 6 and subnet['enable_dhcp']: if attributes.is_attr_set(subnet['ipv6_ra_mode']): args['ipv6_ra_mode'] = subnet['ipv6_ra_mode'] if attributes.is_attr_set(subnet['ipv6_address_mode']): args['ipv6_address_mode'] = subnet['ipv6_address_mode'] return args def _make_fixed_ip_dict(self, ips): # Excludes from dict all keys except subnet_id and ip_address return [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in ips]
from oslo_config import cfg from oslo_log import log as logging from sqlalchemy.orm import exc
random_line_split
db_base_plugin_common.py
# Copyright (c) 2015 OpenStack Foundation. # 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. import functools from oslo_config import cfg from oslo_log import log as logging from sqlalchemy.orm import exc from neutron.api.v2 import attributes from neutron.common import constants from neutron.common import exceptions as n_exc from neutron.common import utils from neutron.db import common_db_mixin from neutron.db import models_v2 LOG = logging.getLogger(__name__) class DbBasePluginCommon(common_db_mixin.CommonDbMixin): """Stores getters and helper methods for db_base_plugin_v2 All private getters and simple helpers like _make_*_dict were moved from db_base_plugin_v2. More complicated logic and public methods left in db_base_plugin_v2. Main purpose of this class is to make getters accessible for Ipam backends. """ @staticmethod def _generate_mac(): return utils.get_random_mac(cfg.CONF.base_mac.split(':')) @staticmethod def _delete_ip_allocation(context, network_id, subnet_id, ip_address): # Delete the IP address from the IPAllocate table LOG.debug("Delete allocated IP %(ip_address)s " "(%(network_id)s/%(subnet_id)s)", {'ip_address': ip_address, 'network_id': network_id, 'subnet_id': subnet_id}) context.session.query(models_v2.IPAllocation).filter_by( network_id=network_id, ip_address=ip_address, subnet_id=subnet_id).delete() @staticmethod def _store_ip_allocation(context, ip_address, network_id, subnet_id, port_id): LOG.debug("Allocated IP %(ip_address)s " "(%(network_id)s/%(subnet_id)s/%(port_id)s)", {'ip_address': ip_address, 'network_id': network_id, 'subnet_id': subnet_id, 'port_id': port_id}) allocated = models_v2.IPAllocation( network_id=network_id, port_id=port_id, ip_address=ip_address, subnet_id=subnet_id ) context.session.add(allocated) def _make_subnet_dict(self, subnet, fields=None, context=None): res = {'id': subnet['id'], 'name': subnet['name'], 'tenant_id': subnet['tenant_id'], 'network_id': subnet['network_id'], 'ip_version': subnet['ip_version'], 'cidr': subnet['cidr'], 'subnetpool_id': subnet.get('subnetpool_id'), 'allocation_pools': [{'start': pool['first_ip'], 'end': pool['last_ip']} for pool in subnet['allocation_pools']], 'gateway_ip': subnet['gateway_ip'], 'enable_dhcp': subnet['enable_dhcp'], 'ipv6_ra_mode': subnet['ipv6_ra_mode'], 'ipv6_address_mode': subnet['ipv6_address_mode'], 'dns_nameservers': [dns['address'] for dns in subnet['dns_nameservers']], 'host_routes': [{'destination': route['destination'], 'nexthop': route['nexthop']} for route in subnet['routes']], } # The shared attribute for a subnet is the same as its parent network res['shared'] = self._make_network_dict(subnet.networks, context=context)['shared'] # Call auxiliary extend functions, if any self._apply_dict_extend_functions(attributes.SUBNETS, res, subnet) return self._fields(res, fields) def _make_subnetpool_dict(self, subnetpool, fields=None): default_prefixlen = str(subnetpool['default_prefixlen']) min_prefixlen = str(subnetpool['min_prefixlen']) max_prefixlen = str(subnetpool['max_prefixlen']) res = {'id': subnetpool['id'], 'name': subnetpool['name'], 'tenant_id': subnetpool['tenant_id'], 'default_prefixlen': default_prefixlen, 'min_prefixlen': min_prefixlen, 'max_prefixlen': max_prefixlen, 'shared': subnetpool['shared'], 'prefixes': [prefix['cidr'] for prefix in subnetpool['prefixes']], 'ip_version': subnetpool['ip_version'], 'default_quota': subnetpool['default_quota']} return self._fields(res, fields) def _make_port_dict(self, port, fields=None, process_extensions=True): res = {"id": port["id"], 'name': port['name'], "network_id": port["network_id"], 'tenant_id': port['tenant_id'], "mac_address": port["mac_address"], "admin_state_up": port["admin_state_up"], "status": port["status"], "fixed_ips": [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in port["fixed_ips"]], "device_id": port["device_id"], "device_owner": port["device_owner"]} # Call auxiliary extend functions, if any if process_extensions: self._apply_dict_extend_functions( attributes.PORTS, res, port) return self._fields(res, fields) def _get_ipam_subnetpool_driver(self, context, subnetpool=None): if cfg.CONF.ipam_driver: return ipam_base.Pool.get_instance(subnetpool, context) else: return subnet_alloc.SubnetAllocator(subnetpool, context) def _get_network(self, context, id): try: network = self._get_by_id(context, models_v2.Network, id) except exc.NoResultFound: raise n_exc.NetworkNotFound(net_id=id) return network def _get_subnet(self, context, id): try: subnet = self._get_by_id(context, models_v2.Subnet, id) except exc.NoResultFound: raise n_exc.SubnetNotFound(subnet_id=id) return subnet def _get_subnetpool(self, context, id): try: return self._get_by_id(context, models_v2.SubnetPool, id) except exc.NoResultFound: raise n_exc.SubnetPoolNotFound(subnetpool_id=id) def _get_all_subnetpools(self, context): # NOTE(tidwellr): see note in _get_all_subnets() return context.session.query(models_v2.SubnetPool).all() def _get_port(self, context, id): try: port = self._get_by_id(context, models_v2.Port, id) except exc.NoResultFound: raise n_exc.PortNotFound(port_id=id) return port def _get_dns_by_subnet(self, context, subnet_id): dns_qry = context.session.query(models_v2.DNSNameServer) return dns_qry.filter_by(subnet_id=subnet_id).all() def _get_route_by_subnet(self, context, subnet_id): route_qry = context.session.query(models_v2.SubnetRoute) return route_qry.filter_by(subnet_id=subnet_id).all() def _get_router_gw_ports_by_network(self, context, network_id): port_qry = context.session.query(models_v2.Port) return port_qry.filter_by(network_id=network_id, device_owner=constants.DEVICE_OWNER_ROUTER_GW).all() def _get_subnets_by_network(self, context, network_id): subnet_qry = context.session.query(models_v2.Subnet) return subnet_qry.filter_by(network_id=network_id).all() def _get_subnets_by_subnetpool(self, context, subnetpool_id): subnet_qry = context.session.query(models_v2.Subnet) return subnet_qry.filter_by(subnetpool_id=subnetpool_id).all() def _get_all_subnets(self, context): # NOTE(salvatore-orlando): This query might end up putting # a lot of stress on the db. Consider adding a cache layer return context.session.query(models_v2.Subnet).all() def _get_subnets(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'subnet', limit, marker) make_subnet_dict = functools.partial(self._make_subnet_dict, context=context) return self._get_collection(context, models_v2.Subnet, make_subnet_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def _make_network_dict(self, network, fields=None, process_extensions=True, context=None): res = {'id': network['id'], 'name': network['name'], 'tenant_id': network['tenant_id'], 'admin_state_up': network['admin_state_up'], 'mtu': network.get('mtu', constants.DEFAULT_NETWORK_MTU), 'status': network['status'], 'subnets': [subnet['id'] for subnet in network['subnets']]} # The shared attribute for a network now reflects if the network # is shared to the calling tenant via an RBAC entry. shared = False matches = ('*',) + ((context.tenant_id,) if context else ()) for entry in network.rbac_entries:
res['shared'] = shared # TODO(pritesh): Move vlan_transparent to the extension module. # vlan_transparent here is only added if the vlantransparent # extension is enabled. if ('vlan_transparent' in network and network['vlan_transparent'] != attributes.ATTR_NOT_SPECIFIED): res['vlan_transparent'] = network['vlan_transparent'] # Call auxiliary extend functions, if any if process_extensions: self._apply_dict_extend_functions( attributes.NETWORKS, res, network) return self._fields(res, fields) def _make_subnet_args(self, detail, subnet, subnetpool_id): gateway_ip = str(detail.gateway_ip) if detail.gateway_ip else None args = {'tenant_id': detail.tenant_id, 'id': subnet['id'], 'name': subnet['name'], 'network_id': subnet['network_id'], 'ip_version': subnet['ip_version'], 'cidr': str(detail.subnet_cidr), 'subnetpool_id': subnetpool_id, 'enable_dhcp': subnet['enable_dhcp'], 'gateway_ip': gateway_ip} if subnet['ip_version'] == 6 and subnet['enable_dhcp']: if attributes.is_attr_set(subnet['ipv6_ra_mode']): args['ipv6_ra_mode'] = subnet['ipv6_ra_mode'] if attributes.is_attr_set(subnet['ipv6_address_mode']): args['ipv6_address_mode'] = subnet['ipv6_address_mode'] return args def _make_fixed_ip_dict(self, ips): # Excludes from dict all keys except subnet_id and ip_address return [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in ips]
if (entry.action == 'access_as_shared' and entry.target_tenant in matches): shared = True break
conditional_block
metrics.ts
// source: models/metrics.ts /// <reference path="proto.ts" /> /// <reference path="../external/mithril/mithril.d.ts" /> /// <reference path="../util/chainprop.ts" /> /// <reference path="../util/convert.ts" /> /// <reference path="../util/http.ts" /> /// <reference path="../util/querycache.ts" /> // Author: Matt Tracy (matt@cockroachlabs.com) /** * Models contains data models pulled from cockroach. */ module Models { "use strict"; /** * Metrics package represents the internal performance metrics collected by * cockroach. */ export module Metrics { import promise = _mithril.MithrilPromise; /** * QueryInfo is an interface that is implemented by both Proto.QueryResult and * Proto.QueryRequest. A QueryInfo object references a unique dataset * that can be returned from the server. */ interface QueryInfo { name: string; aggregator: Proto.QueryAggregator; } /** * QueryInfoKey returns a string key that uniquely identifies the * server-side dataset referenced by the QueryInfo. */ export function QueryInfoKey(qi: QueryInfo): string { return Proto.QueryAggregator[qi.aggregator] + ":" + qi.name; } /** * QueryInfoSet is a generic set structure which contains at most one * QueryInfo object for each possible key. They key for a QueryInfo * object should be generated with the QueryInfoKey() method. */ export class QueryInfoSet<T extends QueryInfo> { private _set: { [key: string]: T } = {}; /** * add adds an object of type T to this set. The supplied T is * uniquely identified by the output of QueryKey(). If the set * already contains an entry with the same QueryKey, it is * overwritten. */ add(qi: T): void { let key: string = QueryInfoKey(qi); this._set[key] = qi; } /** * get returns the object in the set which has the given key. */ get(key: string): T { return this._set[key]; } /** * forEach invokes the supplied function for each member of the set. */ forEach(fn: (element: T) => void): void { let keys: string[] = Object.keys(this._set); for (let i: number = 0; i < keys.length; i++)
} } /** * QueryResultSet is a set structure that contains at most one * QueryResult object for each possible key. The key for each * QueryResult is generated by the QueryInfoKey() method. */ export type QueryResultSet = QueryInfoSet<Proto.QueryResult>; /** * QueryRequestSet is a set structure that contains at most one * QueryRequest object for each possible key. The key for each * QueryRequest is generated by the QueryInfoKey() method. */ export type QueryRequestSet = QueryInfoSet<Proto.QueryRequest>; /** * Select contains time series selectors for use in metrics queries. * Each selector defines a dataset on the server which should be * queried, along with additional information about how to process the * data (e.g. aggregation functions, transformations) and how it should * be displayed (e.g. a friendly title for graph legends). */ export module Select { /** * Selector is the common interface implemented by all Selector * types. The is a read-only interface used by other components to * extract relevant information from the selector. */ export interface Selector { /** * request returns a QueryRequest object based on this selector. */ request(): Proto.QueryRequest; /** * series returns the series that is being queried. */ series(): string; /** * sources returns the data sources to which this query is restrained. */ sources(): string[]; /** * title returns a display-friendly title for this series. */ title(): string; } /** * AvgSelector selects the average value of the supplied time series. */ class AvgSelector implements Selector { constructor(private seriesName: string) { } title: Utils.ChainProperty<string, AvgSelector> = Utils.ChainProp(this, this.seriesName); sources: Utils.ChainProperty<string[], AvgSelector> = Utils.ChainProp(this, []); series: () => string = () => { return this.seriesName; }; request: () => Proto.QueryRequest = (): Proto.QueryRequest => { return { name: this.seriesName, sources: this.sources(), aggregator: Proto.QueryAggregator.AVG }; }; } /** * AvgRateSelector selects the rate of change of the average value * of the supplied time series. */ class AvgRateSelector implements Selector { constructor(private seriesName: string) {} title: Utils.ChainProperty<string, AvgRateSelector> = Utils.ChainProp(this, this.seriesName); sources: Utils.ChainProperty<string[], AvgRateSelector> = Utils.ChainProp(this, []); series: () => string = () => { return this.seriesName; }; request: () => Proto.QueryRequest = (): Proto.QueryRequest => { return { name: this.seriesName, sources: this.sources(), aggregator: Proto.QueryAggregator.AVG_RATE }; }; } /** * Avg instantiates a new AvgSelector for the supplied time series. */ export function Avg(series: string): AvgSelector { return new AvgSelector(series); } /** * AvgRate instantiates a new AvgRateSelector for the supplied time * series. */ export function AvgRate(series: string): AvgRateSelector { return new AvgRateSelector(series); } } /** * time contains available time span specifiers for metrics queries. */ export module Time { /** * TimeSpan is the interface implemeted by time span specifiers. */ export interface TimeSpan { /** * timespan returns a two-value number array which defines the * time range of a query. The first value is a timestamp for the * start of the range, the second value a timestamp for the end * of the range. */ timespan(): number[]; } /** * Recent selects a duration of constant size extending backwards * from the current time. The current time is recomputed each time * Recent's timespan() method is called. */ export function Recent(duration: number): TimeSpan { return { timespan: function(): number[] { let endTime: Date = new Date(); let startTime: Date = new Date(endTime.getTime() - duration); return [startTime.getTime(), endTime.getTime()]; } }; } } /** * An Axis is a collection of selectors which are expressed in the same * units. Data from the selectors can be displayed together on the same * chart with a shared domain. */ export class Axis { /** * label is a string value which labels the axis. This should * describe the units for values on the axis. */ label: Utils.ChainProperty<string, Axis> = Utils.ChainProp(this, null); /** * format is a function which formats numerical values on the axis * for display. */ format: Utils.ChainProperty<(n: number) => string, Axis> = Utils.ChainProp(this, null); /** * selectors is an array of selectors which should be displayed on this * axis. */ selectors: Utils.ChainProperty<Select.Selector[], Axis> = Utils.ChainProp(this, []); /** * Title returns an appropriate title for a chart displaying this * axis. This is generated by combining the titles of all selectors * on the axis. */ title(): string { let selectors: Select.Selector[] = this.selectors(); if (selectors.length === 0) { return "No series selected."; } return selectors.map((s: Select.Selector) => s.title()).join(" vs. "); } } /** * NewAxis constructs a new axis object which displays information from * the supplied selectors. Additional properties of the query can be * configured by calling setter methods on the returned Axis. */ export function NewAxis(...selectors: Select.Selector[]): Axis { return new Axis().selectors(selectors); } /** * Query describes a single, repeatable query for time series data. Each * query contains one or more time series selectors, and a time span * over which to query those selectors. */ export class Query { /** * timespan gets or sets the TimeSpan over which data should be * queried. By default, the query will return the last ten minutes * of data. */ timespan: Utils.ChainProperty<Time.TimeSpan, Query> = Utils.ChainProp(this, Time.Recent(10 * 60 * 1000)); /** * title gets or sets the title of this query, which can be applied * to visualizations of the data from this query. */ title: Utils.ChainProperty<string, Query> = Utils.ChainProp(this, "Query Title"); /** * selectors is a set of selectors which should be displayed on this * axis. */ selectors: Utils.ChainProperty<Select.Selector[], Query> = Utils.ChainProp(this, []); /** * execute dispatches a query to the server and returns a promise * for the results. */ execute: () => promise<QueryResultSet> = (): promise<QueryResultSet> => { let ts: number[] = this.timespan().timespan(); let req: Proto.QueryRequestSet = { start_nanos: Utils.Convert.MilliToNano(ts[0]), end_nanos: Utils.Convert.MilliToNano(ts[1]), queries: [] }; // Build a set of requests by looping over selectors. The set of // requests will be de-duplicated. let requestSet: QueryInfoSet<Proto.QueryRequest> = new QueryInfoSet<Proto.QueryRequest>(); this.selectors().forEach((s: Select.Selector) => { requestSet.add(s.request()); }); requestSet.forEach((qr: Proto.QueryRequest) => { req.queries.push(qr); }); return Query.dispatch_query(req); }; private static dispatch_query(q: Proto.QueryRequestSet): promise<QueryResultSet> { return Utils.Http.Post("/ts/query", q) .then((d: Proto.QueryResultSet) => { // Populate missing collection fields with empty arrays. if (!d.results) { d.results = []; } let result: QueryInfoSet<Proto.QueryResult> = new QueryInfoSet<Proto.QueryResult>(); d.results.forEach((r: Proto.QueryResult) => { if (!r.datapoints) { r.datapoints = []; } result.add(r); }); return result; }); } } /** * NewQuery constructs a new query object which queries the supplied * selectors. Additional properties of the query can be configured by * calling setter methods on the returned Query. */ export function NewQuery(...selectors: Select.Selector[]): Query { return new Query().selectors(selectors); } /** * Executor is a convenience class for persisting the results of a query * execution. */ export class Executor extends Utils.QueryCache<QueryResultSet> { query: () => Query = () => { return this._metricquery; }; private _metricquery: Query; constructor(q: Query) { super(q.execute); this._metricquery = q; } } } }
{ fn(this._set[keys[i]]); }
conditional_block
metrics.ts
// source: models/metrics.ts /// <reference path="proto.ts" /> /// <reference path="../external/mithril/mithril.d.ts" /> /// <reference path="../util/chainprop.ts" /> /// <reference path="../util/convert.ts" /> /// <reference path="../util/http.ts" /> /// <reference path="../util/querycache.ts" /> // Author: Matt Tracy (matt@cockroachlabs.com) /** * Models contains data models pulled from cockroach. */ module Models { "use strict"; /** * Metrics package represents the internal performance metrics collected by * cockroach. */ export module Metrics { import promise = _mithril.MithrilPromise; /** * QueryInfo is an interface that is implemented by both Proto.QueryResult and * Proto.QueryRequest. A QueryInfo object references a unique dataset * that can be returned from the server. */ interface QueryInfo { name: string; aggregator: Proto.QueryAggregator; } /** * QueryInfoKey returns a string key that uniquely identifies the * server-side dataset referenced by the QueryInfo. */ export function QueryInfoKey(qi: QueryInfo): string { return Proto.QueryAggregator[qi.aggregator] + ":" + qi.name; } /** * QueryInfoSet is a generic set structure which contains at most one * QueryInfo object for each possible key. They key for a QueryInfo * object should be generated with the QueryInfoKey() method. */ export class QueryInfoSet<T extends QueryInfo> { private _set: { [key: string]: T } = {}; /** * add adds an object of type T to this set. The supplied T is * uniquely identified by the output of QueryKey(). If the set * already contains an entry with the same QueryKey, it is * overwritten. */ add(qi: T): void { let key: string = QueryInfoKey(qi); this._set[key] = qi; } /** * get returns the object in the set which has the given key. */ get(key: string): T { return this._set[key]; } /** * forEach invokes the supplied function for each member of the set. */ forEach(fn: (element: T) => void): void { let keys: string[] = Object.keys(this._set); for (let i: number = 0; i < keys.length; i++) { fn(this._set[keys[i]]); } } } /** * QueryResultSet is a set structure that contains at most one * QueryResult object for each possible key. The key for each * QueryResult is generated by the QueryInfoKey() method. */ export type QueryResultSet = QueryInfoSet<Proto.QueryResult>; /** * QueryRequestSet is a set structure that contains at most one * QueryRequest object for each possible key. The key for each * QueryRequest is generated by the QueryInfoKey() method. */ export type QueryRequestSet = QueryInfoSet<Proto.QueryRequest>; /** * Select contains time series selectors for use in metrics queries. * Each selector defines a dataset on the server which should be * queried, along with additional information about how to process the * data (e.g. aggregation functions, transformations) and how it should * be displayed (e.g. a friendly title for graph legends). */ export module Select { /** * Selector is the common interface implemented by all Selector * types. The is a read-only interface used by other components to * extract relevant information from the selector. */ export interface Selector { /** * request returns a QueryRequest object based on this selector. */ request(): Proto.QueryRequest; /** * series returns the series that is being queried. */ series(): string; /** * sources returns the data sources to which this query is restrained. */ sources(): string[]; /** * title returns a display-friendly title for this series. */ title(): string; } /** * AvgSelector selects the average value of the supplied time series. */ class AvgSelector implements Selector { constructor(private seriesName: string) { } title: Utils.ChainProperty<string, AvgSelector> = Utils.ChainProp(this, this.seriesName); sources: Utils.ChainProperty<string[], AvgSelector> = Utils.ChainProp(this, []); series: () => string = () => { return this.seriesName; }; request: () => Proto.QueryRequest = (): Proto.QueryRequest => { return { name: this.seriesName, sources: this.sources(), aggregator: Proto.QueryAggregator.AVG }; }; } /** * AvgRateSelector selects the rate of change of the average value * of the supplied time series. */ class AvgRateSelector implements Selector { constructor(private seriesName: string) {} title: Utils.ChainProperty<string, AvgRateSelector> = Utils.ChainProp(this, this.seriesName); sources: Utils.ChainProperty<string[], AvgRateSelector> = Utils.ChainProp(this, []); series: () => string = () => { return this.seriesName; }; request: () => Proto.QueryRequest = (): Proto.QueryRequest => { return { name: this.seriesName, sources: this.sources(), aggregator: Proto.QueryAggregator.AVG_RATE }; }; } /** * Avg instantiates a new AvgSelector for the supplied time series. */ export function Avg(series: string): AvgSelector { return new AvgSelector(series); } /** * AvgRate instantiates a new AvgRateSelector for the supplied time * series. */ export function AvgRate(series: string): AvgRateSelector { return new AvgRateSelector(series); } } /** * time contains available time span specifiers for metrics queries. */ export module Time { /** * TimeSpan is the interface implemeted by time span specifiers. */ export interface TimeSpan { /** * timespan returns a two-value number array which defines the * time range of a query. The first value is a timestamp for the * start of the range, the second value a timestamp for the end * of the range. */ timespan(): number[]; } /** * Recent selects a duration of constant size extending backwards * from the current time. The current time is recomputed each time * Recent's timespan() method is called. */ export function Recent(duration: number): TimeSpan { return { timespan: function(): number[] { let endTime: Date = new Date(); let startTime: Date = new Date(endTime.getTime() - duration); return [startTime.getTime(), endTime.getTime()]; } }; } } /** * An Axis is a collection of selectors which are expressed in the same * units. Data from the selectors can be displayed together on the same * chart with a shared domain. */ export class Axis { /** * label is a string value which labels the axis. This should * describe the units for values on the axis. */ label: Utils.ChainProperty<string, Axis> = Utils.ChainProp(this, null); /** * format is a function which formats numerical values on the axis * for display. */ format: Utils.ChainProperty<(n: number) => string, Axis> = Utils.ChainProp(this, null); /** * selectors is an array of selectors which should be displayed on this * axis. */ selectors: Utils.ChainProperty<Select.Selector[], Axis> = Utils.ChainProp(this, []); /** * Title returns an appropriate title for a chart displaying this * axis. This is generated by combining the titles of all selectors * on the axis. */ title(): string { let selectors: Select.Selector[] = this.selectors(); if (selectors.length === 0) { return "No series selected."; } return selectors.map((s: Select.Selector) => s.title()).join(" vs. "); } } /** * NewAxis constructs a new axis object which displays information from * the supplied selectors. Additional properties of the query can be * configured by calling setter methods on the returned Axis. */ export function
(...selectors: Select.Selector[]): Axis { return new Axis().selectors(selectors); } /** * Query describes a single, repeatable query for time series data. Each * query contains one or more time series selectors, and a time span * over which to query those selectors. */ export class Query { /** * timespan gets or sets the TimeSpan over which data should be * queried. By default, the query will return the last ten minutes * of data. */ timespan: Utils.ChainProperty<Time.TimeSpan, Query> = Utils.ChainProp(this, Time.Recent(10 * 60 * 1000)); /** * title gets or sets the title of this query, which can be applied * to visualizations of the data from this query. */ title: Utils.ChainProperty<string, Query> = Utils.ChainProp(this, "Query Title"); /** * selectors is a set of selectors which should be displayed on this * axis. */ selectors: Utils.ChainProperty<Select.Selector[], Query> = Utils.ChainProp(this, []); /** * execute dispatches a query to the server and returns a promise * for the results. */ execute: () => promise<QueryResultSet> = (): promise<QueryResultSet> => { let ts: number[] = this.timespan().timespan(); let req: Proto.QueryRequestSet = { start_nanos: Utils.Convert.MilliToNano(ts[0]), end_nanos: Utils.Convert.MilliToNano(ts[1]), queries: [] }; // Build a set of requests by looping over selectors. The set of // requests will be de-duplicated. let requestSet: QueryInfoSet<Proto.QueryRequest> = new QueryInfoSet<Proto.QueryRequest>(); this.selectors().forEach((s: Select.Selector) => { requestSet.add(s.request()); }); requestSet.forEach((qr: Proto.QueryRequest) => { req.queries.push(qr); }); return Query.dispatch_query(req); }; private static dispatch_query(q: Proto.QueryRequestSet): promise<QueryResultSet> { return Utils.Http.Post("/ts/query", q) .then((d: Proto.QueryResultSet) => { // Populate missing collection fields with empty arrays. if (!d.results) { d.results = []; } let result: QueryInfoSet<Proto.QueryResult> = new QueryInfoSet<Proto.QueryResult>(); d.results.forEach((r: Proto.QueryResult) => { if (!r.datapoints) { r.datapoints = []; } result.add(r); }); return result; }); } } /** * NewQuery constructs a new query object which queries the supplied * selectors. Additional properties of the query can be configured by * calling setter methods on the returned Query. */ export function NewQuery(...selectors: Select.Selector[]): Query { return new Query().selectors(selectors); } /** * Executor is a convenience class for persisting the results of a query * execution. */ export class Executor extends Utils.QueryCache<QueryResultSet> { query: () => Query = () => { return this._metricquery; }; private _metricquery: Query; constructor(q: Query) { super(q.execute); this._metricquery = q; } } } }
NewAxis
identifier_name
metrics.ts
// source: models/metrics.ts /// <reference path="proto.ts" /> /// <reference path="../external/mithril/mithril.d.ts" /> /// <reference path="../util/chainprop.ts" /> /// <reference path="../util/convert.ts" /> /// <reference path="../util/http.ts" /> /// <reference path="../util/querycache.ts" /> // Author: Matt Tracy (matt@cockroachlabs.com) /** * Models contains data models pulled from cockroach. */ module Models { "use strict"; /** * Metrics package represents the internal performance metrics collected by * cockroach. */ export module Metrics { import promise = _mithril.MithrilPromise; /** * QueryInfo is an interface that is implemented by both Proto.QueryResult and * Proto.QueryRequest. A QueryInfo object references a unique dataset * that can be returned from the server. */ interface QueryInfo { name: string; aggregator: Proto.QueryAggregator; } /** * QueryInfoKey returns a string key that uniquely identifies the * server-side dataset referenced by the QueryInfo. */ export function QueryInfoKey(qi: QueryInfo): string { return Proto.QueryAggregator[qi.aggregator] + ":" + qi.name; } /** * QueryInfoSet is a generic set structure which contains at most one * QueryInfo object for each possible key. They key for a QueryInfo * object should be generated with the QueryInfoKey() method. */ export class QueryInfoSet<T extends QueryInfo> { private _set: { [key: string]: T } = {}; /** * add adds an object of type T to this set. The supplied T is * uniquely identified by the output of QueryKey(). If the set * already contains an entry with the same QueryKey, it is * overwritten. */ add(qi: T): void { let key: string = QueryInfoKey(qi); this._set[key] = qi; } /** * get returns the object in the set which has the given key. */ get(key: string): T { return this._set[key]; } /** * forEach invokes the supplied function for each member of the set. */ forEach(fn: (element: T) => void): void { let keys: string[] = Object.keys(this._set); for (let i: number = 0; i < keys.length; i++) { fn(this._set[keys[i]]); } } } /** * QueryResultSet is a set structure that contains at most one * QueryResult object for each possible key. The key for each * QueryResult is generated by the QueryInfoKey() method. */ export type QueryResultSet = QueryInfoSet<Proto.QueryResult>; /** * QueryRequestSet is a set structure that contains at most one * QueryRequest object for each possible key. The key for each * QueryRequest is generated by the QueryInfoKey() method. */ export type QueryRequestSet = QueryInfoSet<Proto.QueryRequest>; /** * Select contains time series selectors for use in metrics queries. * Each selector defines a dataset on the server which should be * queried, along with additional information about how to process the * data (e.g. aggregation functions, transformations) and how it should * be displayed (e.g. a friendly title for graph legends). */ export module Select { /** * Selector is the common interface implemented by all Selector * types. The is a read-only interface used by other components to * extract relevant information from the selector. */ export interface Selector { /** * request returns a QueryRequest object based on this selector. */ request(): Proto.QueryRequest; /** * series returns the series that is being queried. */ series(): string; /** * sources returns the data sources to which this query is restrained. */ sources(): string[]; /** * title returns a display-friendly title for this series. */ title(): string; } /**
class AvgSelector implements Selector { constructor(private seriesName: string) { } title: Utils.ChainProperty<string, AvgSelector> = Utils.ChainProp(this, this.seriesName); sources: Utils.ChainProperty<string[], AvgSelector> = Utils.ChainProp(this, []); series: () => string = () => { return this.seriesName; }; request: () => Proto.QueryRequest = (): Proto.QueryRequest => { return { name: this.seriesName, sources: this.sources(), aggregator: Proto.QueryAggregator.AVG }; }; } /** * AvgRateSelector selects the rate of change of the average value * of the supplied time series. */ class AvgRateSelector implements Selector { constructor(private seriesName: string) {} title: Utils.ChainProperty<string, AvgRateSelector> = Utils.ChainProp(this, this.seriesName); sources: Utils.ChainProperty<string[], AvgRateSelector> = Utils.ChainProp(this, []); series: () => string = () => { return this.seriesName; }; request: () => Proto.QueryRequest = (): Proto.QueryRequest => { return { name: this.seriesName, sources: this.sources(), aggregator: Proto.QueryAggregator.AVG_RATE }; }; } /** * Avg instantiates a new AvgSelector for the supplied time series. */ export function Avg(series: string): AvgSelector { return new AvgSelector(series); } /** * AvgRate instantiates a new AvgRateSelector for the supplied time * series. */ export function AvgRate(series: string): AvgRateSelector { return new AvgRateSelector(series); } } /** * time contains available time span specifiers for metrics queries. */ export module Time { /** * TimeSpan is the interface implemeted by time span specifiers. */ export interface TimeSpan { /** * timespan returns a two-value number array which defines the * time range of a query. The first value is a timestamp for the * start of the range, the second value a timestamp for the end * of the range. */ timespan(): number[]; } /** * Recent selects a duration of constant size extending backwards * from the current time. The current time is recomputed each time * Recent's timespan() method is called. */ export function Recent(duration: number): TimeSpan { return { timespan: function(): number[] { let endTime: Date = new Date(); let startTime: Date = new Date(endTime.getTime() - duration); return [startTime.getTime(), endTime.getTime()]; } }; } } /** * An Axis is a collection of selectors which are expressed in the same * units. Data from the selectors can be displayed together on the same * chart with a shared domain. */ export class Axis { /** * label is a string value which labels the axis. This should * describe the units for values on the axis. */ label: Utils.ChainProperty<string, Axis> = Utils.ChainProp(this, null); /** * format is a function which formats numerical values on the axis * for display. */ format: Utils.ChainProperty<(n: number) => string, Axis> = Utils.ChainProp(this, null); /** * selectors is an array of selectors which should be displayed on this * axis. */ selectors: Utils.ChainProperty<Select.Selector[], Axis> = Utils.ChainProp(this, []); /** * Title returns an appropriate title for a chart displaying this * axis. This is generated by combining the titles of all selectors * on the axis. */ title(): string { let selectors: Select.Selector[] = this.selectors(); if (selectors.length === 0) { return "No series selected."; } return selectors.map((s: Select.Selector) => s.title()).join(" vs. "); } } /** * NewAxis constructs a new axis object which displays information from * the supplied selectors. Additional properties of the query can be * configured by calling setter methods on the returned Axis. */ export function NewAxis(...selectors: Select.Selector[]): Axis { return new Axis().selectors(selectors); } /** * Query describes a single, repeatable query for time series data. Each * query contains one or more time series selectors, and a time span * over which to query those selectors. */ export class Query { /** * timespan gets or sets the TimeSpan over which data should be * queried. By default, the query will return the last ten minutes * of data. */ timespan: Utils.ChainProperty<Time.TimeSpan, Query> = Utils.ChainProp(this, Time.Recent(10 * 60 * 1000)); /** * title gets or sets the title of this query, which can be applied * to visualizations of the data from this query. */ title: Utils.ChainProperty<string, Query> = Utils.ChainProp(this, "Query Title"); /** * selectors is a set of selectors which should be displayed on this * axis. */ selectors: Utils.ChainProperty<Select.Selector[], Query> = Utils.ChainProp(this, []); /** * execute dispatches a query to the server and returns a promise * for the results. */ execute: () => promise<QueryResultSet> = (): promise<QueryResultSet> => { let ts: number[] = this.timespan().timespan(); let req: Proto.QueryRequestSet = { start_nanos: Utils.Convert.MilliToNano(ts[0]), end_nanos: Utils.Convert.MilliToNano(ts[1]), queries: [] }; // Build a set of requests by looping over selectors. The set of // requests will be de-duplicated. let requestSet: QueryInfoSet<Proto.QueryRequest> = new QueryInfoSet<Proto.QueryRequest>(); this.selectors().forEach((s: Select.Selector) => { requestSet.add(s.request()); }); requestSet.forEach((qr: Proto.QueryRequest) => { req.queries.push(qr); }); return Query.dispatch_query(req); }; private static dispatch_query(q: Proto.QueryRequestSet): promise<QueryResultSet> { return Utils.Http.Post("/ts/query", q) .then((d: Proto.QueryResultSet) => { // Populate missing collection fields with empty arrays. if (!d.results) { d.results = []; } let result: QueryInfoSet<Proto.QueryResult> = new QueryInfoSet<Proto.QueryResult>(); d.results.forEach((r: Proto.QueryResult) => { if (!r.datapoints) { r.datapoints = []; } result.add(r); }); return result; }); } } /** * NewQuery constructs a new query object which queries the supplied * selectors. Additional properties of the query can be configured by * calling setter methods on the returned Query. */ export function NewQuery(...selectors: Select.Selector[]): Query { return new Query().selectors(selectors); } /** * Executor is a convenience class for persisting the results of a query * execution. */ export class Executor extends Utils.QueryCache<QueryResultSet> { query: () => Query = () => { return this._metricquery; }; private _metricquery: Query; constructor(q: Query) { super(q.execute); this._metricquery = q; } } } }
* AvgSelector selects the average value of the supplied time series. */
random_line_split
socialcoffee.js
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //var MODAL = $("#modalProducto"); var URL = Define.URL_BASE; window.onload=function(){ //toastr.error("Ingresaaaaaaaaa"); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'validar' }; httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; function redireccionar(url_direccionar){
$("#olvide").delegate('#semeolvido', 'click', function () {//buscar pedido en bd var usuario_a_buscar = $("#username").val(); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'semeolvido', username: usuario_a_buscar }; if(!SOLICITUSEMEOLVIDO){ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.itemsCount != 0){ SOLICITUSEMEOLVIDO = true; url_direccionar = Define.URL_BASE + "cuenta/login" toastr.warning("Hola " + data.data[0].usuarioNombres + ", se te enviará la nueva contraseña al correo: " + data.data[0].usuarioEmail); redireccionar(url_direccionar); }else{ toastr.error("No existe una cuenta asociada a ese nombre de usuario."); } }); }else{ toastr.error("La solicitud ya fue enviada, revisa tu correo."); }; }); $("#login").delegate('#ingresoLogin', 'click', function () {//validar usuario var url_ajax = URL + Define.URL_LOGIN; //le decimos a qué url tiene que mandar la información var usuario_a_buscar = $("#name").val(); var passwd_user = $("#pswd").val(); var recordame_ve = false; if($('#recuerdame').is(':checked')){ recordame_ve = true; } alert(recordame_ve); var data = { action: 'ingresar', username: usuario_a_buscar, password_user: passwd_user, recuerdame: recordame_ve }; if(usuario_a_buscar == '' || passwd_user == ''){ toastr.error("Username y/o contraseña vacíos, por favor digite un valor"); }else{ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; });
setTimeout(function(){ location.href=url_direccionar; }, 5000); //tiempo expresado en milisegundos }
identifier_body
socialcoffee.js
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //var MODAL = $("#modalProducto"); var URL = Define.URL_BASE; window.onload=function(){ //toastr.error("Ingresaaaaaaaaa"); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'validar' }; httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; function redireccionar(url_direccionar){ setTimeout(function(){ location.href=url_direccionar; }, 5000); //tiempo expresado en milisegundos } $("#olvide").delegate('#semeolvido', 'click', function () {//buscar pedido en bd var usuario_a_buscar = $("#username").val(); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'semeolvido', username: usuario_a_buscar }; if(!SOLICITUSEMEOLVIDO){ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.itemsCount != 0){
toastr.error("No existe una cuenta asociada a ese nombre de usuario."); } }); }else{ toastr.error("La solicitud ya fue enviada, revisa tu correo."); }; }); $("#login").delegate('#ingresoLogin', 'click', function () {//validar usuario var url_ajax = URL + Define.URL_LOGIN; //le decimos a qué url tiene que mandar la información var usuario_a_buscar = $("#name").val(); var passwd_user = $("#pswd").val(); var recordame_ve = false; if($('#recuerdame').is(':checked')){ recordame_ve = true; } alert(recordame_ve); var data = { action: 'ingresar', username: usuario_a_buscar, password_user: passwd_user, recuerdame: recordame_ve }; if(usuario_a_buscar == '' || passwd_user == ''){ toastr.error("Username y/o contraseña vacíos, por favor digite un valor"); }else{ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; });
SOLICITUSEMEOLVIDO = true; url_direccionar = Define.URL_BASE + "cuenta/login" toastr.warning("Hola " + data.data[0].usuarioNombres + ", se te enviará la nueva contraseña al correo: " + data.data[0].usuarioEmail); redireccionar(url_direccionar); }else{
conditional_block