text:
(function() {
  (function($) {
    var methods;
    methods = {
      edit: function(isEditing) {
        return this.each(function() {
          return $(this).attr("contentEditable", isEditing || false);
        });
      },
      save: function(callback) {
        return this.each(function() {
          return callback($(this).attr('id'), $(this).html());
        });
      },
      createlink: function() {
        var urlPrompt;
        urlPrompt = prompt("Enter URL:", "http://");
        return document.execCommand("createlink", false, urlPrompt);
      },
      insertimage: function() {
        var urlPrompt;
        urlPrompt = prompt("Enter Image URL:", "http://");
        return document.execCommand("insertimage", false, urlPrompt);
      },
      formatblock: function(block) {
        return document.execCommand("formatblock", null, block);
      },
      init: function(opts) {
        var $toolbar, button, command, commands, excludes, font, font_list, fontnames, fontsize, fontsizes, group, groups, options, shortcuts, size_list, _i, _j, _k, _l, _len, _len2, _len3, _len4;
        options = opts || {};
        groups = [
          [
            {
              name: 'bold',
              label: "B",
              title: 'Bold (Ctrl+B)',
              classname: 'toolbar_bold'
            }, {
              name: 'italic',
              label: "I",
              title: 'Italic (Ctrl+I)',
              classname: 'toolbar_italic'
            }, {
              name: 'underline',
              label: "U",
              title: 'Underline (Ctrl+U)',
              classname: 'toolbar_underline'
            }, {
              name: 'strikethrough',
              label: "ABC",
              title: 'Strikethrough',
              classname: 'toolbar_strikethrough'
            }, {
              name: 'removeFormat',
              label: "",
              title: 'Remove Formating (Ctrl+M)',
              classname: 'toolbar_remove'
            }
          ], [
            {
              name: 'fontname',
              label: "F ",
              title: 'Select font name',
              classname: 'toolbar_fontname dropdown-toggle',
              dropdown: true
            }
          ], [
            {
              name: 'FontSize',
              label: "AA ",
              title: 'Select font size',
              classname: 'toolbar_fontsize dropdown-toggle',
              dropdown: true
            }
          ], [
            {
              name: 'forecolor',
              label: "
A
",
              title: 'Select font color',
              classname: 'toolbar_forecolor dropdown-toggle',
              dropdown: true
            }
          ], [
            {
              name: 'backcolor',
              label: "

 ",
              title: 'Select background color',
              classname: 'toolbar_bgcolor dropdown-toggle',
              dropdown: true
            }
          ], [
            {
              name: 'justifyleft',
              label: "",
              title: 'Left justify',
              classname: 'toolbar_justifyleft'
            }, {
              name: 'justifycenter',
              label: "",
              title: 'Center justify',
              classname: 'toolbar_justifycenter'
            }, {
              name: 'justifyright',
              label: "",
              title: 'Right justify',
              classname: 'toolbar_justifyright'
            }, {
              name: 'justifyfull',
              label: "",
              title: 'Full justify',
              classname: 'toolbar_justifyfull'
            }
          ], [
            {
              name: 'createlink',
              label: '@',
              title: 'Link to a web page (Ctrl+L)',
              userinput: "yes",
              classname: 'toolbar_link'
            }, {
              name: 'insertimage',
              label: "",
              title: 'Insert an image (Ctrl+G)',
              userinput: "yes",
              classname: 'toolbar_image'
            }, {
              name: 'insertorderedlist',
              label: "",
              title: 'Insert ordered list',
              classname: 'toolbar_ol'
            }, {
              name: 'insertunorderedlist',
              label: "",
              title: 'Insert unordered list',
              classname: 'toolbar_ul'
            }
          ], [
            {
              name: 'insertparagraph',
              label: 'P',
              title: 'Insert a paragraph (Ctrl+Alt+0)',
              classname: 'toolbar_p',
              block: 'p'
            }, {
              name: 'insertheading1',
              label: 'H1',
              title: "Heading 1 (Ctrl+Alt+1)",
              classname: 'toolbar_h1',
              block: 'h1'
            }, {
              name: 'insertheading2',
              label: 'H2',
              title: "Heading 2 (Ctrl+Alt+2)",
              classname: 'toolbar_h2',
              block: 'h2'
            }, {
              name: 'insertheading3',
              label: 'H3',
              title: "Heading 3 (Ctrl+Alt+3)",
              classname: 'toolbar_h3',
              block: 'h3'
            }, {
              name: 'insertheading4',
              label: 'H4',
              title: "Heading 4 (Ctrl+Alt+4)",
              classname: 'toolbar_h4',
              block: 'h4'
            }
          ], [
            {
              name: 'blockquote',
              label: "",
              title: 'Blockquote (Ctrl+Q)',
              classname: 'toolbar_blockquote',
              block: 'blockquote'
            }, {
              name: 'code',
              label: '{ }',
              title: 'Code (Ctrl+Alt+K)',
              classname: 'toolbar_code',
              block: 'pre'
            }, {
              name: 'superscript',
              label: 'x2',
              title: 'Superscript',
              classname: 'toolbar_superscript'
            }, {
              name: 'subscript',
              label: 'x2',
              title: 'Subscript',
              classname: 'toolbar_subscript'
            }
          ]
        ];
        if (options.toolbar_selector != null) {
          $toolbar = $(options.toolbar_selector);
        } else {
          $(this).before("

");
          $toolbar = $('#editor-toolbar');
        }
        $toolbar.addClass('fresheditor-toolbar');
        $toolbar.append("

");
        excludes = options.excludes || [];
        for (_i = 0, _len = groups.length; _i < _len; _i++) {
          commands = groups[_i];
          group = '';
          for (_j = 0, _len2 = commands.length; _j < _len2; _j++) {
            command = commands[_j];
            if (jQuery.inArray(command.name, excludes) < 0) {
              button = "<a href='#' class='btn toolbar-btn toolbar-cmd " + command.classname + "' title='" + command.title + "' command='" + command.name + "'";
              if (command.userinput != null) {
                button += " userinput='" + command.userinput + "'";
              }
              if (command.block != null) {
                button += " block='" + command.block + "'";
              }
              if (command.dropdown) {
                button += " data-toggle='dropdown'";
              }
              button += ">" + command.label + "";
              group += button;
            }
          }
          $('.btn-toolbar', $toolbar).append("
" + group + "
");
        }
        $("[data-toggle='dropdown']").removeClass('toolbar-cmd');
        if (jQuery.inArray('fontname', excludes) < 0) {
          fontnames = ["Arial", "Arial Black", "Comic Sans MS", "Courier New", "Georgia", "Helvetica", "Sans Serif", "Tahoma", "Times New Roman", "Trebuchet MS", "Verdana"];
          font_list = '';
          for (_k = 0, _len3 = fontnames.length; _k < _len3; _k++) {
            font = fontnames[_k];
            font_list += "
" + font + "
";
          }
          $('.toolbar_fontname').after("
" + font_list + "
");
          $('.fontname-option').on('click', function() {
            document.execCommand("fontname", false, $(this).text());
            $(this).closest('.btn-group').removeClass('open');
            return false;
          });
        }
        if (jQuery.inArray('FontSize', excludes) < 0) {
          fontsizes = [
            {
              size: 1,
              point: 8
            }, {
              size: 2,
              point: 10
            }, {
              size: 3,
              point: 12
            }, {
              size: 4,
              point: 14
            }, {
              size: 5,
              point: 18
            }, {
              size: 6,
              point: 24
            }, {
              size: 7,
              point: 36
            }
          ];
          size_list = '';
          for (_l = 0, _len4 = fontsizes.length; _l < _len4; _l++) {
            fontsize = fontsizes[_l];
            size_list += "
" + fontsize.size + "(" + fontsize.point + "pt)
";
          }
          $('.toolbar_fontsize').after("
" + size_list + "
");
          $('a.fontsize-option').on('click', function() {
            document.execCommand("FontSize", false, $(this).attr('fontsize'));
            $(this).closest('.btn-group').removeClass('open');
            return false;
          });
        }
        if (jQuery.inArray('forecolor', excludes) < 0) {
          $('a.toolbar_forecolor').after("
<input type='text' id='forecolor-input' value='' />

");
          $('#forecolor-picker').farbtastic(function(color) {
            $('#forecolor-input').val(color);
            document.execCommand("forecolor", false, color);
            $(this).closest('.btn-group').removeClass('open');
            $('.toolbar_forecolor div').css({
              "color": color
            });
            return false;
          });
        }
        if (jQuery.inArray('backcolor', excludes) < 0) {
          $('a.toolbar_bgcolor').after("
<input type='text' id='bgcolor-input' value='' />

");
          $('#bgcolor-picker').farbtastic(function(color) {
            $('#bgcolor-input').val(color);
            document.execCommand("backcolor", false, color);
            $(this).closest('.btn-group').removeClass('open');
            $('.toolbar_bgcolor div').css({
              "background-color": color
            });
            return false;
          });
        }
        $(this).on('focus', function() {
          var $this;
          $this = $(this);
          $this.data('before', $this.html());
          return $this;
        }).on('blur keyup paste', function() {
          var $this;
          $this = $(this);
          if ($this.data('before') !== $this.html()) {
            $this.data('before', $this.html());
            $this.trigger('change');
          }
          return $this;
        });
        $("a.toolbar-cmd").on('click', function() {
          var ceNode, cmd, dummy, range;
          cmd = $(this).attr('command');
          if ($(this).attr('userinput') === 'yes') {
            methods[cmd].apply(this);
          } else if ($(this).attr('block')) {
            methods['formatblock'].apply(this, ["<" + ($(this).attr('block')) + ">"]);
          } else {
            if ((cmd === 'justifyright') || (cmd === 'justifyleft') || (cmd === 'justifycenter') || (cmd === 'justifyfull')) {
              try {
                document.execCommand(cmd, false, null);
              } catch (e) {
                if (e && e.result === 2147500037) {
                  range = window.getSelection().getRangeAt(0);
                  dummy = document.createElement('br');
                  ceNode = range.startContainer.parentNode;
                  while ((ceNode != null) && ceNode.contentEditable !== 'true') {
                    ceNode = ceNode.parentNode;
                  }
                  if (!ceNode) {
                    throw 'Selected node is not editable!';
                  }
                  ceNode.insertBefore(dummy, ceNode.childNodes[0]);
                  document.execCommand(cmd, false, null);
                  dummy.parentNode.removeChild(dummy);
                } else if (console && console.log) {
                  console.log(e);
                }
              }
            } else {
              document.execCommand(cmd, false, null);
            }
          }
          return false;
        });
        shortcuts = [
          {
            keys: 'Ctrl+l',
            method: function() {
              return methods.createlink.apply(this);
            }
          }, {
            keys: 'Ctrl+g',
            method: function() {
              return methods.insertimage.apply(this);
            }
          }, {
            keys: 'Ctrl+Alt+U',
            method: function() {
              return document.execCommand('insertunorderedlist', false, null);
            }
          }, {
            keys: 'Ctrl+Alt+O',
            method: function() {
              return document.execCommand('insertorderedlist', false, null);
            }
          }, {
            keys: 'Ctrl+q',
            method: function() {
              return methods.formatblock.apply(this, ["
"]);
            }
          }, {
            keys: 'Ctrl+Alt+k',
            method: function() {
              return methods.formatblock.apply(this, ["
"]);
            }
          }, {
            keys: 'Ctrl+.',
            method: function() {
              return document.execCommand('superscript', false, null);
            }
          }, {
            keys: 'Ctrl+Shift+.',
            method: function() {
              return document.execCommand('subscript', false, null);
            }
          }, {
            keys: 'Ctrl+Alt+0',
            method: function() {
              return methods.formatblock.apply(this, ["p"]);
            }
          }, {
            keys: 'Ctrl+b',
            method: function() {
              return document.execCommand('bold', false, null);
            }
          }, {
            keys: 'Ctrl+i',
            method: function() {
              return document.execCommand('italic', false, null);
            }
          }, {
            keys: 'Ctrl+Alt+1',
            method: function() {
              return methods.formatblock.apply(this, ["H1"]);
            }
          }, {
            keys: 'Ctrl+Alt+2',
            method: function() {
              return methods.formatblock.apply(this, ["H2"]);
            }
          }, {
            keys: 'Ctrl+Alt+3',
            method: function() {
              return methods.formatblock.apply(this, ["H3"]);
            }
          }, {
            keys: 'Ctrl+Alt+4',
            method: function() {
              return methods.formatblock.apply(this, ["H4"]);
            }
          }, {
            keys: 'Ctrl+m',
            method: function() {
              return document.execCommand("removeFormat", false, null);
            }
          }, {
            keys: 'Ctrl+u',
            method: function() {
              return document.execCommand('underline', false, null);
            }
          }, {
            keys: 'tab',
            method: function() {
              return document.execCommand('indent', false, null);
            }
          }, {
            keys: 'Ctrl+tab',
            method: function() {
              return document.execCommand('indent', false, null);
            }
          }, {
            keys: 'Shift+tab',
            method: function() {
              return document.execCommand('outdent', false, null);
            }
          }
        ];
        $.each(shortcuts, function(index, elem) {
          return shortcut.add(elem.keys, function() {
            elem.method();
            return false;
          }, {
            'type': 'keydown',
            'propagate': false
          });
        });
        return this.each(function() {
          var $this, data, tooltip;
          $this = $(this);
          data = $this.data('fresheditor');
          tooltip = $('
', {
            text: $this.attr('title')
          });
          if (!data) {
            return $(this).data('fresheditor', {
              target: $this,
              tooltip: tooltip
            });
          }
        });
      }
    };
    return $.fn.freshereditor = function(method) {
      if (methods[method]) {
        methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
      } else if (typeof method === 'object' || !method) {
        methods.init.apply(this, arguments);
      } else {
        $.error('Method ' + method + ' does not exist on jQuery.contentEditable');
      }
    };
  })(jQuery);
}).call(this);


text:
@interface ASLViewController ()

@property (weak, nonatomic) IBOutlet CBAutoScrollLabel *autoScrollLabel;
@property (weak, nonatomic) IBOutlet CBAutoScrollLabel *navigationBarScrollLabel;

@end

@implementation ASLViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // setup the auto scroll label
    self.autoScrollLabel.text = @"This text may be clipped, but now it will be scrolled. This text will be scrolled even after device rotation.";
    self.autoScrollLabel.textColor = [UIColor blueColor];
    self.autoScrollLabel.labelSpacing = 30; // distance between start and end labels
    self.autoScrollLabel.pauseInterval = 1.7; // seconds of pause before scrolling starts again
    self.autoScrollLabel.scrollSpeed = 30; // pixels per second
    self.autoScrollLabel.textAlignment = NSTextAlignmentCenter; // centers text when no auto-scrolling is applied
    self.autoScrollLabel.fadeLength = 12.f;
    self.autoScrollLabel.scrollDirection = CBAutoScrollDirectionLeft;
    [self.autoScrollLabel observeApplicationNotifications];

    // navigation bar auto scroll label
    self.navigationBarScrollLabel.text = @"Navigation Bar Title... Scrolling... And scrolling.";
    self.navigationBarScrollLabel.pauseInterval = 3.f;
    self.navigationBarScrollLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationBarScrollLabel.textColor = [UIColor blackColor];
    [self.navigationBarScrollLabel observeApplicationNotifications];
}

@end

redpajama_set_name: RedPajamaGithub


text:
class DhQGraphicsScene : public DynamicQHandler, public QGraphicsScene
{
private:
  static QHash<QByteArray, int> initXhHash();
  static QHash<QByteArray, int> xhHash;
public:
  bool setDynamicQHandler(void * ro_ptr, char * eventId, void * rf_ptr, void * st_ptr, void * df_ptr);
  bool unSetDynamicQHandler(char * eventId);
  bool setDynamicQHandlerud(int udtyp, void * ro_ptr, int eventId, void * rf_ptr, void * st_ptr, void * df_ptr);
  bool unSetDynamicQHandlerud(int udtyp, int eventId);
  void userDefined(int x1) const;
  QVariant* userDefinedVariant(int x1, QVariant* x2) const;
  explicit DhQGraphicsScene() : DynamicQHandler(), QGraphicsScene() {};
  explicit DhQGraphicsScene(const QRectF& x1) : DynamicQHandler(), QGraphicsScene(x1) {};
  explicit DhQGraphicsScene(QObject* x1) : DynamicQHandler(), QGraphicsScene(x1) {};
  explicit DhQGraphicsScene(const QRectF& x1, QObject* x2) : DynamicQHandler(), QGraphicsScene(x1, x2) {};
  explicit DhQGraphicsScene(qreal x1, qreal x2, qreal x3, qreal x4) : DynamicQHandler(), QGraphicsScene(x1, x2, x3, x4) {};
  explicit DhQGraphicsScene(qreal x1, qreal x2, qreal x3, qreal x4, QObject* x5) : DynamicQHandler(), QGraphicsScene(x1, x2, x3, x4, x5) {};
  void contextMenuEvent(QGraphicsSceneContextMenuEvent* x1);
  void DhcontextMenuEvent(QGraphicsSceneContextMenuEvent* x1);
  void DvhcontextMenuEvent(QGraphicsSceneContextMenuEvent* x1);
  void dragEnterEvent(QGraphicsSceneDragDropEvent* x1);
  void DhdragEnterEvent(QGraphicsSceneDragDropEvent* x1);
  void DvhdragEnterEvent(QGraphicsSceneDragDropEvent* x1);
  void dragLeaveEvent(QGraphicsSceneDragDropEvent* x1);
  void DhdragLeaveEvent(QGraphicsSceneDragDropEvent* x1);
  void DvhdragLeaveEvent(QGraphicsSceneDragDropEvent* x1);
  void dragMoveEvent(QGraphicsSceneDragDropEvent* x1);
  void DhdragMoveEvent(QGraphicsSceneDragDropEvent* x1);
  void DvhdragMoveEvent(QGraphicsSceneDragDropEvent* x1);
  void drawBackground(QPainter* x1, const QRectF& x2);
  void DhdrawBackground(QPainter* x1, const QRectF& x2);
  void DvhdrawBackground(QPainter* x1, const QRectF& x2);
  void drawForeground(QPainter* x1, const QRectF& x2);
  void DhdrawForeground(QPainter* x1, const QRectF& x2);
  void DvhdrawForeground(QPainter* x1, const QRectF& x2);
  void drawItems(QPainter* x1, int x2, QGraphicsItem** x3, QStyleOptionGraphicsItem* x4);
  void DhdrawItems(QPainter* x1, int x2, QGraphicsItem** x3, QStyleOptionGraphicsItem* x4);
  void DvhdrawItems(QPainter* x1, int x2, QGraphicsItem** x3, QStyleOptionGraphicsItem* x4);
  void drawItems(QPainter* x1, int x2, QGraphicsItem** x3, QStyleOptionGraphicsItem* x4, QWidget* x5);
  void DhdrawItems(QPainter* x1, int x2, QGraphicsItem** x3, QStyleOptionGraphicsItem* x4, QWidget* x5);
  void DvhdrawItems(QPainter* x1, int x2, QGraphicsItem** x3, QStyleOptionGraphicsItem* x4, QWidget* x5);
  void dropEvent(QGraphicsSceneDragDropEvent* x1);
  void DhdropEvent(QGraphicsSceneDragDropEvent* x1);
  void DvhdropEvent(QGraphicsSceneDragDropEvent* x1);
  bool event(QEvent* x1);
  bool Dhevent(QEvent* x1);
  bool Dvhevent(QEvent* x1);
  void focusInEvent(QFocusEvent* x1);
  void DhfocusInEvent(QFocusEvent* x1);
  void DvhfocusInEvent(QFocusEvent* x1);
  void focusOutEvent(QFocusEvent* x1);
  void DhfocusOutEvent(QFocusEvent* x1);
  void DvhfocusOutEvent(QFocusEvent* x1);
  void helpEvent(QGraphicsSceneHelpEvent* x1);
  void DhhelpEvent(QGraphicsSceneHelpEvent* x1);
  void DvhhelpEvent(QGraphicsSceneHelpEvent* x1);
  void inputMethodEvent(QInputMethodEvent* x1);
  void DhinputMethodEvent(QInputMethodEvent* x1);
  void DvhinputMethodEvent(QInputMethodEvent* x1);
  QVariant inputMethodQuery(Qt::InputMethodQuery x1) const;
  QVariant DhinputMethodQuery(long x1) const;
  QVariant DvhinputMethodQuery(long x1) const;
  void keyPressEvent(QKeyEvent* x1);
  void DhkeyPressEvent(QKeyEvent* x1);
  void DvhkeyPressEvent(QKeyEvent* x1);
  void keyReleaseEvent(QKeyEvent* x1);
  void DhkeyReleaseEvent(QKeyEvent* x1);
  void DvhkeyReleaseEvent(QKeyEvent* x1);
  void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* x1);
  void DhmouseDoubleClickEvent(QGraphicsSceneMouseEvent* x1);
  void DvhmouseDoubleClickEvent(QGraphicsSceneMouseEvent* x1);
  void mouseMoveEvent(QGraphicsSceneMouseEvent* x1);
  void DhmouseMoveEvent(QGraphicsSceneMouseEvent* x1);
  void DvhmouseMoveEvent(QGraphicsSceneMouseEvent* x1);
  void mousePressEvent(QGraphicsSceneMouseEvent* x1);
  void DhmousePressEvent(QGraphicsSceneMouseEvent* x1);
  void DvhmousePressEvent(QGraphicsSceneMouseEvent* x1);
  void mouseReleaseEvent(QGraphicsSceneMouseEvent* x1);
  void DhmouseReleaseEvent(QGraphicsSceneMouseEvent* x1);
  void DvhmouseReleaseEvent(QGraphicsSceneMouseEvent* x1);
  void wheelEvent(QGraphicsSceneWheelEvent* x1);
  void DhwheelEvent(QGraphicsSceneWheelEvent* x1);
  void DvhwheelEvent(QGraphicsSceneWheelEvent* x1);
  ~DhQGraphicsScene(){}
  void childEvent(QChildEvent* x1);
  void DhchildEvent(QChildEvent* x1);
  void DvhchildEvent(QChildEvent* x1);
  void connectNotify(const char* x1);
  void DhconnectNotify(const char* x1);
  void DvhconnectNotify(const char* x1);
  void customEvent(QEvent* x1);
  void DhcustomEvent(QEvent* x1);
  void DvhcustomEvent(QEvent* x1);
  void disconnectNotify(const char* x1);
  void DhdisconnectNotify(const char* x1);
  void DvhdisconnectNotify(const char* x1);
  bool eventFilter(QObject* x1, QEvent* x2);
  bool DheventFilter(QObject* x1, QEvent* x2);
  bool DvheventFilter(QObject* x1, QEvent* x2);
  int receivers(const char* x1) const;
  int Dhreceivers(const char* x1) const;
  int Dvhreceivers(const char* x1) const;
  QObject* sender() const;
  QObject* Dhsender() const;
  QObject* Dvhsender() const;
  void timerEvent(QTimerEvent* x1);
  void DhtimerEvent(QTimerEvent* x1);
  void DvhtimerEvent(QTimerEvent* x1);
};


text:
#include <grpc/byte_buffer.h>
#include <grpc/byte_buffer_reader.h>
#include <grpc/grpc.h>
#include <grpc/slice.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>

#include "src/core/lib/compression/message_compress.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "test/core/util/test_config.h"

#include <string.h>

#define LOG_TEST(x) gpr_log(GPR_INFO, "%s", x)

static void test_read_one_slice(void) {
  grpc_slice slice;
  grpc_byte_buffer* buffer;
  grpc_byte_buffer_reader reader;
  grpc_slice first_slice, second_slice;
  int first_code, second_code;

  LOG_TEST("test_read_one_slice");
  slice = grpc_slice_from_copied_string("test");
  buffer = grpc_raw_byte_buffer_create(&slice, 1);
  grpc_slice_unref(slice);
  GPR_ASSERT(grpc_byte_buffer_reader_init(&reader, buffer) &&
             "Couldn't init byte buffer reader");
  first_code = grpc_byte_buffer_reader_next(&reader, &first_slice);
  GPR_ASSERT(first_code != 0);
  GPR_ASSERT(memcmp(GRPC_SLICE_START_PTR(first_slice), "test", 4) == 0);
  grpc_slice_unref(first_slice);
  second_code = grpc_byte_buffer_reader_next(&reader, &second_slice);
  GPR_ASSERT(second_code == 0);
  grpc_byte_buffer_destroy(buffer);
}

static void test_read_one_slice_malloc(void) {
  grpc_slice slice;
  grpc_byte_buffer* buffer;
  grpc_byte_buffer_reader reader;
  grpc_slice first_slice, second_slice;
  int first_code, second_code;

  LOG_TEST("test_read_one_slice_malloc");
  slice = grpc_slice_malloc(4);
  memcpy(GRPC_SLICE_START_PTR(slice), "test", 4);
  buffer = grpc_raw_byte_buffer_create(&slice, 1);
  grpc_slice_unref(slice);
  GPR_ASSERT(grpc_byte_buffer_reader_init(&reader, buffer) &&
             "Couldn't init byte buffer reader");
  first_code = grpc_byte_buffer_reader_next(&reader, &first_slice);
  GPR_ASSERT(first_code != 0);
  GPR_ASSERT(memcmp(GRPC_SLICE_START_PTR(first_slice), "test", 4) == 0);
  grpc_slice_unref(first_slice);
  second_code = grpc_byte_buffer_reader_next(&reader, &second_slice);
  GPR_ASSERT(second_code == 0);
  grpc_byte_buffer_destroy(buffer);
}

static void test_read_none_compressed_slice(void) {
  grpc_slice slice;
  grpc_byte_buffer* buffer;
  grpc_byte_buffer_reader reader;
  grpc_slice first_slice, second_slice;
  int first_code, second_code;

  LOG_TEST("test_read_none_compressed_slice");
  slice = grpc_slice_from_copied_string("test");
  buffer = grpc_raw_byte_buffer_create(&slice, 1);
  grpc_slice_unref(slice);
  GPR_ASSERT(grpc_byte_buffer_reader_init(&reader, buffer) &&
             "Couldn't init byte buffer reader");
  first_code = grpc_byte_buffer_reader_next(&reader, &first_slice);
  GPR_ASSERT(first_code != 0);
  GPR_ASSERT(memcmp(GRPC_SLICE_START_PTR(first_slice), "test", 4) == 0);
  grpc_slice_unref(first_slice);
  second_code = grpc_byte_buffer_reader_next(&reader, &second_slice);
  GPR_ASSERT(second_code == 0);
  grpc_byte_buffer_destroy(buffer);
}

static void test_read_corrupted_slice(void) {
  grpc_slice slice;
  grpc_byte_buffer* buffer;
  grpc_byte_buffer_reader reader;

  LOG_TEST("test_read_corrupted_slice");
  slice = grpc_slice_from_copied_string("test");
  buffer = grpc_raw_byte_buffer_create(&slice, 1);
  buffer->data.raw.compression = GRPC_COMPRESS_GZIP; /* lies! */
  grpc_slice_unref(slice);
  GPR_ASSERT(!grpc_byte_buffer_reader_init(&reader, buffer));
  grpc_byte_buffer_destroy(buffer);
}

static void read_compressed_slice(grpc_compression_algorithm algorithm,
                                  size_t input_size) {
  grpc_slice input_slice;
  grpc_slice_buffer sliceb_in;
  grpc_slice_buffer sliceb_out;
  grpc_byte_buffer* buffer;
  grpc_byte_buffer_reader reader;
  grpc_slice read_slice;
  size_t read_count = 0;

  grpc_slice_buffer_init(&sliceb_in);
  grpc_slice_buffer_init(&sliceb_out);

  input_slice = grpc_slice_malloc(input_size);
  memset(GRPC_SLICE_START_PTR(input_slice), 'a', input_size);
  grpc_slice_buffer_add(&sliceb_in, input_slice); /* takes ownership */
  {
    grpc_core::ExecCtx exec_ctx;
    GPR_ASSERT(grpc_msg_compress(algorithm, &sliceb_in, &sliceb_out));
  }

  buffer = grpc_raw_compressed_byte_buffer_create(sliceb_out.slices,
                                                  sliceb_out.count, algorithm);
  GPR_ASSERT(grpc_byte_buffer_reader_init(&reader, buffer) &&
             "Couldn't init byte buffer reader");

  while (grpc_byte_buffer_reader_next(&reader, &read_slice)) {
    GPR_ASSERT(memcmp(GRPC_SLICE_START_PTR(read_slice),
                      GRPC_SLICE_START_PTR(input_slice) + read_count,
                      GRPC_SLICE_LENGTH(read_slice)) == 0);
    read_count += GRPC_SLICE_LENGTH(read_slice);
    grpc_slice_unref(read_slice);
  }
  GPR_ASSERT(read_count == input_size);
  grpc_byte_buffer_reader_destroy(&reader);
  grpc_byte_buffer_destroy(buffer);
  grpc_slice_buffer_destroy(&sliceb_out);
  grpc_slice_buffer_destroy(&sliceb_in);
}

static void test_read_gzip_compressed_slice(void) {
  const size_t INPUT_SIZE = 2048;
  LOG_TEST("test_read_gzip_compressed_slice");
  read_compressed_slice(GRPC_COMPRESS_GZIP, INPUT_SIZE);
}

static void test_read_deflate_compressed_slice(void) {
  const size_t INPUT_SIZE = 2048;
  LOG_TEST("test_read_deflate_compressed_slice");
  read_compressed_slice(GRPC_COMPRESS_DEFLATE, INPUT_SIZE);
}

static void test_byte_buffer_from_reader(void) {
  grpc_slice slice;
  grpc_byte_buffer *buffer, *buffer_from_reader;
  grpc_byte_buffer_reader reader;

  LOG_TEST("test_byte_buffer_from_reader");
  slice = grpc_slice_malloc(4);
  memcpy(GRPC_SLICE_START_PTR(slice), "test", 4);
  buffer = grpc_raw_byte_buffer_create(&slice, 1);
  grpc_slice_unref(slice);
  GPR_ASSERT(grpc_byte_buffer_reader_init(&reader, buffer) &&
             "Couldn't init byte buffer reader");

  buffer_from_reader = grpc_raw_byte_buffer_from_reader(&reader);
  GPR_ASSERT(buffer->type == buffer_from_reader->type);
  GPR_ASSERT(buffer_from_reader->data.raw.compression == GRPC_COMPRESS_NONE);
  GPR_ASSERT(buffer_from_reader->data.raw.slice_buffer.count == 1);
  GPR_ASSERT(memcmp(GRPC_SLICE_START_PTR(
                        buffer_from_reader->data.raw.slice_buffer.slices[0]),
                    "test", 4) == 0);

  grpc_byte_buffer_destroy(buffer);
  grpc_byte_buffer_destroy(buffer_from_reader);
}

static void test_readall(void) {
  char* lotsa_as[512];
  char* lotsa_bs[1024];
  grpc_slice slices[2];
  grpc_byte_buffer* buffer;
  grpc_byte_buffer_reader reader;
  grpc_slice slice_out;

  LOG_TEST("test_readall");

  memset(lotsa_as, 'a', 512);
  memset(lotsa_bs, 'b', 1024);
  /* use slices large enough to overflow inlining */
  slices[0] = grpc_slice_malloc(512);
  memcpy(GRPC_SLICE_START_PTR(slices[0]), lotsa_as, 512);
  slices[1] = grpc_slice_malloc(1024);
  memcpy(GRPC_SLICE_START_PTR(slices[1]), lotsa_bs, 1024);

  buffer = grpc_raw_byte_buffer_create(slices, 2);
  grpc_slice_unref(slices[0]);
  grpc_slice_unref(slices[1]);

  GPR_ASSERT(grpc_byte_buffer_reader_init(&reader, buffer) &&
             "Couldn't init byte buffer reader");
  slice_out = grpc_byte_buffer_reader_readall(&reader);

  GPR_ASSERT(GRPC_SLICE_LENGTH(slice_out) == 512 + 1024);
  GPR_ASSERT(memcmp(GRPC_SLICE_START_PTR(slice_out), lotsa_as, 512) == 0);
  GPR_ASSERT(memcmp(&(GRPC_SLICE_START_PTR(slice_out)[512]), lotsa_bs, 1024) ==
             0);
  grpc_slice_unref(slice_out);
  grpc_byte_buffer_destroy(buffer);
}

static void test_byte_buffer_copy(void) {
  char* lotsa_as[512];
  char* lotsa_bs[1024];
  grpc_slice slices[2];
  grpc_byte_buffer* buffer;
  grpc_byte_buffer* copied_buffer;
  grpc_byte_buffer_reader reader;
  grpc_slice slice_out;

  LOG_TEST("test_byte_buffer_copy");

  memset(lotsa_as, 'a', 512);
  memset(lotsa_bs, 'b', 1024);
  /* use slices large enough to overflow inlining */
  slices[0] = grpc_slice_malloc(512);
  memcpy(GRPC_SLICE_START_PTR(slices[0]), lotsa_as, 512);
  slices[1] = grpc_slice_malloc(1024);
  memcpy(GRPC_SLICE_START_PTR(slices[1]), lotsa_bs, 1024);

  buffer = grpc_raw_byte_buffer_create(slices, 2);
  grpc_slice_unref(slices[0]);
  grpc_slice_unref(slices[1]);
  copied_buffer = grpc_byte_buffer_copy(buffer);

  GPR_ASSERT(grpc_byte_buffer_reader_init(&reader, buffer) &&
             "Couldn't init byte buffer reader");
  slice_out = grpc_byte_buffer_reader_readall(&reader);

  GPR_ASSERT(GRPC_SLICE_LENGTH(slice_out) == 512 + 1024);
  GPR_ASSERT(memcmp(GRPC_SLICE_START_PTR(slice_out), lotsa_as, 512) == 0);
  GPR_ASSERT(memcmp(&(GRPC_SLICE_START_PTR(slice_out)[512]), lotsa_bs, 1024) ==
             0);
  grpc_slice_unref(slice_out);
  grpc_byte_buffer_destroy(buffer);
  grpc_byte_buffer_destroy(copied_buffer);
}

int main(int argc, char** argv) {
  grpc_test_init(argc, argv);
  grpc_init();
  test_read_one_slice();
  test_read_one_slice_malloc();
  test_read_none_compressed_slice();
  test_read_gzip_compressed_slice();
  test_read_deflate_compressed_slice();
  test_read_corrupted_slice();
  test_byte_buffer_from_reader();
  test_byte_buffer_copy();
  test_readall();
  grpc_shutdown();
  return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestyDroid
{
    public interface IProcess
    {
        string FileName { get; }
        string Arguments { get; }
        void Start(string args = null);
        void Stop();
        bool IsRunning { get; }
        void ListenToStandardOut(Action<string> onStdOutReceived);
        void ListenToStandardError(Action<string> onStdErrorReceived);
        int WaitForExit();
    }
}


text:
# Logarithm of Cumulative Distribution Function

> [Laplace][laplace-distribution] distribution logarithm of [cumulative distribution function][cdf].

The [cumulative distribution function][cdf] for a [Laplace][laplace-distribution] random variable is

where `mu` is the location parameter and `b > 0` is the scale parameter.

## Usage

```javascript
var logcdf = require( '@stdlib/stats/base/dists/laplace/logcdf' );
```

#### logcdf( x, mu, b )

Evaluates the logarithm of the [cumulative distribution function][cdf] (CDF) for a [Laplace][laplace-distribution] distribution with parameters `mu` (location parameter) and `b > 0` (scale parameter).

```javascript
var y = logcdf( 2.0, 0.0, 1.0 );
// returns ~-0.07

y = logcdf( 5.0, 10.0, 3.0 );
// returns ~-2.36
```

If provided `NaN` as any argument, the function returns `NaN`.

```javascript
var y = logcdf( NaN, 0.0, 1.0 );
// returns NaN

y = logcdf( 0.0, NaN, 1.0 );
// returns NaN

y = logcdf( 0.0, 0.0, NaN );
// returns NaN
```

If provided `b <= 0`, the function returns `NaN`.

```javascript
var y = logcdf( 2.0, 0.0, -1.0 );
// returns NaN

y = logcdf( 2.0, 0.0, 0.0 );
// returns NaN
```

#### logcdf.factory( mu, b )

Returns a function for evaluating the logarithm of the [cumulative distribution function][cdf] of a [Laplace][laplace-distribution] distribution with parameters `mu` (location parameter) and `b > 0` (scale parameter).

```javascript
var mylogcdf = logcdf.factory( 3.0, 1.5 );

var y = mylogcdf( 1.0 );
// returns ~-2.026

y = mylogcdf( 4.0 );
// returns ~-0.297
```

## Notes

-   In virtually all cases, using the `logpdf` or `logcdf` functions is preferable to manually computing the logarithm of the `pdf` or `cdf`, respectively, since the latter is prone to overflow and underflow.

## Examples

```javascript
var randu = require( '@stdlib/random/base/randu' );
var logcdf = require( '@stdlib/stats/base/dists/laplace/logcdf' );

var mu;
var b;
var x;
var y;
var i;

for ( i = 0; i < 100; i++ ) {
    x = randu() * 10.0;
    mu = randu() * 10.0;
    b = randu() * 10.0;
    y = logcdf( x, mu, b );
    console.log( 'x: %d, µ: %d, b: %d, ln(F(x;µ,b)): %d', x.toFixed( 4 ), mu.toFixed( 4 ), b.toFixed( 4 ), y.toFixed( 4 ) );
}
```

[cdf]: https://en.wikipedia.org/wiki/Cumulative_distribution_function

[laplace-distribution]: https://en.wikipedia.org/wiki/Laplace_distribution


text:
#ifndef VARIABLES_H
#define VARIABLES_H

#include "cutil.h"
#include "oldlist.h"

/*----------------------------------------------------------------------
              T y p e s
----------------------------------------------------------------------*/
typedef union
{
  float float_part;
  int int_part;
  void *ptr_part;
  const char *char_part;
} VALUE;

class VARIABLE;

typedef void (*variables_io) (VARIABLE * variable, char *string);

class VARIABLE
{
  public:
    void *address;
    const char *string;
    VALUE default_value;
    variables_io type_reader;
    variables_io type_writer;
};

extern VALUE dummy;              /* Needed for macros */

/*----------------------------------------------------------------------
              M a c r o s
----------------------------------------------------------------------*/
/* 	To hide variable names for relase to UNLV DONT put the variable names in
  the executable: Toggle be either defining or not defining SECURE_NAMES*/
/* #define SECURE_NAMES defined in secnames.h when necessary */
#ifdef SECURE_NAMES
/**********************************************************************
 * float_variable
 *
 * Create a floating point variable that can be read and written from
 * a configuration file.
 **********************************************************************/

#define float_variable(name,string,default)                \
dummy.float_part = default;                              \
add_32bit_variable (&name, "", dummy, float_read, float_write)

/**********************************************************************
 * string_variable
 *
 * Create a string point variable that can be read and written from
 * a configuration file.
 **********************************************************************/

#define string_variable(name,string,default)              \
dummy.char_part = default;                    \
add_ptr_variable (&name, "", dummy, string_read, string_write)

/**********************************************************************
 * int_variable
 *
 * Create a int point variable that can be read and written from
 * a configuration file.
 **********************************************************************/

#define int_variable(name,string,default)                 \
dummy.int_part = default;                              \
add_32bit_variable (&name, "", dummy, int_read, int_write)

#else
/**********************************************************************
 * float_variable
 *
 * Create a floating point variable that can be read and written from
 * a configuration file.
 **********************************************************************/

#define float_variable(name,string,default)                \
dummy.float_part = default;                              \
add_32bit_variable (&name, string, dummy, float_read, float_write)

/**********************************************************************
 * string_variable
 *
 * Create a string point variable that can be read and written from
 * a configuration file.
 **********************************************************************/

#define string_variable(name,string,default)              \
dummy.char_part = default;                    \
add_ptr_variable (&name, string, dummy, string_read, string_write)

/**********************************************************************
 * int_variable
 *
 * Create a int point variable that can be read and written from
 * a configuration file.
 **********************************************************************/

#define int_variable(name,string,default)                 \
dummy.int_part = default;                              \
add_32bit_variable (&name, string, dummy, int_read, int_write)
#endif

/*--------------------------------------------------------------------------
        Public Function Prototoypes
----------------------------------------------------------------------------*/
void free_variables();

void add_ptr_variable(void *address,
                      const char *string,
                      VALUE default_value,
                      variables_io reader,
                      variables_io writer);

void add_32bit_variable(void *address,
                        const char *string,
                        VALUE default_value,
                        variables_io reader,
                        variables_io writer);

void float_read(VARIABLE *variable, char *string);

void float_write(VARIABLE *variable, char *string);

void int_read(VARIABLE *variable, char *string);

void int_write(VARIABLE *variable, char *string);

void read_variables(const char *filename);

bool set_old_style_variable(const char* variable, const char* value);

int same_var_name(void *item1,   //VARIABLE *variable,
                  void *item2);  //char     *string)

void string_read(VARIABLE *variable, char *string);

void string_write(VARIABLE *variable, char *string);

char *strip_line(char *string);
#endif


text:
#ifndef REGEXMACROS_INCLUDED
#define REGEXMACROS_INCLUDED

#ifdef USE_BOOST_REGEX
#include <boost/regex.hpp>
using namespace boost;
#else
#include <regex>
using namespace std;
#endif

// POSIX basic regular expressions are used for maximum compatibility,
// since g++ does not stably support ECMAScript regexes yet,
// so we resort to boost where clang is not available
// (e.g. Amazon EC2 AMI/yum, at time of writing: 8/25/2015).

// These macros use an ultra-minimal subset of POSIX basic syntax:
// character classes [], ranges a-z, repetition *, wildcards ., groups \\( \\)
// NB literal hyphens must appear at the start of a character class.

#define RE_CHAR_CLASS(STR) "[" STR "]"
#define RE_STAR(CLASS) CLASS "*"
#define RE_PLUS(CLASS) CLASS RE_STAR(CLASS)
#define RE_GROUP(EXPR) "\\(" EXPR "\\)"

#define RE_NUMERIC_RANGE "0-9"
#define RE_ALPHA_RANGE "A-Za-z"
#define RE_ALPHANUM_RANGE RE_ALPHA_RANGE RE_NUMERIC_RANGE
#define RE_NONWHITE_RANGE "!-~"
#define RE_PRINTABLE_RANGE " -~"

#define RE_NUMERIC_CHAR_CLASS RE_CHAR_CLASS(RE_NUMERIC_RANGE)
#define RE_VARNAME_CHAR_CLASS RE_CHAR_CLASS(RE_ALPHANUM_RANGE "_")
#define RE_DNS_CHAR_CLASS RE_CHAR_CLASS("-" RE_ALPHANUM_RANGE "\\.")
#define RE_FLOAT_CHAR_CLASS RE_CHAR_CLASS("-" RE_NUMERIC_RANGE "eE+\\.")
#define RE_NONWHITE_CHAR_CLASS RE_CHAR_CLASS(RE_NONWHITE_RANGE)
#define RE_DOT RE_CHAR_CLASS(RE_PRINTABLE_RANGE)

#define RE_DOT_STAR RE_DOT "*"
#define RE_DOT_PLUS RE_PLUS(RE_DOT)

#define RE_NUMERIC_GROUP RE_GROUP(RE_PLUS(RE_NUMERIC_CHAR_CLASS))
#define RE_VARNAME_GROUP RE_GROUP(RE_PLUS(RE_VARNAME_CHAR_CLASS))
#define RE_DNS_GROUP RE_GROUP(RE_PLUS(RE_DNS_CHAR_CLASS))
#define RE_FLOAT_GROUP RE_GROUP(RE_PLUS(RE_FLOAT_CHAR_CLASS))
#define RE_DOT_GROUP RE_GROUP(RE_PLUS(RE_DOT))

#define RE_WHITE_CHARS " \t\n"
#define RE_WHITE_CHAR_CLASS RE_CHAR_CLASS(RE_WHITE_CHARS)
#define RE_WHITE_OR_EMPTY RE_STAR(RE_WHITE_CHAR_CLASS)
#define RE_WHITE_NONEMPTY RE_PLUS(RE_WHITE_CHAR_CLASS)

#endif /* REGEXMACROS_INCLUDED */


text:
/*eslint-disable*/
/* global keys:true, colorHex, clickButton, maxPlayers, w2, h2, localStorage,
ButtonList, colorHexDark, changingKeys:true, Phaser, defaultKeys */
/*eslint-enable*/
var setKeys = function (game) {
  this.ui = {}
  this.selectedPlayer = 0
  this.buttons = null
  this.playersButton = null
  this.maxPlayers = 7
  this.dialogText = null
  this.previousState = null
  this.gamepadMap = ['A', 'B', 'X', 'Y', 'LB', 'RB', 'LT', 'RT',
                     'BACK', 'START', 'L3', 'R3', 'UP', 'DOWN', 'LEFT', 'RIGHT']
}

setKeys.prototype = {
  init: function (previousState) {
    this.previousState = previousState
  },

  create: function () {
    var ui = this.ui

    ui.title = this.game.add.text(w2, 100, 'configure keys', {
      font: '150px dosis',
      fill: '#ffffff',
      align: 'center'
    })
    ui.title.anchor.setTo(0.5, 0.5)

    this.buttons = new ButtonList(this, this.game)

    this.buttons.add('accept_button', 'confirm', this.backPressed)
    this.playersButton = this.buttons.add(null, '<    player ' + (this.selectedPlayer + 1) + '     >', this.left, this.right)
    this.buttons.add('smallKey_button', 'change', this.change)
    this.buttons.add('restart_button', 'reset', this.reset)
    this.buttons.create()

    ui.keyButton = this.game.add.sprite(w2, h2 + 320, 'key_button')
    ui.keyButton.anchor.setTo(0.5, 0.5)
    ui.keyText = this.game.add.text(w2, h2 + 290, '', {
      font: '150px dosis',
      fill: colorHex,
      align: 'center'
    })
    ui.keyText.anchor.setTo(0.5, 0.5)

    ui.gpText = this.game.add.text(w2, h2 + 425, 'controller 1', {
      font: '40px dosis',
      fill: 'white',
      align: 'center'
    })
    ui.gpText.anchor.setTo(0.5, 0.5)
    ui.gpText.visible = false

    this.updateIcon()

    this.overlay = this.add.sprite(0, 0, 'overlay')
    this.overlay.width = w2 * 2
    this.overlay.height = h2 * 2
    this.overlay.alpha = 0.7
    this.overlay.visible = false

    this.dialogText = this.add.text(w2, h2, '', {
      font: '80px dosis',
      fill: '#ffffff',
      align: 'center'
    })
    this.dialogText.anchor.setTo(0.5, 0.5)
    this.dialogText.visible = false

    this.game.input.keyboard.addCallbacks(this, this.onPressed)
    this.game.input.gamepad.onUpCallback = this.onPressedGamepad.bind(this)
  },

  update: function () {
    if (!changingKeys) {
      this.buttons.update()
    }
  },

  left: function () {
    if (this.selectedPlayer === 0) {
      this.selectedPlayer = this.maxPlayers
    } else {
      this.selectedPlayer--
    }
    this.playersButton.setText('<    player ' + (this.selectedPlayer + 1) + '     >')
    this.updateIcon()
  },

  right: function () {
    if (this.selectedPlayer === this.maxPlayers) {
      this.selectedPlayer = 0
    } else {
      this.selectedPlayer++
    }
    this.playersButton.setText('<    player ' + (this.selectedPlayer + 1) + '     >')
    this.updateIcon()
  },

  up: function () {
    this.buttons.selectUp()
  },

  down: function () {
    this.buttons.selectDown()
  },

  selectPress: function () {
    this.buttons.selectPress()
  },

  selectRelease: function () {
    this.buttons.selectRelease()
  },

  backPressed: function () {
    if (changingKeys) this.hideDialog()
    else {
      localStorage['keys'] = JSON.stringify(keys)
      this.game.state.start(this.previousState)
    }
  },

  onPressed: function () {
    if (changingKeys &&
      this.game.input.keyboard.lastKey.keyCode >= 48 &&
      this.game.input.keyboard.lastKey.keyCode <= 90) {
      keys[this.selectedPlayer] = this.game.input.keyboard.lastKey.keyCode + ''
      this.setKeyboardIcon()
      this.hideDialog()
    }
  },

  onPressedGamepad: function (button, gamepad) {
    if (changingKeys && button !== Phaser.Gamepad.XBOX360_START) {
      keys[this.selectedPlayer] = (gamepad + 1) + ',' + button
      this.setGamepadIcon()
      this.hideDialog()
    }
  },

  updateIcon: function () {
    if (keys[this.selectedPlayer].indexOf(',') === -1) {
      this.setKeyboardIcon()
    } else {
      this.setGamepadIcon()
    }
  },

  setGamepadIcon: function () {
    this.ui.keyButton.loadTexture('gp_button')
    var player = keys[this.selectedPlayer].split(',')[0]
    var button = keys[this.selectedPlayer].split(',')[1]
    var buttonName = this.gamepadMap[button]
    this.ui.keyText.setText(buttonName)
    this.ui.keyText.scale.set(1 / (buttonName.length))
    this.ui.gpText.visible = true
    this.ui.gpText.text = 'gamepad ' + player
  },

  setKeyboardIcon: function () {
    this.ui.keyButton.loadTexture('key_button')
    this.ui.keyText.setText(String.fromCharCode(keys[this.selectedPlayer]))
    this.ui.keyText.scale.set(1)
    this.ui.gpText.visible = false
  },

  change: function () {
    this.showDialog('press the desired key for player ' + (this.selectedPlayer + 1))
  },

  reset: function () {
    keys = defaultKeys.slice() // copy array
    this.ui.keyText.setText(String.fromCharCode(keys[this.selectedPlayer]))
  },

  showDialog: function (text) {
    this.game.input.mouse.enabled = false
    this.dialogText.text = text
    this.dialogText.visible = true
    this.overlay.visible = true
    changingKeys = true
  },

  hideDialog: function () {
    this.game.input.mouse.enabled = true
    this.dialogText.visible = false
    this.overlay.visible = false
    changingKeys = false
  }
}


text:
require_relative '../../spec_helper'
require_relative '../../../app/models/carto/user_creation'

describe Carto::UserCreation do

  describe 'validation token' do
    include_context 'organization with users helper'

    it 'assigns an enable_account_token if user has not signed up with Google' do
      User.any_instance.stubs(:create_in_central).returns(true)
      User.any_instance.stubs(:enable_remote_db_user).returns(true)
      user_data = FactoryGirl.build(:valid_user)
      user_data.organization = @organization
      user_data.google_sign_in = false

      user_creation = Carto::UserCreation.new_user_signup(user_data)
      user_creation.next_creation_step until user_creation.finished?

      saved_user = Carto::User.order("created_at desc").limit(1).first
      saved_user.enable_account_token.should_not be_nil
    end

    it 'does not assign an enable_account_token if user has signed up with Google' do
      User.any_instance.stubs(:create_in_central).returns(true)
      User.any_instance.stubs(:enable_remote_db_user).returns(true)
      user_data = FactoryGirl.build(:valid_user)
      user_data.organization = @organization
      user_data.google_sign_in = true

      user_creation = Carto::UserCreation.new_user_signup(user_data)
      user_creation.next_creation_step until user_creation.finished?

      saved_user = Carto::User.order("created_at desc").limit(1).first
      saved_user.username.should == user_data.username
      saved_user.enable_account_token.should be_nil
    end

    it 'neither creates a new User nor sends the mail and marks creation as failure if saving fails' do
      Cartodb::Central.stubs(:sync_data_with_cartodb_central?).returns(false)
      User.any_instance.stubs(:save).raises('saving error')

      ::Resque.expects(:enqueue).with(::Resque::UserJobs::Mail::NewOrganizationUser).never

      user_data = FactoryGirl.build(:valid_user)
      user_data.organization = @organization
      user_data.google_sign_in = true

      user_creation = Carto::UserCreation.new_user_signup(user_data)
      user_creation.next_creation_step until user_creation.finished?

      saved_user = Carto::User.where(username: user_data.username).first
      saved_user.should == nil

      user_creation.reload
      user_creation.state.should == 'failure'
    end

    after(:each) do
      Cartodb::Central.stubs(:sync_data_with_cartodb_central?).returns(false)
    end

    it 'neither creates a new User nor sends the mail and marks creation as failure if Central fails' do
      Cartodb::Central.stubs(:sync_data_with_cartodb_central?).returns(true)
      User.any_instance.stubs(:create_in_central).raises('Error on state creating_user_in_central, mark_as_failure: false. Error: Application server responded with http 422: {"errors":["Existing username."]}')

      ::Resque.expects(:enqueue).with(::Resque::UserJobs::Mail::NewOrganizationUser).never

      user_data = FactoryGirl.build(:valid_user)
      user_data.organization = @organization
      user_data.google_sign_in = true

      user_creation = Carto::UserCreation.new_user_signup(user_data)
      user_creation.next_creation_step until user_creation.finished?

      saved_user = Carto::User.where(username: user_data.username).first
      saved_user.should == nil

      user_creation.reload
      user_creation.state.should == 'failure'
    end

    it 'neither creates a new User nor sends the mail and marks creation as failure if Central has a registered user matching username' do
      user = prepare_fake_central_user
      # This tests only matching usernames
      user.email = 'other@whatever.com'

      ::Resque.expects(:enqueue).with(::Resque::UserJobs::Mail::NewOrganizationUser).never

      user.organization = @organization

      user_creation = Carto::UserCreation.new_user_signup(user)
      user_creation.next_creation_step until user_creation.finished?

      Carto::User.where(username: user.username).first.should == nil

      user_creation.reload
      user_creation.state.should == 'failure'
    end

    it 'neither creates a new User nor sends the mail and marks creation as failure if Central has a registered user matching email' do
      user = prepare_fake_central_user
      # This tests only matching emails
      user.username = 'other_whatever'

      ::Resque.expects(:enqueue).with(::Resque::UserJobs::Mail::NewOrganizationUser).never

      user.organization = @organization

      user_creation = Carto::UserCreation.new_user_signup(user)
      user_creation.next_creation_step until user_creation.finished?

      Carto::User.where(username: user.username).first.should == nil

      user_creation.reload
      user_creation.state.should == 'failure'
    end

    it 'neither creates a new User nor sends the mail and marks creation as failure if username es empty' do
      user = prepare_fake_central_user
      # This tests only matching emails
      user.username = nil

      ::Resque.expects(:enqueue).with(::Resque::UserJobs::Mail::NewOrganizationUser).never

      user.organization = @organization

      expect {
        user_creation = Carto::UserCreation.new_user_signup(user)
      }.to raise_error
    end

    def prepare_fake_central_user
      Cartodb::Central.stubs(:sync_data_with_cartodb_central?).returns(true)
      fake_central_client = {}
      fake_central_client.stubs(:create_organization_user).returns(true)
      User.any_instance.stubs(:cartodb_central_client).returns(fake_central_client)
      Cartodb::Central.stubs(:new).returns(fake_central_client)
      user = FactoryGirl.build(:valid_user)
      central_user_data = JSON.parse(user.to_json)
      # Central doesn't return exactly the same attributes, but this is good enough for testing
      Cartodb::Central.any_instance.stubs(:get_user).returns(central_user_data)
      fake_central_client.stubs(:get_user).returns(central_user_data)
      user
    end
  end

  describe 'validation email' do
    include_context 'organization with users helper'

    # INFO : this mail contains validation link
    it 'triggers a ::Resque::UserJobs::Mail::NewOrganizationUser' do
      User.any_instance.stubs(:create_in_central).returns(true)
      User.any_instance.stubs(:enable_remote_db_user).returns(true)
      ::Resque.expects(:enqueue).with(Resque::UserJobs::Mail::NewOrganizationUser, instance_of(String)).once

      user_data = FactoryGirl.build(:valid_user)
      user_data.organization = @organization
      user_data.google_sign_in = false

      user_creation = Carto::UserCreation.new_user_signup(user_data)
      user_creation.next_creation_step until user_creation.finished?
    end

  end

end


text:
Project based on Vue.js 2.x, AdminLTE, Bootstrap 3.x

**avui** is a fully responsive admin template that is forked from [AdminLTE](https://github.com/almasaeed2010/AdminLTE). The difference here is that this repo is tailored to use with vue.js 2.x. The UI is based on the [Bootstrap 3](https://github.com/twbs/bootstrap) framework. Highly customizable and easy to use. Fits many screen resolutions from small mobile devices to large desktops.
![AdminLTE Presentation](https://almsaeedstudio.com/AdminLTE2.png)

In an attempt to keep the project clean I have not included every plugin/feature that AdminLTE offers. You simply need to add the plugin in the /static/plugins folder to include them or use npm. I've included the popular ones.

The structure of the app is scaffolded by vue-cli. Which is a simple CLI tool that setups our environment. AVUI uses the webpack package. So we get a full-featured Webpack + vue-loader setup with hot reload, linting, testing & css extraction.

We leverage all the goodies that vue.js offers. Vue-Router for routing. Vue-Resource for AJAX calls. Vuex for state management. This project is using VueJS 2.0!.

I also recommend that you install vue-devtools for Chrome so that you can easily inspect that state of vue.
![vue-devtools](http://res.cloudinary.com/gatec21/image/upload/v1461611064/copilot-vuetools_t1mvpg.png)

The data that is being pulled uses faker.js to make it dynamic. This is for demo purposes. Look for demo.* for information that is generated dynamically.

Installation
------------
Installing avui is easy.

#### Download:

Download from Github

#### Using The Command Line:

```
git clone https://github.com/haycco/avui.git
```

#### Build Setup

``` bash
# install dependencies
sudo npm install

# serve with hot reload at localhost:9090
npm run dev

# build for production with minification
npm run build

# run all tests
npm test
```

For detailed explanation on how things work, checkout the [guide](https://github.com/vuejs-templates/webpack#vue-webpack-boilerplate) and [docs for vue-loader](http://vuejs.github.io/vue-loader).

Documentation
-------------
Depending on the component you are working on you should have the following links handy.

- AdminLTE - [Offical Guide](https://almsaeedstudio.com/themes/AdminLTE/documentation/index.html)
- BootStrap 3 - [Offical Guide](http://getbootstrap.com/)
- Vue.js - [API](https://vuejs.org/v2/api/)
- Vuex - [Github](https://github.com/vuejs/vuex)
- Vue-Router - [Github](https://github.com/vuejs/vue-router)
- Axios - [Github](https://github.com/mzabriskie/axios)

Information and tips about AVUI can be found in the [wiki](https://github.com/haycco/avui/wiki).

Contribution
------------
Contribution are always **welcome and recommended**! Here is how:

- Fork the repository ([here is the guide](https://help.github.com/articles/fork-a-repo/)).
- Clone to your machine ```git clone https://github.com/YOUR_USERNAME/avui.git```
- Make your changes
- Create a pull request

TODOS
-------
The purpose of this project is to provide a full example of how to leverage Vue. If you find anything that can be Vue-ified please send me a PR.

License
-------
AVUI is an open source project by licensed under [MIT](http://opensource.org/licenses/MIT).


text:
require "spec_helper"

module Retsy
  describe Client do
    describe "initializing" do
      subject { described_class.new(options) }
      let(:options) { { key => value } }

      context "defined settings" do
        let(:key) { :login_url }
        let(:value) { "http://example.de" }

        it "sets the settings to instance variables" do
          expect(subject.instance_variable_get("@#{key}")).to eq(value)
        end
      end

      context "non-defined setttings" do
        let(:key) { :fluffy_key }
        let(:value) { "something not nil" }

        it "does not set the setting" do
          expect(subject.instance_variable_get("@#{key}")).to eq(nil)
        end
      end
    end

    describe "#base_url" do
      subject { described_class.new(login_url: "http://propertybase.com/foo") }
      it "builds base_url correctly" do
        expect(subject.base_url).to eq("http://propertybase.com")
      end
    end
  end
end


text:
package com.github.andrewlord1990.snackbarbuilder.parent;

import android.app.Activity;
import android.view.View;

/**
 * Specify how to find the parent view for Snackbars in the specified activity.
 */
public interface SnackbarParentFinder {

  View findSnackbarParent(Activity activity);

}


text:
{-# LANGUAGE StandaloneDeriving, OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

module ParserSpec (main, spec) where

import           Arbitrary ()
import           Unparse

import           Test.Hspec
import           Test.Hspec.QuickCheck (prop)

import           Network.MPD.Commands.Parse
import           Network.MPD.Commands.Types
import           Network.MPD.Util hiding (read)

import qualified Data.ByteString.UTF8 as UTF8
import           Data.List
import qualified Data.Map as M
import           Data.Time

main :: IO ()
main = hspec spec

spec :: Spec
spec = do
    describe "parseIso8601" $ do
        prop "parses dates in ISO8601 format" prop_parseIso8601

    describe "parseCount" $ do
        prop "parses counts" prop_parseCount

    describe "parseOutputs" $ do
        prop "parses outputs" prop_parseOutputs

    describe "parseSong" $ do
        prop "parses songs" prop_parseSong

    describe "parseStats" $ do
        prop "parses stats" prop_parseStats

-- This property also ensures, that (instance Arbitrary UTCTime) is sound.
-- Indeed, a bug in the instance declaration was the primary motivation to add
-- this property.
prop_parseIso8601 :: UTCTime -> Bool
prop_parseIso8601 t = Just t == (parseIso8601 . UTF8.fromString . formatIso8601) t

prop_parseCount :: Count -> Bool
prop_parseCount c = Right c == (parseCount . map UTF8.fromString . lines . unparse) c

prop_parseOutputs :: [Device] -> Bool
prop_parseOutputs ds =
    Right ds == (parseOutputs . map UTF8.fromString . lines . concatMap unparse) ds

deriving instance Ord Value

prop_parseSong :: Song -> Bool
prop_parseSong s = Right (sortTags s) == sortTags `fmap` (parseSong . toAssocList . map UTF8.fromString . lines . unparse) s
  where
    -- We consider lists of tag values equal if they contain the same elements.
    -- To ensure that two lists with the same elements are equal, we bring the
    -- elements in a deterministic order.
    sortTags song = song { sgTags = M.map sort $ sgTags song }

prop_parseStats :: Stats -> Bool
prop_parseStats s = Right s == (parseStats . map UTF8.fromString . lines . unparse) s


text:
from django.apps import AppConfig

class ApplianceConfig(AppConfig):
    name = 'appliance'


text:
package vtgate

// This file contains a test suite to run against a Gateway object.
// We re-use the tabletconn test suite, as it tests all queries and parameters
// go through. There are two exceptions:
// - the health check: we just make that one work, so the gateway knows the
//   tablet is healthy.
// - the error type returned: it's not a TabletError any more, but a ShardError.
//   We still check the error code is correct though which is really all we care
//   about.

import (
	"testing"

	"context"

	"vitess.io/vitess/go/vt/grpcclient"
	"vitess.io/vitess/go/vt/topo"
	"vitess.io/vitess/go/vt/topo/memorytopo"
	"vitess.io/vitess/go/vt/vttablet/queryservice"
	"vitess.io/vitess/go/vt/vttablet/tabletconn"
	"vitess.io/vitess/go/vt/vttablet/tabletconntest"

	querypb "vitess.io/vitess/go/vt/proto/query"
	topodatapb "vitess.io/vitess/go/vt/proto/topodata"
)

// CreateFakeServers returns the servers to use for these tests
func CreateFakeServers(t *testing.T) (*tabletconntest.FakeQueryService, *topo.Server, string) {
	cell := tabletconntest.TestCell

	// the FakeServer is just slightly modified
	f := tabletconntest.CreateFakeServer(t)
	f.TestingGateway = true
	f.StreamHealthResponse = &querypb.StreamHealthResponse{
		Target:                              tabletconntest.TestTarget,
		Serving:                             true,
		TabletExternallyReparentedTimestamp: 1234589,
		RealtimeStats: &querypb.RealtimeStats{
			SecondsBehindMaster: 1,
		},
	}

	// The topo server has a single SrvKeyspace
	ts := memorytopo.NewServer(cell)
	if err := ts.UpdateSrvKeyspace(context.Background(), cell, tabletconntest.TestTarget.Keyspace, &topodatapb.SrvKeyspace{
		Partitions: []*topodatapb.SrvKeyspace_KeyspacePartition{
			{
				ServedType: tabletconntest.TestTarget.TabletType,
				ShardReferences: []*topodatapb.ShardReference{
					{
						Name: tabletconntest.TestTarget.Shard,
					},
				},
			},
		},
	}); err != nil {
		t.Fatalf("can't add srvKeyspace: %v", err)
	}

	return f, ts, cell
}

// gatewayAdapter implements the TabletConn interface, but sends the
// queries to the Gateway.
type gatewayAdapter struct {
	Gateway
}

// Close should be overridden to make sure we don't close the underlying Gateway.
func (ga *gatewayAdapter) Close(ctx context.Context) error {
	return nil
}

// TestSuite executes a set of tests on the provided gateway. The provided
// gateway needs to be configured with one established connection for
// tabletconntest.TestTarget.{Keyspace, Shard, TabletType} to the
// provided tabletconntest.FakeQueryService.
func TestSuite(t *testing.T, name string, g Gateway, f *tabletconntest.FakeQueryService) {

	protocolName := "gateway-test-" + name

	tabletconn.RegisterDialer(protocolName, func(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) {
		return &gatewayAdapter{Gateway: g}, nil
	})

	tabletconntest.TestSuite(t, protocolName, &topodatapb.Tablet{
		Keyspace: tabletconntest.TestTarget.Keyspace,
		Shard:    tabletconntest.TestTarget.Shard,
		Type:     tabletconntest.TestTarget.TabletType,
		Alias:    tabletconntest.TestAlias,
	}, f, nil)
}


text:
#import <CoreMediaStream/MSASAssetTransferer.h>

@class NSMutableArray, NSMutableDictionary, NSMutableSet;

@interface MSASAssetUploader : MSASAssetTransferer
{
    _Bool _didEncounterNetworkConditionError;
    int _state;
    NSMutableArray *_itemsInFlight;
    NSMutableDictionary *_assetCollectionsToItemInFlightMap;
    NSMutableDictionary *_assetToAssetCollectionMap;
    NSMutableArray *_finishedAssetCollections;
    NSMutableSet *_assetCollectionsWithAuthorizationError;
    NSMutableDictionary *_assetCollectionGUIDToRequestorContext;
}

@property(retain, nonatomic) NSMutableDictionary *assetCollectionGUIDToRequestorContext; // @synthesize assetCollectionGUIDToRequestorContext=_assetCollectionGUIDToRequestorContext;
@property(retain, nonatomic) NSMutableSet *assetCollectionsWithAuthorizationError; // @synthesize assetCollectionsWithAuthorizationError=_assetCollectionsWithAuthorizationError;
@property(nonatomic) _Bool didEncounterNetworkConditionError; // @synthesize didEncounterNetworkConditionError=_didEncounterNetworkConditionError;
@property(retain, nonatomic) NSMutableArray *finishedAssetCollections; // @synthesize finishedAssetCollections=_finishedAssetCollections;
@property(retain, nonatomic) NSMutableDictionary *assetToAssetCollectionMap; // @synthesize assetToAssetCollectionMap=_assetToAssetCollectionMap;
@property(retain, nonatomic) NSMutableDictionary *assetCollectionsToItemInFlightMap; // @synthesize assetCollectionsToItemInFlightMap=_assetCollectionsToItemInFlightMap;
@property(retain, nonatomic) NSMutableArray *itemsInFlight; // @synthesize itemsInFlight=_itemsInFlight;
@property(nonatomic) int state; // @synthesize state=_state;
- (void).cxx_destruct;
- (void)didFinishGettingAllAssets;
- (void)MMCSEngine:(id)arg1 didMakeGetProgress:(float)arg2 state:(int)arg3 onAsset:(id)arg4;
- (void)MMCSEngine:(id)arg1 didFinishGettingAsset:(id)arg2 path:(id)arg3 error:(id)arg4;
- (void)didFinishPuttingAllAssets;
- (void)MMCSEngine:(id)arg1 didMakePutProgress:(float)arg2 state:(int)arg3 onAsset:(id)arg4;
- (void)MMCSEngine:(id)arg1 didCreateRequestorContext:(id)arg2 forAssets:(id)arg3;
- (void)MMCSEngine:(id)arg1 didFinishPuttingAsset:(id)arg2 putReceipt:(id)arg3 error:(id)arg4;
- (void)workQueueDidFinishWithItem:(id)arg1 error:(id)arg2;
- (void)workQueueStopTrackingItem:(id)arg1;
- (void)cancelAssetCollections:(id)arg1;
- (void)unregisterAssetCollections:(id)arg1 completionBlock:(id)arg2;
- (void)unregisterAssetCollections:(id)arg1;
- (void)registerAssetCollections:(id)arg1 completionBlock:(id)arg2;
- (void)workQueueRegisterAssetCollections:(id)arg1 index:(unsigned long long)arg2 results:(id)arg3 completionBlock:(id)arg4;
- (void)workQueueRegisterAssets:(id)arg1 index:(unsigned long long)arg2 completionBlock:(id)arg3;
- (void)workQueueCancelAssetCollections:(id)arg1;
- (void)workQueueUploadNextBatch;
- (id)_orphanedAssetCollectionError;
- (void)workQueueCancel;
- (void)workQueueShutDownCompletionBlock:(id)arg1;
- (void)workQueueStop;
- (void)_workQueueStop;
- (void)workQueueGoIdle;
- (void)workQueueRetryOutstandingActivities;
- (id)_pathForPersonID:(id)arg1;

// Remaining properties
@property(nonatomic) __weak id <MSASAssetUploaderDelegate> delegate; // @dynamic delegate;

@end


text:
.class Landroid/sec/clipboard/ClipboardConverter$ImageFileFilter;
.super Ljava/lang/Object;
.source "ClipboardConverter.java"

# interfaces
.implements Ljava/io/FileFilter;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/sec/clipboard/ClipboardConverter;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "ImageFileFilter"
.end annotation

# instance fields
.field private final extensions:[Ljava/lang/String;

.field mFileHelper:Landroid/sec/clipboard/util/FileHelper;

# direct methods
.method private constructor <init>()V
    .locals 3

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    invoke-static {}, Landroid/sec/clipboard/util/FileHelper;->getInstance()Landroid/sec/clipboard/util/FileHelper;

    move-result-object v0

    iput-object v0, p0, Landroid/sec/clipboard/ClipboardConverter$ImageFileFilter;->mFileHelper:Landroid/sec/clipboard/util/FileHelper;

    const/4 v0, 0x4

    new-array v0, v0, [Ljava/lang/String;

    const-string/jumbo v1, "jpg"

    const/4 v2, 0x0

    aput-object v1, v0, v2

    const-string/jumbo v1, "png"

    const/4 v2, 0x1

    aput-object v1, v0, v2

    const-string/jumbo v1, "gif"

    const/4 v2, 0x2

    aput-object v1, v0, v2

    const-string/jumbo v1, "jpeg"

    const/4 v2, 0x3

    aput-object v1, v0, v2

    iput-object v0, p0, Landroid/sec/clipboard/ClipboardConverter$ImageFileFilter;->extensions:[Ljava/lang/String;

    return-void
.end method

.method synthetic constructor <init>(Landroid/sec/clipboard/ClipboardConverter$ImageFileFilter;)V
    .locals 0

    invoke-direct {p0}, Landroid/sec/clipboard/ClipboardConverter$ImageFileFilter;-><init>()V

    return-void
.end method

# virtual methods
.method public accept(Ljava/io/File;)Z
    .locals 6

    const/4 v2, 0x0

    if-nez p1, :cond_0

    return v2

    :cond_0
    iget-object v3, p0, Landroid/sec/clipboard/ClipboardConverter$ImageFileFilter;->extensions:[Ljava/lang/String;

    array-length v4, v3

    move v1, v2

    :goto_0
    if-ge v1, v4, :cond_2

    aget-object v0, v3, v1

    invoke-virtual {p1}, Ljava/io/File;->getName()Ljava/lang/String;

    move-result-object v5

    invoke-virtual {v5}, Ljava/lang/String;->toLowerCase()Ljava/lang/String;

    move-result-object v5

    invoke-virtual {v5, v0}, Ljava/lang/String;->endsWith(Ljava/lang/String;)Z

    move-result v5

    if-eqz v5, :cond_1

    iget-object v5, p0, Landroid/sec/clipboard/ClipboardConverter$ImageFileFilter;->mFileHelper:Landroid/sec/clipboard/util/FileHelper;

    invoke-virtual {v5, p1}, Landroid/sec/clipboard/util/FileHelper;->checkFile(Ljava/io/File;)Z

    move-result v5

    if-nez v5, :cond_1

    const/4 v1, 0x1

    return v1

    :cond_1
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    :cond_2
    return v2
.end method


text:
FROM %%KOLLA_NAMESPACE%%/%%KOLLA_PREFIX%%base
MAINTAINER Kolla Project (https://launchpad.net/kolla)

RUN yum -y install openstack-utils openstack-swift && yum clean all

# These will come after we sort out start time config
RUN mkdir /opt/swift
config-swift.sh /opt/swift/config-swift.sh


text:
import logger from '../utils/logger'

const platformMiddleware = () => async (ctx, next) => {
  const { userAgent } = ctx
  ctx.state.browser = userAgent.browser
  ctx.state.platform = userAgent.platform
  ctx.state.isMobile = userAgent.isMobile
  ctx.state.device = userAgent.isMobile ? 'mobile' : 'desktop'

  await next()
  const { githubLogin } = ctx.session
  logger.info(
    `[${userAgent.browser}][${userAgent.platform}]${
      userAgent.isMobile ? '[Mobile]' : '[Desktop]'
    }${githubLogin ? `[LOGIN:${githubLogin}]` : ''}`
  )
}

export default platformMiddleware


text:
<?php
/**
 * @author Marcel Edmund Franke <info@marcel-edmund-franke.de>
 */

namespace Tests\AppBundle\Unit\Workflow;

use AppBundle\Entity\Article;
use Donutloop\RestfulApiWorkflowBundle\Library\DatabaseWorkflow;
use Donutloop\RestfulApiWorkflowBundle\Library\DatabaseWorkflowEntityInterface;
use Tests\AppBundle\DataFixtures\ORM\LoadOneArticleData;

/**
 * Class ArticleWorkflowTest
 * @package Tests\AppBundle\Unit\Workflow
 */
class ArticleWorkflowTest extends AbstractWorkflowTest
{
    /**
     * @return string
     */
    protected function getRepositoryName(): string
    {
        return 'AppBundle:Article';
    }

    /**
     * @return DatabaseWorkflowEntityInterface
     */
    protected function getEntity(): DatabaseWorkflowEntityInterface
    {
        $entity = new Article();
        $entity->setTitle(sprintf('test-title-%s', uniqid()));

        return $entity;
    }

    /**
     * @return DatabaseWorkflow
     */
    protected function getWorkflow(): DatabaseWorkflow
    {
        return $this->getContainer()->get('appbundle.article.workflow');
    }

    public function testDeleteArticle()
    {
        $this->loadFixtures([
            'Tests\AppBundle\DataFixtures\ORM\LoadOneArticleData'
        ]);

        $workflow = $this->getWorkflow();

        $repo = $this->getContainer()->get('doctrine')->getRepository('AppBundle:Article');

        $entity = $repo->find(LoadOneArticleData::$entity->getId());

        $workflow->delete($entity);

        $entity = $repo->find(LoadOneArticleData::$entity->getId());

        static::assertEquals(null, $entity);
    }

    public function testCreateInvalidTitle()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ValidatorException');
        $entity = $this->getEntity();
        $entity->setTitle('');
        $this->getWorkflow()->create($entity);
    }

    public function testValidateInvalidTitle()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ValidatorException');
        $entity = $this->getEntity();
        $entity->setTitle('');
        $this->getWorkflow()->validate($entity);
    }
}


text:
package koala.dynamicjava.tree;

import java.util.List;

import koala.dynamicjava.tree.visitor.Visitor;

/**
 * This class represents the switch statement nodes of the syntax tree
 *
 * @author  Stephane Hillion
 * @version 1.0 - 1999/05/25
 */

public class SwitchStatement extends Statement {
    /**
     * The selector property name
     */
    public final static String SELECTOR = "selector";

    /**
     * The bindings property name
     */
    public final static String BINDINGS = "bindings";

    /**
     * The selector
     */
    private Expression selector;

    /**
     * The list of case bindings
     */
    private List bindings;

    /**
     * Creates a new switch statement
     * @param sel   the selector
     * @param cases the case bindings (SwitchBlocks)
     * @param fn    the filename
     * @param bl    the begin line
     * @param bc    the begin column
     * @param el    the end line
     * @param ec    the end column
     * @exception IllegalArgumentException if sel is null or cases is null
     */
    public SwitchStatement(Expression sel, List cases,
			   String fn, int bl, int bc, int el, int ec) {
	super(fn, bl, bc, el, ec);

	if (sel == null)   throw new IllegalArgumentException("sel == null");
	if (cases == null) throw new IllegalArgumentException("cases == null");

	selector          = sel;
	bindings          = cases;
    }

    /**
     * Gets the selector
     */
    public Expression getSelector() {
	return selector;
    }

    /**
     * Sets the selector
     * @exception IllegalArgumentException if e is null
     */
    public void setSelector(Expression e) {
	if (e == null) throw new IllegalArgumentException("e == null");

	firePropertyChange(SELECTOR, selector, selector = e);
    }

    /**
     * Returns the 'case' bindings
     */
    public List getBindings() {
	return bindings;
    }

    /**
     * Sets the bindings
     * @exception IllegalArgumentException if e is null
     */
    public void setBindings(List l) {
	if (l == null) throw new IllegalArgumentException("l == null");

	firePropertyChange(BINDINGS, bindings, bindings = l);
    }

    /**
     * Allows a visitor to traverse the tree
     * @param visitor the visitor to accept
     */
    public Object acceptVisitor(Visitor visitor) {
	return visitor.visit(this);
    }
}


text:
#pragma once

#include "upm.h"
#include "mraa/aio.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @file light.h
 * @library light
 * @brief C API for Analog Light (Photocell) Sensors
 *
 * @include light.c
 */

/**
 * driver context
 */
typedef struct _light_context {
    /* mraa aio pin context */
    mraa_aio_context aio;
    /* Analog voltage reference */
    float m_aRef;
    /* Scale */
    float m_scale;
    /* Offset in sensor units */
    float m_offset;
} *light_context;

/**
 * Initialize analog sensor
 * @param pin Analog pin
 * @return sensor context
 */
light_context light_init(int16_t pin);

/**
 * Analog sensor destructor
 * @param sensor context pointer
 */
void light_close(light_context dev);

/**
 * Set ADC reference voltage
 * @param dev sensor context pointer
 * @param aref ADC reference voltage
 * @return Function result code
 */
upm_result_t light_set_aref(const light_context dev, float aref);

/**
 * Set sensor scale.  This scale is applied to the return value:
 *     counts = counts * scale
 * @param dev sensor context pointer
 * @param scale count scale value used
 * @return Function result code
 */
upm_result_t light_set_scale(const light_context dev, float scale);

/**
 * Set sensor offset.  This offset is applied to the return value:
 *     value = value + offset
 * @param dev sensor context pointer
 * @param offset count offset value used
 * @return Function result code
 */
upm_result_t light_set_offset(const light_context dev, float offset);

/**
 * Get sensor aref
 * @param dev sensor context pointer
 * @return Sensor ADC reference voltage
 */
float light_get_aref(const light_context dev);

/**
 * Get sensor scale
 * @param dev sensor context pointer
 * @return Sensor scale
 */
float light_get_scale(const light_context dev);

/**
 * Get sensor offset
 * @param dev sensor context pointer
 * @return Sensor offset
 */
float light_get_offset(const light_context dev);

/**
 * Read normalized value for sensor
 * @param dev sensor context pointer
 * @param *value Normalized value (0.0 -> 1.0)
 * @return Function result code
 */
upm_result_t light_get_normalized(const light_context dev, float *value);

/**
 * Read raw voltage from the sensor
 * @param dev sensor context pointer
 * @param *value Raw sensor voltage
 * @return Function result code
 */
upm_result_t light_get_raw_volts(const light_context dev, float *value);

/**
 * Read scaled/offset light value in lux
 * @param dev sensor context pointer
 * @param *value Adjusted sensor value in lux
 * @return Function result code
 */
upm_result_t light_get_lux(const light_context dev, float *value);
#ifdef __cplusplus
}
#endif


text:
using Landis.Core;
using Landis.SpatialModeling;

namespace Landis.Extension.LandUse
{
    public class SiteVars
    {
        private static ISiteVar<LandUse> landUse;
        private static AllowHarvestSiteVar allowHarvest;
        //private static AllowEstablishmentSitVar allowEstablishment;

        //---------------------------------------------------------------------

        public static void Initialize(ICore modelCore)
        {
            landUse = modelCore.Landscape.NewSiteVar<LandUse>();
            allowHarvest = new AllowHarvestSiteVar();
            Model.Core.RegisterSiteVar(allowHarvest, "LandUse.AllowHarvest");

            //allowEstablishment = new AllowEstablishmentSiteVar();
            //Model.Core.RegisterSiteVar(allowEstablishment, "LandUse.AllowEstablishment");

            Landis.Library.BiomassHarvest.SiteVars.CohortsPartiallyDamaged = modelCore.Landscape.NewSiteVar<int>();
        }

        //---------------------------------------------------------------------

        public static ISiteVar<LandUse> LandUse
        {
            get {
                return landUse;
            }
        }
    }
}


text:
{% extends "blog/base.html" %}
{% load pagination_tags %}

{% block title %}写博客-{{ usersettings.name }}-{{ username }}-金融界博客{% endblock %}

{% block csszone %}
{% include "blog/csszone_1.html" %}
{% endblock %}

{% block rsszone %}
{% include "blog/rsszone_1.html" %}
{% endblock %}

{% block body_header %}
{% include "blog/body_header_1.html" %}
{% endblock %}

{% block body_content %}

	<form method="post" action="/write_comment">
	{{ form.as_ul }}

<input type="submit" value="write" />

	</form>

{% endblock %}

{% block body_footer %}
{% include "blog/body_footer_1.html" %}
{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Slib
{
    public class Message
    {
        public static int T_END = 0;
        public static int T_INT = 1;
        public static int T_STR = 2;
        public static int T_COORD = 3;

        public int type;
        public byte[] blob;
        private int off = 0;

        public Message(int type, byte[] blob)
        {
            this.type = type;
            this.blob = blob;
        }

        public Message(byte[] blob, int offset, int len)
        {
            this.blob = new byte[len];
            Buffer.BlockCopy(blob, offset, this.blob, 0, len);
            this.type = ReadInt32();
        }

        public Message(int type)
        {
            this.type = type;
            blob = new byte[0];
            AddInt32(type);
        }

        public unsafe void addbytes(byte[] src, int off, int len)
        {
            byte[] n = new byte[blob.Length + len];
            Buffer.BlockCopy(blob, 0, n, 0, blob.Length);
            Buffer.BlockCopy(src, off, n, blob.Length, len);
            blob = n;
        }

        public void addbytes(byte[] src)
        {
            addbytes(src, 0, src.Length);
        }

        public void AddSByte(int num)
        {
            addbytes(new byte[] { Utils.sb(num) });
        }

        public void AddByte(int num)
        {
            addbytes(new byte[] { Utils.Byte(num) });
        }

        public void AddInt32(int i)
        {
            byte[] buffer = BitConverter.GetBytes((int)i);
            addbytes(buffer, 0, buffer.Length);
        }

        public void AddUInt32(uint i)
        {
            byte[] buffer = BitConverter.GetBytes((uint)i);
            addbytes(buffer, 0, buffer.Length);
        }

        public void AddInt16(short i)
        {
            byte[] buffer = BitConverter.GetBytes((short)i);
            addbytes(buffer, 0, buffer.Length);
        }

        public void AdduInt16(ushort i)
        {
            byte[] buffer = BitConverter.GetBytes((ushort)i);
            addbytes(buffer, 0, buffer.Length);
        }

        public void AddString(string s)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(s);
            addbytes(buffer, 0, buffer.Length); ;
            addbytes(new byte[] { 0 });
        }

        public void AddCoord(Coord c)
        {
            AddInt32(c.X);
            AddInt32(c.Y);
        }

        public void addlist(params object[] args)
        {
            foreach (Object o in args)
            {
                if (o is int)
                {
                    AddByte(T_INT);
                    AddInt32(((int)o));
                }
                else if (o is String)
                {
                    AddByte(T_STR);
                    AddString((String)o);
                }
                else if (o is Coord)
                {
                    AddByte(T_COORD);
                    AddCoord((Coord)o);
                }
            }
        }

        public int ReadInt32()
        {
            int i = BitConverter.ToInt32(blob, off);
            off = off + 4;
            return i;
        }

        public short ReadInt16()
        {
            short i = BitConverter.ToInt16(blob, off);
            off = off + 2;
            return i;
        }

        public uint ReadUInt32()
        {
            uint i = BitConverter.ToUInt32(blob, off);
            off = off + 4;
            return i;
        }

        public ushort ReadUInt16()
        {
            ushort i = BitConverter.ToUInt16(blob, off);
            off = off + 2;
            return i;
        }

        public byte ReadByte()
        {
            byte i = blob[off];
            off++;
            return i;
        }

        public sbyte ReadSbyte()
        {
            sbyte i = (sbyte)blob[off];
            off++;
            return i;
        }

        public string ReadString()
        {
            int i = off;

            while (blob[off] != 0)
            {
                off++;
            }

            string s = Encoding.UTF8.GetString(blob, i, off - i);

            off++; //increment after 0

            return s;
        }

        public Coord coord()
        {
            return (new Coord(ReadInt32(), ReadInt32()));
        }

        public object[] ReadList()
        {
            List<object> ret = new List<object>();
            while (true)
            {
                if (off >= blob.Length)
                    break;

                int t = ReadByte();
                if (t == T_END)
                    break;
                else if (t == T_INT)
                    ret.Add(ReadInt32());
                else if (t == T_STR)
                    ret.Add(ReadString());
                else if (t == T_COORD)
                    ret.Add(coord());
            }
            return ret.ToArray();
        }
    }
}


text:
package com.mongodb.internal.connection;

import com.mongodb.internal.async.SingleResultCallback;

interface InternalConnectionInitializer {

    InternalConnectionInitializationDescription startHandshake(InternalConnection internalConnection);

    InternalConnectionInitializationDescription finishHandshake(InternalConnection internalConnection,
                                                                InternalConnectionInitializationDescription description);

    void startHandshakeAsync(InternalConnection internalConnection,
                             SingleResultCallback<InternalConnectionInitializationDescription> callback);

    void finishHandshakeAsync(InternalConnection internalConnection, InternalConnectionInitializationDescription description,
                              SingleResultCallback<InternalConnectionInitializationDescription> callback);
}


text:
'use strict';

angular
    .module('AmsterdamConf', [])
    .config(['$interpolateProvider', function($interpolateProvider){
        $interpolateProvider.startSymbol('[[').endSymbol(']]');
    }])
    .controller('TemplateCtrl', ['$scope', function ($scope) {
        $scope.text = '';
        $scope.templateSubmit = function () {
            alert("text value is:" + $scope.text);
        };
    }])
    .controller('DirectiveCtrl', ['$scope', function ($scope) {
        $scope.value = 0;
        $scope.tools = ['AngularJS', 'Go Lang', 'Dart'];
        $scope.selection = $scope.tools[0];

        $scope.name = 'Wilk';

        $scope.articles = [
            {title: 'Article A', body: 'Content of article A', notes: 'Notes of article A'},
            {title: 'Article B', body: 'Content of article B', notes: 'Notes of article B'},
            {title: 'Article C', body: 'Content of article C', notes: 'Notes of article C'}
        ];
    }])
    .controller('FilterCtrl', ['$scope', function ($scope) {
        $scope.amount = 0;
        $scope.today = new Date();
        $scope.objectToDebug = {a:10, b:30, c:[1,2,3]};
        $scope.users = [
            {name: 'Mario', telephone: '123 456 789', age: 35},
            {name: 'Luigi', telephone: '321 654 987', age: 30},
            {name: 'Vincenzo', telephone: '456 123 789', age: 27}
        ];
        $scope.predicates = ['name', 'telephone', 'age'];
        $scope.predicate = $scope.predicates[0];
        $scope.reverse = false;
        $scope.name = '';
        $scope.starNumber = 0;
    }])
    .controller('FormCtrl', ['$scope', function ($scope) {
        $scope.origin = {};
        $scope.reset = function () {
            $scope.user = angular.copy($scope.origin);
        };
        $scope.update = function (user) {
            $scope.origin = angular.copy(user);
        };
        $scope.isUnchanged = function (user) {
            return angular.equals(user, $scope.origin);
        };
        $scope.reset();
    }])
    .controller('ServiceCtrl', ['$scope', '$filter', '$http', '$httpBackend', '$location', 'Mario', function ($scope, $filter, $http, $httpBackend, $location, Mario) {
        $scope.date = '';
        $scope.americanDate = '';
        $scope.filter = function () {
            var dateFilter = $filter('date');
            $scope.americanDate = dateFilter($scope.date, 'M/d/yyyy');
        };

        /*$httpBackend.when('GET', '/Users.json')
            .respond([
                {name: 'Mario', telephone: '123 456 789', age: 35},
                {name: 'Luigi', telephone: '321 654 987', age: 30},
                {name: 'Vincenzo', telephone: '456 123 789', age: 27}
            ]);*/
        $scope.users = [];
        $scope.getUsers = function () {
            $http.get('fixtures/Users.json')
                .success(function (users) {
                    $scope.users = users;
                });
        };

        $scope.url = {};
        $scope.getUrl = function () {
            $scope.url.absUrl = $location.absUrl();
            $scope.url.url = $location.url();
            $scope.url.protocol = $location.protocol();
            $scope.url.host = $location.host();
            $scope.url.path = $location.path();
            $scope.url.port = $location.port();
        };

        $scope.salutation = Mario.salutation;
        $scope.findLuigi = Mario.findLuigi;
    }])
    .service('Mario', ['$http', '$log', function ($http, $log) {
        this.salutation = function () {
            alert('Hi, I\'m Mario!');
        };

        this.findLuigi = function () {
            $http.get('fixtures/Users.json')
                .success(function (luigi) {
                    alert('I found you Luigi!');
                    $log.debug(luigi);
                });
        };
    }])
    .filter('star', ['uppercaseFilter', function (uppercaseFilter) {
        return function (value, starNumber) {
            value = String(value);
            starNumber = starNumber || 0;
            var stars = '',
                result = [];

            for (var i = 0; i < starNumber; i++) {
                stars += '*';
            }

            result.push(stars);
            result.push(uppercaseFilter(value));
            result.push(stars);

            if (value && value.length > 0) return result.join(' ');
            else return '';
        };
    }])
    .directive('myClock', ['$interval', 'dateFilter', function ($interval, dateFilter) {
        return {
            restrict: 'E',
            link: function (scope, element, attrs) {
                $interval(function () {
                    element.text(dateFilter(new Date(), 'H:mm:ss'));
                }, 1000);
            }
        };
    }]);


text:
package dht

import (
	"testing"

	key "github.com/djbarber/ipfs-hack/blocks/key"
	peer "github.com/djbarber/ipfs-hack/p2p/peer"

	context "github.com/djbarber/ipfs-hack/Godeps/_workspace/src/golang.org/x/net/context"
)

func TestProviderManager(t *testing.T) {
	ctx := context.Background()
	mid := peer.ID("testing")
	p := NewProviderManager(ctx, mid)
	a := key.Key("test")
	p.AddProvider(ctx, a, peer.ID("testingprovider"))
	resp := p.GetProviders(ctx, a)
	if len(resp) != 1 {
		t.Fatal("Could not retrieve provider.")
	}
	p.proc.Close()
}