text
stringlengths
2
99k
meta
dict
/* * /MathJax/extensions/TeX/mathchoice.js * * Copyright (c) 2009-2015 The MathJax Consortium * * 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. */ MathJax.Hub.Register.StartupHook("TeX Jax Ready",function(){var c="2.5.2";var a=MathJax.ElementJax.mml;var d=MathJax.InputJax.TeX;var b=d.Definitions;b.Add({macros:{mathchoice:"MathChoice"}},null,true);d.Parse.Augment({MathChoice:function(f){var i=this.ParseArg(f),e=this.ParseArg(f),g=this.ParseArg(f),h=this.ParseArg(f);this.Push(a.TeXmathchoice(i,e,g,h))}});a.TeXmathchoice=a.mbase.Subclass({type:"TeXmathchoice",notParent:true,choice:function(){if(this.selection!=null){return this.selection}if(this.choosing){return 2}this.choosing=true;var f=0,e=this.getValues("displaystyle","scriptlevel");if(e.scriptlevel>0){f=Math.min(3,e.scriptlevel+1)}else{f=(e.displaystyle?0:1)}var g=this.inherit;while(g&&g.type!=="math"){g=g.inherit}if(g){this.selection=f}this.choosing=false;return f},selected:function(){return this.data[this.choice()]},setTeXclass:function(e){return this.selected().setTeXclass(e)},isSpacelike:function(){return this.selected().isSpacelike()},isEmbellished:function(){return this.selected().isEmbellished()},Core:function(){return this.selected()},CoreMO:function(){return this.selected().CoreMO()},toHTML:function(e){e=this.HTMLcreateSpan(e);e.bbox=this.Core().toHTML(e).bbox;if(e.firstChild&&e.firstChild.style.marginLeft){e.style.marginLeft=e.firstChild.style.marginLeft;e.firstChild.style.marginLeft=""}return e},toSVG:function(){var e=this.Core().toSVG();this.SVGsaveData(e);return e},toCommonHTML:function(e){e=this.CHTMLcreateSpan(e);this.CHTMLhandleStyle(e);this.CHTMLhandleColor(e);this.CHTMLaddChild(e,this.choice(),{});return e}});MathJax.Hub.Startup.signal.Post("TeX mathchoice Ready")});MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/mathchoice.js");
{ "pile_set_name": "Github" }
// Copyright (C) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. package codegen import "fmt" func assertTypesEqual(x, y Type) { if x != y { panic(fmt.Errorf("Arguments have differing types: %v and %v", x.TypeName(), y.TypeName())) } } func assertVectorsSameLength(x, y Type) { vecX, ok := x.(Vector) if !ok { return } vecY, ok := y.(Vector) if !ok { return } if vecX.Count != vecY.Count { panic(fmt.Errorf("Expected vectors of same length, got %v and %v", x.TypeName(), y.TypeName())) } }
{ "pile_set_name": "Github" }
using UnityEngine; namespace Lockstep { public class LSAnimator : LSAnimatorBase { //Sphagetti :D [SerializeField] protected string _idling = "idling"; [SerializeField] protected string _moving = "moving"; [SerializeField] protected string _engaging = "engaging"; [SerializeField] protected string _specialEngaging = "specialEngaging"; [SerializeField] protected string _dying = "dying"; [Space(10f), SerializeField] protected string _fire = "fire"; [SerializeField] protected string _specialFire = "specialFire"; [SerializeField] protected string _specialAttack = "specialAttack"; [SerializeField] protected string _extra = "extra"; private AnimationClip idlingClip; private AnimationClip movingClip; private AnimationClip engagingClip; private AnimationClip dyingClip; private AnimationClip specialEngagingClip; private AnimationClip fireClip; private AnimationClip specialFireClip; private AnimationClip specialAttackClip; private AnimationClip extraClip; private Animation animator; protected override void OnSetup() { } protected override void OnInitialize() { animator = GetComponent<Animation>(); if (animator == null) animator = this.GetComponentInChildren<Animation>(); if (CanAnimate = (animator != null)) { //States idlingClip = animator.GetClip(_idling); movingClip = animator.GetClip(_moving); engagingClip = animator.GetClip(_engaging); dyingClip = animator.GetClip(_dying); specialEngagingClip = animator.GetClip(_specialEngaging); //Impulses fireClip = animator.GetClip(_fire); specialFireClip = animator.GetClip(_specialFire); specialAttackClip = animator.GetClip(_specialAttack); extraClip = animator.GetClip(_extra); } Play(AnimState.Idling); } const float fadeLength = .5f; protected override void OnApplyImpulse(AnimImpulse animImpulse, double speed) { if (CanAnimate) { AnimationClip clip = GetImpulseClip(animImpulse); if (clip.IsNotNull()) { animator.Play(clip.name, PlayMode.StopSameLayer); } } } protected override void OnPlay(AnimState state, double speed) { if (CanAnimate) { AnimationClip clip = GetStateClip(state); if (clip.IsNotNull()) { //animator.Blend(clip.name,.8f,fadeLength); animator.CrossFade(clip.name, fadeLength); } } } private AnimationClip GetStateClip(AnimState state) { switch (state) { case AnimState.Moving: return movingClip; case AnimState.Idling: return idlingClip; case AnimState.Engaging: return engagingClip; case AnimState.Dying: return dyingClip; case AnimState.SpecialEngaging: return this.specialEngagingClip; } return idlingClip; } private AnimationClip GetImpulseClip(AnimImpulse impulse) { switch (impulse) { case AnimImpulse.Fire: return fireClip; case AnimImpulse.SpecialFire: return specialFireClip; case AnimImpulse.SpecialAttack: return specialAttackClip; case AnimImpulse.Extra: return extraClip; } return idlingClip; } } }
{ "pile_set_name": "Github" }
/** * Copyright (c) 2013 by 苏州科大国创信息技术有限公司. */ package com.github.diamond.client; import java.io.IOException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.github.diamond.client.event.ConfigurationEvent; import com.github.diamond.client.event.ConfigurationListener; /** * Create on @2013-8-26 @上午10:00:54 * @author bsli@ustcinfo.com */ public class PropertiesConfigurationFactoryBeanTest { public static void main(String[] args) throws IOException { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml"); PropertiesConfiguration configuration = PropertiesConfigurationFactoryBean.getPropertiesConfiguration(); configuration.addConfigurationListener(new ConfigurationListener() { @Override public void configurationChanged(ConfigurationEvent event) { //监听配置参数变化,监听不到? System.out.println(event.getType().name() + " " + event.getPropertyName() + " " + event.getPropertyValue()); } }); System.in.read(); } }
{ "pile_set_name": "Github" }
@import "../../css/colors.css"; .green-flag { width: 2rem; height: 2rem; padding: 0.375rem; border-radius: 0.25rem; user-select: none; user-drag: none; cursor: pointer; } .green-flag:hover { background-color: $motion-light-transparent; } .green-flag.is-active { background-color: $motion-transparent; }
{ "pile_set_name": "Github" }
import functools import importlib import os import re import signal import sys import traceback import matplotlib from matplotlib import backend_tools, cbook from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase, cursors, ToolContainerBase, StatusbarBase, MouseButton) import matplotlib.backends.qt_editor.figureoptions as figureoptions from matplotlib.backends.qt_editor._formsubplottool import UiSubplotTool from . import qt_compat from .qt_compat import ( QtCore, QtGui, QtWidgets, __version__, QT_API, _devicePixelRatioF, _isdeleted, _setDevicePixelRatioF, ) backend_version = __version__ # SPECIAL_KEYS are keys that do *not* return their unicode name # instead they have manually specified names SPECIAL_KEYS = {QtCore.Qt.Key_Control: 'control', QtCore.Qt.Key_Shift: 'shift', QtCore.Qt.Key_Alt: 'alt', QtCore.Qt.Key_Meta: 'super', QtCore.Qt.Key_Return: 'enter', QtCore.Qt.Key_Left: 'left', QtCore.Qt.Key_Up: 'up', QtCore.Qt.Key_Right: 'right', QtCore.Qt.Key_Down: 'down', QtCore.Qt.Key_Escape: 'escape', QtCore.Qt.Key_F1: 'f1', QtCore.Qt.Key_F2: 'f2', QtCore.Qt.Key_F3: 'f3', QtCore.Qt.Key_F4: 'f4', QtCore.Qt.Key_F5: 'f5', QtCore.Qt.Key_F6: 'f6', QtCore.Qt.Key_F7: 'f7', QtCore.Qt.Key_F8: 'f8', QtCore.Qt.Key_F9: 'f9', QtCore.Qt.Key_F10: 'f10', QtCore.Qt.Key_F11: 'f11', QtCore.Qt.Key_F12: 'f12', QtCore.Qt.Key_Home: 'home', QtCore.Qt.Key_End: 'end', QtCore.Qt.Key_PageUp: 'pageup', QtCore.Qt.Key_PageDown: 'pagedown', QtCore.Qt.Key_Tab: 'tab', QtCore.Qt.Key_Backspace: 'backspace', QtCore.Qt.Key_Enter: 'enter', QtCore.Qt.Key_Insert: 'insert', QtCore.Qt.Key_Delete: 'delete', QtCore.Qt.Key_Pause: 'pause', QtCore.Qt.Key_SysReq: 'sysreq', QtCore.Qt.Key_Clear: 'clear', } if sys.platform == 'darwin': # in OSX, the control and super (aka cmd/apple) keys are switched, so # switch them back. SPECIAL_KEYS.update({QtCore.Qt.Key_Control: 'cmd', # cmd/apple key QtCore.Qt.Key_Meta: 'control', }) # Define which modifier keys are collected on keyboard events. # Elements are (Modifier Flag, Qt Key) tuples. # Order determines the modifier order (ctrl+alt+...) reported by Matplotlib. _MODIFIER_KEYS = [ (QtCore.Qt.ShiftModifier, QtCore.Qt.Key_Shift), (QtCore.Qt.ControlModifier, QtCore.Qt.Key_Control), (QtCore.Qt.AltModifier, QtCore.Qt.Key_Alt), (QtCore.Qt.MetaModifier, QtCore.Qt.Key_Meta), ] cursord = { cursors.MOVE: QtCore.Qt.SizeAllCursor, cursors.HAND: QtCore.Qt.PointingHandCursor, cursors.POINTER: QtCore.Qt.ArrowCursor, cursors.SELECT_REGION: QtCore.Qt.CrossCursor, cursors.WAIT: QtCore.Qt.WaitCursor, } SUPER = 0 # Deprecated. ALT = 1 # Deprecated. CTRL = 2 # Deprecated. SHIFT = 3 # Deprecated. MODIFIER_KEYS = [ # Deprecated. (SPECIAL_KEYS[key], mod, key) for mod, key in _MODIFIER_KEYS] # make place holder qApp = None def _create_qApp(): """ Only one qApp can exist at a time, so check before creating one. """ global qApp if qApp is None: app = QtWidgets.QApplication.instance() if app is None: # check for DISPLAY env variable on X11 build of Qt if QtCore.qVersion() >= "5.": try: importlib.import_module( # i.e. PyQt5.QtX11Extras or PySide2.QtX11Extras. f"{QtWidgets.__package__}.QtX11Extras") is_x11_build = True except ImportError: is_x11_build = False else: is_x11_build = hasattr(QtGui, "QX11Info") if is_x11_build: display = os.environ.get('DISPLAY') if display is None or not re.search(r':\d', display): raise RuntimeError('Invalid DISPLAY variable') try: QtWidgets.QApplication.setAttribute( QtCore.Qt.AA_EnableHighDpiScaling) except AttributeError: # Attribute only exists for Qt>=5.6. pass qApp = QtWidgets.QApplication(["matplotlib"]) qApp.lastWindowClosed.connect(qApp.quit) cbook._setup_new_guiapp() else: qApp = app try: qApp.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) except AttributeError: pass def _allow_super_init(__init__): """ Decorator for ``__init__`` to allow ``super().__init__`` on PyQt4/PySide2. """ if QT_API == "PyQt5": return __init__ else: # To work around lack of cooperative inheritance in PyQt4, PySide, # and PySide2, when calling FigureCanvasQT.__init__, we temporarily # patch QWidget.__init__ by a cooperative version, that first calls # QWidget.__init__ with no additional arguments, and then finds the # next class in the MRO with an __init__ that does support cooperative # inheritance (i.e., not defined by the PyQt4, PySide, PySide2, sip # or Shiboken packages), and manually call its `__init__`, once again # passing the additional arguments. qwidget_init = QtWidgets.QWidget.__init__ def cooperative_qwidget_init(self, *args, **kwargs): qwidget_init(self) mro = type(self).__mro__ next_coop_init = next( cls for cls in mro[mro.index(QtWidgets.QWidget) + 1:] if cls.__module__.split(".")[0] not in [ "PyQt4", "sip", "PySide", "PySide2", "Shiboken"]) next_coop_init.__init__(self, *args, **kwargs) @functools.wraps(__init__) def wrapper(self, *args, **kwargs): with cbook._setattr_cm(QtWidgets.QWidget, __init__=cooperative_qwidget_init): __init__(self, *args, **kwargs) return wrapper class TimerQT(TimerBase): """Subclass of `.TimerBase` using QTimer events.""" def __init__(self, *args, **kwargs): # Create a new timer and connect the timeout() signal to the # _on_timer method. self._timer = QtCore.QTimer() self._timer.timeout.connect(self._on_timer) super().__init__(*args, **kwargs) def __del__(self): # The check for deletedness is needed to avoid an error at animation # shutdown with PySide2. if not _isdeleted(self._timer): self._timer_stop() def _timer_set_single_shot(self): self._timer.setSingleShot(self._single) def _timer_set_interval(self): self._timer.setInterval(self._interval) def _timer_start(self): self._timer.start() def _timer_stop(self): self._timer.stop() class FigureCanvasQT(QtWidgets.QWidget, FigureCanvasBase): required_interactive_framework = "qt5" _timer_cls = TimerQT # map Qt button codes to MouseEvent's ones: buttond = {QtCore.Qt.LeftButton: MouseButton.LEFT, QtCore.Qt.MidButton: MouseButton.MIDDLE, QtCore.Qt.RightButton: MouseButton.RIGHT, QtCore.Qt.XButton1: MouseButton.BACK, QtCore.Qt.XButton2: MouseButton.FORWARD, } @_allow_super_init def __init__(self, figure): _create_qApp() super().__init__(figure=figure) # We don't want to scale up the figure DPI more than once. # Note, we don't handle a signal for changing DPI yet. figure._original_dpi = figure.dpi self._update_figure_dpi() # In cases with mixed resolution displays, we need to be careful if the # dpi_ratio changes - in this case we need to resize the canvas # accordingly. We could watch for screenChanged events from Qt, but # the issue is that we can't guarantee this will be emitted *before* # the first paintEvent for the canvas, so instead we keep track of the # dpi_ratio value here and in paintEvent we resize the canvas if # needed. self._dpi_ratio_prev = None self._draw_pending = False self._is_drawing = False self._draw_rect_callback = lambda painter: None self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent) self.setMouseTracking(True) self.resize(*self.get_width_height()) palette = QtGui.QPalette(QtCore.Qt.white) self.setPalette(palette) def _update_figure_dpi(self): dpi = self._dpi_ratio * self.figure._original_dpi self.figure._set_dpi(dpi, forward=False) @property def _dpi_ratio(self): return _devicePixelRatioF(self) def _update_dpi(self): # As described in __init__ above, we need to be careful in cases with # mixed resolution displays if dpi_ratio is changing between painting # events. # Return whether we triggered a resizeEvent (and thus a paintEvent) # from within this function. if self._dpi_ratio != self._dpi_ratio_prev: # We need to update the figure DPI. self._update_figure_dpi() self._dpi_ratio_prev = self._dpi_ratio # The easiest way to resize the canvas is to emit a resizeEvent # since we implement all the logic for resizing the canvas for # that event. event = QtGui.QResizeEvent(self.size(), self.size()) self.resizeEvent(event) # resizeEvent triggers a paintEvent itself, so we exit this one # (after making sure that the event is immediately handled). return True return False def get_width_height(self): w, h = FigureCanvasBase.get_width_height(self) return int(w / self._dpi_ratio), int(h / self._dpi_ratio) def enterEvent(self, event): try: x, y = self.mouseEventCoords(event.pos()) except AttributeError: # the event from PyQt4 does not include the position x = y = None FigureCanvasBase.enter_notify_event(self, guiEvent=event, xy=(x, y)) def leaveEvent(self, event): QtWidgets.QApplication.restoreOverrideCursor() FigureCanvasBase.leave_notify_event(self, guiEvent=event) def mouseEventCoords(self, pos): """ Calculate mouse coordinates in physical pixels. Qt5 use logical pixels, but the figure is scaled to physical pixels for rendering. Transform to physical pixels so that all of the down-stream transforms work as expected. Also, the origin is different and needs to be corrected. """ dpi_ratio = self._dpi_ratio x = pos.x() # flip y so y=0 is bottom of canvas y = self.figure.bbox.height / dpi_ratio - pos.y() return x * dpi_ratio, y * dpi_ratio def mousePressEvent(self, event): x, y = self.mouseEventCoords(event.pos()) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_press_event(self, x, y, button, guiEvent=event) def mouseDoubleClickEvent(self, event): x, y = self.mouseEventCoords(event.pos()) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_press_event(self, x, y, button, dblclick=True, guiEvent=event) def mouseMoveEvent(self, event): x, y = self.mouseEventCoords(event) FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) def mouseReleaseEvent(self, event): x, y = self.mouseEventCoords(event) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_release_event(self, x, y, button, guiEvent=event) if QtCore.qVersion() >= "5.": def wheelEvent(self, event): x, y = self.mouseEventCoords(event) # from QWheelEvent::delta doc if event.pixelDelta().x() == 0 and event.pixelDelta().y() == 0: steps = event.angleDelta().y() / 120 else: steps = event.pixelDelta().y() if steps: FigureCanvasBase.scroll_event( self, x, y, steps, guiEvent=event) else: def wheelEvent(self, event): x = event.x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y() # from QWheelEvent::delta doc steps = event.delta() / 120 if event.orientation() == QtCore.Qt.Vertical: FigureCanvasBase.scroll_event( self, x, y, steps, guiEvent=event) def keyPressEvent(self, event): key = self._get_key(event) if key is not None: FigureCanvasBase.key_press_event(self, key, guiEvent=event) def keyReleaseEvent(self, event): key = self._get_key(event) if key is not None: FigureCanvasBase.key_release_event(self, key, guiEvent=event) def resizeEvent(self, event): # _dpi_ratio_prev will be set the first time the canvas is painted, and # the rendered buffer is useless before anyways. if self._dpi_ratio_prev is None: return w = event.size().width() * self._dpi_ratio h = event.size().height() * self._dpi_ratio dpival = self.figure.dpi winch = w / dpival hinch = h / dpival self.figure.set_size_inches(winch, hinch, forward=False) # pass back into Qt to let it finish QtWidgets.QWidget.resizeEvent(self, event) # emit our resize events FigureCanvasBase.resize_event(self) def sizeHint(self): w, h = self.get_width_height() return QtCore.QSize(w, h) def minumumSizeHint(self): return QtCore.QSize(10, 10) def _get_key(self, event): event_key = event.key() event_mods = int(event.modifiers()) # actually a bitmask # get names of the pressed modifier keys # 'control' is named 'control' when a standalone key, but 'ctrl' when a # modifier # bit twiddling to pick out modifier keys from event_mods bitmask, # if event_key is a MODIFIER, it should not be duplicated in mods mods = [SPECIAL_KEYS[key].replace('control', 'ctrl') for mod, key in _MODIFIER_KEYS if event_key != key and event_mods & mod] try: # for certain keys (enter, left, backspace, etc) use a word for the # key, rather than unicode key = SPECIAL_KEYS[event_key] except KeyError: # unicode defines code points up to 0x10ffff (sys.maxunicode) # QT will use Key_Codes larger than that for keyboard keys that are # are not unicode characters (like multimedia keys) # skip these # if you really want them, you should add them to SPECIAL_KEYS if event_key > sys.maxunicode: return None key = chr(event_key) # qt delivers capitalized letters. fix capitalization # note that capslock is ignored if 'shift' in mods: mods.remove('shift') else: key = key.lower() return '+'.join(mods + [key]) def flush_events(self): # docstring inherited qApp.processEvents() def start_event_loop(self, timeout=0): # docstring inherited if hasattr(self, "_event_loop") and self._event_loop.isRunning(): raise RuntimeError("Event loop already running") self._event_loop = event_loop = QtCore.QEventLoop() if timeout > 0: timer = QtCore.QTimer.singleShot(int(timeout * 1000), event_loop.quit) event_loop.exec_() def stop_event_loop(self, event=None): # docstring inherited if hasattr(self, "_event_loop"): self._event_loop.quit() def draw(self): """Render the figure, and queue a request for a Qt draw.""" # The renderer draw is done here; delaying causes problems with code # that uses the result of the draw() to update plot elements. if self._is_drawing: return with cbook._setattr_cm(self, _is_drawing=True): super().draw() self.update() def draw_idle(self): """Queue redraw of the Agg buffer and request Qt paintEvent.""" # The Agg draw needs to be handled by the same thread Matplotlib # modifies the scene graph from. Post Agg draw request to the # current event loop in order to ensure thread affinity and to # accumulate multiple draw requests from event handling. # TODO: queued signal connection might be safer than singleShot if not (getattr(self, '_draw_pending', False) or getattr(self, '_is_drawing', False)): self._draw_pending = True QtCore.QTimer.singleShot(0, self._draw_idle) def blit(self, bbox=None): # docstring inherited if bbox is None and self.figure: bbox = self.figure.bbox # Blit the entire canvas if bbox is None. # repaint uses logical pixels, not physical pixels like the renderer. l, b, w, h = [int(pt / self._dpi_ratio) for pt in bbox.bounds] t = b + h self.repaint(l, self.rect().height() - t, w, h) def _draw_idle(self): with self._idle_draw_cntx(): if not self._draw_pending: return self._draw_pending = False if self.height() < 0 or self.width() < 0: return try: self.draw() except Exception: # Uncaught exceptions are fatal for PyQt5, so catch them. traceback.print_exc() def drawRectangle(self, rect): # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs # to be called at the end of paintEvent. if rect is not None: x0, y0, w, h = [int(pt / self._dpi_ratio) for pt in rect] x1 = x0 + w y1 = y0 + h def _draw_rect_callback(painter): pen = QtGui.QPen(QtCore.Qt.black, 1 / self._dpi_ratio) pen.setDashPattern([3, 3]) for color, offset in [ (QtCore.Qt.black, 0), (QtCore.Qt.white, 3)]: pen.setDashOffset(offset) pen.setColor(color) painter.setPen(pen) # Draw the lines from x0, y0 towards x1, y1 so that the # dashes don't "jump" when moving the zoom box. painter.drawLine(x0, y0, x0, y1) painter.drawLine(x0, y0, x1, y0) painter.drawLine(x0, y1, x1, y1) painter.drawLine(x1, y0, x1, y1) else: def _draw_rect_callback(painter): return self._draw_rect_callback = _draw_rect_callback self.update() class MainWindow(QtWidgets.QMainWindow): closing = QtCore.Signal() def closeEvent(self, event): self.closing.emit() super().closeEvent(event) class FigureManagerQT(FigureManagerBase): """ Attributes ---------- canvas : `FigureCanvas` The FigureCanvas instance num : int or str The Figure number toolbar : qt.QToolBar The qt.QToolBar window : qt.QMainWindow The qt.QMainWindow """ def __init__(self, canvas, num): super().__init__(canvas, num) self.window = MainWindow() self.window.closing.connect(canvas.close_event) self.window.closing.connect(self._widgetclosed) self.window.setWindowTitle("Figure %d" % num) image = str(cbook._get_data_path('images/matplotlib.svg')) self.window.setWindowIcon(QtGui.QIcon(image)) self.window._destroying = False self.toolbar = self._get_toolbar(self.canvas, self.window) if self.toolmanager: backend_tools.add_tools_to_manager(self.toolmanager) if self.toolbar: backend_tools.add_tools_to_container(self.toolbar) if self.toolbar: self.window.addToolBar(self.toolbar) tbs_height = self.toolbar.sizeHint().height() else: tbs_height = 0 # resize the main window so it will display the canvas with the # requested size: cs = canvas.sizeHint() cs_height = cs.height() height = cs_height + tbs_height self.window.resize(cs.width(), height) self.window.setCentralWidget(self.canvas) if matplotlib.is_interactive(): self.window.show() self.canvas.draw_idle() # Give the keyboard focus to the figure instead of the manager: # StrongFocus accepts both tab and click to focus and will enable the # canvas to process event without clicking. # https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus) self.canvas.setFocus() self.window.raise_() def full_screen_toggle(self): if self.window.isFullScreen(): self.window.showNormal() else: self.window.showFullScreen() def _widgetclosed(self): if self.window._destroying: return self.window._destroying = True try: Gcf.destroy(self) except AttributeError: pass # It seems that when the python session is killed, # Gcf can get destroyed before the Gcf.destroy # line is run, leading to a useless AttributeError. def _get_toolbar(self, canvas, parent): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2QT(canvas, parent, True) elif matplotlib.rcParams['toolbar'] == 'toolmanager': toolbar = ToolbarQt(self.toolmanager, self.window) else: toolbar = None return toolbar def resize(self, width, height): # these are Qt methods so they return sizes in 'virtual' pixels # so we do not need to worry about dpi scaling here. extra_width = self.window.width() - self.canvas.width() extra_height = self.window.height() - self.canvas.height() self.canvas.resize(width, height) self.window.resize(width + extra_width, height + extra_height) def show(self): self.window.show() if matplotlib.rcParams['figure.raise_window']: self.window.activateWindow() self.window.raise_() def destroy(self, *args): # check for qApp first, as PySide deletes it in its atexit handler if QtWidgets.QApplication.instance() is None: return if self.window._destroying: return self.window._destroying = True if self.toolbar: self.toolbar.destroy() self.window.close() def get_window_title(self): return self.window.windowTitle() def set_window_title(self, title): self.window.setWindowTitle(title) class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar): message = QtCore.Signal(str) toolitems = [*NavigationToolbar2.toolitems] toolitems.insert( # Add 'customize' action after 'subplots' [name for name, *_ in toolitems].index("Subplots") + 1, ("Customize", "Edit axis, curve and image parameters", "qt4_editor_options", "edit_parameters")) def __init__(self, canvas, parent, coordinates=True): """coordinates: should we show the coordinates on the right?""" QtWidgets.QToolBar.__init__(self, parent) self.setAllowedAreas( QtCore.Qt.TopToolBarArea | QtCore.Qt.BottomToolBarArea) self.coordinates = coordinates self._actions = {} # mapping of toolitem method names to QActions. for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.addSeparator() else: a = self.addAction(self._icon(image_file + '.png'), text, getattr(self, callback)) self._actions[callback] = a if callback in ['zoom', 'pan']: a.setCheckable(True) if tooltip_text is not None: a.setToolTip(tooltip_text) # Add the (x, y) location widget at the right side of the toolbar # The stretch factor is 1 which means any resizing of the toolbar # will resize this label instead of the buttons. if self.coordinates: self.locLabel = QtWidgets.QLabel("", self) self.locLabel.setAlignment( QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter) self.locLabel.setSizePolicy( QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Ignored)) labelAction = self.addWidget(self.locLabel) labelAction.setVisible(True) NavigationToolbar2.__init__(self, canvas) @cbook.deprecated("3.3", alternative="self.canvas.parent()") @property def parent(self): return self.canvas.parent() @cbook.deprecated("3.3", alternative="self.canvas.setParent()") @parent.setter def parent(self, value): pass @cbook.deprecated( "3.3", alternative="os.path.join(mpl.get_data_path(), 'images')") @property def basedir(self): return str(cbook._get_data_path('images')) def _icon(self, name): """ Construct a `.QIcon` from an image file *name*, including the extension and relative to Matplotlib's "images" data directory. """ if QtCore.qVersion() >= '5.': name = name.replace('.png', '_large.png') pm = QtGui.QPixmap(str(cbook._get_data_path('images', name))) _setDevicePixelRatioF(pm, _devicePixelRatioF(self)) if self.palette().color(self.backgroundRole()).value() < 128: icon_color = self.palette().color(self.foregroundRole()) mask = pm.createMaskFromColor(QtGui.QColor('black'), QtCore.Qt.MaskOutColor) pm.fill(icon_color) pm.setMask(mask) return QtGui.QIcon(pm) def edit_parameters(self): axes = self.canvas.figure.get_axes() if not axes: QtWidgets.QMessageBox.warning( self.canvas.parent(), "Error", "There are no axes to edit.") return elif len(axes) == 1: ax, = axes else: titles = [ ax.get_label() or ax.get_title() or " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or f"<anonymous {type(ax).__name__}>" for ax in axes] duplicate_titles = [ title for title in titles if titles.count(title) > 1] for i, ax in enumerate(axes): if titles[i] in duplicate_titles: titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles. item, ok = QtWidgets.QInputDialog.getItem( self.canvas.parent(), 'Customize', 'Select axes:', titles, 0, False) if not ok: return ax = axes[titles.index(item)] figureoptions.figure_edit(ax, self) def _update_buttons_checked(self): # sync button checkstates to match active mode if 'pan' in self._actions: self._actions['pan'].setChecked(self.mode.name == 'PAN') if 'zoom' in self._actions: self._actions['zoom'].setChecked(self.mode.name == 'ZOOM') def pan(self, *args): super().pan(*args) self._update_buttons_checked() def zoom(self, *args): super().zoom(*args) self._update_buttons_checked() def set_message(self, s): self.message.emit(s) if self.coordinates: self.locLabel.setText(s) def set_cursor(self, cursor): self.canvas.setCursor(cursord[cursor]) def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] self.canvas.drawRectangle(rect) def remove_rubberband(self): self.canvas.drawRectangle(None) def configure_subplots(self): image = str(cbook._get_data_path('images/matplotlib.png')) dia = SubplotToolQt(self.canvas.figure, self.canvas.parent()) dia.setWindowIcon(QtGui.QIcon(image)) dia.exec_() def save_figure(self, *args): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = sorted(filetypes.items()) default_filetype = self.canvas.get_default_filetype() startpath = os.path.expanduser( matplotlib.rcParams['savefig.directory']) start = os.path.join(startpath, self.canvas.get_default_filename()) filters = [] selectedFilter = None for name, exts in sorted_filetypes: exts_list = " ".join(['*.%s' % ext for ext in exts]) filter = '%s (%s)' % (name, exts_list) if default_filetype in exts: selectedFilter = filter filters.append(filter) filters = ';;'.join(filters) fname, filter = qt_compat._getSaveFileName( self.canvas.parent(), "Choose a filename to save to", start, filters, selectedFilter) if fname: # Save dir for next time, unless empty str (i.e., use cwd). if startpath != "": matplotlib.rcParams['savefig.directory'] = ( os.path.dirname(fname)) try: self.canvas.figure.savefig(fname) except Exception as e: QtWidgets.QMessageBox.critical( self, "Error saving file", str(e), QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton) def set_history_buttons(self): can_backward = self._nav_stack._pos > 0 can_forward = self._nav_stack._pos < len(self._nav_stack._elements) - 1 if 'back' in self._actions: self._actions['back'].setEnabled(can_backward) if 'forward' in self._actions: self._actions['forward'].setEnabled(can_forward) class SubplotToolQt(UiSubplotTool): def __init__(self, targetfig, parent): super().__init__(None) self._figure = targetfig for lower, higher in [("bottom", "top"), ("left", "right")]: self._widgets[lower].valueChanged.connect( lambda val: self._widgets[higher].setMinimum(val + .001)) self._widgets[higher].valueChanged.connect( lambda val: self._widgets[lower].setMaximum(val - .001)) self._attrs = ["top", "bottom", "left", "right", "hspace", "wspace"] self._defaults = {attr: vars(self._figure.subplotpars)[attr] for attr in self._attrs} # Set values after setting the range callbacks, but before setting up # the redraw callbacks. self._reset() for attr in self._attrs: self._widgets[attr].valueChanged.connect(self._on_value_changed) for action, method in [("Export values", self._export_values), ("Tight layout", self._tight_layout), ("Reset", self._reset), ("Close", self.close)]: self._widgets[action].clicked.connect(method) def _export_values(self): # Explicitly round to 3 decimals (which is also the spinbox precision) # to avoid numbers of the form 0.100...001. dialog = QtWidgets.QDialog() layout = QtWidgets.QVBoxLayout() dialog.setLayout(layout) text = QtWidgets.QPlainTextEdit() text.setReadOnly(True) layout.addWidget(text) text.setPlainText( ",\n".join("{}={:.3}".format(attr, self._widgets[attr].value()) for attr in self._attrs)) # Adjust the height of the text widget to fit the whole text, plus # some padding. size = text.maximumSize() size.setHeight( QtGui.QFontMetrics(text.document().defaultFont()) .size(0, text.toPlainText()).height() + 20) text.setMaximumSize(size) dialog.exec_() def _on_value_changed(self): self._figure.subplots_adjust(**{attr: self._widgets[attr].value() for attr in self._attrs}) self._figure.canvas.draw_idle() def _tight_layout(self): self._figure.tight_layout() for attr in self._attrs: widget = self._widgets[attr] widget.blockSignals(True) widget.setValue(vars(self._figure.subplotpars)[attr]) widget.blockSignals(False) self._figure.canvas.draw_idle() def _reset(self): for attr, value in self._defaults.items(): self._widgets[attr].setValue(value) class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar): def __init__(self, toolmanager, parent): ToolContainerBase.__init__(self, toolmanager) QtWidgets.QToolBar.__init__(self, parent) self.setAllowedAreas( QtCore.Qt.TopToolBarArea | QtCore.Qt.BottomToolBarArea) message_label = QtWidgets.QLabel("") message_label.setAlignment( QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter) message_label.setSizePolicy( QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Ignored)) self._message_action = self.addWidget(message_label) self._toolitems = {} self._groups = {} def add_toolitem( self, name, group, position, image_file, description, toggle): button = QtWidgets.QToolButton(self) if image_file: button.setIcon(NavigationToolbar2QT._icon(self, image_file)) button.setText(name) if description: button.setToolTip(description) def handler(): self.trigger_tool(name) if toggle: button.setCheckable(True) button.toggled.connect(handler) else: button.clicked.connect(handler) self._toolitems.setdefault(name, []) self._add_to_group(group, name, button, position) self._toolitems[name].append((button, handler)) def _add_to_group(self, group, name, button, position): gr = self._groups.get(group, []) if not gr: sep = self.insertSeparator(self._message_action) gr.append(sep) before = gr[position] widget = self.insertWidget(before, button) gr.insert(position, widget) self._groups[group] = gr def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for button, handler in self._toolitems[name]: button.toggled.disconnect(handler) button.setChecked(toggled) button.toggled.connect(handler) def remove_toolitem(self, name): for button, handler in self._toolitems[name]: button.setParent(None) del self._toolitems[name] def set_message(self, s): self.widgetForAction(self._message_action).setText(s) @cbook.deprecated("3.3") class StatusbarQt(StatusbarBase, QtWidgets.QLabel): def __init__(self, window, *args, **kwargs): StatusbarBase.__init__(self, *args, **kwargs) QtWidgets.QLabel.__init__(self) window.statusBar().addWidget(self) def set_message(self, s): self.setText(s) class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase): def trigger(self, *args): NavigationToolbar2QT.configure_subplots( self._make_classic_style_pseudo_toolbar()) class SaveFigureQt(backend_tools.SaveFigureBase): def trigger(self, *args): NavigationToolbar2QT.save_figure( self._make_classic_style_pseudo_toolbar()) class SetCursorQt(backend_tools.SetCursorBase): def set_cursor(self, cursor): NavigationToolbar2QT.set_cursor( self._make_classic_style_pseudo_toolbar(), cursor) class RubberbandQt(backend_tools.RubberbandBase): def draw_rubberband(self, x0, y0, x1, y1): NavigationToolbar2QT.draw_rubberband( self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) def remove_rubberband(self): NavigationToolbar2QT.remove_rubberband( self._make_classic_style_pseudo_toolbar()) class HelpQt(backend_tools.ToolHelpBase): def trigger(self, *args): QtWidgets.QMessageBox.information(None, "Help", self._get_help_html()) class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase): def trigger(self, *args, **kwargs): pixmap = self.canvas.grab() qApp.clipboard().setPixmap(pixmap) backend_tools.ToolSaveFigure = SaveFigureQt backend_tools.ToolConfigureSubplots = ConfigureSubplotsQt backend_tools.ToolSetCursor = SetCursorQt backend_tools.ToolRubberband = RubberbandQt backend_tools.ToolHelp = HelpQt backend_tools.ToolCopyToClipboard = ToolCopyToClipboardQT @_Backend.export class _BackendQT5(_Backend): FigureCanvas = FigureCanvasQT FigureManager = FigureManagerQT @staticmethod def trigger_manager_draw(manager): manager.canvas.draw_idle() @staticmethod def mainloop(): old_signal = signal.getsignal(signal.SIGINT) # allow SIGINT exceptions to close the plot window. is_python_signal_handler = old_signal is not None if is_python_signal_handler: signal.signal(signal.SIGINT, signal.SIG_DFL) try: qApp.exec_() finally: # reset the SIGINT exception handler if is_python_signal_handler: signal.signal(signal.SIGINT, old_signal)
{ "pile_set_name": "Github" }
# Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. vespa_add_executable(fnet_databuffer_test_app TEST SOURCES databuffer.cpp DEPENDS fnet ) vespa_add_test(NAME fnet_databuffer_test_app COMMAND fnet_databuffer_test_app)
{ "pile_set_name": "Github" }
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zap import ( "flag" "go.uber.org/zap/zapcore" ) // LevelFlag uses the standard library's flag.Var to declare a global flag // with the specified name, default, and usage guidance. The returned value is // a pointer to the value of the flag. // // If you don't want to use the flag package's global state, you can use any // non-nil *Level as a flag.Value with your own *flag.FlagSet. func LevelFlag(name string, defaultLevel zapcore.Level, usage string) *zapcore.Level { lvl := defaultLevel flag.Var(&lvl, name, usage) return &lvl }
{ "pile_set_name": "Github" }
<?php final class Braintree_MerchantAccount_BusinessDetails extends Braintree { protected function _initialize($businessAttribs) { $this->_attributes = $businessAttribs; if (isset($businessAttribs['address'])) { $this->_set('addressDetails', new Braintree_MerchantAccount_AddressDetails($businessAttribs['address'])); } } public static function factory($attributes) { $instance = new self(); $instance->_initialize($attributes); return $instance; } }
{ "pile_set_name": "Github" }
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once #include "Object.h" #include "KBECommon.h" #include "KBEventTypes.h" #include "KBEvent.generated.h" /* 事件模块 事件的数据基础类, 不同事件需要实现不同的数据类 */ UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData : public UObject { GENERATED_BODY() public: // 事件名称,可用于对事件类型进行判断,该名称由事件触发时事件系统进行填充 UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString eventName; }; /* 事件模块 KBEngine插件层与Unity3D表现层通过事件来交互 */ class KBENGINEPLUGINS_API KBEvent { public: KBEvent(); virtual ~KBEvent(); public: static bool registerEvent(const FString& eventName, const FString& funcName, TFunction<void(const UKBEventData*)> func, void* objPtr); static bool deregister(void* objPtr, const FString& eventName, const FString& funcName); static bool deregister(void* objPtr); static void fire(const FString& eventName, UKBEventData* pEventData); static void clear(); static void clearFiredEvents(); static void processInEvents() {} static void processOutEvents() {} static void pause(); static void resume(); static void removeFiredEvent(void* objPtr, const FString& eventName = TEXT(""), const FString& funcName = TEXT("")); protected: struct EventObj { TFunction<void(const UKBEventData*)> method; FString funcName; void* objPtr; }; struct FiredEvent { EventObj evt; FString eventName; UKBEventData* args; }; static TMap<FString, TArray<EventObj>> events_; static TArray<FiredEvent*> firedEvents_; static bool isPause_; }; // 注册事件 #define KBENGINE_REGISTER_EVENT(EVENT_NAME, EVENT_FUNC) \ KBEvent::registerEvent(EVENT_NAME, #EVENT_FUNC, [this](const UKBEventData* pEventData) { EVENT_FUNC(pEventData); }, (void*)this); // 注册事件,可重写事件函数 #define KBENGINE_REGISTER_EVENT_OVERRIDE_FUNC(EVENT_NAME, FUNC_NAME, EVENT_FUNC) \ KBEvent::registerEvent(EVENT_NAME, FUNC_NAME, EVENT_FUNC, (void*)this); // 注销这个对象某个事件 #define KBENGINE_DEREGISTER_EVENT_BY_FUNCNAME(EVENT_NAME, FUNC_NAME) KBEvent::deregister((void*)this, EVENT_NAME, FUNC_NAME); #define KBENGINE_DEREGISTER_EVENT(EVENT_NAME) KBEvent::deregister((void*)this, EVENT_NAME, TEXT("")); // 注销这个对象所有的事件 #define KBENGINE_DEREGISTER_ALL_EVENT() KBEvent::deregister((void*)this); // fire event #define KBENGINE_EVENT_FIRE(EVENT_NAME, EVENT_DATA) KBEvent::fire(EVENT_NAME, EVENT_DATA); // 暂停事件 #define KBENGINE_EVENT_PAUSE() KBEvent::pause(); // 恢复事件 #define KBENGINE_EVENT_RESUME() KBEvent::resume(); // 清除所有的事件 #define KBENGINE_EVENT_CLEAR() KBEvent::clear(); UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_Baseapp_importClientMessages : public UKBEventData { GENERATED_BODY() public: }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onKicked : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int32 failedcode; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString errorStr; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_createAccount : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString username; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString password; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) TArray<uint8> datas; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_login : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString username; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString password; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) TArray<uint8> datas; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_logout : public UKBEventData { GENERATED_BODY() public: }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onLoginFailed : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int32 failedcode; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString errorStr; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) TArray<uint8> serverdatas; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onLoginBaseapp : public UKBEventData { GENERATED_BODY() public: }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onLoginSuccessfully : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, /*BlueprintReadWrite, No support*/ Category = KBEngine) uint64 entity_uuid; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int32 entity_id; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onReloginBaseapp : public UKBEventData { GENERATED_BODY() public: }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onLoginBaseappFailed : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int32 failedcode; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString errorStr; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onReloginBaseappFailed : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int32 failedcode; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString errorStr; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onReloginBaseappSuccessfully : public UKBEventData { GENERATED_BODY() public: }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onVersionNotMatch : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString clientVersion; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString serverVersion; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onScriptVersionNotMatch : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString clientScriptVersion; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString serverScriptVersion; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_Loginapp_importClientMessages : public UKBEventData { GENERATED_BODY() public: }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_Baseapp_importClientEntityDef : public UKBEventData { GENERATED_BODY() public: }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onControlled : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int entityID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isControlled; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onLoseControlledEntity : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int entityID; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_updatePosition : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FVector position; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FRotator direction; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int entityID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) float moveSpeed; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isOnGround; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_set_position : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FVector position; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int entityID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) float moveSpeed; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isOnGround; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_set_direction : public UKBEventData { GENERATED_BODY() public: // roll, pitch, yaw UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FRotator direction; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int entityID; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onCreateAccountResult : public UKBEventData { GENERATED_BODY() public: UPROPERTY(Category = KBEngine, BlueprintReadWrite, EditAnywhere) int errorCode; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString errorStr; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) TArray<uint8> datas; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_addSpaceGeometryMapping : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString spaceResPath; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onSetSpaceData : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int spaceID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString key; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString value; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onDelSpaceData : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int spaceID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString key; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onDisconnected : public UKBEventData { GENERATED_BODY() public: }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onConnectionState : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool success; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString address; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onEnterWorld : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString entityClassName; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int spaceID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int entityID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString res; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FVector position; // roll, pitch, yaw UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FVector direction; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) float moveSpeed; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isOnGround; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isPlayer; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onLeaveWorld : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int spaceID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int entityID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isPlayer; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onEnterSpace : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString entityClassName; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int spaceID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int entityID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString res; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FVector position; // roll, pitch, yaw UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FVector direction; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) float moveSpeed; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isOnGround; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isPlayer; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onLeaveSpace : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int spaceID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int entityID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isPlayer; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_resetPassword : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString username; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onResetPassword : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int32 failedcode; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString errorStr; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_bindAccountEmail : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString email; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onBindAccountEmail : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int32 failedcode; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString errorStr; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_newPassword : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString old_password; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString new_password; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onNewPassword : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int32 failedcode; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString errorStr; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onStreamDataStarted : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int resID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int dataSize; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString dataDescr; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onStreamDataRecv : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int resID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) TArray<uint8> data; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onStreamDataCompleted : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int resID; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onImportClientSDK : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int remainingFiles; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) int fileSize; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) FString fileName; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) TArray<uint8> fileDatas; }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onImportClientSDKSuccessfully : public UKBEventData { GENERATED_BODY() public: }; UCLASS(Blueprintable, BlueprintType) class KBENGINEPLUGINS_API UKBEventData_onDownloadSDK : public UKBEventData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = KBEngine) bool isDownload; };
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import ConfigParser import logging import time from operator import itemgetter from api_utils import SaliencyAPI, SimilarityAPI, SeriationAPI class ComputeSeriation( object ): """Seriation algorithm. Re-order words to improve promote the legibility of multi-word phrases and reveal the clustering of related terms. As output, the algorithm produces a list of seriated terms and its 'ranking' (i.e., the iteration in which a term was seriated). """ DEFAULT_NUM_SERIATED_TERMS = 100 def __init__( self, logging_level ): self.logger = logging.getLogger( 'ComputeSeriation' ) self.logger.setLevel( logging_level ) handler = logging.StreamHandler( sys.stderr ) handler.setLevel( logging_level ) self.logger.addHandler( handler ) def execute( self, data_path, numSeriatedTerms = None ): assert data_path is not None if numSeriatedTerms is None: numSeriatedTerms = ComputeSeriation.DEFAULT_NUM_SERIATED_TERMS self.logger.info( '--------------------------------------------------------------------------------' ) self.logger.info( 'Computing term seriation...' ) self.logger.info( ' data_path = %s', data_path ) self.logger.info( ' number_of_seriated_terms = %d', numSeriatedTerms ) self.logger.info( 'Connecting to data...' ) self.saliency = SaliencyAPI( data_path ) self.similarity = SimilarityAPI( data_path ) self.seriation = SeriationAPI( data_path ) self.logger.info( 'Reading data from disk...' ) self.saliency.read() self.similarity.read() self.logger.info( 'Reshaping saliency data...' ) self.reshape() self.logger.info( 'Computing seriation...' ) self.compute( numSeriatedTerms ) self.logger.info( 'Writing data to disk...' ) self.seriation.write() self.logger.info( '--------------------------------------------------------------------------------' ) def reshape( self ): self.candidateSize = 100 self.orderedTermList = [] self.termSaliency = {} self.termFreqs = {} self.termDistinct = {} self.termRank = {} self.termVisibility = {} for element in self.saliency.term_info: term = element['term'] self.orderedTermList.append( term ) self.termSaliency[term] = element['saliency'] self.termFreqs[term] = element['frequency'] self.termDistinct[term] = element['distinctiveness'] self.termRank[term] = element['rank'] self.termVisibility[term] = element['visibility'] def compute( self, numSeriatedTerms ): # Elicit from user (1) the number of terms to output and (2) a list of terms that should be included in the output... # set in init (i.e. read from config file) # Seriate! start_time = time.time() candidateTerms = self.orderedTermList self.seriation.term_ordering = [] self.seriation.term_iter_index = [] self.buffers = [0,0] preBest = [] postBest = [] for iteration in range(numSeriatedTerms): print "Iteration no. ", iteration addedTerm = 0 if len(self.seriation.term_iter_index) > 0: addedTerm = self.seriation.term_iter_index[-1] if iteration == 1: (preBest, postBest) = self.initBestEnergies(addedTerm, candidateTerms) (preBest, postBest, self.bestEnergies) = self.getBestEnergies(preBest, postBest, addedTerm) (candidateTerms, self.seriation.term_ordering, self.seriation.term_iter_index, self.buffers) = self.iterate_eff(candidateTerms, self.seriation.term_ordering, self.seriation.term_iter_index, self.buffers, self.bestEnergies, iteration) print "---------------" seriation_time = time.time() - start_time # Output consists of (1) a list of ordered terms, and (2) the iteration index in which a term was ordered #print "term_ordering: ", self.seriation.term_ordering #print "term_iter_index: ", self.seriation.term_iter_index # Feel free to pick a less confusing variable name #print "similarity matrix generation time: ", compute_sim_time #print "seriation time: ", seriation_time self.logger.debug("seriation time: " + str(seriation_time)) #-------------------------------------------------------------------------------# # Helper Functions def initBestEnergies(self, firstTerm, candidateTerms): preBest = [] postBest = [] for candidate in candidateTerms: pre_score = 0 post_score = 0 # preBest if (candidate, firstTerm) in self.similarity.combined_g2: pre_score = self.similarity.combined_g2[(candidate, firstTerm)] # postBest if (firstTerm, candidate) in self.similarity.combined_g2: post_score = self.similarity.combined_g2[(firstTerm, candidate)] preBest.append((candidate, pre_score)) postBest.append((candidate, post_score)) return (preBest, postBest) def getBestEnergies(self, preBest, postBest, addedTerm): if addedTerm == 0: return (preBest, postBest, []) term_order = [x[0] for x in preBest] # compare candidate terms' bests against newly added term remove_index = -1 for existingIndex in range(len(preBest)): term = term_order[existingIndex] if term == addedTerm: remove_index = existingIndex # check pre energies if (term, addedTerm) in self.similarity.combined_g2: if self.similarity.combined_g2[(term, addedTerm)] > preBest[existingIndex][1]: preBest[existingIndex] = (term, self.similarity.combined_g2[(term, addedTerm)]) # check post energies if (addedTerm, term) in self.similarity.combined_g2: if self.similarity.combined_g2[(addedTerm, term)] > postBest[existingIndex][1]: postBest[existingIndex] = (term, self.similarity.combined_g2[(addedTerm, term)]) # remove the added term's preBest and postBest scores if remove_index != -1: del preBest[remove_index] del postBest[remove_index] #create and sort the bestEnergies list energyMax = [sum(pair) for pair in zip([x[1] for x in preBest], [y[1] for y in postBest])] bestEnergies = zip([x[0] for x in preBest], energyMax) return (preBest, postBest, sorted(bestEnergies, key=itemgetter(1), reverse=True)) def iterate_eff( self, candidateTerms, term_ordering, term_iter_index, buffers, bestEnergies, iteration_no ): maxEnergyChange = 0.0; maxTerm = ""; maxPosition = 0; if len(bestEnergies) != 0: bestEnergy_terms = [x[0] for x in bestEnergies] else: bestEnergy_terms = candidateTerms breakout_counter = 0 for candidate_index in range(len(bestEnergy_terms)): breakout_counter += 1 candidate = bestEnergy_terms[candidate_index] for position in range(len(term_ordering)+1): current_buffer = buffers[position] candidateRank = self.termRank[candidate] if candidateRank <= (len(term_ordering) + self.candidateSize): current_energy_change = self.getEnergyChange(candidate, position, term_ordering, current_buffer, iteration_no) if current_energy_change > maxEnergyChange: maxEnergyChange = current_energy_change maxTerm = candidate maxPosition = position # check for early termination if candidate_index < len(bestEnergy_terms)-1 and len(bestEnergies) != 0: if maxEnergyChange >= (2*(bestEnergies[candidate_index][1] + current_buffer)): print "#-------- breaking out early ---------#" print "candidates checked: ", breakout_counter break; print "change in energy: ", maxEnergyChange print "maxTerm: ", maxTerm print "maxPosition: ", maxPosition candidateTerms.remove(maxTerm) # update buffers buf_score = 0 if len(term_ordering) == 0: buffers = buffers elif maxPosition >= len(term_ordering): if (term_ordering[-1], maxTerm) in self.similarity.combined_g2: buf_score = self.similarity.combined_g2[(term_ordering[-1], maxTerm)] buffers.insert(len(buffers)-1, buf_score) elif maxPosition == 0: if (maxTerm, term_ordering[0]) in self.similarity.combined_g2: buf_score = self.similarity.combined_g2[(maxTerm, term_ordering[0])] buffers.insert(1, buf_score) else: if (term_ordering[maxPosition-1], maxTerm) in self.similarity.combined_g2: buf_score = self.similarity.combined_g2[(term_ordering[maxPosition-1], maxTerm)] buffers[maxPosition] = buf_score buf_score = 0 if (maxTerm, term_ordering[maxPosition]) in self.similarity.combined_g2: buf_score = self.similarity.combined_g2[(maxTerm, term_ordering[maxPosition])] buffers.insert(maxPosition+1, buf_score) # update term ordering and ranking if maxPosition >= len(term_ordering): term_ordering.append(maxTerm) else: term_ordering.insert(maxPosition, maxTerm) term_iter_index.append(maxTerm) return (candidateTerms, term_ordering, term_iter_index, buffers) def getEnergyChange(self, candidateTerm, position, term_list, currentBuffer, iteration_no): prevBond = 0.0 postBond = 0.0 # first iteration only if iteration_no == 0: current_freq = 0.0 current_saliency = 0.0 if candidateTerm in self.termFreqs: current_freq = self.termFreqs[candidateTerm] if candidateTerm in self.termSaliency: current_saliency = self.termSaliency[candidateTerm] return 0.001 * current_freq * current_saliency # get previous term if position > 0: prev_term = term_list[position-1] if (prev_term, candidateTerm) in self.similarity.combined_g2: prevBond = self.similarity.combined_g2[(prev_term, candidateTerm)] # get next term if position < len(term_list): next_term = term_list[position] if (next_term, candidateTerm) in self.similarity.combined_g2: postBond = self.similarity.combined_g2[(candidateTerm, next_term)] return 2*(prevBond + postBond - currentBuffer) #-------------------------------------------------------------------------------# def main(): parser = argparse.ArgumentParser( description = 'Compute term seriation for TermiteVis.' ) parser.add_argument( 'config_file' , type = str, default = None , help = 'Path of Termite configuration file.' ) parser.add_argument( '--data-path' , type = str, dest = 'data_path' , help = 'Override data path.' ) parser.add_argument( '--number-of-seriated-terms', type = int, dest = 'number_of_seriated_terms', help = 'Override the number of terms to seriate.' ) parser.add_argument( '--logging' , type = int, dest = 'logging' , help = 'Override logging level.' ) args = parser.parse_args() data_path = None number_of_seriated_terms = None logging_level = 20 # Read in default values from the configuration file if args.config_file is not None: config = ConfigParser.RawConfigParser() config.read( args.config_file ) if config.has_section( 'Termite' ) and config.has_option( 'Termite', 'path' ): data_path = config.get( 'Termite', 'path' ) if config.has_section( 'Termite' ) and config.has_option( 'Termite', 'number_of_seriated_terms' ): number_of_seriated_terms = config.getint( 'Termite', 'number_of_seriated_terms' ) if config.has_section( 'Misc' ) and config.has_option( 'Misc', 'logging' ): logging_level = config.getint( 'Misc', 'logging' ) # Read in user-specifiec values from the program arguments if args.data_path is not None: data_path = args.data_path if args.number_of_seriated_terms is not None: number_of_seriated_terms = args.number_of_seriated_terms if args.logging is not None: logging_level = args.logging ComputeSeriation( logging_level ).execute( data_path, number_of_seriated_terms ) if __name__ == '__main__': main()
{ "pile_set_name": "Github" }
// +build !ignore_autogenerated /* Copyright The Kubernetes Authors. 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. */ // Code generated by prerelease-lifecycle-gen. DO NOT EDIT. package v1beta1 import ( schema "k8s.io/apimachinery/pkg/runtime/schema" ) // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *ControllerRevision) APILifecycleIntroduced() (major, minor int) { return 1, 7 } // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *ControllerRevision) APILifecycleDeprecated() (major, minor int) { return 1, 8 } // APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. // It is controlled by "k8s:prerelease-lifecycle-gen:replacement=<group>,<version>,<kind>" tags in types.go. func (in *ControllerRevision) APILifecycleReplacement() schema.GroupVersionKind { return schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "ControllerRevision"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *ControllerRevision) APILifecycleRemoved() (major, minor int) { return 1, 18 } // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *ControllerRevisionList) APILifecycleIntroduced() (major, minor int) { return 1, 7 } // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *ControllerRevisionList) APILifecycleDeprecated() (major, minor int) { return 1, 8 } // APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. // It is controlled by "k8s:prerelease-lifecycle-gen:replacement=<group>,<version>,<kind>" tags in types.go. func (in *ControllerRevisionList) APILifecycleReplacement() schema.GroupVersionKind { return schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "ControllerRevisionList"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *ControllerRevisionList) APILifecycleRemoved() (major, minor int) { return 1, 18 } // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *Deployment) APILifecycleIntroduced() (major, minor int) { return 1, 6 } // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *Deployment) APILifecycleDeprecated() (major, minor int) { return 1, 8 } // APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. // It is controlled by "k8s:prerelease-lifecycle-gen:replacement=<group>,<version>,<kind>" tags in types.go. func (in *Deployment) APILifecycleReplacement() schema.GroupVersionKind { return schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *Deployment) APILifecycleRemoved() (major, minor int) { return 1, 18 } // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *DeploymentList) APILifecycleIntroduced() (major, minor int) { return 1, 6 } // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *DeploymentList) APILifecycleDeprecated() (major, minor int) { return 1, 8 } // APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. // It is controlled by "k8s:prerelease-lifecycle-gen:replacement=<group>,<version>,<kind>" tags in types.go. func (in *DeploymentList) APILifecycleReplacement() schema.GroupVersionKind { return schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "DeploymentList"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *DeploymentList) APILifecycleRemoved() (major, minor int) { return 1, 18 } // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *DeploymentRollback) APILifecycleIntroduced() (major, minor int) { return 1, 6 } // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *DeploymentRollback) APILifecycleDeprecated() (major, minor int) { return 1, 8 } // APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. // It is controlled by "k8s:prerelease-lifecycle-gen:replacement=<group>,<version>,<kind>" tags in types.go. func (in *DeploymentRollback) APILifecycleReplacement() schema.GroupVersionKind { return schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "DeploymentRollback"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *DeploymentRollback) APILifecycleRemoved() (major, minor int) { return 1, 18 } // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *Scale) APILifecycleIntroduced() (major, minor int) { return 1, 6 } // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *Scale) APILifecycleDeprecated() (major, minor int) { return 1, 8 } // APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. // It is controlled by "k8s:prerelease-lifecycle-gen:replacement=<group>,<version>,<kind>" tags in types.go. func (in *Scale) APILifecycleReplacement() schema.GroupVersionKind { return schema.GroupVersionKind{Group: "autoscaling", Version: "v1", Kind: "Scale"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *Scale) APILifecycleRemoved() (major, minor int) { return 1, 18 } // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *StatefulSet) APILifecycleIntroduced() (major, minor int) { return 1, 5 } // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *StatefulSet) APILifecycleDeprecated() (major, minor int) { return 1, 8 } // APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. // It is controlled by "k8s:prerelease-lifecycle-gen:replacement=<group>,<version>,<kind>" tags in types.go. func (in *StatefulSet) APILifecycleReplacement() schema.GroupVersionKind { return schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "StatefulSet"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *StatefulSet) APILifecycleRemoved() (major, minor int) { return 1, 18 } // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *StatefulSetList) APILifecycleIntroduced() (major, minor int) { return 1, 5 } // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *StatefulSetList) APILifecycleDeprecated() (major, minor int) { return 1, 8 } // APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. // It is controlled by "k8s:prerelease-lifecycle-gen:replacement=<group>,<version>,<kind>" tags in types.go. func (in *StatefulSetList) APILifecycleReplacement() schema.GroupVersionKind { return schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "StatefulSetList"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *StatefulSetList) APILifecycleRemoved() (major, minor int) { return 1, 18 }
{ "pile_set_name": "Github" }
curl -i -X POST 'http://localhost:3080/v2/compute/projects/a1e920ca-338a-4e9f-b363-aa607b09dd80/traceng/nodes/770d23d8-e568-4fc4-8497-216c2e129d53/adapters/0/ports/0/start_capture' -d '{"capture_file_name": "test.pcap", "data_link_type": "DLT_EN10MB"}' POST /v2/compute/projects/a1e920ca-338a-4e9f-b363-aa607b09dd80/traceng/nodes/770d23d8-e568-4fc4-8497-216c2e129d53/adapters/0/ports/0/start_capture HTTP/1.1 { "capture_file_name": "test.pcap", "data_link_type": "DLT_EN10MB" } HTTP/1.1 200 Connection: close Content-Length: 123 Content-Type: application/json Date: Wed, 08 Jan 2020 02:27:27 GMT Server: Python/3.6 GNS3/2.2.4dev1 X-Route: /v2/compute/projects/{project_id}/traceng/nodes/{node_id}/adapters/{adapter_number:\d+}/ports/{port_number:\d+}/start_capture { "pcap_file_path": "/tmp/tmp3gc2avyo/projects/a1e920ca-338a-4e9f-b363-aa607b09dd80/project-files/captures/test.pcap" }
{ "pile_set_name": "Github" }
/** * \file * * \brief Instance description for NVMCTRL * * Copyright (c) 2016 Atmel Corporation, * a wholly owned subsidiary of Microchip Technology Inc. * * \asf_license_start * * \page License * * 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 Licence 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. * * \asf_license_stop * */ #ifndef _SAML21_NVMCTRL_INSTANCE_ #define _SAML21_NVMCTRL_INSTANCE_ /* ========== Register definition for NVMCTRL peripheral ========== */ #if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) #define REG_NVMCTRL_CTRLA (0x41004000) /**< \brief (NVMCTRL) Control A */ #define REG_NVMCTRL_CTRLB (0x41004004) /**< \brief (NVMCTRL) Control B */ #define REG_NVMCTRL_PARAM (0x41004008) /**< \brief (NVMCTRL) NVM Parameter */ #define REG_NVMCTRL_INTENCLR (0x4100400C) /**< \brief (NVMCTRL) Interrupt Enable Clear */ #define REG_NVMCTRL_INTENSET (0x41004010) /**< \brief (NVMCTRL) Interrupt Enable Set */ #define REG_NVMCTRL_INTFLAG (0x41004014) /**< \brief (NVMCTRL) Interrupt Flag Status and Clear */ #define REG_NVMCTRL_STATUS (0x41004018) /**< \brief (NVMCTRL) Status */ #define REG_NVMCTRL_ADDR (0x4100401C) /**< \brief (NVMCTRL) Address */ #define REG_NVMCTRL_LOCK (0x41004020) /**< \brief (NVMCTRL) Lock Section */ #else #define REG_NVMCTRL_CTRLA (*(RwReg16*)0x41004000UL) /**< \brief (NVMCTRL) Control A */ #define REG_NVMCTRL_CTRLB (*(RwReg *)0x41004004UL) /**< \brief (NVMCTRL) Control B */ #define REG_NVMCTRL_PARAM (*(RwReg *)0x41004008UL) /**< \brief (NVMCTRL) NVM Parameter */ #define REG_NVMCTRL_INTENCLR (*(RwReg8 *)0x4100400CUL) /**< \brief (NVMCTRL) Interrupt Enable Clear */ #define REG_NVMCTRL_INTENSET (*(RwReg8 *)0x41004010UL) /**< \brief (NVMCTRL) Interrupt Enable Set */ #define REG_NVMCTRL_INTFLAG (*(RwReg8 *)0x41004014UL) /**< \brief (NVMCTRL) Interrupt Flag Status and Clear */ #define REG_NVMCTRL_STATUS (*(RwReg16*)0x41004018UL) /**< \brief (NVMCTRL) Status */ #define REG_NVMCTRL_ADDR (*(RwReg *)0x4100401CUL) /**< \brief (NVMCTRL) Address */ #define REG_NVMCTRL_LOCK (*(RwReg16*)0x41004020UL) /**< \brief (NVMCTRL) Lock Section */ #endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ /* ========== Instance parameters for NVMCTRL peripheral ========== */ #define NVMCTRL_AUX0_ADDRESS 0x00804000 #define NVMCTRL_AUX1_ADDRESS 0x00806000 #define NVMCTRL_AUX2_ADDRESS 0x00808000 #define NVMCTRL_AUX3_ADDRESS 0x0080A000 #define NVMCTRL_CLK_AHB_ID 8 // Index of AHB Clock in PM.AHBMASK register #define NVMCTRL_CLK_AHB_ID_PICACHU 15 // Index of PICACHU AHB Clock #define NVMCTRL_FACTORY_WORD_IMPLEMENTED_MASK 0XC0000007FFFFFFFF #define NVMCTRL_FLASH_SIZE 262144 #define NVMCTRL_GCLK_ID 35 // Index of Generic Clock for test #define NVMCTRL_LOCKBIT_ADDRESS 0x00802000 #define NVMCTRL_PAGE_HW 32 #define NVMCTRL_PAGE_SIZE 64 #define NVMCTRL_PAGE_W 16 #define NVMCTRL_PMSB 3 #define NVMCTRL_PSZ_BITS 6 #define NVMCTRL_ROW_PAGES 4 #define NVMCTRL_ROW_SIZE 256 #define NVMCTRL_USER_PAGE_ADDRESS 0x00800000 #define NVMCTRL_USER_PAGE_OFFSET 0x00800000 #define NVMCTRL_USER_WORD_IMPLEMENTED_MASK 0XC01FFFFFFFFFFFFF #define NVMCTRL_RWWEE_PAGES 128 #define NVMCTRL_RWW_EEPROM_ADDR 0x00400000 // Start address of the RWW EEPROM area #endif /* _SAML21_NVMCTRL_INSTANCE_ */
{ "pile_set_name": "Github" }
// FastNoiseSIMD_internal.cpp // // MIT License // // Copyright(c) 2017 Jordan Peck // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // The developer's email is jorzixdan.me2@gzixmail.com (for great email, take // off every 'zix'.) // #include "FastNoiseSIMD.h" #include <assert.h> #if defined(SIMD_LEVEL) || defined(FN_COMPILE_NO_SIMD_FALLBACK) #ifndef SIMD_LEVEL #define SIMD_LEVEL FN_NO_SIMD_FALLBACK #define SIMD_LEVEL_H FN_NO_SIMD_FALLBACK #include "FastNoiseSIMD_internal.h" #include <math.h> #define FN_ALIGNED_SETS #endif // Per SIMD level var/function naming #define L_VAR2(x, l) L##l##_##x #define L_VAR(x, l) L_VAR2(x, l) #define VAR(x) L_VAR(x, SIMD_LEVEL) #define FUNC(x) VAR(FUNC_##x) #define SIMDf_NUM(n) VAR(SIMDf_NUM_##n) #define SIMDi_NUM(n) VAR(SIMDi_NUM_##n) #define SIMD_LEVEL_CLASS FastNoiseSIMD_internal::FASTNOISE_SIMD_CLASS(SIMD_LEVEL) #if defined(_WIN32) && SIMD_LEVEL > FN_NO_SIMD_FALLBACK #define VECTORCALL __vectorcall #else #define VECTORCALL #endif // Typedefs #if SIMD_LEVEL == FN_NEON #define VECTOR_SIZE 4 #define MEMORY_ALIGNMENT 16 typedef float32x4_t SIMDf; typedef int32x4_t SIMDi; #define SIMDf_SET(a) vdupq_n_f32(a) #define SIMDf_SET_ZERO() vdupq_n_f32(0) #define SIMDi_SET(a) vdupq_n_s32(a) #define SIMDi_SET_ZERO() vdupq_n_s32(0) #elif SIMD_LEVEL == FN_AVX512 #define VECTOR_SIZE 16 #define MEMORY_ALIGNMENT 64 typedef __m512 SIMDf; typedef __m512i SIMDi; #define SIMDf_SET(a) _mm512_set1_ps(a) #define SIMDf_SET_ZERO() _mm512_setzero_ps() #define SIMDi_SET(a) _mm512_set1_epi32(a) #define SIMDi_SET_ZERO() _mm512_setzero_si512() #elif SIMD_LEVEL == FN_AVX2 #define VECTOR_SIZE 8 #define MEMORY_ALIGNMENT 32 typedef __m256 SIMDf; typedef __m256i SIMDi; #define SIMDf_SET(a) _mm256_set1_ps(a) #define SIMDf_SET_ZERO() _mm256_setzero_ps() #define SIMDi_SET(a) _mm256_set1_epi32(a) #define SIMDi_SET_ZERO() _mm256_setzero_si256() #elif SIMD_LEVEL >= FN_SSE2 #define VECTOR_SIZE 4 #define MEMORY_ALIGNMENT 16 typedef __m128 SIMDf; typedef __m128i SIMDi; #define SIMDf_SET(a) _mm_set1_ps(a) #define SIMDf_SET_ZERO() _mm_setzero_ps() #define SIMDi_SET(a) _mm_set1_epi32(a) #define SIMDi_SET_ZERO() _mm_setzero_si128() #else // Fallback to float/int #define VECTOR_SIZE 1 #define MEMORY_ALIGNMENT 4 typedef float SIMDf; typedef int SIMDi; #define SIMDf_SET(a) (a) #define SIMDf_SET_ZERO() (0) #define SIMDi_SET(a) (a) #define SIMDi_SET_ZERO() (0) #endif // Memory Allocation #if SIMD_LEVEL > FN_NO_SIMD_FALLBACK && defined(FN_ALIGNED_SETS) #ifdef _WIN32 #define SIMD_ALLOCATE_SET(floatP, floatCount) floatP = (float*)_aligned_malloc((floatCount)* sizeof(float), MEMORY_ALIGNMENT) #else #define SIMD_ALLOCATE_SET(floatP, floatCount) posix_memalign((void**)&floatP, MEMORY_ALIGNMENT, (floatCount)* sizeof(float)) #endif #else #define SIMD_ALLOCATE_SET(floatP, floatCount) floatP = new float[floatCount] #endif union uSIMDf { SIMDf m; float a[VECTOR_SIZE]; }; union uSIMDi { SIMDi m; int a[VECTOR_SIZE]; }; #if SIMD_LEVEL == FN_AVX512 typedef __mmask16 MASK; #else typedef SIMDi MASK; #endif static SIMDi SIMDi_NUM(0xffffffff); static SIMDf SIMDf_NUM(1); // SIMD functions #if SIMD_LEVEL == FN_NEON #define SIMDf_STORE(p,a) vst1q_f32(p, a) #define SIMDf_LOAD(p) vld1q_f32(p) #define SIMDf_UNDEFINED() SIMDf_SET(0) #define SIMDi_UNDEFINED() SIMDi_SET(0) #define SIMDf_CONVERT_TO_FLOAT(a) vcvtq_f32_s32(a) #define SIMDf_CAST_TO_FLOAT(a) vreinterpretq_f32_s32(a) #define SIMDi_CONVERT_TO_INT(a) vcvtq_s32_f32(a) #define SIMDi_CAST_TO_INT(a) vreinterpretq_s32_f32(a) #define SIMDf_ADD(a,b) vaddq_f32(a,b) #define SIMDf_SUB(a,b) vsubq_f32(a,b) #define SIMDf_MUL(a,b) vmulq_f32(a,b) #define SIMDf_DIV(a,b) FUNC(DIV)(a,b) static SIMDf VECTORCALL FUNC(DIV)(SIMDf a, SIMDf b) { SIMDf reciprocal = vrecpeq_f32(b); // use a couple Newton-Raphson steps to refine the estimate. Depending on your // application's accuracy requirements, you may be able to get away with only // one refinement (instead of the two used here). Be sure to test! reciprocal = vmulq_f32(vrecpsq_f32(b, reciprocal), reciprocal); // and finally, compute a/b = a*(1/b) return vmulq_f32(a, reciprocal); } #define SIMDf_MIN(a,b) vminq_f32(a,b) #define SIMDf_MAX(a,b) vmaxq_f32(a,b) #define SIMDf_INV_SQRT(a) vrsqrteq_f32(a) #define SIMDf_LESS_THAN(a,b) vreinterpretq_f32_u32(vcltq_f32(a,b)) #define SIMDf_GREATER_THAN(a,b) vreinterpretq_f32_u32(vcgtq_f32(a,b)) #define SIMDf_LESS_EQUAL(a,b) vreinterpretq_f32_u32(vcleq_f32(a,b)) #define SIMDf_GREATER_EQUAL(a,b) vreinterpretq_f32_u32(vcgeq_f32(a,b)) #define SIMDf_AND(a,b) SIMDf_CAST_TO_FLOAT(vandq_s32(vreinterpretq_s32_f32(a),vreinterpretq_s32_f32(b))) #define SIMDf_AND_NOT(a,b) SIMDf_CAST_TO_FLOAT(vandq_s32(vmvnq_s32(vreinterpretq_s32_f32(a)),vreinterpretq_s32_f32(b))) #define SIMDf_XOR(a,b) SIMDf_CAST_TO_FLOAT(veorq_s32(vreinterpretq_s32_f32(a),vreinterpretq_s32_f32(b))) #ifndef __aarch64__ static SIMDf VECTORCALL FUNC(FLOOR)(SIMDf a) { SIMDf fval = SIMDf_CONVERT_TO_FLOAT(SIMDi_CONVERT_TO_INT(a)); return vsubq_f32(fval, SIMDf_AND(SIMDf_LESS_THAN(a, fval), SIMDf_NUM(1))); } #define SIMDf_FLOOR(a) FUNC(FLOOR)(a) #else #define SIMDf_FLOOR(a) vrndmq_f32(a) #endif #define SIMDf_ABS(a) vabsq_f32(a) #define SIMDf_BLENDV(a,b,mask) vbslq_f32(mask,b,a) #define SIMDi_ADD(a,b) vaddq_s32(a,b) #define SIMDi_SUB(a,b) vsubq_s32(a,b) #define SIMDi_MUL(a,b) vmulq_s32(a,b) #define SIMDi_AND(a,b) vandq_s32(a,b) #define SIMDi_AND_NOT(a,b) vandq_s32(vmvnq_s32(a),b) #define SIMDi_OR(a,b) vorrq_s32(a,b) #define SIMDi_XOR(a,b) veorq_s32(a,b) #define SIMDi_NOT(a) vmvnq_s32(a) #define SIMDi_SHIFT_R(a, b) vshrq_n_s32(a, b) #define SIMDi_SHIFT_L(a, b) vshlq_n_s32(a, b) #define SIMDi_VSHIFT_L(a, b) vshlq_s32(a, b) #define SIMDi_EQUAL(a,b) vreinterpretq_s32_u32(vceqq_s32(a,b)) #define SIMDi_GREATER_THAN(a,b) vreinterpretq_s32_u32(vcgtq_s32(a,b)) #define SIMDi_LESS_THAN(a,b) vreinterpretq_s32_u32(vcltq_s32(a,b)) #elif SIMD_LEVEL == FN_AVX512 #ifdef FN_ALIGNED_SETS #define SIMDf_STORE(p,a) _mm512_store_ps(p,a) #define SIMDf_LOAD(p) _mm512_load_ps(p) #else #define SIMDf_STORE(p,a) _mm512_storeu_ps(p,a) #define SIMDf_LOAD(p) _mm512_loadu_ps(p) #endif #define SIMDf_UNDEFINED() _mm512_undefined_ps() #define SIMDi_UNDEFINED() _mm512_undefined_epi32() #define SIMDf_ADD(a,b) _mm512_add_ps(a,b) #define SIMDf_SUB(a,b) _mm512_sub_ps(a,b) #define SIMDf_MUL(a,b) _mm512_mul_ps(a,b) #define SIMDf_DIV(a,b) _mm512_div_ps(a,b) #define SIMDf_MIN(a,b) _mm512_min_ps(a,b) #define SIMDf_MAX(a,b) _mm512_max_ps(a,b) #define SIMDf_INV_SQRT(a) _mm512_rsqrt14_ps(a) #define SIMDf_LESS_THAN(a,b) _mm512_cmp_ps_mask(a,b,_CMP_LT_OQ) #define SIMDf_GREATER_THAN(a,b) _mm512_cmp_ps_mask(a,b,_CMP_GT_OQ) #define SIMDf_LESS_EQUAL(a,b) _mm512_cmp_ps_mask(a,b,_CMP_LE_OQ) #define SIMDf_GREATER_EQUAL(a,b) _mm512_cmp_ps_mask(a,b,_CMP_GE_OQ) #define SIMDf_AND(a,b) _mm512_and_ps(a,b) #define SIMDf_AND_NOT(a,b) _mm512_andnot_ps(a,b) #define SIMDf_XOR(a,b) _mm512_xor_ps(a,b) #define SIMDf_FLOOR(a) _mm512_floor_ps(a) #define SIMDf_ABS(a) _mm512_abs_ps(a) #define SIMDf_BLENDV(a,b,mask) _mm512_mask_blend_ps(mask,a,b) #define SIMDf_GATHER(p,a) _mm512_i32gather_ps(a,p,4) #define SIMDf_PERMUTE(a,b) _mm512_permutexvar_ps(b,a) #define SIMDi_ADD(a,b) _mm512_add_epi32(a,b) #define SIMDi_SUB(a,b) _mm512_sub_epi32(a,b) #define SIMDi_MUL(a,b) _mm512_mullo_epi32(a,b) #define SIMDi_AND(a,b) _mm512_and_si512(a,b) #define SIMDi_AND_NOT(a,b) _mm512_andnot_si512(a,b) #define SIMDi_OR(a,b) _mm512_or_si512(a,b) #define SIMDi_XOR(a,b) _mm512_xor_si512(a,b) #define SIMDi_NOT(a) SIMDi_XOR(a,SIMDi_NUM(0xffffffff)) #define SIMDi_SHIFT_R(a, b) _mm512_srai_epi32(a, b) #define SIMDi_SHIFT_L(a, b) _mm512_slli_epi32(a, b) #define SIMDi_VSHIFT_R(a,b) _mm512_srl_epi32(a, b) #define SIMDi_VSHIFT_L(a,b) _mm512_sll_epi32(a, b) #define SIMDi_EQUAL(a,b) _mm512_cmpeq_epi32_mask(a,b) #define SIMDi_GREATER_THAN(a,b) _mm512_cmpgt_epi32_mask(a,b) #define SIMDi_LESS_THAN(a,b) _mm512_cmpgt_epi32_mask(b,a) #define SIMDf_CONVERT_TO_FLOAT(a) _mm512_cvtepi32_ps(a) #define SIMDf_CAST_TO_FLOAT(a) _mm512_castsi512_ps(a) #define SIMDi_CONVERT_TO_INT(a) _mm512_cvtps_epi32(a) #define SIMDi_CAST_TO_INT(a) _mm512_castps_si512(a) #elif SIMD_LEVEL == FN_AVX2 #ifdef FN_ALIGNED_SETS #define SIMDf_STORE(p,a) _mm256_store_ps(p,a) #define SIMDf_LOAD(p) _mm256_load_ps(p) #else #define SIMDf_STORE(p,a) _mm256_storeu_ps(p,a) #define SIMDf_LOAD(p) _mm256_loadu_ps(p) #endif #define SIMDf_UNDEFINED() _mm256_undefined_ps() #define SIMDi_UNDEFINED() _mm256_undefined_si256() #define SIMDf_CONVERT_TO_FLOAT(a) _mm256_cvtepi32_ps(a) #define SIMDf_CAST_TO_FLOAT(a) _mm256_castsi256_ps(a) #define SIMDi_CONVERT_TO_INT(a) _mm256_cvtps_epi32(a) #define SIMDi_CAST_TO_INT(a) _mm256_castps_si256(a) #define SIMDf_ADD(a,b) _mm256_add_ps(a,b) #define SIMDf_SUB(a,b) _mm256_sub_ps(a,b) #define SIMDf_MUL(a,b) _mm256_mul_ps(a,b) #define SIMDf_DIV(a,b) _mm256_div_ps(a,b) #define SIMDf_MIN(a,b) _mm256_min_ps(a,b) #define SIMDf_MAX(a,b) _mm256_max_ps(a,b) #define SIMDf_INV_SQRT(a) _mm256_rsqrt_ps(a) #define SIMDf_LESS_THAN(a,b) SIMDi_CAST_TO_INT(_mm256_cmp_ps(a,b,_CMP_LT_OQ)) #define SIMDf_GREATER_THAN(a,b) SIMDi_CAST_TO_INT(_mm256_cmp_ps(a,b,_CMP_GT_OQ)) #define SIMDf_LESS_EQUAL(a,b) SIMDi_CAST_TO_INT(_mm256_cmp_ps(a,b,_CMP_LE_OQ)) #define SIMDf_GREATER_EQUAL(a,b) SIMDi_CAST_TO_INT( _mm256_cmp_ps(a,b,_CMP_GE_OQ)) #define SIMDf_AND(a,b) _mm256_and_ps(a,b) #define SIMDf_AND_NOT(a,b) _mm256_andnot_ps(a,b) #define SIMDf_XOR(a,b) _mm256_xor_ps(a,b) #define SIMDf_FLOOR(a) _mm256_floor_ps(a) #define SIMDf_ABS(a) SIMDf_AND(a,SIMDf_CAST_TO_FLOAT(SIMDi_NUM(0x7fffffff))) #define SIMDf_BLENDV(a,b,mask) _mm256_blendv_ps(a,b,SIMDf_CAST_TO_FLOAT(mask)) #define SIMDf_PERMUTE(a,b) _mm256_permutevar8x32_ps(a,b) #define SIMDi_ADD(a,b) _mm256_add_epi32(a,b) #define SIMDi_SUB(a,b) _mm256_sub_epi32(a,b) #define SIMDi_MUL(a,b) _mm256_mullo_epi32(a,b) #define SIMDi_AND(a,b) _mm256_and_si256(a,b) #define SIMDi_AND_NOT(a,b) _mm256_andnot_si256(a,b) #define SIMDi_OR(a,b) _mm256_or_si256(a,b) #define SIMDi_XOR(a,b) _mm256_xor_si256(a,b) #define SIMDi_NOT(a) SIMDi_XOR(a,SIMDi_NUM(0xffffffff)) #define SIMDi_SHIFT_R(a, b) _mm256_srai_epi32(a, b) #define SIMDi_SHIFT_L(a, b) _mm256_slli_epi32(a, b) #define SIMDi_EQUAL(a,b) _mm256_cmpeq_epi32(a,b) #define SIMDi_GREATER_THAN(a,b) _mm256_cmpgt_epi32(a,b) #define SIMDi_LESS_THAN(a,b) _mm256_cmpgt_epi32(b,a) #elif SIMD_LEVEL >= FN_SSE2 #ifdef FN_ALIGNED_SETS #define SIMDf_STORE(p,a) _mm_store_ps(p,a) #define SIMDf_LOAD(p) _mm_load_ps(p) #else #define SIMDf_STORE(p,a) _mm_storeu_ps(p,a) #define SIMDf_LOAD(p) _mm_loadu_ps(p) #endif #define SIMDf_UNDEFINED() SIMDf_SET_ZERO() #define SIMDi_UNDEFINED() SIMDi_SET_ZERO() #define SIMDf_CONVERT_TO_FLOAT(a) _mm_cvtepi32_ps(a) #define SIMDf_CAST_TO_FLOAT(a) _mm_castsi128_ps(a) #define SIMDi_CONVERT_TO_INT(a) _mm_cvtps_epi32(a) #define SIMDi_CAST_TO_INT(a) _mm_castps_si128(a) #define SIMDf_ADD(a,b) _mm_add_ps(a,b) #define SIMDf_SUB(a,b) _mm_sub_ps(a,b) #define SIMDf_MUL(a,b) _mm_mul_ps(a,b) #define SIMDf_DIV(a,b) _mm_div_ps(a,b) #define SIMDf_MIN(a,b) _mm_min_ps(a,b) #define SIMDf_MAX(a,b) _mm_max_ps(a,b) #define SIMDf_INV_SQRT(a) _mm_rsqrt_ps(a) #define SIMDf_LESS_THAN(a,b) SIMDi_CAST_TO_INT(_mm_cmplt_ps(a,b)) #define SIMDf_GREATER_THAN(a,b) SIMDi_CAST_TO_INT(_mm_cmpgt_ps(a,b)) #define SIMDf_LESS_EQUAL(a,b) SIMDi_CAST_TO_INT(_mm_cmple_ps(a,b)) #define SIMDf_GREATER_EQUAL(a,b) SIMDi_CAST_TO_INT(_mm_cmpge_ps(a,b)) #define SIMDf_AND(a,b) _mm_and_ps(a,b) #define SIMDf_AND_NOT(a,b) _mm_andnot_ps(a,b) #define SIMDf_XOR(a,b) _mm_xor_ps(a,b) #define SIMDf_ABS(a) SIMDf_AND(a,SIMDf_CAST_TO_FLOAT(SIMDi_NUM(0x7fffffff))) #if SIMD_LEVEL == FN_SSE41 #define SIMDi_MUL(a,b) _mm_mullo_epi32(a,b) #define SIMDf_FLOOR(a) _mm_floor_ps(a) #define SIMDf_BLENDV(a,b,mask) _mm_blendv_ps(a,b,SIMDf_CAST_TO_FLOAT(mask)) #else static SIMDi VECTORCALL FUNC(MUL)(SIMDi a, SIMDi b) { __m128 tmp1 = _mm_castsi128_ps(_mm_mul_epu32(a, b)); /* mul 2,0*/ __m128 tmp2 = _mm_castsi128_ps(_mm_mul_epu32(_mm_srli_si128(a, 4), _mm_srli_si128(b, 4))); /* mul 3,1 */ return _mm_shuffle_epi32(_mm_castps_si128(_mm_shuffle_ps(tmp1, tmp2, _MM_SHUFFLE(2, 0, 2, 0))), _MM_SHUFFLE(3, 1, 2, 0)); } #define SIMDi_MUL(a,b) FUNC(MUL)(a,b) static SIMDf VECTORCALL FUNC(FLOOR)(SIMDf a) { __m128 fval = _mm_cvtepi32_ps(_mm_cvttps_epi32(a)); return _mm_sub_ps(fval, _mm_and_ps(_mm_cmplt_ps(a, fval), SIMDf_NUM(1))); } #define SIMDf_FLOOR(a) FUNC(FLOOR)(a) #define SIMDf_BLENDV(a,b,mask) _mm_or_ps(_mm_andnot_ps(SIMDf_CAST_TO_FLOAT(mask), a), _mm_and_ps(SIMDf_CAST_TO_FLOAT(mask), b)) #endif #define SIMDi_ADD(a,b) _mm_add_epi32(a,b) #define SIMDi_SUB(a,b) _mm_sub_epi32(a,b) #define SIMDi_AND(a,b) _mm_and_si128(a,b) #define SIMDi_AND_NOT(a,b) _mm_andnot_si128(a,b) #define SIMDi_OR(a,b) _mm_or_si128(a,b) #define SIMDi_XOR(a,b) _mm_xor_si128(a,b) #define SIMDi_NOT(a) SIMDi_XOR(a,SIMDi_NUM(0xffffffff)) #define SIMDi_SHIFT_R(a,b) _mm_srai_epi32(a, b) #define SIMDi_SHIFT_L(a,b) _mm_slli_epi32(a, b) #define SIMDi_EQUAL(a,b) _mm_cmpeq_epi32(a,b) #define SIMDi_GREATER_THAN(a,b) _mm_cmpgt_epi32(a,b) #define SIMDi_LESS_THAN(a,b) _mm_cmpgt_epi32(b,a) #else // Fallback static int FUNC(CAST_TO_INT)(float f) { return *reinterpret_cast<int*>(&f); } static float FUNC(CAST_TO_FLOAT)(int i) { return *reinterpret_cast<float*>(&i); } #define SIMDi_CAST_TO_INT(a) FUNC(CAST_TO_INT)(a) #define SIMDf_CAST_TO_FLOAT(a) FUNC(CAST_TO_FLOAT)(a) #define SIMDf_STORE(p,a) (*(p) = a) #define SIMDf_LOAD(p) (*p) #define SIMDf_UNDEFINED() (0) #define SIMDi_UNDEFINED() (0) #define SIMDf_ADD(a,b) ((a) + (b)) #define SIMDf_SUB(a,b) ((a) - (b)) #define SIMDf_MUL(a,b) ((a) * (b)) #define SIMDf_DIV(a,b) ((a) / (b)) #define SIMDf_MIN(a,b) fminf(a,b) #define SIMDf_MAX(a,b) fmaxf(a,b) static float FUNC(INV_SQRT)(float x) { float xhalf = 0.5f * x; int i = *(int*)&x; i = 0x5f3759df - (i >> 1); x = *(float*)&i; x = x*(1.5f - xhalf*x*x); return x; } #define SIMDf_INV_SQRT(a) FUNC(INV_SQRT)(a) #define SIMDf_LESS_THAN(a,b) (((a) < (b)) ? 0xFFFFFFFF : 0) #define SIMDf_GREATER_THAN(a,b) (((a) > (b)) ? 0xFFFFFFFF : 0) #define SIMDf_LESS_EQUAL(a,b) (((a) <= (b)) ? 0xFFFFFFFF : 0) #define SIMDf_GREATER_EQUAL(a,b) (((a) >= (b)) ? 0xFFFFFFFF : 0) #define SIMDf_AND(a,b) SIMDf_CAST_TO_FLOAT(SIMDi_CAST_TO_INT(a) & SIMDi_CAST_TO_INT(b)) #define SIMDf_AND_NOT(a,b) SIMDf_CAST_TO_FLOAT(~SIMDi_CAST_TO_INT(a) & SIMDi_CAST_TO_INT(b)) #define SIMDf_XOR(a,b) SIMDf_CAST_TO_FLOAT(SIMDi_CAST_TO_INT(a) ^ SIMDi_CAST_TO_INT(b)) #define SIMDf_FLOOR(a) floorf(a) #define SIMDf_ABS(a) fabsf(a) #define SIMDf_BLENDV(a,b,mask) (mask ? (b) : (a)) #define SIMDf_GATHER(p,a) (*(reinterpret_cast<const float*>(p)+(a))) #define SIMDi_ADD(a,b) ((a) + (b)) #define SIMDi_SUB(a,b) ((a) - (b)) #define SIMDi_MUL(a,b) ((a) * (b)) #define SIMDi_AND(a,b) ((a) & (b)) #define SIMDi_AND_NOT(a,b) (~(a) & (b)) #define SIMDi_OR(a,b) ((a) | (b)) #define SIMDi_XOR(a,b) ((a) ^ (b)) #define SIMDi_NOT(a) (~(a)) #define SIMDi_SHIFT_R(a, b) ((a) >> (b)) #define SIMDi_SHIFT_L(a, b) ((a) << (b)) #define SIMDi_EQUAL(a,b) (((a) == (b)) ? 0xFFFFFFFF : 0) #define SIMDi_GREATER_THAN(a,b) (((a) > (b)) ? 0xFFFFFFFF : 0) #define SIMDi_LESS_THAN(a,b) (((a) < (b)) ? 0xFFFFFFFF : 0) #define SIMDi_CONVERT_TO_INT(a) static_cast<int>(roundf(a)) #define SIMDf_CONVERT_TO_FLOAT(a) static_cast<float>(a) #endif //#define SIMDf_SIGN_FLIP(a) SIMDf_XOR(a,SIMDf_NUM(neg0))) //#define SIMDi_GREATER_EQUAL(a,b) SIMDi_NOT(SIMDi_LESS_THAN(a,b)) //#define SIMDi_LESS_EQUAL(a,b) SIMDi_NOT(SIMDi_GREATER_THAN(a,b)) //#define SIMDi_BLENDV(a,b, mask) SIMDi_CAST_TO_INT(SIMDf_BLENDV(SIMDf_CAST_TO_FLOAT(a),SIMDf_CAST_TO_FLOAT(b),SIMDf_CAST_TO_FLOAT(mask))) #if SIMD_LEVEL == FN_AVX512 #define MASK_OR(a,b) ((a)|(b)) #define MASK_AND(a,b) ((a)&(b)) #define MASK_AND_NOT(a,b) (~(a)&(b)) #define MASK_NOT(a) (~(a)) #define SIMDf_MASK(m,a) _mm512_maskz_mov_ps(m,a) #define SIMDf_MASK_ADD(m,a,b) _mm512_mask_add_ps(a,m,a,b) #define SIMDf_MASK_SUB(m,a,b) _mm512_mask_sub_ps(a,m,a,b) #define SIMDi_MASK_ADD(m,a,b) _mm512_mask_add_epi32(a,m,a,b) #define SIMDi_MASK_SUB(m,a,b) _mm512_mask_sub_epi32(a,m,a,b) #else #define MASK_OR(a,b) SIMDi_OR(a,b) #define MASK_AND(a,b) SIMDi_AND(a,b) #define MASK_AND_NOT(a,b) SIMDi_AND_NOT(a,b) #define MASK_NOT(a) SIMDi_NOT(a) #define SIMDf_MASK(m,a) SIMDf_AND(SIMDf_CAST_TO_FLOAT(m),a) #define SIMDf_MASK_ADD(m,a,b) SIMDf_ADD(a,SIMDf_AND(SIMDf_CAST_TO_FLOAT(m),b)) #define SIMDf_MASK_SUB(m,a,b) SIMDf_SUB(a,SIMDf_AND(SIMDf_CAST_TO_FLOAT(m),b)) #define SIMDi_MASK_ADD(m,a,b) SIMDi_ADD(a,SIMDi_AND(m,b)) #define SIMDi_MASK_SUB(m,a,b) SIMDi_SUB(a,SIMDi_AND(m,b)) #endif #if SIMD_LEVEL == FN_AVX512 #elif SIMD_LEVEL == FN_NEON #elif SIMD_LEVEL == FN_NO_SIMD_FALLBACK #else #endif #if SIMD_LEVEL == FN_AVX2 #define SIMD_ZERO_ALL() //_mm256_zeroall() #else #define SIMD_ZERO_ALL() #endif // FMA #ifdef FN_USE_FMA #if SIMD_LEVEL == FN_NEON #define SIMDf_MUL_ADD(a,b,c) vmlaq_f32(b,c,a) #define SIMDf_MUL_SUB(a,b,c) SIMDf_SUB(SIMDf_MUL(a,b),c) // Neon multiply sub swaps sides of minus compared to FMA making it unusable #define SIMDf_NMUL_ADD(a,b,c) vmlaq_f32(b,c,a) #elif SIMD_LEVEL == FN_AVX512 #define SIMDf_MUL_ADD(a,b,c) _mm512_fmadd_ps(a,b,c) #define SIMDf_MUL_SUB(a,b,c) _mm512_fmsub_ps(a,b,c) #define SIMDf_NMUL_ADD(a,b,c) _mm512_fnmadd_ps(a,b,c) #elif SIMD_LEVEL == FN_AVX2 #define SIMDf_MUL_ADD(a,b,c) _mm256_fmadd_ps(a,b,c) #define SIMDf_MUL_SUB(a,b,c) _mm256_fmsub_ps(a,b,c) #define SIMDf_NMUL_ADD(a,b,c) _mm256_fnmadd_ps(a,b,c) #endif #endif #ifndef SIMDf_MUL_ADD #define SIMDf_MUL_ADD(a,b,c) SIMDf_ADD(SIMDf_MUL(a,b),c) #define SIMDf_MUL_SUB(a,b,c) SIMDf_SUB(SIMDf_MUL(a,b),c) #define SIMDf_NMUL_ADD(a,b,c) SIMDf_SUB(c, SIMDf_MUL(a,b)) #endif static bool VAR(SIMD_Values_Set) = false; static SIMDf SIMDf_NUM(incremental); static SIMDf SIMDf_NUM(0); static SIMDf SIMDf_NUM(2); static SIMDf SIMDf_NUM(6); static SIMDf SIMDf_NUM(10); static SIMDf SIMDf_NUM(15); static SIMDf SIMDf_NUM(32); static SIMDf SIMDf_NUM(999999); static SIMDf SIMDf_NUM(0_5); static SIMDf SIMDf_NUM(0_6); static SIMDf SIMDf_NUM(15_5); static SIMDf SIMDf_NUM(511_5); //static SIMDf SIMDf_NUM(cellJitter); static SIMDf SIMDf_NUM(F3); static SIMDf SIMDf_NUM(G3); static SIMDf SIMDf_NUM(G33); static SIMDf SIMDf_NUM(hash2Float); static SIMDf SIMDf_NUM(vectorSize); static SIMDf SIMDf_NUM(cubicBounding); #if SIMD_LEVEL == FN_AVX512 static SIMDf SIMDf_NUM(X_GRAD); static SIMDf SIMDf_NUM(Y_GRAD); static SIMDf SIMDf_NUM(Z_GRAD); #else static SIMDi SIMDi_NUM(8); static SIMDi SIMDi_NUM(12); static SIMDi SIMDi_NUM(13); #endif static SIMDi SIMDi_NUM(incremental); static SIMDi SIMDi_NUM(1); static SIMDi SIMDi_NUM(2); static SIMDi SIMDi_NUM(255); static SIMDi SIMDi_NUM(60493); static SIMDi SIMDi_NUM(0x7fffffff); //static SIMDi SIMDi_NUM(xGradBits); //static SIMDi SIMDi_NUM(yGradBits); //static SIMDi SIMDi_NUM(zGradBits); static SIMDi SIMDi_NUM(xPrime); static SIMDi SIMDi_NUM(yPrime); static SIMDi SIMDi_NUM(zPrime); static SIMDi SIMDi_NUM(bit5Mask); static SIMDi SIMDi_NUM(bit10Mask); static SIMDi SIMDi_NUM(vectorSize); void FUNC(InitSIMDValues)() { if (VAR(SIMD_Values_Set)) return; uSIMDf incF; uSIMDi incI; for (int i = 0; i < VECTOR_SIZE; i++) { incF.a[i] = float(i); incI.a[i] = i; } SIMDf_NUM(incremental) = incF.m; SIMDi_NUM(incremental) = incI.m; SIMDf_NUM(0) = SIMDf_SET_ZERO(); SIMDf_NUM(1) = SIMDf_SET(1.0f); SIMDf_NUM(2) = SIMDf_SET(2.0f); SIMDf_NUM(6) = SIMDf_SET(6.0f); SIMDf_NUM(10) = SIMDf_SET(10.0f); SIMDf_NUM(15) = SIMDf_SET(15.0f); SIMDf_NUM(32) = SIMDf_SET(32.0f); SIMDf_NUM(999999) = SIMDf_SET(999999.0f); SIMDf_NUM(0_5) = SIMDf_SET(0.5f); SIMDf_NUM(0_6) = SIMDf_SET(0.6f); SIMDf_NUM(15_5) = SIMDf_SET(15.5f); SIMDf_NUM(511_5) = SIMDf_SET(511.5f); //SIMDf_NUM(cellJitter) = SIMDf_SET(0.39614f); SIMDf_NUM(F3) = SIMDf_SET(1.f / 3.f); SIMDf_NUM(G3) = SIMDf_SET(1.f / 6.f); SIMDf_NUM(G33) = SIMDf_SET((3.f / 6.f) - 1.f); SIMDf_NUM(hash2Float) = SIMDf_SET(1.f / 2147483648.f); SIMDf_NUM(vectorSize) = SIMDf_SET(VECTOR_SIZE); SIMDf_NUM(cubicBounding) = SIMDf_SET(1.f / (1.5f*1.5f*1.5f)); #if SIMD_LEVEL == FN_AVX512 SIMDf_NUM(X_GRAD) = _mm512_set_ps(0, -1, 0, 1, 0, 0, 0, 0, -1, 1, -1, 1, -1, 1, -1, 1); SIMDf_NUM(Y_GRAD) = _mm512_set_ps(-1, 1, -1, 1, -1, 1, -1, 1, 0, 0, 0, 0, -1, -1, 1, 1); SIMDf_NUM(Z_GRAD) = _mm512_set_ps(-1, 0, 1, 0, -1, -1, 1, 1, -1, -1, 1, 1, 0, 0, 0, 0); #else SIMDi_NUM(8) = SIMDi_SET(8); SIMDi_NUM(12) = SIMDi_SET(12); SIMDi_NUM(13) = SIMDi_SET(13); #endif SIMDi_NUM(1) = SIMDi_SET(1); SIMDi_NUM(2) = SIMDi_SET(2); SIMDi_NUM(255) = SIMDi_SET(255); SIMDi_NUM(60493) = SIMDi_SET(60493); SIMDi_NUM(0x7fffffff) = SIMDi_SET(0x7fffffff); //SIMDi_NUM(xGradBits) = SIMDi_SET(1683327112); //SIMDi_NUM(yGradBits) = SIMDi_SET(-2004331104); //SIMDi_NUM(zGradBits) = SIMDi_SET(-1851744171); SIMDi_NUM(xPrime) = SIMDi_SET(1619); SIMDi_NUM(yPrime) = SIMDi_SET(31337); SIMDi_NUM(zPrime) = SIMDi_SET(6971); SIMDi_NUM(bit5Mask) = SIMDi_SET(31); SIMDi_NUM(bit10Mask) = SIMDi_SET(1023); SIMDi_NUM(vectorSize) = SIMDi_SET(VECTOR_SIZE); SIMDi_NUM(0xffffffff) = SIMDi_SET(-1); VAR(SIMD_Values_Set) = true; } static SIMDf VECTORCALL FUNC(Lerp)(SIMDf a, SIMDf b, SIMDf t) { SIMDf r; r = SIMDf_SUB(b, a); r = SIMDf_MUL_ADD(r, t, a); return r; } static SIMDf VECTORCALL FUNC(InterpQuintic)(SIMDf t) { SIMDf r; r = SIMDf_MUL_SUB(t, SIMDf_NUM(6), SIMDf_NUM(15)); r = SIMDf_MUL_ADD(r, t, SIMDf_NUM(10)); r = SIMDf_MUL(r, t); r = SIMDf_MUL(r, t); r = SIMDf_MUL(r, t); return r; } static SIMDf VECTORCALL FUNC(CubicLerp)(SIMDf a, SIMDf b, SIMDf c, SIMDf d, SIMDf t) { SIMDf p = SIMDf_SUB(SIMDf_SUB(d, c), SIMDf_SUB(a, b)); return SIMDf_MUL_ADD(t, SIMDf_MUL(t, SIMDf_MUL(t, p)), SIMDf_MUL_ADD(t, SIMDf_MUL(t, SIMDf_SUB(SIMDf_SUB(a, b), p)), SIMDf_MUL_ADD(t, SIMDf_SUB(c, a), b))); } //static SIMDf VECTORCALL FUNC(InterpHermite)(SIMDf t) //{ // SIMDf r; // r = SIMDf_MUL(t, SIMDf_NUM(2)); // r = SIMDf_SUB(SIMDf_ADD(SIMDf_NUM(1), SIMDf_NUM(2)), r); // r = SIMDf_MUL(r, t); // r = SIMDf_MUL(r, t); // // return r; //} static SIMDi VECTORCALL FUNC(Hash)(SIMDi seed, SIMDi x, SIMDi y, SIMDi z) { SIMDi hash = seed; hash = SIMDi_XOR(x, hash); hash = SIMDi_XOR(y, hash); hash = SIMDi_XOR(z, hash); hash = SIMDi_MUL(SIMDi_MUL(SIMDi_MUL(hash, hash), SIMDi_NUM(60493)), hash); hash = SIMDi_XOR(SIMDi_SHIFT_R(hash, 13), hash); return hash; } static SIMDi VECTORCALL FUNC(HashHB)(SIMDi seed, SIMDi x, SIMDi y, SIMDi z) { SIMDi hash = seed; hash = SIMDi_XOR(x, hash); hash = SIMDi_XOR(y, hash); hash = SIMDi_XOR(z, hash); //hash = SIMDi_XOR(SIMDi_SHIFT_R(hash, 13), hash); hash = SIMDi_MUL(SIMDi_MUL(SIMDi_MUL(hash, hash), SIMDi_NUM(60493)), hash); return hash; } static SIMDf VECTORCALL FUNC(ValCoord)(SIMDi seed, SIMDi x, SIMDi y, SIMDi z) { // High bit hash SIMDi hash = seed; hash = SIMDi_XOR(x, hash); hash = SIMDi_XOR(y, hash); hash = SIMDi_XOR(z, hash); hash = SIMDi_MUL(SIMDi_MUL(SIMDi_MUL(hash, hash), SIMDi_NUM(60493)), hash); //hash = SIMDi_XOR(SIMDi_SHIFT_L(hash, 13), hash); return SIMDf_MUL(SIMDf_NUM(hash2Float), SIMDf_CONVERT_TO_FLOAT(hash)); } #if SIMD_LEVEL == FN_AVX512 static SIMDf VECTORCALL FUNC(GradCoord)(SIMDi seed, SIMDi xi, SIMDi yi, SIMDi zi, SIMDf x, SIMDf y, SIMDf z) { SIMDi hash = FUNC(Hash)(seed, xi, yi, zi); SIMDf xGrad = SIMDf_PERMUTE(SIMDf_NUM(X_GRAD), hash); SIMDf yGrad = SIMDf_PERMUTE(SIMDf_NUM(Y_GRAD), hash); SIMDf zGrad = SIMDf_PERMUTE(SIMDf_NUM(Z_GRAD), hash); return SIMDf_MUL_ADD(x, xGrad, SIMDf_MUL_ADD(y, yGrad, SIMDf_MUL(z, zGrad))); } #else static SIMDf VECTORCALL FUNC(GradCoord)(SIMDi seed, SIMDi xi, SIMDi yi, SIMDi zi, SIMDf x, SIMDf y, SIMDf z) { SIMDi hash = FUNC(Hash)(seed, xi, yi, zi); SIMDi hasha13 = SIMDi_AND(hash, SIMDi_NUM(13)); //if h < 8 then x, else y MASK l8 = SIMDi_LESS_THAN(hasha13, SIMDi_NUM(8)); SIMDf u = SIMDf_BLENDV(y, x, l8); //if h < 4 then y else if h is 12 or 14 then x else z MASK l4 = SIMDi_LESS_THAN(hasha13, SIMDi_NUM(2)); MASK h12o14 = SIMDi_EQUAL(SIMDi_NUM(12), hasha13); SIMDf v = SIMDf_BLENDV(SIMDf_BLENDV(z, x, h12o14), y, l4); //if h1 then -u else u //if h2 then -v else v SIMDf h1 = SIMDf_CAST_TO_FLOAT(SIMDi_SHIFT_L(hash, 31)); SIMDf h2 = SIMDf_CAST_TO_FLOAT(SIMDi_SHIFT_L(SIMDi_AND(hash, SIMDi_NUM(2)), 30)); //then add them return SIMDf_ADD(SIMDf_XOR(u, h1), SIMDf_XOR(v, h2)); } #endif static SIMDf VECTORCALL FUNC(WhiteNoiseSingle)(SIMDi seed, SIMDf x, SIMDf y, SIMDf z) { return FUNC(ValCoord)(seed, SIMDi_MUL(SIMDi_XOR(SIMDi_CAST_TO_INT(x), SIMDi_SHIFT_R(SIMDi_CAST_TO_INT(x), 16)), SIMDi_NUM(xPrime)), SIMDi_MUL(SIMDi_XOR(SIMDi_CAST_TO_INT(y), SIMDi_SHIFT_R(SIMDi_CAST_TO_INT(y), 16)), SIMDi_NUM(yPrime)), SIMDi_MUL(SIMDi_XOR(SIMDi_CAST_TO_INT(z), SIMDi_SHIFT_R(SIMDi_CAST_TO_INT(z), 16)), SIMDi_NUM(zPrime))); } static SIMDf VECTORCALL FUNC(ValueSingle)(SIMDi seed, SIMDf x, SIMDf y, SIMDf z) { SIMDf xs = SIMDf_FLOOR(x); SIMDf ys = SIMDf_FLOOR(y); SIMDf zs = SIMDf_FLOOR(z); SIMDi x0 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(xs), SIMDi_NUM(xPrime)); SIMDi y0 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(ys), SIMDi_NUM(yPrime)); SIMDi z0 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(zs), SIMDi_NUM(zPrime)); SIMDi x1 = SIMDi_ADD(x0, SIMDi_NUM(xPrime)); SIMDi y1 = SIMDi_ADD(y0, SIMDi_NUM(yPrime)); SIMDi z1 = SIMDi_ADD(z0, SIMDi_NUM(zPrime)); xs = FUNC(InterpQuintic)(SIMDf_SUB(x, xs)); ys = FUNC(InterpQuintic)(SIMDf_SUB(y, ys)); zs = FUNC(InterpQuintic)(SIMDf_SUB(z, zs)); return FUNC(Lerp)( FUNC(Lerp)( FUNC(Lerp)(FUNC(ValCoord)(seed, x0, y0, z0), FUNC(ValCoord)(seed, x1, y0, z0), xs), FUNC(Lerp)(FUNC(ValCoord)(seed, x0, y1, z0), FUNC(ValCoord)(seed, x1, y1, z0), xs), ys), FUNC(Lerp)( FUNC(Lerp)(FUNC(ValCoord)(seed, x0, y0, z1), FUNC(ValCoord)(seed, x1, y0, z1), xs), FUNC(Lerp)(FUNC(ValCoord)(seed, x0, y1, z1), FUNC(ValCoord)(seed, x1, y1, z1), xs), ys), zs); } static SIMDf VECTORCALL FUNC(PerlinSingle)(SIMDi seed, SIMDf x, SIMDf y, SIMDf z) { SIMDf xs = SIMDf_FLOOR(x); SIMDf ys = SIMDf_FLOOR(y); SIMDf zs = SIMDf_FLOOR(z); SIMDi x0 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(xs), SIMDi_NUM(xPrime)); SIMDi y0 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(ys), SIMDi_NUM(yPrime)); SIMDi z0 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(zs), SIMDi_NUM(zPrime)); SIMDi x1 = SIMDi_ADD(x0, SIMDi_NUM(xPrime)); SIMDi y1 = SIMDi_ADD(y0, SIMDi_NUM(yPrime)); SIMDi z1 = SIMDi_ADD(z0, SIMDi_NUM(zPrime)); SIMDf xf0 = xs = SIMDf_SUB(x, xs); SIMDf yf0 = ys = SIMDf_SUB(y, ys); SIMDf zf0 = zs = SIMDf_SUB(z, zs); SIMDf xf1 = SIMDf_SUB(xf0, SIMDf_NUM(1)); SIMDf yf1 = SIMDf_SUB(yf0, SIMDf_NUM(1)); SIMDf zf1 = SIMDf_SUB(zf0, SIMDf_NUM(1)); xs = FUNC(InterpQuintic)(xs); ys = FUNC(InterpQuintic)(ys); zs = FUNC(InterpQuintic)(zs); return FUNC(Lerp)( FUNC(Lerp)( FUNC(Lerp)(FUNC(GradCoord)(seed, x0, y0, z0, xf0, yf0, zf0), FUNC(GradCoord)(seed, x1, y0, z0, xf1, yf0, zf0), xs), FUNC(Lerp)(FUNC(GradCoord)(seed, x0, y1, z0, xf0, yf1, zf0), FUNC(GradCoord)(seed, x1, y1, z0, xf1, yf1, zf0), xs), ys), FUNC(Lerp)( FUNC(Lerp)(FUNC(GradCoord)(seed, x0, y0, z1, xf0, yf0, zf1), FUNC(GradCoord)(seed, x1, y0, z1, xf1, yf0, zf1), xs), FUNC(Lerp)(FUNC(GradCoord)(seed, x0, y1, z1, xf0, yf1, zf1), FUNC(GradCoord)(seed, x1, y1, z1, xf1, yf1, zf1), xs), ys), zs); } static SIMDf VECTORCALL FUNC(SimplexSingle)(SIMDi seed, SIMDf x, SIMDf y, SIMDf z) { SIMDf f = SIMDf_MUL(SIMDf_NUM(F3), SIMDf_ADD(SIMDf_ADD(x, y), z)); SIMDf x0 = SIMDf_FLOOR(SIMDf_ADD(x, f)); SIMDf y0 = SIMDf_FLOOR(SIMDf_ADD(y, f)); SIMDf z0 = SIMDf_FLOOR(SIMDf_ADD(z, f)); SIMDi i = SIMDi_MUL(SIMDi_CONVERT_TO_INT(x0), SIMDi_NUM(xPrime)); SIMDi j = SIMDi_MUL(SIMDi_CONVERT_TO_INT(y0), SIMDi_NUM(yPrime)); SIMDi k = SIMDi_MUL(SIMDi_CONVERT_TO_INT(z0), SIMDi_NUM(zPrime)); SIMDf g = SIMDf_MUL(SIMDf_NUM(G3), SIMDf_ADD(SIMDf_ADD(x0, y0), z0)); x0 = SIMDf_SUB(x, SIMDf_SUB(x0, g)); y0 = SIMDf_SUB(y, SIMDf_SUB(y0, g)); z0 = SIMDf_SUB(z, SIMDf_SUB(z0, g)); MASK x0_ge_y0 = SIMDf_GREATER_EQUAL(x0, y0); MASK y0_ge_z0 = SIMDf_GREATER_EQUAL(y0, z0); MASK x0_ge_z0 = SIMDf_GREATER_EQUAL(x0, z0); MASK i1 = MASK_AND(x0_ge_y0, x0_ge_z0); MASK j1 = MASK_AND_NOT(x0_ge_y0, y0_ge_z0); MASK k1 = MASK_AND_NOT(x0_ge_z0, MASK_NOT(y0_ge_z0)); MASK i2 = MASK_OR(x0_ge_y0, x0_ge_z0); MASK j2 = MASK_OR(MASK_NOT(x0_ge_y0), y0_ge_z0); MASK k2 = MASK_NOT(MASK_AND(x0_ge_z0, y0_ge_z0)); SIMDf x1 = SIMDf_ADD(SIMDf_MASK_SUB(i1, x0, SIMDf_NUM(1)), SIMDf_NUM(G3)); SIMDf y1 = SIMDf_ADD(SIMDf_MASK_SUB(j1, y0, SIMDf_NUM(1)), SIMDf_NUM(G3)); SIMDf z1 = SIMDf_ADD(SIMDf_MASK_SUB(k1, z0, SIMDf_NUM(1)), SIMDf_NUM(G3)); SIMDf x2 = SIMDf_ADD(SIMDf_MASK_SUB(i2, x0, SIMDf_NUM(1)), SIMDf_NUM(F3)); SIMDf y2 = SIMDf_ADD(SIMDf_MASK_SUB(j2, y0, SIMDf_NUM(1)), SIMDf_NUM(F3)); SIMDf z2 = SIMDf_ADD(SIMDf_MASK_SUB(k2, z0, SIMDf_NUM(1)), SIMDf_NUM(F3)); SIMDf x3 = SIMDf_ADD(x0, SIMDf_NUM(G33)); SIMDf y3 = SIMDf_ADD(y0, SIMDf_NUM(G33)); SIMDf z3 = SIMDf_ADD(z0, SIMDf_NUM(G33)); SIMDf t0 = SIMDf_NMUL_ADD(z0, z0, SIMDf_NMUL_ADD(y0, y0, SIMDf_NMUL_ADD(x0, x0, SIMDf_NUM(0_6)))); SIMDf t1 = SIMDf_NMUL_ADD(z1, z1, SIMDf_NMUL_ADD(y1, y1, SIMDf_NMUL_ADD(x1, x1, SIMDf_NUM(0_6)))); SIMDf t2 = SIMDf_NMUL_ADD(z2, z2, SIMDf_NMUL_ADD(y2, y2, SIMDf_NMUL_ADD(x2, x2, SIMDf_NUM(0_6)))); SIMDf t3 = SIMDf_NMUL_ADD(z3, z3, SIMDf_NMUL_ADD(y3, y3, SIMDf_NMUL_ADD(x3, x3, SIMDf_NUM(0_6)))); MASK n0 = SIMDf_GREATER_EQUAL(t0, SIMDf_NUM(0)); MASK n1 = SIMDf_GREATER_EQUAL(t1, SIMDf_NUM(0)); MASK n2 = SIMDf_GREATER_EQUAL(t2, SIMDf_NUM(0)); MASK n3 = SIMDf_GREATER_EQUAL(t3, SIMDf_NUM(0)); t0 = SIMDf_MUL(t0, t0); t1 = SIMDf_MUL(t1, t1); t2 = SIMDf_MUL(t2, t2); t3 = SIMDf_MUL(t3, t3); SIMDf v0 = SIMDf_MUL(SIMDf_MUL(t0, t0), FUNC(GradCoord)(seed, i, j, k, x0, y0, z0)); SIMDf v1 = SIMDf_MUL(SIMDf_MUL(t1, t1), FUNC(GradCoord)(seed, SIMDi_MASK_ADD(i1, i, SIMDi_NUM(xPrime)), SIMDi_MASK_ADD(j1, j, SIMDi_NUM(yPrime)), SIMDi_MASK_ADD(k1, k, SIMDi_NUM(zPrime)), x1, y1, z1)); SIMDf v2 = SIMDf_MUL(SIMDf_MUL(t2, t2), FUNC(GradCoord)(seed, SIMDi_MASK_ADD(i2, i, SIMDi_NUM(xPrime)), SIMDi_MASK_ADD(j2, j, SIMDi_NUM(yPrime)), SIMDi_MASK_ADD(k2, k, SIMDi_NUM(zPrime)), x2, y2, z2)); SIMDf v3 = SIMDf_MASK(n3, SIMDf_MUL(SIMDf_MUL(t3, t3), FUNC(GradCoord)(seed, SIMDi_ADD(i, SIMDi_NUM(xPrime)), SIMDi_ADD(j, SIMDi_NUM(yPrime)), SIMDi_ADD(k, SIMDi_NUM(zPrime)), x3, y3, z3))); return SIMDf_MUL(SIMDf_NUM(32), SIMDf_MASK_ADD(n0, SIMDf_MASK_ADD(n1, SIMDf_MASK_ADD(n2, v3, v2), v1), v0)); } static SIMDf VECTORCALL FUNC(CubicSingle)(SIMDi seed, SIMDf x, SIMDf y, SIMDf z) { SIMDf xf1 = SIMDf_FLOOR(x); SIMDf yf1 = SIMDf_FLOOR(y); SIMDf zf1 = SIMDf_FLOOR(z); SIMDi x1 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(xf1), SIMDi_NUM(xPrime)); SIMDi y1 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(yf1), SIMDi_NUM(yPrime)); SIMDi z1 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(zf1), SIMDi_NUM(zPrime)); SIMDi x0 = SIMDi_SUB(x1, SIMDi_NUM(xPrime)); SIMDi y0 = SIMDi_SUB(y1, SIMDi_NUM(yPrime)); SIMDi z0 = SIMDi_SUB(z1, SIMDi_NUM(zPrime)); SIMDi x2 = SIMDi_ADD(x1, SIMDi_NUM(xPrime)); SIMDi y2 = SIMDi_ADD(y1, SIMDi_NUM(yPrime)); SIMDi z2 = SIMDi_ADD(z1, SIMDi_NUM(zPrime)); SIMDi x3 = SIMDi_ADD(x2, SIMDi_NUM(xPrime)); SIMDi y3 = SIMDi_ADD(y2, SIMDi_NUM(yPrime)); SIMDi z3 = SIMDi_ADD(z2, SIMDi_NUM(zPrime)); SIMDf xs = SIMDf_SUB(x, xf1); SIMDf ys = SIMDf_SUB(y, yf1); SIMDf zs = SIMDf_SUB(z, zf1); return SIMDf_MUL(FUNC(CubicLerp)( FUNC(CubicLerp)( FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y0, z0), FUNC(ValCoord)(seed, x1, y0, z0), FUNC(ValCoord)(seed, x2, y0, z0), FUNC(ValCoord)(seed, x3, y0, z0), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y1, z0), FUNC(ValCoord)(seed, x1, y1, z0), FUNC(ValCoord)(seed, x2, y1, z0), FUNC(ValCoord)(seed, x3, y1, z0), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y2, z0), FUNC(ValCoord)(seed, x1, y2, z0), FUNC(ValCoord)(seed, x2, y2, z0), FUNC(ValCoord)(seed, x3, y2, z0), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y3, z0), FUNC(ValCoord)(seed, x1, y3, z0), FUNC(ValCoord)(seed, x2, y3, z0), FUNC(ValCoord)(seed, x3, y3, z0), xs), ys), FUNC(CubicLerp)( FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y0, z1), FUNC(ValCoord)(seed, x1, y0, z1), FUNC(ValCoord)(seed, x2, y0, z1), FUNC(ValCoord)(seed, x3, y0, z1), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y1, z1), FUNC(ValCoord)(seed, x1, y1, z1), FUNC(ValCoord)(seed, x2, y1, z1), FUNC(ValCoord)(seed, x3, y1, z1), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y2, z1), FUNC(ValCoord)(seed, x1, y2, z1), FUNC(ValCoord)(seed, x2, y2, z1), FUNC(ValCoord)(seed, x3, y2, z1), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y3, z1), FUNC(ValCoord)(seed, x1, y3, z1), FUNC(ValCoord)(seed, x2, y3, z1), FUNC(ValCoord)(seed, x3, y3, z1), xs), ys), FUNC(CubicLerp)( FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y0, z2), FUNC(ValCoord)(seed, x1, y0, z2), FUNC(ValCoord)(seed, x2, y0, z2), FUNC(ValCoord)(seed, x3, y0, z2), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y1, z2), FUNC(ValCoord)(seed, x1, y1, z2), FUNC(ValCoord)(seed, x2, y1, z2), FUNC(ValCoord)(seed, x3, y1, z2), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y2, z2), FUNC(ValCoord)(seed, x1, y2, z2), FUNC(ValCoord)(seed, x2, y2, z2), FUNC(ValCoord)(seed, x3, y2, z2), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y3, z2), FUNC(ValCoord)(seed, x1, y3, z2), FUNC(ValCoord)(seed, x2, y3, z2), FUNC(ValCoord)(seed, x3, y3, z2), xs), ys), FUNC(CubicLerp)( FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y0, z3), FUNC(ValCoord)(seed, x1, y0, z3), FUNC(ValCoord)(seed, x2, y0, z3), FUNC(ValCoord)(seed, x3, y0, z3), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y1, z3), FUNC(ValCoord)(seed, x1, y1, z3), FUNC(ValCoord)(seed, x2, y1, z3), FUNC(ValCoord)(seed, x3, y1, z3), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y2, z3), FUNC(ValCoord)(seed, x1, y2, z3), FUNC(ValCoord)(seed, x2, y2, z3), FUNC(ValCoord)(seed, x3, y2, z3), xs), FUNC(CubicLerp)(FUNC(ValCoord)(seed, x0, y3, z3), FUNC(ValCoord)(seed, x1, y3, z3), FUNC(ValCoord)(seed, x2, y3, z3), FUNC(ValCoord)(seed, x3, y3, z3), xs), ys), zs), SIMDf_NUM(cubicBounding)); } #define GRADIENT_COORD(_x,_y,_z)\ SIMDi hash##_x##_y##_z = FUNC(HashHB)(seed, x##_x, y##_y, z##_z); \ SIMDf x##_x##_y##_z = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(hash##_x##_y##_z, SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5)); \ SIMDf y##_x##_y##_z = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash##_x##_y##_z, 10), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5)); \ SIMDf z##_x##_y##_z = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash##_x##_y##_z, 20), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5)); //SIMDf invMag##_x##_y##_z = SIMDf_MUL(SIMDf_NUM(cellJitter), SIMDf_INV_SQRT(SIMDf_MUL_ADD(x##_x##_y##_z, x##_x##_y##_z, SIMDf_MUL_ADD(y##_x##_y##_z, y##_x##_y##_z, SIMDf_MUL(z##_x##_y##_z, z##_x##_y##_z))))); //x##_x##_y##_z = SIMDf_MUL(x##_x##_y##_z, invMag##_x##_y##_z); //y##_x##_y##_z = SIMDf_MUL(y##_x##_y##_z, invMag##_x##_y##_z); //z##_x##_y##_z = SIMDf_MUL(z##_x##_y##_z, invMag##_x##_y##_z); static void VECTORCALL FUNC(GradientPerturbSingle)(SIMDi seed, SIMDf perturbAmp, SIMDf perturbFrequency, SIMDf& x, SIMDf& y, SIMDf& z) { SIMDf xf = SIMDf_MUL(x, perturbFrequency); SIMDf yf = SIMDf_MUL(y, perturbFrequency); SIMDf zf = SIMDf_MUL(z, perturbFrequency); SIMDf xs = SIMDf_FLOOR(xf); SIMDf ys = SIMDf_FLOOR(yf); SIMDf zs = SIMDf_FLOOR(zf); SIMDi x0 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(xs), SIMDi_NUM(xPrime)); SIMDi y0 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(ys), SIMDi_NUM(yPrime)); SIMDi z0 = SIMDi_MUL(SIMDi_CONVERT_TO_INT(zs), SIMDi_NUM(zPrime)); SIMDi x1 = SIMDi_ADD(x0, SIMDi_NUM(xPrime)); SIMDi y1 = SIMDi_ADD(y0, SIMDi_NUM(yPrime)); SIMDi z1 = SIMDi_ADD(z0, SIMDi_NUM(zPrime)); xs = FUNC(InterpQuintic)(SIMDf_SUB(xf, xs)); ys = FUNC(InterpQuintic)(SIMDf_SUB(yf, ys)); zs = FUNC(InterpQuintic)(SIMDf_SUB(zf, zs)); GRADIENT_COORD(0, 0, 0); GRADIENT_COORD(0, 0, 1); GRADIENT_COORD(0, 1, 0); GRADIENT_COORD(0, 1, 1); GRADIENT_COORD(1, 0, 0); GRADIENT_COORD(1, 0, 1); GRADIENT_COORD(1, 1, 0); GRADIENT_COORD(1, 1, 1); SIMDf x0y = FUNC(Lerp)(FUNC(Lerp)(x000, x100, xs), FUNC(Lerp)(x010, x110, xs), ys); SIMDf y0y = FUNC(Lerp)(FUNC(Lerp)(y000, y100, xs), FUNC(Lerp)(y010, y110, xs), ys); SIMDf z0y = FUNC(Lerp)(FUNC(Lerp)(z000, z100, xs), FUNC(Lerp)(z010, z110, xs), ys); SIMDf x1y = FUNC(Lerp)(FUNC(Lerp)(x001, x101, xs), FUNC(Lerp)(x011, x111, xs), ys); SIMDf y1y = FUNC(Lerp)(FUNC(Lerp)(y001, y101, xs), FUNC(Lerp)(y011, y111, xs), ys); SIMDf z1y = FUNC(Lerp)(FUNC(Lerp)(z001, z101, xs), FUNC(Lerp)(z011, z111, xs), ys); x = SIMDf_MUL_ADD(FUNC(Lerp)(x0y, x1y, zs), perturbAmp, x); y = SIMDf_MUL_ADD(FUNC(Lerp)(y0y, y1y, zs), perturbAmp, y); z = SIMDf_MUL_ADD(FUNC(Lerp)(z0y, z1y, zs), perturbAmp, z); } SIMD_LEVEL_CLASS::FASTNOISE_SIMD_CLASS(SIMD_LEVEL)(int seed) { m_seed = seed; m_fractalBounding = CalculateFractalBounding(m_octaves, m_gain); m_perturbFractalBounding = CalculateFractalBounding(m_perturbOctaves, m_perturbGain); FUNC(InitSIMDValues)(); s_currentSIMDLevel = SIMD_LEVEL; } int SIMD_LEVEL_CLASS::AlignedSize(int size) { #ifdef FN_ALIGNED_SETS // size must be a multiple of VECTOR_SIZE (8) if ((size & (VECTOR_SIZE - 1)) != 0) { size &= ~(VECTOR_SIZE - 1); size += VECTOR_SIZE; } #endif return size; } float* SIMD_LEVEL_CLASS::GetEmptySet(int size) { size = AlignedSize(size); float* noiseSet; SIMD_ALLOCATE_SET(noiseSet, size); return noiseSet; } #define AXIS_RESET(_zSize, _start) for (int _i = (_zSize) * (_start); _i < VECTOR_SIZE; _i+=(_zSize)){\ MASK _zReset = SIMDi_GREATER_THAN(z, zEndV);\ y = SIMDi_MASK_ADD(_zReset, y, SIMDi_NUM(1));\ z = SIMDi_MASK_SUB(_zReset, z, zSizeV);\ \ MASK _yReset = SIMDi_GREATER_THAN(y, yEndV);\ x = SIMDi_MASK_ADD(_yReset, x, SIMDi_NUM(1));\ y = SIMDi_MASK_SUB(_yReset, y, ySizeV);} #ifdef FN_ALIGNED_SETS #define STORE_LAST_RESULT(_dest, _source) SIMDf_STORE(_dest, _source) #else #include <cstring> #define STORE_LAST_RESULT(_dest, _source) std::memcpy(_dest, &_source, (maxIndex - index) * 4) #endif #define INIT_PERTURB_VALUES() \ SIMDf perturbAmpV, perturbFreqV, perturbLacunarityV, perturbGainV, perturbNormaliseLengthV;\ switch (m_perturbType)\ {\ case None:\ break;\ case Gradient_Normalise:\ perturbNormaliseLengthV = SIMDf_SET(m_perturbNormaliseLength*m_frequency);\ case Gradient:\ perturbAmpV = SIMDf_SET(m_perturbAmp);\ perturbFreqV = SIMDf_SET(m_perturbFrequency);\ break;\ case GradientFractal_Normalise:\ perturbNormaliseLengthV = SIMDf_SET(m_perturbNormaliseLength*m_frequency);\ case GradientFractal:\ perturbAmpV = SIMDf_SET(m_perturbAmp*m_fractalBounding);\ perturbFreqV = SIMDf_SET(m_perturbFrequency);\ perturbLacunarityV = SIMDf_SET(m_perturbLacunarity);\ perturbGainV = SIMDf_SET(m_perturbGain);\ break;\ case Normalise:\ perturbNormaliseLengthV = SIMDf_SET(m_perturbNormaliseLength*m_frequency);\ break;\ } #define PERTURB_SWITCH()\ switch (m_perturbType)\ {\ case None:\ break;\ case Gradient:\ FUNC(GradientPerturbSingle)(SIMDi_SUB(seedV, SIMDi_NUM(1)), perturbAmpV, perturbFreqV, xF, yF, zF); \ break; \ case GradientFractal:\ {\ SIMDi seedF = SIMDi_SUB(seedV, SIMDi_NUM(1));\ SIMDf freqF = perturbFreqV;\ SIMDf ampF = perturbAmpV;\ \ FUNC(GradientPerturbSingle)(seedF, ampF, freqF, xF, yF, zF);\ \ int octaveIndex = 0;\ \ while (++octaveIndex < m_perturbOctaves)\ {\ freqF = SIMDf_MUL(freqF, perturbLacunarityV);\ seedF = SIMDi_SUB(seedF, SIMDi_NUM(1));\ ampF = SIMDf_MUL(ampF, perturbGainV);\ \ FUNC(GradientPerturbSingle)(seedF, ampF, freqF, xF, yF, zF);\ }}\ break;\ case Gradient_Normalise:\ FUNC(GradientPerturbSingle)(SIMDi_SUB(seedV, SIMDi_NUM(1)), perturbAmpV, perturbFreqV, xF, yF, zF); \ case Normalise:\ {\ SIMDf invMag = SIMDf_MUL(perturbNormaliseLengthV, SIMDf_INV_SQRT(SIMDf_MUL_ADD(xF, xF, SIMDf_MUL_ADD(yF, yF, SIMDf_MUL(zF, zF)))));\ xF = SIMDf_MUL(xF, invMag);\ yF = SIMDf_MUL(yF, invMag);\ zF = SIMDf_MUL(zF, invMag);\ }break;\ case GradientFractal_Normalise:\ {\ SIMDi seedF = SIMDi_SUB(seedV, SIMDi_NUM(1));\ SIMDf freqF = perturbFreqV;\ SIMDf ampF = perturbAmpV;\ \ FUNC(GradientPerturbSingle)(seedF, ampF, freqF, xF, yF, zF);\ \ int octaveIndex = 0;\ \ while (++octaveIndex < m_perturbOctaves)\ {\ freqF = SIMDf_MUL(freqF, perturbLacunarityV);\ seedF = SIMDi_SUB(seedF, SIMDi_NUM(1));\ ampF = SIMDf_MUL(ampF, perturbGainV);\ \ FUNC(GradientPerturbSingle)(seedF, ampF, freqF, xF, yF, zF);\ }\ SIMDf invMag = SIMDf_MUL(perturbNormaliseLengthV, SIMDf_INV_SQRT(SIMDf_MUL_ADD(xF, xF, SIMDf_MUL_ADD(yF, yF, SIMDf_MUL(zF, zF)))));\ xF = SIMDf_MUL(xF, invMag);\ yF = SIMDf_MUL(yF, invMag);\ zF = SIMDf_MUL(zF, invMag);\ }break;\ } #define SET_BUILDER(f)\ if ((zSize & (VECTOR_SIZE - 1)) == 0)\ {\ SIMDi yBase = SIMDi_SET(yStart);\ SIMDi zBase = SIMDi_ADD(SIMDi_NUM(incremental), SIMDi_SET(zStart));\ \ SIMDi x = SIMDi_SET(xStart);\ \ int index = 0;\ \ for (int ix = 0; ix < xSize; ix++)\ {\ SIMDf xf = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(x), xFreqV);\ SIMDi y = yBase;\ \ for (int iy = 0; iy < ySize; iy++)\ {\ SIMDf yf = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(y), yFreqV);\ SIMDi z = zBase;\ SIMDf xF = xf;\ SIMDf yF = yf;\ SIMDf zF = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(z), zFreqV);\ \ PERTURB_SWITCH()\ SIMDf result;\ f;\ SIMDf_STORE(&noiseSet[index], result);\ \ int iz = VECTOR_SIZE;\ while (iz < zSize)\ {\ z = SIMDi_ADD(z, SIMDi_NUM(vectorSize));\ index += VECTOR_SIZE;\ iz += VECTOR_SIZE;\ xF = xf;\ yF = yf;\ zF = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(z), zFreqV);\ \ PERTURB_SWITCH()\ SIMDf result;\ f;\ SIMDf_STORE(&noiseSet[index], result);\ }\ index += VECTOR_SIZE;\ y = SIMDi_ADD(y, SIMDi_NUM(1));\ }\ x = SIMDi_ADD(x, SIMDi_NUM(1));\ }\ }\ else\ {\ SIMDi ySizeV = SIMDi_SET(ySize); \ SIMDi zSizeV = SIMDi_SET(zSize); \ \ SIMDi yEndV = SIMDi_SET(yStart + ySize - 1); \ SIMDi zEndV = SIMDi_SET(zStart + zSize - 1); \ \ SIMDi x = SIMDi_SET(xStart); \ SIMDi y = SIMDi_SET(yStart); \ SIMDi z = SIMDi_ADD(SIMDi_SET(zStart), SIMDi_NUM(incremental)); \ AXIS_RESET(zSize, 1)\ \ int index = 0; \ int maxIndex = xSize * ySize * zSize; \ \ for (; index < maxIndex - VECTOR_SIZE; index += VECTOR_SIZE)\ {\ SIMDf xF = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(x), xFreqV);\ SIMDf yF = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(y), yFreqV);\ SIMDf zF = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(z), zFreqV);\ \ PERTURB_SWITCH()\ SIMDf result;\ f;\ SIMDf_STORE(&noiseSet[index], result);\ \ z = SIMDi_ADD(z, SIMDi_NUM(vectorSize));\ \ AXIS_RESET(zSize, 0)\ }\ \ SIMDf xF = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(x), xFreqV);\ SIMDf yF = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(y), yFreqV);\ SIMDf zF = SIMDf_MUL(SIMDf_CONVERT_TO_FLOAT(z), zFreqV);\ \ PERTURB_SWITCH()\ SIMDf result;\ f;\ STORE_LAST_RESULT(&noiseSet[index], result);\ } // FBM SINGLE #define FBM_SINGLE(f)\ SIMDi seedF = seedV;\ \ result = FUNC(f##Single)(seedF, xF, yF, zF);\ \ SIMDf ampF = SIMDf_NUM(1);\ int octaveIndex = 0;\ \ while (++octaveIndex < m_octaves)\ {\ xF = SIMDf_MUL(xF, lacunarityV);\ yF = SIMDf_MUL(yF, lacunarityV);\ zF = SIMDf_MUL(zF, lacunarityV);\ seedF = SIMDi_ADD(seedF, SIMDi_NUM(1));\ \ ampF = SIMDf_MUL(ampF, gainV);\ result = SIMDf_MUL_ADD(FUNC(f##Single)(seedF, xF, yF, zF), ampF, result);\ }\ result = SIMDf_MUL(result, fractalBoundingV) // BILLOW SINGLE #define BILLOW_SINGLE(f)\ SIMDi seedF = seedV;\ \ result = SIMDf_MUL_SUB(SIMDf_ABS(FUNC(f##Single)(seedF, xF, yF, zF)), SIMDf_NUM(2), SIMDf_NUM(1));\ \ SIMDf ampF = SIMDf_NUM(1);\ int octaveIndex = 0;\ \ while (++octaveIndex < m_octaves)\ {\ xF = SIMDf_MUL(xF, lacunarityV);\ yF = SIMDf_MUL(yF, lacunarityV);\ zF = SIMDf_MUL(zF, lacunarityV);\ seedF = SIMDi_ADD(seedF, SIMDi_NUM(1));\ \ ampF = SIMDf_MUL(ampF, gainV);\ result = SIMDf_MUL_ADD(SIMDf_MUL_SUB(SIMDf_ABS(FUNC(f##Single)(seedF, xF, yF, zF)), SIMDf_NUM(2), SIMDf_NUM(1)), ampF, result);\ }\ result = SIMDf_MUL(result, fractalBoundingV) // RIGIDMULTI SINGLE #define RIGIDMULTI_SINGLE(f)\ SIMDi seedF = seedV;\ \ result = SIMDf_SUB(SIMDf_NUM(1), SIMDf_ABS(FUNC(f##Single)(seedF, xF, yF, zF)));\ \ SIMDf ampF = SIMDf_NUM(1);\ int octaveIndex = 0;\ \ while (++octaveIndex < m_octaves)\ {\ xF = SIMDf_MUL(xF, lacunarityV);\ yF = SIMDf_MUL(yF, lacunarityV);\ zF = SIMDf_MUL(zF, lacunarityV);\ seedF = SIMDi_ADD(seedF, SIMDi_NUM(1));\ \ ampF = SIMDf_MUL(ampF, gainV);\ result = SIMDf_NMUL_ADD(SIMDf_SUB(SIMDf_NUM(1), SIMDf_ABS(FUNC(f##Single)(seedF, xF, yF, zF))), ampF, result);\ } #define FILL_SET(func) \ void SIMD_LEVEL_CLASS::Fill##func##Set(float* noiseSet, int xStart, int yStart, int zStart, int xSize, int ySize, int zSize, float scaleModifier)\ {\ assert(noiseSet);\ SIMD_ZERO_ALL();\ SIMDi seedV = SIMDi_SET(m_seed); \ INIT_PERTURB_VALUES();\ \ scaleModifier *= m_frequency;\ \ SIMDf xFreqV = SIMDf_SET(scaleModifier * m_xScale);\ SIMDf yFreqV = SIMDf_SET(scaleModifier * m_yScale);\ SIMDf zFreqV = SIMDf_SET(scaleModifier * m_zScale);\ \ SET_BUILDER(result = FUNC(func##Single)(seedV, xF, yF, zF))\ \ SIMD_ZERO_ALL();\ } #define FILL_FRACTAL_SET(func) \ void SIMD_LEVEL_CLASS::Fill##func##FractalSet(float* noiseSet, int xStart, int yStart, int zStart, int xSize, int ySize, int zSize, float scaleModifier)\ {\ assert(noiseSet);\ SIMD_ZERO_ALL();\ \ SIMDi seedV = SIMDi_SET(m_seed);\ SIMDf lacunarityV = SIMDf_SET(m_lacunarity);\ SIMDf gainV = SIMDf_SET(m_gain);\ SIMDf fractalBoundingV = SIMDf_SET(m_fractalBounding);\ INIT_PERTURB_VALUES();\ \ scaleModifier *= m_frequency;\ \ SIMDf xFreqV = SIMDf_SET(scaleModifier * m_xScale);\ SIMDf yFreqV = SIMDf_SET(scaleModifier * m_yScale);\ SIMDf zFreqV = SIMDf_SET(scaleModifier * m_zScale);\ \ switch(m_fractalType)\ {\ case FBM:\ SET_BUILDER(FBM_SINGLE(func))\ break;\ case Billow:\ SET_BUILDER(BILLOW_SINGLE(func))\ break;\ case RigidMulti:\ SET_BUILDER(RIGIDMULTI_SINGLE(func))\ break;\ }\ SIMD_ZERO_ALL();\ } FILL_SET(Value) FILL_FRACTAL_SET(Value) FILL_SET(Perlin) FILL_FRACTAL_SET(Perlin) FILL_SET(Simplex) FILL_FRACTAL_SET(Simplex) //FILL_SET(WhiteNoise) FILL_SET(Cubic) FILL_FRACTAL_SET(Cubic) #ifdef FN_ALIGNED_SETS #define SIZE_MASK #define SAFE_LAST(f) #else #define SIZE_MASK & ~(VECTOR_SIZE - 1) #define SAFE_LAST(f)\ if (loopMax != vectorSet->size)\ {\ std::size_t remaining = (vectorSet->size - loopMax) * 4;\ \ SIMDf xF = SIMDf_LOAD(&vectorSet->xSet[loopMax]);\ SIMDf yF = SIMDf_LOAD(&vectorSet->ySet[loopMax]);\ SIMDf zF = SIMDf_LOAD(&vectorSet->zSet[loopMax]);\ \ xF = SIMDf_MUL_ADD(xF, xFreqV, xOffsetV);\ yF = SIMDf_MUL_ADD(yF, yFreqV, yOffsetV);\ zF = SIMDf_MUL_ADD(zF, zFreqV, zOffsetV);\ \ SIMDf result;\ f;\ std::memcpy(&noiseSet[index], &result, remaining);\ } #endif #define VECTOR_SET_BUILDER(f)\ while (index < loopMax)\ {\ SIMDf xF = SIMDf_MUL_ADD(SIMDf_LOAD(&vectorSet->xSet[index]), xFreqV, xOffsetV);\ SIMDf yF = SIMDf_MUL_ADD(SIMDf_LOAD(&vectorSet->ySet[index]), yFreqV, yOffsetV);\ SIMDf zF = SIMDf_MUL_ADD(SIMDf_LOAD(&vectorSet->zSet[index]), zFreqV, zOffsetV);\ \ PERTURB_SWITCH()\ SIMDf result;\ f;\ SIMDf_STORE(&noiseSet[index], result);\ index += VECTOR_SIZE;\ }\ SAFE_LAST(f) #define FILL_VECTOR_SET(func)\ void SIMD_LEVEL_CLASS::Fill##func##Set(float* noiseSet, FastNoiseVectorSet* vectorSet, float xOffset, float yOffset, float zOffset)\ {\ assert(noiseSet);\ assert(vectorSet);\ assert(vectorSet->size >= 0);\ SIMD_ZERO_ALL();\ \ SIMDi seedV = SIMDi_SET(m_seed);\ SIMDf xFreqV = SIMDf_SET(m_frequency * m_xScale);\ SIMDf yFreqV = SIMDf_SET(m_frequency * m_yScale);\ SIMDf zFreqV = SIMDf_SET(m_frequency * m_zScale);\ SIMDf xOffsetV = SIMDf_MUL(SIMDf_SET(xOffset), xFreqV);\ SIMDf yOffsetV = SIMDf_MUL(SIMDf_SET(yOffset), yFreqV);\ SIMDf zOffsetV = SIMDf_MUL(SIMDf_SET(zOffset), zFreqV);\ INIT_PERTURB_VALUES();\ \ int index = 0;\ int loopMax = vectorSet->size SIZE_MASK;\ \ VECTOR_SET_BUILDER(result = FUNC(func##Single)(seedV, xF, yF, zF))\ SIMD_ZERO_ALL();\ } #define FILL_FRACTAL_VECTOR_SET(func)\ void SIMD_LEVEL_CLASS::Fill##func##FractalSet(float* noiseSet, FastNoiseVectorSet* vectorSet, float xOffset, float yOffset, float zOffset)\ {\ assert(noiseSet);\ assert(vectorSet);\ assert(vectorSet->size >= 0);\ SIMD_ZERO_ALL();\ \ SIMDi seedV = SIMDi_SET(m_seed);\ SIMDf lacunarityV = SIMDf_SET(m_lacunarity);\ SIMDf gainV = SIMDf_SET(m_gain);\ SIMDf fractalBoundingV = SIMDf_SET(m_fractalBounding);\ SIMDf xFreqV = SIMDf_SET(m_frequency * m_xScale);\ SIMDf yFreqV = SIMDf_SET(m_frequency * m_yScale);\ SIMDf zFreqV = SIMDf_SET(m_frequency * m_zScale);\ SIMDf xOffsetV = SIMDf_MUL(SIMDf_SET(xOffset), xFreqV);\ SIMDf yOffsetV = SIMDf_MUL(SIMDf_SET(yOffset), yFreqV);\ SIMDf zOffsetV = SIMDf_MUL(SIMDf_SET(zOffset), zFreqV);\ INIT_PERTURB_VALUES();\ \ int index = 0;\ int loopMax = vectorSet->size SIZE_MASK;\ \ switch(m_fractalType)\ {\ case FBM:\ VECTOR_SET_BUILDER(FBM_SINGLE(func))\ break;\ case Billow:\ VECTOR_SET_BUILDER(BILLOW_SINGLE(func))\ break;\ case RigidMulti:\ VECTOR_SET_BUILDER(RIGIDMULTI_SINGLE(func))\ break;\ }\ SIMD_ZERO_ALL();\ } FILL_VECTOR_SET(Value) FILL_FRACTAL_VECTOR_SET(Value) FILL_VECTOR_SET(Perlin) FILL_FRACTAL_VECTOR_SET(Perlin) FILL_VECTOR_SET(Simplex) FILL_FRACTAL_VECTOR_SET(Simplex) FILL_VECTOR_SET(WhiteNoise) FILL_VECTOR_SET(Cubic) FILL_FRACTAL_VECTOR_SET(Cubic) void SIMD_LEVEL_CLASS::FillWhiteNoiseSet(float* noiseSet, int xStart, int yStart, int zStart, int xSize, int ySize, int zSize, float scaleModifier) { assert(noiseSet); SIMD_ZERO_ALL(); SIMDi seedV = SIMDi_SET(m_seed); if ((zSize & (VECTOR_SIZE - 1)) == 0) { SIMDi x = SIMDi_MUL(SIMDi_SET(xStart), SIMDi_NUM(xPrime)); SIMDi yBase = SIMDi_MUL(SIMDi_SET(yStart), SIMDi_NUM(yPrime)); SIMDi zBase = SIMDi_MUL(SIMDi_ADD(SIMDi_NUM(incremental), SIMDi_SET(zStart)), SIMDi_NUM(zPrime)); SIMDi zStep = SIMDi_MUL(SIMDi_NUM(vectorSize), SIMDi_NUM(zPrime)); int index = 0; for (int ix = 0; ix < xSize; ix++) { SIMDi y = yBase; for (int iy = 0; iy < ySize; iy++) { SIMDi z = zBase; SIMDf_STORE(&noiseSet[index], FUNC(ValCoord)(seedV, x, y, z)); int iz = VECTOR_SIZE; while (iz < zSize) { z = SIMDi_ADD(z, zStep); index += VECTOR_SIZE; iz += VECTOR_SIZE; SIMDf_STORE(&noiseSet[index], FUNC(ValCoord)(seedV, x, y, z)); } index += VECTOR_SIZE; y = SIMDi_ADD(y, SIMDi_NUM(yPrime)); } x = SIMDi_ADD(x, SIMDi_NUM(xPrime)); } } else { SIMDi ySizeV = SIMDi_SET(ySize); SIMDi zSizeV = SIMDi_SET(zSize); SIMDi yEndV = SIMDi_SET(yStart + ySize - 1); SIMDi zEndV = SIMDi_SET(zStart + zSize - 1); SIMDi x = SIMDi_SET(xStart); SIMDi y = SIMDi_SET(yStart); SIMDi z = SIMDi_ADD(SIMDi_SET(zStart), SIMDi_NUM(incremental)); AXIS_RESET(zSize, 1); int index = 0; int maxIndex = xSize * ySize * zSize; for (; index < maxIndex - VECTOR_SIZE; index += VECTOR_SIZE) { SIMDf_STORE(&noiseSet[index], FUNC(ValCoord)(seedV, SIMDi_MUL(x, SIMDi_NUM(xPrime)), SIMDi_MUL(y, SIMDi_NUM(yPrime)), SIMDi_MUL(z, SIMDi_NUM(zPrime)))); z = SIMDi_ADD(z, SIMDi_NUM(vectorSize)); AXIS_RESET(zSize, 0); } SIMDf result = FUNC(ValCoord)(seedV, SIMDi_MUL(x, SIMDi_NUM(xPrime)), SIMDi_MUL(y, SIMDi_NUM(yPrime)), SIMDi_MUL(z, SIMDi_NUM(zPrime))); STORE_LAST_RESULT(&noiseSet[index], result); } SIMD_ZERO_ALL(); } #define Euclidean_DISTANCE(_x, _y, _z) SIMDf_MUL_ADD(_x, _x, SIMDf_MUL_ADD(_y, _y, SIMDf_MUL(_z, _z))) #define Manhattan_DISTANCE(_x, _y, _z) SIMDf_ADD(SIMDf_ADD(SIMDf_ABS(_x), SIMDf_ABS(_y)), SIMDf_ABS(_z)) #define Natural_DISTANCE(_x, _y, _z) SIMDf_ADD(Euclidean_DISTANCE(_x,_y,_z), Manhattan_DISTANCE(_x,_y,_z)) #define Distance2_RETURN(_distance, _distance2) (_distance2) #define Distance2Add_RETURN(_distance, _distance2) SIMDf_ADD(_distance, _distance2) #define Distance2Sub_RETURN(_distance, _distance2) SIMDf_SUB(_distance2, _distance) #define Distance2Mul_RETURN(_distance, _distance2) SIMDf_MUL(_distance, _distance2) #define Distance2Div_RETURN(_distance, _distance2) SIMDf_DIV(_distance, _distance2) #define CELLULAR_VALUE_SINGLE(distanceFunc)\ static SIMDf VECTORCALL FUNC(CellularValue##distanceFunc##Single)(SIMDi seed, SIMDf x, SIMDf y, SIMDf z, SIMDf cellJitter)\ {\ SIMDf distance = SIMDf_NUM(999999);\ SIMDf cellValue = SIMDf_UNDEFINED();\ \ SIMDi xc = SIMDi_SUB(SIMDi_CONVERT_TO_INT(x), SIMDi_NUM(1));\ SIMDi ycBase = SIMDi_SUB(SIMDi_CONVERT_TO_INT(y), SIMDi_NUM(1));\ SIMDi zcBase = SIMDi_SUB(SIMDi_CONVERT_TO_INT(z), SIMDi_NUM(1));\ \ SIMDf xcf = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(xc), x);\ SIMDf ycfBase = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(ycBase), y);\ SIMDf zcfBase = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(zcBase), z);\ \ xc = SIMDi_MUL(xc, SIMDi_NUM(xPrime));\ ycBase = SIMDi_MUL(ycBase, SIMDi_NUM(yPrime));\ zcBase = SIMDi_MUL(zcBase, SIMDi_NUM(zPrime));\ \ for (int xi = 0; xi < 3; xi++)\ {\ SIMDf ycf = ycfBase;\ SIMDi yc = ycBase;\ for (int yi = 0; yi < 3; yi++)\ {\ SIMDf zcf = zcfBase;\ SIMDi zc = zcBase;\ for (int zi = 0; zi < 3; zi++)\ {\ SIMDi hash = FUNC(HashHB)(seed, xc, yc, zc);\ SIMDf xd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(hash, SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ SIMDf yd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash,10), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ SIMDf zd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash,20), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ \ SIMDf invMag = SIMDf_MUL(cellJitter, SIMDf_INV_SQRT(SIMDf_MUL_ADD(xd, xd, SIMDf_MUL_ADD(yd, yd, SIMDf_MUL(zd, zd)))));\ \ xd = SIMDf_MUL_ADD(xd, invMag, xcf);\ yd = SIMDf_MUL_ADD(yd, invMag, ycf);\ zd = SIMDf_MUL_ADD(zd, invMag, zcf);\ \ SIMDf newCellValue = SIMDf_MUL(SIMDf_NUM(hash2Float), SIMDf_CONVERT_TO_FLOAT(hash));\ SIMDf newDistance = distanceFunc##_DISTANCE(xd, yd, zd);\ \ MASK closer = SIMDf_LESS_THAN(newDistance, distance);\ \ distance = SIMDf_MIN(newDistance, distance);\ cellValue = SIMDf_BLENDV(cellValue, newCellValue, closer);\ \ zcf = SIMDf_ADD(zcf, SIMDf_NUM(1));\ zc = SIMDi_ADD(zc, SIMDi_NUM(zPrime));\ }\ ycf = SIMDf_ADD(ycf, SIMDf_NUM(1));\ yc = SIMDi_ADD(yc, SIMDi_NUM(yPrime));\ }\ xcf = SIMDf_ADD(xcf, SIMDf_NUM(1));\ xc = SIMDi_ADD(xc, SIMDi_NUM(xPrime));\ }\ \ return cellValue;\ } struct NoiseLookupSettings { FastNoiseSIMD::NoiseType type; SIMDf frequency; FastNoiseSIMD::FractalType fractalType; int fractalOctaves; SIMDf fractalLacunarity; SIMDf fractalGain; SIMDf fractalBounding; }; #define CELLULAR_LOOKUP_FRACTAL_VALUE(noiseType){\ SIMDf lacunarityV = noiseLookupSettings.fractalLacunarity;\ SIMDf gainV = noiseLookupSettings.fractalGain;\ SIMDf fractalBoundingV = noiseLookupSettings.fractalBounding;\ int m_octaves = noiseLookupSettings.fractalOctaves;\ switch(noiseLookupSettings.fractalType)\ {\ case FastNoiseSIMD::FBM:\ {FBM_SINGLE(noiseType);}\ break;\ case FastNoiseSIMD::Billow:\ {BILLOW_SINGLE(noiseType);}\ break;\ case FastNoiseSIMD::RigidMulti:\ {RIGIDMULTI_SINGLE(noiseType);}\ break;\ }}\ #define CELLULAR_LOOKUP_SINGLE(distanceFunc)\ static SIMDf VECTORCALL FUNC(CellularLookup##distanceFunc##Single)(SIMDi seedV, SIMDf x, SIMDf y, SIMDf z, SIMDf cellJitter, const NoiseLookupSettings& noiseLookupSettings)\ {\ SIMDf distance = SIMDf_NUM(999999);\ SIMDf xCell = SIMDf_UNDEFINED();\ SIMDf yCell = SIMDf_UNDEFINED();\ SIMDf zCell = SIMDf_UNDEFINED();\ \ SIMDi xc = SIMDi_SUB(SIMDi_CONVERT_TO_INT(x), SIMDi_NUM(1));\ SIMDi ycBase = SIMDi_SUB(SIMDi_CONVERT_TO_INT(y), SIMDi_NUM(1));\ SIMDi zcBase = SIMDi_SUB(SIMDi_CONVERT_TO_INT(z), SIMDi_NUM(1));\ \ SIMDf xcf = SIMDf_CONVERT_TO_FLOAT(xc);\ SIMDf ycfBase = SIMDf_CONVERT_TO_FLOAT(ycBase);\ SIMDf zcfBase = SIMDf_CONVERT_TO_FLOAT(zcBase);\ \ xc = SIMDi_MUL(xc, SIMDi_NUM(xPrime));\ ycBase = SIMDi_MUL(ycBase, SIMDi_NUM(yPrime));\ zcBase = SIMDi_MUL(zcBase, SIMDi_NUM(zPrime));\ \ for (int xi = 0; xi < 3; xi++)\ {\ SIMDf ycf = ycfBase;\ SIMDi yc = ycBase;\ SIMDf xLocal = SIMDf_SUB(xcf, x);\ for (int yi = 0; yi < 3; yi++)\ {\ SIMDf zcf = zcfBase;\ SIMDi zc = zcBase;\ SIMDf yLocal = SIMDf_SUB(ycf, y);\ for (int zi = 0; zi < 3; zi++)\ {\ SIMDf zLocal = SIMDf_SUB(zcf, z);\ \ SIMDi hash = FUNC(HashHB)(seedV, xc, yc, zc);\ SIMDf xd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(hash, SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ SIMDf yd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash,10), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ SIMDf zd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash,20), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ \ SIMDf invMag = SIMDf_MUL(cellJitter, SIMDf_INV_SQRT(SIMDf_MUL_ADD(xd, xd, SIMDf_MUL_ADD(yd, yd, SIMDf_MUL(zd, zd)))));\ \ SIMDf xCellNew = SIMDf_MUL(xd, invMag);\ SIMDf yCellNew = SIMDf_MUL(yd, invMag);\ SIMDf zCellNew = SIMDf_MUL(zd, invMag);\ \ xd = SIMDf_ADD(xCellNew, xLocal);\ yd = SIMDf_ADD(yCellNew, yLocal);\ zd = SIMDf_ADD(zCellNew, zLocal);\ \ xCellNew = SIMDf_ADD(xCellNew, xcf); \ yCellNew = SIMDf_ADD(yCellNew, ycf); \ zCellNew = SIMDf_ADD(zCellNew, zcf); \ \ SIMDf newDistance = distanceFunc##_DISTANCE(xd, yd, zd);\ \ MASK closer = SIMDf_LESS_THAN(newDistance, distance);\ \ distance = SIMDf_MIN(newDistance, distance);\ xCell = SIMDf_BLENDV(xCell, xCellNew, closer);\ yCell = SIMDf_BLENDV(yCell, yCellNew, closer);\ zCell = SIMDf_BLENDV(zCell, zCellNew, closer);\ \ zcf = SIMDf_ADD(zcf, SIMDf_NUM(1));\ zc = SIMDi_ADD(zc, SIMDi_NUM(zPrime));\ }\ ycf = SIMDf_ADD(ycf, SIMDf_NUM(1));\ yc = SIMDi_ADD(yc, SIMDi_NUM(yPrime));\ }\ xcf = SIMDf_ADD(xcf, SIMDf_NUM(1));\ xc = SIMDi_ADD(xc, SIMDi_NUM(xPrime));\ }\ \ SIMDf xF = SIMDf_MUL(xCell, noiseLookupSettings.frequency);\ SIMDf yF = SIMDf_MUL(yCell, noiseLookupSettings.frequency);\ SIMDf zF = SIMDf_MUL(zCell, noiseLookupSettings.frequency);\ SIMDf result;\ \ switch(noiseLookupSettings.type)\ {\ default:\ break;\ case FastNoiseSIMD::Value:\ result = FUNC(ValueSingle)(seedV, xF, yF, zF); \ break;\ case FastNoiseSIMD::ValueFractal:\ CELLULAR_LOOKUP_FRACTAL_VALUE(Value);\ break; \ case FastNoiseSIMD::Perlin:\ result = FUNC(PerlinSingle)(seedV, xF, yF, zF); \ break;\ case FastNoiseSIMD::PerlinFractal:\ CELLULAR_LOOKUP_FRACTAL_VALUE(Perlin);\ break; \ case FastNoiseSIMD::Simplex:\ result = FUNC(SimplexSingle)(seedV, xF, yF, zF); \ break;\ case FastNoiseSIMD::SimplexFractal:\ CELLULAR_LOOKUP_FRACTAL_VALUE(Simplex);\ break; \ case FastNoiseSIMD::Cubic:\ result = FUNC(CubicSingle)(seedV, xF, yF, zF); \ break;\ case FastNoiseSIMD::CubicFractal:\ CELLULAR_LOOKUP_FRACTAL_VALUE(Cubic);\ break; \ }\ \ return result;\ } #define CELLULAR_DISTANCE_SINGLE(distanceFunc)\ static SIMDf VECTORCALL FUNC(CellularDistance##distanceFunc##Single)(SIMDi seed, SIMDf x, SIMDf y, SIMDf z, SIMDf cellJitter)\ {\ SIMDf distance = SIMDf_NUM(999999);\ \ SIMDi xc = SIMDi_SUB(SIMDi_CONVERT_TO_INT(x), SIMDi_NUM(1));\ SIMDi ycBase = SIMDi_SUB(SIMDi_CONVERT_TO_INT(y), SIMDi_NUM(1));\ SIMDi zcBase = SIMDi_SUB(SIMDi_CONVERT_TO_INT(z), SIMDi_NUM(1));\ \ SIMDf xcf = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(xc), x);\ SIMDf ycfBase = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(ycBase), y);\ SIMDf zcfBase = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(zcBase), z);\ \ xc = SIMDi_MUL(xc, SIMDi_NUM(xPrime));\ ycBase = SIMDi_MUL(ycBase, SIMDi_NUM(yPrime));\ zcBase = SIMDi_MUL(zcBase, SIMDi_NUM(zPrime));\ \ for (int xi = 0; xi < 3; xi++)\ {\ SIMDf ycf = ycfBase;\ SIMDi yc = ycBase;\ for (int yi = 0; yi < 3; yi++)\ {\ SIMDf zcf = zcfBase;\ SIMDi zc = zcBase;\ for (int zi = 0; zi < 3; zi++)\ {\ SIMDi hash = FUNC(HashHB)(seed, xc, yc, zc);\ SIMDf xd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(hash, SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ SIMDf yd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash,10), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ SIMDf zd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash,20), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ \ SIMDf invMag = SIMDf_MUL(cellJitter, SIMDf_INV_SQRT(SIMDf_MUL_ADD(xd, xd, SIMDf_MUL_ADD(yd, yd, SIMDf_MUL(zd, zd)))));\ \ xd = SIMDf_MUL_ADD(xd, invMag, xcf);\ yd = SIMDf_MUL_ADD(yd, invMag, ycf);\ zd = SIMDf_MUL_ADD(zd, invMag, zcf);\ \ SIMDf newDistance = distanceFunc##_DISTANCE(xd, yd, zd);\ \ distance = SIMDf_MIN(distance, newDistance);\ \ zcf = SIMDf_ADD(zcf, SIMDf_NUM(1));\ zc = SIMDi_ADD(zc, SIMDi_NUM(zPrime));\ }\ ycf = SIMDf_ADD(ycf, SIMDf_NUM(1));\ yc = SIMDi_ADD(yc, SIMDi_NUM(yPrime));\ }\ xcf = SIMDf_ADD(xcf, SIMDf_NUM(1));\ xc = SIMDi_ADD(xc, SIMDi_NUM(xPrime));\ }\ \ return distance;\ } #define CELLULAR_DISTANCE2_SINGLE(distanceFunc, returnFunc)\ static SIMDf VECTORCALL FUNC(Cellular##returnFunc##distanceFunc##Single)(SIMDi seed, SIMDf x, SIMDf y, SIMDf z, SIMDf cellJitter, int index0, int index1)\ {\ SIMDf distance[4] = {SIMDf_NUM(999999),SIMDf_NUM(999999),SIMDf_NUM(999999),SIMDf_NUM(999999)};\ \ SIMDi xc = SIMDi_SUB(SIMDi_CONVERT_TO_INT(x), SIMDi_NUM(1));\ SIMDi ycBase = SIMDi_SUB(SIMDi_CONVERT_TO_INT(y), SIMDi_NUM(1));\ SIMDi zcBase = SIMDi_SUB(SIMDi_CONVERT_TO_INT(z), SIMDi_NUM(1));\ \ SIMDf xcf = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(xc), x);\ SIMDf ycfBase = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(ycBase), y);\ SIMDf zcfBase = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(zcBase), z);\ \ xc = SIMDi_MUL(xc, SIMDi_NUM(xPrime));\ ycBase = SIMDi_MUL(ycBase, SIMDi_NUM(yPrime));\ zcBase = SIMDi_MUL(zcBase, SIMDi_NUM(zPrime));\ \ for (int xi = 0; xi < 3; xi++)\ {\ SIMDf ycf = ycfBase;\ SIMDi yc = ycBase;\ for (int yi = 0; yi < 3; yi++)\ {\ SIMDf zcf = zcfBase;\ SIMDi zc = zcBase;\ for (int zi = 0; zi < 3; zi++)\ {\ SIMDi hash = FUNC(HashHB)(seed, xc, yc, zc);\ SIMDf xd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(hash, SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ SIMDf yd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash,10), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ SIMDf zd = SIMDf_SUB(SIMDf_CONVERT_TO_FLOAT(SIMDi_AND(SIMDi_SHIFT_R(hash,20), SIMDi_NUM(bit10Mask))), SIMDf_NUM(511_5));\ \ SIMDf invMag = SIMDf_MUL(cellJitter, SIMDf_INV_SQRT(SIMDf_MUL_ADD(xd, xd, SIMDf_MUL_ADD(yd, yd, SIMDf_MUL(zd, zd)))));\ \ xd = SIMDf_MUL_ADD(xd, invMag, xcf);\ yd = SIMDf_MUL_ADD(yd, invMag, ycf);\ zd = SIMDf_MUL_ADD(zd, invMag, zcf);\ \ SIMDf newDistance = distanceFunc##_DISTANCE(xd, yd, zd);\ \ for(int i = index1; i > 0; i--)\ distance[i] = SIMDf_MAX(SIMDf_MIN(distance[i], newDistance), distance[i-1]);\ distance[0] = SIMDf_MIN(distance[0], newDistance);\ \ zcf = SIMDf_ADD(zcf, SIMDf_NUM(1));\ zc = SIMDi_ADD(zc, SIMDi_NUM(zPrime));\ }\ ycf = SIMDf_ADD(ycf, SIMDf_NUM(1));\ yc = SIMDi_ADD(yc, SIMDi_NUM(yPrime));\ }\ xcf = SIMDf_ADD(xcf, SIMDf_NUM(1));\ xc = SIMDi_ADD(xc, SIMDi_NUM(xPrime));\ }\ \ return returnFunc##_RETURN(distance[index0], distance[index1]);\ } #define CELLULAR_DISTANCE2CAVE_SINGLE(distanceFunc)\ static SIMDf VECTORCALL FUNC(CellularDistance2Cave##distanceFunc##Single)(SIMDi seed, SIMDf x, SIMDf y, SIMDf z, SIMDf cellJitter, int index0, int index1)\ {\ SIMDf c0 = FUNC(CellularDistance2Div##distanceFunc##Single)(seed, x, y, z, cellJitter, index0, index1);\ \ x = SIMDf_ADD(x, SIMDf_NUM(0_5));\ y = SIMDf_ADD(y, SIMDf_NUM(0_5));\ z = SIMDf_ADD(z, SIMDf_NUM(0_5));\ seed = SIMDi_ADD(seed, SIMDi_NUM(1));\ \ SIMDf c1 = FUNC(CellularDistance2Div##distanceFunc##Single)(seed, x, y, z, cellJitter, index0, index1);\ \ return SIMDf_MIN(c0,c1);\ } CELLULAR_VALUE_SINGLE(Euclidean) CELLULAR_VALUE_SINGLE(Manhattan) CELLULAR_VALUE_SINGLE(Natural) CELLULAR_LOOKUP_SINGLE(Euclidean) CELLULAR_LOOKUP_SINGLE(Manhattan) CELLULAR_LOOKUP_SINGLE(Natural) #undef Natural_DISTANCE #define Natural_DISTANCE(_x, _y, _z) SIMDf_MUL(Euclidean_DISTANCE(_x,_y,_z), Manhattan_DISTANCE(_x,_y,_z)) CELLULAR_DISTANCE_SINGLE(Euclidean) CELLULAR_DISTANCE_SINGLE(Manhattan) CELLULAR_DISTANCE_SINGLE(Natural) #define CELLULAR_DISTANCE2_MULTI(returnFunc)\ CELLULAR_DISTANCE2_SINGLE(Euclidean, returnFunc)\ CELLULAR_DISTANCE2_SINGLE(Manhattan, returnFunc)\ CELLULAR_DISTANCE2_SINGLE(Natural, returnFunc) CELLULAR_DISTANCE2_MULTI(Distance2) CELLULAR_DISTANCE2_MULTI(Distance2Add) CELLULAR_DISTANCE2_MULTI(Distance2Sub) CELLULAR_DISTANCE2_MULTI(Distance2Div) CELLULAR_DISTANCE2_MULTI(Distance2Mul) CELLULAR_DISTANCE2CAVE_SINGLE(Euclidean) CELLULAR_DISTANCE2CAVE_SINGLE(Manhattan) CELLULAR_DISTANCE2CAVE_SINGLE(Natural) #define CELLULAR_MULTI(returnFunc)\ switch(m_cellularDistanceFunction)\ {\ case Euclidean:\ SET_BUILDER(result = FUNC(Cellular##returnFunc##EuclideanSingle)(seedV, xF, yF, zF, cellJitterV))\ break;\ case Manhattan:\ SET_BUILDER(result = FUNC(Cellular##returnFunc##ManhattanSingle)(seedV, xF, yF, zF, cellJitterV))\ break;\ case Natural:\ SET_BUILDER(result = FUNC(Cellular##returnFunc##NaturalSingle)(seedV, xF, yF, zF, cellJitterV))\ break;\ } #define CELLULAR_INDEX_MULTI(returnFunc)\ switch(m_cellularDistanceFunction)\ {\ case Euclidean:\ SET_BUILDER(result = FUNC(Cellular##returnFunc##EuclideanSingle)(seedV, xF, yF, zF, cellJitterV, m_cellularDistanceIndex0, m_cellularDistanceIndex1))\ break;\ case Manhattan:\ SET_BUILDER(result = FUNC(Cellular##returnFunc##ManhattanSingle)(seedV, xF, yF, zF, cellJitterV, m_cellularDistanceIndex0, m_cellularDistanceIndex1))\ break;\ case Natural:\ SET_BUILDER(result = FUNC(Cellular##returnFunc##NaturalSingle)(seedV, xF, yF, zF, cellJitterV, m_cellularDistanceIndex0, m_cellularDistanceIndex1))\ break;\ } void SIMD_LEVEL_CLASS::FillCellularSet(float* noiseSet, int xStart, int yStart, int zStart, int xSize, int ySize, int zSize, float scaleModifier) { assert(noiseSet); SIMD_ZERO_ALL(); SIMDi seedV = SIMDi_SET(m_seed); INIT_PERTURB_VALUES(); scaleModifier *= m_frequency; SIMDf xFreqV = SIMDf_SET(scaleModifier * m_xScale); SIMDf yFreqV = SIMDf_SET(scaleModifier * m_yScale); SIMDf zFreqV = SIMDf_SET(scaleModifier * m_zScale); SIMDf cellJitterV = SIMDf_SET(m_cellularJitter); NoiseLookupSettings nls; switch (m_cellularReturnType) { case CellValue: CELLULAR_MULTI(Value); break; case Distance: CELLULAR_MULTI(Distance); break; case Distance2: CELLULAR_INDEX_MULTI(Distance2); break; case Distance2Add: CELLULAR_INDEX_MULTI(Distance2Add); break; case Distance2Sub: CELLULAR_INDEX_MULTI(Distance2Sub); break; case Distance2Mul: CELLULAR_INDEX_MULTI(Distance2Mul); break; case Distance2Div: CELLULAR_INDEX_MULTI(Distance2Div); break; case Distance2Cave: CELLULAR_INDEX_MULTI(Distance2Cave); break; case NoiseLookup: nls.type = m_cellularNoiseLookupType; nls.frequency = SIMDf_SET(m_cellularNoiseLookupFrequency); nls.fractalType = m_fractalType; nls.fractalOctaves = m_octaves; nls.fractalLacunarity = SIMDf_SET(m_lacunarity); nls.fractalGain = SIMDf_SET(m_gain); nls.fractalBounding = SIMDf_SET(m_fractalBounding); switch (m_cellularDistanceFunction) { case Euclidean: SET_BUILDER(result = FUNC(CellularLookupEuclideanSingle)(seedV, xF, yF, zF, cellJitterV, nls)) break; \ case Manhattan: SET_BUILDER(result = FUNC(CellularLookupManhattanSingle)(seedV, xF, yF, zF, cellJitterV, nls)) break; \ case Natural: SET_BUILDER(result = FUNC(CellularLookupNaturalSingle)(seedV, xF, yF, zF, cellJitterV, nls)) break; } break; } SIMD_ZERO_ALL(); } #define CELLULAR_MULTI_VECTOR(returnFunc)\ switch(m_cellularDistanceFunction)\ {\ case Euclidean:\ VECTOR_SET_BUILDER(result = FUNC(Cellular##returnFunc##EuclideanSingle)(seedV, xF, yF, zF, cellJitterV))\ break;\ case Manhattan:\ VECTOR_SET_BUILDER(result = FUNC(Cellular##returnFunc##ManhattanSingle)(seedV, xF, yF, zF, cellJitterV))\ break;\ case Natural:\ VECTOR_SET_BUILDER(result = FUNC(Cellular##returnFunc##NaturalSingle)(seedV, xF, yF, zF, cellJitterV))\ break;\ } #define CELLULAR_INDEX_MULTI_VECTOR(returnFunc)\ switch(m_cellularDistanceFunction)\ {\ case Euclidean:\ VECTOR_SET_BUILDER(result = FUNC(Cellular##returnFunc##EuclideanSingle)(seedV, xF, yF, zF, cellJitterV, m_cellularDistanceIndex0, m_cellularDistanceIndex1))\ break;\ case Manhattan:\ VECTOR_SET_BUILDER(result = FUNC(Cellular##returnFunc##ManhattanSingle)(seedV, xF, yF, zF, cellJitterV, m_cellularDistanceIndex0, m_cellularDistanceIndex1))\ break;\ case Natural:\ VECTOR_SET_BUILDER(result = FUNC(Cellular##returnFunc##NaturalSingle)(seedV, xF, yF, zF, cellJitterV, m_cellularDistanceIndex0, m_cellularDistanceIndex1))\ break;\ } void SIMD_LEVEL_CLASS::FillCellularSet(float* noiseSet, FastNoiseVectorSet* vectorSet, float xOffset, float yOffset, float zOffset) { assert(noiseSet); assert(vectorSet); assert(vectorSet->size >= 0); SIMD_ZERO_ALL(); SIMDi seedV = SIMDi_SET(m_seed); SIMDf xFreqV = SIMDf_SET(m_frequency * m_xScale); SIMDf yFreqV = SIMDf_SET(m_frequency * m_yScale); SIMDf zFreqV = SIMDf_SET(m_frequency * m_zScale); SIMDf xOffsetV = SIMDf_MUL(SIMDf_SET(xOffset), xFreqV); SIMDf yOffsetV = SIMDf_MUL(SIMDf_SET(yOffset), yFreqV); SIMDf zOffsetV = SIMDf_MUL(SIMDf_SET(zOffset), zFreqV); SIMDf cellJitterV = SIMDf_SET(m_cellularJitter); INIT_PERTURB_VALUES(); int index = 0; int loopMax = vectorSet->size SIZE_MASK; NoiseLookupSettings nls; switch (m_cellularReturnType) { case CellValue: CELLULAR_MULTI_VECTOR(Value); break; case Distance: CELLULAR_MULTI_VECTOR(Distance); break; case Distance2: CELLULAR_INDEX_MULTI_VECTOR(Distance2); break; case Distance2Add: CELLULAR_INDEX_MULTI_VECTOR(Distance2Add); break; case Distance2Sub: CELLULAR_INDEX_MULTI_VECTOR(Distance2Sub); break; case Distance2Mul: CELLULAR_INDEX_MULTI_VECTOR(Distance2Mul); break; case Distance2Div: CELLULAR_INDEX_MULTI_VECTOR(Distance2Div); break; case Distance2Cave: CELLULAR_INDEX_MULTI_VECTOR(Distance2Cave); break; case NoiseLookup: nls.type = m_cellularNoiseLookupType; nls.frequency = SIMDf_SET(m_cellularNoiseLookupFrequency); nls.fractalType = m_fractalType; nls.fractalOctaves = m_octaves; nls.fractalLacunarity = SIMDf_SET(m_lacunarity); nls.fractalGain = SIMDf_SET(m_gain); nls.fractalBounding = SIMDf_SET(m_fractalBounding); switch (m_cellularDistanceFunction) { case Euclidean: VECTOR_SET_BUILDER(result = FUNC(CellularLookupEuclideanSingle)(seedV, xF, yF, zF, cellJitterV, nls)); break; case Manhattan: VECTOR_SET_BUILDER(result = FUNC(CellularLookupManhattanSingle)(seedV, xF, yF, zF, cellJitterV, nls)); break; case Natural: VECTOR_SET_BUILDER(result = FUNC(CellularLookupNaturalSingle)(seedV, xF, yF, zF, cellJitterV, nls)); break; } break; } SIMD_ZERO_ALL(); } #define SAMPLE_INDEX(_x,_y,_z) ((_x) * yzSizeSample + (_y) * zSizeSample + (_z)) #define SET_INDEX(_x,_y,_z) ((_x) * yzSize + (_y) * zSize + (_z)) void SIMD_LEVEL_CLASS::FillSampledNoiseSet(float* noiseSet, int xStart, int yStart, int zStart, int xSize, int ySize, int zSize, int sampleScale) { assert(noiseSet); SIMD_ZERO_ALL(); if (sampleScale <= 0) { FillNoiseSet(noiseSet, xStart, yStart, zStart, xSize, ySize, zSize); return; } int sampleSize = 1 << sampleScale; int sampleMask = sampleSize - 1; float scaleModifier = float(sampleSize); int xOffset = (sampleSize - (xStart & sampleMask)) & sampleMask; int yOffset = (sampleSize - (yStart & sampleMask)) & sampleMask; int zOffset = (sampleSize - (zStart & sampleMask)) & sampleMask; int xSizeSample = xSize + xOffset; int ySizeSample = ySize + yOffset; int zSizeSample = zSize + zOffset; if (xSizeSample & sampleMask) xSizeSample = (xSizeSample & ~sampleMask) + sampleSize; if (ySizeSample & sampleMask) ySizeSample = (ySizeSample & ~sampleMask) + sampleSize; if (zSizeSample & sampleMask) zSizeSample = (zSizeSample & ~sampleMask) + sampleSize; xSizeSample = (xSizeSample >> sampleScale) + 1; ySizeSample = (ySizeSample >> sampleScale) + 1; zSizeSample = (zSizeSample >> sampleScale) + 1; float* noiseSetSample = GetEmptySet(xSizeSample * ySizeSample * zSizeSample); FillNoiseSet(noiseSetSample, xStart >> sampleScale, yStart >> sampleScale, zStart >> sampleScale, xSizeSample, ySizeSample, zSizeSample, scaleModifier); int yzSizeSample = ySizeSample * zSizeSample; int yzSize = ySize * zSize; SIMDi axisMask = SIMDi_SET(sampleMask); SIMDf axisScale = SIMDf_SET(1.f / scaleModifier); SIMDf axisOffset = SIMDf_MUL(axisScale, SIMDf_NUM(0_5)); SIMDi sampleSizeSIMD = SIMDi_SET(sampleSize); SIMDi xSIMD = SIMDi_SET(-xOffset); SIMDi yBase = SIMDi_SET(-yOffset); SIMDi zBase = SIMDi_SET(-zOffset); int localCountMax = (1 << (sampleScale * 3)); int vMax = VECTOR_SIZE; #if SIMD_LEVEL == FN_NEON SIMDi sampleScaleV = SIMDi_SET(-sampleScale); SIMDi sampleScale2V = SIMDi_MUL(sampleScaleV, SIMDi_NUM(2)); #endif for (int x = 0; x < xSizeSample - 1; x++) { SIMDi ySIMD = yBase; for (int y = 0; y < ySizeSample - 1; y++) { SIMDi zSIMD = zBase; SIMDf c001 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x, y, 0)]); SIMDf c101 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x + 1, y, 0)]); SIMDf c011 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x, y + 1, 0)]); SIMDf c111 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x + 1, y + 1, 0)]); for (int z = 0; z < zSizeSample - 1; z++) { SIMDf c000 = c001; SIMDf c100 = c101; SIMDf c010 = c011; SIMDf c110 = c111; c001 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x, y, z + 1)]); c101 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x + 1, y, z + 1)]); c011 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x, y + 1, z + 1)]); c111 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x + 1, y + 1, z + 1)]); SIMDi localCountSIMD = SIMDi_NUM(incremental); int localCount = 0; while (localCount < localCountMax) { uSIMDi xi, yi, zi; #if SIMD_LEVEL == FN_NEON xi.m = SIMDi_AND(SIMDi_VSHIFT_L(localCountSIMD, sampleScale2V), axisMask); yi.m = SIMDi_AND(SIMDi_VSHIFT_L(localCountSIMD, sampleScaleV), axisMask); #else xi.m = SIMDi_AND(SIMDi_SHIFT_R(localCountSIMD, sampleScale * 2), axisMask); yi.m = SIMDi_AND(SIMDi_SHIFT_R(localCountSIMD, sampleScale), axisMask); #endif zi.m = SIMDi_AND(localCountSIMD, axisMask); SIMDf xf = SIMDf_MUL_ADD(SIMDf_CONVERT_TO_FLOAT(xi.m), axisScale, axisOffset); SIMDf yf = SIMDf_MUL_ADD(SIMDf_CONVERT_TO_FLOAT(yi.m), axisScale, axisOffset); SIMDf zf = SIMDf_MUL_ADD(SIMDf_CONVERT_TO_FLOAT(zi.m), axisScale, axisOffset); xi.m = SIMDi_ADD(xi.m, xSIMD); yi.m = SIMDi_ADD(yi.m, ySIMD); zi.m = SIMDi_ADD(zi.m, zSIMD); uSIMDf sampledResults; sampledResults.m = FUNC(Lerp)( FUNC(Lerp)( FUNC(Lerp)(c000, c100, xf), FUNC(Lerp)(c010, c110, xf), yf), FUNC(Lerp)( FUNC(Lerp)(c001, c101, xf), FUNC(Lerp)(c011, c111, xf), yf), zf); for (int i = 0; i < vMax; i++) { if (xi.a[i] >= 0 && xi.a[i] < xSize && yi.a[i] >= 0 && yi.a[i] < ySize && zi.a[i] >= 0 && zi.a[i] < zSize) { int index = SET_INDEX(xi.a[i], yi.a[i], zi.a[i]); noiseSet[index] = sampledResults.a[i]; } } localCount += VECTOR_SIZE; localCountSIMD = SIMDi_ADD(localCountSIMD, SIMDi_NUM(vectorSize)); } zSIMD = SIMDi_ADD(zSIMD, sampleSizeSIMD); } ySIMD = SIMDi_ADD(ySIMD, sampleSizeSIMD); } xSIMD = SIMDi_ADD(xSIMD, sampleSizeSIMD); } FreeNoiseSet(noiseSetSample); SIMD_ZERO_ALL(); } void SIMD_LEVEL_CLASS::FillSampledNoiseSet(float* noiseSet, FastNoiseVectorSet* vectorSet, float xOffset, float yOffset, float zOffset) { assert(noiseSet); assert(vectorSet); assert(vectorSet->size >= 0); SIMD_ZERO_ALL(); int sampleScale = vectorSet->sampleScale; if (sampleScale <= 0) { FillNoiseSet(noiseSet, vectorSet, xOffset, yOffset, zOffset); return; } int sampleSize = 1 << sampleScale; int sampleMask = sampleSize - 1; float scaleModifier = float(sampleSize); int xSize = vectorSet->sampleSizeX; int ySize = vectorSet->sampleSizeY; int zSize = vectorSet->sampleSizeZ; int xSizeSample = xSize; int ySizeSample = ySize; int zSizeSample = zSize; if (xSizeSample & sampleMask) xSizeSample = (xSizeSample & ~sampleMask) + sampleSize; if (ySizeSample & sampleMask) ySizeSample = (ySizeSample & ~sampleMask) + sampleSize; if (zSizeSample & sampleMask) zSizeSample = (zSizeSample & ~sampleMask) + sampleSize; xSizeSample = (xSizeSample >> sampleScale) + 1; ySizeSample = (ySizeSample >> sampleScale) + 1; zSizeSample = (zSizeSample >> sampleScale) + 1; float* noiseSetSample = GetEmptySet(vectorSet->size); FillNoiseSet(noiseSetSample, vectorSet, xOffset - 0.5f, yOffset - 0.5f, zOffset - 0.5f); int yzSizeSample = ySizeSample * zSizeSample; int yzSize = ySize * zSize; SIMDi axisMask = SIMDi_SET(sampleMask); SIMDf axisScale = SIMDf_SET(1.f / scaleModifier); SIMDf axisOffset = SIMDf_MUL(axisScale, SIMDf_NUM(0_5)); SIMDi sampleSizeSIMD = SIMDi_SET(sampleSize); SIMDi xSIMD = SIMDi_SET_ZERO(); int localCountMax = (1 << (sampleScale * 3)); int vMax = VECTOR_SIZE; #if SIMD_LEVEL == FN_NEON SIMDi sampleScaleV = SIMDi_SET(-sampleScale); SIMDi sampleScale2V = SIMDi_MUL(sampleScaleV, SIMDi_NUM(2)); #endif for (int x = 0; x < xSizeSample - 1; x++) { SIMDi ySIMD = SIMDi_SET_ZERO(); for (int y = 0; y < ySizeSample - 1; y++) { SIMDi zSIMD = SIMDi_SET_ZERO(); SIMDf c001 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x, y, 0)]); SIMDf c101 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x + 1, y, 0)]); SIMDf c011 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x, y + 1, 0)]); SIMDf c111 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x + 1, y + 1, 0)]); for (int z = 0; z < zSizeSample - 1; z++) { SIMDf c000 = c001; SIMDf c100 = c101; SIMDf c010 = c011; SIMDf c110 = c111; c001 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x, y, z + 1)]); c101 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x + 1, y, z + 1)]); c011 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x, y + 1, z + 1)]); c111 = SIMDf_SET(noiseSetSample[SAMPLE_INDEX(x + 1, y + 1, z + 1)]); SIMDi localCountSIMD = SIMDi_NUM(incremental); int localCount = 0; while (localCount < localCountMax) { uSIMDi xi, yi, zi; #if SIMD_LEVEL == FN_NEON xi.m = SIMDi_AND(SIMDi_VSHIFT_L(localCountSIMD, sampleScale2V), axisMask); yi.m = SIMDi_AND(SIMDi_VSHIFT_L(localCountSIMD, sampleScaleV), axisMask); #else xi.m = SIMDi_AND(SIMDi_SHIFT_R(localCountSIMD, sampleScale * 2), axisMask); yi.m = SIMDi_AND(SIMDi_SHIFT_R(localCountSIMD, sampleScale), axisMask); #endif zi.m = SIMDi_AND(localCountSIMD, axisMask); SIMDf xf = SIMDf_MUL_ADD(SIMDf_CONVERT_TO_FLOAT(xi.m), axisScale, axisOffset); SIMDf yf = SIMDf_MUL_ADD(SIMDf_CONVERT_TO_FLOAT(yi.m), axisScale, axisOffset); SIMDf zf = SIMDf_MUL_ADD(SIMDf_CONVERT_TO_FLOAT(zi.m), axisScale, axisOffset); xi.m = SIMDi_ADD(xi.m, xSIMD); yi.m = SIMDi_ADD(yi.m, ySIMD); zi.m = SIMDi_ADD(zi.m, zSIMD); uSIMDf sampledResults; sampledResults.m = FUNC(Lerp)( FUNC(Lerp)( FUNC(Lerp)(c000, c100, xf), FUNC(Lerp)(c010, c110, xf), yf), FUNC(Lerp)( FUNC(Lerp)(c001, c101, xf), FUNC(Lerp)(c011, c111, xf), yf), zf); for (int i = 0; i < vMax; i++) { if (xi.a[i] < xSize && yi.a[i] < ySize && zi.a[i] < zSize) { int index = SET_INDEX(xi.a[i], yi.a[i], zi.a[i]); noiseSet[index] = sampledResults.a[i]; } } localCount += VECTOR_SIZE; localCountSIMD = SIMDi_ADD(localCountSIMD, SIMDi_NUM(vectorSize)); } zSIMD = SIMDi_ADD(zSIMD, sampleSizeSIMD); } ySIMD = SIMDi_ADD(ySIMD, sampleSizeSIMD); } xSIMD = SIMDi_ADD(xSIMD, sampleSizeSIMD); } FreeNoiseSet(noiseSetSample); SIMD_ZERO_ALL(); } #undef SIMD_LEVEL #endif
{ "pile_set_name": "Github" }
/* * Copyright (C) 2016 The Android Open Source Project * * 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. */ package com.android.contacts.util.concurrent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.Loader; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.util.Log; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.CancellationException; import java.util.concurrent.Executor; /** * Wraps a ListenableFuture for integration with {@link android.app.LoaderManager} * * <p>Using a loader ensures that the result is delivered while the receiving component (activity * or fragment) is resumed and also prevents leaking references these components * </p> */ public abstract class ListenableFutureLoader<D> extends Loader<D> { private static final String TAG = "FutureLoader"; private final IntentFilter mReloadFilter; private final Executor mUiExecutor; private final LocalBroadcastManager mLocalBroadcastManager; private ListenableFuture<D> mFuture; private D mLoadedData; private BroadcastReceiver mReceiver; /** * Stores away the application context associated with context. * Since Loaders can be used across multiple activities it's dangerous to * store the context directly; always use {@link #getContext()} to retrieve * the Loader's Context, don't use the constructor argument directly. * The Context returned by {@link #getContext} is safe to use across * Activity instances. * * @param context used to retrieve the application context. */ public ListenableFutureLoader(Context context) { this(context, null); } public ListenableFutureLoader(Context context, IntentFilter reloadBroadcastFilter) { super(context); mUiExecutor = ContactsExecutors.newUiThreadExecutor(); mReloadFilter = reloadBroadcastFilter; mLocalBroadcastManager = LocalBroadcastManager.getInstance(context); } @Override protected void onStartLoading() { if (mReloadFilter != null && mReceiver == null) { mReceiver = new ForceLoadReceiver(); mLocalBroadcastManager.registerReceiver(mReceiver, mReloadFilter); } if (mLoadedData != null) { deliverResult(mLoadedData); } if (mFuture == null) { takeContentChanged(); forceLoad(); } else if (takeContentChanged()) { forceLoad(); } } @Override protected void onForceLoad() { mFuture = loadData(); Futures.addCallback(mFuture, new FutureCallback<D>() { @Override public void onSuccess(D result) { if (mLoadedData == null || !isSameData(mLoadedData, result)) { deliverResult(result); } mLoadedData = result; commitContentChanged(); } @Override public void onFailure(Throwable t) { if (t instanceof CancellationException) { Log.i(TAG, "Loading cancelled", t); rollbackContentChanged(); } else { Log.e(TAG, "Loading failed", t); } } }, mUiExecutor); } @Override protected void onStopLoading() { if (mFuture != null) { mFuture.cancel(false); mFuture = null; } } @Override protected void onReset() { mFuture = null; mLoadedData = null; if (mReceiver != null) { mLocalBroadcastManager.unregisterReceiver(mReceiver); } } protected abstract ListenableFuture<D> loadData(); /** * Returns whether the newly loaded data is the same as the cached value * * <p>This allows subclasses to suppress delivering results when the data hasn't * actually changed. By default it will always return false. * </p> */ protected boolean isSameData(D previousData, D newData) { return false; } public final D getLoadedData() { return mLoadedData; } public class ForceLoadReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { onContentChanged(); } } }
{ "pile_set_name": "Github" }
""" When a location type is set from stock-tracking to not stock-tracking, find all locations of that type and: close the supply point case, nullify the supply_point_id, nullify the StockState sql_location field When a location type is set from not stock tracking to stock tracking, find all locations of that type and: see if there is a closed supply point case with that location id if so: reopen that case set the supply_point_id to that set the sql_location field on any appropriate stock states otherwise: open a new supply point case as normal """ import datetime from django.test import TestCase from casexml.apps.stock.const import SECTION_TYPE_STOCK from corehq.apps.commtrack.models import StockState, SupplyPointCase from corehq.apps.commtrack.tests.util import bootstrap_domain from corehq.apps.products.models import SQLProduct from ..models import SQLLocation from .util import setup_locations_and_types class TestChangeStatus(TestCase): domain = 'test-change-administrative' location_type_names = ['state', 'county', 'city'] stock_tracking_types = ['city'] location_structure = [ ('Massachusetts', [ ('Middlesex', [ ('Cambridge', []), ('Somerville', []), ]), ('Suffolk', [ ('Boston', []), ]) ]) ] def setUp(self): self.domain_obj = bootstrap_domain(self.domain) self.location_types, self.locations = setup_locations_and_types( self.domain, self.location_type_names, self.stock_tracking_types, self.location_structure, ) self.suffolk = self.locations['Suffolk'] self.boston = self.locations['Boston'] self.county_type = self.location_types['county'] self.city_type = self.location_types['city'] def tearDown(self): self.domain_obj.delete() def assertHasSupplyPoint(self, location): msg = "'{}' does not have a supply point.".format(location.name) loc = SQLLocation.objects.get(location_id=location.location_id) self.assertIsNotNone(loc.supply_point_id, msg) self.assertIsNotNone(loc.linked_supply_point(), msg) def assertHasNoSupplyPoint(self, location): msg = "'{}' should not have a supply point".format(location.name) loc = SQLLocation.objects.get(location_id=location.location_id) self.assertIsNone(loc.supply_point_id, msg) def test_change_to_track_stock(self): self.assertHasNoSupplyPoint(self.suffolk) self.county_type.administrative = False self.county_type.save() self.assertHasSupplyPoint(self.suffolk) def test_change_to_administrative_and_back(self): # at first it should have a supply point self.assertHasSupplyPoint(self.boston) supply_point_id = self.boston.supply_point_id self.city_type.administrative = True self.city_type.save() # Now that it's administrative, it shouldn't have one # The case should still exist, but be closed self.assertHasNoSupplyPoint(self.boston) self.assertTrue(SupplyPointCase.get(supply_point_id).closed) self.city_type.administrative = False self.city_type.save() # The same supply point case should be reopened self.assertHasSupplyPoint(self.boston) self.assertEqual(self.boston.supply_point_id, supply_point_id) self.assertFalse(SupplyPointCase.get(supply_point_id).closed) def test_stock_states(self): def has_stock_states(location): return StockState.objects.filter(sql_location=location).exists() product = SQLProduct.objects.create( domain=self.domain, product_id='foo', name='foo') StockState.objects.create( section_id=SECTION_TYPE_STOCK, case_id=self.boston.supply_point_id, product_id='foo', last_modified_date=datetime.datetime.now(), stock_on_hand=10, sql_product=product, sql_location=self.boston, ) # I just created a stock state, it'd better show up self.assertTrue(has_stock_states(self.boston)) # making the location administrative should hide its stock states self.city_type.administrative = True self.city_type.save() self.assertFalse(has_stock_states(self.boston)) # tracking stock again should restore the stock states self.city_type.administrative = False self.city_type.save() self.assertTrue(has_stock_states(self.boston))
{ "pile_set_name": "Github" }
{ "symbol": "univ2WBTCETH", "invalid_erc20_symbol": true, "name": "Uniswap V2 WBTC-ETH", "type": "ERC20", "address": "0xBb2b8038a1640196FbE3e38816F3e67Cba72D940", "ens_address": "", "decimals": 18, "website": "https://www.uniswap.org", "logo": { "src": "https://uniswap.info/static/media/logo.5827780d.svg", "width": "", "height": "", "ipfs_hash": "" }, "support": { "email": "contact@uniswap.io", "url": "" }, "social": { "blog": "https://uniswap.org/blog", "chat": "", "facebook": "", "forum": "", "github": "https://github.com/Uniswap", "gitter": "", "instagram": "", "linkedin": "", "reddit": "https://www.reddit.com/r/Uniswap", "slack": "", "telegram": "", "twitter": "https://twitter.com/UniswapProtocol", "youtube": "" } }
{ "pile_set_name": "Github" }
#include "ExtrusionEntity.hpp" #include "ExtrusionEntityCollection.hpp" #include "ExPolygonCollection.hpp" #include "ClipperUtils.hpp" #include "Extruder.hpp" #include "Flow.hpp" #include <cmath> #include <limits> #include <sstream> #define L(s) (s) namespace Slic3r { void ExtrusionPath::intersect_expolygons(const ExPolygonCollection &collection, ExtrusionEntityCollection* retval) const { this->_inflate_collection(intersection_pl(this->polyline, (Polygons)collection), retval); } void ExtrusionPath::subtract_expolygons(const ExPolygonCollection &collection, ExtrusionEntityCollection* retval) const { this->_inflate_collection(diff_pl(this->polyline, (Polygons)collection), retval); } void ExtrusionPath::clip_end(double distance) { this->polyline.clip_end(distance); } void ExtrusionPath::simplify(double tolerance) { this->polyline.simplify(tolerance); } double ExtrusionPath::length() const { return this->polyline.length(); } void ExtrusionPath::_inflate_collection(const Polylines &polylines, ExtrusionEntityCollection* collection) const { for (const Polyline &polyline : polylines) collection->entities.emplace_back(new ExtrusionPath(polyline, *this)); } void ExtrusionPath::polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const { polygons_append(out, offset(this->polyline, float(scale_(this->width/2)) + scaled_epsilon)); } void ExtrusionPath::polygons_covered_by_spacing(Polygons &out, const float scaled_epsilon) const { // Instantiating the Flow class to get the line spacing. // Don't know the nozzle diameter, setting to zero. It shall not matter it shall be optimized out by the compiler. Flow flow(this->width, this->height, 0.f, is_bridge(this->role())); polygons_append(out, offset(this->polyline, 0.5f * float(flow.scaled_spacing()) + scaled_epsilon)); } void ExtrusionMultiPath::reverse() { for (ExtrusionPath &path : this->paths) path.reverse(); std::reverse(this->paths.begin(), this->paths.end()); } double ExtrusionMultiPath::length() const { double len = 0; for (const ExtrusionPath &path : this->paths) len += path.polyline.length(); return len; } void ExtrusionMultiPath::polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const { for (const ExtrusionPath &path : this->paths) path.polygons_covered_by_width(out, scaled_epsilon); } void ExtrusionMultiPath::polygons_covered_by_spacing(Polygons &out, const float scaled_epsilon) const { for (const ExtrusionPath &path : this->paths) path.polygons_covered_by_spacing(out, scaled_epsilon); } double ExtrusionMultiPath::min_mm3_per_mm() const { double min_mm3_per_mm = std::numeric_limits<double>::max(); for (const ExtrusionPath &path : this->paths) min_mm3_per_mm = std::min(min_mm3_per_mm, path.mm3_per_mm); return min_mm3_per_mm; } Polyline ExtrusionMultiPath::as_polyline() const { Polyline out; if (! paths.empty()) { size_t len = 0; for (size_t i_path = 0; i_path < paths.size(); ++ i_path) { assert(! paths[i_path].polyline.points.empty()); assert(i_path == 0 || paths[i_path - 1].polyline.points.back() == paths[i_path].polyline.points.front()); len += paths[i_path].polyline.points.size(); } // The connecting points between the segments are equal. len -= paths.size() - 1; assert(len > 0); out.points.reserve(len); out.points.push_back(paths.front().polyline.points.front()); for (size_t i_path = 0; i_path < paths.size(); ++ i_path) out.points.insert(out.points.end(), paths[i_path].polyline.points.begin() + 1, paths[i_path].polyline.points.end()); } return out; } bool ExtrusionLoop::make_clockwise() { bool was_ccw = this->polygon().is_counter_clockwise(); if (was_ccw) this->reverse(); return was_ccw; } bool ExtrusionLoop::make_counter_clockwise() { bool was_cw = this->polygon().is_clockwise(); if (was_cw) this->reverse(); return was_cw; } void ExtrusionLoop::reverse() { for (ExtrusionPath &path : this->paths) path.reverse(); std::reverse(this->paths.begin(), this->paths.end()); } Polygon ExtrusionLoop::polygon() const { Polygon polygon; for (const ExtrusionPath &path : this->paths) { // for each polyline, append all points except the last one (because it coincides with the first one of the next polyline) polygon.points.insert(polygon.points.end(), path.polyline.points.begin(), path.polyline.points.end()-1); } return polygon; } double ExtrusionLoop::length() const { double len = 0; for (const ExtrusionPath &path : this->paths) len += path.polyline.length(); return len; } bool ExtrusionLoop::split_at_vertex(const Point &point) { for (ExtrusionPaths::iterator path = this->paths.begin(); path != this->paths.end(); ++path) { int idx = path->polyline.find_point(point); if (idx != -1) { if (this->paths.size() == 1) { // just change the order of points path->polyline.points.insert(path->polyline.points.end(), path->polyline.points.begin() + 1, path->polyline.points.begin() + idx + 1); path->polyline.points.erase(path->polyline.points.begin(), path->polyline.points.begin() + idx); } else { // new paths list starts with the second half of current path ExtrusionPaths new_paths; new_paths.reserve(this->paths.size() + 1); { ExtrusionPath p = *path; p.polyline.points.erase(p.polyline.points.begin(), p.polyline.points.begin() + idx); if (p.polyline.is_valid()) new_paths.push_back(p); } // then we add all paths until the end of current path list new_paths.insert(new_paths.end(), path+1, this->paths.end()); // not including this path // then we add all paths since the beginning of current list up to the previous one new_paths.insert(new_paths.end(), this->paths.begin(), path); // not including this path // finally we add the first half of current path { ExtrusionPath p = *path; p.polyline.points.erase(p.polyline.points.begin() + idx + 1, p.polyline.points.end()); if (p.polyline.is_valid()) new_paths.push_back(p); } // we can now override the old path list with the new one and stop looping std::swap(this->paths, new_paths); } return true; } } return false; } // Splitting an extrusion loop, possibly made of multiple segments, some of the segments may be bridging. void ExtrusionLoop::split_at(const Point &point, bool prefer_non_overhang) { if (this->paths.empty()) return; // Find the closest path and closest point belonging to that path. Avoid overhangs, if asked for. size_t path_idx = 0; Point p; { double min = std::numeric_limits<double>::max(); Point p_non_overhang; size_t path_idx_non_overhang = 0; double min_non_overhang = std::numeric_limits<double>::max(); for (const ExtrusionPath &path : this->paths) { Point p_tmp = point.projection_onto(path.polyline); double dist = (p_tmp - point).cast<double>().norm(); if (dist < min) { p = p_tmp; min = dist; path_idx = &path - &this->paths.front(); } if (prefer_non_overhang && ! is_bridge(path.role()) && dist < min_non_overhang) { p_non_overhang = p_tmp; min_non_overhang = dist; path_idx_non_overhang = &path - &this->paths.front(); } } if (prefer_non_overhang && min_non_overhang != std::numeric_limits<double>::max()) { // Only apply the non-overhang point if there is one. path_idx = path_idx_non_overhang; p = p_non_overhang; } } // now split path_idx in two parts const ExtrusionPath &path = this->paths[path_idx]; ExtrusionPath p1(path.role(), path.mm3_per_mm, path.width, path.height); ExtrusionPath p2(path.role(), path.mm3_per_mm, path.width, path.height); path.polyline.split_at(p, &p1.polyline, &p2.polyline); if (this->paths.size() == 1) { if (! p1.polyline.is_valid()) std::swap(this->paths.front().polyline.points, p2.polyline.points); else if (! p2.polyline.is_valid()) std::swap(this->paths.front().polyline.points, p1.polyline.points); else { p2.polyline.points.insert(p2.polyline.points.end(), p1.polyline.points.begin() + 1, p1.polyline.points.end()); std::swap(this->paths.front().polyline.points, p2.polyline.points); } } else { // install the two paths this->paths.erase(this->paths.begin() + path_idx); if (p2.polyline.is_valid()) this->paths.insert(this->paths.begin() + path_idx, p2); if (p1.polyline.is_valid()) this->paths.insert(this->paths.begin() + path_idx, p1); } // split at the new vertex this->split_at_vertex(p); } void ExtrusionLoop::clip_end(double distance, ExtrusionPaths* paths) const { *paths = this->paths; while (distance > 0 && !paths->empty()) { ExtrusionPath &last = paths->back(); double len = last.length(); if (len <= distance) { paths->pop_back(); distance -= len; } else { last.polyline.clip_end(distance); break; } } } bool ExtrusionLoop::has_overhang_point(const Point &point) const { for (const ExtrusionPath &path : this->paths) { int pos = path.polyline.find_point(point); if (pos != -1) { // point belongs to this path // we consider it overhang only if it's not an endpoint return (is_bridge(path.role()) && pos > 0 && pos != (int)(path.polyline.points.size())-1); } } return false; } void ExtrusionLoop::polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const { for (const ExtrusionPath &path : this->paths) path.polygons_covered_by_width(out, scaled_epsilon); } void ExtrusionLoop::polygons_covered_by_spacing(Polygons &out, const float scaled_epsilon) const { for (const ExtrusionPath &path : this->paths) path.polygons_covered_by_spacing(out, scaled_epsilon); } double ExtrusionLoop::min_mm3_per_mm() const { double min_mm3_per_mm = std::numeric_limits<double>::max(); for (const ExtrusionPath &path : this->paths) min_mm3_per_mm = std::min(min_mm3_per_mm, path.mm3_per_mm); return min_mm3_per_mm; } std::string ExtrusionEntity::role_to_string(ExtrusionRole role) { switch (role) { #if ENABLE_GCODE_VIEWER case erNone : return L("Unknown"); #else case erNone : return L("None"); #endif // ENABLE_GCODE_VIEWER case erPerimeter : return L("Perimeter"); case erExternalPerimeter : return L("External perimeter"); case erOverhangPerimeter : return L("Overhang perimeter"); case erInternalInfill : return L("Internal infill"); case erSolidInfill : return L("Solid infill"); case erTopSolidInfill : return L("Top solid infill"); case erIroning : return L("Ironing"); case erBridgeInfill : return L("Bridge infill"); case erGapFill : return L("Gap fill"); case erSkirt : return L("Skirt"); case erSupportMaterial : return L("Support material"); case erSupportMaterialInterface : return L("Support material interface"); case erWipeTower : return L("Wipe tower"); case erCustom : return L("Custom"); case erMixed : return L("Mixed"); default : assert(false); } return ""; } ExtrusionRole ExtrusionEntity::string_to_role(const std::string& role) { if (role == L("Perimeter")) return erPerimeter; else if (role == L("External perimeter")) return erExternalPerimeter; else if (role == L("Overhang perimeter")) return erOverhangPerimeter; else if (role == L("Internal infill")) return erInternalInfill; else if (role == L("Solid infill")) return erSolidInfill; else if (role == L("Top solid infill")) return erTopSolidInfill; else if (role == L("Ironing")) return erIroning; else if (role == L("Bridge infill")) return erBridgeInfill; else if (role == L("Gap fill")) return erGapFill; else if (role == L("Skirt")) return erSkirt; else if (role == L("Support material")) return erSupportMaterial; else if (role == L("Support material interface")) return erSupportMaterialInterface; else if (role == L("Wipe tower")) return erWipeTower; else if (role == L("Custom")) return erCustom; else if (role == L("Mixed")) return erMixed; else return erNone; } }
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <SAObjects/SABaseClientBoundCommand.h> @class NSArray; @interface SANPGetVolumeLevel : SABaseClientBoundCommand { } + (id)getVolumeLevelWithDictionary:(id)arg1 context:(id)arg2; + (id)getVolumeLevel; - (BOOL)requiresResponse; @property(copy, nonatomic) NSArray *hashedRouteUIDs; - (id)encodedClassName; - (id)groupIdentifier; @end
{ "pile_set_name": "Github" }
using UnityEngine; namespace Mirror.Examples.NetworkRoom { public class PlayerScore : NetworkBehaviour { [SyncVar] public int index; [SyncVar] public uint score; public override void OnStartServer() { index = connectionToClient.connectionId; } void OnGUI() { GUI.Box(new Rect(10f + (index * 110), 10f, 100f, 25f), $"P{index}: {score.ToString("0000000")}"); } } }
{ "pile_set_name": "Github" }
CHPL_RT_NUM_THREADS_PER_LOCALE=200 # Lower stack size for systems that have limited memory. CHPL_RT_CALL_STACK_SIZE=1M
{ "pile_set_name": "Github" }
LEO-MANAGER DEFINITIONS ::= BEGIN IMPORTS MODULE-IDENTITY, OBJECT-TYPE, Gauge32, enterprises FROM SNMPv2-SMI OBJECT-GROUP FROM SNMPv2-CONF DisplayString, TruthValue FROM SNMPv2-TC; leofs MODULE-IDENTITY LAST-UPDATED "201502170000Z" ORGANIZATION "github.com/leo-project" CONTACT-INFO "e-mail:dev@leo-project.org" DESCRIPTION "LEO MANAGER SNMP MIB" REVISION "201502170000Z" DESCRIPTION "v1.0" ::= { enterprises 35450} leofsGroups OBJECT IDENTIFIER ::= { leofs 1 } staticOid OBJECT IDENTIFIER ::= { leofs 15} -- ===================================== -- Items -- ===================================== -- ErlangVM Related node-name OBJECT-TYPE SYNTAX DisplayString MAX-ACCESS read-only STATUS current DESCRIPTION "Node name" ::= { staticOid 1 } vm-proc-count-1m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Num of Processes (1min mean)" ::= { staticOid 2 } vm-total-mem-1m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Total Memory (1min mean)" ::= { staticOid 3 } vm-system-mem-1m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "System Memory (1min mean)" ::= { staticOid 4 } vm-procs-mem-1m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Procs Memory (1min mean)" ::= { staticOid 5 } vm-ets-mem-1m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "ETS Memory (1min mean)" ::= { staticOid 6 } vm-proc-count-5m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Num of Processes (5min mean)" ::= { staticOid 7 } vm-total-mem-5m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Total Memory (5min mean)" ::= { staticOid 8 } vm-system-mem-5m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "System Memory (5min mean)" ::= { staticOid 9 } vm-procs-mem-5m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Procs Memory (5min mean)" ::= { staticOid 10 } vm-ets-mem-5m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "ETS Memory (5min mean)" ::= { staticOid 11 } --- --- Optional VM-related items --- vm-used-per-allocated-mem-1m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Used per allocated memory ratio (1min mean)" ::= { staticOid 12 } vm-allocated-mem-1m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Allocated memory (1min mean)" ::= { staticOid 13 } vm-used-per-allocated-mem-5m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Used per allocated memory ratio (5min mean)" ::= { staticOid 14 } vm-allocated-mem-5m OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Allocated memory (5min mean)" ::= { staticOid 15 } -- -- Global Group -- leofsGroup OBJECT-GROUP OBJECTS {node-name, vm-proc-count-1m, vm-total-mem-1m, vm-system-mem-1m, vm-procs-mem-1m, vm-ets-mem-1m, vm-proc-count-5m, vm-total-mem-5m, vm-system-mem-5m, vm-procs-mem-5m, vm-ets-mem-5m, vm-used-per-allocated-mem-1m, vm-allocated-mem-1m, vm-used-per-allocated-mem-5m, vm-allocated-mem-5m } STATUS current DESCRIPTION "LeoFS group" ::= { leofsGroups 1 } END
{ "pile_set_name": "Github" }
global.Get("document") global.Get("document").Call("querySelector", "body") global.Get("document") global.Get("document").Call("createTextNode", "Hello world!") global.Get("document").Call("createTextNode", "Hello world!").Get("classList") global.Get("document").Call("createTextNode", "Hello world!").Get("dataset") global.Get("document").Call("createTextNode", "Hello world!").Get("style") global.Get("document").Call("querySelector", "body").Get("nodeName")
{ "pile_set_name": "Github" }
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Regression test for hitting a DCHECK in StoreProxy. for (var i = 0; i < 10; i++) { __proto__ = new Proxy({}, { getPrototypeOf() { } }); }
{ "pile_set_name": "Github" }
// Clearfix // // For modern browsers // 1. The space content is one way to avoid an Opera bug when the // contenteditable attribute is included anywhere else in the document. // Otherwise it causes space to appear at the top and bottom of elements // that are clearfixed. // 2. The use of `table` rather than `block` is only necessary if using // `:before` to contain the top-margins of child elements. // // Source: http://nicolasgallagher.com/micro-clearfix-hack/ .clearfix() { &:before, &:after { content: " "; // 1 display: table; // 2 } &:after { clear: both; } }
{ "pile_set_name": "Github" }
/* * tst.verror.js: tests basic functionality of the VError class. */ var mod_assert = require('assert'); var mod_verror = require('../lib/verror'); var VError = mod_verror.VError; var WError = mod_verror.WError; var err, suberr, stack, substack; /* * Remove full paths and relative line numbers from stack traces so that we can * compare against "known-good" output. */ function cleanStack(stacktxt) { var re = new RegExp(__filename + ':\\d+:\\d+', 'gm'); stacktxt = stacktxt.replace(re, 'tst.verror.js'); return (stacktxt); } /* * Save the generic parts of all stack traces so we can avoid hardcoding * Node-specific implementation details in our testing of stack traces. */ var nodestack = new Error().stack.split('\n').slice(2).join('\n'); /* no arguments */ err = new VError(); mod_assert.equal(err.name, 'VError'); mod_assert.ok(err instanceof Error); mod_assert.ok(err instanceof VError); mod_assert.equal(err.message, ''); mod_assert.ok(err.cause() === undefined); stack = cleanStack(err.stack); mod_assert.equal(stack, [ 'VError', ' at Object.<anonymous> (tst.verror.js)' ].join('\n') + '\n' + nodestack); /* options-argument form */ err = new VError({}); mod_assert.equal(err.message, ''); mod_assert.ok(err.cause() === undefined); /* simple message */ err = new VError('my error'); mod_assert.equal(err.message, 'my error'); mod_assert.ok(err.cause() === undefined); stack = cleanStack(err.stack); mod_assert.equal(stack, [ 'VError: my error', ' at Object.<anonymous> (tst.verror.js)' ].join('\n') + '\n' + nodestack); err = new VError({}, 'my error'); mod_assert.equal(err.message, 'my error'); mod_assert.ok(err.cause() === undefined); /* printf-style message */ err = new VError('%s error: %3d problems', 'very bad', 15); mod_assert.equal(err.message, 'very bad error: 15 problems'); mod_assert.ok(err.cause() === undefined); err = new VError({}, '%s error: %3d problems', 'very bad', 15); mod_assert.equal(err.message, 'very bad error: 15 problems'); mod_assert.ok(err.cause() === undefined); /* caused by another error, with no additional message */ suberr = new Error('root cause'); err = new VError(suberr); mod_assert.equal(err.message, ': root cause'); mod_assert.ok(err.cause() === suberr); err = new VError({ 'cause': suberr }); mod_assert.equal(err.message, ': root cause'); mod_assert.ok(err.cause() === suberr); /* caused by another error, with annotation */ err = new VError(suberr, 'proximate cause: %d issues', 3); mod_assert.equal(err.message, 'proximate cause: 3 issues: root cause'); mod_assert.ok(err.cause() === suberr); stack = cleanStack(err.stack); mod_assert.equal(stack, [ 'VError: proximate cause: 3 issues: root cause', ' at Object.<anonymous> (tst.verror.js)' ].join('\n') + '\n' + nodestack); err = new VError({ 'cause': suberr }, 'proximate cause: %d issues', 3); mod_assert.equal(err.message, 'proximate cause: 3 issues: root cause'); mod_assert.ok(err.cause() === suberr); stack = cleanStack(err.stack); mod_assert.equal(stack, [ 'VError: proximate cause: 3 issues: root cause', ' at Object.<anonymous> (tst.verror.js)' ].join('\n') + '\n' + nodestack); /* caused by another VError, with annotation. */ suberr = err; err = new VError(suberr, 'top'); mod_assert.equal(err.message, 'top: proximate cause: 3 issues: root cause'); mod_assert.ok(err.cause() === suberr); err = new VError({ 'cause': suberr }, 'top'); mod_assert.equal(err.message, 'top: proximate cause: 3 issues: root cause'); mod_assert.ok(err.cause() === suberr); /* caused by a WError */ suberr = new WError(new Error('root cause'), 'mid'); err = new VError(suberr, 'top'); mod_assert.equal(err.message, 'top: mid'); mod_assert.ok(err.cause() === suberr); /* null cause (for backwards compatibility with older versions) */ err = new VError(null, 'my error'); mod_assert.equal(err.message, 'my error'); mod_assert.ok(err.cause() === undefined); stack = cleanStack(err.stack); mod_assert.equal(stack, [ 'VError: my error', ' at Object.<anonymous> (tst.verror.js)' ].join('\n') + '\n' + nodestack); err = new VError({ 'cause': null }, 'my error'); mod_assert.equal(err.message, 'my error'); mod_assert.ok(err.cause() === undefined); err = new VError(null); mod_assert.equal(err.message, ''); mod_assert.ok(err.cause() === undefined); stack = cleanStack(err.stack); mod_assert.equal(stack, [ 'VError', ' at Object.<anonymous> (tst.verror.js)' ].join('\n') + '\n' + nodestack); /* constructorOpt */ function makeErr(options) { return (new VError(options, 'test error')); } err = makeErr({}); stack = cleanStack(err.stack); mod_assert.equal(stack, [ 'VError: test error', ' at makeErr (tst.verror.js)', ' at Object.<anonymous> (tst.verror.js)' ].join('\n') + '\n' + nodestack); err = makeErr({ 'constructorOpt': makeErr }); stack = cleanStack(err.stack); mod_assert.equal(stack, [ 'VError: test error', ' at Object.<anonymous> (tst.verror.js)' ].join('\n') + '\n' + nodestack);
{ "pile_set_name": "Github" }
// Copyright 2017 gRPC authors. // // 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. syntax = "proto3"; package grpc.testing; message SearchResponse { message Result { string url = 1; string title = 2; repeated string snippets = 3; } repeated Result results = 1; } message SearchRequest { string query = 1; } service SearchService { rpc Search(SearchRequest) returns (SearchResponse); rpc StreamingSearch(stream SearchRequest) returns (stream SearchResponse); }
{ "pile_set_name": "Github" }
//===----------------------------- typeinfo.cpp ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <typeinfo> namespace std { // type_info type_info::~type_info() { } // bad_cast bad_cast::bad_cast() _NOEXCEPT { } bad_cast::~bad_cast() _NOEXCEPT { } const char* bad_cast::what() const _NOEXCEPT { return "std::bad_cast"; } // bad_typeid bad_typeid::bad_typeid() _NOEXCEPT { } bad_typeid::~bad_typeid() _NOEXCEPT { } const char* bad_typeid::what() const _NOEXCEPT { return "std::bad_typeid"; } } // std
{ "pile_set_name": "Github" }
/******************************************************************* * This file is part of the Emulex Linux Device Driver for * * Fibre Channel Host Bus Adapters. * * Copyright (C) 2009-2016 Emulex. All rights reserved. * * EMULEX and SLI are trademarks of Emulex. * * www.emulex.com * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of version 2 of the GNU General * * Public License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful. * * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE * * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD * * TO BE LEGALLY INVALID. See the GNU General Public License for * * more details, a copy of which can be found in the file COPYING * * included with this package. * *******************************************************************/ #define LPFC_ACTIVE_MBOX_WAIT_CNT 100 #define LPFC_XRI_EXCH_BUSY_WAIT_TMO 10000 #define LPFC_XRI_EXCH_BUSY_WAIT_T1 10 #define LPFC_XRI_EXCH_BUSY_WAIT_T2 30000 #define LPFC_RELEASE_NOTIFICATION_INTERVAL 32 #define LPFC_RPI_LOW_WATER_MARK 10 #define LPFC_UNREG_FCF 1 #define LPFC_SKIP_UNREG_FCF 0 /* Amount of time in seconds for waiting FCF rediscovery to complete */ #define LPFC_FCF_REDISCOVER_WAIT_TMO 2000 /* msec */ /* Number of SGL entries can be posted in a 4KB nonembedded mbox command */ #define LPFC_NEMBED_MBOX_SGL_CNT 254 /* Multi-queue arrangement for FCP EQ/CQ/WQ tuples */ #define LPFC_FCP_IO_CHAN_DEF 4 #define LPFC_FCP_IO_CHAN_MIN 1 #define LPFC_FCP_IO_CHAN_MAX 16 /* Number of channels used for Flash Optimized Fabric (FOF) operations */ #define LPFC_FOF_IO_CHAN_NUM 1 /* * Provide the default FCF Record attributes used by the driver * when nonFIP mode is configured and there is no other default * FCF Record attributes. */ #define LPFC_FCOE_FCF_DEF_INDEX 0 #define LPFC_FCOE_FCF_GET_FIRST 0xFFFF #define LPFC_FCOE_FCF_NEXT_NONE 0xFFFF #define LPFC_FCOE_NULL_VID 0xFFF #define LPFC_FCOE_IGNORE_VID 0xFFFF /* First 3 bytes of default FCF MAC is specified by FC_MAP */ #define LPFC_FCOE_FCF_MAC3 0xFF #define LPFC_FCOE_FCF_MAC4 0xFF #define LPFC_FCOE_FCF_MAC5 0xFE #define LPFC_FCOE_FCF_MAP0 0x0E #define LPFC_FCOE_FCF_MAP1 0xFC #define LPFC_FCOE_FCF_MAP2 0x00 #define LPFC_FCOE_MAX_RCV_SIZE 0x800 #define LPFC_FCOE_FKA_ADV_PER 0 #define LPFC_FCOE_FIP_PRIORITY 0x80 #define sli4_sid_from_fc_hdr(fc_hdr) \ ((fc_hdr)->fh_s_id[0] << 16 | \ (fc_hdr)->fh_s_id[1] << 8 | \ (fc_hdr)->fh_s_id[2]) #define sli4_did_from_fc_hdr(fc_hdr) \ ((fc_hdr)->fh_d_id[0] << 16 | \ (fc_hdr)->fh_d_id[1] << 8 | \ (fc_hdr)->fh_d_id[2]) #define sli4_fctl_from_fc_hdr(fc_hdr) \ ((fc_hdr)->fh_f_ctl[0] << 16 | \ (fc_hdr)->fh_f_ctl[1] << 8 | \ (fc_hdr)->fh_f_ctl[2]) #define sli4_type_from_fc_hdr(fc_hdr) \ ((fc_hdr)->fh_type) #define LPFC_FW_RESET_MAXIMUM_WAIT_10MS_CNT 12000 #define INT_FW_UPGRADE 0 #define RUN_FW_UPGRADE 1 enum lpfc_sli4_queue_type { LPFC_EQ, LPFC_GCQ, LPFC_MCQ, LPFC_WCQ, LPFC_RCQ, LPFC_MQ, LPFC_WQ, LPFC_HRQ, LPFC_DRQ }; /* The queue sub-type defines the functional purpose of the queue */ enum lpfc_sli4_queue_subtype { LPFC_NONE, LPFC_MBOX, LPFC_FCP, LPFC_ELS, LPFC_USOL }; union sli4_qe { void *address; struct lpfc_eqe *eqe; struct lpfc_cqe *cqe; struct lpfc_mcqe *mcqe; struct lpfc_wcqe_complete *wcqe_complete; struct lpfc_wcqe_release *wcqe_release; struct sli4_wcqe_xri_aborted *wcqe_xri_aborted; struct lpfc_rcqe_complete *rcqe_complete; struct lpfc_mqe *mqe; union lpfc_wqe *wqe; union lpfc_wqe128 *wqe128; struct lpfc_rqe *rqe; }; struct lpfc_queue { struct list_head list; enum lpfc_sli4_queue_type type; enum lpfc_sli4_queue_subtype subtype; struct lpfc_hba *phba; struct list_head child_list; uint32_t entry_count; /* Number of entries to support on the queue */ uint32_t entry_size; /* Size of each queue entry. */ uint32_t entry_repost; /* Count of entries before doorbell is rung */ #define LPFC_QUEUE_MIN_REPOST 8 uint32_t queue_id; /* Queue ID assigned by the hardware */ uint32_t assoc_qid; /* Queue ID associated with, for CQ/WQ/MQ */ struct list_head page_list; uint32_t page_count; /* Number of pages allocated for this queue */ uint32_t host_index; /* The host's index for putting or getting */ uint32_t hba_index; /* The last known hba index for get or put */ struct lpfc_sli_ring *pring; /* ptr to io ring associated with q */ uint16_t db_format; #define LPFC_DB_RING_FORMAT 0x01 #define LPFC_DB_LIST_FORMAT 0x02 void __iomem *db_regaddr; /* For q stats */ uint32_t q_cnt_1; uint32_t q_cnt_2; uint32_t q_cnt_3; uint64_t q_cnt_4; /* defines for EQ stats */ #define EQ_max_eqe q_cnt_1 #define EQ_no_entry q_cnt_2 #define EQ_badstate q_cnt_3 #define EQ_processed q_cnt_4 /* defines for CQ stats */ #define CQ_mbox q_cnt_1 #define CQ_max_cqe q_cnt_1 #define CQ_release_wqe q_cnt_2 #define CQ_xri_aborted q_cnt_3 #define CQ_wq q_cnt_4 /* defines for WQ stats */ #define WQ_overflow q_cnt_1 #define WQ_posted q_cnt_4 /* defines for RQ stats */ #define RQ_no_posted_buf q_cnt_1 #define RQ_no_buf_found q_cnt_2 #define RQ_buf_trunc q_cnt_3 #define RQ_rcv_buf q_cnt_4 union sli4_qe qe[1]; /* array to index entries (must be last) */ }; struct lpfc_sli4_link { uint16_t speed; uint8_t duplex; uint8_t status; uint8_t type; uint8_t number; uint8_t fault; uint16_t logical_speed; uint16_t topology; }; struct lpfc_fcf_rec { uint8_t fabric_name[8]; uint8_t switch_name[8]; uint8_t mac_addr[6]; uint16_t fcf_indx; uint32_t priority; uint16_t vlan_id; uint32_t addr_mode; uint32_t flag; #define BOOT_ENABLE 0x01 #define RECORD_VALID 0x02 }; struct lpfc_fcf_pri_rec { uint16_t fcf_index; #define LPFC_FCF_ON_PRI_LIST 0x0001 #define LPFC_FCF_FLOGI_FAILED 0x0002 uint16_t flag; uint32_t priority; }; struct lpfc_fcf_pri { struct list_head list; struct lpfc_fcf_pri_rec fcf_rec; }; /* * Maximum FCF table index, it is for driver internal book keeping, it * just needs to be no less than the supported HBA's FCF table size. */ #define LPFC_SLI4_FCF_TBL_INDX_MAX 32 struct lpfc_fcf { uint16_t fcfi; uint32_t fcf_flag; #define FCF_AVAILABLE 0x01 /* FCF available for discovery */ #define FCF_REGISTERED 0x02 /* FCF registered with FW */ #define FCF_SCAN_DONE 0x04 /* FCF table scan done */ #define FCF_IN_USE 0x08 /* Atleast one discovery completed */ #define FCF_INIT_DISC 0x10 /* Initial FCF discovery */ #define FCF_DEAD_DISC 0x20 /* FCF DEAD fast FCF failover discovery */ #define FCF_ACVL_DISC 0x40 /* All CVL fast FCF failover discovery */ #define FCF_DISCOVERY (FCF_INIT_DISC | FCF_DEAD_DISC | FCF_ACVL_DISC) #define FCF_REDISC_PEND 0x80 /* FCF rediscovery pending */ #define FCF_REDISC_EVT 0x100 /* FCF rediscovery event to worker thread */ #define FCF_REDISC_FOV 0x200 /* Post FCF rediscovery fast failover */ #define FCF_REDISC_PROG (FCF_REDISC_PEND | FCF_REDISC_EVT) uint32_t addr_mode; uint32_t eligible_fcf_cnt; struct lpfc_fcf_rec current_rec; struct lpfc_fcf_rec failover_rec; struct list_head fcf_pri_list; struct lpfc_fcf_pri fcf_pri[LPFC_SLI4_FCF_TBL_INDX_MAX]; uint32_t current_fcf_scan_pri; struct timer_list redisc_wait; unsigned long *fcf_rr_bmask; /* Eligible FCF indexes for RR failover */ }; #define LPFC_REGION23_SIGNATURE "RG23" #define LPFC_REGION23_VERSION 1 #define LPFC_REGION23_LAST_REC 0xff #define DRIVER_SPECIFIC_TYPE 0xA2 #define LINUX_DRIVER_ID 0x20 #define PORT_STE_TYPE 0x1 struct lpfc_fip_param_hdr { uint8_t type; #define FCOE_PARAM_TYPE 0xA0 uint8_t length; #define FCOE_PARAM_LENGTH 2 uint8_t parm_version; #define FIPP_VERSION 0x01 uint8_t parm_flags; #define lpfc_fip_param_hdr_fipp_mode_SHIFT 6 #define lpfc_fip_param_hdr_fipp_mode_MASK 0x3 #define lpfc_fip_param_hdr_fipp_mode_WORD parm_flags #define FIPP_MODE_ON 0x1 #define FIPP_MODE_OFF 0x0 #define FIPP_VLAN_VALID 0x1 }; struct lpfc_fcoe_params { uint8_t fc_map[3]; uint8_t reserved1; uint16_t vlan_tag; uint8_t reserved[2]; }; struct lpfc_fcf_conn_hdr { uint8_t type; #define FCOE_CONN_TBL_TYPE 0xA1 uint8_t length; /* words */ uint8_t reserved[2]; }; struct lpfc_fcf_conn_rec { uint16_t flags; #define FCFCNCT_VALID 0x0001 #define FCFCNCT_BOOT 0x0002 #define FCFCNCT_PRIMARY 0x0004 /* if not set, Secondary */ #define FCFCNCT_FBNM_VALID 0x0008 #define FCFCNCT_SWNM_VALID 0x0010 #define FCFCNCT_VLAN_VALID 0x0020 #define FCFCNCT_AM_VALID 0x0040 #define FCFCNCT_AM_PREFERRED 0x0080 /* if not set, AM Required */ #define FCFCNCT_AM_SPMA 0x0100 /* if not set, FPMA */ uint16_t vlan_tag; uint8_t fabric_name[8]; uint8_t switch_name[8]; }; struct lpfc_fcf_conn_entry { struct list_head list; struct lpfc_fcf_conn_rec conn_rec; }; /* * Define the host's bootstrap mailbox. This structure contains * the member attributes needed to create, use, and destroy the * bootstrap mailbox region. * * The macro definitions for the bmbx data structure are defined * in lpfc_hw4.h with the register definition. */ struct lpfc_bmbx { struct lpfc_dmabuf *dmabuf; struct dma_address dma_address; void *avirt; dma_addr_t aphys; uint32_t bmbx_size; }; #define LPFC_EQE_SIZE LPFC_EQE_SIZE_4 #define LPFC_EQE_SIZE_4B 4 #define LPFC_EQE_SIZE_16B 16 #define LPFC_CQE_SIZE 16 #define LPFC_WQE_SIZE 64 #define LPFC_WQE128_SIZE 128 #define LPFC_MQE_SIZE 256 #define LPFC_RQE_SIZE 8 #define LPFC_EQE_DEF_COUNT 1024 #define LPFC_CQE_DEF_COUNT 1024 #define LPFC_WQE_DEF_COUNT 256 #define LPFC_WQE128_DEF_COUNT 128 #define LPFC_MQE_DEF_COUNT 16 #define LPFC_RQE_DEF_COUNT 512 #define LPFC_QUEUE_NOARM false #define LPFC_QUEUE_REARM true /* * SLI4 CT field defines */ #define SLI4_CT_RPI 0 #define SLI4_CT_VPI 1 #define SLI4_CT_VFI 2 #define SLI4_CT_FCFI 3 /* * SLI4 specific data structures */ struct lpfc_max_cfg_param { uint16_t max_xri; uint16_t xri_base; uint16_t xri_used; uint16_t max_rpi; uint16_t rpi_base; uint16_t rpi_used; uint16_t max_vpi; uint16_t vpi_base; uint16_t vpi_used; uint16_t max_vfi; uint16_t vfi_base; uint16_t vfi_used; uint16_t max_fcfi; uint16_t fcfi_used; uint16_t max_eq; uint16_t max_rq; uint16_t max_cq; uint16_t max_wq; }; struct lpfc_hba; /* SLI4 HBA multi-fcp queue handler struct */ struct lpfc_fcp_eq_hdl { uint32_t idx; struct lpfc_hba *phba; atomic_t fcp_eq_in_use; }; /* Port Capabilities for SLI4 Parameters */ struct lpfc_pc_sli4_params { uint32_t supported; uint32_t if_type; uint32_t sli_rev; uint32_t sli_family; uint32_t featurelevel_1; uint32_t featurelevel_2; uint32_t proto_types; #define LPFC_SLI4_PROTO_FCOE 0x0000001 #define LPFC_SLI4_PROTO_FC 0x0000002 #define LPFC_SLI4_PROTO_NIC 0x0000004 #define LPFC_SLI4_PROTO_ISCSI 0x0000008 #define LPFC_SLI4_PROTO_RDMA 0x0000010 uint32_t sge_supp_len; uint32_t if_page_sz; uint32_t rq_db_window; uint32_t loopbk_scope; uint32_t oas_supported; uint32_t eq_pages_max; uint32_t eqe_size; uint32_t cq_pages_max; uint32_t cqe_size; uint32_t mq_pages_max; uint32_t mqe_size; uint32_t mq_elem_cnt; uint32_t wq_pages_max; uint32_t wqe_size; uint32_t rq_pages_max; uint32_t rqe_size; uint32_t hdr_pages_max; uint32_t hdr_size; uint32_t hdr_pp_align; uint32_t sgl_pages_max; uint32_t sgl_pp_align; uint8_t cqv; uint8_t mqv; uint8_t wqv; uint8_t rqv; uint8_t wqsize; #define LPFC_WQ_SZ64_SUPPORT 1 #define LPFC_WQ_SZ128_SUPPORT 2 }; struct lpfc_iov { uint32_t pf_number; uint32_t vf_number; }; struct lpfc_sli4_lnk_info { uint8_t lnk_dv; #define LPFC_LNK_DAT_INVAL 0 #define LPFC_LNK_DAT_VAL 1 uint8_t lnk_tp; #define LPFC_LNK_GE 0x0 /* FCoE */ #define LPFC_LNK_FC 0x1 /* FC */ uint8_t lnk_no; uint8_t optic_state; }; #define LPFC_SLI4_HANDLER_CNT (LPFC_FCP_IO_CHAN_MAX+ \ LPFC_FOF_IO_CHAN_NUM) #define LPFC_SLI4_HANDLER_NAME_SZ 16 /* Used for IRQ vector to CPU mapping */ struct lpfc_vector_map_info { uint16_t phys_id; uint16_t core_id; uint16_t irq; uint16_t channel_id; }; #define LPFC_VECTOR_MAP_EMPTY 0xffff /* SLI4 HBA data structure entries */ struct lpfc_sli4_hba { void __iomem *conf_regs_memmap_p; /* Kernel memory mapped address for PCI BAR0, config space registers */ void __iomem *ctrl_regs_memmap_p; /* Kernel memory mapped address for PCI BAR1, control registers */ void __iomem *drbl_regs_memmap_p; /* Kernel memory mapped address for PCI BAR2, doorbell registers */ union { struct { /* IF Type 0, BAR 0 PCI cfg space reg mem map */ void __iomem *UERRLOregaddr; void __iomem *UERRHIregaddr; void __iomem *UEMASKLOregaddr; void __iomem *UEMASKHIregaddr; } if_type0; struct { /* IF Type 2, BAR 0 PCI cfg space reg mem map. */ void __iomem *STATUSregaddr; void __iomem *CTRLregaddr; void __iomem *ERR1regaddr; #define SLIPORT_ERR1_REG_ERR_CODE_1 0x1 #define SLIPORT_ERR1_REG_ERR_CODE_2 0x2 void __iomem *ERR2regaddr; #define SLIPORT_ERR2_REG_FW_RESTART 0x0 #define SLIPORT_ERR2_REG_FUNC_PROVISON 0x1 #define SLIPORT_ERR2_REG_FORCED_DUMP 0x2 #define SLIPORT_ERR2_REG_FAILURE_EQ 0x3 #define SLIPORT_ERR2_REG_FAILURE_CQ 0x4 #define SLIPORT_ERR2_REG_FAILURE_BUS 0x5 #define SLIPORT_ERR2_REG_FAILURE_RQ 0x6 } if_type2; } u; /* IF type 0, BAR1 and if type 2, Bar 0 CSR register memory map */ void __iomem *PSMPHRregaddr; /* Well-known SLI INTF register memory map. */ void __iomem *SLIINTFregaddr; /* IF type 0, BAR 1 function CSR register memory map */ void __iomem *ISRregaddr; /* HST_ISR register */ void __iomem *IMRregaddr; /* HST_IMR register */ void __iomem *ISCRregaddr; /* HST_ISCR register */ /* IF type 0, BAR 0 and if type 2, BAR 0 doorbell register memory map */ void __iomem *RQDBregaddr; /* RQ_DOORBELL register */ void __iomem *WQDBregaddr; /* WQ_DOORBELL register */ void __iomem *EQCQDBregaddr; /* EQCQ_DOORBELL register */ void __iomem *MQDBregaddr; /* MQ_DOORBELL register */ void __iomem *BMBXregaddr; /* BootStrap MBX register */ uint32_t ue_mask_lo; uint32_t ue_mask_hi; uint32_t ue_to_sr; uint32_t ue_to_rp; struct lpfc_register sli_intf; struct lpfc_pc_sli4_params pc_sli4_params; struct msix_entry *msix_entries; uint8_t handler_name[LPFC_SLI4_HANDLER_CNT][LPFC_SLI4_HANDLER_NAME_SZ]; struct lpfc_fcp_eq_hdl *fcp_eq_hdl; /* FCP per-WQ handle */ /* Pointers to the constructed SLI4 queues */ struct lpfc_queue **hba_eq;/* Event queues for HBA */ struct lpfc_queue **fcp_cq;/* Fast-path FCP compl queue */ struct lpfc_queue **fcp_wq;/* Fast-path FCP work queue */ uint16_t *fcp_cq_map; struct lpfc_queue *mbx_cq; /* Slow-path mailbox complete queue */ struct lpfc_queue *els_cq; /* Slow-path ELS response complete queue */ struct lpfc_queue *mbx_wq; /* Slow-path MBOX work queue */ struct lpfc_queue *els_wq; /* Slow-path ELS work queue */ struct lpfc_queue *hdr_rq; /* Slow-path Header Receive queue */ struct lpfc_queue *dat_rq; /* Slow-path Data Receive queue */ uint32_t fw_func_mode; /* FW function protocol mode */ uint32_t ulp0_mode; /* ULP0 protocol mode */ uint32_t ulp1_mode; /* ULP1 protocol mode */ struct lpfc_queue *fof_eq; /* Flash Optimized Fabric Event queue */ /* Optimized Access Storage specific queues/structures */ struct lpfc_queue *oas_cq; /* OAS completion queue */ struct lpfc_queue *oas_wq; /* OAS Work queue */ struct lpfc_sli_ring *oas_ring; uint64_t oas_next_lun; uint8_t oas_next_tgt_wwpn[8]; uint8_t oas_next_vpt_wwpn[8]; /* Setup information for various queue parameters */ int eq_esize; int eq_ecount; int cq_esize; int cq_ecount; int wq_esize; int wq_ecount; int mq_esize; int mq_ecount; int rq_esize; int rq_ecount; #define LPFC_SP_EQ_MAX_INTR_SEC 10000 #define LPFC_FP_EQ_MAX_INTR_SEC 10000 uint32_t intr_enable; struct lpfc_bmbx bmbx; struct lpfc_max_cfg_param max_cfg_param; uint16_t extents_in_use; /* must allocate resource extents. */ uint16_t rpi_hdrs_in_use; /* must post rpi hdrs if set. */ uint16_t next_xri; /* last_xri - max_cfg_param.xri_base = used */ uint16_t next_rpi; uint16_t scsi_xri_max; uint16_t scsi_xri_cnt; uint16_t els_xri_cnt; uint16_t scsi_xri_start; struct list_head lpfc_free_sgl_list; struct list_head lpfc_sgl_list; struct list_head lpfc_abts_els_sgl_list; struct list_head lpfc_abts_scsi_buf_list; struct lpfc_sglq **lpfc_sglq_active_list; struct list_head lpfc_rpi_hdr_list; unsigned long *rpi_bmask; uint16_t *rpi_ids; uint16_t rpi_count; struct list_head lpfc_rpi_blk_list; unsigned long *xri_bmask; uint16_t *xri_ids; struct list_head lpfc_xri_blk_list; unsigned long *vfi_bmask; uint16_t *vfi_ids; uint16_t vfi_count; struct list_head lpfc_vfi_blk_list; struct lpfc_sli4_flags sli4_flags; struct list_head sp_queue_event; struct list_head sp_cqe_event_pool; struct list_head sp_asynce_work_queue; struct list_head sp_fcp_xri_aborted_work_queue; struct list_head sp_els_xri_aborted_work_queue; struct list_head sp_unsol_work_queue; struct lpfc_sli4_link link_state; struct lpfc_sli4_lnk_info lnk_info; uint32_t pport_name_sta; #define LPFC_SLI4_PPNAME_NON 0 #define LPFC_SLI4_PPNAME_GET 1 struct lpfc_iov iov; spinlock_t abts_scsi_buf_list_lock; /* list of aborted SCSI IOs */ spinlock_t abts_sgl_list_lock; /* list of aborted els IOs */ uint32_t physical_port; /* CPU to vector mapping information */ struct lpfc_vector_map_info *cpu_map; uint16_t num_online_cpu; uint16_t num_present_cpu; uint16_t curr_disp_cpu; }; enum lpfc_sge_type { GEN_BUFF_TYPE, SCSI_BUFF_TYPE }; enum lpfc_sgl_state { SGL_FREED, SGL_ALLOCATED, SGL_XRI_ABORTED }; struct lpfc_sglq { /* lpfc_sglqs are used in double linked lists */ struct list_head list; struct list_head clist; enum lpfc_sge_type buff_type; /* is this a scsi sgl */ enum lpfc_sgl_state state; struct lpfc_nodelist *ndlp; /* ndlp associated with IO */ uint16_t iotag; /* pre-assigned IO tag */ uint16_t sli4_lxritag; /* logical pre-assigned xri. */ uint16_t sli4_xritag; /* pre-assigned XRI, (OXID) tag. */ struct sli4_sge *sgl; /* pre-assigned SGL */ void *virt; /* virtual address. */ dma_addr_t phys; /* physical address */ }; struct lpfc_rpi_hdr { struct list_head list; uint32_t len; struct lpfc_dmabuf *dmabuf; uint32_t page_count; uint32_t start_rpi; }; struct lpfc_rsrc_blks { struct list_head list; uint16_t rsrc_start; uint16_t rsrc_size; uint16_t rsrc_used; }; struct lpfc_rdp_context { struct lpfc_nodelist *ndlp; uint16_t ox_id; uint16_t rx_id; READ_LNK_VAR link_stat; uint8_t page_a0[DMP_SFF_PAGE_A0_SIZE]; uint8_t page_a2[DMP_SFF_PAGE_A2_SIZE]; void (*cmpl)(struct lpfc_hba *, struct lpfc_rdp_context*, int); }; struct lpfc_lcb_context { uint8_t sub_command; uint8_t type; uint8_t frequency; uint16_t ox_id; uint16_t rx_id; struct lpfc_nodelist *ndlp; }; /* * SLI4 specific function prototypes */ int lpfc_pci_function_reset(struct lpfc_hba *); int lpfc_sli4_pdev_status_reg_wait(struct lpfc_hba *); int lpfc_sli4_hba_setup(struct lpfc_hba *); int lpfc_sli4_config(struct lpfc_hba *, struct lpfcMboxq *, uint8_t, uint8_t, uint32_t, bool); void lpfc_sli4_mbox_cmd_free(struct lpfc_hba *, struct lpfcMboxq *); void lpfc_sli4_mbx_sge_set(struct lpfcMboxq *, uint32_t, dma_addr_t, uint32_t); void lpfc_sli4_mbx_sge_get(struct lpfcMboxq *, uint32_t, struct lpfc_mbx_sge *); int lpfc_sli4_mbx_read_fcf_rec(struct lpfc_hba *, struct lpfcMboxq *, uint16_t); void lpfc_sli4_hba_reset(struct lpfc_hba *); struct lpfc_queue *lpfc_sli4_queue_alloc(struct lpfc_hba *, uint32_t, uint32_t); void lpfc_sli4_queue_free(struct lpfc_queue *); int lpfc_eq_create(struct lpfc_hba *, struct lpfc_queue *, uint32_t); int lpfc_modify_fcp_eq_delay(struct lpfc_hba *, uint32_t); int lpfc_cq_create(struct lpfc_hba *, struct lpfc_queue *, struct lpfc_queue *, uint32_t, uint32_t); int32_t lpfc_mq_create(struct lpfc_hba *, struct lpfc_queue *, struct lpfc_queue *, uint32_t); int lpfc_wq_create(struct lpfc_hba *, struct lpfc_queue *, struct lpfc_queue *, uint32_t); int lpfc_rq_create(struct lpfc_hba *, struct lpfc_queue *, struct lpfc_queue *, struct lpfc_queue *, uint32_t); void lpfc_rq_adjust_repost(struct lpfc_hba *, struct lpfc_queue *, int); int lpfc_eq_destroy(struct lpfc_hba *, struct lpfc_queue *); int lpfc_cq_destroy(struct lpfc_hba *, struct lpfc_queue *); int lpfc_mq_destroy(struct lpfc_hba *, struct lpfc_queue *); int lpfc_wq_destroy(struct lpfc_hba *, struct lpfc_queue *); int lpfc_rq_destroy(struct lpfc_hba *, struct lpfc_queue *, struct lpfc_queue *); int lpfc_sli4_queue_setup(struct lpfc_hba *); void lpfc_sli4_queue_unset(struct lpfc_hba *); int lpfc_sli4_post_sgl(struct lpfc_hba *, dma_addr_t, dma_addr_t, uint16_t); int lpfc_sli4_repost_scsi_sgl_list(struct lpfc_hba *); uint16_t lpfc_sli4_next_xritag(struct lpfc_hba *); void lpfc_sli4_free_xri(struct lpfc_hba *, int); int lpfc_sli4_post_async_mbox(struct lpfc_hba *); int lpfc_sli4_post_scsi_sgl_block(struct lpfc_hba *, struct list_head *, int); struct lpfc_cq_event *__lpfc_sli4_cq_event_alloc(struct lpfc_hba *); struct lpfc_cq_event *lpfc_sli4_cq_event_alloc(struct lpfc_hba *); void __lpfc_sli4_cq_event_release(struct lpfc_hba *, struct lpfc_cq_event *); void lpfc_sli4_cq_event_release(struct lpfc_hba *, struct lpfc_cq_event *); int lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *); int lpfc_sli4_post_rpi_hdr(struct lpfc_hba *, struct lpfc_rpi_hdr *); int lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *); struct lpfc_rpi_hdr *lpfc_sli4_create_rpi_hdr(struct lpfc_hba *); void lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *); int lpfc_sli4_alloc_rpi(struct lpfc_hba *); void lpfc_sli4_free_rpi(struct lpfc_hba *, int); void lpfc_sli4_remove_rpis(struct lpfc_hba *); void lpfc_sli4_async_event_proc(struct lpfc_hba *); void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *); int lpfc_sli4_resume_rpi(struct lpfc_nodelist *, void (*)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *); void lpfc_sli4_fcp_xri_abort_event_proc(struct lpfc_hba *); void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *); void lpfc_sli4_fcp_xri_aborted(struct lpfc_hba *, struct sli4_wcqe_xri_aborted *); void lpfc_sli4_els_xri_aborted(struct lpfc_hba *, struct sli4_wcqe_xri_aborted *); void lpfc_sli4_vport_delete_els_xri_aborted(struct lpfc_vport *); void lpfc_sli4_vport_delete_fcp_xri_aborted(struct lpfc_vport *); int lpfc_sli4_brdreset(struct lpfc_hba *); int lpfc_sli4_add_fcf_record(struct lpfc_hba *, struct fcf_record *); void lpfc_sli_remove_dflt_fcf(struct lpfc_hba *); int lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *); int lpfc_sli4_init_vpi(struct lpfc_vport *); uint32_t lpfc_sli4_cq_release(struct lpfc_queue *, bool); uint32_t lpfc_sli4_eq_release(struct lpfc_queue *, bool); void lpfc_sli4_fcfi_unreg(struct lpfc_hba *, uint16_t); int lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *, uint16_t); int lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *, uint16_t); int lpfc_sli4_read_fcf_rec(struct lpfc_hba *, uint16_t); void lpfc_mbx_cmpl_fcf_scan_read_fcf_rec(struct lpfc_hba *, LPFC_MBOXQ_t *); void lpfc_mbx_cmpl_fcf_rr_read_fcf_rec(struct lpfc_hba *, LPFC_MBOXQ_t *); void lpfc_mbx_cmpl_read_fcf_rec(struct lpfc_hba *, LPFC_MBOXQ_t *); int lpfc_sli4_unregister_fcf(struct lpfc_hba *); int lpfc_sli4_post_status_check(struct lpfc_hba *); uint8_t lpfc_sli_config_mbox_subsys_get(struct lpfc_hba *, LPFC_MBOXQ_t *); uint8_t lpfc_sli_config_mbox_opcode_get(struct lpfc_hba *, LPFC_MBOXQ_t *);
{ "pile_set_name": "Github" }
namespace UnityEditor.Timeline { partial class TimelineWindow { void InitializeStateChange() { state.OnPlayStateChange += OnPreviewPlayModeChanged; state.OnDirtyStampChange += OnStateChange; state.OnBeforeSequenceChange += OnBeforeSequenceChange; state.OnAfterSequenceChange += OnAfterSequenceChange; state.OnRebuildGraphChange += () => { // called when the graph is rebuild, since the UI tree isn't necessarily rebuilt. if (!state.rebuildGraph) { // send callbacks to the tacks if (treeView != null) { var allTrackGuis = treeView.allTrackGuis; if (allTrackGuis != null) { for (int i = 0; i < allTrackGuis.Count; i++) allTrackGuis[i].OnGraphRebuilt(); } } } }; state.OnTimeChange += () => { if (EditorApplication.isPlaying == false) { state.UpdateRecordingState(); EditorApplication.SetSceneRepaintDirty(); } // the time is sync'd prior to the callback state.Evaluate(); // will do the repaint InspectorWindow.RepaintAllInspectors(); }; state.OnRecordingChange += () => { if (!state.recording) { TrackAssetRecordingExtensions.ClearRecordingState(); } }; } } }
{ "pile_set_name": "Github" }
from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass
{ "pile_set_name": "Github" }
import { Member } from './member'; import { Id } from './types'; export interface TeamData { title: string; } export type TeamWithoutMembers = Id & TeamData; export type Team = TeamWithoutMembers & { members: Member[]; };
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using Waher.Content.Markdown.Model.Atoms; namespace Waher.Content.Markdown.Model.SpanElements { /// <summary> /// Inline HTML. /// </summary> public class InlineHTML : MarkdownElement, IEditableText { private readonly string html; /// <summary> /// Inline HTML. /// </summary> /// <param name="Document">Markdown document.</param> /// <param name="HTML">Inline HTML.</param> public InlineHTML(MarkdownDocument Document, string HTML) : base(Document) { this.html = HTML; } /// <summary> /// HTML /// </summary> public string HTML { get { return this.html; } } /// <summary> /// Generates Markdown for the markdown element. /// </summary> /// <param name="Output">Markdown will be output here.</param> public override void GenerateMarkdown(StringBuilder Output) { Output.Append(this.html); } /// <summary> /// Generates HTML for the markdown element. /// </summary> /// <param name="Output">HTML will be output here.</param> public override void GenerateHTML(StringBuilder Output) { Output.Append(this.html); } /// <summary> /// Generates plain text for the markdown element. /// </summary> /// <param name="Output">Plain text will be output here.</param> public override void GeneratePlainText(StringBuilder Output) { } /// <summary> /// <see cref="Object.ToString()"/> /// </summary> public override string ToString() { return this.html; } /// <summary> /// Generates WPF XAML for the markdown element. /// </summary> /// <param name="Output">XAML will be output here.</param> /// <param name="TextAlignment">Alignment of text in element.</param> public override void GenerateXAML(XmlWriter Output, TextAlignment TextAlignment) { Output.WriteComment(this.html); } /// <summary> /// Generates Xamarin.Forms XAML for the markdown element. /// </summary> /// <param name="Output">XAML will be output here.</param> /// <param name="TextAlignment">Alignment of text in element.</param> public override void GenerateXamarinForms(XmlWriter Output, TextAlignment TextAlignment) { InlineText.GenerateInlineFormattedTextXamarinForms(Output, this); } /// <summary> /// If the element is an inline span element. /// </summary> internal override bool InlineSpanElement { get { return true; } } /// <summary> /// Exports the element to XML. /// </summary> /// <param name="Output">XML Output.</param> public override void Export(XmlWriter Output) { Output.WriteStartElement("Html"); Output.WriteCData(this.html); Output.WriteEndElement(); } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <param name="obj">The object to compare with the current object.</param> /// <returns>true if the specified object is equal to the current object; otherwise, false.</returns> public override bool Equals(object obj) { return obj is InlineHTML x && this.html == x.html && base.Equals(obj); } /// <summary> /// Serves as the default hash function. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { int h1 = base.GetHashCode(); int h2 = this.html?.GetHashCode() ?? 0; h1 = ((h1 << 5) + h1) ^ h2; return h1; } /// <summary> /// Return an enumeration of the editable HTML as atoms. /// </summary> /// <returns>Atoms.</returns> public IEnumerable<Atom> Atomize() { LinkedList<Atom> Result = new LinkedList<Atom>(); foreach (char ch in this.html) Result.AddLast(new InlineHtmlCharacter(this.Document, this, ch)); return Result; } /// <summary> /// Assembles a markdown element from a sequence of atoms. /// </summary> /// <param name="Document">Document that will contain the new element.</param> /// <param name="Text">Assembled text.</param> /// <returns>Assembled markdown element.</returns> public MarkdownElement Assemble(MarkdownDocument Document, string Text) { return new InlineHTML(Document, Text); } } }
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // 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/. #ifndef EIGEN_PARALLELIZER_H #define EIGEN_PARALLELIZER_H namespace Eigen { namespace internal { /** \internal */ inline void manage_multi_threading(Action action, int* v) { static EIGEN_UNUSED int m_maxThreads = -1; if(action==SetAction) { eigen_internal_assert(v!=0); m_maxThreads = *v; } else if(action==GetAction) { eigen_internal_assert(v!=0); #ifdef EIGEN_HAS_OPENMP if(m_maxThreads>0) *v = m_maxThreads; else *v = omp_get_max_threads(); #else *v = 1; #endif } else { eigen_internal_assert(false); } } } /** Must be call first when calling Eigen from multiple threads */ inline void initParallel() { int nbt; internal::manage_multi_threading(GetAction, &nbt); std::ptrdiff_t l1, l2; internal::manage_caching_sizes(GetAction, &l1, &l2); } /** \returns the max number of threads reserved for Eigen * \sa setNbThreads */ inline int nbThreads() { int ret; internal::manage_multi_threading(GetAction, &ret); return ret; } /** Sets the max number of threads reserved for Eigen * \sa nbThreads */ inline void setNbThreads(int v) { internal::manage_multi_threading(SetAction, &v); } namespace internal { template<typename Index> struct GemmParallelInfo { GemmParallelInfo() : sync(-1), users(0), rhs_start(0), rhs_length(0) {} int volatile sync; int volatile users; Index rhs_start; Index rhs_length; }; template<bool Condition, typename Functor, typename Index> void parallelize_gemm(const Functor& func, Index rows, Index cols, bool transpose) { // TODO when EIGEN_USE_BLAS is defined, // we should still enable OMP for other scalar types #if !(defined (EIGEN_HAS_OPENMP)) || defined (EIGEN_USE_BLAS) // FIXME the transpose variable is only needed to properly split // the matrix product when multithreading is enabled. This is a temporary // fix to support row-major destination matrices. This whole // parallelizer mechanism has to be redisigned anyway. EIGEN_UNUSED_VARIABLE(transpose); func(0,rows, 0,cols); #else // Dynamically check whether we should enable or disable OpenMP. // The conditions are: // - the max number of threads we can create is greater than 1 // - we are not already in a parallel code // - the sizes are large enough // 1- are we already in a parallel session? // FIXME omp_get_num_threads()>1 only works for openmp, what if the user does not use openmp? if((!Condition) || (omp_get_num_threads()>1)) return func(0,rows, 0,cols); Index size = transpose ? cols : rows; // 2- compute the maximal number of threads from the size of the product: // FIXME this has to be fine tuned Index max_threads = std::max<Index>(1,size / 32); // 3 - compute the number of threads we are going to use Index threads = std::min<Index>(nbThreads(), max_threads); if(threads==1) return func(0,rows, 0,cols); Eigen::initParallel(); func.initParallelSession(); if(transpose) std::swap(rows,cols); Index blockCols = (cols / threads) & ~Index(0x3); Index blockRows = (rows / threads) & ~Index(0x7); GemmParallelInfo<Index>* info = new GemmParallelInfo<Index>[threads]; #pragma omp parallel for schedule(static,1) num_threads(threads) for(Index i=0; i<threads; ++i) { Index r0 = i*blockRows; Index actualBlockRows = (i+1==threads) ? rows-r0 : blockRows; Index c0 = i*blockCols; Index actualBlockCols = (i+1==threads) ? cols-c0 : blockCols; info[i].rhs_start = c0; info[i].rhs_length = actualBlockCols; if(transpose) func(0, cols, r0, actualBlockRows, info); else func(r0, actualBlockRows, 0,cols, info); } delete[] info; #endif } } // end namespace internal } // end namespace Eigen #endif // EIGEN_PARALLELIZER_H
{ "pile_set_name": "Github" }
/****************************************************************************** * $Id$ * * Project: GDAL Core * Purpose: GDAL Core C/Public declarations. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1998, 2002 Frank Warmerdam * Copyright (c) 2007-2014, Even Rouault <even dot rouault at mines-paris dot org> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef GDAL_H_INCLUDED #define GDAL_H_INCLUDED /** * \file gdal.h * * Public (C callable) GDAL entry points. */ #ifndef DOXYGEN_SKIP #include "gdal_version.h" #include "cpl_port.h" #include "cpl_error.h" #include "cpl_progress.h" #include "cpl_virtualmem.h" #include "cpl_minixml.h" #include "ogr_api.h" #endif /* -------------------------------------------------------------------- */ /* Significant constants. */ /* -------------------------------------------------------------------- */ CPL_C_START /*! Pixel data types */ typedef enum { /*! Unknown or unspecified type */ GDT_Unknown = 0, /*! Eight bit unsigned integer */ GDT_Byte = 1, /*! Sixteen bit unsigned integer */ GDT_UInt16 = 2, /*! Sixteen bit signed integer */ GDT_Int16 = 3, /*! Thirty two bit unsigned integer */ GDT_UInt32 = 4, /*! Thirty two bit signed integer */ GDT_Int32 = 5, /*! Thirty two bit floating point */ GDT_Float32 = 6, /*! Sixty four bit floating point */ GDT_Float64 = 7, /*! Complex Int16 */ GDT_CInt16 = 8, /*! Complex Int32 */ GDT_CInt32 = 9, /*! Complex Float32 */ GDT_CFloat32 = 10, /*! Complex Float64 */ GDT_CFloat64 = 11, GDT_TypeCount = 12 /* maximum type # + 1 */ } GDALDataType; int CPL_DLL CPL_STDCALL GDALGetDataTypeSize( GDALDataType ); // Deprecated. int CPL_DLL CPL_STDCALL GDALGetDataTypeSizeBits( GDALDataType eDataType ); int CPL_DLL CPL_STDCALL GDALGetDataTypeSizeBytes( GDALDataType ); int CPL_DLL CPL_STDCALL GDALDataTypeIsComplex( GDALDataType ); const char CPL_DLL * CPL_STDCALL GDALGetDataTypeName( GDALDataType ); GDALDataType CPL_DLL CPL_STDCALL GDALGetDataTypeByName( const char * ); GDALDataType CPL_DLL CPL_STDCALL GDALDataTypeUnion( GDALDataType, GDALDataType ); double CPL_DLL GDALAdjustValueToDataType( GDALDataType eDT, double dfValue, int* pbClamped, int* pbRounded ); /** * status of the asynchronous stream */ typedef enum { GARIO_PENDING = 0, GARIO_UPDATE = 1, GARIO_ERROR = 2, GARIO_COMPLETE = 3, GARIO_TypeCount = 4 } GDALAsyncStatusType; const char CPL_DLL * CPL_STDCALL GDALGetAsyncStatusTypeName( GDALAsyncStatusType ); GDALAsyncStatusType CPL_DLL CPL_STDCALL GDALGetAsyncStatusTypeByName( const char * ); /*! Flag indicating read/write, or read-only access to data. */ typedef enum { /*! Read only (no update) access */ GA_ReadOnly = 0, /*! Read/write access. */ GA_Update = 1 } GDALAccess; /*! Read/Write flag for RasterIO() method */ typedef enum { /*! Read data */ GF_Read = 0, /*! Write data */ GF_Write = 1 } GDALRWFlag; /* NOTE: values are selected to be consistent with GDALResampleAlg of alg/gdalwarper.h */ /** RasterIO() resampling method. * @since GDAL 2.0 */ typedef enum { /*! Nearest neighbour */ GRIORA_NearestNeighbour = 0, /*! Bilinear (2x2 kernel) */ GRIORA_Bilinear = 1, /*! Cubic Convolution Approximation (4x4 kernel) */ GRIORA_Cubic = 2, /*! Cubic B-Spline Approximation (4x4 kernel) */ GRIORA_CubicSpline = 3, /*! Lanczos windowed sinc interpolation (6x6 kernel) */ GRIORA_Lanczos = 4, /*! Average */ GRIORA_Average = 5, /*! Mode (selects the value which appears most often of all the sampled points) */ GRIORA_Mode = 6, /*! Gauss blurring */ GRIORA_Gauss = 7 /* NOTE: values 8 to 12 are reserved for max,min,med,Q1,Q3 */ } GDALRIOResampleAlg; /* NOTE to developers: only add members, and if so edit INIT_RASTERIO_EXTRA_ARG */ /* and INIT_RASTERIO_EXTRA_ARG */ /** Structure to pass extra arguments to RasterIO() method * @since GDAL 2.0 */ typedef struct { /*! Version of structure (to allow future extensions of the structure) */ int nVersion; /*! Resampling algorithm */ GDALRIOResampleAlg eResampleAlg; /*! Progress callback */ GDALProgressFunc pfnProgress; /*! Progress callback user data */ void *pProgressData; /*! Indicate if dfXOff, dfYOff, dfXSize and dfYSize are set. Mostly reserved from the VRT driver to communicate a more precise source window. Must be such that dfXOff - nXOff < 1.0 and dfYOff - nYOff < 1.0 and nXSize - dfXSize < 1.0 and nYSize - dfYSize < 1.0 */ int bFloatingPointWindowValidity; /*! Pixel offset to the top left corner. Only valid if bFloatingPointWindowValidity = TRUE */ double dfXOff; /*! Line offset to the top left corner. Only valid if bFloatingPointWindowValidity = TRUE */ double dfYOff; /*! Width in pixels of the area of interest. Only valid if bFloatingPointWindowValidity = TRUE */ double dfXSize; /*! Height in pixels of the area of interest. Only valid if bFloatingPointWindowValidity = TRUE */ double dfYSize; } GDALRasterIOExtraArg; #define RASTERIO_EXTRA_ARG_CURRENT_VERSION 1 /** Macro to initialize an instance of GDALRasterIOExtraArg structure. * @since GDAL 2.0 */ #define INIT_RASTERIO_EXTRA_ARG(s) \ do { (s).nVersion = RASTERIO_EXTRA_ARG_CURRENT_VERSION; \ (s).eResampleAlg = GRIORA_NearestNeighbour; \ (s).pfnProgress = NULL; \ (s).pProgressData = NULL; \ (s).bFloatingPointWindowValidity = FALSE; } while(0) /*! Types of color interpretation for raster bands. */ typedef enum { GCI_Undefined=0, /*! Greyscale */ GCI_GrayIndex=1, /*! Paletted (see associated color table) */ GCI_PaletteIndex=2, /*! Red band of RGBA image */ GCI_RedBand=3, /*! Green band of RGBA image */ GCI_GreenBand=4, /*! Blue band of RGBA image */ GCI_BlueBand=5, /*! Alpha (0=transparent, 255=opaque) */ GCI_AlphaBand=6, /*! Hue band of HLS image */ GCI_HueBand=7, /*! Saturation band of HLS image */ GCI_SaturationBand=8, /*! Lightness band of HLS image */ GCI_LightnessBand=9, /*! Cyan band of CMYK image */ GCI_CyanBand=10, /*! Magenta band of CMYK image */ GCI_MagentaBand=11, /*! Yellow band of CMYK image */ GCI_YellowBand=12, /*! Black band of CMLY image */ GCI_BlackBand=13, /*! Y Luminance */ GCI_YCbCr_YBand=14, /*! Cb Chroma */ GCI_YCbCr_CbBand=15, /*! Cr Chroma */ GCI_YCbCr_CrBand=16, /*! Max current value */ GCI_Max=16 } GDALColorInterp; const char CPL_DLL *GDALGetColorInterpretationName( GDALColorInterp ); GDALColorInterp CPL_DLL GDALGetColorInterpretationByName( const char *pszName ); /*! Types of color interpretations for a GDALColorTable. */ typedef enum { /*! Grayscale (in GDALColorEntry.c1) */ GPI_Gray=0, /*! Red, Green, Blue and Alpha in (in c1, c2, c3 and c4) */ GPI_RGB=1, /*! Cyan, Magenta, Yellow and Black (in c1, c2, c3 and c4)*/ GPI_CMYK=2, /*! Hue, Lightness and Saturation (in c1, c2, and c3) */ GPI_HLS=3 } GDALPaletteInterp; const char CPL_DLL *GDALGetPaletteInterpretationName( GDALPaletteInterp ); /* "well known" metadata items. */ #define GDALMD_AREA_OR_POINT "AREA_OR_POINT" # define GDALMD_AOP_AREA "Area" # define GDALMD_AOP_POINT "Point" /* -------------------------------------------------------------------- */ /* GDAL Specific error codes. */ /* */ /* error codes 100 to 299 reserved for GDAL. */ /* -------------------------------------------------------------------- */ #define CPLE_WrongFormat (CPLErrorNum)200 /* -------------------------------------------------------------------- */ /* Define handle types related to various internal classes. */ /* -------------------------------------------------------------------- */ /** Opaque type used for the C bindings of the C++ GDALMajorObject class */ typedef void *GDALMajorObjectH; /** Opaque type used for the C bindings of the C++ GDALDataset class */ typedef void *GDALDatasetH; /** Opaque type used for the C bindings of the C++ GDALRasterBand class */ typedef void *GDALRasterBandH; /** Opaque type used for the C bindings of the C++ GDALDriver class */ typedef void *GDALDriverH; /** Opaque type used for the C bindings of the C++ GDALColorTable class */ typedef void *GDALColorTableH; /** Opaque type used for the C bindings of the C++ GDALRasterAttributeTable class */ typedef void *GDALRasterAttributeTableH; /** Opaque type used for the C bindings of the C++ GDALAsyncReader class */ typedef void *GDALAsyncReaderH; /** Type to express pixel, line or band spacing. Signed 64 bit integer. */ typedef GIntBig GSpacing; /* ==================================================================== */ /* Registration/driver related. */ /* ==================================================================== */ /** Long name of the driver */ #define GDAL_DMD_LONGNAME "DMD_LONGNAME" /** URL (relative to http://gdal.org/) to the help page of the driver */ #define GDAL_DMD_HELPTOPIC "DMD_HELPTOPIC" /** MIME type handled by the driver. */ #define GDAL_DMD_MIMETYPE "DMD_MIMETYPE" /** Extension handled by the driver. */ #define GDAL_DMD_EXTENSION "DMD_EXTENSION" /** Connection prefix to provide as the file name of the open function. * Typically set for non-file based drivers. Generally used with open options. * @since GDAL 2.0 */ #define GDAL_DMD_CONNECTION_PREFIX "DMD_CONNECTION_PREFIX" /** List of (space separated) extensions handled by the driver. * @since GDAL 2.0 */ #define GDAL_DMD_EXTENSIONS "DMD_EXTENSIONS" /** XML snippet with creation options. */ #define GDAL_DMD_CREATIONOPTIONLIST "DMD_CREATIONOPTIONLIST" /** XML snippet with open options. * @since GDAL 2.0 */ #define GDAL_DMD_OPENOPTIONLIST "DMD_OPENOPTIONLIST" /** List of (space separated) raster data types support by the Create()/CreateCopy() API. */ #define GDAL_DMD_CREATIONDATATYPES "DMD_CREATIONDATATYPES" /** List of (space separated) vector field types support by the CreateField() API. * @since GDAL 2.0 * */ #define GDAL_DMD_CREATIONFIELDDATATYPES "DMD_CREATIONFIELDDATATYPES" /** Capability set by a driver that exposes Subdatasets. */ #define GDAL_DMD_SUBDATASETS "DMD_SUBDATASETS" /** Capability set by a driver that implements the Open() API. */ #define GDAL_DCAP_OPEN "DCAP_OPEN" /** Capability set by a driver that implements the Create() API. */ #define GDAL_DCAP_CREATE "DCAP_CREATE" /** Capability set by a driver that implements the CreateCopy() API. */ #define GDAL_DCAP_CREATECOPY "DCAP_CREATECOPY" /** Capability set by a driver that can read/create datasets through the VSI*L API. */ #define GDAL_DCAP_VIRTUALIO "DCAP_VIRTUALIO" /** Capability set by a driver having raster capability. * @since GDAL 2.0 */ #define GDAL_DCAP_RASTER "DCAP_RASTER" /** Capability set by a driver having vector capability. * @since GDAL 2.0 */ #define GDAL_DCAP_VECTOR "DCAP_VECTOR" /** Capability set by a driver having vector capability. * @since GDAL 2.1 */ #define GDAL_DCAP_GNM "DCAP_GNM" /** Capability set by a driver that can create fields with NOT NULL constraint. * @since GDAL 2.0 */ #define GDAL_DCAP_NOTNULL_FIELDS "DCAP_NOTNULL_FIELDS" /** Capability set by a driver that can create fields with DEFAULT values. * @since GDAL 2.0 */ #define GDAL_DCAP_DEFAULT_FIELDS "DCAP_DEFAULT_FIELDS" /** Capability set by a driver that can create geometry fields with NOT NULL constraint. * @since GDAL 2.0 */ #define GDAL_DCAP_NOTNULL_GEOMFIELDS "DCAP_NOTNULL_GEOMFIELDS" void CPL_DLL CPL_STDCALL GDALAllRegister( void ); GDALDatasetH CPL_DLL CPL_STDCALL GDALCreate( GDALDriverH hDriver, const char *, int, int, int, GDALDataType, char ** ) CPL_WARN_UNUSED_RESULT; GDALDatasetH CPL_DLL CPL_STDCALL GDALCreateCopy( GDALDriverH, const char *, GDALDatasetH, int, char **, GDALProgressFunc, void * ) CPL_WARN_UNUSED_RESULT; GDALDriverH CPL_DLL CPL_STDCALL GDALIdentifyDriver( const char * pszFilename, char ** papszFileList ); GDALDatasetH CPL_DLL CPL_STDCALL GDALOpen( const char *pszFilename, GDALAccess eAccess ) CPL_WARN_UNUSED_RESULT; GDALDatasetH CPL_DLL CPL_STDCALL GDALOpenShared( const char *, GDALAccess ) CPL_WARN_UNUSED_RESULT; /* Note: we define GDAL_OF_READONLY and GDAL_OF_UPDATE to be on purpose */ /* equals to GA_ReadOnly and GA_Update */ /** Open in read-only mode. * Used by GDALOpenEx(). * @since GDAL 2.0 */ #define GDAL_OF_READONLY 0x00 /** Open in update mode. * Used by GDALOpenEx(). * @since GDAL 2.0 */ #define GDAL_OF_UPDATE 0x01 /** Allow raster and vector drivers to be used. * Used by GDALOpenEx(). * @since GDAL 2.0 */ #define GDAL_OF_ALL 0x00 /** Allow raster drivers to be used. * Used by GDALOpenEx(). * @since GDAL 2.0 */ #define GDAL_OF_RASTER 0x02 /** Allow vector drivers to be used. * Used by GDALOpenEx(). * @since GDAL 2.0 */ #define GDAL_OF_VECTOR 0x04 /** Allow gnm drivers to be used. * Used by GDALOpenEx(). * @since GDAL 2.1 */ #define GDAL_OF_GNM 0x08 /* Some space for GDAL 3.0 new types ;-) */ /*#define GDAL_OF_OTHER_KIND1 0x08 */ /*#define GDAL_OF_OTHER_KIND2 0x10 */ #ifndef DOXYGEN_SKIP #define GDAL_OF_KIND_MASK 0x1E #endif /** Open in shared mode. * Used by GDALOpenEx(). * @since GDAL 2.0 */ #define GDAL_OF_SHARED 0x20 /** Emit error message in case of failed open. * Used by GDALOpenEx(). * @since GDAL 2.0 */ #define GDAL_OF_VERBOSE_ERROR 0x40 /** Open as internal dataset. Such dataset isn't registered in the global list * of opened dataset. Cannot be used with GDAL_OF_SHARED. * * Used by GDALOpenEx(). * @since GDAL 2.0 */ #define GDAL_OF_INTERNAL 0x80 /** Let GDAL decide if a array-based or hashset-based storage strategy for * cached blocks must be used. * * GDAL_OF_DEFAULT_BLOCK_ACCESS, GDAL_OF_ARRAY_BLOCK_ACCESS and * GDAL_OF_HASHSET_BLOCK_ACCESS are mutually exclusive. * * Used by GDALOpenEx(). * @since GDAL 2.1 */ #define GDAL_OF_DEFAULT_BLOCK_ACCESS 0 /** Use a array-based storage strategy for cached blocks. * * GDAL_OF_DEFAULT_BLOCK_ACCESS, GDAL_OF_ARRAY_BLOCK_ACCESS and * GDAL_OF_HASHSET_BLOCK_ACCESS are mutually exclusive. * * Used by GDALOpenEx(). * @since GDAL 2.1 */ #define GDAL_OF_ARRAY_BLOCK_ACCESS 0x100 /** Use a hashset-based storage strategy for cached blocks. * * GDAL_OF_DEFAULT_BLOCK_ACCESS, GDAL_OF_ARRAY_BLOCK_ACCESS and * GDAL_OF_HASHSET_BLOCK_ACCESS are mutually exclusive. * * Used by GDALOpenEx(). * @since GDAL 2.1 */ #define GDAL_OF_HASHSET_BLOCK_ACCESS 0x200 #define GDAL_OF_RESERVED_1 0x300 #define GDAL_OF_BLOCK_ACCESS_MASK 0x300 GDALDatasetH CPL_DLL CPL_STDCALL GDALOpenEx( const char* pszFilename, unsigned int nOpenFlags, const char* const* papszAllowedDrivers, const char* const* papszOpenOptions, const char* const* papszSiblingFiles ) CPL_WARN_UNUSED_RESULT; int CPL_DLL CPL_STDCALL GDALDumpOpenDatasets( FILE * ); GDALDriverH CPL_DLL CPL_STDCALL GDALGetDriverByName( const char * ); int CPL_DLL CPL_STDCALL GDALGetDriverCount( void ); GDALDriverH CPL_DLL CPL_STDCALL GDALGetDriver( int ); void CPL_DLL CPL_STDCALL GDALDestroyDriver( GDALDriverH ); int CPL_DLL CPL_STDCALL GDALRegisterDriver( GDALDriverH ); void CPL_DLL CPL_STDCALL GDALDeregisterDriver( GDALDriverH ); void CPL_DLL CPL_STDCALL GDALDestroyDriverManager( void ); void CPL_DLL GDALDestroy( void ); CPLErr CPL_DLL CPL_STDCALL GDALDeleteDataset( GDALDriverH, const char * ); CPLErr CPL_DLL CPL_STDCALL GDALRenameDataset( GDALDriverH, const char * pszNewName, const char * pszOldName ); CPLErr CPL_DLL CPL_STDCALL GDALCopyDatasetFiles( GDALDriverH, const char * pszNewName, const char * pszOldName); int CPL_DLL CPL_STDCALL GDALValidateCreationOptions( GDALDriverH, char** papszCreationOptions); /* The following are deprecated */ const char CPL_DLL * CPL_STDCALL GDALGetDriverShortName( GDALDriverH ); const char CPL_DLL * CPL_STDCALL GDALGetDriverLongName( GDALDriverH ); const char CPL_DLL * CPL_STDCALL GDALGetDriverHelpTopic( GDALDriverH ); const char CPL_DLL * CPL_STDCALL GDALGetDriverCreationOptionList( GDALDriverH ); /* ==================================================================== */ /* GDAL_GCP */ /* ==================================================================== */ /** Ground Control Point */ typedef struct { /** Unique identifier, often numeric */ char *pszId; /** Informational message or "" */ char *pszInfo; /** Pixel (x) location of GCP on raster */ double dfGCPPixel; /** Line (y) location of GCP on raster */ double dfGCPLine; /** X position of GCP in georeferenced space */ double dfGCPX; /** Y position of GCP in georeferenced space */ double dfGCPY; /** Elevation of GCP, or zero if not known */ double dfGCPZ; } GDAL_GCP; void CPL_DLL CPL_STDCALL GDALInitGCPs( int, GDAL_GCP * ); void CPL_DLL CPL_STDCALL GDALDeinitGCPs( int, GDAL_GCP * ); GDAL_GCP CPL_DLL * CPL_STDCALL GDALDuplicateGCPs( int, const GDAL_GCP * ); int CPL_DLL CPL_STDCALL GDALGCPsToGeoTransform( int nGCPCount, const GDAL_GCP *pasGCPs, double *padfGeoTransform, int bApproxOK ) CPL_WARN_UNUSED_RESULT; int CPL_DLL CPL_STDCALL GDALInvGeoTransform( double *padfGeoTransformIn, double *padfInvGeoTransformOut ) CPL_WARN_UNUSED_RESULT; void CPL_DLL CPL_STDCALL GDALApplyGeoTransform( double *, double, double, double *, double * ); void CPL_DLL GDALComposeGeoTransforms(const double *padfGeoTransform1, const double *padfGeoTransform2, double *padfGeoTransformOut); /* ==================================================================== */ /* major objects (dataset, and, driver, drivermanager). */ /* ==================================================================== */ char CPL_DLL ** CPL_STDCALL GDALGetMetadataDomainList( GDALMajorObjectH hObject ); char CPL_DLL ** CPL_STDCALL GDALGetMetadata( GDALMajorObjectH, const char * ); CPLErr CPL_DLL CPL_STDCALL GDALSetMetadata( GDALMajorObjectH, char **, const char * ); const char CPL_DLL * CPL_STDCALL GDALGetMetadataItem( GDALMajorObjectH, const char *, const char * ); CPLErr CPL_DLL CPL_STDCALL GDALSetMetadataItem( GDALMajorObjectH, const char *, const char *, const char * ); const char CPL_DLL * CPL_STDCALL GDALGetDescription( GDALMajorObjectH ); void CPL_DLL CPL_STDCALL GDALSetDescription( GDALMajorObjectH, const char * ); /* ==================================================================== */ /* GDALDataset class ... normally this represents one file. */ /* ==================================================================== */ #define GDAL_DS_LAYER_CREATIONOPTIONLIST "DS_LAYER_CREATIONOPTIONLIST" GDALDriverH CPL_DLL CPL_STDCALL GDALGetDatasetDriver( GDALDatasetH ); char CPL_DLL ** CPL_STDCALL GDALGetFileList( GDALDatasetH ); void CPL_DLL CPL_STDCALL GDALClose( GDALDatasetH ); int CPL_DLL CPL_STDCALL GDALGetRasterXSize( GDALDatasetH ); int CPL_DLL CPL_STDCALL GDALGetRasterYSize( GDALDatasetH ); int CPL_DLL CPL_STDCALL GDALGetRasterCount( GDALDatasetH ); GDALRasterBandH CPL_DLL CPL_STDCALL GDALGetRasterBand( GDALDatasetH, int ); CPLErr CPL_DLL CPL_STDCALL GDALAddBand( GDALDatasetH hDS, GDALDataType eType, char **papszOptions ); GDALAsyncReaderH CPL_DLL CPL_STDCALL GDALBeginAsyncReader(GDALDatasetH hDS, int nXOff, int nYOff, int nXSize, int nYSize, void *pBuf, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int* panBandMap, int nPixelSpace, int nLineSpace, int nBandSpace, char **papszOptions) CPL_WARN_UNUSED_RESULT; void CPL_DLL CPL_STDCALL GDALEndAsyncReader(GDALDatasetH hDS, GDALAsyncReaderH hAsynchReaderH); CPLErr CPL_DLL CPL_STDCALL GDALDatasetRasterIO( GDALDatasetH hDS, GDALRWFlag eRWFlag, int nDSXOff, int nDSYOff, int nDSXSize, int nDSYSize, void * pBuffer, int nBXSize, int nBYSize, GDALDataType eBDataType, int nBandCount, int *panBandCount, int nPixelSpace, int nLineSpace, int nBandSpace) CPL_WARN_UNUSED_RESULT; CPLErr CPL_DLL CPL_STDCALL GDALDatasetRasterIOEx( GDALDatasetH hDS, GDALRWFlag eRWFlag, int nDSXOff, int nDSYOff, int nDSXSize, int nDSYSize, void * pBuffer, int nBXSize, int nBYSize, GDALDataType eBDataType, int nBandCount, int *panBandCount, GSpacing nPixelSpace, GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg* psExtraArg) CPL_WARN_UNUSED_RESULT; CPLErr CPL_DLL CPL_STDCALL GDALDatasetAdviseRead( GDALDatasetH hDS, int nDSXOff, int nDSYOff, int nDSXSize, int nDSYSize, int nBXSize, int nBYSize, GDALDataType eBDataType, int nBandCount, int *panBandCount, char **papszOptions ); const char CPL_DLL * CPL_STDCALL GDALGetProjectionRef( GDALDatasetH ); CPLErr CPL_DLL CPL_STDCALL GDALSetProjection( GDALDatasetH, const char * ); CPLErr CPL_DLL CPL_STDCALL GDALGetGeoTransform( GDALDatasetH, double * ); CPLErr CPL_DLL CPL_STDCALL GDALSetGeoTransform( GDALDatasetH, double * ); int CPL_DLL CPL_STDCALL GDALGetGCPCount( GDALDatasetH ); const char CPL_DLL * CPL_STDCALL GDALGetGCPProjection( GDALDatasetH ); const GDAL_GCP CPL_DLL * CPL_STDCALL GDALGetGCPs( GDALDatasetH ); CPLErr CPL_DLL CPL_STDCALL GDALSetGCPs( GDALDatasetH, int, const GDAL_GCP *, const char * ); void CPL_DLL * CPL_STDCALL GDALGetInternalHandle( GDALDatasetH, const char * ); int CPL_DLL CPL_STDCALL GDALReferenceDataset( GDALDatasetH ); int CPL_DLL CPL_STDCALL GDALDereferenceDataset( GDALDatasetH ); CPLErr CPL_DLL CPL_STDCALL GDALBuildOverviews( GDALDatasetH, const char *, int, int *, int, int *, GDALProgressFunc, void * ) CPL_WARN_UNUSED_RESULT; void CPL_DLL CPL_STDCALL GDALGetOpenDatasets( GDALDatasetH **hDS, int *pnCount ); int CPL_DLL CPL_STDCALL GDALGetAccess( GDALDatasetH hDS ); void CPL_DLL CPL_STDCALL GDALFlushCache( GDALDatasetH hDS ); CPLErr CPL_DLL CPL_STDCALL GDALCreateDatasetMaskBand( GDALDatasetH hDS, int nFlags ); CPLErr CPL_DLL CPL_STDCALL GDALDatasetCopyWholeRaster( GDALDatasetH hSrcDS, GDALDatasetH hDstDS, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressData ) CPL_WARN_UNUSED_RESULT; CPLErr CPL_DLL CPL_STDCALL GDALRasterBandCopyWholeRaster( GDALRasterBandH hSrcBand, GDALRasterBandH hDstBand, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressData ) CPL_WARN_UNUSED_RESULT; CPLErr CPL_DLL GDALRegenerateOverviews( GDALRasterBandH hSrcBand, int nOverviewCount, GDALRasterBandH *pahOverviewBands, const char *pszResampling, GDALProgressFunc pfnProgress, void *pProgressData ); int CPL_DLL GDALDatasetGetLayerCount( GDALDatasetH ); OGRLayerH CPL_DLL GDALDatasetGetLayer( GDALDatasetH, int ); OGRLayerH CPL_DLL GDALDatasetGetLayerByName( GDALDatasetH, const char * ); OGRErr CPL_DLL GDALDatasetDeleteLayer( GDALDatasetH, int ); OGRLayerH CPL_DLL GDALDatasetCreateLayer( GDALDatasetH, const char *, OGRSpatialReferenceH, OGRwkbGeometryType, char ** ); OGRLayerH CPL_DLL GDALDatasetCopyLayer( GDALDatasetH, OGRLayerH, const char *, char ** ); int CPL_DLL GDALDatasetTestCapability( GDALDatasetH, const char * ); OGRLayerH CPL_DLL GDALDatasetExecuteSQL( GDALDatasetH, const char *, OGRGeometryH, const char * ); void CPL_DLL GDALDatasetReleaseResultSet( GDALDatasetH, OGRLayerH ); OGRStyleTableH CPL_DLL GDALDatasetGetStyleTable( GDALDatasetH ); void CPL_DLL GDALDatasetSetStyleTableDirectly( GDALDatasetH, OGRStyleTableH ); void CPL_DLL GDALDatasetSetStyleTable( GDALDatasetH, OGRStyleTableH ); OGRErr CPL_DLL GDALDatasetStartTransaction(GDALDatasetH hDS, int bForce); OGRErr CPL_DLL GDALDatasetCommitTransaction(GDALDatasetH hDS); OGRErr CPL_DLL GDALDatasetRollbackTransaction(GDALDatasetH hDS); /* ==================================================================== */ /* GDALRasterBand ... one band/channel in a dataset. */ /* ==================================================================== */ /** * SRCVAL - Macro which may be used by pixel functions to obtain * a pixel from a source buffer. */ #define SRCVAL(papoSource, eSrcType, ii) \ (eSrcType == GDT_Byte ? \ ((GByte *)papoSource)[ii] : \ (eSrcType == GDT_Float32 ? \ ((float *)papoSource)[ii] : \ (eSrcType == GDT_Float64 ? \ ((double *)papoSource)[ii] : \ (eSrcType == GDT_Int32 ? \ ((GInt32 *)papoSource)[ii] : \ (eSrcType == GDT_UInt16 ? \ ((GUInt16 *)papoSource)[ii] : \ (eSrcType == GDT_Int16 ? \ ((GInt16 *)papoSource)[ii] : \ (eSrcType == GDT_UInt32 ? \ ((GUInt32 *)papoSource)[ii] : \ (eSrcType == GDT_CInt16 ? \ ((GInt16 *)papoSource)[ii * 2] : \ (eSrcType == GDT_CInt32 ? \ ((GInt32 *)papoSource)[ii * 2] : \ (eSrcType == GDT_CFloat32 ? \ ((float *)papoSource)[ii * 2] : \ (eSrcType == GDT_CFloat64 ? \ ((double *)papoSource)[ii * 2] : 0))))))))))) typedef CPLErr (*GDALDerivedPixelFunc)(void **papoSources, int nSources, void *pData, int nBufXSize, int nBufYSize, GDALDataType eSrcType, GDALDataType eBufType, int nPixelSpace, int nLineSpace); GDALDataType CPL_DLL CPL_STDCALL GDALGetRasterDataType( GDALRasterBandH ); void CPL_DLL CPL_STDCALL GDALGetBlockSize( GDALRasterBandH, int * pnXSize, int * pnYSize ); CPLErr CPL_DLL CPL_STDCALL GDALRasterAdviseRead( GDALRasterBandH hRB, int nDSXOff, int nDSYOff, int nDSXSize, int nDSYSize, int nBXSize, int nBYSize, GDALDataType eBDataType, char **papszOptions ); CPLErr CPL_DLL CPL_STDCALL GDALRasterIO( GDALRasterBandH hRBand, GDALRWFlag eRWFlag, int nDSXOff, int nDSYOff, int nDSXSize, int nDSYSize, void * pBuffer, int nBXSize, int nBYSize,GDALDataType eBDataType, int nPixelSpace, int nLineSpace ) CPL_WARN_UNUSED_RESULT; CPLErr CPL_DLL CPL_STDCALL GDALRasterIOEx( GDALRasterBandH hRBand, GDALRWFlag eRWFlag, int nDSXOff, int nDSYOff, int nDSXSize, int nDSYSize, void * pBuffer, int nBXSize, int nBYSize,GDALDataType eBDataType, GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg* psExtraArg ) CPL_WARN_UNUSED_RESULT; CPLErr CPL_DLL CPL_STDCALL GDALReadBlock( GDALRasterBandH, int, int, void * ) CPL_WARN_UNUSED_RESULT; CPLErr CPL_DLL CPL_STDCALL GDALWriteBlock( GDALRasterBandH, int, int, void * ) CPL_WARN_UNUSED_RESULT; int CPL_DLL CPL_STDCALL GDALGetRasterBandXSize( GDALRasterBandH ); int CPL_DLL CPL_STDCALL GDALGetRasterBandYSize( GDALRasterBandH ); GDALAccess CPL_DLL CPL_STDCALL GDALGetRasterAccess( GDALRasterBandH ); int CPL_DLL CPL_STDCALL GDALGetBandNumber( GDALRasterBandH ); GDALDatasetH CPL_DLL CPL_STDCALL GDALGetBandDataset( GDALRasterBandH ); GDALColorInterp CPL_DLL CPL_STDCALL GDALGetRasterColorInterpretation( GDALRasterBandH ); CPLErr CPL_DLL CPL_STDCALL GDALSetRasterColorInterpretation( GDALRasterBandH, GDALColorInterp ); GDALColorTableH CPL_DLL CPL_STDCALL GDALGetRasterColorTable( GDALRasterBandH ); CPLErr CPL_DLL CPL_STDCALL GDALSetRasterColorTable( GDALRasterBandH, GDALColorTableH ); int CPL_DLL CPL_STDCALL GDALHasArbitraryOverviews( GDALRasterBandH ); int CPL_DLL CPL_STDCALL GDALGetOverviewCount( GDALRasterBandH ); GDALRasterBandH CPL_DLL CPL_STDCALL GDALGetOverview( GDALRasterBandH, int ); double CPL_DLL CPL_STDCALL GDALGetRasterNoDataValue( GDALRasterBandH, int * ); CPLErr CPL_DLL CPL_STDCALL GDALSetRasterNoDataValue( GDALRasterBandH, double ); CPLErr CPL_DLL CPL_STDCALL GDALDeleteRasterNoDataValue( GDALRasterBandH ); char CPL_DLL ** CPL_STDCALL GDALGetRasterCategoryNames( GDALRasterBandH ); CPLErr CPL_DLL CPL_STDCALL GDALSetRasterCategoryNames( GDALRasterBandH, char ** ); double CPL_DLL CPL_STDCALL GDALGetRasterMinimum( GDALRasterBandH, int *pbSuccess ); double CPL_DLL CPL_STDCALL GDALGetRasterMaximum( GDALRasterBandH, int *pbSuccess ); CPLErr CPL_DLL CPL_STDCALL GDALGetRasterStatistics( GDALRasterBandH, int bApproxOK, int bForce, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev ); CPLErr CPL_DLL CPL_STDCALL GDALComputeRasterStatistics( GDALRasterBandH, int bApproxOK, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev, GDALProgressFunc pfnProgress, void *pProgressData ); CPLErr CPL_DLL CPL_STDCALL GDALSetRasterStatistics( GDALRasterBandH hBand, double dfMin, double dfMax, double dfMean, double dfStdDev ); const char CPL_DLL * CPL_STDCALL GDALGetRasterUnitType( GDALRasterBandH ); CPLErr CPL_DLL CPL_STDCALL GDALSetRasterUnitType( GDALRasterBandH hBand, const char *pszNewValue ); double CPL_DLL CPL_STDCALL GDALGetRasterOffset( GDALRasterBandH, int *pbSuccess ); CPLErr CPL_DLL CPL_STDCALL GDALSetRasterOffset( GDALRasterBandH hBand, double dfNewOffset); double CPL_DLL CPL_STDCALL GDALGetRasterScale( GDALRasterBandH, int *pbSuccess ); CPLErr CPL_DLL CPL_STDCALL GDALSetRasterScale( GDALRasterBandH hBand, double dfNewOffset ); void CPL_DLL CPL_STDCALL GDALComputeRasterMinMax( GDALRasterBandH hBand, int bApproxOK, double adfMinMax[2] ); CPLErr CPL_DLL CPL_STDCALL GDALFlushRasterCache( GDALRasterBandH hBand ); CPLErr CPL_DLL CPL_STDCALL GDALGetRasterHistogram( GDALRasterBandH hBand, double dfMin, double dfMax, int nBuckets, int *panHistogram, int bIncludeOutOfRange, int bApproxOK, GDALProgressFunc pfnProgress, void * pProgressData ) CPL_WARN_DEPRECATED("Use GDALGetRasterHistogramEx() instead"); CPLErr CPL_DLL CPL_STDCALL GDALGetRasterHistogramEx( GDALRasterBandH hBand, double dfMin, double dfMax, int nBuckets, GUIntBig *panHistogram, int bIncludeOutOfRange, int bApproxOK, GDALProgressFunc pfnProgress, void * pProgressData ); CPLErr CPL_DLL CPL_STDCALL GDALGetDefaultHistogram( GDALRasterBandH hBand, double *pdfMin, double *pdfMax, int *pnBuckets, int **ppanHistogram, int bForce, GDALProgressFunc pfnProgress, void * pProgressData ) CPL_WARN_DEPRECATED("Use GDALGetDefaultHistogramEx() instead"); CPLErr CPL_DLL CPL_STDCALL GDALGetDefaultHistogramEx( GDALRasterBandH hBand, double *pdfMin, double *pdfMax, int *pnBuckets, GUIntBig **ppanHistogram, int bForce, GDALProgressFunc pfnProgress, void * pProgressData ); CPLErr CPL_DLL CPL_STDCALL GDALSetDefaultHistogram( GDALRasterBandH hBand, double dfMin, double dfMax, int nBuckets, int *panHistogram ) CPL_WARN_DEPRECATED("Use GDALSetDefaultHistogramEx() instead"); CPLErr CPL_DLL CPL_STDCALL GDALSetDefaultHistogramEx( GDALRasterBandH hBand, double dfMin, double dfMax, int nBuckets, GUIntBig *panHistogram ); int CPL_DLL CPL_STDCALL GDALGetRandomRasterSample( GDALRasterBandH, int, float * ); GDALRasterBandH CPL_DLL CPL_STDCALL GDALGetRasterSampleOverview( GDALRasterBandH, int ); GDALRasterBandH CPL_DLL CPL_STDCALL GDALGetRasterSampleOverviewEx( GDALRasterBandH, GUIntBig ); CPLErr CPL_DLL CPL_STDCALL GDALFillRaster( GDALRasterBandH hBand, double dfRealValue, double dfImaginaryValue ); CPLErr CPL_DLL CPL_STDCALL GDALComputeBandStats( GDALRasterBandH hBand, int nSampleStep, double *pdfMean, double *pdfStdDev, GDALProgressFunc pfnProgress, void *pProgressData ); CPLErr CPL_DLL GDALOverviewMagnitudeCorrection( GDALRasterBandH hBaseBand, int nOverviewCount, GDALRasterBandH *pahOverviews, GDALProgressFunc pfnProgress, void *pProgressData ); GDALRasterAttributeTableH CPL_DLL CPL_STDCALL GDALGetDefaultRAT( GDALRasterBandH hBand ); CPLErr CPL_DLL CPL_STDCALL GDALSetDefaultRAT( GDALRasterBandH, GDALRasterAttributeTableH ); CPLErr CPL_DLL CPL_STDCALL GDALAddDerivedBandPixelFunc( const char *pszName, GDALDerivedPixelFunc pfnPixelFunc ); GDALRasterBandH CPL_DLL CPL_STDCALL GDALGetMaskBand( GDALRasterBandH hBand ); int CPL_DLL CPL_STDCALL GDALGetMaskFlags( GDALRasterBandH hBand ); CPLErr CPL_DLL CPL_STDCALL GDALCreateMaskBand( GDALRasterBandH hBand, int nFlags ); #define GMF_ALL_VALID 0x01 #define GMF_PER_DATASET 0x02 #define GMF_ALPHA 0x04 #define GMF_NODATA 0x08 /* ==================================================================== */ /* GDALAsyncReader */ /* ==================================================================== */ GDALAsyncStatusType CPL_DLL CPL_STDCALL GDALARGetNextUpdatedRegion(GDALAsyncReaderH hARIO, double dfTimeout, int* pnXBufOff, int* pnYBufOff, int* pnXBufSize, int* pnYBufSize ); int CPL_DLL CPL_STDCALL GDALARLockBuffer(GDALAsyncReaderH hARIO, double dfTimeout); void CPL_DLL CPL_STDCALL GDALARUnlockBuffer(GDALAsyncReaderH hARIO); /* -------------------------------------------------------------------- */ /* Helper functions. */ /* -------------------------------------------------------------------- */ int CPL_DLL CPL_STDCALL GDALGeneralCmdLineProcessor( int nArgc, char ***ppapszArgv, int nOptions ); void CPL_DLL CPL_STDCALL GDALSwapWords( void *pData, int nWordSize, int nWordCount, int nWordSkip ); void CPL_DLL CPL_STDCALL GDALSwapWordsEx( void *pData, int nWordSize, size_t nWordCount, int nWordSkip ); void CPL_DLL CPL_STDCALL GDALCopyWords( const void * pSrcData, GDALDataType eSrcType, int nSrcPixelOffset, void * pDstData, GDALDataType eDstType, int nDstPixelOffset, int nWordCount ); void CPL_DLL GDALCopyBits( const GByte *pabySrcData, int nSrcOffset, int nSrcStep, GByte *pabyDstData, int nDstOffset, int nDstStep, int nBitCount, int nStepCount ); int CPL_DLL CPL_STDCALL GDALLoadWorldFile( const char *, double * ); int CPL_DLL CPL_STDCALL GDALReadWorldFile( const char *, const char *, double * ); int CPL_DLL CPL_STDCALL GDALWriteWorldFile( const char *, const char *, double * ); int CPL_DLL CPL_STDCALL GDALLoadTabFile( const char *, double *, char **, int *, GDAL_GCP ** ); int CPL_DLL CPL_STDCALL GDALReadTabFile( const char *, double *, char **, int *, GDAL_GCP ** ); int CPL_DLL CPL_STDCALL GDALLoadOziMapFile( const char *, double *, char **, int *, GDAL_GCP ** ); int CPL_DLL CPL_STDCALL GDALReadOziMapFile( const char *, double *, char **, int *, GDAL_GCP ** ); const char CPL_DLL * CPL_STDCALL GDALDecToDMS( double, const char *, int ); double CPL_DLL CPL_STDCALL GDALPackedDMSToDec( double ); double CPL_DLL CPL_STDCALL GDALDecToPackedDMS( double ); /* Note to developers : please keep this section in sync with ogr_core.h */ #ifndef GDAL_VERSION_INFO_DEFINED #define GDAL_VERSION_INFO_DEFINED const char CPL_DLL * CPL_STDCALL GDALVersionInfo( const char * ); #endif #ifndef GDAL_CHECK_VERSION int CPL_DLL CPL_STDCALL GDALCheckVersion( int nVersionMajor, int nVersionMinor, const char* pszCallingComponentName); /** Helper macro for GDALCheckVersion() @see GDALCheckVersion() */ #define GDAL_CHECK_VERSION(pszCallingComponentName) \ GDALCheckVersion(GDAL_VERSION_MAJOR, GDAL_VERSION_MINOR, pszCallingComponentName) #endif typedef struct { double dfLINE_OFF; double dfSAMP_OFF; double dfLAT_OFF; double dfLONG_OFF; double dfHEIGHT_OFF; double dfLINE_SCALE; double dfSAMP_SCALE; double dfLAT_SCALE; double dfLONG_SCALE; double dfHEIGHT_SCALE; double adfLINE_NUM_COEFF[20]; double adfLINE_DEN_COEFF[20]; double adfSAMP_NUM_COEFF[20]; double adfSAMP_DEN_COEFF[20]; double dfMIN_LONG; double dfMIN_LAT; double dfMAX_LONG; double dfMAX_LAT; } GDALRPCInfo; int CPL_DLL CPL_STDCALL GDALExtractRPCInfo( char **, GDALRPCInfo * ); /* ==================================================================== */ /* Color tables. */ /* ==================================================================== */ /** Color tuple */ typedef struct { /*! gray, red, cyan or hue */ short c1; /*! green, magenta, or lightness */ short c2; /*! blue, yellow, or saturation */ short c3; /*! alpha or blackband */ short c4; } GDALColorEntry; GDALColorTableH CPL_DLL CPL_STDCALL GDALCreateColorTable( GDALPaletteInterp ) CPL_WARN_UNUSED_RESULT; void CPL_DLL CPL_STDCALL GDALDestroyColorTable( GDALColorTableH ); GDALColorTableH CPL_DLL CPL_STDCALL GDALCloneColorTable( GDALColorTableH ); GDALPaletteInterp CPL_DLL CPL_STDCALL GDALGetPaletteInterpretation( GDALColorTableH ); int CPL_DLL CPL_STDCALL GDALGetColorEntryCount( GDALColorTableH ); const GDALColorEntry CPL_DLL * CPL_STDCALL GDALGetColorEntry( GDALColorTableH, int ); int CPL_DLL CPL_STDCALL GDALGetColorEntryAsRGB( GDALColorTableH, int, GDALColorEntry *); void CPL_DLL CPL_STDCALL GDALSetColorEntry( GDALColorTableH, int, const GDALColorEntry * ); void CPL_DLL CPL_STDCALL GDALCreateColorRamp( GDALColorTableH hTable, int nStartIndex, const GDALColorEntry *psStartColor, int nEndIndex, const GDALColorEntry *psEndColor ); /* ==================================================================== */ /* Raster Attribute Table */ /* ==================================================================== */ /** Field type of raster attribute table */ typedef enum { /*! Integer field */ GFT_Integer, /*! Floating point (double) field */ GFT_Real, /*! String field */ GFT_String } GDALRATFieldType; /** Field usage of raster attribute table */ typedef enum { /*! General purpose field. */ GFU_Generic = 0, /*! Histogram pixel count */ GFU_PixelCount = 1, /*! Class name */ GFU_Name = 2, /*! Class range minimum */ GFU_Min = 3, /*! Class range maximum */ GFU_Max = 4, /*! Class value (min=max) */ GFU_MinMax = 5, /*! Red class color (0-255) */ GFU_Red = 6, /*! Green class color (0-255) */ GFU_Green = 7, /*! Blue class color (0-255) */ GFU_Blue = 8, /*! Alpha (0=transparent,255=opaque)*/ GFU_Alpha = 9, /*! Color Range Red Minimum */ GFU_RedMin = 10, /*! Color Range Green Minimum */ GFU_GreenMin = 11, /*! Color Range Blue Minimum */ GFU_BlueMin = 12, /*! Color Range Alpha Minimum */ GFU_AlphaMin = 13, /*! Color Range Red Maximum */ GFU_RedMax = 14, /*! Color Range Green Maximum */ GFU_GreenMax = 15, /*! Color Range Blue Maximum */ GFU_BlueMax = 16, /*! Color Range Alpha Maximum */ GFU_AlphaMax = 17, /*! Maximum GFU value */ GFU_MaxCount } GDALRATFieldUsage; GDALRasterAttributeTableH CPL_DLL CPL_STDCALL GDALCreateRasterAttributeTable(void) CPL_WARN_UNUSED_RESULT; void CPL_DLL CPL_STDCALL GDALDestroyRasterAttributeTable( GDALRasterAttributeTableH ); int CPL_DLL CPL_STDCALL GDALRATGetColumnCount( GDALRasterAttributeTableH ); const char CPL_DLL * CPL_STDCALL GDALRATGetNameOfCol( GDALRasterAttributeTableH, int ); GDALRATFieldUsage CPL_DLL CPL_STDCALL GDALRATGetUsageOfCol( GDALRasterAttributeTableH, int ); GDALRATFieldType CPL_DLL CPL_STDCALL GDALRATGetTypeOfCol( GDALRasterAttributeTableH, int ); int CPL_DLL CPL_STDCALL GDALRATGetColOfUsage( GDALRasterAttributeTableH, GDALRATFieldUsage ); int CPL_DLL CPL_STDCALL GDALRATGetRowCount( GDALRasterAttributeTableH ); const char CPL_DLL * CPL_STDCALL GDALRATGetValueAsString( GDALRasterAttributeTableH, int, int); int CPL_DLL CPL_STDCALL GDALRATGetValueAsInt( GDALRasterAttributeTableH, int, int); double CPL_DLL CPL_STDCALL GDALRATGetValueAsDouble( GDALRasterAttributeTableH, int, int); void CPL_DLL CPL_STDCALL GDALRATSetValueAsString( GDALRasterAttributeTableH, int, int, const char * ); void CPL_DLL CPL_STDCALL GDALRATSetValueAsInt( GDALRasterAttributeTableH, int, int, int ); void CPL_DLL CPL_STDCALL GDALRATSetValueAsDouble( GDALRasterAttributeTableH, int, int, double ); int CPL_DLL CPL_STDCALL GDALRATChangesAreWrittenToFile( GDALRasterAttributeTableH hRAT ); CPLErr CPL_DLL CPL_STDCALL GDALRATValuesIOAsDouble( GDALRasterAttributeTableH hRAT, GDALRWFlag eRWFlag, int iField, int iStartRow, int iLength, double *pdfData ); CPLErr CPL_DLL CPL_STDCALL GDALRATValuesIOAsInteger( GDALRasterAttributeTableH hRAT, GDALRWFlag eRWFlag, int iField, int iStartRow, int iLength, int *pnData); CPLErr CPL_DLL CPL_STDCALL GDALRATValuesIOAsString( GDALRasterAttributeTableH hRAT, GDALRWFlag eRWFlag, int iField, int iStartRow, int iLength, char **papszStrList); void CPL_DLL CPL_STDCALL GDALRATSetRowCount( GDALRasterAttributeTableH, int ); CPLErr CPL_DLL CPL_STDCALL GDALRATCreateColumn( GDALRasterAttributeTableH, const char *, GDALRATFieldType, GDALRATFieldUsage ); CPLErr CPL_DLL CPL_STDCALL GDALRATSetLinearBinning( GDALRasterAttributeTableH, double, double ); int CPL_DLL CPL_STDCALL GDALRATGetLinearBinning( GDALRasterAttributeTableH, double *, double * ); CPLErr CPL_DLL CPL_STDCALL GDALRATInitializeFromColorTable( GDALRasterAttributeTableH, GDALColorTableH ); GDALColorTableH CPL_DLL CPL_STDCALL GDALRATTranslateToColorTable( GDALRasterAttributeTableH, int nEntryCount ); void CPL_DLL CPL_STDCALL GDALRATDumpReadable( GDALRasterAttributeTableH, FILE * ); GDALRasterAttributeTableH CPL_DLL CPL_STDCALL GDALRATClone( GDALRasterAttributeTableH ); void CPL_DLL* CPL_STDCALL GDALRATSerializeJSON( GDALRasterAttributeTableH ) CPL_WARN_UNUSED_RESULT; int CPL_DLL CPL_STDCALL GDALRATGetRowOfValue( GDALRasterAttributeTableH, double ); /* ==================================================================== */ /* GDAL Cache Management */ /* ==================================================================== */ void CPL_DLL CPL_STDCALL GDALSetCacheMax( int nBytes ); int CPL_DLL CPL_STDCALL GDALGetCacheMax(void); int CPL_DLL CPL_STDCALL GDALGetCacheUsed(void); void CPL_DLL CPL_STDCALL GDALSetCacheMax64( GIntBig nBytes ); GIntBig CPL_DLL CPL_STDCALL GDALGetCacheMax64(void); GIntBig CPL_DLL CPL_STDCALL GDALGetCacheUsed64(void); int CPL_DLL CPL_STDCALL GDALFlushCacheBlock(void); /* ==================================================================== */ /* GDAL virtual memory */ /* ==================================================================== */ CPLVirtualMem CPL_DLL* GDALDatasetGetVirtualMem( GDALDatasetH hDS, GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int* panBandMap, int nPixelSpace, GIntBig nLineSpace, GIntBig nBandSpace, size_t nCacheSize, size_t nPageSizeHint, int bSingleThreadUsage, char **papszOptions ) CPL_WARN_UNUSED_RESULT; CPLVirtualMem CPL_DLL* GDALRasterBandGetVirtualMem( GDALRasterBandH hBand, GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nPixelSpace, GIntBig nLineSpace, size_t nCacheSize, size_t nPageSizeHint, int bSingleThreadUsage, char **papszOptions ) CPL_WARN_UNUSED_RESULT; CPLVirtualMem CPL_DLL* GDALGetVirtualMemAuto( GDALRasterBandH hBand, GDALRWFlag eRWFlag, int *pnPixelSpace, GIntBig *pnLineSpace, char **papszOptions ) CPL_WARN_UNUSED_RESULT; typedef enum { /*! Tile Interleaved by Pixel: tile (0,0) with internal band interleaved by pixel organization, tile (1, 0), ... */ GTO_TIP, /*! Band Interleaved by Tile : tile (0,0) of first band, tile (0,0) of second band, ... tile (1,0) of first band, tile (1,0) of second band, ... */ GTO_BIT, /*! Band SeQuential : all the tiles of first band, all the tiles of following band... */ GTO_BSQ } GDALTileOrganization; CPLVirtualMem CPL_DLL* GDALDatasetGetTiledVirtualMem( GDALDatasetH hDS, GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, int nTileXSize, int nTileYSize, GDALDataType eBufType, int nBandCount, int* panBandMap, GDALTileOrganization eTileOrganization, size_t nCacheSize, int bSingleThreadUsage, char **papszOptions ) CPL_WARN_UNUSED_RESULT; CPLVirtualMem CPL_DLL* GDALRasterBandGetTiledVirtualMem( GDALRasterBandH hBand, GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, int nTileXSize, int nTileYSize, GDALDataType eBufType, size_t nCacheSize, int bSingleThreadUsage, char **papszOptions ) CPL_WARN_UNUSED_RESULT; /* ==================================================================== */ /* VRTPansharpenedDataset class. */ /* ==================================================================== */ GDALDatasetH CPL_DLL GDALCreatePansharpenedVRT( const char* pszXML, GDALRasterBandH hPanchroBand, int nInputSpectralBands, GDALRasterBandH* pahInputSpectralBands ) CPL_WARN_UNUSED_RESULT; /* =================================================================== */ /* Misc API */ /* ==================================================================== */ CPLXMLNode CPL_DLL* GDALGetJPEG2000Structure(const char* pszFilename, char** papszOptions) CPL_WARN_UNUSED_RESULT; CPL_C_END #endif /* ndef GDAL_H_INCLUDED */
{ "pile_set_name": "Github" }
/* * Copyright (C) 2008 The Android Open Source Project * * 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. */ /** * Common interface. */ public interface ICommon2 { public DoubledImplement2 getDoubledInstance2(); }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 280f8698e6adc2a468764d54a839473e timeCreated: 1473792193 licenseType: Pro NativeFormatImporter: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
[package] name = "stdtx" description = "Extensible schema-driven Cosmos StdTx builder and Amino serializer" version = "0.2.1" # Also update html_root_url in lib.rs when bumping this authors = ["Tony Arcieri <tony@iqlusion.io>"] license = "Apache-2.0" homepage = "https://github.com/iqlusioninc/crates/" repository = "https://github.com/iqlusioninc/crates/tree/develop/stdtx" readme = "README.md" categories = ["cryptography", "encoding"] keywords = ["amino", "crypto", "cosmos", "transaction", "tendermint"] edition = "2018" [badges] circle-ci = { repository = "tendermint/kms" } [dependencies] anomaly = { version = "0.2", path = "../anomaly" } ecdsa = { version = "0.6", features = ["k256"] } prost-amino = "0.6" prost-amino-derive = "0.6" rust_decimal = "1.7" serde = { version = "1", features = ["serde_derive"] } serde_json = "1" sha2 = "0.9" thiserror = "1" toml = "0.5" [dependencies.subtle-encoding] version = "0.5" features = ["bech32-preview"] path = "../subtle-encoding" [dev-dependencies] signatory-secp256k1 = "0.20"
{ "pile_set_name": "Github" }
{ "result": { "item": "projecte:dm_shears" }, "pattern": [ " M", "D " ], "type": "minecraft:crafting_shaped", "key": { "D": { "tag": "forge:gems/diamond" }, "M": { "item": "projecte:dark_matter" } } }
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <doc> <assembly> <name>MogreDependencies</name> </assembly> <members> </members> </doc>
{ "pile_set_name": "Github" }
<?php /* Smarty version 2.6.14, created on 2011-04-21 08:13:32 compiled from structures.tpl */ ?> <?php if (count ( $this->_tpl_vars['showstructs'] ) != 0): ?> <tr class="formcolor"> <td>Structures:</td> <td> [ <a class="link" href="javascript:show('showstructs');">show structures</a> | <a class="link" href="javascript:hide('showstructs');">hide structures</a> ] <div id="showstructs" style="display:none;"> <table> <?php $_from = $this->_tpl_vars['showstructs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)): foreach ($_from as $this->_tpl_vars['page_info']): ?> <tr><td><?php echo $this->_tpl_vars['page_info']['pageName']; if (! empty ( $this->_tpl_vars['page_info']['page_alias'] )): ?>(<?php echo $this->_tpl_vars['page_info']['page_alias']; ?> )<?php endif; ?></td></tr> <?php endforeach; endif; unset($_from); ?> </table> <?php if ($this->_tpl_vars['tiki_p_edit_structures'] == 'y'): ?> <a href="tiki-admin_structures.php" class="link">Manage structures</a> <?php endif; ?> </div> </td> </tr> <?php endif; ?>
{ "pile_set_name": "Github" }
// synchronizaion.hpp --------------------------------------------------------------// // Copyright 2010 Vicente J. Botet Escriba // Copyright 2015 Andrey Semashev // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #ifndef BOOST_DETAIL_WINAPI_SYNCHRONIZATION_HPP #define BOOST_DETAIL_WINAPI_SYNCHRONIZATION_HPP #include <boost/detail/winapi/basic_types.hpp> #include <boost/detail/winapi/critical_section.hpp> #include <boost/detail/winapi/wait.hpp> #include <boost/detail/winapi/event.hpp> #include <boost/detail/winapi/mutex.hpp> #include <boost/detail/winapi/semaphore.hpp> #include <boost/detail/winapi/init_once.hpp> #include <boost/detail/winapi/srw_lock.hpp> #include <boost/detail/winapi/condition_variable.hpp> #include <boost/detail/winapi/apc.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #endif // BOOST_DETAIL_WINAPI_SYNCHRONIZATION_HPP
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Ockam Node</title> </head> <body> Error </body> </html>
{ "pile_set_name": "Github" }
// // MPViewControllerLifeCycle.h // MobileProject 一个关于VC生周期的实例,可以查看LOG记录执行顺序 // // Created by wujunyang on 2016/11/10. // Copyright © 2016年 wujunyang. All rights reserved. // #import <UIKit/UIKit.h> #import "BaseViewController.h" @interface MPViewControllerLifeCycle : BaseViewController @end
{ "pile_set_name": "Github" }
# Aim: create up-to-date map of Earthquakes in previous week # set-up ------------------------------------------------------------------ library(sf) library(spData) # download data ----------------------------------------------------------- u = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson" earthquakes = read_sf(u) # summary(earthquakes) # summarise # text results ------------------------------------------------------------ print(paste0(nrow(earthquakes), " significant earthquakes happened last month")) # map --------------------------------------------------------------------- plot(st_geometry(world), border = "grey") plot(st_geometry(earthquakes), cex = earthquakes$mag, add = TRUE) title(paste0( "Location of significant (mag > 5) Earthquakes in the month to ", Sys.Date(), "\n(circle diameter is proportional to magnitude)" ))
{ "pile_set_name": "Github" }
/** * ownCloud Android client application * * @author David A. Velasco * @author David González Verdugo * @author Shashvat Kedia * Copyright (C) 2020 ownCloud GmbH. * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.db; import android.accounts.Account; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.util.Log; import com.owncloud.android.R; import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.services.FileUploader; import com.owncloud.android.ui.activity.BiometricActivity; import com.owncloud.android.utils.FileStorageUtils; import java.io.File; /** * Helper to simplify reading of Preferences all around the app */ public abstract class PreferenceManager { /** * Constant to access value of last path selected by the user to upload a file shared from other app. * Value handled by the app without direct access in the UI. */ private static final String AUTO_PREF__LAST_UPLOAD_PATH = "last_upload_path"; private static final String AUTO_PREF__SORT_ORDER_FILE_DISP = "sortOrderFileDisp"; private static final String AUTO_PREF__SORT_ASCENDING_FILE_DISP = "sortAscendingFileDisp"; private static final String AUTO_PREF__SORT_ORDER_UPLOAD = "sortOrderUpload"; private static final String AUTO_PREF__SORT_ASCENDING_UPLOAD = "sortAscendingUpload"; private static final String PREF__CAMERA_PICTURE_UPLOADS_ENABLED = "camera_picture_uploads"; private static final String PREF__CAMERA_VIDEO_UPLOADS_ENABLED = "camera_video_uploads"; private static final String PREF__CAMERA_PICTURE_UPLOADS_WIFI_ONLY = "camera_picture_uploads_on_wifi"; private static final String PREF__CAMERA_VIDEO_UPLOADS_WIFI_ONLY = "camera_video_uploads_on_wifi"; private static final String PREF__CAMERA_UPLOADS_ACCOUNT_NAME = "camera_uploads_account_name"; // NEW - not // saved yet private static final String PREF__CAMERA_PICTURE_UPLOADS_PATH = "camera_picture_uploads_path"; private static final String PREF__CAMERA_VIDEO_UPLOADS_PATH = "camera_video_uploads_path"; private static final String PREF__CAMERA_UPLOADS_BEHAVIOUR = "camera_uploads_behaviour"; private static final String PREF__CAMERA_UPLOADS_SOURCE = "camera_uploads_source_path"; public static final String PREF__CAMERA_UPLOADS_DEFAULT_PATH = "/CameraUpload"; public static final String PREF__LEGACY_FINGERPRINT = "set_fingerprint"; public static void migrateFingerprintToBiometricKey(Context context) { SharedPreferences sharedPref = getDefaultSharedPreferences(context); // Check if legacy fingerprint key exists, delete it and migrate its value to the new key if (sharedPref.contains(PREF__LEGACY_FINGERPRINT)) { boolean currentFingerprintValue = sharedPref.getBoolean(PREF__LEGACY_FINGERPRINT, false); SharedPreferences.Editor editor = sharedPref.edit(); editor.remove(PREF__LEGACY_FINGERPRINT); editor.putBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, currentFingerprintValue); editor.apply(); } } public static boolean cameraPictureUploadEnabled(Context context) { return getDefaultSharedPreferences(context).getBoolean(PREF__CAMERA_PICTURE_UPLOADS_ENABLED, false); } public static boolean cameraVideoUploadEnabled(Context context) { return getDefaultSharedPreferences(context).getBoolean(PREF__CAMERA_VIDEO_UPLOADS_ENABLED, false); } public static boolean cameraPictureUploadViaWiFiOnly(Context context) { return getDefaultSharedPreferences(context).getBoolean(PREF__CAMERA_PICTURE_UPLOADS_WIFI_ONLY, false); } public static boolean cameraVideoUploadViaWiFiOnly(Context context) { return getDefaultSharedPreferences(context).getBoolean(PREF__CAMERA_VIDEO_UPLOADS_WIFI_ONLY, false); } public static CameraUploadsConfiguration getCameraUploadsConfiguration(Context context) { CameraUploadsConfiguration result = new CameraUploadsConfiguration(); SharedPreferences prefs = getDefaultSharedPreferences(context); result.setEnabledForPictures( prefs.getBoolean(PREF__CAMERA_PICTURE_UPLOADS_ENABLED, false) ); result.setEnabledForVideos( prefs.getBoolean(PREF__CAMERA_VIDEO_UPLOADS_ENABLED, false) ); result.setWifiOnlyForPictures( prefs.getBoolean(PREF__CAMERA_PICTURE_UPLOADS_WIFI_ONLY, false) ); result.setWifiOnlyForVideos( prefs.getBoolean(PREF__CAMERA_VIDEO_UPLOADS_WIFI_ONLY, false) ); Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context); result.setUploadAccountName( prefs.getString( PREF__CAMERA_UPLOADS_ACCOUNT_NAME, (currentAccount == null) ? "" : currentAccount.name ) ); String uploadPath = prefs.getString( PREF__CAMERA_PICTURE_UPLOADS_PATH, PREF__CAMERA_UPLOADS_DEFAULT_PATH + File.separator ); result.setUploadPathForPictures( uploadPath.endsWith(File.separator) ? uploadPath : uploadPath + File.separator ); uploadPath = prefs.getString( PREF__CAMERA_VIDEO_UPLOADS_PATH, PREF__CAMERA_UPLOADS_DEFAULT_PATH + File.separator ); result.setUploadPathForVideos( uploadPath.endsWith(File.separator) ? uploadPath : uploadPath + File.separator ); result.setBehaviourAfterUpload( prefs.getString( PREF__CAMERA_UPLOADS_BEHAVIOUR, context.getResources().getStringArray(R.array.pref_behaviour_entryValues)[0] ) ); result.setSourcePath( prefs.getString( PREF__CAMERA_UPLOADS_SOURCE, CameraUploadsConfiguration.DEFAULT_SOURCE_PATH ) ); return result; } /** * Gets the path where the user selected to do the last upload of a file shared from other app. * * @param context Caller {@link Context}, used to access to shared preferences manager. * @return path Absolute path to a folder, as previously stored by {@link #setLastUploadPath(String, Context)}, * or empty String if never saved before. */ public static String getLastUploadPath(Context context) { return getDefaultSharedPreferences(context).getString(AUTO_PREF__LAST_UPLOAD_PATH, ""); } /** * Saves the path where the user selected to do the last upload of a file shared from other app. * * @param path Absolute path to a folder. * @param context Caller {@link Context}, used to access to shared preferences manager. */ public static void setLastUploadPath(String path, Context context) { saveStringPreference(AUTO_PREF__LAST_UPLOAD_PATH, path, context); } /** * Gets the sort order which the user has set last. * * @param context Caller {@link Context}, used to access to shared preferences manager. * @return sort order the sort order, default is {@link FileStorageUtils#SORT_NAME} (sort by name) */ public static int getSortOrder(Context context, int flag) { if (flag == FileStorageUtils.FILE_DISPLAY_SORT) { return getDefaultSharedPreferences(context) .getInt(AUTO_PREF__SORT_ORDER_FILE_DISP, FileStorageUtils.SORT_NAME); } else { return getDefaultSharedPreferences(context) .getInt(AUTO_PREF__SORT_ORDER_UPLOAD, FileStorageUtils.SORT_DATE); } } /** * Save the sort order which the user has set last. * * @param order the sort order * @param context Caller {@link Context}, used to access to shared preferences manager. */ public static void setSortOrder(int order, Context context, int flag) { if (flag == FileStorageUtils.FILE_DISPLAY_SORT) { saveIntPreference(AUTO_PREF__SORT_ORDER_FILE_DISP, order, context); } else { saveIntPreference(AUTO_PREF__SORT_ORDER_UPLOAD, order, context); } } /** * Gets the ascending order flag which the user has set last. * * @param context Caller {@link Context}, used to access to shared preferences manager. * @return ascending order the ascending order, default is true */ public static boolean getSortAscending(Context context, int flag) { if (flag == FileStorageUtils.FILE_DISPLAY_SORT) { return getDefaultSharedPreferences(context) .getBoolean(AUTO_PREF__SORT_ASCENDING_FILE_DISP, true); } else { return getDefaultSharedPreferences(context) .getBoolean(AUTO_PREF__SORT_ASCENDING_UPLOAD, true); } } /** * Saves the ascending order flag which the user has set last. * * @param ascending flag if sorting is ascending or descending * @param context Caller {@link Context}, used to access to shared preferences manager. */ public static void setSortAscending(boolean ascending, Context context, int flag) { if (flag == FileStorageUtils.FILE_DISPLAY_SORT) { saveBooleanPreference(AUTO_PREF__SORT_ASCENDING_FILE_DISP, ascending, context); } else { saveBooleanPreference(AUTO_PREF__SORT_ASCENDING_UPLOAD, ascending, context); } } private static void saveBooleanPreference(String key, boolean value, Context context) { SharedPreferences.Editor appPreferences = getDefaultSharedPreferences(context.getApplicationContext()).edit(); appPreferences.putBoolean(key, value); appPreferences.apply(); } private static void saveStringPreference(String key, String value, Context context) { SharedPreferences.Editor appPreferences = getDefaultSharedPreferences(context.getApplicationContext()).edit(); appPreferences.putString(key, value); appPreferences.apply(); } private static void saveIntPreference(String key, int value, Context context) { SharedPreferences.Editor appPreferences = getDefaultSharedPreferences(context.getApplicationContext()).edit(); appPreferences.putInt(key, value); appPreferences.apply(); } public static SharedPreferences getDefaultSharedPreferences(Context context) { return android.preference.PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()); } /** * Aggregates preferences related to camera uploads in a single object. */ public static class CameraUploadsConfiguration { public static final String DEFAULT_SOURCE_PATH = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM ).getAbsolutePath() + "/Camera"; private boolean mEnabledForPictures; private boolean mEnabledForVideos; private boolean mWifiOnlyForPictures; private boolean mWifiOnlyForVideos; private String mUploadAccountName; // same for both audio & video private String mUploadPathForPictures; private String mUploadPathForVideos; private String mBehaviourAfterUpload; private String mSourcePath; // same for both audio & video public boolean isEnabledForPictures() { return mEnabledForPictures; } public void setEnabledForPictures(boolean uploadPictures) { mEnabledForPictures = uploadPictures; } public boolean isEnabledForVideos() { return mEnabledForVideos; } public void setEnabledForVideos(boolean uploadVideos) { mEnabledForVideos = uploadVideos; } public boolean isWifiOnlyForPictures() { return mWifiOnlyForPictures; } public void setWifiOnlyForPictures(boolean wifiOnlyForPictures) { mWifiOnlyForPictures = wifiOnlyForPictures; } public boolean isWifiOnlyForVideos() { return mWifiOnlyForVideos; } public void setWifiOnlyForVideos(boolean wifiOnlyForVideos) { mWifiOnlyForVideos = wifiOnlyForVideos; } public String getUploadAccountName() { return mUploadAccountName; } public void setUploadAccountName(String uploadAccountName) { mUploadAccountName = uploadAccountName; } public String getUploadPathForPictures() { return mUploadPathForPictures; } public void setUploadPathForPictures(String uploadPathForPictures) { mUploadPathForPictures = uploadPathForPictures; } public String getUploadPathForVideos() { return mUploadPathForVideos; } public void setUploadPathForVideos(String uploadPathForVideos) { mUploadPathForVideos = uploadPathForVideos; } public int getBehaviourAfterUpload() { if (mBehaviourAfterUpload.equalsIgnoreCase("MOVE")) { return FileUploader.LOCAL_BEHAVIOUR_MOVE; } return FileUploader.LOCAL_BEHAVIOUR_FORGET; // "NOTHING } public void setBehaviourAfterUpload(String behaviourAfterUpload) { mBehaviourAfterUpload = behaviourAfterUpload; } public String getSourcePath() { return mSourcePath; } public void setSourcePath(String sourcePath) { mSourcePath = sourcePath; } } }
{ "pile_set_name": "Github" }
#pragma once /************************************************************************/ /* Automatically generated benchmark latex for the huge tables */ /************************************************************************/ class BenchMarkLatex { public: BenchMarkLatex(const vecS &dbNames, const vecS &methodNames); void ProduceTable(CStr dataFileDir, CStr outTexFileDir); // void analysisDataset(CStr &rootDir, CStr &outStatisticDir); void produceSupperPixels(CStr &rootDir); void bestWostCases(CStr &rootDir, const vecS &dbNames, CStr &outDir); static double avergeFMeare(CMat &gtMask, CMat &map1u); private: vecS _dbNames, _methodNames; int _numMethod, _numDb; vecI _subNumbers; // Number of method in each sub categories static vecD readVectorFromMatlabeFile(CStr &fileName, CStr &vecName); // Return a same int matrix, with each value is the ranking index of that value in the column. static Mat getRankIdx(Mat value1d, bool descendOrder = true); static void saveData2Csv(CMat &value1d, CStr csvFile, vecS &rowStart); void printMat(CMat &mat1d, CStr texFile, bool descendOrder = true); void printMatTransport(CMat &mat1di, CStr texFile, const char* rowDes[], bool *descendOrder); void copySampleWithGt(CStr sampleDir, CStr imgNameNE, CStr mName, CStr dstDir); void printModelRanking(CStr outName, CMat &meanF1d, CMat &maxF1d, CMat &cutAdp1d, CMat &cutSC1d, CMat &auc1d, CMat &mae1d); };
{ "pile_set_name": "Github" }
/* Copyright 2019 The Kubernetes Authors. 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. */ package v1alpha1 import ( kubectrlmgrconfigv1alpha1 "k8s.io/kube-controller-manager/config/v1alpha1" utilpointer "k8s.io/utils/pointer" ) // RecommendedDefaultGarbageCollectorControllerConfiguration defaults a pointer to a // GarbageCollectorControllerConfiguration struct. This will set the recommended default // values, but they may be subject to change between API versions. This function // is intentionally not registered in the scheme as a "normal" `SetDefaults_Foo` // function to allow consumers of this type to set whatever defaults for their // embedded configs. Forcing consumers to use these defaults would be problematic // as defaulting in the scheme is done as part of the conversion, and there would // be no easy way to opt-out. Instead, if you want to use this defaulting method // run it in your wrapper struct of this type in its `SetDefaults_` method. func RecommendedDefaultGarbageCollectorControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.GarbageCollectorControllerConfiguration) { if obj.EnableGarbageCollector == nil { obj.EnableGarbageCollector = utilpointer.BoolPtr(true) } if obj.ConcurrentGCSyncs == 0 { obj.ConcurrentGCSyncs = 20 } }
{ "pile_set_name": "Github" }
/* * Copyright 2008-2019 by Emeric Vernat * * This file is part of Java Melody. * * 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. */ package net.bull.javamelody; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import net.bull.javamelody.internal.common.I18N; import net.bull.javamelody.internal.common.Parameters; import net.bull.javamelody.internal.model.Action; import net.bull.javamelody.internal.model.RemoteCollector; import net.bull.javamelody.internal.model.SessionInformations; import net.bull.javamelody.internal.model.SessionInformations.SessionAttribute; import net.bull.javamelody.internal.web.html.HtmlSessionInformationsReport; import net.bull.javamelody.internal.web.pdf.PdfOtherReport; import net.bull.javamelody.swing.MButton; import net.bull.javamelody.swing.Utilities; import net.bull.javamelody.swing.table.MDateTableCellRenderer; import net.bull.javamelody.swing.table.MDefaultTableCellRenderer; import net.bull.javamelody.swing.table.MTable; import net.bull.javamelody.swing.table.MTableScrollPane; /** * Panel de la liste des sessions. * @author Emeric Vernat */ class SessionInformationsPanel extends MelodyPanel { private static final ImageIcon INVALIDATE_SESSION_ICON = ImageIconCache .getScaledImageIcon("user-trash.png", 16, 16); private static final long serialVersionUID = 1L; @SuppressWarnings("all") private List<SessionInformations> sessionsInformations; private MTable<SessionInformations> table; private MTable<SessionAttribute> attributesTable; private class CountryTableCellRenderer extends MDefaultTableCellRenderer { private static final long serialVersionUID = 1L; CountryTableCellRenderer() { super(); setHorizontalAlignment(SwingConstants.CENTER); } @Override public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // icône et tooltip correspondant au pays if (row == -1) { setIcon(null); setToolTipText(null); } else { final MTable<SessionInformations> myTable = getTable(); final SessionInformations sessionInformations = myTable.getList() .get(myTable.convertRowIndexToModel(row)); final String country = sessionInformations.getCountry(); if (country == null) { setIcon(null); } else { final String fileName = "flags/" + country + ".gif"; if (getClass().getResource(Parameters.getResourcePath(fileName)) == null) { setIcon(null); } else { setIcon(ImageIconCache.getImageIcon(fileName)); } } setToolTipText(sessionInformations.getCountryDisplay()); } // sans texte return super.getTableCellRendererComponent(jtable, null, isSelected, hasFocus, row, column); } } private class BrowserTableCellRenderer extends MDefaultTableCellRenderer { private static final long serialVersionUID = 1L; BrowserTableCellRenderer() { super(); setHorizontalAlignment(SwingConstants.CENTER); } @Override public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // icône et tooltip correspondant au navigateur if (row == -1) { setIcon(null); setToolTipText(null); } else { final MTable<SessionInformations> myTable = getTable(); final SessionInformations sessionInformations = myTable.getList() .get(myTable.convertRowIndexToModel(row)); final String browser = sessionInformations.getBrowser(); if (browser == null) { setIcon(null); } else { final String browserIconName = HtmlSessionInformationsReport .getBrowserIconName(browser); final String fileName = "browsers/" + browserIconName; if (getClass().getResource(Parameters.getResourcePath(fileName)) == null) { setIcon(null); } else { setIcon(ImageIconCache.getImageIcon(fileName)); } } setToolTipText(browser); } // sans texte return super.getTableCellRendererComponent(jtable, null, isSelected, hasFocus, row, column); } } private class OsTableCellRenderer extends MDefaultTableCellRenderer { private static final long serialVersionUID = 1L; OsTableCellRenderer() { super(); setHorizontalAlignment(SwingConstants.CENTER); } @Override public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // icône et tooltip correspondant au navigateur if (row == -1) { setIcon(null); setToolTipText(null); } else { final MTable<SessionInformations> myTable = getTable(); final SessionInformations sessionInformations = myTable.getList() .get(myTable.convertRowIndexToModel(row)); final String os = sessionInformations.getOs(); if (os == null) { setIcon(null); } else { final String osIconName = HtmlSessionInformationsReport.getOSIconName(os); final String fileName = "servers/" + osIconName; if (getClass().getResource(Parameters.getResourcePath(fileName)) == null) { setIcon(null); } else { setIcon(ImageIconCache.getImageIcon(fileName)); } } setToolTipText(os); } // sans texte return super.getTableCellRendererComponent(jtable, null, isSelected, hasFocus, row, column); } } SessionInformationsPanel(RemoteCollector remoteCollector) throws IOException { super(remoteCollector); refresh(); } final void refresh() throws IOException { removeAll(); this.sessionsInformations = getRemoteCollector().collectSessionInformations(null); this.attributesTable = new MTable<>(); setName(getString("Sessions")); final JLabel titleLabel = Utilities.createParagraphTitle(getName(), "system-users.png"); add(titleLabel, BorderLayout.NORTH); final MTableScrollPane<SessionInformations> scrollPane = createScrollPane(); this.table = scrollPane.getTable(); table.setList(sessionsInformations); add(scrollPane, BorderLayout.CENTER); final JPanel southPanel = new JPanel(new BorderLayout()); southPanel.setOpaque(false); southPanel.add(createButtonsPanel(), BorderLayout.NORTH); southPanel.add(createSummaryLabel(), BorderLayout.CENTER); southPanel.add(createAttributesPanel(), BorderLayout.SOUTH); add(southPanel, BorderLayout.SOUTH); } private MTableScrollPane<SessionInformations> createScrollPane() { boolean displayUser = false; for (final SessionInformations sessionInformations : sessionsInformations) { if (sessionInformations.getRemoteUser() != null) { displayUser = true; break; } } final MTableScrollPane<SessionInformations> tableScrollPane = new MTableScrollPane<>(); final MTable<SessionInformations> myTable = tableScrollPane.getTable(); myTable.addColumn("id", getString("Session_id")); myTable.addColumn("lastAccess", getString("Dernier_acces")); myTable.addColumn("age", getString("Age")); myTable.addColumn("expirationDate", getString("Expiration")); myTable.addColumn("attributeCount", getString("Nb_attributs")); myTable.addColumn("serializable", getString("Serialisable")); myTable.addColumn("serializedSize", getString("Taille_serialisee")); myTable.addColumn("remoteAddr", getString("Adresse_IP")); myTable.addColumn("countryDisplay", getString("Pays")); myTable.addColumn("browser", getString("Navigateur")); myTable.addColumn("os", getString("OS")); if (displayUser) { myTable.addColumn("remoteUser", getString("Utilisateur")); } final MDateTableCellRenderer durationTableCellRenderer = new MDateTableCellRenderer(); durationTableCellRenderer.setDateFormat(I18N.createDurationFormat()); myTable.setColumnCellRenderer("lastAccess", durationTableCellRenderer); myTable.setColumnCellRenderer("age", durationTableCellRenderer); final MDateTableCellRenderer dateAndTimeTableCellRenderer = new MDateTableCellRenderer(); dateAndTimeTableCellRenderer.setDateFormat(I18N.createDateAndTimeFormat()); myTable.setColumnCellRenderer("expirationDate", dateAndTimeTableCellRenderer); myTable.setColumnCellRenderer("countryDisplay", new CountryTableCellRenderer()); myTable.setColumnCellRenderer("browser", new BrowserTableCellRenderer()); myTable.setColumnCellRenderer("os", new OsTableCellRenderer()); return tableScrollPane; } private JPanel createAttributesPanel() { final JPanel attributesPanel = new JPanel(new BorderLayout()); attributesPanel.setOpaque(false); final JLabel attributesLabel = new JLabel(getString("Attributs")); attributesLabel.setFont(attributesLabel.getFont().deriveFont(Font.BOLD)); attributesPanel.add(attributesLabel, BorderLayout.NORTH); final MTableScrollPane<SessionAttribute> attributesTableScrollPane = new MTableScrollPane<>( attributesTable); attributesTable.addColumn("name", getString("Nom")); attributesTable.addColumn("type", getString("Type")); attributesTable.addColumn("serializable", getString("Serialisable")); attributesTable.addColumn("serializedSize", getString("Taille_serialisee")); attributesTable.addColumn("content", getString("Contenu")); attributesTable.setPreferredScrollableViewportSize(new Dimension(-1, 100)); attributesPanel.add(attributesTableScrollPane, BorderLayout.CENTER); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { refreshAttributes(); } } }); return attributesPanel; } private JLabel createSummaryLabel() { long totalSerializedSize = 0; int nbSerializableSessions = 0; for (final SessionInformations sessionInformations : sessionsInformations) { final int size = sessionInformations.getSerializedSize(); if (size >= 0) { totalSerializedSize += size; nbSerializableSessions++; } } final long meanSerializedSize; if (nbSerializableSessions > 0) { meanSerializedSize = totalSerializedSize / nbSerializableSessions; } else { meanSerializedSize = -1; } final JLabel summaryLabel = new JLabel("<html><div align='right'>" + getFormattedString("nb_sessions", sessionsInformations.size()) + "<br/>" + getFormattedString("taille_moyenne_sessions", meanSerializedSize)); summaryLabel.setHorizontalAlignment(SwingConstants.RIGHT); return summaryLabel; } private JPanel createButtonsPanel() { final MButton refreshButton = createRefreshButton(); refreshButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { refresh(); } catch (final IOException ex) { showException(ex); } } }); final MButton pdfButton = createPdfButton(); pdfButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { actionPdf(); } catch (final IOException ex) { showException(ex); } } }); final MButton xmlJsonButton = createXmlJsonButton((Serializable) sessionsInformations); final MButton invalidateAllSessionsButton = createInvalidateAllSessionsButton(); final MButton invalidateSessionButton = createInvalidateSessionButton(); getTable().getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { final SessionInformations sessionInformations = getTable().getSelectedObject(); invalidateSessionButton.setEnabled(sessionInformations != null); } }); invalidateSessionButton.setEnabled(getTable().getSelectedObject() != null); return Utilities.createButtonsPanel(refreshButton, pdfButton, xmlJsonButton, invalidateAllSessionsButton, invalidateSessionButton); } private MButton createInvalidateAllSessionsButton() { final MButton invalidateAllSessionsButton = new MButton(getString("invalidate_sessions"), INVALIDATE_SESSION_ICON); invalidateAllSessionsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (confirm(getFormattedString("confirm_invalidate_sessions"))) { actionInvalidateAllSessions(); } } }); return invalidateAllSessionsButton; } private MButton createInvalidateSessionButton() { final MButton invalidateSessionButton = new MButton(getString("invalidate_session"), INVALIDATE_SESSION_ICON); invalidateSessionButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final SessionInformations sessionInformations = getTable().getSelectedObject(); if (sessionInformations != null && confirm(getFormattedString("confirm_invalidate_session"))) { actionInvalidateSession(sessionInformations); } } }); return invalidateSessionButton; } final void actionInvalidateAllSessions() { try { final String message = getRemoteCollector().executeActionAndCollectData( Action.INVALIDATE_SESSIONS, null, null, null, null, null); showMessage(message); refresh(); } catch (final IOException ex) { showException(ex); } } final void actionInvalidateSession(final SessionInformations sessionInformations) { try { final String message = getRemoteCollector().executeActionAndCollectData( Action.INVALIDATE_SESSION, null, sessionInformations.getId(), null, null, null); showMessage(message); refresh(); } catch (final IOException ex) { showException(ex); } } final void actionPdf() throws IOException { final File tempFile = createTempFileForPdf(); final PdfOtherReport pdfOtherReport = createPdfOtherReport(tempFile); try { pdfOtherReport.writeSessionInformations(sessionsInformations); } finally { pdfOtherReport.close(); } Desktop.getDesktop().open(tempFile); } final void refreshAttributes() { getAttributesTable().setList(null); final SessionInformations sessionInformations = getTable().getSelectedObject(); if (sessionInformations != null) { try { final List<SessionInformations> list = getRemoteCollector() .collectSessionInformations(sessionInformations.getId()); if (list.isEmpty()) { final String message = getFormattedString("session_invalidee", sessionInformations.getId()); showMessage(message); } else { getAttributesTable().setList(list.get(0).getAttributes()); } } catch (final IOException ex) { showException(ex); } } } MTable<SessionInformations> getTable() { return table; } MTable<SessionAttribute> getAttributesTable() { return attributesTable; } }
{ "pile_set_name": "Github" }
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the gradio package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: gradio\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2018-01-01 14:42+0100\n" "PO-Revision-Date: 2018-01-05 12:13+0000\n" "Last-Translator: Florian <floflr@zaclys.net>\n" "Language-Team: French " "<https://hosted.weblate.org/projects/gradio/translations/fr/>\n" "Language: fr\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n > 1;\n" "X-Generator: Weblate 2.19-dev\n" #: data/ui/app-menu.ui:6 data/ui/menubutton.ui:192 #: src/page/gradio-settings-page.vala:120 msgid "Settings" msgstr "Paramètres" #: data/ui/app-menu.ui:12 data/ui/menubutton.ui:206 msgid "About" msgstr "À propos" #: data/ui/app-menu.ui:18 data/ui/menubutton.ui:220 msgid "Quit" msgstr "Quitter" #: data/ui/page/library-page.ui:44 msgid "Your library is empty" msgstr "Votre bibliothèque est vide" #: data/ui/page/library-page.ui:62 msgid "If you add stations to the library, you will find them here." msgstr "" "Si vous ajoutez des stations radio à la bibliothèque, vous les trouverez ici." #: data/ui/page/library-page.ui:75 msgid "Add stations to library" msgstr "Ajouter des stations radios à la bibliothèque" #: data/ui/page/collections-page.ui:43 msgid "You don't have any collection" msgstr "Vous n'avez aucune collection / liste de lecture" #: data/ui/page/collections-page.ui:61 msgid "You can group stations into collections." msgstr "" "Vous pouvez regrouper des stations dans des collections / listes de lecture." #: data/ui/details-box.ui:23 data/ui/selection-toolbar.ui:233 msgid "Details" msgstr "Détails" #: data/ui/details-box.ui:137 data/ui/station-editor.ui:125 #: data/ui/menubutton.ui:369 src/gradio-searchbar.vala:188 msgid "Name" msgstr "Nom" #: data/ui/details-box.ui:169 msgid "Type" msgstr "Genre" #: data/ui/details-box.ui:206 msgid "Items" msgstr "Contenu" #: data/ui/details-box.ui:250 data/ui/menubutton.ui:354 #: src/gradio-searchbar.vala:187 msgid "Votes" msgstr "Votes" #: data/ui/details-box.ui:282 msgid "Location" msgstr "Lieu d'origine" #: data/ui/details-box.ui:314 data/ui/station-editor.ui:322 msgid "Tags" msgstr "Mots clés" #: data/ui/details-box.ui:346 msgid "Codec" msgstr "Codec" #: data/ui/details-box.ui:433 data/ui/selection-toolbar.ui:83 msgid "Play" msgstr "Lire" #: data/ui/details-box.ui:478 msgid "Open homepage" msgstr "Ouvrir la page d'accueil" #: data/ui/details-box.ui:523 data/ui/selection-toolbar.ui:195 msgid "Edit" msgstr "Éditer" #: data/ui/organize-collection-popover.ui:25 msgid "Enter name for new collection..." msgstr "Entrer un nom pour la nouvelle collection..." #: data/ui/organize-collection-popover.ui:35 msgid "Create" msgstr "Créer" #: data/ui/organize-collection-popover.ui:78 msgid "Select collection:" msgstr "Sélectionner la collection :" #: data/ui/selection-menu.ui:7 msgid "Select All" msgstr "Tout sélectionner" #: data/ui/selection-menu.ui:11 msgid "Select None" msgstr "Ne rien sélectionner" #: data/ui/selection-toolbar.ui:28 msgid "Save" msgstr "Enregistrer" #: data/ui/selection-toolbar.ui:70 msgid "Click an item to view options" msgstr "Cliquer sur un élément pour voir les options" #: data/ui/selection-toolbar.ui:104 msgid "Collection" msgstr "Collection" #: data/ui/selection-toolbar.ui:117 msgid "Add to library" msgstr "Ajouter à la bibliothèque" #: data/ui/selection-toolbar.ui:134 msgid "Remove from Library" msgstr "Supprimer de la Bibliothèque" #: data/ui/selection-toolbar.ui:159 msgid "Rename" msgstr "Renommer" #: data/ui/selection-toolbar.ui:174 msgid "Vote" msgstr "Votes" #: data/ui/station-editor.ui:39 msgid "Global database" msgstr "Base de données générale" #: data/ui/station-editor.ui:54 msgid "" "Gradio is using an internet database. Everything you enter here, is " "going to be visible for all users. Please be careful, and double check your " "input!" msgstr "" "Gradio utilise une base de données Internet. Tout ce que vous entrez ici " "sera visible par tous les utilisateurs. Faites attention et vérifier vos " "ajouts !" #: data/ui/station-editor.ui:68 msgid "Continue" msgstr "Continuer" #: data/ui/station-editor.ui:151 msgid "Stream Address" msgstr "Adresse du flux" #: data/ui/station-editor.ui:166 data/ui/menubutton.ui:399 #: src/gradio-searchbar.vala:190 msgid "Country" msgstr "Pays" #: data/ui/station-editor.ui:181 data/ui/menubutton.ui:414 #: src/gradio-searchbar.vala:191 msgid "State" msgstr "Ville" #: data/ui/station-editor.ui:196 data/ui/menubutton.ui:384 #: src/gradio-searchbar.vala:189 msgid "Language" msgstr "Langue" #: data/ui/station-editor.ui:266 msgid "Favicon Address" msgstr "Adresse icône" #: data/ui/station-editor.ui:304 msgid "Enter tags separated by commas" msgstr "Entrez les tags, séparés par des virgules" #: data/ui/station-editor.ui:337 msgid "Homepage" msgstr "Page d'accueil" #: data/ui/station-editor.ui:480 msgid "Server Response" msgstr "Réponse du serveur" #: data/ui/station-editor.ui:516 msgid "Close" msgstr "Fermer" #: data/ui/station-editor.ui:546 msgid "Cancel" msgstr "Annuler" #: data/ui/station-editor.ui:555 msgid "Done" msgstr "Valider" #: data/ui/page/search-page.ui:79 data/ui/page/search-page.ui:158 #: data/ui/page/search-page.ui:237 msgid "More..." msgstr "Plus..." #: data/ui/page/search-page.ui:101 msgid "Stations with the most votes" msgstr "Stations radio avec le plus de votes" #: data/ui/page/search-page.ui:180 msgid "Recently clicked stations" msgstr "Stations radio récentes" #: data/ui/page/search-page.ui:259 msgid "Stations with the most clicks" msgstr "Stations radio avec le plus de vues" #: data/ui/page/search-page.ui:346 src/page/gradio-search-page.vala:171 msgid "Search" msgstr "Recherche" #: data/ui/page/search-page.ui:381 msgid "Results:" msgstr "Résultat :" #: data/ui/page/search-page.ui:477 msgid "No results found" msgstr "Aucun résultat trouvé" #: data/ui/page/search-page.ui:495 msgid "" "Either the station does not exist, or you have to search with other keywords." msgstr "" "Soit la station n'existe pas, soit vous devez rechercher avec d'autres mots-" "clés." #: data/ui/menubutton.ui:104 data/ui/menubutton.ui:332 msgid "Sorting" msgstr "Trier" #: data/ui/menubutton.ui:119 msgid "Hide broken stations" msgstr "Cacher les stations sans lien valide" #: data/ui/menubutton.ui:145 data/ui/menubutton.ui:264 #: src/page/gradio-library-page.vala:81 msgid "Library" msgstr "Bibliothèque" #: data/ui/menubutton.ui:160 msgid "Create new radio station" msgstr "Créer une nouvelle station radio" #: data/ui/menubutton.ui:281 msgid "Import" msgstr "Importer" #: data/ui/menubutton.ui:295 msgid "Export" msgstr "Exporter" #: data/ui/menubutton.ui:429 src/gradio-searchbar.vala:193 msgid "Clicks" msgstr "Vues" #: data/ui/menubutton.ui:444 src/gradio-searchbar.vala:192 msgid "Bitrate" msgstr "Débit" #: data/ui/menubutton.ui:459 src/gradio-searchbar.vala:194 msgid "Date" msgstr "Date" #: data/ui/menubutton.ui:499 src/gradio-searchbar.vala:197 msgid "Ascending" msgstr "Croissant" #: data/ui/menubutton.ui:514 src/gradio-searchbar.vala:198 msgid "Descending" msgstr "Décroissant" #: src/page/gradio-collection-items-page.vala:75 #: src/page/gradio-library-page.vala:88 msgid "Items: " msgstr "Contenu: " #: src/page/gradio-library-page.vala:86 msgid "Fetching station data…" msgstr "Récupération des données de la station radio…" #: src/page/gradio-settings-page.vala:37 msgid "Features" msgstr "Fonctionalités" #: src/page/gradio-settings-page.vala:40 msgid "Playback" msgstr "Playback" #: src/page/gradio-settings-page.vala:43 msgid "Appearance" msgstr "Apparence" #: src/page/gradio-settings-page.vala:46 msgid "Cache" msgstr "Cache" #. APPEARANCE #. Dark design #: src/page/gradio-settings-page.vala:54 msgid "Prefer dark theme" msgstr "Préférer le thème sombre" #: src/page/gradio-settings-page.vala:54 msgid "Use a dark theme, if possible" msgstr "Utiliser un thème sombre, si possible" #. Show technical station information. #: src/page/gradio-settings-page.vala:60 msgid "Show technical information" msgstr "Afficher les informations techniques" #: src/page/gradio-settings-page.vala:60 msgid "Display additional information such as bitrate and codec" msgstr "Afficher des informations supplémentaires (bitrate et codec)" #. PLAYBACK #. enable background playback #: src/page/gradio-settings-page.vala:68 msgid "Background Playback" msgstr "Lecture en arrière plan" #: src/page/gradio-settings-page.vala:68 msgid "Continue the playback if you close the Gradio window" msgstr "Continuer la lecture si on ferme la fenêtre Gradio" #. resume playback on startup #: src/page/gradio-settings-page.vala:74 msgid "Resume playback on startup" msgstr "Démarrer avec la lecture précédente" #: src/page/gradio-settings-page.vala:74 msgid "Play the latest station if you start Gradio" msgstr "Jouer la dernière station au démarrage de Gradio" #. FEATURES #. mpris #: src/page/gradio-settings-page.vala:83 msgid "MPRIS" msgstr "MPRIS" #: src/page/gradio-settings-page.vala:83 msgid "Integrate Gradio as media player in your desktop environment" msgstr "" "Intégrer Gradio comme lecteur multimédia dans votre environnement de bureau" #. enable notifications #: src/page/gradio-settings-page.vala:89 msgid "Notifications" msgstr "Notifications" #: src/page/gradio-settings-page.vala:89 msgid "Show desktop notifications" msgstr "Afficher des notifications sur le bureau" #. enable tray icon #: src/page/gradio-settings-page.vala:95 msgid "Tray icon" msgstr "Icône de barre d'état" #: src/page/gradio-settings-page.vala:95 msgid "Show a tray icon, to restore the main window" msgstr "" "Afficher une icône dans la barre d'état, pour restaurer la fenêtre principale" #. CACHE #. cache station images #: src/page/gradio-settings-page.vala:104 msgid "Cache station icons" msgstr "Icônes station radio" #: src/page/gradio-settings-page.vala:104 msgid "Saves the images locally." msgstr "Sauvegarder les images en local." #: src/page/gradio-settings-page.vala:109 msgid "Clear Cache" msgstr "Vider le cache" #: src/page/gradio-settings-page.vala:109 msgid "Clear all cached station icons" msgstr "Supprimer tout les icônes en cache" #: src/gradio-headerbar.vala:53 src/gradio-headerbar.vala:59 msgid "Click on items to select them" msgstr "Cliquer sur des éléments pour les sélectionner" #: src/gradio-headerbar.vala:61 #, c-format msgid "%i selected" msgstr "%i sélectionné" #: src/gradio-searchbar.vala:83 msgid "Search for radio stations" msgstr "Rechercher des stations radio" #: src/gradio-searchbar.vala:201 #, c-format msgid "Sorting: %s / %s" msgstr "Trier : %s / %s" #: src/gradio-searchbar.vala:277 msgid "Select Country …" msgstr "Sélectionner Pays …" #: src/gradio-searchbar.vala:308 msgid "Select State …" msgstr "Sélectionner Ville …" #: src/gradio-searchbar.vala:339 msgid "Select Language …" msgstr "Sélectionner Langue …" #: src/gradio-searchbar.vala:370 msgid "Select Tag …" msgstr "Sélectionner Marque …" #: src/gradio-station-editor-dialog.vala:54 msgid "Create radio station" msgstr "Créer station radio" #: src/gradio-station-editor-dialog.vala:60 msgid "Edit radio station" msgstr "Éditer station radio" #: src/gradio-station-editor-dialog.vala:131 msgid "\"Name\" and \"Stream\" information is required." msgstr "Les informations \"Nom\" et \"Flux\" sont requises." #: src/gradio-selection-toolbar.vala:98 #, c-format msgid "%i radio station(s) not present in library." msgstr "%i station(s) radio non présentes dans la bibliothèque." #: src/gradio-selection-toolbar.vala:108 #, c-format msgid "%i radio station(s) already added to library." msgstr "%i station(s) radio déjà ajouté à la bibliothèque." #~ msgid "Description" #~ msgstr "Description" #~ msgid " Items" #~ msgstr " Éléments" #~ msgid "100%" #~ msgstr "100%" #~ msgid "New public radio station" #~ msgstr "Nouvelle station radio publique" #~ msgid "Create a new radio station, which is visible for all users." #~ msgstr "" #~ "Créer une nouvelle station radio, visible par tous les utilisateurs." #~ msgid "Where" #~ msgstr "Lieu" #~ msgid "Fill your library with something new" #~ msgstr "Importer dans votre bibliothèque" #~ msgid "There are several options available to add something new." #~ msgstr "Il y a plusieurs possibilités pour ajouter une nouveauté." #~ msgid "New Collection…" #~ msgstr "Nouvelle collection…" #~ msgid "Add" #~ msgstr "Ajouter" #~ msgid "Remove" #~ msgstr "Retirer" #~ msgid "Don't show stations, which are not working" #~ msgstr "Ne pas afficher les stations hors service" #~ msgid "Replace the current library with a another one" #~ msgstr "Remplacer la librairie actuelle par une autre" #~ msgid "Do you want to replace the current library with this one?" #~ msgstr "Voulez vous remplacer cette librairie par celle ci?" #~ msgid "Export the current library" #~ msgstr "Exporter la librairie actuelle" #~ msgid "_Cancel" #~ msgstr "_Annuler" #~ msgid "Select database to import" #~ msgstr "Choisir la base de données à importer" #~ msgid "Show famous radio stations" #~ msgstr "Afficher les stations radio célèbres" #~ msgid "Show popular radio stations" #~ msgstr "Afficher les stations radio populaires" #~ msgid "Show radio stations which have recently been clicked." #~ msgstr "Afficher les stations radio vues récemment." #~ msgid "Search for specific radio stations." #~ msgstr "Rechercher des stations radio spécifiques."
{ "pile_set_name": "Github" }
class C { x match { case (x: T) :: Nil => } }
{ "pile_set_name": "Github" }
新しいエンコーディング変換関数の追加方法 2006/04/15 Tatsuo Ishii はじめに PostgreSQLには,データベースとフロントエンドのエンコーディングが異なる ときに,自動的にエンコーディングの変換を行う機能があります.このディレ クトリには,そのときに使われる関数が登録されています.これらの関数はユー ザ定義C関数として,initdbの中で登録されます.具体的には, /usr/local/pgsql/share/conversion_create.sql の中で登録されます(このファ イルはこのディレクトリでmakeしたときに自動生成されます). また,これらの関数はconvert()関数からも呼び出されることもあります. このREADMEでは,C関数を定義する方法と,それをMakefileなどに追加する方 法を説明します. o C関数の呼び出し形式 エンコーディング変換関数の呼び出し形式は次のようになります. conv_proc( INTEGER, -- source encoding id INTEGER, -- destination encoding id CSTRING, -- source string (null terminated C string) INTERNAL, -- destination string (null terminated C string) INTEGER -- source string length ) returns VOID; 唯一の出力引数は4番目のdestination stringです.ユーザ定義関数は必要 なメモリをpallocし,そこに変換結果をNULLターミネートされたC文字列と して出力しなければなりません.また,適切な大きさのメモリを確保するの は,このC関数の責任です.というのは,一般に変換された文字列の長さは ソース文字列の長さ(5番目の引数で指定されます.単位はNULLターミネート を含まないバイト数です)とは一致しないからです. エンコーディングIDはinclude/mb/pg_wchar.hのtypedef enum pg_encで定義 されています. o 関数の登録とコンパイル 作ったC関数はサブディレクトリを作り,その中に納めます.その中に Makefileも必要になりますが,他のディレクトリにあるMakefileを参考にす れば簡単に作成できるでしょう. 次にメインのMakefile(このファイルが置いてある同じディレクトリにあり ます)に関数に関する記述を追加します. (1) DIRS=の後にサブディレクトリ名を追加します. (2) @set \ で始まる項目に記述を追加します.1関数につき1行の追加が必要 です. コンバージョンの名前 ソースエンコーディング名 デスティネーションエンコーディング名 関数名 オブジェクトファイル名 を1行の中にスペースで区切って追加します. o テスト 以上が終わったら,このファイルがあるディレクトリでmakeし,すべてがう まくいくことを確認します.特に,create_conversion.sqlがちゃんとした 内容になっているかどうか確認しましょう.良さそうだったら,テスト用に 新しいデータベースを作り,そこでこのスクリプトを実行します. $ psql -e -f create_conversion.sql test これも正常だったら,最後にregression test suiteにテスト項目を追加し てください.具体的には,src/test/regress/sql/conversion.sqlに追加し, regression testを行います. o 注意事項 デフォルトのエンコーディング変換として使用できるためには,ソースエン コーディングとデスティネーションエンコーディングの間で双方向の変換が できることが必要です.すなわち,あるエンコーディングのペアに付き,2 個の関数の作成が必要です.これらの関数は別々のサブディレクトリに登録 しても良いですが,通常は一つのソースファイル中に2個の関数を書くこと が多いでしょう.
{ "pile_set_name": "Github" }
17 comment:c C 0.0324960 0.9635310 0.4248560 C -1.2139010 0.3117780 -0.1703540 C -1.2690260 -1.1610110 0.2385370 C -0.0408820 -1.9398950 -0.2580310 C 1.2168480 -1.1088530 -0.2813690 C 1.2560360 0.1880130 0.0166160 H -2.1171870 0.8370150 0.1686210 H -1.3173860 -1.2176770 1.3345571 H -0.2214380 -2.3246150 -1.2721570 H 2.1339431 -1.6192600 -0.5733430 H -2.1857650 -1.6292220 -0.1365870 H -1.1611530 0.4137470 -1.2615960 H 0.1174780 -2.8278530 0.3679930 H -0.0509760 0.9421960 1.5270680 H 2.1881521 0.7481970 -0.0179540 O 0.2132210 2.3042090 -0.0052430 H -0.5502180 2.8094211 0.3007880
{ "pile_set_name": "Github" }
################# :mod:`hvad.query` ################# .. module:: hvad.query This modules containts abstractions for accessing some internal parts of Django ORM that are used in hvad. The intent is that anytime some code in hvad needs to access some Django internals, it should do so through a function in this module. .. function:: query_terms(model, path) This iterator yields all terms in the specified ``path``, along with full introspection data. Each term is output as a named tuple with the following members: * ``depth``: how deep in the path is this term. Counted from zero. * ``term``: the term string. * ``model: `` the model the term is attached to. It will start with passed ``model`` then walk through relations as terms are enumerated. * ``field``: the actual field, on the model, the term refers to. * ``translated``: whether the field is a translated field (True) or a shared fielf (False). * ``target``: the target model of the relation, or ``None`` if not a relational field. * ``many``: whether the target can be multiple (that is, it is a M2M or reverse FK). If a field is not recognized, it is assumed the path is complete and everything that follows is a query expression (such as ``__year__in``). Query expression terms will be yielded with ``field`` set to ``None``. .. function:: q_children(q) Iterator that recursively yields all key-value pairs of a ``Q`` object. Each pair is yielded as a 3-tuple: the pair itself, its container and its index in the container. This allows modifying it. .. function:: expression_nodes(expression) Iterator that recursively yields all nodes in an expression tree. .. function:: where_node_children(node) Iterator that recursively yields all fields of a where node. It is used to determine whether a custom ``Q`` object included a ``language_code`` filter.
{ "pile_set_name": "Github" }
# 编排配置说明文档 ## 功能菜单 WeCube界面导航包含任务、设计、执行、监测、调整、智慧、协同、系统共八个主菜单。 访问 “协同 > 任务编排” 菜单 ![orchestration_menu](images/orchestration_menu.png) 进入 “任务编排管理” 页面 ![orchestration_main](images/orchestration_main.png) 点击 “编排名称” 下拉选择框, 可以新增编排或者查看已经配置好的编排列表 ![orchestration_search](images/orchestration_search.png) 在编排下拉列表选中一个已经编排, 显示编排详细信息 ![orchestration_search_result](images/orchestration_search_result.png) ## 编排元素 在编排编辑页面中,除了显示当前选择编排节点和流程信息外, 还显示了编排可以用使用的节点元素,见下图红框部分 ![orchestration_config_item](images/orchestration_config_item.png) 自上而下编排元素依次为: - 启动手动工具 - 启动Lasso工具 - 启动创建/删除空间工具 - 启动全局连接工具 - 创建StratEvent - Create intermediate/Boundary Event - 创建EndEvent - Create Gateway - 创建Task - 创建可折叠子流程 各元素详细说明是使用方式详见文档[camunda产品模型官网](https://camunda.com/products/modeler/) ## 新增编排 下面以 “删除MYSQL” 为例, 演示如何新增一个编排。 1. 新建编排 点击 “编排名称” 下拉框右侧的加号按钮, 开始新建编排,弹出新建编排的权限配置页面,如下图所示: ![orchestration_new_auth_1](images/orchestration_new_auth_1.png) 页面上半部分的 “属主角色” 决定哪些角色的用户可以编辑、查看和使用该编排。角色清单是当前用户所拥有的角色。 页面下半部分的 “使用角色” 决定哪些角色的用户可以查看和使用该编排, 但是无编排的编辑权限。 配置完成后, 点击 “确定” 保存,权限配置页面关闭 ![orchestration_new_auth_2](images/orchestration_new_auth_2.png) 2. 编排编辑页面 权限配置页面关闭后, 回到编排编辑页面 ![orchestration_new_step_1](images/orchestration_new_step_1.png) 3. 选择编排实体类型 在 “编排实体类型” 下拉框中选择编排关联的实体类型, 实体类型来源于各插件提供的数据模型。 ![orchestration_new_step_2](images/orchestration_new_step_2.png) 本示例所演示的“删除MYSQL” 属于wecmdb的 “resource_instance” 资源实例类型。 4. 编排名称和版本 在编排编辑页面右侧, 输入编排名称和版本名称,如下图: ![orchestration_new_step_3](images/orchestration_new_step_3.png) 5. 配置编排流程节点 - 在编排元素面板中,点击选中 “创建StratEvent”, 拖到画布空白处,如下图, 在开始节点右侧的小图标中选择 “追加Task” ![orchestration_new_step_4](images/orchestration_new_step_4.png) - 新增一个任务节点, 在右侧 “名称”输入框中输入节点名称,点击工具按钮,修改节点类型,当前Task类型只支持“可折叠子流程”。 ![orchestration_new_step_4_1](images/orchestration_new_step_4_1.png) - 右键选择 “配置插件” ![orchestration_new_step_5](images/orchestration_new_step_5.png) - 在弹出页面中的 “插件” 下拉框中选择已注册的插件功能 ![orchestration_new_step_6](images/orchestration_new_step_6.png) - “确认” 保存 ![orchestration_new_step_7](images/orchestration_new_step_7.png) - 回到主编辑页面, 点击当前节点, 可以继续 “追加Task” ![orchestration_new_step_8](images/orchestration_new_step_8.png) - 按同样的方式增加后续节点知道所有流程节点配置完成。注意插件节点中, 如果要使用前置节点的输出作为入参, 可以在插件配置中进行参数配置, 如下图 ![orchestration_new_step_9](images/orchestration_new_step_9.png) - 流程节点配置完成后, 最后新增一个结束节点 “创建EndEvent” ![orchestration_new_step_10](images/orchestration_new_step_10.png) - 点击 “保存编排” ![orchestration_new_step_11](images/orchestration_new_step_11.png) 至此,已经新建了一个完整的编排。能在 “编排名称” 下拉列表中看到刚刚创建的编排, 排在第一位。 ![orchestration_new_step_12](images/orchestration_new_step_12.png) ## 修改/删除编排 1. 删除编排 在 “编排名称” 下拉列表中,点击删除按钮, 确认后可以删除编排。 ![orchestration_del_1](images/orchestration_del_1.png) 2. 修改编排权限信息 在 “编排名称” 下拉列表中,点击编辑按钮 ![orchestration_upd_1](images/orchestration_upd_1.png) 弹出权限修改页面 ![orchestration_upd_2](images/orchestration_upd_2.png) 可以修改属主和使用权限。 3. 修改编排的详细信息 在 “编排名称” 下拉列表中, 选择编排, ![orchestration_upd_3](images/orchestration_upd_3.png) 显示编排详细信息,可以进行编辑。 ![orchestration_upd_4](images/orchestration_upd_4.png) 注意:当前版本修改编排后需要同时修改编排名称, 否则会保存名称冲突无法保存。 ## 编排导出 选择一个编排, 点击 “导出” 按钮,即可完成编排导出。 ![orchestration_export](images/orchestration_export.png) ## 编排导入 在任务编排主页面,点击 “导入” 按钮, 在弹出框中选择要导入的编排文件, 点击 “打开” ![orchestration_import_1](images/orchestration_import_1.png) 即可完成编排导入,如下图 ![orchestration_import_2](images/orchestration_import_2.png)
{ "pile_set_name": "Github" }
/* crypto/bf/blowfish.h */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #ifndef HEADER_BLOWFISH_H # define HEADER_BLOWFISH_H # include <openssl/e_os2.h> #ifdef __cplusplus extern "C" { #endif # ifdef OPENSSL_NO_BF # error BF is disabled. # endif # define BF_ENCRYPT 1 # define BF_DECRYPT 0 /*- * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * ! BF_LONG has to be at least 32 bits wide. If it's wider, then ! * ! BF_LONG_LOG2 has to be defined along. ! * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ # if defined(__LP32__) # define BF_LONG unsigned long # elif defined(OPENSSL_SYS_CRAY) || defined(__ILP64__) # define BF_LONG unsigned long # define BF_LONG_LOG2 3 /* * _CRAY note. I could declare short, but I have no idea what impact * does it have on performance on none-T3E machines. I could declare * int, but at least on C90 sizeof(int) can be chosen at compile time. * So I've chosen long... * <appro@fy.chalmers.se> */ # else # define BF_LONG unsigned int # endif # define BF_ROUNDS 16 # define BF_BLOCK 8 typedef struct bf_key_st { BF_LONG P[BF_ROUNDS + 2]; BF_LONG S[4 * 256]; } BF_KEY; # ifdef OPENSSL_FIPS void private_BF_set_key(BF_KEY *key, int len, const unsigned char *data); # endif void BF_set_key(BF_KEY *key, int len, const unsigned char *data); void BF_encrypt(BF_LONG *data, const BF_KEY *key); void BF_decrypt(BF_LONG *data, const BF_KEY *key); void BF_ecb_encrypt(const unsigned char *in, unsigned char *out, const BF_KEY *key, int enc); void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int enc); void BF_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int *num, int enc); void BF_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int *num); const char *BF_options(void); #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
// greater.hpp // // (C) Copyright 2011 Vicente J. Botet Escriba // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // #ifndef BOOST_RATIO_MPL_GREATER_HPP #define BOOST_RATIO_MPL_GREATER_HPP #include <boost/ratio/ratio.hpp> #include <boost/ratio/mpl/numeric_cast.hpp> #include <boost/mpl/greater.hpp> namespace boost { namespace mpl { template<> struct greater_impl< rational_c_tag,rational_c_tag > { template< typename R1, typename R2 > struct apply : ratio_greater<R1, R2> { }; }; } } #endif // BOOST_RATIO_MPL_GREATER_HPP
{ "pile_set_name": "Github" }
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Multivariate Normal distribution classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib import linalg from tensorflow.contrib.distributions.python.ops import distribution_util from tensorflow.contrib.distributions.python.ops.bijectors import AffineLinearOperator from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops.distributions import kullback_leibler from tensorflow.python.ops.distributions import normal from tensorflow.python.ops.distributions import transformed_distribution __all__ = [ "MultivariateNormalLinearOperator", ] _mvn_sample_note = """ `value` is a batch vector with compatible shape if `value` is a `Tensor` whose shape can be broadcast up to either: ```python self.batch_shape + self.event_shape ``` or ```python [M1, ..., Mm] + self.batch_shape + self.event_shape ``` """ # TODO(b/35290280): Import in `../../__init__.py` after adding unit-tests. class MultivariateNormalLinearOperator( transformed_distribution.TransformedDistribution): """The multivariate normal distribution on `R^k`. The Multivariate Normal distribution is defined over `R^k` and parameterized by a (batch of) length-`k` `loc` vector (aka "mu") and a (batch of) `k x k` `scale` matrix; `covariance = scale @ scale.T`, where `@` denotes matrix-multiplication. #### Mathematical Details The probability density function (pdf) is, ```none pdf(x; loc, scale) = exp(-0.5 ||y||**2) / Z, y = inv(scale) @ (x - loc), Z = (2 pi)**(0.5 k) |det(scale)|, ``` where: * `loc` is a vector in `R^k`, * `scale` is a linear operator in `R^{k x k}`, `cov = scale @ scale.T`, * `Z` denotes the normalization constant, and, * `||y||**2` denotes the squared Euclidean norm of `y`. The MultivariateNormal distribution is a member of the [location-scale family](https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be constructed as, ```none X ~ MultivariateNormal(loc=0, scale=1) # Identity scale, zero shift. Y = scale @ X + loc ``` #### Examples ```python ds = tf.contrib.distributions la = tf.contrib.linalg # Initialize a single 3-variate Gaussian. mu = [1., 2, 3] cov = [[ 0.36, 0.12, 0.06], [ 0.12, 0.29, -0.13], [ 0.06, -0.13, 0.26]] scale = tf.cholesky(cov) # ==> [[ 0.6, 0. , 0. ], # [ 0.2, 0.5, 0. ], # [ 0.1, -0.3, 0.4]]) mvn = ds.MultivariateNormalLinearOperator( loc=mu, scale=la.LinearOperatorTriL(scale)) # Covariance agrees with cholesky(cov) parameterization. mvn.covariance().eval() # ==> [[ 0.36, 0.12, 0.06], # [ 0.12, 0.29, -0.13], # [ 0.06, -0.13, 0.26]] # Compute the pdf of an`R^3` observation; return a scalar. mvn.prob([-1., 0, 1]).eval() # shape: [] # Initialize a 2-batch of 3-variate Gaussians. mu = [[1., 2, 3], [11, 22, 33]] # shape: [2, 3] scale_diag = [[1., 2, 3], [0.5, 1, 1.5]] # shape: [2, 3] mvn = ds.MultivariateNormalLinearOperator( loc=mu, scale=la.LinearOperatorDiag(scale_diag)) # Compute the pdf of two `R^3` observations; return a length-2 vector. x = [[-0.9, 0, 0.1], [-10, 0, 9]] # shape: [2, 3] mvn.prob(x).eval() # shape: [2] ``` """ def __init__(self, loc=None, scale=None, validate_args=False, allow_nan_stats=True, name="MultivariateNormalLinearOperator"): """Construct Multivariate Normal distribution on `R^k`. The `batch_shape` is the broadcast shape between `loc` and `scale` arguments. The `event_shape` is given by last dimension of the matrix implied by `scale`. The last dimension of `loc` (if provided) must broadcast with this. Recall that `covariance = scale @ scale.T`. Additional leading dimensions (if any) will index batches. Args: loc: Floating-point `Tensor`. If this is set to `None`, `loc` is implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where `b >= 0` and `k` is the event size. scale: Instance of `LinearOperator` with same `dtype` as `loc` and shape `[B1, ..., Bb, k, k]`. validate_args: Python `bool`, default `False`. Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: Python `bool`, default `True`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to give Ops created by the initializer. Raises: ValueError: if `scale` is unspecified. TypeError: if not `scale.dtype.is_floating` """ parameters = locals() if scale is None: raise ValueError("Missing required `scale` parameter.") if not scale.dtype.is_floating: raise TypeError("`scale` parameter must have floating-point dtype.") with ops.name_scope(name, values=[loc] + scale.graph_parents): # Since expand_dims doesn't preserve constant-ness, we obtain the # non-dynamic value if possible. loc = ops.convert_to_tensor(loc, name="loc") if loc is not None else loc batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale( loc, scale) super(MultivariateNormalLinearOperator, self).__init__( distribution=normal.Normal( loc=array_ops.zeros([], dtype=scale.dtype), scale=array_ops.ones([], dtype=scale.dtype)), bijector=AffineLinearOperator( shift=loc, scale=scale, validate_args=validate_args), batch_shape=batch_shape, event_shape=event_shape, validate_args=validate_args, name=name) self._parameters = parameters @property def loc(self): """The `loc` `Tensor` in `Y = scale @ X + loc`.""" return self.bijector.shift @property def scale(self): """The `scale` `LinearOperator` in `Y = scale @ X + loc`.""" return self.bijector.scale @distribution_util.AppendDocstring(_mvn_sample_note) def _log_prob(self, x): return super(MultivariateNormalLinearOperator, self)._log_prob(x) @distribution_util.AppendDocstring(_mvn_sample_note) def _prob(self, x): return super(MultivariateNormalLinearOperator, self)._prob(x) def _mean(self): shape = self.batch_shape.concatenate(self.event_shape) has_static_shape = shape.is_fully_defined() if not has_static_shape: shape = array_ops.concat([ self.batch_shape_tensor(), self.event_shape_tensor(), ], 0) if self.loc is None: return array_ops.zeros(shape, self.dtype) if has_static_shape and shape == self.loc.get_shape(): return array_ops.identity(self.loc) # Add dummy tensor of zeros to broadcast. This is only necessary if shape # != self.loc.shape, but we could not determine if this is the case. return array_ops.identity(self.loc) + array_ops.zeros(shape, self.dtype) def _covariance(self): if distribution_util.is_diagonal_scale(self.scale): return array_ops.matrix_diag(math_ops.square(self.scale.diag_part())) else: return self.scale.matmul(self.scale.to_dense(), adjoint_arg=True) def _variance(self): if distribution_util.is_diagonal_scale(self.scale): return math_ops.square(self.scale.diag_part()) elif (isinstance(self.scale, linalg.LinearOperatorUDVHUpdate) and self.scale.is_self_adjoint): return array_ops.matrix_diag_part( self.scale.matmul(self.scale.to_dense())) else: return array_ops.matrix_diag_part( self.scale.matmul(self.scale.to_dense(), adjoint_arg=True)) def _stddev(self): if distribution_util.is_diagonal_scale(self.scale): return math_ops.abs(self.scale.diag_part()) elif (isinstance(self.scale, linalg.LinearOperatorUDVHUpdate) and self.scale.is_self_adjoint): return math_ops.sqrt(array_ops.matrix_diag_part( self.scale.matmul(self.scale.to_dense()))) else: return math_ops.sqrt(array_ops.matrix_diag_part( self.scale.matmul(self.scale.to_dense(), adjoint_arg=True))) def _mode(self): return self._mean() @kullback_leibler.RegisterKL(MultivariateNormalLinearOperator, MultivariateNormalLinearOperator) def _kl_brute_force(a, b, name=None): """Batched KL divergence `KL(a || b)` for multivariate Normals. With `X`, `Y` both multivariate Normals in `R^k` with means `mu_a`, `mu_b` and covariance `C_a`, `C_b` respectively, ``` KL(a || b) = 0.5 * ( L - k + T + Q ), L := Log[Det(C_b)] - Log[Det(C_a)] T := trace(C_b^{-1} C_a), Q := (mu_b - mu_a)^T C_b^{-1} (mu_b - mu_a), ``` This `Op` computes the trace by solving `C_b^{-1} C_a`. Although efficient methods for solving systems with `C_b` may be available, a dense version of (the square root of) `C_a` is used, so performance is `O(B s k**2)` where `B` is the batch size, and `s` is the cost of solving `C_b x = y` for vectors `x` and `y`. Args: a: Instance of `MultivariateNormalLinearOperator`. b: Instance of `MultivariateNormalLinearOperator`. name: (optional) name to use for created ops. Default "kl_mvn". Returns: Batchwise `KL(a || b)`. """ def squared_frobenius_norm(x): """Helper to make KL calculation slightly more readable.""" # http://mathworld.wolfram.com/FrobeniusNorm.html return math_ops.square(linalg_ops.norm(x, ord="fro", axis=[-2, -1])) # TODO(b/35041439): See also b/35040945. Remove this function once LinOp # supports something like: # A.inverse().solve(B).norm(order='fro', axis=[-1, -2]) def is_diagonal(x): """Helper to identify if `LinearOperator` has only a diagonal component.""" return (isinstance(x, linalg.LinearOperatorIdentity) or isinstance(x, linalg.LinearOperatorScaledIdentity) or isinstance(x, linalg.LinearOperatorDiag)) with ops.name_scope(name, "kl_mvn", values=[a.loc, b.loc] + a.scale.graph_parents + b.scale.graph_parents): # Calculation is based on: # http://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians # and, # https://en.wikipedia.org/wiki/Matrix_norm#Frobenius_norm # i.e., # If Ca = AA', Cb = BB', then # tr[inv(Cb) Ca] = tr[inv(B)' inv(B) A A'] # = tr[inv(B) A A' inv(B)'] # = tr[(inv(B) A) (inv(B) A)'] # = sum_{ij} (inv(B) A)_{ij}**2 # = ||inv(B) A||_F**2 # where ||.||_F is the Frobenius norm and the second equality follows from # the cyclic permutation property. if is_diagonal(a.scale) and is_diagonal(b.scale): # Using `stddev` because it handles expansion of Identity cases. b_inv_a = (a.stddev() / b.stddev())[..., array_ops.newaxis] else: b_inv_a = b.scale.solve(a.scale.to_dense()) kl_div = (b.scale.log_abs_determinant() - a.scale.log_abs_determinant() + 0.5 * ( - math_ops.cast(a.scale.domain_dimension_tensor(), a.dtype) + squared_frobenius_norm(b_inv_a) + squared_frobenius_norm(b.scale.solve( (b.mean() - a.mean())[..., array_ops.newaxis])))) kl_div.set_shape(array_ops.broadcast_static_shape( a.batch_shape, b.batch_shape)) return kl_div
{ "pile_set_name": "Github" }
/* * Copyright (C) Lightbend Inc. <https://www.lightbend.com> */ package com.example.shoppingcart.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.google.common.base.Preconditions; import org.pcollections.PMap; public class Summary { public final PMap<String, Integer> items; public final boolean checkedOut; @JsonCreator public Summary(PMap<String, Integer> items, boolean checkedOut) { this.items = Preconditions.checkNotNull(items, "items"); this.checkedOut = checkedOut; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>JQuery Form Wizard</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta> <link rel="stylesheet" type="text/css" href="./css/ui-lightness/jquery-ui-1.8.2.custom.css" /> <style type="text/css"> #demoWrapper { padding : 1em; width : 500px; border-style: solid; } #fieldWrapper { } #demoNavigation { margin-top : 0.5em; margin-right : 1em; text-align: right; } #data { font-size : 0.7em; } input { margin-right: 0.1em; margin-bottom: 0.5em; } .input_field_25em { width: 2.5em; } .input_field_3em { width: 3em; } .input_field_35em { width: 3.5em; } .input_field_12em { width: 12em; } label { margin-bottom: 0.2em; font-weight: bold; font-size: 0.8em; } label.error { color: red; font-size: 0.8em; margin-left : 0.5em; } .step span { float: right; font-weight: bold; padding-right: 0.8em; } .navigation_button { width : 70px; } #data { overflow : auto; } #extra_steps{ display : none; } </style> </head> <body> <div id="demoWrapper"> <h3>Example of a straight wizard</h3> <ul> <li>Straight wizard with one initial step.</li> <li>Add one a step by clicking the 'Add step' button.</li> <li>It is possible to add 2 additional steps.</li> </ul> <hr /> <h5 id="status"></h5> <form id="demoForm" method="post" action="json.html" class="bbq"> <div id="fieldWrapper"> <span class="step" id="first"> <span class="font_normal_07em_black">First step - Name</span><br /> <label for="firstname">First name</label><br /> <input class="input_field_12em" name="firstname" id="firstname" /><br /> <label for="surname">Surname</label><br /> <input class="input_field_12em" name="surname" id="surname" /><br /> </span> </div> <div id="demoNavigation"> <!-- Note the two added buttons, remove is initially hidden in the css above --> <input id="add" value="Add step" type="button" /> <input class="navigation_button" id="back" value="Back" type="reset" /> <input class="navigation_button" id="next" value="Next" type="submit" /> </div> </form> <hr /> <p id="data"></p> </div> <!-- Note that the following steps are outside the form and hidden in the css above --> <div id="extra_steps"> <div id="finland" class="step"> <span class="font_normal_07em_black">Step 2 - Personal information</span><br /> <label for="day_fi">Social Security Number</label><br /> <input class="input_field_25em" name="day" id="day_fi" value="DD" /> <input class="input_field_25em" name="month" id="month_fi" value="MM" /> <input class="input_field_3em" name="year" id="year_fi" value="YYYY" /> - <input class="input_field_3em" name="lastFour" id="lastFour_fi" value="XXXX" /><br /> <label for="countryPrefix_fi">Phone number</label><br /> <input class="input_field_35em" name="countryPrefix" id="countryPrefix_fi" value="+358" /> - <input class="input_field_3em" name="areaCode" id="areaCode_fi" /> - <input class="input_field_12em" name="phoneNumber" id="phoneNumber_fi" /><br /> <label for="email">*Email</label><br /> <input class="input_field_12em email required" name="myemail" id="myemail" /><br /> </div> <div id="confirmation" class="step"> <span class="font_normal_07em_black">Last step - Username</span><br /> <label for="username">User name</label><br /> <input class="input_field_12em" name="username" id="username" /><br /> <label for="password">Password</label><br /> <input class="input_field_12em" name="password" id="password" type="password" /><br /> <label for="retypePassword">Retype password</label><br /> <input class="input_field_12em" name="retypePassword" id="retypePassword" type="password" /><br /> </div> </div> <script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="../js/jquery.form.js"></script> <script type="text/javascript" src="../js/jquery.validate.js"></script> <script type="text/javascript" src="../js/bbq.js"></script> <script type="text/javascript" src="../js/jquery-ui-1.8.5.custom.min.js"></script> <script type="text/javascript" src="../js/jquery.form.wizard.js"></script> <script type="text/javascript"> $(function(){ $("#demoForm").formwizard({ formPluginEnabled: true, validationEnabled: true, focusFirstInput : true, formOptions :{ success: function(data){$("#status").fadeTo(500,1,function(){ $(this).html("You are now registered!").fadeTo(5000, 0); })}, beforeSubmit: function(data){$("#data").html("data sent to the server: " + $.param(data));}, dataType: 'json', resetForm: true } } ); $("#add").click(function(){ $("#fieldWrapper").append($("#extra_steps .step:first")); $("#demoForm").formwizard("update_steps"); return false; }); }); </script> </body> </html>
{ "pile_set_name": "Github" }
// Copyright 2020 The Google Research Authors. // // 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. goog.module('eeg_modelling.eeg_viewer.WindowLocation'); const Dispatcher = goog.require('eeg_modelling.eeg_viewer.Dispatcher'); const Store = goog.require('eeg_modelling.eeg_viewer.Store'); class WindowLocation { constructor() { const store = Store.getInstance(); // This listener callback will update the request parameters in the URL // hash and update the web history state accordingly. store.registerListener( Store.RequestProperties, 'WindowLocation', (store, changedProperties) => this.handleRequestParams(store, changedProperties)); } /** * Parses the URL fragment into a QueryData object. * @return {!Dispatcher.FragmentData} Dictionary of query data fields to * update store with. */ parseFragment() { const fragmentData = {}; const hash = location.hash.substring(1); if (hash) { const assignments = hash.split('&'); assignments.forEach((assignment) => { const elements = assignment.split('='); if (elements.length < 2) { Dispatcher.getInstance().sendAction({ actionType: Dispatcher.ActionType.ERROR, data: { message: 'Bad Fragment', }, }); } fragmentData[elements[0]] = decodeURIComponent( elements.slice(1).join('=')); }); } const actionData = {}; Store.RequestProperties.forEach((storeParam) => { const param = storeParam.toLowerCase(); const valid = (param in fragmentData && (fragmentData[param] == 0 || fragmentData[param])); actionData[param] = valid ? fragmentData[param] : null; }); return /** @type {!Dispatcher.FragmentData} */ (actionData); } /** * Creates a URL event that makes a data request. */ makeDataRequest() { const fragmentData = this.parseFragment(); Dispatcher.getInstance().sendAction({ actionType: Dispatcher.ActionType.WINDOW_LOCATION_PENDING_REQUEST, data: fragmentData, }); } /** * Converts store chunk data into a fragment string and sets the fragment. * Also handles browser history state based on whether the file parameters in * the request have changed. * @param {!Store.StoreData} store Store chunk data to use to update fragment. * @param {!Array<!Store.Property>} changedProperties List of the properties * that changed because of the last action. */ handleRequestParams(store, changedProperties) { if (!store.chunkGraphData) { return; } const fileParamDirty = Store.FileRequestProperties.some( (param) => changedProperties.includes(param)); const assignments = Store.RequestProperties.map((param) => { const key = param.toLowerCase(); let value = store[param]; if (Store.FileRequestProperties.includes(param)) { value = value ? value : ''; } else if (Store.ListRequestProperties.includes(param)) { value = value ? value.join(',') : ''; } return `${key}=${value}`; }); const url = '#' + assignments.join('&'); if (fileParamDirty) { history.pushState({}, '', url); } else { history.replaceState({}, '', url); } } } goog.addSingletonGetter(WindowLocation); exports = WindowLocation;
{ "pile_set_name": "Github" }
/** * This file is part of alf.io. * * alf.io 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. * * alf.io 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 alf.io. If not, see <http://www.gnu.org/licenses/>. */ package alfio.repository; import alfio.model.ExtensionLog; import ch.digitalfondue.npjt.Bind; import ch.digitalfondue.npjt.Query; import ch.digitalfondue.npjt.QueryRepository; import java.util.List; @QueryRepository public interface ExtensionLogRepository { @Query("insert into extension_log(effective_path, path, name, description, type) values (:effectivePath, :path, :name, :description, :type)") int insert(@Bind("effectivePath") String effectivePath, @Bind("path") String path, @Bind("name") String name, @Bind("description") String description, @Bind("type") ExtensionLog.Type type); String FIND_EXTENSION_LOG = "select * from extension_log where ((:path is null or path = :path) and (:name is null or name = :name)) and (:type is null or type = :type) order by event_ts desc"; @Query("select count(*) from (" + FIND_EXTENSION_LOG + ") as el_tbl") int countPages(@Bind("path") String path, @Bind("name") String name, @Bind("type") String type); @Query("select * from (" + FIND_EXTENSION_LOG + " limit :pageSize offset :offset) as el_tbl") List<ExtensionLog> getPage(@Bind("path") String path, @Bind("name") String name, @Bind("type") String type, @Bind("pageSize") int pageSize, @Bind("offset") int offset); }
{ "pile_set_name": "Github" }
#!/bin/bash set -o xtrace # print commands during script execution sudo service vpp stop pci_search="Ethernet" pci_devs=($(lspci | grep "$pci_search" | awk '{print $1}' | grep -v "00:05.0")) dev_list="" if [ ! "${#pci_devs[@]}" == "0" ]; then for dev in ${pci_devs[@]}; do dev_list+="dev 0000:$dev " done fi sudo /vagrant/dpdk-devbind.py -b igb_uio ${pci_devs[@]} # Overwrite default VPP configuration sudo bash -c "cat > /etc/vpp/startup.conf" <<EOF unix { nodaemon log /var/log/vpp/vpp.log full-coredump cli-listen /run/vpp/cli.sock gid vpp startup-config /etc/vpp/setup.gate } api-trace { ## This stanza controls binary API tracing. Unless there is a very strong reason, ## please leave this feature enabled. on ## Additional parameters: ## ## To set the number of binary API trace records in the circular buffer, configure nitems ## ## nitems <nnn> ## ## To save the api message table decode tables, configure a filename. Results in /tmp/<filename> ## Very handy for understanding api message changes between versions, identifying missing ## plugins, and so forth. ## ## save-api-table <filename> } api-segment { gid vpp } cpu { ## In the VPP there is one main thread and optionally the user can create worker(s) ## The main thread and worker thread(s) can be pinned to CPU core(s) manually or automatically ## Manual pinning of thread(s) to CPU core(s) ## Set logical CPU core where main thread runs main-core 0 ## Set logical CPU core(s) where worker threads are running corelist-workers 1-2 ## Automatic pinning of thread(s) to CPU core(s) ## Sets number of CPU core(s) to be skipped (1 ... N-1) ## Skipped CPU core(s) are not used for pinning main thread and working thread(s). ## The main thread is automatically pinned to the first available CPU core and worker(s) ## are pinned to next free CPU core(s) after core assigned to main thread # skip-cores 4 ## Specify a number of workers to be created ## Workers are pinned to N consecutive CPU cores while skipping "skip-cores" CPU core(s) ## and main thread's CPU core # workers 2 ## Set scheduling policy and priority of main and worker threads ## Scheduling policy options are: other (SCHED_OTHER), batch (SCHED_BATCH) ## idle (SCHED_IDLE), fifo (SCHED_FIFO), rr (SCHED_RR) # scheduler-policy fifo ## Scheduling priority is used only for "real-time policies (fifo and rr), ## and has to be in the range of priorities supported for a particular policy # scheduler-priority 50 } dpdk { ## Change default settings for all intefaces dev default { ## Number of receive queues, enables RSS ## Default is 1 num-rx-queues 2 ## Number of transmit queues, Default is equal ## to number of worker threads or 1 if no workers treads # num-tx-queues 3 ## Number of descriptors in transmit and receive rings ## increasing or reducing number can impact performance ## Default is 1024 for both rx and tx num-rx-desc 512 num-tx-desc 512 ## VLAN strip offload mode for interface ## Default is off # vlan-strip-offload on } ## Whitelist specific interface by specifying PCI address ${dev_list} ## Whitelist specific interface by specifying PCI address and in ## addition specify custom parameters for this interface # dev 0000:02:00.1 { # num-rx-queues 2 # } ## Specify bonded interface and its slaves via PCI addresses ## ## Bonded interface in XOR load balance mode (mode 2) with L3 and L4 headers # vdev eth_bond0,mode=2,slave=0000:02:00.0,slave=0000:03:00.0,xmit_policy=l34 # vdev eth_bond1,mode=2,slave=0000:02:00.1,slave=0000:03:00.1,xmit_policy=l34 ## ## Bonded interface in Active-Back up mode (mode 1) # vdev eth_bond0,mode=1,slave=0000:02:00.0,slave=0000:03:00.0 # vdev eth_bond1,mode=1,slave=0000:02:00.1,slave=0000:03:00.1 ## Change UIO driver used by VPP, Options are: igb_uio, vfio-pci, ## uio_pci_generic or auto (default) # uio-driver vfio-pci ## Disable mutli-segment buffers, improves performance but ## disables Jumbo MTU support no-multi-seg ## Increase number of buffers allocated, needed only in scenarios with ## large number of interfaces and worker threads. Value is per CPU socket. ## Default is 16384 # num-mbufs 128000 ## Change hugepages allocation per-socket, needed only if there is need for ## larger number of mbufs. Default is 256M on each detected CPU socket # socket-mem 2048,2048 ## Disables UDP / TCP TX checksum offload. Typically needed for use ## faster vector PMDs (together with no-multi-seg) # no-tx-checksum-offload } # plugins { ## Adjusting the plugin path depending on where the VPP plugins are # path /home/bms/vpp/build-root/install-vpp-native/vpp/lib64/vpp_plugins ## Disable all plugins by default and then selectively enable specific plugins # plugin default { disable } # plugin dpdk_plugin.so { enable } # plugin acl_plugin.so { enable } ## Enable all plugins by default and then selectively disable specific plugins # plugin dpdk_plugin.so { disable } # plugin acl_plugin.so { disable } # } ## Alternate syntax to choose plugin path # plugin_path /home/bms/vpp/build-root/install-vpp-native/vpp/lib64/vpp_plugins EOF sudo service vpp start sleep 10 # Pre-heating the API so that the following works (workaround?) sudo vppctl show int intfs=($(sudo vppctl show int | grep Ethernet | awk '{print $1}')) if [ ! "${#intfs[@]}" == "2" ]; then echo "ERROR: Number of interfaces should be 2 (is ${#intfs[@]})" exit 1 fi # Create interface configuration for VPP sudo bash -c "cat > /etc/vpp/setup.gate" <<EOF set int state ${intfs[0]} up set interface ip address ${intfs[0]} 172.16.10.10/24 set int state ${intfs[1]} up set interface ip address ${intfs[1]} 172.16.20.10/24 set ip arp static ${intfs[0]} 172.16.10.100 8a:fd:d5:d5:d6:b6 set ip arp static ${intfs[1]} 172.16.20.100 06:9c:b3:cc:f0:62 ip route add 172.16.64.0/18 via 172.16.10.100 ip route add 172.16.192.0/18 via 172.16.20.100 EOF sudo service vpp restart
{ "pile_set_name": "Github" }
<?xml version='1.0' encoding='utf-8'?> <SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="ClearCanvas.Ris.Client.Workflow.Extended" GeneratedClassName="PreliminaryDiagnosisSettings"> <Profiles /> <Settings> <Setting Name="RadiologyTemplatesXml" Description="XML document that defines the templates available when accessed from Reporting." Type="System.String" Scope="Application"> <Value Profile="(Default)">PreliminaryDiagnosisFromRadiologyTemplates.xml</Value> </Setting> <Setting Name="EmergencyTemplatesXml" Description="XML document that defines the templates available when accessed from Emergency." Type="System.String" Scope="Application"> <Value Profile="(Default)">PreliminaryDiagnosisFromEmergencyTemplates.xml</Value> </Setting> <Setting Name="RadiologySoftKeysXml" Description="XML document that defines the soft-keys available when accessed from Reporting." Type="System.String" Scope="Application"> <Value Profile="(Default)">PreliminaryDiagnosisFromRadiologySoftKeys.xml</Value> </Setting> <Setting Name="EmergencySoftKeysXml" Description="XML document that defines the soft-keys available when accessed from Emergency." Type="System.String" Scope="Application"> <Value Profile="(Default)">PreliminaryDiagnosisFromEmergencySoftKeys.xml</Value> </Setting> <Setting Name="VerificationTemplatesXml" Description="XML document that defines the templates available when accessed during Verification." Type="System.String" Scope="Application"> <Value Profile="(Default)">PreliminaryDiagnosisFromVerificationTemplates.xml</Value> </Setting> <Setting Name="VerificationSoftKeysXml" Description="XML document that defines the soft-keys available when accessed during Verification." Type="System.String" Scope="Application"> <Value Profile="(Default)">PreliminaryDiagnosisFromVerificationSoftKeys.xml</Value> </Setting> <Setting Name="PreliminaryDiagnosisReviewForPatientClass" Type="System.String" Scope="Application"> <Value Profile="(Default)">E</Value> </Setting> </Settings> </SettingsFile>
{ "pile_set_name": "Github" }
/* * Copyright 2016 Azavea * * 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. */ package geotrellis.proj4 import org.locationtech.proj4j._ import org.locationtech.proj4j.util._ import java.io.File import org.scalatest.matchers.{ BeMatcher, MatchResult } import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers /** * Runs MetaCRS test files. * * @author mbdavis (port by Rob Emanuele) */ class MetaCRSTest extends AnyFunSuite with Matchers { val crsFactory = new CRSFactory test("MetaCRSExample") { val file = new File("src/test/resources/TestData.csv") val tests = MetaCRSTestFileReader.readTests(file) for (test <- tests) { test should be(passing) } } test("PROJ4_SPCS") { val file = new File("src/test/resources/PROJ4_SPCS_EPSG_nad83.csv") val tests = MetaCRSTestFileReader.readTests(file) for (test <- tests) { test should be(passing) } } // TODO: update this test, started failing with switch from EPSG Database 8.6 to 9.2 ignore("PROJ4_Empirical") { val file = new File("src/test/resources/proj4-epsg.csv") val tests = MetaCRSTestFileReader.readTests(file) for (test <- tests) { test.testMethod match { case "passing" => test should be(passing) case "failing" => test should not(be(passing)) case "error" => intercept[org.locationtech.proj4j.Proj4jException] { test.execute(crsFactory) } } } } } object passing extends BeMatcher[MetaCRSTestCase] { val crsFactory = new CRSFactory def apply(left: MetaCRSTestCase) = { import left._ val (success, x, y) = left.execute(crsFactory) MatchResult( success, f"$srcCrsAuth:$srcCrs→$tgtCrsAuth:$tgtCrs ($srcOrd1, $srcOrd2, $srcOrd3) → ($tgtOrd1, $tgtOrd2, $tgtOrd3); got ($x, $y)", f"$srcCrsAuth:$srcCrs→$tgtCrsAuth:$tgtCrs in tolerance") } } case class MetaCRSTestCase( testName: String, testMethod: String, srcCrsAuth: String, srcCrs: String, tgtCrsAuth: String, tgtCrs: String, srcOrd1: Double, srcOrd2: Double, srcOrd3: Double, tgtOrd1: Double, tgtOrd2: Double, tgtOrd3: Double, tolOrd1: Double, tolOrd2: Double, tolOrd3: Double, using: String, dataSource: String, dataCmnts: String, maintenanceCmnts: String ) { val verbose = true val srcPt = new ProjCoordinate() val resultPt = new ProjCoordinate() def sourceCrsName = csName(srcCrsAuth, srcCrs) def targetCrsName = csName(tgtCrsAuth, tgtCrs) def sourceCoordinate = new ProjCoordinate(srcOrd1, srcOrd2, srcOrd3) def targetCoordinate = new ProjCoordinate(tgtOrd1, tgtOrd2, tgtOrd3) def resultCoordinate = new ProjCoordinate(resultPt.x, resultPt.y) // public void setCache(CRSCache crsCache) // { // this.crsCache = crsCache // } def execute(csFactory: CRSFactory): (Boolean, Double, Double) = { val srcCS = createCS(csFactory, srcCrsAuth, srcCrs) val tgtCS = createCS(csFactory, tgtCrsAuth, tgtCrs) executeTransform(srcCS, tgtCS) } def csName(auth: String, code: String) = auth + ":" + code def createCS(csFactory: CRSFactory, auth: String, code: String) = { val name = csName(auth, code) csFactory.createFromName(name) } def executeTransform(srcCS: CoordinateReferenceSystem, tgtCS: CoordinateReferenceSystem): (Boolean, Double, Double) = { srcPt.x = srcOrd1 srcPt.y = srcOrd2 // Testing: flip axis order to test SS sample file //srcPt.x = srcOrd2 //srcPt.y = srcOrd1 val trans = new BasicCoordinateTransform(srcCS, tgtCS) trans.transform(srcPt, resultPt) val dx = math.abs(resultPt.x - tgtOrd1) val dy = math.abs(resultPt.y - tgtOrd2) // println(srcPt, resultPt, (tgtOrd1, tgtOrd2), (dx, dy), (tolOrd1, tolOrd2)) (dx <= tolOrd1 && dy <= tolOrd2, resultPt.x, resultPt.y) } def print(isInTol: Boolean, srcCS: CoordinateReferenceSystem, tgtCS: CoordinateReferenceSystem) = { System.out.println(testName) System.out.println(ProjectionUtil.toString(srcPt) + " -> " + ProjectionUtil.toString(resultPt) + " ( expected: " + tgtOrd1 + ", " + tgtOrd2 + " )" ) if (!isInTol) { System.out.println("FAIL") System.out.println("Src CRS: (" + srcCrsAuth + ":" + srcCrs + ") " + srcCS.getParameterString()) System.out.println("Tgt CRS: (" + tgtCrsAuth + ":" + tgtCrs + ") " + tgtCS.getParameterString()) } } }
{ "pile_set_name": "Github" }
/* * Copyright 2014 the original author or authors. * * 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. */ package org.gradle.language.twirl; import org.gradle.api.Incubating; import org.gradle.language.base.LanguageSourceSet; import java.util.List; /** * Represents a source set containing twirl templates * * <pre class='autoTested'> * plugins { * id 'play' * } * * model { * components { * play { * sources { * withType(TwirlSourceSet) { * // Use template format views.formats.csv.CsvFormat for all files named *.scala.csv * // Additionally, include views.formats.csv._ package imports in generated sources. * addUserTemplateFormat("csv", "views.formats.csv.CsvFormat", "views.formats.csv._") * // Add these additional imports to all generated Scala code from Twirl templates * additionalImports = [ 'my.pkg._', 'my.pkg.MyClass' ] * } * } * } * } * } * </pre> */ @Incubating @Deprecated public interface TwirlSourceSet extends LanguageSourceSet { /** * The default imports that should be added to generated source files */ TwirlImports getDefaultImports(); /** * Sets the default imports that should be added to generated source files to the given language */ void setDefaultImports(TwirlImports defaultImports); /** * Returns the custom template formats configured for this source set. * * @since 4.2 */ List<TwirlTemplateFormat> getUserTemplateFormats(); /** * Sets the custom template formats for this source set. * * @since 4.2 */ void setUserTemplateFormats(List<TwirlTemplateFormat> userTemplateFormats); /** * Adds a custom template format. * * @param extension file extension this template applies to (e.g., {@code html}). * @param templateType fully-qualified type for this template format. * @param imports additional imports to add for the custom template format. * * @since 4.2 */ void addUserTemplateFormat(final String extension, String templateType, String... imports); /** * Returns the list of additional imports to add to the generated Scala code. * * @since 4.2 */ List<String> getAdditionalImports(); /** * Sets the additional imports to add to all generated Scala code. * * @param additionalImports additional imports * * @since 4.2 */ void setAdditionalImports(List<String> additionalImports); }
{ "pile_set_name": "Github" }
/* * 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. */ package com.aliyuncs.arms.model.v20190808; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.arms.Endpoint; /** * @author auto create * @version */ public class DeleteAlertContactGroupRequest extends RpcAcsRequest<DeleteAlertContactGroupResponse> { private Long contactGroupId; public DeleteAlertContactGroupRequest() { super("ARMS", "2019-08-08", "DeleteAlertContactGroup", "arms"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public Long getContactGroupId() { return this.contactGroupId; } public void setContactGroupId(Long contactGroupId) { this.contactGroupId = contactGroupId; if(contactGroupId != null){ putQueryParameter("ContactGroupId", contactGroupId.toString()); } } @Override public Class<DeleteAlertContactGroupResponse> getResponseClass() { return DeleteAlertContactGroupResponse.class; } }
{ "pile_set_name": "Github" }
/* ### * IP: GHIDRA * * 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. */ package ghidra.app.util.bin.format.pdb2.pdbreader.symbol; import ghidra.app.util.bin.format.pdb2.pdbreader.*; /** * This class represents the <B>MsSymbol</B> flavor of Using Namespace symbol. * <P> * Note: we do not necessarily understand each of these symbol type classes. Refer to the * base class for more information. */ public class UsingNamespaceMsSymbol extends AbstractUsingNamespaceMsSymbol { public static final int PDB_ID = 0x1124; /** * Constructor for this symbol. * @param pdb {@link AbstractPdb} to which this symbol belongs. * @param reader {@link PdbByteReader} from which this symbol is deserialized. * @throws PdbException upon error parsing a field. */ public UsingNamespaceMsSymbol(AbstractPdb pdb, PdbByteReader reader) throws PdbException { super(pdb, reader, StringParseType.StringUtf8Nt); } @Override public int getPdbId() { return PDB_ID; } @Override public void emit(StringBuilder builder) { builder.append(String.format("%s: %s", getSymbolTypeName(), name)); } @Override protected String getSymbolTypeName() { return "UNAMESPACE"; } }
{ "pile_set_name": "Github" }
#include "kjtableview.h" KJTableView::KJTableView(QObject *parent) : QTableView(parent) { }
{ "pile_set_name": "Github" }
/* ========================================================================== */ /* === Include/cholmod.h ==================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod.h. * Copyright (C) 2005-2006, Univ. of Florida. Author: Timothy A. Davis * CHOLMOD/Include/cholmod.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.cise.ufl.edu/research/sparse * * Portions of CHOLMOD (the Core and Partition Modules) are copyrighted by the * University of Florida. The Modify Module is co-authored by William W. * Hager, Univ. of Florida. * * Acknowledgements: this work was supported in part by the National Science * Foundation (NFS CCR-0203270 and DMS-9803599), and a grant from Sandia * National Laboratories (Dept. of Energy) which supported the development of * CHOLMOD's Partition Module. * -------------------------------------------------------------------------- */ /* CHOLMOD include file, for inclusion user programs. * * The include files listed below include a short description of each user- * callable routine. Each routine in CHOLMOD has a consistent interface. * More details about the CHOLMOD data types is in the cholmod_core.h file. * * Naming convention: * ------------------ * * All routine names, data types, and CHOLMOD library files use the * cholmod_ prefix. All macros and other #define's use the CHOLMOD * prefix. * * Return value: * ------------- * * Most CHOLMOD routines return an int (TRUE (1) if successful, or FALSE * (0) otherwise. A UF_long or double return value is >= 0 if successful, * or -1 otherwise. A size_t return value is > 0 if successful, or 0 * otherwise. * * If a routine returns a pointer, it is a pointer to a newly allocated * object or NULL if a failure occured, with one exception. cholmod_free * always returns NULL. * * "Common" parameter: * ------------------ * * The last parameter in all CHOLMOD routines is a pointer to the CHOLMOD * "Common" object. This contains control parameters, statistics, and * workspace used between calls to CHOLMOD. It is always an input/output * parameter. * * Input, Output, and Input/Output parameters: * ------------------------------------------- * * Input parameters are listed first. They are not modified by CHOLMOD. * * Input/output are listed next. They must be defined on input, and * are modified on output. * * Output parameters are listed next. If they are pointers, they must * point to allocated space on input, but their contents are not defined * on input. * * Workspace parameters appear next. They are used in only two routines * in the Supernodal module. * * The cholmod_common *Common parameter always appears as the last * parameter. It is always an input/output parameter. */ #ifndef CHOLMOD_H #define CHOLMOD_H /* make it easy for C++ programs to include CHOLMOD */ #ifdef __cplusplus extern "C" { #endif /* assume large file support. If problems occur, compile with -DNLARGEFILE */ #include "cholmod_io64.h" /* define UF_long */ #include "UFconfig.h" #include "cholmod_config.h" /* CHOLMOD always includes the Core module. */ #include "cholmod_core.h" #ifndef NCHECK #include "cholmod_check.h" #endif #ifndef NCHOLESKY #include "cholmod_cholesky.h" #endif #ifndef NMATRIXOPS #include "cholmod_matrixops.h" #endif #ifndef NMODIFY #include "cholmod_modify.h" #endif #ifndef NPARTITION #include "cholmod_partition.h" #endif #ifndef NSUPERNODAL #include "cholmod_supernodal.h" #endif #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
import datetime import StringIO import sys from django.conf import settings from django.core.mail import mail_managers, mail_admins from django.template.loader import render_to_string from django.contrib.sites.models import Site from twill.parse import execute_string from twill.errors import TwillAssertionError def _send_error(kong_site, test, content): real_site = Site.objects.get_current() message = render_to_string('kong/failed_email.txt', {'kong_site': kong_site, 'test': test, 'error': content, 'real_site': real_site}) if getattr(settings, 'KONG_MAIL_MANAGERS', False): mail_managers('Kong Test Failed: %s (%s)' % (test, kong_site), message) if getattr(settings, 'KONG_MAIL_ADMINS', False): mail_admins('Kong Test Failed: %s (%s)' % (test, kong_site), message) def _send_recovery(kong_site, test, content): real_site = Site.objects.get_current() message = render_to_string( 'kong/recovered_email.txt', { 'kong_site': kong_site, 'test': test, 'content': content, 'real_site': real_site } ) if getattr(settings, 'KONG_MAIL_MANAGERS', False): mail_managers('Kong Test Recovered: %s (%s)' % (test, kong_site), message) if getattr(settings, 'KONG_MAIL_ADMINS', False): mail_admins('Kong Test Recovered: %s (%s)' % (test, kong_site), message) def execute_test(site, test): import twill.commands as commands #Avoid circular import from kong.models import TestResult twill_script = test.render(site) content = '' old_err = sys.stderr new_err = StringIO.StringIO() commands.ERR = new_err now = datetime.datetime.now() try: if getattr(settings, 'KONG_RESET_BROWSER', False): execute_string(twill_script, no_reset = False) else: execute_string(twill_script) succeeded = True content = new_err.getvalue().strip() except Exception, e: succeeded = False content = new_err.getvalue().strip() + "\n\nException:\n\n" + str(e) end = datetime.datetime.now() duration = end - now duration = duration.microseconds commands.ERR = old_err result = TestResult.objects.create(site=site, test=test, succeeded=succeeded, duration=duration, content=content) if result.notification_needed and result.failed: _send_error(site, test, content) if result.notification_needed and result.succeeded: _send_recovery(site, test, content) return succeeded
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); /** * This file is part of Hyperf. * * @link https://www.hyperf.io * @document https://hyperf.wiki * @contact group@hyperf.io * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ namespace Hyperf\Process; use Hyperf\Process\Listener\BootProcessListener; use Hyperf\Process\Listener\LogAfterProcessStoppedListener; use Hyperf\Process\Listener\LogBeforeProcessStartListener; class ConfigProvider { public function __invoke(): array { return [ 'listeners' => [ BootProcessListener::class, LogAfterProcessStoppedListener::class, LogBeforeProcessStartListener::class, ], 'annotations' => [ 'scan' => [ 'paths' => [ __DIR__, ], ], ], ]; } }
{ "pile_set_name": "Github" }
source 'https://rubygems.org' gemspec gem "therubyracer", ">= 0.10.1", :require => nil, :platforms => :ruby gem "therubyrhino", ">= 1.73.2", :require => nil, :platforms => :jruby
{ "pile_set_name": "Github" }
=pod =head1 NAME DSA_sign, DSA_sign_setup, DSA_verify - DSA signatures =head1 SYNOPSIS #include <openssl/dsa.h> int DSA_sign(int type, const unsigned char *dgst, int len, unsigned char *sigret, unsigned int *siglen, DSA *dsa); int DSA_sign_setup(DSA *dsa, BN_CTX *ctx, BIGNUM **kinvp, BIGNUM **rp); int DSA_verify(int type, const unsigned char *dgst, int len, unsigned char *sigbuf, int siglen, DSA *dsa); =head1 DESCRIPTION DSA_sign() computes a digital signature on the B<len> byte message digest B<dgst> using the private key B<dsa> and places its ASN.1 DER encoding at B<sigret>. The length of the signature is places in *B<siglen>. B<sigret> must point to DSA_size(B<dsa>) bytes of memory. DSA_sign_setup() may be used to precompute part of the signing operation in case signature generation is time-critical. It expects B<dsa> to contain DSA parameters. It places the precomputed values in newly allocated B<BIGNUM>s at *B<kinvp> and *B<rp>, after freeing the old ones unless *B<kinvp> and *B<rp> are NULL. These values may be passed to DSA_sign() in B<dsa-E<gt>kinv> and B<dsa-E<gt>r>. B<ctx> is a pre-allocated B<BN_CTX> or NULL. DSA_verify() verifies that the signature B<sigbuf> of size B<siglen> matches a given message digest B<dgst> of size B<len>. B<dsa> is the signer's public key. The B<type> parameter is ignored. The PRNG must be seeded before DSA_sign() (or DSA_sign_setup()) is called. =head1 RETURN VALUES DSA_sign() and DSA_sign_setup() return 1 on success, 0 on error. DSA_verify() returns 1 for a valid signature, 0 for an incorrect signature and -1 on error. The error codes can be obtained by L<ERR_get_error(3)|ERR_get_error(3)>. =head1 CONFORMING TO US Federal Information Processing Standard FIPS 186 (Digital Signature Standard, DSS), ANSI X9.30 =head1 SEE ALSO L<dsa(3)|dsa(3)>, L<ERR_get_error(3)|ERR_get_error(3)>, L<rand(3)|rand(3)>, L<DSA_do_sign(3)|DSA_do_sign(3)> =head1 HISTORY DSA_sign() and DSA_verify() are available in all versions of SSLeay. DSA_sign_setup() was added in SSLeay 0.8. =cut
{ "pile_set_name": "Github" }
/****************************************************************************** * netif.h * * Unified network-device I/O interface for Xen guest OSes. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Copyright (c) 2003-2004, Keir Fraser */ #ifndef __XEN_PUBLIC_IO_NETIF_H__ #define __XEN_PUBLIC_IO_NETIF_H__ #include "ring.h" #include "../grant_table.h" /* * Older implementation of Xen network frontend / backend has an * implicit dependency on the MAX_SKB_FRAGS as the maximum number of * ring slots a skb can use. Netfront / netback may not work as * expected when frontend and backend have different MAX_SKB_FRAGS. * * A better approach is to add mechanism for netfront / netback to * negotiate this value. However we cannot fix all possible * frontends, so we need to define a value which states the minimum * slots backend must support. * * The minimum value derives from older Linux kernel's MAX_SKB_FRAGS * (18), which is proved to work with most frontends. Any new backend * which doesn't negotiate with frontend should expect frontend to * send a valid packet using slots up to this value. */ #define XEN_NETIF_NR_SLOTS_MIN 18 /* * Notifications after enqueuing any type of message should be conditional on * the appropriate req_event or rsp_event field in the shared ring. * If the client sends notification for rx requests then it should specify * feature 'feature-rx-notify' via xenbus. Otherwise the backend will assume * that it cannot safely queue packets (as it may not be kicked to send them). */ /* * "feature-split-event-channels" is introduced to separate guest TX * and RX notification. Backend either doesn't support this feature or * advertises it via xenstore as 0 (disabled) or 1 (enabled). * * To make use of this feature, frontend should allocate two event * channels for TX and RX, advertise them to backend as * "event-channel-tx" and "event-channel-rx" respectively. If frontend * doesn't want to use this feature, it just writes "event-channel" * node as before. */ /* * Multiple transmit and receive queues: * If supported, the backend will write the key "multi-queue-max-queues" to * the directory for that vif, and set its value to the maximum supported * number of queues. * Frontends that are aware of this feature and wish to use it can write the * key "multi-queue-num-queues", set to the number they wish to use, which * must be greater than zero, and no more than the value reported by the backend * in "multi-queue-max-queues". * * Queues replicate the shared rings and event channels. * "feature-split-event-channels" may optionally be used when using * multiple queues, but is not mandatory. * * Each queue consists of one shared ring pair, i.e. there must be the same * number of tx and rx rings. * * For frontends requesting just one queue, the usual event-channel and * ring-ref keys are written as before, simplifying the backend processing * to avoid distinguishing between a frontend that doesn't understand the * multi-queue feature, and one that does, but requested only one queue. * * Frontends requesting two or more queues must not write the toplevel * event-channel (or event-channel-{tx,rx}) and {tx,rx}-ring-ref keys, * instead writing those keys under sub-keys having the name "queue-N" where * N is the integer ID of the queue for which those keys belong. Queues * are indexed from zero. For example, a frontend with two queues and split * event channels must write the following set of queue-related keys: * * /local/domain/1/device/vif/0/multi-queue-num-queues = "2" * /local/domain/1/device/vif/0/queue-0 = "" * /local/domain/1/device/vif/0/queue-0/tx-ring-ref = "<ring-ref-tx0>" * /local/domain/1/device/vif/0/queue-0/rx-ring-ref = "<ring-ref-rx0>" * /local/domain/1/device/vif/0/queue-0/event-channel-tx = "<evtchn-tx0>" * /local/domain/1/device/vif/0/queue-0/event-channel-rx = "<evtchn-rx0>" * /local/domain/1/device/vif/0/queue-1 = "" * /local/domain/1/device/vif/0/queue-1/tx-ring-ref = "<ring-ref-tx1>" * /local/domain/1/device/vif/0/queue-1/rx-ring-ref = "<ring-ref-rx1" * /local/domain/1/device/vif/0/queue-1/event-channel-tx = "<evtchn-tx1>" * /local/domain/1/device/vif/0/queue-1/event-channel-rx = "<evtchn-rx1>" * * If there is any inconsistency in the XenStore data, the backend may * choose not to connect any queues, instead treating the request as an * error. This includes scenarios where more (or fewer) queues were * requested than the frontend provided details for. * * Mapping of packets to queues is considered to be a function of the * transmitting system (backend or frontend) and is not negotiated * between the two. Guests are free to transmit packets on any queue * they choose, provided it has been set up correctly. Guests must be * prepared to receive packets on any queue they have requested be set up. */ /* * "feature-no-csum-offload" should be used to turn IPv4 TCP/UDP checksum * offload off or on. If it is missing then the feature is assumed to be on. * "feature-ipv6-csum-offload" should be used to turn IPv6 TCP/UDP checksum * offload on or off. If it is missing then the feature is assumed to be off. */ /* * "feature-gso-tcpv4" and "feature-gso-tcpv6" advertise the capability to * handle large TCP packets (in IPv4 or IPv6 form respectively). Neither * frontends nor backends are assumed to be capable unless the flags are * present. */ /* * "feature-multicast-control" and "feature-dynamic-multicast-control" * advertise the capability to filter ethernet multicast packets in the * backend. If the frontend wishes to take advantage of this feature then * it may set "request-multicast-control". If the backend only advertises * "feature-multicast-control" then "request-multicast-control" must be set * before the frontend moves into the connected state. The backend will * sample the value on this state transition and any subsequent change in * value will have no effect. However, if the backend also advertises * "feature-dynamic-multicast-control" then "request-multicast-control" * may be set by the frontend at any time. In this case, the backend will * watch the value and re-sample on watch events. * * If the sampled value of "request-multicast-control" is set then the * backend transmit side should no longer flood multicast packets to the * frontend, it should instead drop any multicast packet that does not * match in a filter list. * The list is amended by the frontend by sending dummy transmit requests * containing XEN_NETIF_EXTRA_TYPE_MCAST_{ADD,DEL} extra-info fragments as * specified below. * Note that the filter list may be amended even if the sampled value of * "request-multicast-control" is not set, however the filter should only * be applied if it is set. */ /* * Control ring * ============ * * Some features, such as hashing (detailed below), require a * significant amount of out-of-band data to be passed from frontend to * backend. Use of xenstore is not suitable for large quantities of data * because of quota limitations and so a dedicated 'control ring' is used. * The ability of the backend to use a control ring is advertised by * setting: * * /local/domain/X/backend/<domid>/<vif>/feature-ctrl-ring = "1" * * The frontend provides a control ring to the backend by setting: * * /local/domain/<domid>/device/vif/<vif>/ctrl-ring-ref = <gref> * /local/domain/<domid>/device/vif/<vif>/event-channel-ctrl = <port> * * where <gref> is the grant reference of the shared page used to * implement the control ring and <port> is an event channel to be used * as a mailbox interrupt. These keys must be set before the frontend * moves into the connected state. * * The control ring uses a fixed request/response message size and is * balanced (i.e. one request to one response), so operationally it is much * the same as a transmit or receive ring. * Note that there is no requirement that responses are issued in the same * order as requests. */ /* * Hash types * ========== * * For the purposes of the definitions below, 'Packet[]' is an array of * octets containing an IP packet without options, 'Array[X..Y]' means a * sub-array of 'Array' containing bytes X thru Y inclusive, and '+' is * used to indicate concatenation of arrays. */ /* * A hash calculated over an IP version 4 header as follows: * * Buffer[0..8] = Packet[12..15] (source address) + * Packet[16..19] (destination address) * * Result = Hash(Buffer, 8) */ #define _XEN_NETIF_CTRL_HASH_TYPE_IPV4 0 #define XEN_NETIF_CTRL_HASH_TYPE_IPV4 \ (1 << _XEN_NETIF_CTRL_HASH_TYPE_IPV4) /* * A hash calculated over an IP version 4 header and TCP header as * follows: * * Buffer[0..12] = Packet[12..15] (source address) + * Packet[16..19] (destination address) + * Packet[20..21] (source port) + * Packet[22..23] (destination port) * * Result = Hash(Buffer, 12) */ #define _XEN_NETIF_CTRL_HASH_TYPE_IPV4_TCP 1 #define XEN_NETIF_CTRL_HASH_TYPE_IPV4_TCP \ (1 << _XEN_NETIF_CTRL_HASH_TYPE_IPV4_TCP) /* * A hash calculated over an IP version 6 header as follows: * * Buffer[0..32] = Packet[8..23] (source address ) + * Packet[24..39] (destination address) * * Result = Hash(Buffer, 32) */ #define _XEN_NETIF_CTRL_HASH_TYPE_IPV6 2 #define XEN_NETIF_CTRL_HASH_TYPE_IPV6 \ (1 << _XEN_NETIF_CTRL_HASH_TYPE_IPV6) /* * A hash calculated over an IP version 6 header and TCP header as * follows: * * Buffer[0..36] = Packet[8..23] (source address) + * Packet[24..39] (destination address) + * Packet[40..41] (source port) + * Packet[42..43] (destination port) * * Result = Hash(Buffer, 36) */ #define _XEN_NETIF_CTRL_HASH_TYPE_IPV6_TCP 3 #define XEN_NETIF_CTRL_HASH_TYPE_IPV6_TCP \ (1 << _XEN_NETIF_CTRL_HASH_TYPE_IPV6_TCP) /* * Hash algorithms * =============== */ #define XEN_NETIF_CTRL_HASH_ALGORITHM_NONE 0 /* * Toeplitz hash: */ #define XEN_NETIF_CTRL_HASH_ALGORITHM_TOEPLITZ 1 /* * Control requests (struct xen_netif_ctrl_request) * ================================================ * * All requests have the following format: * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * | id | type | data[0] | * +-----+-----+-----+-----+-----+-----+-----+-----+ * | data[1] | data[2] | * +-----+-----+-----+-----+-----------------------+ * * id: the request identifier, echoed in response. * type: the type of request (see below) * data[]: any data associated with the request (determined by type) */ struct xen_netif_ctrl_request { uint16_t id; uint16_t type; #define XEN_NETIF_CTRL_TYPE_INVALID 0 #define XEN_NETIF_CTRL_TYPE_GET_HASH_FLAGS 1 #define XEN_NETIF_CTRL_TYPE_SET_HASH_FLAGS 2 #define XEN_NETIF_CTRL_TYPE_SET_HASH_KEY 3 #define XEN_NETIF_CTRL_TYPE_GET_HASH_MAPPING_SIZE 4 #define XEN_NETIF_CTRL_TYPE_SET_HASH_MAPPING_SIZE 5 #define XEN_NETIF_CTRL_TYPE_SET_HASH_MAPPING 6 #define XEN_NETIF_CTRL_TYPE_SET_HASH_ALGORITHM 7 #define XEN_NETIF_CTRL_TYPE_GET_GREF_MAPPING_SIZE 8 #define XEN_NETIF_CTRL_TYPE_ADD_GREF_MAPPING 9 #define XEN_NETIF_CTRL_TYPE_DEL_GREF_MAPPING 10 uint32_t data[3]; }; /* * Control responses (struct xen_netif_ctrl_response) * ================================================== * * All responses have the following format: * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * | id | type | status | * +-----+-----+-----+-----+-----+-----+-----+-----+ * | data | * +-----+-----+-----+-----+ * * id: the corresponding request identifier * type: the type of the corresponding request * status: the status of request processing * data: any data associated with the response (determined by type and * status) */ struct xen_netif_ctrl_response { uint16_t id; uint16_t type; uint32_t status; #define XEN_NETIF_CTRL_STATUS_SUCCESS 0 #define XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED 1 #define XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER 2 #define XEN_NETIF_CTRL_STATUS_BUFFER_OVERFLOW 3 uint32_t data; }; /* * Static Grants (struct xen_netif_gref) * ===================================== * * A frontend may provide a fixed set of grant references to be mapped on * the backend. The message of type XEN_NETIF_CTRL_TYPE_ADD_GREF_MAPPING * prior its usage in the command ring allows for creation of these mappings. * The backend will maintain a fixed amount of these mappings. * * XEN_NETIF_CTRL_TYPE_GET_GREF_MAPPING_SIZE lets a frontend query how many * of these mappings can be kept. * * Each entry in the XEN_NETIF_CTRL_TYPE_{ADD,DEL}_GREF_MAPPING input table has * the following format: * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * | grant ref | flags | status | * +-----+-----+-----+-----+-----+-----+-----+-----+ * * grant ref: grant reference (IN) * flags: flags describing the control operation (IN) * status: XEN_NETIF_CTRL_STATUS_* (OUT) * * 'status' is an output parameter which does not require to be set to zero * prior to its usage in the corresponding control messages. */ struct xen_netif_gref { grant_ref_t ref; uint16_t flags; #define _XEN_NETIF_CTRLF_GREF_readonly 0 #define XEN_NETIF_CTRLF_GREF_readonly (1U<<_XEN_NETIF_CTRLF_GREF_readonly) uint16_t status; }; /* * Control messages * ================ * * XEN_NETIF_CTRL_TYPE_SET_HASH_ALGORITHM * -------------------------------------- * * This is sent by the frontend to set the desired hash algorithm. * * Request: * * type = XEN_NETIF_CTRL_TYPE_SET_HASH_ALGORITHM * data[0] = a XEN_NETIF_CTRL_HASH_ALGORITHM_* value * data[1] = 0 * data[2] = 0 * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not * supported * XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER - The algorithm is not * supported * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * * NOTE: Setting data[0] to XEN_NETIF_CTRL_HASH_ALGORITHM_NONE disables * hashing and the backend is free to choose how it steers packets * to queues (which is the default behaviour). * * XEN_NETIF_CTRL_TYPE_GET_HASH_FLAGS * ---------------------------------- * * This is sent by the frontend to query the types of hash supported by * the backend. * * Request: * * type = XEN_NETIF_CTRL_TYPE_GET_HASH_FLAGS * data[0] = 0 * data[1] = 0 * data[2] = 0 * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not supported * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * data = supported hash types (if operation was successful) * * NOTE: A valid hash algorithm must be selected before this operation can * succeed. * * XEN_NETIF_CTRL_TYPE_SET_HASH_FLAGS * ---------------------------------- * * This is sent by the frontend to set the types of hash that the backend * should calculate. (See above for hash type definitions). * Note that the 'maximal' type of hash should always be chosen. For * example, if the frontend sets both IPV4 and IPV4_TCP hash types then * the latter hash type should be calculated for any TCP packet and the * former only calculated for non-TCP packets. * * Request: * * type = XEN_NETIF_CTRL_TYPE_SET_HASH_FLAGS * data[0] = bitwise OR of XEN_NETIF_CTRL_HASH_TYPE_* values * data[1] = 0 * data[2] = 0 * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not * supported * XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER - One or more flag * value is invalid or * unsupported * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * data = 0 * * NOTE: A valid hash algorithm must be selected before this operation can * succeed. * Also, setting data[0] to zero disables hashing and the backend * is free to choose how it steers packets to queues. * * XEN_NETIF_CTRL_TYPE_SET_HASH_KEY * -------------------------------- * * This is sent by the frontend to set the key of the hash if the algorithm * requires it. (See hash algorithms above). * * Request: * * type = XEN_NETIF_CTRL_TYPE_SET_HASH_KEY * data[0] = grant reference of page containing the key (assumed to * start at beginning of grant) * data[1] = size of key in octets * data[2] = 0 * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not * supported * XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER - Key size is invalid * XEN_NETIF_CTRL_STATUS_BUFFER_OVERFLOW - Key size is larger * than the backend * supports * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * data = 0 * * NOTE: Any key octets not specified are assumed to be zero (the key * is assumed to be empty by default) and specifying a new key * invalidates any previous key, hence specifying a key size of * zero will clear the key (which ensures that the calculated hash * will always be zero). * The maximum size of key is algorithm and backend specific, but * is also limited by the single grant reference. * The grant reference may be read-only and must remain valid until * the response has been processed. * * XEN_NETIF_CTRL_TYPE_GET_HASH_MAPPING_SIZE * ----------------------------------------- * * This is sent by the frontend to query the maximum size of mapping * table supported by the backend. The size is specified in terms of * table entries. * * Request: * * type = XEN_NETIF_CTRL_TYPE_GET_HASH_MAPPING_SIZE * data[0] = 0 * data[1] = 0 * data[2] = 0 * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not supported * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * data = maximum number of entries allowed in the mapping table * (if operation was successful) or zero if a mapping table is * not supported (i.e. hash mapping is done only by modular * arithmetic). * * XEN_NETIF_CTRL_TYPE_SET_HASH_MAPPING_SIZE * ------------------------------------- * * This is sent by the frontend to set the actual size of the mapping * table to be used by the backend. The size is specified in terms of * table entries. * Any previous table is invalidated by this message and any new table * is assumed to be zero filled. * * Request: * * type = XEN_NETIF_CTRL_TYPE_SET_HASH_MAPPING_SIZE * data[0] = number of entries in mapping table * data[1] = 0 * data[2] = 0 * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not * supported * XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER - Table size is invalid * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * data = 0 * * NOTE: Setting data[0] to 0 means that hash mapping should be done * using modular arithmetic. * * XEN_NETIF_CTRL_TYPE_SET_HASH_MAPPING * ------------------------------------ * * This is sent by the frontend to set the content of the table mapping * hash value to queue number. The backend should calculate the hash from * the packet header, use it as an index into the table (modulo the size * of the table) and then steer the packet to the queue number found at * that index. * * Request: * * type = XEN_NETIF_CTRL_TYPE_SET_HASH_MAPPING * data[0] = grant reference of page containing the mapping (sub-)table * (assumed to start at beginning of grant) * data[1] = size of (sub-)table in entries * data[2] = offset, in entries, of sub-table within overall table * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not * supported * XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER - Table size or content * is invalid * XEN_NETIF_CTRL_STATUS_BUFFER_OVERFLOW - Table size is larger * than the backend * supports * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * data = 0 * * NOTE: The overall table has the following format: * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * | mapping[0] | mapping[1] | * +-----+-----+-----+-----+-----+-----+-----+-----+ * | . | * | . | * | . | * +-----+-----+-----+-----+-----+-----+-----+-----+ * | mapping[N-2] | mapping[N-1] | * +-----+-----+-----+-----+-----+-----+-----+-----+ * * where N is specified by a XEN_NETIF_CTRL_TYPE_SET_HASH_MAPPING_SIZE * message and each mapping must specifies a queue between 0 and * "multi-queue-num-queues" (see above). * The backend may support a mapping table larger than can be * mapped by a single grant reference. Thus sub-tables within a * larger table can be individually set by sending multiple messages * with differing offset values. Specifying a new sub-table does not * invalidate any table data outside that range. * The grant reference may be read-only and must remain valid until * the response has been processed. * * XEN_NETIF_CTRL_TYPE_GET_GREF_MAPPING_SIZE * ----------------------------------------- * * This is sent by the frontend to fetch the number of grefs that can be kept * mapped in the backend. * * Request: * * type = XEN_NETIF_CTRL_TYPE_GET_GREF_MAPPING_SIZE * data[0] = queue index (assumed 0 for single queue) * data[1] = 0 * data[2] = 0 * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not * supported * XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER - The queue index is * out of range * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * data = maximum number of entries allowed in the gref mapping table * (if operation was successful) or zero if it is not supported. * * XEN_NETIF_CTRL_TYPE_ADD_GREF_MAPPING * ------------------------------------ * * This is sent by the frontend for backend to map a list of grant * references. * * Request: * * type = XEN_NETIF_CTRL_TYPE_ADD_GREF_MAPPING * data[0] = queue index * data[1] = grant reference of page containing the mapping list * (r/w and assumed to start at beginning of page) * data[2] = size of list in entries * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not * supported * XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER - Operation failed * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * * NOTE: Each entry in the input table has the format outlined * in struct xen_netif_gref. * Contrary to XEN_NETIF_CTRL_TYPE_DEL_GREF_MAPPING, the struct * xen_netif_gref 'status' field is not used and therefore the response * 'status' determines the success of this operation. In case of * failure none of grants mappings get added in the backend. * * XEN_NETIF_CTRL_TYPE_DEL_GREF_MAPPING * ------------------------------------ * * This is sent by the frontend for backend to unmap a list of grant * references. * * Request: * * type = XEN_NETIF_CTRL_TYPE_DEL_GREF_MAPPING * data[0] = queue index * data[1] = grant reference of page containing the mapping list * (r/w and assumed to start at beginning of page) * data[2] = size of list in entries * * Response: * * status = XEN_NETIF_CTRL_STATUS_NOT_SUPPORTED - Operation not * supported * XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER - Operation failed * XEN_NETIF_CTRL_STATUS_SUCCESS - Operation successful * data = number of entries that were unmapped * * NOTE: Each entry in the input table has the format outlined in struct * xen_netif_gref. * The struct xen_netif_gref 'status' field determines if the entry * was successfully removed. * The entries used are only the ones representing grant references that * were previously the subject of a XEN_NETIF_CTRL_TYPE_ADD_GREF_MAPPING * operation. Any other entries will have their status set to * XEN_NETIF_CTRL_STATUS_INVALID_PARAMETER upon completion. */ DEFINE_RING_TYPES(xen_netif_ctrl, struct xen_netif_ctrl_request, struct xen_netif_ctrl_response); /* * Guest transmit * ============== * * This is the 'wire' format for transmit (frontend -> backend) packets: * * Fragment 1: netif_tx_request_t - flags = NETTXF_* * size = total packet size * [Extra 1: netif_extra_info_t] - (only if fragment 1 flags include * NETTXF_extra_info) * ... * [Extra N: netif_extra_info_t] - (only if extra N-1 flags include * XEN_NETIF_EXTRA_MORE) * ... * Fragment N: netif_tx_request_t - (only if fragment N-1 flags include * NETTXF_more_data - flags on preceding * extras are not relevant here) * flags = 0 * size = fragment size * * NOTE: * * This format slightly is different from that used for receive * (backend -> frontend) packets. Specifically, in a multi-fragment * packet the actual size of fragment 1 can only be determined by * subtracting the sizes of fragments 2..N from the total packet size. * * Ring slot size is 12 octets, however not all request/response * structs use the full size. * * tx request data (netif_tx_request_t) * ------------------------------------ * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * | grant ref | offset | flags | * +-----+-----+-----+-----+-----+-----+-----+-----+ * | id | size | * +-----+-----+-----+-----+ * * grant ref: Reference to buffer page. * offset: Offset within buffer page. * flags: NETTXF_*. * id: request identifier, echoed in response. * size: packet size in bytes. * * tx response (netif_tx_response_t) * --------------------------------- * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * | id | status | unused | * +-----+-----+-----+-----+-----+-----+-----+-----+ * | unused | * +-----+-----+-----+-----+ * * id: reflects id in transmit request * status: NETIF_RSP_* * * Guest receive * ============= * * This is the 'wire' format for receive (backend -> frontend) packets: * * Fragment 1: netif_rx_request_t - flags = NETRXF_* * size = fragment size * [Extra 1: netif_extra_info_t] - (only if fragment 1 flags include * NETRXF_extra_info) * ... * [Extra N: netif_extra_info_t] - (only if extra N-1 flags include * XEN_NETIF_EXTRA_MORE) * ... * Fragment N: netif_rx_request_t - (only if fragment N-1 flags include * NETRXF_more_data - flags on preceding * extras are not relevant here) * flags = 0 * size = fragment size * * NOTE: * * This format slightly is different from that used for transmit * (frontend -> backend) packets. Specifically, in a multi-fragment * packet the size of the packet can only be determined by summing the * sizes of fragments 1..N. * * Ring slot size is 8 octets. * * rx request (netif_rx_request_t) * ------------------------------- * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * | id | pad | gref | * +-----+-----+-----+-----+-----+-----+-----+-----+ * * id: request identifier, echoed in response. * gref: reference to incoming granted frame. * * rx response (netif_rx_response_t) * --------------------------------- * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * | id | offset | flags | status | * +-----+-----+-----+-----+-----+-----+-----+-----+ * * id: reflects id in receive request * offset: offset in page of start of received packet * flags: NETRXF_* * status: -ve: NETIF_RSP_*; +ve: Rx'ed pkt size. * * NOTE: Historically, to support GSO on the frontend receive side, Linux * netfront does not make use of the rx response id (because, as * described below, extra info structures overlay the id field). * Instead it assumes that responses always appear in the same ring * slot as their corresponding request. Thus, to maintain * compatibility, backends must make sure this is the case. * * Extra Info * ========== * * Can be present if initial request or response has NET{T,R}XF_extra_info, * or previous extra request has XEN_NETIF_EXTRA_MORE. * * The struct therefore needs to fit into either a tx or rx slot and * is therefore limited to 8 octets. * * NOTE: Because extra info data overlays the usual request/response * structures, there is no id information in the opposite direction. * So, if an extra info overlays an rx response the frontend can * assume that it is in the same ring slot as the request that was * consumed to make the slot available, and the backend must ensure * this assumption is true. * * extra info (netif_extra_info_t) * ------------------------------- * * General format: * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * |type |flags| type specific data | * +-----+-----+-----+-----+-----+-----+-----+-----+ * | padding for tx | * +-----+-----+-----+-----+ * * type: XEN_NETIF_EXTRA_TYPE_* * flags: XEN_NETIF_EXTRA_FLAG_* * padding for tx: present only in the tx case due to 8 octet limit * from rx case. Not shown in type specific entries * below. * * XEN_NETIF_EXTRA_TYPE_GSO: * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * |type |flags| size |type | pad | features | * +-----+-----+-----+-----+-----+-----+-----+-----+ * * type: Must be XEN_NETIF_EXTRA_TYPE_GSO * flags: XEN_NETIF_EXTRA_FLAG_* * size: Maximum payload size of each segment. For example, * for TCP this is just the path MSS. * type: XEN_NETIF_GSO_TYPE_*: This determines the protocol of * the packet and any extra features required to segment the * packet properly. * features: EN_NETIF_GSO_FEAT_*: This specifies any extra GSO * features required to process this packet, such as ECN * support for TCPv4. * * XEN_NETIF_EXTRA_TYPE_MCAST_{ADD,DEL}: * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * |type |flags| addr | * +-----+-----+-----+-----+-----+-----+-----+-----+ * * type: Must be XEN_NETIF_EXTRA_TYPE_MCAST_{ADD,DEL} * flags: XEN_NETIF_EXTRA_FLAG_* * addr: address to add/remove * * XEN_NETIF_EXTRA_TYPE_HASH: * * A backend that supports teoplitz hashing is assumed to accept * this type of extra info in transmit packets. * A frontend that enables hashing is assumed to accept * this type of extra info in receive packets. * * 0 1 2 3 4 5 6 7 octet * +-----+-----+-----+-----+-----+-----+-----+-----+ * |type |flags|htype| alg |LSB ---- value ---- MSB| * +-----+-----+-----+-----+-----+-----+-----+-----+ * * type: Must be XEN_NETIF_EXTRA_TYPE_HASH * flags: XEN_NETIF_EXTRA_FLAG_* * htype: Hash type (one of _XEN_NETIF_CTRL_HASH_TYPE_* - see above) * alg: The algorithm used to calculate the hash (one of * XEN_NETIF_CTRL_HASH_TYPE_ALGORITHM_* - see above) * value: Hash value */ /* Protocol checksum field is blank in the packet (hardware offload)? */ #define _NETTXF_csum_blank (0) #define NETTXF_csum_blank (1U<<_NETTXF_csum_blank) /* Packet data has been validated against protocol checksum. */ #define _NETTXF_data_validated (1) #define NETTXF_data_validated (1U<<_NETTXF_data_validated) /* Packet continues in the next request descriptor. */ #define _NETTXF_more_data (2) #define NETTXF_more_data (1U<<_NETTXF_more_data) /* Packet to be followed by extra descriptor(s). */ #define _NETTXF_extra_info (3) #define NETTXF_extra_info (1U<<_NETTXF_extra_info) #define XEN_NETIF_MAX_TX_SIZE 0xFFFF struct netif_tx_request { grant_ref_t gref; uint16_t offset; uint16_t flags; uint16_t id; uint16_t size; }; typedef struct netif_tx_request netif_tx_request_t; /* Types of netif_extra_info descriptors. */ #define XEN_NETIF_EXTRA_TYPE_NONE (0) /* Never used - invalid */ #define XEN_NETIF_EXTRA_TYPE_GSO (1) /* u.gso */ #define XEN_NETIF_EXTRA_TYPE_MCAST_ADD (2) /* u.mcast */ #define XEN_NETIF_EXTRA_TYPE_MCAST_DEL (3) /* u.mcast */ #define XEN_NETIF_EXTRA_TYPE_HASH (4) /* u.hash */ #define XEN_NETIF_EXTRA_TYPE_MAX (5) /* netif_extra_info_t flags. */ #define _XEN_NETIF_EXTRA_FLAG_MORE (0) #define XEN_NETIF_EXTRA_FLAG_MORE (1U<<_XEN_NETIF_EXTRA_FLAG_MORE) /* GSO types */ #define XEN_NETIF_GSO_TYPE_NONE (0) #define XEN_NETIF_GSO_TYPE_TCPV4 (1) #define XEN_NETIF_GSO_TYPE_TCPV6 (2) /* * This structure needs to fit within both netif_tx_request_t and * netif_rx_response_t for compatibility. */ struct netif_extra_info { uint8_t type; uint8_t flags; union { struct { uint16_t size; uint8_t type; uint8_t pad; uint16_t features; } gso; struct { uint8_t addr[6]; } mcast; struct { uint8_t type; uint8_t algorithm; uint8_t value[4]; } hash; uint16_t pad[3]; } u; }; typedef struct netif_extra_info netif_extra_info_t; struct netif_tx_response { uint16_t id; int16_t status; }; typedef struct netif_tx_response netif_tx_response_t; struct netif_rx_request { uint16_t id; /* Echoed in response message. */ uint16_t pad; grant_ref_t gref; }; typedef struct netif_rx_request netif_rx_request_t; /* Packet data has been validated against protocol checksum. */ #define _NETRXF_data_validated (0) #define NETRXF_data_validated (1U<<_NETRXF_data_validated) /* Protocol checksum field is blank in the packet (hardware offload)? */ #define _NETRXF_csum_blank (1) #define NETRXF_csum_blank (1U<<_NETRXF_csum_blank) /* Packet continues in the next request descriptor. */ #define _NETRXF_more_data (2) #define NETRXF_more_data (1U<<_NETRXF_more_data) /* Packet to be followed by extra descriptor(s). */ #define _NETRXF_extra_info (3) #define NETRXF_extra_info (1U<<_NETRXF_extra_info) /* Packet has GSO prefix. Deprecated but included for compatibility */ #define _NETRXF_gso_prefix (4) #define NETRXF_gso_prefix (1U<<_NETRXF_gso_prefix) struct netif_rx_response { uint16_t id; uint16_t offset; uint16_t flags; int16_t status; }; typedef struct netif_rx_response netif_rx_response_t; /* * Generate netif ring structures and types. */ DEFINE_RING_TYPES(netif_tx, struct netif_tx_request, struct netif_tx_response); DEFINE_RING_TYPES(netif_rx, struct netif_rx_request, struct netif_rx_response); #define NETIF_RSP_DROPPED -2 #define NETIF_RSP_ERROR -1 #define NETIF_RSP_OKAY 0 /* No response: used for auxiliary requests (e.g., netif_extra_info_t). */ #define NETIF_RSP_NULL 1 #endif
{ "pile_set_name": "Github" }
# GalaxyNG - Home: http://galaxyng.sourceforge.net/, https://sourceforge.net/projects/galaxyng/ - State: mature, inactive since 2005 - Download: https://sourceforge.net/projects/galaxyng/files - Keywords: strategy, turn-based - Code repository: https://gitlab.com/osgames/galaxyng.git (backup of cvs), http://galaxyng.cvs.sourceforge.net/ (cvs) - Code language: C - Code license: GPL-2.0 Play by email interstellar wargame for multiple players. See also https://github.com/scumola/GalaxyNG, https://github.com/toddcarnes/goggle, [GalaxyView](https://sourceforge.net/projects/galaxyview/) a turn viewer for this project, https://github.com/gumpu/GalaxyNGV2 ## Building
{ "pile_set_name": "Github" }
class FalseClass def to_json(options = nil) #:nodoc: 'false' end end
{ "pile_set_name": "Github" }
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; long long f[51][51], g[51][51][51], h[51], c[51][51], pow2[1250]; int n, m, mod = 1000000007; int main() { cin >> n >> m; if (m >= n) { cout << 0 << endl; return 0; } for (int i = 0; i <= n; i++) c[i][0] = 1; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod; pow2[0] = 1; for (int i = 1; i <= n * (n - 1) / 2; i++) pow2[i] = pow2[i - 1] * 2 % mod; g[0][0][0] = 1; for (int i = 1; i <= n; i++) { h[i] = pow2[i*(i - 1) / 2]; for (int j = 1; j < i; j++) h[i] = (h[i] - h[j] * c[i - 1][j - 1] % mod * pow2[(i - j)*(i - j - 1) / 2]) % mod; f[i][0] = h[i]; for (int j = 1; j < i; j++) { for (int k = 1; k < i; k++) { long long component_1 = f[k][0] * c[i - 1][k - 1] % mod; long long k_x = 1; for (int x = 1; x <= min(i - k, j); x++) { k_x = k_x * k % mod; f[i][j] = (f[i][j] + component_1 * g[i - k][j - x][x] % mod * k_x) % mod; } } f[i][0] = (f[i][0] - f[i][j]) % mod; } for (int j = 0; j < i; j++) for (int k = 1; k <= i; k++) for (int p = 1; p <= i; p++) for (int q = 0; q <= j; q++) g[i][j][k] = (g[i][j][k] + f[p][q] * c[i - 1][p - 1] % mod * p % mod * g[i - p][j - q][k - 1]) % mod; } cout << (f[n][m] + mod) % mod << endl; }
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSSegmentedControl.h" @interface NSProSegmentedControl : NSSegmentedControl { } + (void)initialize; - (long long)indexOfSelectedMenuItemInMenuForSegmentAtIndex:(long long)arg1; - (id)selectedMenuItemInMenuForSegmentAtIndex:(long long)arg1; - (void)selectMenuItemAtIndex:(long long)arg1 inMenuForSegmentAtIndex:(long long)arg2; - (void)selectMenuItem:(id)arg1 inMenuForSegmentAtIndex:(long long)arg2; - (void)setMenu:(id)arg1 forSegment:(long long)arg2 isPopUp:(BOOL)arg3 useMenuDelay:(BOOL)arg4; - (double)displayWidthForSegment:(long long)arg1; - (void)setSlider:(id)arg1 forSegment:(long long)arg2; - (id)sliderForSegment:(long long)arg1; - (void)setAttributedLabel:(id)arg1 forSegment:(long long)arg2; - (id)attributedLabelForSegment:(long long)arg1; - (void)setThemeImageSource:(id)arg1 forSegment:(long long)arg2; - (id)themeImageSourceForSegment:(long long)arg1; - (void)setTintIndex:(long long)arg1; - (long long)tintIndex; - (void)viewDidMoveToWindow; - (void)instantiateWithObjectInstantiator:(id)arg1; - (void)encodeWithCoder:(id)arg1; - (id)initWithCoder:(id)arg1; - (id)initWithFrame:(struct CGRect)arg1; @end
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="donate">Donér</string> <string name="lichessPatron">Bidragsytar til Lichess</string> <string name="freeAccount">Gratis konto</string> <string name="becomePatron">Bli ein bidragsytar til Lichess</string> <string name="xBecamePatron">%s vart bidragsytar til Lichess</string> <string name="newPatrons">Nye bidragsytarar</string> <string name="freeChess">Gratis sjakk for alle, for alltid!</string> <string name="noAdsNoSubs">Ingen annonsar, ingen abonnement; men open-kjeldekode og glødande engasjement.</string> <string name="thankYou">Takk for bidraget ditt!</string> <string name="youHaveLifetime">Du har ein bidragsytar-konto på livstid. Det er rett og slett storarta!</string> <string name="patronUntil">Du har ein bidragsytar-konto fram til %s.</string> <string name="ifNotRenewed">Dersom den ikkje blir fornya vil kontoen din bli nedgradert til gratis.</string> <string name="weAreNonProfit">Vi er ein nonprofitorganisasjon fordi vi meiner at alle bør ha tilgang til ein gratis, verdsomspennande sjakkplatform.</string> <string name="weRelyOnSupport">For å gjere det mogleg er vi avhengige av stønad frå folk som deg. Dersom du set pris på å bruka Lichess, så vurdér gjerne å støtte oss med eit bidrag og bli ein bidragsytar!</string> <string name="lifetime">Livstid</string> <string name="payLifetimeOnce">Betal %s éin gong og ver Lichess bidragsytar for alltid!</string> <string name="lifetimePatron">Lichess-mesén på livstid</string> <string name="makeExtraDonation">Gje eit ekstra bidrag?</string> <string name="monthly">Månadleg</string> <string name="recurringBilling">Tilbakevendande fakturering, forny bidragsytar-vingane dine kvar månad.</string> <string name="onetime">Ein gong</string> <string name="singleDonation">Eit enkelt bidrag vil gje deg bidragsytar-vingar i ein månad.</string> <string name="otherAmount">Anna</string> <string name="pleaseEnterAmount">Ver venleg og skriv inn eit beløp i USA-dollar (USD)</string> <string name="withCreditCard">Kredittkort</string> <string name="withPaypal">PayPal</string> <string name="weAreSmallTeam">Vi er ei lita gruppe, så støtta di er av stor vekt!</string> <string name="celebratedPatrons">Dei akta bidragsytarane som gjer Lichess mogleg</string> <string name="whereMoneyGoes">Kva går pengane til?</string> <string name="serversAndDeveloper">Framfor alt til kraftige tenarmaskiner. Deretter løner vi ein fulltidsutviklar: %s, grunnleggaren av Lichess.</string> <string name="costBreakdown">Sjå ei detaljert oversikt over kostnadar</string> <string name="officialNonProfit">Er Lichess offisielt ein nonprofit organisasjon?</string> <string name="actOfCreation">Ja, her er grunnleggingsdokumentet. (på fransk)</string> <string name="changeMonthlySupport">Kan eg endre/annullere det månadlege bidraget mitt?</string> <string name="changeOrContact">Ja, når som helst, frå denne sida. Eller du kan %s.</string> <string name="contactSupport">ta kontakt med Lichess-hjelpa</string> <string name="otherMethods">Andre måtar å bidra på?</string> <string name="bankTransfers">Vi tek òg mot bankoverføringar</string> <string name="bitcoin">Og her er bitcoin-adressa vår: %s</string> <string name="patronFeatures">Er nokre funksjonar reservert bidragsytarar?</string> <string name="noPatronFeatures">Nei, for Lichess er heilt gratis, for alltid og for alle. Det er ein lovnad. Men bidragsytarar kan briske seg med et tøft, nytt profil-ikon.</string> <string name="featuresComparison">Sjå ein detaljert samanlikning av funksjonar</string> <plurals name="patronForMonths"> <item quantity="one">Lichess-mesén for ein månad</item> <item quantity="other">Lichess-mesén for %s månader</item> </plurals> <string name="youSupportWith">Du støttar lichess.org med %s i månaden.</string> <string name="tyvm">Mange takk for støtta di. Du er sjef!</string> <string name="currentStatus">Gjeldande status</string> <string name="nextPayment">Neste betaling</string> <string name="youWillBeChargedXOnY">Du vil bli trekt %1$s, %2$s.</string> <string name="makeAdditionalDonation">Legg inn ei ekstra pengegåve no</string> <string name="update">Oppdater</string> <string name="changeMonthlyAmount">Endre månadleg beløp (%s)</string> <string name="cancelSupport">avslutt støtta di</string> <string name="xOrY">%1$s eller %2$s</string> <string name="decideHowMuch">Avgjer kor stor verde Lichess har for deg:</string> <string name="stopPayments">Slett kredittkortdetaljar og stopp faste innbetalingar:</string> <string name="noLongerSupport">Avslutt å støtte Lichess</string> <string name="paymentHistory">Betalingshistorikk</string> <string name="paid">Betalt</string> <string name="viewOthers">Sjå andre Lichess-mesenar</string> <string name="date">Dato</string> <string name="amount">Beløp</string> <string name="transactionCompleted">Transaksjonen er gjennomført og ei kvittering er sendt til epostadressa di.</string> <string name="permanentPatron">Du har no ein permanent mesenkonto.</string> <string name="checkOutProfile">Sjekk profilen din!</string> <string name="nowLifetime">Du er no livslang Lichess-mesen!</string> <string name="nowOneMonth">Du er no Lichess-mesen for ein månad!</string> <string name="downgradeNextMonth">Om ein månad blir du IKKJE belasta på ny, og Lichess-kontoen din blir gradert ned til gratis-nivået.</string> </resources>
{ "pile_set_name": "Github" }
#!/usr/bin/python3 import os import tempfile import shutil import json from optparse import OptionParser # # Runtime variables # TEMP_DIR = tempfile.mkdtemp() # Directory of this python file CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) def updateVersion(path, channel, version): print("Updating json file {0}".format(path)) file = open(path, 'r') data = file.read() try: config_json = json.loads(data) except json.decoder.JSONDecodeError: print("Creating new json file..") config_json = { "darwin-x64-prod": {"readme": "Standalone release", "update": "https://adguardteam.github.io/AdGuardForSafari/release/release.json", "install": "https://static.adguard.com/safari/release/AdGuard_Safari.app.zip", "version": "1.4.1"}, "darwin-x64-beta": { "readme": "Standalone beta", "update": "https://adguardteam.github.io/AdGuardForSafari/beta/release.json", "install": "https://static.adguard.com/safari/beta/AdGuard_Safari_Beta.app.zip", "version": "1.4.1"} } prodConfig = config_json["darwin-x64-prod"] betaConfig = config_json["darwin-x64-beta"] if channel == "release": prodConfig["version"] = version if channel == "beta": betaConfig["version"] = version file = open(path, "w") file.write(json.dumps(config_json, indent=4)) file.close() return def main(): parser = OptionParser() parser.add_option("-p", "--path", dest="path", help="path to the file or app to notarize.") parser.add_option("-c", "--channel", dest="channel", help="updates channel name") parser.add_option("-v", "--version", dest="version", help="semantic version") # pylint: disable=unused-variable (options, args) = parser.parse_args() path = options.path if not path: parser.error("Path is not given") if not options.channel: parser.error("Channel is not given") if not options.version: parser.error("Version is not given") if not os.path.isabs(path): path = os.path.join(CURRENT_DIR, path) if not os.path.exists(path): raise ValueError("Cannot find json file: {0}".format(path)) updateVersion(path, options.channel, options.version) return # Entry point try: main() finally: shutil.rmtree(TEMP_DIR)
{ "pile_set_name": "Github" }
package us.myles.ViaVersion.api.minecraft.chunks; import com.github.steveice10.opennbt.tag.builtin.CompoundTag; import java.util.List; public interface Chunk { int getX(); int getZ(); boolean isBiomeData(); boolean isFullChunk(); @Deprecated default boolean isGroundUp() { return isFullChunk(); } boolean isIgnoreOldLightData(); void setIgnoreOldLightData(boolean ignoreOldLightData); int getBitmask(); ChunkSection[] getSections(); int[] getBiomeData(); void setBiomeData(int[] biomeData); CompoundTag getHeightMap(); void setHeightMap(CompoundTag heightMap); List<CompoundTag> getBlockEntities(); }
{ "pile_set_name": "Github" }
# Copyright (C) 1991-1999,2002,2004,2005 Free Software Foundation, Inc. # This file is part of the GNU C Library. # The GNU C Library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # The GNU C Library 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 # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with the GNU C Library; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA # 02111-1307 USA. # errno.texi contains lines like: # @comment errno.h # @comment POSIX.1: Function not implemented # @deftypevr Macro int ENOSYS # @comment errno 78 # Descriptive paragraph... # @end deftypevr BEGIN { # Here we list the E* names that might be duplicate names for the # same integer value on some systems. This causes the code below # to generate ``#if defined (ALIAS) && ALIAS != ORIGINAL'' in the code, # so the output does not presume that these are in fact aliases. # We list here all the known potential cases on any system, # so that the C source we produce will do the right thing based # on the actual #define'd values it's compiled with. alias["EWOULDBLOCK"]= "EAGAIN"; alias["EDEADLOCK"] = "EDEADLK"; alias["ENOTSUP"] = "EOPNOTSUPP"; print "/* This file is generated from errno.texi by errlist.awk. */" print ""; print "#include <errno.h>"; print "#include <libintl.h>"; print ""; print "#ifndef ERR_REMAP"; print "# define ERR_REMAP(n) n"; print "#endif"; print ""; print "#if !defined EMIT_ERR_MAX && !defined ERRLIST_NO_COMPAT"; print "# include <errlist-compat.h>"; print "#endif"; print "#ifdef ERR_MAX"; print "# define ERRLIST_SIZE ERR_MAX + 1"; print "#else" print "# define ERRLIST_SIZE"; print "#endif"; print "const char *const _sys_errlist_internal[ERRLIST_SIZE] ="; print " {"; print " [0] = N_(\"Success\")," } $1 == "@comment" && $2 == "errno.h" { errnoh=1; next } errnoh == 1 && $1 == "@comment" \ { ++errnoh; etext = $3; for (i = 4; i <= NF; ++i) etext = etext " " $i; next; } errnoh == 2 && $1 == "@deftypevr" && $2 == "Macro" && $3 == "int" \ { e = $4; errnoh++; next; } errnoh == 3 && $1 == "@comment" && $2 == "errno" \ { errno = $3 + 0; if (alias[e]) printf "#if defined (%s) && %s != %s\n", e, e, alias[e]; else printf "#ifdef %s\n", e; errnoh = 4; desc=""; next; } errnoh == 4 && $1 == "@end" && $2 == "deftypevr" \ { printf "/*%s */\n", desc; printf " [ERR_REMAP (%s)] = N_(\"%s\"),\n", e, etext; printf "# if %s > ERR_MAX\n", e; print "# undef ERR_MAX"; printf "# define ERR_MAX %s\n", e; print "# endif"; print "#endif"; errnoh = 0; next; } errnoh == 4 \ { # This magic tag in C comments gets them copied into libc.pot. desc = desc "\nTRANS " $0; next } { errnoh=0 } END { print " };"; print ""; print "#define NERR \\"; print " (sizeof _sys_errlist_internal / sizeof _sys_errlist_internal [0])"; print "const int _sys_nerr_internal = NERR;" print ""; print "#if !defined NOT_IN_libc && !ERRLIST_NO_COMPAT"; print "# include <errlist-compat.c>"; print "#endif"; print ""; print "#ifdef EMIT_ERR_MAX"; print "void dummy (void)" print "{ asm volatile (\" @@@ %0 @@@ \" : : \"i\" (ERR_REMAP (ERR_MAX))); }" print "#endif"; }
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com> // // 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/. #ifndef EIGEN_CXX11_TENSOR_TENSOR_DEVICE_H #define EIGEN_CXX11_TENSOR_TENSOR_DEVICE_H namespace Eigen { /** \class TensorDevice * \ingroup CXX11_Tensor_Module * * \brief Pseudo expression providing an operator = that will evaluate its argument * on the specified computing 'device' (GPU, thread pool, ...) * * Example: * C.device(EIGEN_GPU) = A + B; * * Todo: operator *= and /=. */ template <typename ExpressionType, typename DeviceType> class TensorDevice { public: TensorDevice(const DeviceType& device, ExpressionType& expression) : m_device(device), m_expression(expression) {} template<typename OtherDerived> EIGEN_STRONG_INLINE TensorDevice& operator=(const OtherDerived& other) { typedef TensorAssignOp<ExpressionType, const OtherDerived> Assign; Assign assign(m_expression, other); internal::TensorExecutor<const Assign, DeviceType>::run(assign, m_device); return *this; } template<typename OtherDerived> EIGEN_STRONG_INLINE TensorDevice& operator+=(const OtherDerived& other) { typedef typename OtherDerived::Scalar Scalar; typedef TensorCwiseBinaryOp<internal::scalar_sum_op<Scalar>, const ExpressionType, const OtherDerived> Sum; Sum sum(m_expression, other); typedef TensorAssignOp<ExpressionType, const Sum> Assign; Assign assign(m_expression, sum); internal::TensorExecutor<const Assign, DeviceType>::run(assign, m_device); return *this; } template<typename OtherDerived> EIGEN_STRONG_INLINE TensorDevice& operator-=(const OtherDerived& other) { typedef typename OtherDerived::Scalar Scalar; typedef TensorCwiseBinaryOp<internal::scalar_difference_op<Scalar>, const ExpressionType, const OtherDerived> Difference; Difference difference(m_expression, other); typedef TensorAssignOp<ExpressionType, const Difference> Assign; Assign assign(m_expression, difference); internal::TensorExecutor<const Assign, DeviceType>::run(assign, m_device); return *this; } protected: const DeviceType& m_device; ExpressionType& m_expression; }; } // end namespace Eigen #endif // EIGEN_CXX11_TENSOR_TENSOR_DEVICE_H
{ "pile_set_name": "Github" }
package test import ( "bytes" "encoding" "encoding/base64" "strings" ) type marshalerForTest struct { X string } func encode(str string) string { buf := bytes.Buffer{} b64 := base64.NewEncoder(base64.StdEncoding, &buf) if _, err := b64.Write([]byte(str)); err != nil { panic(err) } if err := b64.Close(); err != nil { panic(err) } return buf.String() } func decode(str string) string { if len(str) == 0 { return "" } b64 := base64.NewDecoder(base64.StdEncoding, strings.NewReader(str)) bs := make([]byte, len(str)) if n, err := b64.Read(bs); err != nil { panic(err) } else { bs = bs[:n] } return string(bs) } func (m marshalerForTest) MarshalText() ([]byte, error) { return []byte(`MANUAL__` + encode(m.X)), nil } func (m *marshalerForTest) UnmarshalText(text []byte) error { m.X = decode(strings.TrimPrefix(string(text), "MANUAL__")) return nil } var _ encoding.TextMarshaler = marshalerForTest{} var _ encoding.TextUnmarshaler = &marshalerForTest{} type marshalerAlias marshalerForTest type typeForTest struct { S string M marshalerAlias I int8 }
{ "pile_set_name": "Github" }
module Jekyll module TablerFilter def to_pretty_time(value) a = (Time.now-value).to_i case a when 0 then 'just now' when 1 then 'a second ago' when 2..59 then a.to_s+' seconds ago' when 60..119 then 'a minute ago' #120 = 2 minutes when 120..3540 then (a/60).to_i.to_s+' minutes ago' when 3541..7100 then 'an hour ago' # 3600 = 1 hour when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago' when 82801..172000 then 'a day ago' # 86400 = 1 day when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago' when 518400..1036800 then 'a week ago' else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago' end end def divide(value, number) value.to_i * 1.0 / number end def number_color(value) value = value.to_i if value >= 80 'green' elsif value >= 40 'yellow' else 'red' end end def first_letter(value) return value[0, 1] end def mix(color_1, color_2, weight=50) color = "#" color_1 = color_1[0,1] == '#' ? color_1[1,6] : color_1 color_2 = color_2[0,1] == '#' ? color_2[1,6] : color_2 for i in [0, 2, 4] v1 = color_1[i, 2].to_i(16).to_s(10) v2 = color_2[i, 2].to_i(16).to_s(10) val = ((v2.to_i + (v1.to_i - v2.to_i) * (weight / 100.0)).round).to_s(16); while val.length < 2 val = '0' + val end color += val end color end def each_slice(array, count=2) @size = (array.size / (count * 1.0)).ceil array.each_slice(@size).to_a end end end Liquid::Template.register_filter(Jekyll::TablerFilter)
{ "pile_set_name": "Github" }
SELECT dish_stuff.name, string_agg(stuff, ','), sum(g), sum(calories), sum(g / 100.0 * calories) AS result FROM dish_stuff JOIN stuff_calories ON dish_stuff.stuff = stuff_calories.name WHERE dish_stuff.name = '华夫饼' GROUP BY dish_stuff.name
{ "pile_set_name": "Github" }
<?xml version="1.0" ?> <annotation> <folder>widerface</folder> <filename>55--Sports_Coach_Trainer_55_Sports_Coach_Trainer_sportcoaching_55_177.jpg</filename> <source> <database>wider face Database</database> <annotation>PASCAL VOC2007</annotation> <image>flickr</image> <flickrid>-1</flickrid> </source> <owner> <flickrid>yanyu</flickrid> <name>yanyu</name> </owner> <size> <width>1024</width> <height>683</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>192</xmin> <ymin>230</ymin> <xmax>222</xmax> <ymax>269</ymax> </bndbox> <lm> <x1>207.737</x1> <y1>239.906</y1> <x2>219.031</x2> <y2>238.679</y2> <x3>220.504</x3> <y3>246.29</y3> <x4>210.929</x4> <y4>256.848</y4> <x5>219.031</x5> <y5>256.112</y5> <visible>1</visible> <blur>0.41</blur> </lm> <has_lm>1</has_lm> </object> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>517</xmin> <ymin>222</ymin> <xmax>548</xmax> <ymax>261</ymax> </bndbox> <lm> <x1>524.75</x1> <y1>235.0</y1> <x2>538.25</x2> <y2>237.0</y2> <x3>529.5</x3> <y3>243.5</y3> <x4>523.5</x4> <y4>249.25</y4> <x5>535.0</x5> <y5>251.0</y5> <visible>1</visible> <blur>0.54</blur> </lm> <has_lm>1</has_lm> </object> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>657</xmin> <ymin>237</ymin> <xmax>681</xmax> <ymax>285</ymax> </bndbox> <lm> <x1>659.286</x1> <y1>253.321</y1> <x2>660.5</x2> <y2>253.321</y2> <x3>658.982</x3> <y3>262.125</y3> <x4>661.107</x4> <y4>269.107</y4> <x5>662.321</x5> <y5>269.107</y5> <visible>1</visible> <blur>0.33</blur> </lm> <has_lm>1</has_lm> </object> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>753</xmin> <ymin>223</ymin> <xmax>785</xmax> <ymax>268</ymax> </bndbox> <lm> <x1>756.286</x1> <y1>239.286</y1> <x2>765.143</x2> <y2>241.857</y2> <x3>754.857</x3> <y3>248.429</y3> <x4>764.0</x4> <y4>256.143</y4> <x5>764.857</x5> <y5>256.429</y5> <visible>1</visible> <blur>0.55</blur> </lm> <has_lm>1</has_lm> </object> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>853</xmin> <ymin>218</ymin> <xmax>885</xmax> <ymax>265</ymax> </bndbox> <lm> <x1>861.621</x1> <y1>233.723</y1> <x2>862.518</x2> <y2>233.723</y2> <x3>853.246</x3> <y3>244.79</y3> <x4>863.714</x4> <y4>253.464</y4> <x5>867.304</x5> <y5>253.763</y5> <visible>0</visible> <blur>0.5</blur> </lm> <has_lm>1</has_lm> </object> </annotation>
{ "pile_set_name": "Github" }
#ifndef _X11_IMUTIL_H_ #define _X11_IMUTIL_H_ extern int _XGetScanlinePad( Display *dpy, int depth); extern int _XGetBitsPerPixel( Display *dpy, int depth); extern int _XSetImage( XImage *srcimg, register XImage *dstimg, register int x, register int y); extern int _XReverse_Bytes( register unsigned char *bpt, register int nb); extern void _XInitImageFuncPtrs( register XImage *image); #endif /* _X11_IMUTIL_H_ */
{ "pile_set_name": "Github" }
// modarith.h - originally written and placed in the public domain by Wei Dai /// \file modarith.h /// \brief Class file for performing modular arithmetic. #ifndef CRYPTOPP_MODARITH_H #define CRYPTOPP_MODARITH_H // implementations are in integer.cpp #include "cryptlib.h" #include "integer.h" #include "algebra.h" #include "secblock.h" #include "misc.h" #if CRYPTOPP_MSC_VERSION # pragma warning(push) # pragma warning(disable: 4231 4275) #endif NAMESPACE_BEGIN(CryptoPP) CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<Integer>; CRYPTOPP_DLL_TEMPLATE_CLASS AbstractRing<Integer>; CRYPTOPP_DLL_TEMPLATE_CLASS AbstractEuclideanDomain<Integer>; /// \brief Ring of congruence classes modulo n /// \details This implementation represents each congruence class as the smallest /// non-negative integer in that class. /// \details <tt>const Element&</tt> returned by member functions are references /// to internal data members. Since each object may have only /// one such data member for holding results, the following code /// will produce incorrect results: /// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre> /// But this should be fine: /// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre> class CRYPTOPP_DLL ModularArithmetic : public AbstractRing<Integer> { public: typedef int RandomizationParameter; typedef Integer Element; virtual ~ModularArithmetic() {} /// \brief Construct a ModularArithmetic /// \param modulus congruence class modulus ModularArithmetic(const Integer &modulus = Integer::One()) : AbstractRing<Integer>(), m_modulus(modulus), m_result(static_cast<word>(0), modulus.reg.size()) {} /// \brief Copy construct a ModularArithmetic /// \param ma other ModularArithmetic ModularArithmetic(const ModularArithmetic &ma) : AbstractRing<Integer>(), m_modulus(ma.m_modulus), m_result(static_cast<word>(0), ma.m_modulus.reg.size()) {} /// \brief Construct a ModularArithmetic /// \param bt BER encoded ModularArithmetic ModularArithmetic(BufferedTransformation &bt); // construct from BER encoded parameters /// \brief Clone a ModularArithmetic /// \returns pointer to a new ModularArithmetic /// \details Clone effectively copy constructs a new ModularArithmetic. The caller is /// responsible for deleting the pointer returned from this method. virtual ModularArithmetic * Clone() const {return new ModularArithmetic(*this);} /// \brief Encodes in DER format /// \param bt BufferedTransformation object void DEREncode(BufferedTransformation &bt) const; /// \brief Encodes element in DER format /// \param out BufferedTransformation object /// \param a Element to encode void DEREncodeElement(BufferedTransformation &out, const Element &a) const; /// \brief Decodes element in DER format /// \param in BufferedTransformation object /// \param a Element to decode void BERDecodeElement(BufferedTransformation &in, Element &a) const; /// \brief Retrieves the modulus /// \returns the modulus const Integer& GetModulus() const {return m_modulus;} /// \brief Sets the modulus /// \param newModulus the new modulus void SetModulus(const Integer &newModulus) {m_modulus = newModulus; m_result.reg.resize(m_modulus.reg.size());} /// \brief Retrieves the representation /// \returns true if the if the modulus is in Montgomery form for multiplication, false otherwise virtual bool IsMontgomeryRepresentation() const {return false;} /// \brief Reduces an element in the congruence class /// \param a element to convert /// \returns the reduced element /// \details ConvertIn is useful for derived classes, like MontgomeryRepresentation, which /// must convert between representations. virtual Integer ConvertIn(const Integer &a) const {return a%m_modulus;} /// \brief Reduces an element in the congruence class /// \param a element to convert /// \returns the reduced element /// \details ConvertOut is useful for derived classes, like MontgomeryRepresentation, which /// must convert between representations. virtual Integer ConvertOut(const Integer &a) const {return a;} /// \brief Divides an element by 2 /// \param a element to convert const Integer& Half(const Integer &a) const; /// \brief Compare two elements for equality /// \param a first element /// \param b second element /// \returns true if the elements are equal, false otherwise /// \details Equal() tests the elements for equality using <tt>a==b</tt> bool Equal(const Integer &a, const Integer &b) const {return a==b;} /// \brief Provides the Identity element /// \returns the Identity element const Integer& Identity() const {return Integer::Zero();} /// \brief Adds elements in the ring /// \param a first element /// \param b second element /// \returns the sum of <tt>a</tt> and <tt>b</tt> const Integer& Add(const Integer &a, const Integer &b) const; /// \brief TODO /// \param a first element /// \param b second element /// \returns TODO Integer& Accumulate(Integer &a, const Integer &b) const; /// \brief Inverts the element in the ring /// \param a first element /// \returns the inverse of the element const Integer& Inverse(const Integer &a) const; /// \brief Subtracts elements in the ring /// \param a first element /// \param b second element /// \returns the difference of <tt>a</tt> and <tt>b</tt>. The element <tt>a</tt> must provide a Subtract member function. const Integer& Subtract(const Integer &a, const Integer &b) const; /// \brief TODO /// \param a first element /// \param b second element /// \returns TODO Integer& Reduce(Integer &a, const Integer &b) const; /// \brief Doubles an element in the ring /// \param a the element /// \returns the element doubled /// \details Double returns <tt>Add(a, a)</tt>. The element <tt>a</tt> must provide an Add member function. const Integer& Double(const Integer &a) const {return Add(a, a);} /// \brief Retrieves the multiplicative identity /// \returns the multiplicative identity /// \details the base class implementations returns 1. const Integer& MultiplicativeIdentity() const {return Integer::One();} /// \brief Multiplies elements in the ring /// \param a the multiplicand /// \param b the multiplier /// \returns the product of a and b /// \details Multiply returns <tt>a*b\%n</tt>. const Integer& Multiply(const Integer &a, const Integer &b) const {return m_result1 = a*b%m_modulus;} /// \brief Square an element in the ring /// \param a the element /// \returns the element squared /// \details Square returns <tt>a*a\%n</tt>. The element <tt>a</tt> must provide a Square member function. const Integer& Square(const Integer &a) const {return m_result1 = a.Squared()%m_modulus;} /// \brief Determines whether an element is a unit in the ring /// \param a the element /// \returns true if the element is a unit after reduction, false otherwise. bool IsUnit(const Integer &a) const {return Integer::Gcd(a, m_modulus).IsUnit();} /// \brief Calculate the multiplicative inverse of an element in the ring /// \param a the element /// \details MultiplicativeInverse returns <tt>a<sup>-1</sup>\%n</tt>. The element <tt>a</tt> must /// provide a InverseMod member function. const Integer& MultiplicativeInverse(const Integer &a) const {return m_result1 = a.InverseMod(m_modulus);} /// \brief Divides elements in the ring /// \param a the dividend /// \param b the divisor /// \returns the quotient /// \details Divide returns <tt>a*b<sup>-1</sup>\%n</tt>. const Integer& Divide(const Integer &a, const Integer &b) const {return Multiply(a, MultiplicativeInverse(b));} /// \brief TODO /// \param x first element /// \param e1 first exponent /// \param y second element /// \param e2 second exponent /// \returns TODO Integer CascadeExponentiate(const Integer &x, const Integer &e1, const Integer &y, const Integer &e2) const; /// \brief Exponentiates a base to multiple exponents in the ring /// \param results an array of Elements /// \param base the base to raise to the exponents /// \param exponents an array of exponents /// \param exponentsCount the number of exponents in the array /// \details SimultaneousExponentiate() raises the base to each exponent in the exponents array and stores the /// result at the respective position in the results array. /// \details SimultaneousExponentiate() must be implemented in a derived class. /// \pre <tt>COUNTOF(results) == exponentsCount</tt> /// \pre <tt>COUNTOF(exponents) == exponentsCount</tt> void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const; /// \brief Provides the maximum bit size of an element in the ring /// \returns maximum bit size of an element unsigned int MaxElementBitLength() const {return (m_modulus-1).BitCount();} /// \brief Provides the maximum byte size of an element in the ring /// \returns maximum byte size of an element unsigned int MaxElementByteLength() const {return (m_modulus-1).ByteCount();} /// \brief Provides a random element in the ring /// \param rng RandomNumberGenerator used to generate material /// \param ignore_for_now unused /// \returns a random element that is uniformly distributed /// \details RandomElement constructs a new element in the range <tt>[0,n-1]</tt>, inclusive. /// The element's class must provide a constructor with the signature <tt>Element(RandomNumberGenerator rng, /// Element min, Element max)</tt>. Element RandomElement(RandomNumberGenerator &rng , const RandomizationParameter &ignore_for_now = 0) const // left RandomizationParameter arg as ref in case RandomizationParameter becomes a more complicated struct { CRYPTOPP_UNUSED(ignore_for_now); return Element(rng, Integer::Zero(), m_modulus - Integer::One()) ; } /// \brief Compares two ModularArithmetic for equality /// \param rhs other ModularArithmetic /// \returns true if this is equal to the other, false otherwise /// \details The operator tests for equality using <tt>this.m_modulus == rhs.m_modulus</tt>. bool operator==(const ModularArithmetic &rhs) const {return m_modulus == rhs.m_modulus;} static const RandomizationParameter DefaultRandomizationParameter ; protected: Integer m_modulus; mutable Integer m_result, m_result1; }; // const ModularArithmetic::RandomizationParameter ModularArithmetic::DefaultRandomizationParameter = 0 ; /// \brief Performs modular arithmetic in Montgomery representation for increased speed /// \details The Montgomery representation represents each congruence class <tt>[a]</tt> as /// <tt>a*r\%n</tt>, where <tt>r</tt> is a convenient power of 2. /// \details <tt>const Element&</tt> returned by member functions are references to /// internal data members. Since each object may have only one such data member for holding /// results, the following code will produce incorrect results: /// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre> /// But this should be fine: /// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre> class CRYPTOPP_DLL MontgomeryRepresentation : public ModularArithmetic { public: virtual ~MontgomeryRepresentation() {} /// \brief Construct a MontgomeryRepresentation /// \param modulus congruence class modulus /// \note The modulus must be odd. MontgomeryRepresentation(const Integer &modulus); /// \brief Clone a MontgomeryRepresentation /// \returns pointer to a new MontgomeryRepresentation /// \details Clone effectively copy constructs a new MontgomeryRepresentation. The caller is /// responsible for deleting the pointer returned from this method. virtual ModularArithmetic * Clone() const {return new MontgomeryRepresentation(*this);} bool IsMontgomeryRepresentation() const {return true;} Integer ConvertIn(const Integer &a) const {return (a<<(WORD_BITS*m_modulus.reg.size()))%m_modulus;} Integer ConvertOut(const Integer &a) const; const Integer& MultiplicativeIdentity() const {return m_result1 = Integer::Power2(WORD_BITS*m_modulus.reg.size())%m_modulus;} const Integer& Multiply(const Integer &a, const Integer &b) const; const Integer& Square(const Integer &a) const; const Integer& MultiplicativeInverse(const Integer &a) const; Integer CascadeExponentiate(const Integer &x, const Integer &e1, const Integer &y, const Integer &e2) const {return AbstractRing<Integer>::CascadeExponentiate(x, e1, y, e2);} void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const {AbstractRing<Integer>::SimultaneousExponentiate(results, base, exponents, exponentsCount);} private: Integer m_u; mutable IntegerSecBlock m_workspace; }; NAMESPACE_END #if CRYPTOPP_MSC_VERSION # pragma warning(pop) #endif #endif
{ "pile_set_name": "Github" }
"" "none dropped" ("","none split")
{ "pile_set_name": "Github" }
/* * COPYRIGHT (c) 1989-2009. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.org/license/LICENSE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <tmacros.h> const char rtems_test_name[] = "SPSTKALLOC"; /* forward declarations to avoid warnings */ rtems_task Init(rtems_task_argument argument); #define MAXIMUM_STACKS 2 typedef struct { uint8_t Space[CPU_STACK_MINIMUM_SIZE]; } StackMemory_t; int stackToAlloc = 0; StackMemory_t Stacks[MAXIMUM_STACKS]; void *StackDeallocated = NULL; static void *StackAllocator(size_t size) { if (stackToAlloc < MAXIMUM_STACKS) return &Stacks[stackToAlloc++]; return NULL; } static void StackDeallocator(void *stack) { StackDeallocated = stack; } rtems_task Init( rtems_task_argument ignored ) { rtems_status_code rc; rtems_id taskId; rtems_id taskId1; TEST_BEGIN(); puts( "Init - create task TA1 to use custom stack allocator - OK" ); rc = rtems_task_create( rtems_build_name( 'T', 'A', '1', ' ' ), 1, RTEMS_MINIMUM_STACK_SIZE, RTEMS_DEFAULT_MODES, RTEMS_DEFAULT_ATTRIBUTES, &taskId ); directive_failed( rc, "rtems_task_create of TA1" ); puts( "Init - create task TA1 to have custom stack allocator fail" ); rc = rtems_task_create( rtems_build_name( 'F', 'A', 'I', 'L' ), 1, RTEMS_MINIMUM_STACK_SIZE, RTEMS_DEFAULT_MODES, RTEMS_DEFAULT_ATTRIBUTES, &taskId1 ); fatal_directive_status( rc, RTEMS_UNSATISFIED, "rtems_task_create of FAIL" ); puts( "Init - delete task TA1 to use custom stack deallocator - OK" ); rc = rtems_task_delete( taskId ); directive_failed( rc, "rtems_task_delete of TA1" ); TEST_END(); rtems_test_exit(0); } /* configuration information */ #define CONFIGURE_APPLICATION_NEEDS_SIMPLE_CONSOLE_DRIVER #define CONFIGURE_APPLICATION_DOES_NOT_NEED_CLOCK_DRIVER #define CONFIGURE_TASK_STACK_ALLOCATOR StackAllocator #define CONFIGURE_TASK_STACK_DEALLOCATOR StackDeallocator #define CONFIGURE_INITIAL_EXTENSIONS RTEMS_TEST_INITIAL_EXTENSION #define CONFIGURE_RTEMS_INIT_TASKS_TABLE #define CONFIGURE_MAXIMUM_TASKS 3 #define CONFIGURE_INIT #include <rtems/confdefs.h> /* global variables */
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Graph demo</title> <style type="text/css"> body {font: 10pt arial;} </style> <script type="text/javascript" src="../graph.js"></script> <!--[if IE]><script type="text/javascript" src="../excanvas.js"></script><![endif]--> <link rel="stylesheet" type="text/css" href="../graph.css"> <script type="text/javascript"> /** * Split given dataset in two datasets. The first * @param {Object[]} data Array with objects, each object has * a parameter date and value * @param {Number} threshold Threshold value * @return {Object} splitted An object containing data sets 'lower' * 'threshold', and 'upper' */ function dataSplit(data, threshold) { var upper = []; var lower = []; var thres = []; var prevIsLower = undefined; for (var i = 0, l = data.length; i < l; i++) { var d = data[i]; var isLower = (d.value < threshold); if (isLower) { lower.push({ 'date': new Date(d.date), 'value': d.value}); } else { upper.push({'date': new Date(d.date), 'value': d.value}); } thres.push({'date': new Date(d.date), 'value': threshold}); if (i > 0 && prevIsLower != isLower) { // change from lower to upper or vice versa var dPrev = data[i - 1]; var fraction = (threshold - dPrev.value) / (d.value - dPrev.value); var dateAvg = new Date(Math.round( dPrev.date.valueOf() + (d.date.valueOf() - dPrev.date.valueOf()) * fraction)); var valueAvg = dPrev.value + (d.value - dPrev.value) * fraction; if (prevIsLower) { lower.push({'date': new Date(dateAvg), 'value': valueAvg}); lower.push({'date': new Date(dateAvg), 'value': undefined}); upper.push({'date': new Date(dateAvg), 'value': undefined}); upper.push({'date': new Date(dateAvg), 'value': valueAvg}); } else { upper.push({'date': new Date(dateAvg), 'value': valueAvg}); upper.push({'date': new Date(dateAvg), 'value': undefined}); lower.push({'date': new Date(dateAvg), 'value': undefined}); lower.push({'date': new Date(dateAvg), 'value': valueAvg}); } } prevIsLower = isLower; } return { "upper": upper, "lower": lower, "threshold": thres }; } function drawVisualization() { // Create and populate a data table. var graphData = []; function functionA(x) { return Math.sin(x / 10) * Math.cos(x / 5) * 50; } // create a set of dates var d = new Date(2010, 9, 23, 20, 0, 0); for (var i = 0; i < 100; i++) { graphData.push({ 'date': new Date(d), 'value': functionA(i) }); d.setMinutes(d.getMinutes() + 1); } var threshold = -5; var splittedData = dataSplit(graphData, threshold); var data = [ {"label": "Threshold", "data" : splittedData.threshold}, {"label": "Upper", "data" : splittedData.upper}, {"label": "Lower", "data" : splittedData.lower} ]; // specify options var options = { width: "100%", height: "350px", lines: [ {color: "#FF9900", width: 1}, // orange {color: "#109618", width: 3}, // green {color: "#DC3912", width: 3} // red ] }; // Instantiate our graph object. var graph = new links.Graph(document.getElementById('mygraph')); // Draw our graph with the created data and options graph.draw(data, options); } </script> </head> <body onload="drawVisualization();"> <p> In this example the data of one function is splitted around a threshold into two functions. The two functions are plotted with a different color and visually look like one continuous function. </p> <div id="mygraph"></div> <div id="info"></div> </body> </html>
{ "pile_set_name": "Github" }
package libcontainer import "testing" func TestErrorCode(t *testing.T) { codes := map[ErrorCode]string{ IdInUse: "Id already in use", InvalidIdFormat: "Invalid format", ContainerPaused: "Container paused", ConfigInvalid: "Invalid configuration", SystemError: "System error", ContainerNotExists: "Container does not exist", } for code, expected := range codes { if actual := code.String(); actual != expected { t.Fatalf("expected string %q but received %q", expected, actual) } } }
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <ZopeData> <record id="1" aka="AAAAAAAAAAE="> <pickle> <global name="VariableDefinition" module="Products.DCWorkflow.Variables"/> </pickle> <pickle> <dictionary> <item> <key> <string>default_expr</string> </key> <value> <persistent> <string encoding="base64">AAAAAAAAAAI=</string> </persistent> </value> </item> <item> <key> <string>default_value</string> </key> <value> <string></string> </value> </item> <item> <key> <string>description</string> </key> <value> <string></string> </value> </item> <item> <key> <string>for_catalog</string> </key> <value> <int>0</int> </value> </item> <item> <key> <string>for_status</string> </key> <value> <int>1</int> </value> </item> <item> <key> <string>id</string> </key> <value> <string>action</string> </value> </item> <item> <key> <string>info_guard</string> </key> <value> <none/> </value> </item> <item> <key> <string>update_always</string> </key> <value> <int>1</int> </value> </item> </dictionary> </pickle> </record> <record id="2" aka="AAAAAAAAAAI="> <pickle> <tuple> <tuple> <string>Products.CMFCore.Expression</string> <string>Expression</string> </tuple> <none/> </tuple> </pickle> <pickle> <dictionary> <item> <key> <string>text</string> </key> <value> <string>transition/getId|nothing</string> </value> </item> </dictionary> </pickle> </record> </ZopeData>
{ "pile_set_name": "Github" }
package org.rewedigital.katana.comparison import org.koin.core.KoinComponent import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.core.inject import org.koin.dsl.bind import org.koin.dsl.module class KoinSubject : Subject, KoinComponent { override fun setup() { val module = module { single { MySingleton() } factory { MyDependencyImpl(get()) } bind MyDependency::class factory { MyDependency2(get()) } } startKoin { modules(module) } } override fun execute() { val dependency: MyDependency by inject() val dependency2: MyDependency2 by inject() dependency.execute() dependency2.execute() } override fun shutdown() { stopKoin() } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE keyboard SYSTEM "../dtd/ldmlKeyboard.dtd"> <keyboard locale="km-t-k0-osx"> <version platform="10.9" number="$Revision$"/> <names> <name value="Khmer"/> </names> <keyMap> <map iso="E00" to="«"/> <!-- ` --> <map iso="E01" to="១"/> <!-- 1 --> <map iso="E02" to="២"/> <!-- 2 --> <map iso="E03" to="៣"/> <!-- 3 --> <map iso="E04" to="៤"/> <!-- 4 --> <map iso="E05" to="៥"/> <!-- 5 --> <map iso="E06" to="៦"/> <!-- 6 --> <map iso="E07" to="៧"/> <!-- 7 --> <map iso="E08" to="៨"/> <!-- 8 --> <map iso="E09" to="៩"/> <!-- 9 --> <map iso="E10" to="០"/> <!-- 0 --> <map iso="E11" to="ឥ"/> <!-- - --> <map iso="E12" to="ឲ"/> <!-- = --> <map iso="D01" to="ឆ"/> <!-- Q --> <map iso="D02" to="\u{17B9}"/> <!-- W to= ឹ --> <map iso="D03" to="\u{17C1}"/> <!-- E to= េ --> <map iso="D04" to="រ"/> <!-- R --> <map iso="D05" to="ត"/> <!-- T --> <map iso="D06" to="យ"/> <!-- Y --> <map iso="D07" to="\u{17BB}"/> <!-- U to= ុ --> <map iso="D08" to="\u{17B7}"/> <!-- I to= ិ --> <map iso="D09" to="\u{17C4}"/> <!-- O to= ោ --> <map iso="D10" to="ផ"/> <!-- P --> <map iso="D11" to="\u{17C0}"/> <!-- [ to= ៀ --> <map iso="D12" to="ឪ"/> <!-- ] --> <map iso="D13" to="ឭ"/> <!-- \ --> <map iso="C01" to="\u{17B6}"/> <!-- A to= ា --> <map iso="C02" to="ស"/> <!-- S --> <map iso="C03" to="ដ"/> <!-- D --> <map iso="C04" to="ថ"/> <!-- F --> <map iso="C05" to="ង"/> <!-- G --> <map iso="C06" to="ហ"/> <!-- H --> <map iso="C07" to="\u{17D2}"/> <!-- J to= ្ --> <map iso="C08" to="ក"/> <!-- K --> <map iso="C09" to="ល"/> <!-- L --> <map iso="C10" to="\u{17BE}"/> <!-- ; to= ើ --> <map iso="C11" to="\u{17CB}"/> <!-- ' to= ់ --> <map iso="B01" to="ឋ"/> <!-- Z --> <map iso="B02" to="ខ"/> <!-- X --> <map iso="B03" to="ច"/> <!-- C --> <map iso="B04" to="វ"/> <!-- V --> <map iso="B05" to="ប"/> <!-- B --> <map iso="B06" to="ន"/> <!-- N --> <map iso="B07" to="ម"/> <!-- M --> <map iso="B08" to="ឦ"/> <!-- , --> <map iso="B09" to="។"/> <!-- . --> <map iso="B10" to="\u{17CA}"/> <!-- / to= ៊ --> <map iso="A03" to=" "/> <!-- space --> </keyMap> <keyMap modifiers="shift"> <map iso="E00" to="»"/> <!-- ` base=« --> <map iso="E01" to="!"/> <!-- 1 base=១ --> <map iso="E02" to="ៗ"/> <!-- 2 base=២ --> <map iso="E03" to="\u{22}"/> <!-- 3 base=៣ to= " --> <map iso="E04" to="៛"/> <!-- 4 base=៤ --> <map iso="E05" to="%"/> <!-- 5 base=៥ --> <map iso="E06" to="\u{17CD}"/> <!-- 6 base=៦ to= ៍ --> <map iso="E07" to="\u{17D0}"/> <!-- 7 base=៧ to= ័ --> <map iso="E08" to="\u{17CF}"/> <!-- 8 base=៨ to= ៏ --> <map iso="E09" to="ឰ"/> <!-- 9 base=៩ --> <map iso="E10" to="ឳ"/> <!-- 0 base=០ --> <map iso="E11" to="\u{17CC}"/> <!-- - base=ឥ to= ៌ --> <map iso="E12" to="\u{17CE}"/> <!-- = base=ឲ to= ៎ --> <map iso="D01" to="ឈ"/> <!-- Q base=ឆ --> <map iso="D02" to="\u{17BA}"/> <!-- W base=ឹ to= ឺ --> <map iso="D03" to="\u{17C2}"/> <!-- E base=េ to= ែ --> <map iso="D04" to="ឬ"/> <!-- R base=រ --> <map iso="D05" to="ទ"/> <!-- T base=ត --> <map iso="D06" to="\u{17BD}"/> <!-- Y base=យ to= ួ --> <map iso="D07" to="\u{17BC}"/> <!-- U base=ុ to= ូ --> <map iso="D08" to="\u{17B8}"/> <!-- I base=ិ to= ី --> <map iso="D09" to="\u{17C5}"/> <!-- O base=ោ to= ៅ --> <map iso="D10" to="ភ"/> <!-- P base=ផ --> <map iso="D11" to="\u{17BF}"/> <!-- [ base=ៀ to= ឿ --> <map iso="D12" to="ឧ"/> <!-- ] base=ឪ --> <map iso="D13" to="ឮ"/> <!-- \ base=ឭ --> <map iso="C01" to="ឫ"/> <!-- A base=ា --> <map iso="C02" to="\u{17C3}"/> <!-- S base=ស to= ៃ --> <map iso="C03" to="ឌ"/> <!-- D base=ដ --> <map iso="C04" to="ធ"/> <!-- F base=ថ --> <map iso="C05" to="អ"/> <!-- G base=ង --> <map iso="C06" to="\u{17C7}"/> <!-- H base=ហ to= ះ --> <map iso="C07" to="ញ"/> <!-- J base=្ --> <map iso="C08" to="គ"/> <!-- K base=ក --> <map iso="C09" to="ឡ"/> <!-- L base=ល --> <map iso="C10" to="៖"/> <!-- ; base=ើ --> <map iso="C11" to="\u{17C9}"/> <!-- ' base=់ to= ៉ --> <map iso="B01" to="ឍ"/> <!-- Z base=ឋ --> <map iso="B02" to="ឃ"/> <!-- X base=ខ --> <map iso="B03" to="ជ"/> <!-- C base=ច --> <map iso="B04" to="\u{17C8}"/> <!-- V base=វ to= ៈ --> <map iso="B05" to="ព"/> <!-- B base=ប --> <map iso="B06" to="ណ"/> <!-- N base=ន --> <map iso="B07" to="\u{17C6}"/> <!-- M base=ម to= ំ --> <map iso="B08" to="ឱ"/> <!-- , base=ឦ --> <map iso="B09" to="៕"/> <!-- . base=។ --> <map iso="B10" to="ឯ"/> <!-- / base=៊ --> <map iso="A03" to="\u{200B}"/> <!-- space --> </keyMap> <keyMap modifiers="caps cmd+opt?+caps?"> <map iso="E00" to="`"/> <!-- base=« --> <map iso="E01" to="1"/> <!-- base=១ --> <map iso="E02" to="2"/> <!-- base=២ --> <map iso="E03" to="3"/> <!-- base=៣ --> <map iso="E04" to="4"/> <!-- base=៤ --> <map iso="E05" to="5"/> <!-- base=៥ --> <map iso="E06" to="6"/> <!-- base=៦ --> <map iso="E07" to="7"/> <!-- base=៧ --> <map iso="E08" to="8"/> <!-- base=៨ --> <map iso="E09" to="9"/> <!-- base=៩ --> <map iso="E10" to="0"/> <!-- base=០ --> <map iso="E11" to="-"/> <!-- base=ឥ --> <map iso="E12" to="="/> <!-- base=ឲ --> <map iso="D01" to="q"/> <!-- base=ឆ --> <map iso="D02" to="w"/> <!-- base=ឹ --> <map iso="D03" to="e"/> <!-- base=េ --> <map iso="D04" to="r"/> <!-- base=រ --> <map iso="D05" to="t"/> <!-- base=ត --> <map iso="D06" to="y"/> <!-- base=យ --> <map iso="D07" to="u"/> <!-- base=ុ --> <map iso="D08" to="i"/> <!-- base=ិ --> <map iso="D09" to="o"/> <!-- base=ោ --> <map iso="D10" to="p"/> <!-- base=ផ --> <map iso="D11" to="["/> <!-- base=ៀ --> <map iso="D12" to="]"/> <!-- base=ឪ --> <map iso="D13" to="\"/> <!-- base=ឭ --> <map iso="C01" to="a"/> <!-- base=ា --> <map iso="C02" to="s"/> <!-- base=ស --> <map iso="C03" to="d"/> <!-- base=ដ --> <map iso="C04" to="f"/> <!-- base=ថ --> <map iso="C05" to="g"/> <!-- base=ង --> <map iso="C06" to="h"/> <!-- base=ហ --> <map iso="C07" to="j"/> <!-- base=្ --> <map iso="C08" to="k"/> <!-- base=ក --> <map iso="C09" to="l"/> <!-- base=ល --> <map iso="C10" to=";"/> <!-- base=ើ --> <map iso="C11" to="&apos;"/> <!-- base=់ --> <map iso="B01" to="z"/> <!-- base=ឋ --> <map iso="B02" to="x"/> <!-- base=ខ --> <map iso="B03" to="c"/> <!-- base=ច --> <map iso="B04" to="v"/> <!-- base=វ --> <map iso="B05" to="b"/> <!-- base=ប --> <map iso="B06" to="n"/> <!-- base=ន --> <map iso="B07" to="m"/> <!-- base=ម --> <map iso="B08" to=","/> <!-- base=ឦ --> <map iso="B09" to="."/> <!-- base=។ --> <map iso="B10" to="/"/> <!-- base=៊ --> <map iso="A03" to=" "/> <!-- space --> </keyMap> <keyMap modifiers="caps+shift cmd+shift+opt?+caps?"> <map iso="E00" to="~"/> <!-- ` base=« --> <map iso="E01" to="!"/> <!-- 1 base=១ --> <map iso="E02" to="@"/> <!-- 2 base=២ --> <map iso="E03" to="#"/> <!-- 3 base=៣ --> <map iso="E04" to="$"/> <!-- 4 base=៤ --> <map iso="E05" to="%"/> <!-- 5 base=៥ --> <map iso="E06" to="^"/> <!-- 6 base=៦ --> <map iso="E07" to="&amp;"/> <!-- 7 base=៧ --> <map iso="E08" to="*"/> <!-- 8 base=៨ --> <map iso="E09" to="("/> <!-- 9 base=៩ --> <map iso="E10" to=")"/> <!-- 0 base=០ --> <map iso="E11" to="_"/> <!-- - base=ឥ --> <map iso="E12" to="+"/> <!-- = base=ឲ --> <map iso="D01" to="Q"/> <!-- base=ឆ --> <map iso="D02" to="W"/> <!-- base=ឹ --> <map iso="D03" to="E"/> <!-- base=េ --> <map iso="D04" to="R"/> <!-- base=រ --> <map iso="D05" to="T"/> <!-- base=ត --> <map iso="D06" to="Y"/> <!-- base=យ --> <map iso="D07" to="U"/> <!-- base=ុ --> <map iso="D08" to="I"/> <!-- base=ិ --> <map iso="D09" to="O"/> <!-- base=ោ --> <map iso="D10" to="P"/> <!-- base=ផ --> <map iso="D11" to="{"/> <!-- [ base=ៀ --> <map iso="D12" to="}"/> <!-- ] base=ឪ --> <map iso="D13" to="|"/> <!-- \ base=ឭ --> <map iso="C01" to="A"/> <!-- base=ា --> <map iso="C02" to="S"/> <!-- base=ស --> <map iso="C03" to="D"/> <!-- base=ដ --> <map iso="C04" to="F"/> <!-- base=ថ --> <map iso="C05" to="G"/> <!-- base=ង --> <map iso="C06" to="H"/> <!-- base=ហ --> <map iso="C07" to="J"/> <!-- base=្ --> <map iso="C08" to="K"/> <!-- base=ក --> <map iso="C09" to="L"/> <!-- base=ល --> <map iso="C10" to=":"/> <!-- ; base=ើ --> <map iso="C11" to="\u{22}"/> <!-- ' base=់ to= " --> <map iso="B01" to="Z"/> <!-- base=ឋ --> <map iso="B02" to="X"/> <!-- base=ខ --> <map iso="B03" to="C"/> <!-- base=ច --> <map iso="B04" to="V"/> <!-- base=វ --> <map iso="B05" to="B"/> <!-- base=ប --> <map iso="B06" to="N"/> <!-- base=ន --> <map iso="B07" to="M"/> <!-- base=ម --> <map iso="B08" to="&lt;"/> <!-- , base=ឦ --> <map iso="B09" to="&gt;"/> <!-- . base=។ --> <map iso="B10" to="?"/> <!-- / base=៊ --> <map iso="A03" to=" "/> <!-- space --> </keyMap> <keyMap modifiers="opt+caps?"> <map iso="E00" to="\u{200D}"/> <!-- ` base=« --> <map iso="E01" to="\u{200C}"/> <!-- 1 base=១ --> <map iso="E02" to="@"/> <!-- 2 base=២ --> <map iso="E03" to="\u{17D1}"/> <!-- 3 base=៣ to= ៑ --> <map iso="E04" to="$"/> <!-- 4 base=៤ --> <map iso="E05" to="€"/> <!-- 5 base=៥ --> <map iso="E06" to="៙"/> <!-- 6 base=៦ --> <map iso="E07" to="៚"/> <!-- 7 base=៧ --> <map iso="E08" to="*"/> <!-- 8 base=៨ --> <map iso="E09" to="("/> <!-- 9 base=៩ --> <map iso="E10" to=")"/> <!-- 0 base=០ --> <map iso="E11" to="+"/> <!-- - base=ឥ --> <map iso="E12" to="="/> <!-- base=ឲ --> <map iso="D05" to="ថ"/> <!-- T base=ត --> <map iso="D11" to="ឨ"/> <!-- [ base=ៀ --> <map iso="D12" to="ឩ"/> <!-- ] base=ឪ --> <map iso="D13" to="\"/> <!-- base=ឭ --> <map iso="C01" to="ៜ"/> <!-- A base=ា --> <map iso="C02" to="ឝ"/> <!-- S base=ស --> <map iso="C03" to="ឞ"/> <!-- D base=ដ --> <map iso="C10" to=";"/> <!-- base=ើ --> <map iso="C11" to="&apos;"/> <!-- base=់ --> <map iso="B08" to=","/> <!-- base=ឦ --> <map iso="B09" to="."/> <!-- base=។ --> <map iso="B10" to="?"/> <!-- / base=៊ --> <map iso="A03" to=" "/> <!-- space --> </keyMap> <keyMap modifiers="opt+shift+caps?"> <map iso="E00" to="~"/> <!-- ` base=« --> <map iso="E01" to="…"/> <!-- 1 base=១ --> <map iso="E02" to="©"/> <!-- 2 base=២ --> <map iso="E03" to="®"/> <!-- 3 base=៣ --> <map iso="E04" to="™"/> <!-- 4 base=៤ --> <map iso="E05" to="’"/> <!-- 5 base=៥ --> <map iso="E06" to="‘"/> <!-- 6 base=៦ --> <map iso="E07" to="–"/> <!-- 7 base=៧ --> <map iso="E08" to="•"/> <!-- 8 base=៨ --> <map iso="E09" to="—"/> <!-- 9 base=៩ --> <map iso="E10" to="×"/> <!-- 0 base=០ --> <map iso="E11" to="−"/> <!-- - base=ឥ --> <map iso="E12" to="+"/> <!-- = base=ឲ --> <map iso="C02" to="ឞ"/> <!-- S base=ស --> <map iso="A03" to=" "/> <!-- space --> </keyMap> <keyMap modifiers="ctrlL+cmd?+opt?+caps? ctrlL+shift+cmd?+optL?+caps? ctrlL+opt+cmd?+caps?+shiftL?"> <map iso="E00" to="`"/> <!-- base=« --> <map iso="E01" to="1"/> <!-- base=១ --> <map iso="E02" to="2"/> <!-- base=២ --> <map iso="E03" to="3"/> <!-- base=៣ --> <map iso="E04" to="4"/> <!-- base=៤ --> <map iso="E05" to="5"/> <!-- base=៥ --> <map iso="E06" to="6"/> <!-- base=៦ --> <map iso="E07" to="7"/> <!-- base=៧ --> <map iso="E08" to="8"/> <!-- base=៨ --> <map iso="E09" to="9"/> <!-- base=៩ --> <map iso="E10" to="0"/> <!-- base=០ --> <map iso="E11" to="\u{1F}"/> <!-- - base=ឥ --> <map iso="E12" to="="/> <!-- base=ឲ --> <map iso="D01" to="\u{11}"/> <!-- Q base=ឆ --> <map iso="D02" to="\u{17}"/> <!-- W base=ឹ --> <map iso="D03" to="\u{5}"/> <!-- E base=េ --> <map iso="D04" to="\u{12}"/> <!-- R base=រ --> <map iso="D05" to="\u{14}"/> <!-- T base=ត --> <map iso="D06" to="\u{19}"/> <!-- Y base=យ --> <map iso="D07" to="\u{15}"/> <!-- U base=ុ --> <map iso="D08" to="\u{9}"/> <!-- I base=ិ --> <map iso="D09" to="\u{F}"/> <!-- O base=ោ --> <map iso="D10" to="\u{10}"/> <!-- P base=ផ --> <map iso="D11" to="\u{1B}"/> <!-- [ base=ៀ --> <map iso="D12" to="\u{1D}"/> <!-- ] base=ឪ --> <map iso="D13" to="\u{1C}"/> <!-- \ base=ឭ --> <map iso="C01" to="\u{1}"/> <!-- A base=ា --> <map iso="C02" to="\u{13}"/> <!-- S base=ស --> <map iso="C03" to="\u{4}"/> <!-- D base=ដ --> <map iso="C04" to="\u{6}"/> <!-- F base=ថ --> <map iso="C05" to="\u{7}"/> <!-- G base=ង --> <map iso="C06" to="\u{8}"/> <!-- H base=ហ --> <map iso="C07" to="\u{A}"/> <!-- J base=្ --> <map iso="C08" to="\u{B}"/> <!-- K base=ក --> <map iso="C09" to="\u{C}"/> <!-- L base=ល --> <map iso="C10" to=";"/> <!-- base=ើ --> <map iso="C11" to="&apos;"/> <!-- base=់ --> <map iso="B00" to="0"/> <!-- (key to left of Z) --> <map iso="B01" to="\u{1A}"/> <!-- Z base=ឋ --> <map iso="B02" to="\u{18}"/> <!-- X base=ខ --> <map iso="B03" to="\u{3}"/> <!-- C base=ច --> <map iso="B04" to="\u{16}"/> <!-- V base=វ --> <map iso="B05" to="\u{2}"/> <!-- B base=ប --> <map iso="B06" to="\u{E}"/> <!-- N base=ន --> <map iso="B07" to="\u{D}"/> <!-- M base=ម --> <map iso="B08" to=","/> <!-- base=ឦ --> <map iso="B09" to="."/> <!-- base=។ --> <map iso="B10" to="/"/> <!-- base=៊ --> <map iso="A03" to=" "/> <!-- space --> </keyMap> </keyboard>
{ "pile_set_name": "Github" }
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package mocks import ( "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" "github.com/hyperledger/fabric-sdk-go/pkg/fab/mocks" ) /** * Mock Discovery Provider is used to mock peers on the network */ // MockStaticDiscoveryProvider implements mock discovery provider type MockStaticDiscoveryProvider struct { Error error Peers []fab.Peer } // MockStaticDiscoveryService implements mock discovery service type MockStaticDiscoveryService struct { Error error Peers []fab.Peer } // NewMockDiscoveryProvider returns mock discovery provider func NewMockDiscoveryProvider(err error, peers []fab.Peer) (*MockStaticDiscoveryProvider, error) { return &MockStaticDiscoveryProvider{Error: err, Peers: peers}, nil } // CreateLocalDiscoveryService return discovery service for specific channel func (dp *MockStaticDiscoveryProvider) CreateLocalDiscoveryService(mspID string) (fab.DiscoveryService, error) { return &MockStaticDiscoveryService{Error: dp.Error, Peers: dp.Peers}, nil } // NewMockDiscoveryService returns mock discovery service func NewMockDiscoveryService(err error, peers ...fab.Peer) *MockStaticDiscoveryService { return &MockStaticDiscoveryService{Error: err, Peers: peers} } // GetPeers is used to discover eligible peers for chaincode func (ds *MockStaticDiscoveryService) GetPeers() ([]fab.Peer, error) { if ds.Error != nil { return nil, ds.Error } if ds.Peers == nil { mockPeer := mocks.MockPeer{MockName: "Peer1", MockURL: "http://peer1.com", MockRoles: []string{}, MockCert: nil, MockMSP: "Org1MSP"} peers := make([]fab.Peer, 0) peers = append(peers, &mockPeer) ds.Peers = peers } return ds.Peers, nil }
{ "pile_set_name": "Github" }
#!/bin/bash # Copyright JS Foundation and other contributors, http://js.foundation # # 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. doxygen 2>&1 >/dev/null | head -n 1000 | tee doxygen.log if [ -s doxygen.log ] then EXIT=1 else EXIT=0 fi rm -f doxygen.log exit $EXIT
{ "pile_set_name": "Github" }