text:
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using CppSharp.AST;
using CppSharp.Generators;

namespace CppSharp.Passes
{
    class DeclarationName
    {
        private readonly Dictionary<string, int> methodSignatures;
        private int Count;

        public DeclarationName()
        {
            methodSignatures = new Dictionary<string, int>();
        }

        public bool UpdateName(Declaration decl)
        {
            var function = decl as Function;
            if (function != null)
            {
                return UpdateName(function);
            }

            var property = decl as Property;
            var isIndexer = property != null && property.Parameters.Count > 0;
            if (isIndexer)
            {
                return false;
            }

            var count = Count++;
            if (count == 0)
                return false;

            decl.Name += count.ToString(CultureInfo.InvariantCulture);
            return true;
        }

        private bool UpdateName(Function function)
        {
            var @params = function.Parameters.Where(p => p.Kind != ParameterKind.IndirectReturnType)
                                .Select(p => p.QualifiedType.ToString());
            // Include the conversion type in case of conversion operators
            var method = function as Method;
            if (method != null &&
                method.IsOperator &&
                (method.OperatorKind == CXXOperatorKind.Conversion ||
                 method.OperatorKind == CXXOperatorKind.ExplicitConversion))
                @params = @params.Concat(new[] { method.ConversionType.ToString() });
            var signature = string.Format("{0}({1})", function.Name, string.Join( ", ", @params));
            signature = FixSignatureForConversions(function, signature);

            if (Count == 0)
                Count++;

            if (!methodSignatures.ContainsKey(signature))
            {
                methodSignatures.Add(signature, 0);
                return false;
            }

            var methodCount = ++methodSignatures[signature];

            if (Count < methodCount + 1)
                Count = methodCount + 1;

            if (function.IsOperator)
            {
                // TODO: turn into a method; append the original type (say, "signed long")
                // of the last parameter to the type so that the user knows which overload is called
                Diagnostics.Warning("Duplicate operator {0} ignored", function.Name);
                function.ExplicitlyIgnore();
            }
            else if (method != null && method.IsConstructor)
            {
                Diagnostics.Warning("Duplicate constructor {0} ignored", function.Name);
                function.ExplicitlyIgnore();
            }
            else
                function.Name += methodCount.ToString(CultureInfo.InvariantCulture);
            return true;
        }

        public static string FixSignatureForConversions(Function function, string signature)
        {
            switch (function.OperatorKind)
            {
                // C# does not allow an explicit and an implicit operator from the same type
                case CXXOperatorKind.Conversion:
                    signature = signature.Replace("implicit ", "conversion ");
                    break;
                case CXXOperatorKind.ExplicitConversion:
                    signature = signature.Replace("explicit ", "conversion ");
                    break;
            }
            return signature;
        }
    }

    public class CheckDuplicatedNamesPass : TranslationUnitPass
    {
        private readonly IDictionary<string, DeclarationName> names;

        public CheckDuplicatedNamesPass()
        {
            ClearVisitedDeclarations = false;
            names = new Dictionary<string, DeclarationName>();
        }

        public override bool VisitProperty(Property decl)
        {
            if (!VisitDeclaration(decl))
                return false;

            if (decl.ExplicitInterfaceImpl == null)
                CheckDuplicate(decl);

            return false;
        }

        public override bool VisitFunctionDecl(Function decl)
        {
            if (!VisitDeclaration(decl))
                return false;

            if (ASTUtils.CheckIgnoreFunction(decl))
                return false;

            CheckDuplicate(decl);
            return false;
        }

        public override bool VisitMethodDecl(Method decl)
        {
            if (!VisitDeclaration(decl))
                return false;

            if (ASTUtils.CheckIgnoreMethod(decl))
                return false;

            if (decl.ExplicitInterfaceImpl == null)
                CheckDuplicate(decl);

            return false;
        }

        public override bool VisitClassDecl(Class @class)
        {
            if (!base.VisitClassDecl(@class))
                return false;

            if (@class.IsIncomplete)
                return false;

            // DeclarationName should always process methods first,
            // so we visit methods first.
            foreach (var method in @class.Methods)
                VisitMethodDecl(method);

            foreach (var function in @class.Functions)
                VisitFunctionDecl(function);

            if (!@class.IsDependent)
            {
                foreach (var fields in @class.Layout.Fields.GroupBy(
                    f => f.Name).Select(g => g.ToList()))
                {
                    for (var i = 1; i < fields.Count; i++)
                    {
                        var name = fields[i].Name;
                        fields[i].Name = (string.IsNullOrEmpty(name) ? "__" : name) + i;
                    }
                }
            }

            foreach (var property in @class.Properties)
                VisitProperty(property);

            return false;
        }

        private static IEnumerable<Field> GetAllFields(Class @class, List<Field> fields = null)
        {
            fields = fields ?? new List<Field>();
            foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class != @class))
                GetAllFields(@base.Class, fields);
            fields.AddRange(@class.Fields);
            return fields;
        }

        private void CheckDuplicate(Declaration decl)
        {
            if (decl.IsDependent || !decl.IsGenerated)
                return;

            if (string.IsNullOrWhiteSpace(decl.Name))
                return;

            var fullName = decl.QualifiedName;
            var function = decl as Function;
            if (function != null)
                fullName = DeclarationName.FixSignatureForConversions(function, fullName);

            // If the name is not yet on the map, then add it.
            if (!names.ContainsKey(fullName))
                names.Add(fullName, new DeclarationName());

            if (names[fullName].UpdateName(decl))
            {
                Diagnostics.Debug("Duplicate name {0}, renamed to {1}",
                    fullName, decl.Name);
            }
        }
    }
}


text:
module RuboCop
  module Cop
    module Lint
      # This cop checks for implicit string concatenation of string literals
      # which are on the same line.
      #
      # @example
      #   @bad
      #   array = ['Item 1' 'Item 2']
      #
      #   @good
      #   array = ['Item 1Item 2']
      #   array = ['Item 1' + 'Item 2']
      #   array = [
      #     'Item 1' \
      #     'Item 2'
      #   ]
      class ImplicitStringConcatenation < Cop
        MSG = 'Combine %s and %s into a single string literal, rather than ' \
              'using implicit string concatenation.'
        FOR_ARRAY = ' Or, if they were intended to be separate array ' \
                    'elements, separate them with a comma.'
        FOR_METHOD = ' Or, if they were intended to be separate method ' \
                     'arguments, separate them with a comma.'

        def on_dstr(node)
          node.children.each_cons(2) do |child1, child2|
            # `'abc' 'def'` -> (dstr (str "abc") (str "def"))
            next unless string_literal?(child1) && string_literal?(child2)
            next unless child1.loc.last_line == child2.loc.line

            # Make sure we don't flag a string literal which simply has
            # embedded newlines
            # `"abc\ndef"` also -> (dstr (str "abc") (str "def"))
            next unless child1.source[-1] == ending_delimiter(child1)

            range   = child1.loc.expression.join(child2.loc.expression)
            message = format(MSG, display_str(child1), display_str(child2))
            if node.parent && node.parent.array_type?
              message << FOR_ARRAY
            elsif node.parent && node.parent.send_type?
              message << FOR_METHOD
            end
            add_offense(node, range, message)
          end
        end

        private

        def ending_delimiter(str)
          # implicit string concatenation does not work with %{}, etc.
          if str.source[0] == "'"
            "'"
          elsif str.source[0] == '"'
            '"'
          end
        end

        def string_literal?(node)
          node.str_type? ||
            (node.dstr_type? && node.children.all? { |c| string_literal?(c) })
        end

        def display_str(node)
          if node.source =~ /\n/
            str_content(node).inspect
          else
            node.source
          end
        end

        def str_content(node)
          if node.str_type?
            node.children[0]
          else
            node.children.map { |c| str_content(c) }.join
          end
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package kodi

// Request define the object sended to the server for the JSONRPC call
type Request struct {
	Jsonrpc string      `json:"jsonrpc"`
	Method  string      `json:"method"`
	ID      int64       `json:"id"`
	Params  interface{} `json:"params,omitempty"`
}

// ErrorStack define sonme errors informations
type ErrorStack struct {
	Name     string      `json:"name,omitempty"`
	Type     string      `json:"type,omitempty"`
	Message  string      `json:"message,omitempty"`
	Property *ErrorStack `json:"property,omitempty"`
}

// ErrorData define some additional information about the error.
type ErrorData struct {
	Method string      `json:"method"`
	Stack  *ErrorStack `json:"stack"`
}

// ResponseError define the error member of the response when a rpc call encounters an error
type ResponseError struct {
	Code    int        `json:"code"`
	Message string     `json:"message"`
	Data    *ErrorData `json:"data,omitempty"`
}

// ResponseBase define the base JSON object response after a JSONRPC call
type ResponseBase struct {
	Jsonrpc string         `json:"jsonrpc,omitempty"`
	Method  string         `json:"method,omitempty"`
	ID      int64          `json:"id,omitempty"`
	Error   *ResponseError `json:"error,omitempty"`
}


text:
name: Debra Solomon
work_title: Former Data Academy Instructor
email:
bio:
gravatar:
twitter:
headshot_image_path: /uploads/debra-bio-pic.png
instructor: Alum
---

Debra Solomon is the Director of Contract Compliance for the San Francisco Department of Public Health.  Together, she and her group have responsibility for monitoring the compliance, performance, and fiscal health of more than 350 contracts and public health programs. Previously, Debra was a Budget Analyst and Contracts Manager at the San Francisco Human Services Agency. She also has many years of experience in program evaluation and nonprofit management, with a special focus on using research and data to improve services and outcomes for the Bay Area's most vulnerable populations.  She received a bachelor's degree in History from Stanford University and a Master's in Public Policy from the University of California, Berkeley.


text:
<html>
<body>
This package contains the classes needed by Spoon.
</body>
</html>


text:
'use strict';

/*
 * Icon constructor
 *
 * @param {Object} descriptor
 *                 An object that contains the data necessary to draw this
 *                 icon.
 * @param {Application} app [optional]
 *                      The Application or Bookmark object corresponding to
 *                      this icon.
 */
function Icon(descriptor, app) {
  this.descriptor = descriptor;
  this.app = app;
  this.updateAppStatus(app);
}

// Support rendering icons for different screens
var BASE_WIDTH = 320;
var SCALE_RATIO = window.devicePixelRatio;
var MIN_ICON_SIZE = 52;
var MAX_ICON_SIZE = 60;
var ICON_PADDING_IN_CANVAS = 4;

var DRAGGING_TRANSITION = '-moz-transform .3s';

Icon.prototype = {

  MAX_ICON_SIZE: MAX_ICON_SIZE,

  MIN_ICON_SIZE: MIN_ICON_SIZE,

  // It defines the time (in ms) to ensure that the onDragStop method finishes
  FALLBACK_DRAG_STOP_DELAY: 1000,

  DEFAULT_BOOKMARK_ICON_URL: window.location.protocol + '//' +
                    window.location.host + '/style/images/default_favicon.png',
  DEFAULT_ICON_URL: window.location.protocol + '//' + window.location.host +
                    '/style/images/default.png',
  DOWNLOAD_ICON_URL: window.location.protocol + '//' + window.location.host +
                    '/style/images/app_downloading.png',
  CANCELED_ICON_URL: window.location.protocol + '//' + window.location.host +
                    '/style/images/app_paused.png',

  // These properties will be copied from the descriptor onto the icon's HTML
  // element dataset and allow us to uniquely look up the Icon object from
  // the HTML element.
  _descriptorIdentifiers: ['manifestURL', 'entry_point', 'bookmarkURL',
                           'useAsyncPanZoom'],

  /**
   * The Application (or Bookmark) object corresponding to this icon.
   */
  app: null,

  /**
   * It returns an unique identifier among all icons installed on the homescreen
   */
  getUID: function icon_getUID() {
    var descriptor = this.descriptor;

    return (descriptor.manifestURL || descriptor.bookmarkURL) +
           (descriptor.entry_point ? descriptor.entry_point : '');
  },

  /*
   * Renders the icon into the page
   *
   * @param{Object} where the icon should be rendered
   *
   * @param{Object} where the draggable element should be appened
   */
  render: function icon_render(target) {
    /*
     *

     *

     *
     *     label
     *

     *
     *

     */

    var container = this.container = document.createElement('li');
    container.className = 'icon';
    if (this.descriptor.hidden) {
      delete this.descriptor.hidden;
      container.dataset.visible = false;
    }

    var descriptor = this.descriptor;
    container.dataset.isIcon = true;
    this._descriptorIdentifiers.forEach(function(prop) {
      var value = descriptor[prop];
      if (value)
        container.dataset[prop] = value;
    });

    var localizedName = descriptor.localizedName || descriptor.name;
    container.setAttribute('role', 'button');
    container.setAttribute('aria-label', localizedName);

    // Icon container
    var icon = this.icon = document.createElement('div');

    // Image
    var img = this.img = new Image();
    img.setAttribute('role', 'presentation');
    img.width = MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS;
    img.height = MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS;
    img.style.visibility = 'hidden';
    if (descriptor.renderedIcon) {
      this.displayRenderedIcon();
    } else {
      this.fetchImageData();
    }
    icon.appendChild(img);

    // Label

    // wrapper of the label -> overflow text should be centered
    // in draggable mode
    var wrapper = document.createElement('span');
    wrapper.className = 'labelWrapper';
    var label = this.label = document.createElement('span');
    label.textContent = localizedName;
    wrapper.appendChild(label);
    this.applyOverflowTextMask();

    icon.appendChild(wrapper);

    container.appendChild(icon);

    if (descriptor.removable === true) {
      this.appendOptions();
    }

    target.appendChild(container);

    if (this.downloading) {
      //XXX: Bug 816043 We need to force the repaint to show the span
      // with the label and the animation (associated to the span)
      container.style.visibility = 'visible';
      icon.classList.add('loading');
    }
  },

  appendOptions: function icon_appendOptions() {
    var options = this.container.querySelector('.options');
    if (options) {
      return;
    }

    // Menu button to delete the app
    options = document.createElement('span');
    options.className = 'options';
    options.dataset.isIcon = true;
    this.container.appendChild(options);
  },

  removeOptions: function icon_removeOptions() {
    var options = this.container.querySelector('.options');
    if (!options) {
      return;
    }

    this.container.removeChild(options);
  },

  applyOverflowTextMask: function icon_applyOverflowTextMask() {
    var label = this.label;
    if (TextOverflowDetective.check(label.textContent)) {
      label.parentNode.classList.add('mask');
    } else {
      label.parentNode.classList.remove('mask');
    }
  },

  fetchImageData: function icon_fetchImageData() {
    var descriptor = this.descriptor;
    var icon = descriptor.icon;
    if (!icon) {
      this.loadCachedIcon();
      return;
    }

    // Display the default/oldRendered icon before trying to get the icon.
    // Sometimes when the network is quite bad the XHR can take time, and we
    // have an empty space
    this.loadCachedIcon();

    IconRetriever.get({
      icon: this,
      success: function(blob) {
        this.loadImageData(blob);
      },
      error: function() {
        if (this.icon && !this.downloading &&
            this.icon.classList.contains('loading')) {
          this.icon.classList.remove('loading');
          this.img.src = null;
        }
        this.loadCachedIcon();
      }
    });
  },

  loadCachedIcon: function icon_loadCachedImage() {
    var oldRenderedIcon = this.descriptor.oldRenderedIcon;
    if (oldRenderedIcon && oldRenderedIcon instanceof Blob) {
      this.renderBlob(oldRenderedIcon);
    } else {
      this.loadDefaultIcon();
    }
  },

  loadImageData: function icon_loadImageData(blob) {
    var self = this;
    var img = new Image();
    img.src = window.URL.createObjectURL(blob);

    if (this.icon && !this.downloading) {
      this.icon.classList.remove('loading');
    }

    img.onload = function icon_loadSuccess() {
      img.onload = img.onerror = null;
      window.URL.revokeObjectURL(img.src);
      self.renderImage(img);
    };

    img.onerror = function icon_loadError() {
      console.error('error while loading the icon', img.src, '. Falling back ' +
          'to default icon.');
      window.URL.revokeObjectURL(img.src);
      self.loadDefaultIcon(img);
    };
  },

  loadDefaultIcon: function icon_loadDefaultIcon(img) {
    var image = img || new Image();
    var self = this;

    if (self.img && self.img.src) {
      // If there is one already loaded, do not continue...
      image.onload = image.onerror = null;
      return;
    }

    var blob = GridManager.getBlobByDefault(self.app);
    if (blob === null) {
      // At this point theoretically the flow shouldn't go because the icons
      // by default have to be loaded, but just in case to avoid race conditions
      image.src = getDefaultIcon(self.app);
      image.onload = function icon_defaultIconLoadSucess() {
        image.onload = image.onerror = null;
        self.renderImage(image);
      };
    } else {
      self.renderBlob(blob);
      image.onload = image.onerror = null;
    }
  },

  renderImageForBookMark: function icon_renderImageForBookmark(img) {
    var self = this;
    var canvas = document.createElement('canvas');
    canvas.width = (MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS) * SCALE_RATIO;
    canvas.height = (MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS) * SCALE_RATIO;
    var ctx = canvas.getContext('2d');

    // Draw the background
    var background = new Image();
    background.src = 'style/images/default_background.png';
    background.onload = function icon_loadBackgroundSuccess() {
      ctx.shadowColor = 'rgba(0,0,0,0.8)';
      ctx.shadowBlur = 2;
      ctx.shadowOffsetY = 2;
      ctx.drawImage(background, 2 * SCALE_RATIO, 2 * SCALE_RATIO,
                    MAX_ICON_SIZE * SCALE_RATIO, MAX_ICON_SIZE * SCALE_RATIO);
      // Disable smoothing on icon resize
      ctx.shadowBlur = 0;
      ctx.shadowOffsetY = 0;
      ctx.mozImageSmoothingEnabled = false;
      ctx.drawImage(img, 16 * SCALE_RATIO, 16 * SCALE_RATIO,
                    32 * SCALE_RATIO, 32 * SCALE_RATIO);
      canvas.toBlob(self.renderBlob.bind(self));
    };
  },

  renderImage: function icon_renderImage(img) {
    if (this.app && this.app.iconable) {
      this.renderImageForBookMark(img);
      return;
    }

    var canvas = document.createElement('canvas');
    canvas.width = (MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS) * SCALE_RATIO;
    canvas.height = (MAX_ICON_SIZE + ICON_PADDING_IN_CANVAS) * SCALE_RATIO;

    var ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.shadowColor = 'rgba(0,0,0,0.8)';
    ctx.shadowBlur = 2;
    ctx.shadowOffsetY = 2;

    // Deal with very small or very large icons
    img.width =
        Math.min(MAX_ICON_SIZE, Math.max(img.width, MAX_ICON_SIZE));
    img.height =
        Math.min(MAX_ICON_SIZE, Math.max(img.height, MAX_ICON_SIZE));

    var width = Math.min(img.width * SCALE_RATIO,
                         canvas.width - ICON_PADDING_IN_CANVAS * SCALE_RATIO);
    var height = Math.min(img.width * SCALE_RATIO,
                          canvas.height - ICON_PADDING_IN_CANVAS * SCALE_RATIO);
    ctx.drawImage(img,
                  (canvas.width - width) / 2,
                  (canvas.height - height) / 2,
                  width, height);
    ctx.fill();

    canvas.toBlob(this.renderBlob.bind(this));
  },

  // The url that is passed as a parameter to the callback must be revoked
  loadRenderedIcon: function icon_loadRenderedIcon(callback) {
    var img = this.img;
    img.src = window.URL.createObjectURL(this.descriptor.renderedIcon);
    if (callback) {
      img.onload = img.onerror = function done() {
        callback(this.src);
        img.onload = img.onerror = null;
      };
    }
  },

  renderBlob: function icon_renderBlob(blob) {
    this.descriptor.renderedIcon = blob;
    GridManager.markDirtyState();
    this.displayRenderedIcon();
  },

  displayRenderedIcon: function icon_displayRenderedIcon() {
    var self = this;
    this.loadRenderedIcon(function cleanup(url) {
      self.img.style.visibility = 'visible';
      window.URL.revokeObjectURL(url);
      if (self.needsShow)
        self.show();
    });
  },

  show: function icon_show() {
    // Wait for the icon image to load until we start the animation.
    if (!this.img.naturalWidth) {
      this.needsShow = true;
      return;
    }

    this.needsShow = false;
    var container = this.container;
    container.dataset.visible = true;
    container.addEventListener('animationend', function animationEnd(e) {
      container.removeEventListener('animationend', animationEnd);
      delete container.dataset.visible;
    });
  },

  updateAppStatus: function icon_updateAppStatus(app) {
    if (app) {
      this.downloading = app.downloading;
      this.cancelled = (app.installState === 'pending') && !app.downloading;
    } else {
      this.downloading = false;
      this.cancelled = false;
    }
  },

  update: function icon_update(descriptor, app) {
    this.app = app;
    this.updateAppStatus(app);
    var oldDescriptor = this.descriptor;
    this.descriptor = descriptor;
    descriptor.removable === true ? this.appendOptions() : this.removeOptions();

    if (descriptor.updateTime == oldDescriptor.updateTime &&
        descriptor.icon == oldDescriptor.icon) {
      this.descriptor.renderedIcon = oldDescriptor.renderedIcon;
    } else {
      this.descriptor.oldRenderedIcon = oldDescriptor.renderedIcon;
      this.fetchImageData();
    }
    if (descriptor.updateTime != oldDescriptor.updateTime ||
        descriptor.name != oldDescriptor.name ||
        descriptor.localizedName != oldDescriptor.localizedName) {
      this.translate();
    }
  },

  showDownloading: function icon_showDownloading() {
    this.img.src = this.DOWNLOAD_ICON_URL;
    this.container.style.visibility = 'visible';
    this.icon.classList.add('loading');
  },

  showCancelled: function icon_showCancelled() {
    this.img.src = this.CANCELED_ICON_URL;
    this.container.style.visibility = 'visible';
    this.icon.classList.remove('loading');
    this.fetchImageData();
  },

  remove: function icon_remove() {
    this.container.parentNode.removeChild(this.container);
  },

  /*
   * Translates the label of the icon
   */
  translate: function icon_translate() {
    var descriptor = this.descriptor;
    if (descriptor.bookmarkURL)
      return;

    var app = this.app;
    if (!app)
      return;

    var manifest = app.manifest || app.updateManifest;
    if (!manifest)
      return;

    var iconsAndNameHolder = manifest;
    var entryPoint = descriptor.entry_point;
    if (entryPoint)
      iconsAndNameHolder = manifest.entry_points[entryPoint];

    var localizedName = new ManifestHelper(iconsAndNameHolder).name;

    this.label.textContent = localizedName;
    if (descriptor.localizedName != localizedName) {
      descriptor.localizedName = localizedName;
      GridManager.markDirtyState();
    }

    this.applyOverflowTextMask();
  },

  /*
   * This method is invoked when the drag gesture starts
   *
   * @param{int} x-coordinate
   *
   * @param{int} y-coordinate
   */
  onDragStart: function icon_onDragStart(x, y) {
    this.initX = x;
    this.initY = y;

    var draggableElem = this.draggableElem = document.createElement('div');
    draggableElem.className = 'draggable';

    // For some reason, cloning and moving a node re-triggers the blob
    // URI to be validated. So we assign a new blob URI to the image
    // and don't revoke it until we're finished with the animation.
    this.loadRenderedIcon();

    var icon = this.icon.cloneNode();
    var img = icon.querySelector('img');
    img.style.visibility = 'hidden';
    img.onload = img.onerror = function unhide() {
      img.style.visibility = 'visible';
    };
    draggableElem.appendChild(icon);

    var container = this.container;
    container.dataset.dragging = 'true';

    var rectangle = container.getBoundingClientRect();
    var style = draggableElem.style;
    style.left = rectangle.left + 'px';
    style.top = rectangle.top + 'px';
    this.initXCenter = (rectangle.left + rectangle.right) / 2;
    this.initYCenter = (rectangle.top + rectangle.bottom) / 2;
    this.initHeight = rectangle.bottom - rectangle.top;

    document.body.appendChild(draggableElem);
  },

  addClassToDragElement: function icon_addStyleToDragElement(className) {
    this.draggableElem.classList.add(className);
  },

  removeClassToDragElement: function icon_addStyleToDragElement(className) {
    this.draggableElem.classList.remove(className);
  },

  /*
   * This method is invoked when the drag gesture finishes
   */
  onDragStop: function icon_onDragStop(callback) {
    var container = this.container;

    var rect = container.getBoundingClientRect();
    var x = (Math.abs(rect.left + rect.right) / 2) % window.innerWidth;
    x -= this.initXCenter;

    var y = (rect.top + rect.bottom) / 2 +
            (this.initHeight - (rect.bottom - rect.top)) / 2;
    y -= this.initYCenter;

    var draggableElem = this.draggableElem;
    var style = draggableElem.style;
    style.MozTransition = '-moz-transform .4s';
    style.MozTransform = 'translate(' + x + 'px,' + y + 'px)';

    var finishDrag = function() {
      delete container.dataset.dragging;
      if (draggableElem) {
        var img = draggableElem.querySelector('img');
        window.URL.revokeObjectURL(img.src);
        draggableElem.parentNode.removeChild(draggableElem);
      }
      callback();
    };

    // We ensure that there is not an icon lost on the grid
    var fallbackID = window.setTimeout(function() {
      fallbackID = null;
      finishDrag();
    }, this.FALLBACK_DRAG_STOP_DELAY);

    var content = draggableElem.querySelector('div');
    content.style.MozTransform = 'scale(1)';
    content.addEventListener('transitionend', function tEnd(e) {
      e.target.removeEventListener('transitionend', tEnd);
      if (fallbackID !== null) {
        window.clearTimeout(fallbackID);
        finishDrag();
      }
    });
  },

  getTop: function icon_getTop() {
    return this.container.getBoundingClientRect().top;
  },

  getLeft: function icon_getLeft() {
    return this.container.getBoundingClientRect().left;
  }
};

function TemplateIcon(isBookmark) {
  var descriptor = {
    name: 'templateIcon',
    hidden: true,
    renderedIcon: null
  };

  var app = {};
  if (isBookmark) {
    app.iconable = true;
  }

  Icon.call(this, descriptor, app);
}

TemplateIcon.prototype = {
  __proto__: Icon.prototype,
  loadDefaultIcon: function ticon_loadDefaultIcon() {
    var image = new Image();
    var self = this;
    image.src = getDefaultIcon(self.app);
    image.onload = function icon_defaultIconLoadSucess() {
      image.onload = null;
      self.renderImage(image);
    };
  },
  renderBlob: function ticon_renderBlob(blob) {
    this.descriptor.renderedIcon = blob;
  }
};

/*
 * Page constructor
 *
 * @param {HTMLElement] container
 *                      HTML container element of the page.
 *
 * @param {Array} icons [optional]
 *                List of Icon objects.
 */
function Page(container, icons) {
  this.container = this.movableContainer = container;
  if (icons)
    this.render(icons);
  this.iconsWhileDragging = [];
}

Page.prototype = {

  // After launching an app we disable the page during <this time> in order to
  // prevent multiple open-app animations
  DISABLE_TAP_EVENT_DELAY: 600,

  FALLBACK_READY_EVENT_DELAY: 1000,

  /*
   * Renders a page for a list of apps
   *
   * @param{Array} icons
   *               List of Icon objects.
   */
  render: function pg_render(icons) {
    this.olist = document.createElement('ol');
    for (var i = 0; i < icons.length; i++) {
      this.appendIcon(icons[i]);
    }
    this.container.appendChild(this.olist);
  },

  /*
   * Applies a translation effect to the page
   *
   * @param{int} scroll X
   * @param{int} duration
   */
  moveByWithEffect: function pg_moveByWithEffect(scrollX, duration) {
    var container = this.movableContainer;
    var style = container.style;
    style.MozTransform = 'translateX(' + scrollX + 'px)';
    style.MozTransition = '-moz-transform ' + duration + 'ms ease';
  },

  /*
   * Applies a translation to the page
   *
   * @param{int} scroll X
   */
  moveBy: function pg_moveBy(scrollX) {
    var style = this.movableContainer.style;
    style.MozTransform = 'translateX(' + scrollX + 'px)';
    style.MozTransition = '';
  },

  ready: true,

  setReady: function pg_setReady(value) {
    this.ready = value;
    if (value) {
      this.container.dispatchEvent(new CustomEvent('onpageready'));
    }
  },

  /*
   * Changes position between two icons
   *
   * @param {Icon} originIcon
   *               The origin icon that's being dragged.
   *
   * @param {Icon} targetIcon
   *               The target icon that is replaced by the origin icon.
   */
  drop: function pg_drop(originIcon, targetIcon) {
    if (!this.ready || originIcon === targetIcon) {
      return;
    }

    this.setReady(false);

    var iconList = this.olist.children;
    if (originIcon && targetIcon && iconList.length > 1) {
      if (this.iconsWhileDragging.length === 0)
        this.iconsWhileDragging = Array.prototype.slice.call(iconList, 0,
                                                             iconList.length);

      this.animate(this.iconsWhileDragging, originIcon.container,
                   targetIcon.container);
    } else {
      setTimeout(this.setReady.bind(this, true));
    }
  },

  animate: function pg_animate(children, draggableNode, targetNode) {
    var draggableIndex = children.indexOf(draggableNode);
    var targetIndex = children.indexOf(targetNode);

    if (draggableIndex === -1 || targetIndex === -1) {
      // Index is outside the bounds of the array, it doesn't make sense
      setTimeout(this.setReady.bind(this, true));
      return;
    }

    var upward = draggableIndex < targetIndex;
    this.draggableNode = draggableNode;
    this.beforeNode = upward ? targetNode.nextSibling : targetNode;
    this.placeIcon(draggableNode, draggableIndex, targetIndex);

    var self = this;
    targetNode.addEventListener('transitionend', function onTransitionEnd(e) {
      e.target.removeEventListener('transitionend', onTransitionEnd);
      children.splice(draggableIndex, 1);
      children.splice(targetIndex, 0, draggableNode);
      setTimeout(self.setReady.bind(self, true));
    });

    if (upward) {
      for (var i = draggableIndex + 1; i <= targetIndex; i++)
        this.placeIcon(children[i], i, i - 1, DRAGGING_TRANSITION);
    } else {
      for (var i = targetIndex; i < draggableIndex; i++)
        this.placeIcon(children[i], i, i + 1, DRAGGING_TRANSITION);
    }
  },

  doDragLeave: function pg_doReArrange(callback, reflow) {
    this.iconsWhileDragging.forEach(function reset(node) {
      node.style.MozTransform = node.style.MozTransition = '';
      delete node.dataset.posX;
      delete node.dataset.posY;
    });

    this.iconsWhileDragging = [];

    if (reflow && this.olist.contains(this.draggableNode))
      this.olist.insertBefore(this.draggableNode, this.beforeNode);

    callback();
  },

  onDragLeave: function pg_onDragLeave(callback, reflow) {
    if (this.iconsWhileDragging.length === 0) {
      setTimeout(callback);
      return;
    }

    if (!this.ready) {
      var self = this;
      var ensureCallbackID = null;
      self.container.addEventListener('onpageready', function onPageReady(e) {
        e.target.removeEventListener('onpageready', onPageReady);
        if (ensureCallbackID !== null) {
          window.clearTimeout(ensureCallbackID);
          self.doDragLeave(callback, reflow);
        }
      });

      // We ensure that there is not a transitionend lost on dragging
      ensureCallbackID = window.setTimeout(function() {
        ensureCallbackID = null;
        self.container.removeEventListener('onpageready', onPageReady);
        self.doDragLeave(callback, reflow);
      }, this.FALLBACK_READY_EVENT_DELAY);

      return;
    }

    this.doDragLeave(callback, reflow);
  },

  placeIcon: function pg_placeIcon(node, from, to, transition) {
    if (!node)
      return;

    var x = node.dataset.posX = parseInt(node.dataset.posX || 0) +
                      ((Math.floor(to % 4) - Math.floor(from % 4)) * 100);
    var y = node.dataset.posY = parseInt(node.dataset.posY || 0) +
                      ((Math.floor(to / 4) - Math.floor(from / 4)) * 100);

    window.mozRequestAnimationFrame(function() {
      node.style.MozTransform = 'translate(' + x + '%, ' + y + '%)';
      if (transition)
        node.style.MozTransition = transition;
    });
  },

  /*
   * Implements the tap behaviour
   *
   * @param{Object} DOM element
   */
  tap: function pg_tap(elem) {
    if (Homescreen.isInEditMode()) {
      if (elem.classList.contains('options')) {
        var icon = GridManager.getIcon(elem.parentNode.dataset);
        if (icon.app)
          Homescreen.showAppDialog(icon.app);
      }
    } else if ('isIcon' in elem.dataset &&
               !this.olist.getAttribute('disabled')) {
      var icon = GridManager.getIcon(elem.dataset);
      if (!icon.app)
        return;

      if (icon.descriptor.entry_point) {
        icon.app.launch(icon.descriptor.entry_point);
        this.disableTap();
        return;
      }

      if (icon.cancelled) {
        GridManager.showRestartDownloadDialog(icon);
        return;
      }
      icon.app.launch();
      this.disableTap();
    }
  },

  /*
   * Disables the tap event for the page
   *
   * @param{Integer} milliseconds
   */
  disableTap: function pg_disableTap(icon, time) {
    var olist = this.olist;
    olist.setAttribute('disabled', true);
    setTimeout(function disableTapTimeout() {
      olist.removeAttribute('disabled');
    }, time || this.DISABLE_TAP_EVENT_DELAY);
  },

  /*
   * Adds an icon to the begining of the page
   *
   * @param{Object} icon object
   */
  prependIcon: function pg_prependIcon(icon) {
    var olist = this.olist;
    if (olist.children.length > 0) {
      olist.insertBefore(icon.container, olist.firstChild);
    } else {
      olist.appendChild(icon.container);
    }
  },

  /*
   * Removes the last icon of the page and returns it
   */
  popIcon: function pg_popIcon() {
    var icon = this.getLastIcon();
    icon.remove();
    return icon;
  },

  insertBeforeLastIcon: function pg_insertBeforeLastIcon(icon) {
    var olist = this.olist;
    if (olist.children.length > 0) {
      olist.insertBefore(icon.container, olist.lastChild);
    }
  },

  /*
   * Returns the last icon of the page
   */
  getLastIcon: function pg_getLastIcon() {
    var lastIcon = this.olist.lastChild;
    if (this.iconsWhileDragging.length > 0)
      lastIcon = this.iconsWhileDragging[this.iconsWhileDragging.length - 1];

    if (!lastIcon)
      return null;
    return GridManager.getIcon(lastIcon.dataset);
  },

  /*
   * Returns the first icon of the page
   */
  getFirstIcon: function pg_getFirstIcon() {
    var firstIcon = this.olist.firstChild;
    if (this.iconsWhileDragging.length > 0)
      firstIcon = this.iconsWhileDragging[0];

    if (!firstIcon)
      return null;
    return GridManager.getIcon(firstIcon.dataset);
  },

  /*
   * Appends an icon to the end of the page
   *
   * @param{Object} moz app or icon object
   */
  appendIcon: function pg_appendIcon(icon) {
    if (!icon.container) {
      icon.render(this.olist, this.container);
      return;
    }
    this.olist.appendChild(icon.container);
  },

  /**
   * Appends an icon to the end of the page
   * If the page is already full, then we insert the icon at the last place, and
   * the icon that was at the last place and will be hidden will eventually flow
   * to the next page. This is done in GridManager's ensurePagesOverflow
   *
   * @param {Object} icon the icon to be added.
   */
  appendIconVisible: function pg_appendIconVisible(icon) {
    if (this.getNumIcons() >= GridManager.pageHelper.maxIconsPerPage) {
      this.insertBeforeLastIcon(icon);
    } else {
      this.appendIcon(icon);
    }
  },

  containsIcon: function pg_containsIcon(icon) {
    return icon.container.parentNode === this.olist;
  },

  /*
   * Removes the page container from the DOM tree.
   *
   * @note This does *not* take care of any icons that are left on
   * this page. Their DOM elements will be lost unless these icons are
   * explicitly moved to different pages.
   */
  destroy: function pg_destroy() {
    this.container.parentNode.removeChild(this.container);
  },

  /*
   * Returns the number of icons
   */
  getNumIcons: function pg_getNumIcons() {
    return this.olist.children.length;
  },

  /**
   * Marshall the page's state.
   */
  getIconDescriptors: function pg_getIconDescriptors() {
    var nodes = this.olist.children;
    return Array.prototype.map.call(nodes, function marshall(node) {
      var icon = GridManager.getIcon(node.dataset);
      return icon.descriptor;
    });
  }
};

function getDefaultIcon(app) {
  if (app && app.iconable) {
    return Icon.prototype.DEFAULT_BOOKMARK_ICON_URL;
  } else {
    return Icon.prototype.DEFAULT_ICON_URL;
  }
}

function extend(subClass, superClass) {
  var F = function() {};
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;
  subClass.uber = superClass.prototype;
}

function Dock(container, icons) {
  Page.call(this, container, icons);
}

extend(Dock, Page);

var dockProto = Dock.prototype;

dockProto.baseRender = Page.prototype.render;

dockProto.render = function dk_render(apps, target) {
  this.baseRender(apps, target);
  this.movableContainer = this.olist;
};

dockProto.moveByWithEffect = function dk_moveByWithEffect(scrollX, duration) {
  var container = this.movableContainer;
  var style = container.style;
  style.MozTransform = 'translateX(' + scrollX + 'px)';
  style.MozTransition = '-moz-transform ' + duration + 'ms ease';
};

dockProto.moveByWithDuration = function dk_moveByWithDuration(scrollX,
                                                              duration) {
  var style = this.movableContainer.style;
  style.MozTransform = 'translateX(' + scrollX + 'px)';
  style.MozTransition = '-moz-transform ' + duration + 'ms ease';
};

dockProto.getLeft = function dk_getLeft() {
  return this.olist.getBoundingClientRect().left;
};

dockProto.getTransform = function dk_getTransform() {
  return this.movableContainer.style.MozTransform;
};

dockProto.getRight = function dk_getRight() {
  return this.getLeft() + this.getWidth();
};

dockProto.getWidth = function dk_getWidth() {
  return this.olist.clientWidth;
};

dockProto.placeIcon = function pg_placeIcon(node, from, to, transition) {
  if (!node)
    return;

  var x = node.dataset.posX = parseInt(node.dataset.posX || 0) + (to - from) *
                              100;

  node.style.MozTransform = 'translateX(' + x + '%)';
  if (transition)
    node.style.MozTransition = transition;
};

const TextOverflowDetective = (function() {

  var iconFakeWrapperWidth;
  var iconFakeLabel;

  function init() {
    var fakeIconName = document.querySelector('#fake-icon-name-wrapper');
    iconFakeWrapperWidth = fakeIconName.offsetWidth;
    iconFakeLabel = document.querySelector('#fake-icon-name');
  }

  function check(text) {
    if (!iconFakeLabel || !iconFakeWrapperWidth) {
      init();
    }
    iconFakeLabel.textContent = text;
    return iconFakeLabel.offsetWidth >= iconFakeWrapperWidth;
  }

  return {
    check: check
  };
})();


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

using Microsoft.VisualStudio.TestTools.UnitTesting;

using Moq;

using PicnicOrm.Data;
using PicnicOrm.Mapping;
using PicnicOrm.TestModels;

namespace PicnicOrm.UnitTests.Mapping
{
    [TestClass]
    public class OneToManyMappingShould
    {
        #region Properties

        public Mock<IChildMapping<OneToManyItem>> MockChildMapping { get; set; }

        public Mock<IGridReader> MockGridReader { get; set; }

        public OneToManyMapping<ParentItem, OneToManyItem> OneToManyMapping { get; set; }

        #endregion

        #region Public Methods

        [TestInitialize]
        public void Initialize()
        {
            MockChildMapping = new Mock<IChildMapping<OneToManyItem>>();
            MockGridReader = new Mock<IGridReader>();

            OneToManyMapping = new OneToManyMapping<ParentItem, OneToManyItem>(child => child.Id, child => child.ParentId, (parent, children) => parent.Children = children.ToList());
        }

        [TestMethod]
        public void Map_HasNoResultsAndShouldContinueThroughEmptyTablesIsFalse_DoesNotMapChildren()
        {
            //Arrange
            var oneToManyItemList = new List<OneToManyItem>();
            MockGridReader.Setup(gridReader => gridReader.Read<OneToManyItem>()).Returns(oneToManyItemList);
            OneToManyMapping.AddMapping(MockChildMapping.Object);
            IDictionary<int, ParentItem> parents = null;

            //Act
            OneToManyMapping.Map(MockGridReader.Object, parents, false);

            //Assert
            MockChildMapping.Verify(childMapping => childMapping.Map(It.IsAny<IGridReader>(), It.IsAny<IDictionary<int, OneToManyItem>>(), It.IsAny<bool>()), Times.Never);
        }

        [TestMethod]
        public void Map_HasNoResultsAndShouldContinueThroughEmptyTablesIsTrue_MapsChildren()
        {
            //Arrange
            var oneToManyItemList = new List<OneToManyItem>();
            MockGridReader.Setup(gridReader => gridReader.Read<OneToManyItem>()).Returns(oneToManyItemList);
            OneToManyMapping.AddMapping(MockChildMapping.Object);
            IDictionary<int, ParentItem> parents = null;

            //Act
            OneToManyMapping.Map(MockGridReader.Object, parents, true);

            //Assert
            MockChildMapping.Verify(childMapping => childMapping.Map(It.IsAny<IGridReader>(), It.IsAny<IDictionary<int, OneToManyItem>>(), It.IsAny<bool>()), Times.Once);
        }

        [TestMethod]
        public void Map_HasResultsAndParents_MapsParents()
        {
            //Arrange
            var oneToManyItem = new OneToManyItem { Id = 5, ParentId = 1 };
            var oneToManyItem2 = new OneToManyItem { Id = 18, ParentId = 5 };
            var oneToManyItem3 = new OneToManyItem { Id = 23, ParentId = 1 };
            var oneToManyItemList = new List<OneToManyItem> { oneToManyItem, oneToManyItem2, oneToManyItem3 };
            MockGridReader.Setup(gridReader => gridReader.Read<OneToManyItem>()).Returns(oneToManyItemList);
            var parent = new ParentItem { ChildId = 5 };
            var parentDictionary = new Dictionary<int, ParentItem> { [1] = parent };

            //Act
            OneToManyMapping.Map(MockGridReader.Object, parentDictionary, true);

            //Assert
            Assert.IsNull(parentDictionary[1].Child);
            Assert.AreEqual(2, parentDictionary[1].Children.Count);
            Assert.AreEqual(oneToManyItem, parentDictionary[1].Children[0]);
            Assert.AreEqual(oneToManyItem3, parentDictionary[1].Children[1]);
        }

        [TestMethod]
        public void Map_HasResultsAndShouldContinueThroughEmptyTablesIsFalse_MapsChildren()
        {
            //Arrange
            var oneToManyItem = new OneToManyItem();
            var oneToManyItemList = new List<OneToManyItem> { oneToManyItem };
            MockGridReader.Setup(gridReader => gridReader.Read<OneToManyItem>()).Returns(oneToManyItemList);
            OneToManyMapping.AddMapping(MockChildMapping.Object);
            IDictionary<int, ParentItem> parents = null;

            //Act
            OneToManyMapping.Map(MockGridReader.Object, parents, false);

            //Assert
            MockChildMapping.Verify(childMapping => childMapping.Map(It.IsAny<IGridReader>(), It.IsAny<IDictionary<int, OneToManyItem>>(), It.IsAny<bool>()), Times.Once);
        }

        #endregion
    }
}


text:
/*
==================================================================================
-- Vendor packages for webpack ---------------------------------------------------
==================================================================================
** This is where all vendor resources will be imported                          **
** This file is used by webpack to include stable vendor packages               **
** The webpack file is located here: GOATstack/config/webpack/webpack.common.js **
==================================================================================
*/

// Angular
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';

import '@angular/material';
import 'hammerjs/hammer';

// RxJS
import 'rxjs';

import '@angular-redux/store';
import 'lodash';
import 'ng2-cookies/ng2-cookies';

// Other vendors for example jQuery, Lodash or Bootstrap
// You can import js, ts, css, sass, ...

require('./styles');


text:
using GraphQL.SystemTextJson;
using GraphQL.Types;
using Microsoft.Extensions.DependencyInjection;

namespace GraphQL.Tests.Bugs;

public class Bug3100
{
    [Fact]
    public async Task OverrideAutoGraphTypeWithinDI()
    {
        // set up service collection and default services
        var services = new ServiceCollection();
        services.AddGraphQL(b => b
            .AddSchema<Schema1>()
            .AddAutoClrMappings(true, true));
        services.AddTransient<Query1>();

        // this test works without the next line of code here
        services.AddTransient(typeof(AutoRegisteringObjectGraphType<>), typeof(MyAutoGraphType<>));

        // run the sample query
        var provider = services.BuildServiceProvider();
        var executer = provider.GetRequiredService<IDocumentExecuter<ISchema>>();
        var serializer = new GraphQLSerializer();
        var result = await executer.ExecuteAsync(new ExecutionOptions
        {
            Query = "{class2{id}}",
            RequestServices = provider,
        }).ConfigureAwait(false);
        var actual = serializer.Serialize(result);

        // verify the result
        actual.ShouldBe("""{"data":{"class2":[{"id":"test"}]}}""");
    }

    private class MyAutoGraphType<T> : AutoRegisteringObjectGraphType<T>
    {
        // this class contains no code and should perform identical to the type it derives from
    }

    private class Schema1 : Schema
    {
        public Schema1(IServiceProvider serviceProvider) : base(serviceProvider)
        {
            Query = serviceProvider.GetRequiredService<Query1>();
        }
    }

    private class Query1 : ObjectGraphType
    {
        public Query1()
        {
            Field("Class2", typeof(NonNullGraphType<ListGraphType<NonNullGraphType<GraphQLClrOutputTypeReference<Class2>>>>))
                .Resolve(_ => new Class2[] { new Class2() });
        }
    }

    private class Class2
    {
        public string Id { get; set; } = "test";
    }
}


text:
<?php

namespace Emarref\Jwt\Verification;

use Emarref\Jwt\Claim;

class AudienceVerifierTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $payload;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $token;

    public function setUp()
    {
        $this->payload = $this->getMockBuilder('Emarref\Jwt\Token\Payload')->getMock();

        $this->token = $this->getMockBuilder('Emarref\Jwt\Token')->getMock();
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Cannot verify invalid audience value.
     */
    public function testInvalidAudience()
    {
        new AudienceVerifier(new \stdClass());
    }

    public function testNoAudienceInToken()
    {
        $this->token->expects($this->once())
            ->method('getPayload')
            ->will($this->returnValue($this->payload));

        $this->payload->expects($this->once())
            ->method('findClaimByName')
            ->with(Claim\Audience::NAME)
            ->will($this->returnValue(null));

        $verifier = new AudienceVerifier();
        $verifier->verify($this->token);
    }

    /**
     * @expectedException Emarref\Jwt\Exception\VerificationException
     * @expectedExceptionMessage Audience is invalid.
     */
    public function testInvalidAudienceInToken()
    {
        $expectedAudience = 'urn://myaudience';

        $audienceClaim = $this->getMockBuilder('Emarref\Jwt\Claim\Audience')->getMock();

        $audienceClaim->expects($this->once())
            ->method('getValue')
            ->will($this->returnValue($expectedAudience));

        $this->payload->expects($this->once())
            ->method('findClaimByName')
            ->with(Claim\Audience::NAME)
            ->will($this->returnValue($audienceClaim));

        $this->token->expects($this->once())
            ->method('getPayload')
            ->will($this->returnValue($this->payload));

        $verifier = new AudienceVerifier('foobar');
        $verifier->verify($this->token);
    }

    public function testArrayAudience()
    {
        $audienceClaim = $this->getMockBuilder('Emarref\Jwt\Claim\Audience')->getMock();

        $audienceClaim->expects($this->once())
                      ->method('getValue')
                      ->will($this->returnValue(['urn://audienceone', 'urn://audiencetwo']));

        $this->payload->expects($this->once())
                      ->method('findClaimByName')
                      ->with(Claim\Audience::NAME)
                      ->will($this->returnValue($audienceClaim));

        $this->token->expects($this->once())
                    ->method('getPayload')
                    ->will($this->returnValue($this->payload));

        $verifier = new AudienceVerifier('urn://audienceone');
        $verifier->verify($this->token);
    }

    public function testStringAudience()
    {
        $audienceClaim = $this->getMockBuilder('Emarref\Jwt\Claim\Audience')->getMock();

        $audienceClaim->expects($this->once())
                      ->method('getValue')
                      ->will($this->returnValue('urn://audienceone'));

        $this->payload->expects($this->once())
                      ->method('findClaimByName')
                      ->with(Claim\Audience::NAME)
                      ->will($this->returnValue($audienceClaim));

        $this->token->expects($this->once())
                    ->method('getPayload')
                    ->will($this->returnValue($this->payload));

        $verifier = new AudienceVerifier('urn://audienceone');
        $verifier->verify($this->token);
    }
}


text:
using System;
using ObjCRuntime;

[assembly: LinkWith ("libInfColorPickerSDK.a", LinkTarget.Simulator, SmartLink = true, ForceLoad = true)]


text:
package com.yiqiniu.easytrans.rpc.impl.dubbo;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
* @author xudeyou
*/

@ConfigurationProperties(prefix="easytrans.rpc.dubbo")
public class DubboEasyTransRpcProperties {

	private Boolean enabled;

	public Boolean getEnabled() {
		return enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

}


text:
magmex
======

MAGMEX : Exports from Magento Database.

Helper to work with [MAGMI](https://github.com/dweeves/magmi-git), to get formatted .csv file export from Magento database to be edited for MAGMI imports.

Note: This is a work in progress
================================


text:
<?php

declare(strict_types=1);

namespace SD\Admin\Model;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\Tools\Pagination\Paginator as ORMPaginator;
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as PaginatorAdapter;
use SD\Admin\Entity\User;
use Zend\Paginator\Paginator as ZendPaginator;

final class UserTable implements AbstractTableInterface
{
    /*
     * @var ObjectManager
     */
    private $objectManager;

    /*
     * @var object
     */
    private $objectRepository;

    /**
     * @param ObjectManager    $objectManager
     * @param ObjectRepository $objectRepository
     */
    public function __construct(ObjectManager $objectManager, ObjectRepository $objectRepository)
    {
        $this->objectManager = $objectManager;
        $this->objectRepository = $objectRepository;
    }

    /**
     * @return object
     */
    public function queryBuilder()
    {
        return $this->objectManager->createQueryBuilder();
    }

    /**
     * @param \Doctrine\ORM\Query|\Doctrine\ORM\QueryBuilder $query               A Doctrine ORM query or query builder.
     * @param bool                                           $fetchJoinCollection Whether the query joins a collection (true by default).
     *
     * @return ZendPaginator
     */
    public function preparePagination($query, bool $fetchJoinCollection = true) : ZendPaginator
    {
        return new ZendPaginator(new PaginatorAdapter(new ORMPaginator($query, $fetchJoinCollection)));
    }

    /**
     * @return object
     */
    public function getEntityRepository()
    {
        return $this->objectRepository;
    }

    /**
     * @param int $userId user id
     *
     * @return User
     */
    public function getUser(int $userId = 0) : User
    {
        $user = $this->getEntityRepository()->find($userId);

        if (empty($user)) {
            throw new \Exception('User not found');
        }

        return $user;
    }

    /**
     * This method can disable or enable user accounts.
     *
     * @param int $userId user id
     * @param int $state  0 - enabled, 1 - disabled
     */
    public function toggleUserState(int $userId = 0, int $state = 0)
    {
        $user = $this->getUser($userId);
        if ($user) {
            $user->setDisabled((int) $state);
            $user->setAdmin(0); // doesn't matter the $state. Remove user admin rights.
            $this->saveUser($user);
        }
    }

    /**
     * Update user based on the provided id.
     *
     * @param User $user
     *
     * @return User
     */
    public function saveUser(User $user)
    {
        $this->objectManager->persist($user);
        $this->objectManager->flush();

        return $user;
    }
}


text:
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/vmstat.h>
#include <linux/highmem.h>
#include <asm/pgtable.h>

static inline pte_t gup_get_pte(pte_t *ptep)
{
#ifndef CONFIG_X2TLB
	return ACCESS_ONCE(*ptep);
#else
	/*
	 * With get_user_pages_fast, we walk down the pagetables without
	 * taking any locks.  For this we would like to load the pointers
	 * atomically, but that is not possible with 64-bit PTEs.  What
	 * we do have is the guarantee that a pte will only either go
	 * from not present to present, or present to not present or both
	 * -- it will not switch to a completely different present page
	 * without a TLB flush in between; something that we are blocking
	 * by holding interrupts off.
	 *
	 * Setting ptes from not present to present goes:
	 * ptep->pte_high = h;
	 * smp_wmb();
	 * ptep->pte_low = l;
	 *
	 * And present to not present goes:
	 * ptep->pte_low = 0;
	 * smp_wmb();
	 * ptep->pte_high = 0;
	 *
	 * We must ensure here that the load of pte_low sees l iff pte_high
	 * sees h. We load pte_high *after* loading pte_low, which ensures we
	 * don't see an older value of pte_high.  *Then* we recheck pte_low,
	 * which ensures that we haven't picked up a changed pte high. We might
	 * have got rubbish values from pte_low and pte_high, but we are
	 * guaranteed that pte_low will not have the present bit set *unless*
	 * it is 'l'. And get_user_pages_fast only operates on present ptes, so
	 * we're safe.
	 *
	 * gup_get_pte should not be used or copied outside gup.c without being
	 * very careful -- it does not atomically load the pte or anything that
	 * is likely to be useful for you.
	 */
	pte_t pte;

retry:
	pte.pte_low = ptep->pte_low;
	smp_rmb();
	pte.pte_high = ptep->pte_high;
	smp_rmb();
	if (unlikely(pte.pte_low != ptep->pte_low))
		goto retry;

	return pte;
#endif
}

/*
 * The performance critical leaf functions are made noinline otherwise gcc
 * inlines everything into a single function which results in too much
 * register pressure.
 */
static noinline int gup_pte_range(pmd_t pmd, unsigned long addr,
		unsigned long end, int write, struct page **pages, int *nr)
{
	u64 mask, result;
	pte_t *ptep;

#ifdef CONFIG_X2TLB
	result = _PAGE_PRESENT | _PAGE_EXT(_PAGE_EXT_KERN_READ | _PAGE_EXT_USER_READ);
	if (write)
		result |= _PAGE_EXT(_PAGE_EXT_KERN_WRITE | _PAGE_EXT_USER_WRITE);
#elif defined(CONFIG_SUPERH64)
	result = _PAGE_PRESENT | _PAGE_USER | _PAGE_READ;
	if (write)
		result |= _PAGE_WRITE;
#else
	result = _PAGE_PRESENT | _PAGE_USER;
	if (write)
		result |= _PAGE_RW;
#endif

	mask = result | _PAGE_SPECIAL;

	ptep = pte_offset_map(&pmd, addr);
	do {
		pte_t pte = gup_get_pte(ptep);
		struct page *page;

		if ((pte_val(pte) & mask) != result) {
			pte_unmap(ptep);
			return 0;
		}
		VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
		page = pte_page(pte);
		get_page(page);
		pages[*nr] = page;
		(*nr)++;

	} while (ptep++, addr += PAGE_SIZE, addr != end);
	pte_unmap(ptep - 1);

	return 1;
}

static int gup_pmd_range(pud_t pud, unsigned long addr, unsigned long end,
		int write, struct page **pages, int *nr)
{
	unsigned long next;
	pmd_t *pmdp;

	pmdp = pmd_offset(&pud, addr);
	do {
		pmd_t pmd = *pmdp;

		next = pmd_addr_end(addr, end);
		if (pmd_none(pmd))
			return 0;
		if (!gup_pte_range(pmd, addr, next, write, pages, nr))
			return 0;
	} while (pmdp++, addr = next, addr != end);

	return 1;
}

static int gup_pud_range(pgd_t pgd, unsigned long addr, unsigned long end,
			int write, struct page **pages, int *nr)
{
	unsigned long next;
	pud_t *pudp;

	pudp = pud_offset(&pgd, addr);
	do {
		pud_t pud = *pudp;

		next = pud_addr_end(addr, end);
		if (pud_none(pud))
			return 0;
		if (!gup_pmd_range(pud, addr, next, write, pages, nr))
			return 0;
	} while (pudp++, addr = next, addr != end);

	return 1;
}

/*
 * Like get_user_pages_fast() except its IRQ-safe in that it won't fall
 * back to the regular GUP.
 */
int __get_user_pages_fast(unsigned long start, int nr_pages, int write,
			  struct page **pages)
{
	struct mm_struct *mm = current->mm;
	unsigned long addr, len, end;
	unsigned long next;
	unsigned long flags;
	pgd_t *pgdp;
	int nr = 0;

	start &= PAGE_MASK;
	addr = start;
	len = (unsigned long) nr_pages << PAGE_SHIFT;
	end = start + len;
	if (unlikely(!access_ok(write ? VERIFY_WRITE : VERIFY_READ,
					(void __user *)start, len)))
		return 0;

	/*
	 * This doesn't prevent pagetable teardown, but does prevent
	 * the pagetables and pages from being freed.
	 */
	local_irq_save(flags);
	pgdp = pgd_offset(mm, addr);
	do {
		pgd_t pgd = *pgdp;

		next = pgd_addr_end(addr, end);
		if (pgd_none(pgd))
			break;
		if (!gup_pud_range(pgd, addr, next, write, pages, &nr))
			break;
	} while (pgdp++, addr = next, addr != end);
	local_irq_restore(flags);

	return nr;
}

/**
 * get_user_pages_fast() - pin user pages in memory
 * @start:	starting user address
 * @nr_pages:	number of pages from start to pin
 * @write:	whether pages will be written to
 * @pages:	array that receives pointers to the pages pinned.
 *		Should be at least nr_pages long.
 *
 * Attempt to pin user pages in memory without taking mm->mmap_sem.
 * If not successful, it will fall back to taking the lock and
 * calling get_user_pages().
 *
 * Returns number of pages pinned. This may be fewer than the number
 * requested. If nr_pages is 0 or negative, returns 0. If no pages
 * were pinned, returns -errno.
 */
int get_user_pages_fast(unsigned long start, int nr_pages, int write,
			struct page **pages)
{
	struct mm_struct *mm = current->mm;
	unsigned long addr, len, end;
	unsigned long next;
	pgd_t *pgdp;
	int nr = 0;

	start &= PAGE_MASK;
	addr = start;
	len = (unsigned long) nr_pages << PAGE_SHIFT;

	end = start + len;
	if (end < start)
		goto slow_irqon;

	local_irq_disable();
	pgdp = pgd_offset(mm, addr);
	do {
		pgd_t pgd = *pgdp;

		next = pgd_addr_end(addr, end);
		if (pgd_none(pgd))
			goto slow;
		if (!gup_pud_range(pgd, addr, next, write, pages, &nr))
			goto slow;
	} while (pgdp++, addr = next, addr != end);
	local_irq_enable();

	VM_BUG_ON(nr != (end - start) >> PAGE_SHIFT);
	return nr;

	{
		int ret;

slow:
		local_irq_enable();
slow_irqon:
		/* Try to get the remaining pages with get_user_pages */
		start += nr << PAGE_SHIFT;
		pages += nr;

		down_read(&mm->mmap_sem);
		ret = get_user_pages(current, mm, start,
			(end - start) >> PAGE_SHIFT, write, 0, pages, NULL);
		up_read(&mm->mmap_sem);

		/* Have to be a bit careful with return values */
		if (nr > 0) {
			if (ret < 0)
				ret = nr;
			else
				ret += nr;
		}

		return ret;
	}
}


text:
#include "config.h"

#include "GtkInputMethodFilter.h"
#include "WTFStringUtilities.h"
#include <gdk/gdkkeysyms.h>
#include <gtk/gtk.h>
#include <wtf/gobject/GOwnPtr.h>
#include <wtf/gobject/GRefPtr.h>
#include <wtf/text/CString.h>

using namespace WebCore;

namespace TestWebKitAPI {

class TestInputMethodFilter : public GtkInputMethodFilter {
public:
    TestInputMethodFilter()
        : m_testWindow(gtk_window_new(GTK_WINDOW_POPUP))
    {
        gtk_widget_show(m_testWindow.get());
        setWidget(m_testWindow.get());

        // Focus in is necessary to activate the default input method in the multicontext.
        notifyFocusedIn();
    }

    Vector<String>& events() { return m_events; }

    void sendKeyEventToFilter(unsigned int gdkKeyValue, GdkEventType type, unsigned int modifiers = 0)
    {
        GdkEvent* event = gdk_event_new(type);
        event->key.keyval = gdkKeyValue;
        event->key.state = modifiers;
        event->key.window = gtk_widget_get_window(m_testWindow.get());
        event->key.time = GDK_CURRENT_TIME;
        g_object_ref(event->key.window);

#ifndef GTK_API_VERSION_2
        gdk_event_set_device(event, gdk_device_manager_get_client_pointer(gdk_display_get_device_manager(gdk_display_get_default())));
#endif

        GOwnPtr<GdkKeymapKey> keys;
        gint nKeys;
        if (gdk_keymap_get_entries_for_keyval(gdk_keymap_get_default(), gdkKeyValue, &keys.outPtr(), &nKeys))
            event->key.hardware_keycode = keys.get()[0].keycode;

        filterKeyEvent(&event->key);
        gdk_event_free(event);
    }

    void sendPressAndReleaseKeyEventPairToFilter(unsigned int gdkKeyValue, unsigned int modifiers = 0)
    {
        sendKeyEventToFilter(gdkKeyValue, GDK_KEY_PRESS, modifiers);
        sendKeyEventToFilter(gdkKeyValue, GDK_KEY_RELEASE, modifiers);
    }

protected:
    virtual bool sendSimpleKeyEvent(GdkEventKey* event, WTF::String eventString)
    {
        const char* eventType = event->type == GDK_KEY_RELEASE ? "release" : "press";
        if (!eventString.isNull())
            m_events.append(String::format("sendSimpleKeyEvent type=%s keycode=%x text='%s'", eventType, event->keyval, eventString.utf8().data()));
        else
            m_events.append(String::format("sendSimpleKeyEvent type=%s keycode=%x", eventType, event->keyval));

        return true;
    }

    virtual bool sendKeyEventWithCompositionResults(GdkEventKey* event, ResultsToSend resultsToSend)
    {
        const char* eventType = event->type == GDK_KEY_RELEASE ? "release" : "press";
        m_events.append(String::format("sendKeyEventWithCompositionResults type=%s keycode=%u", eventType, event->keyval));

        if (resultsToSend & Composition && !m_confirmedComposition.isNull())
            confirmCompositionText(m_confirmedComposition);
        if (resultsToSend & Preedit && !m_preedit.isNull())
            setPreedit(m_preedit, m_cursorOffset);

        return true;
    }

    virtual bool canEdit()
    {
        return true;
    }

    virtual void confirmCompositionText(String text)
    {
        m_events.append(String::format("confirmComposition '%s'", text.utf8().data()));
    }

    virtual void confirmCurrentComposition()
    {
        m_events.append(String("confirmCurrentcomposition"));
    }

    virtual void cancelCurrentComposition()
    {
        m_events.append(String("cancelCurrentComposition"));
    }

    virtual void setPreedit(String preedit, int cursorOffset)
    {
        m_events.append(String::format("setPreedit text='%s' cursorOffset=%i", preedit.utf8().data(), cursorOffset));
    }

private:
    GRefPtr<GtkWidget> m_testWindow;
    Vector<String> m_events;
};

TEST(GTK, GtkInputMethodFilterSimple)
{
    TestInputMethodFilter inputMethodFilter;
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_g);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_t);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_k);

    const Vector<String>& events = inputMethodFilter.events();

    ASSERT_EQ(6, events.size());
    ASSERT_EQ(String("sendSimpleKeyEvent type=press keycode=67 text='g'"), events[0]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=67"), events[1]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=press keycode=74 text='t'"), events[2]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=74"), events[3]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=press keycode=6b text='k'"), events[4]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=6b"), events[5]);
}

TEST(GTK, GtkInputMethodFilterUnicodeSequence)
{
    TestInputMethodFilter inputMethodFilter;

    // This is simple unicode hex entry of the characters, u, 0, 0, f, 4 pressed with
    // the shift and controls keys held down. In reality, these values are not typical
    // of an actual hex entry, because they'd be transformed by the shift modifier according
    // to the keyboard layout. For instance, on a US keyboard a 0 with the shift key pressed
    // is a right parenthesis. Using these values prevents having to work out what the
    // transformed characters are based on the current keyboard layout.
    inputMethodFilter.sendKeyEventToFilter(GDK_KEY_Control_L, GDK_KEY_PRESS);
    inputMethodFilter.sendKeyEventToFilter(GDK_KEY_Shift_L, GDK_KEY_PRESS, GDK_CONTROL_MASK);

    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_U, GDK_SHIFT_MASK | GDK_CONTROL_MASK);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_0, GDK_SHIFT_MASK | GDK_CONTROL_MASK);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_0, GDK_SHIFT_MASK | GDK_CONTROL_MASK);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_F, GDK_SHIFT_MASK | GDK_CONTROL_MASK);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_4, GDK_SHIFT_MASK | GDK_CONTROL_MASK);

    inputMethodFilter.sendKeyEventToFilter(GDK_KEY_Shift_L, GDK_KEY_RELEASE, GDK_CONTROL_MASK | GDK_SHIFT_MASK);
    inputMethodFilter.sendKeyEventToFilter(GDK_KEY_Control_L, GDK_KEY_RELEASE, GDK_CONTROL_MASK);

    const Vector<String>& events = inputMethodFilter.events();
    ASSERT_EQ(21, events.size());
    ASSERT_EQ(String("sendSimpleKeyEvent type=press keycode=ffe3"), events[0]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=press keycode=ffe1"), events[1]);
    ASSERT_EQ(String("sendKeyEventWithCompositionResults type=press keycode=85"), events[2]);
    ASSERT_EQ(String("setPreedit text='u' cursorOffset=1"), events[3]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=55"), events[4]);
    ASSERT_EQ(String("sendKeyEventWithCompositionResults type=press keycode=48"), events[5]);
    ASSERT_EQ(String("setPreedit text='u0' cursorOffset=2"), events[6]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=30"), events[7]);
    ASSERT_EQ(String("sendKeyEventWithCompositionResults type=press keycode=48"), events[8]);
    ASSERT_EQ(String("setPreedit text='u00' cursorOffset=3"), events[9]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=30"), events[10]);
    ASSERT_EQ(String("sendKeyEventWithCompositionResults type=press keycode=70"), events[11]);
    ASSERT_EQ(String("setPreedit text='u00F' cursorOffset=4"), events[12]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=46"), events[13]);
    ASSERT_EQ(String("sendKeyEventWithCompositionResults type=press keycode=52"), events[14]);
    ASSERT_EQ(String("setPreedit text='u00F4' cursorOffset=5"), events[15]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=34"), events[16]);
    ASSERT_EQ(String("confirmComposition 'ô'"), events[17]);
    ASSERT_EQ(String("setPreedit text='' cursorOffset=0"), events[18]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=ffe1"), events[19]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=ffe3"), events[20]);
}

TEST(GTK, GtkInputMethodFilterComposeKey)
{
    TestInputMethodFilter inputMethodFilter;

    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_Multi_key);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_apostrophe);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_o);

    const Vector<String>& events = inputMethodFilter.events();
    ASSERT_EQ(5, events.size());
    ASSERT_EQ(String("sendKeyEventWithCompositionResults type=press keycode=39"), events[0]);
    ASSERT_EQ(String("setPreedit text='' cursorOffset=0"), events[1]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=27"), events[2]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=press keycode=6f text='ó'"), events[3]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=6f"), events[4]);
}

typedef void (*GetPreeditStringCallback) (GtkIMContext*, gchar**, PangoAttrList**, int*);
static void temporaryGetPreeditStringOverride(GtkIMContext*, char** string, PangoAttrList** attrs, int* cursorPosition)
{
    *string = g_strdup("preedit of doom, bringer of cheese");
    *cursorPosition = 3;
}

TEST(GTK, GtkInputMethodFilterContextEventsWithoutKeyEvents)
{
    TestInputMethodFilter inputMethodFilter;

    // This is a bit of a hack to avoid mocking out the entire InputMethodContext, by
    // simply replacing the get_preedit_string virtual method for the length of this test.
    GtkIMContext* context = inputMethodFilter.context();
    GtkIMContextClass* contextClass = GTK_IM_CONTEXT_GET_CLASS(context);
    GetPreeditStringCallback previousCallback = contextClass->get_preedit_string;
    contextClass->get_preedit_string = temporaryGetPreeditStringOverride;

    g_signal_emit_by_name(context, "preedit-changed");
    g_signal_emit_by_name(context, "commit", "commit text");

    contextClass->get_preedit_string = previousCallback;

    const Vector<String>& events = inputMethodFilter.events();
    ASSERT_EQ(6, events.size());
    ASSERT_EQ(String("sendKeyEventWithCompositionResults type=press keycode=16777215"), events[0]);
    ASSERT_EQ(String("setPreedit text='preedit of doom, bringer of cheese' cursorOffset=3"), events[1]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=ffffff"), events[2]);
    ASSERT_EQ(String("sendKeyEventWithCompositionResults type=press keycode=16777215"), events[3]);
    ASSERT_EQ(String("confirmComposition 'commit text'"), events[4]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=ffffff"), events[5]);
}

static bool gSawContextReset = false;
typedef void (*ResetCallback) (GtkIMContext*);
static void temporaryResetOverride(GtkIMContext*)
{
    gSawContextReset = true;
}

static void verifyCanceledComposition(const Vector<String>& events)
{
    ASSERT_EQ(4, events.size());
    ASSERT_EQ(String("sendKeyEventWithCompositionResults type=press keycode=39"), events[0]);
    ASSERT_EQ(String("setPreedit text='' cursorOffset=0"), events[1]);
    ASSERT_EQ(String("sendSimpleKeyEvent type=release keycode=27"), events[2]);
    ASSERT_EQ(String("confirmCurrentcomposition"), events[3]);
    ASSERT(gSawContextReset);
}

TEST(GTK, GtkInputMethodFilterContextFocusOutDuringOngoingComposition)
{
    TestInputMethodFilter inputMethodFilter;

    // See comment above about this technique.
    GtkIMContext* context = inputMethodFilter.context();
    GtkIMContextClass* contextClass = GTK_IM_CONTEXT_GET_CLASS(context);
    ResetCallback previousCallback = contextClass->reset;
    contextClass->reset = temporaryResetOverride;

    gSawContextReset = false;
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_Multi_key);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_apostrophe);
    inputMethodFilter.notifyFocusedOut();

    verifyCanceledComposition(inputMethodFilter.events());

    contextClass->reset = previousCallback;
}

TEST(GTK, GtkInputMethodFilterContextMouseClickDuringOngoingComposition)
{
    TestInputMethodFilter inputMethodFilter;

    // See comment above about this technique.
    GtkIMContext* context = inputMethodFilter.context();
    GtkIMContextClass* contextClass = GTK_IM_CONTEXT_GET_CLASS(context);
    ResetCallback previousCallback = contextClass->reset;
    contextClass->reset = temporaryResetOverride;

    gSawContextReset = false;
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_Multi_key);
    inputMethodFilter.sendPressAndReleaseKeyEventPairToFilter(GDK_KEY_apostrophe);
    inputMethodFilter.notifyMouseButtonPress();

    verifyCanceledComposition(inputMethodFilter.events());

    contextClass->reset = previousCallback;
}

} // namespace TestWebKitAPI


text:
Content Removed

This content has been removed due to a takedown request by the author.


text:
<?php

namespace Model;

/**
 * Repository of Model\SortableScopeReference document.
 */
class SortableScopeReferenceRepository extends \Model\Base\SortableScopeReferenceRepository
{
}


text:
\section{\_\-fixed  Union Reference}
\label{_fixed}\index{_fixed@{\_\-fixed}}
Useful definition for fixed point values.

{\tt \#include $<$asm/types.h$>$}

\subsection*{Public Members}
\begin{CompactItemize}
\item
\begin{tabbing}
xx\=xx\=xx\=xx\=xx\=xx\=xx\=xx\=xx\=\kill
\label{_fixed_a2}
\index{b@{b}!_fixed@{\_fixed}}\index{_fixed@{\_fixed}!b@{b}}
struct \{\\
\>{\bf UBYTE} {\bf l}\\
\>{\bf UBYTE} {\bf h}\\
\} {\bf b}
\end{tabbing}
\item
\label{_fixed_a3}
\index{w@{w}!_fixed@{\_\-fixed}}\index{_fixed@{\_\-fixed}!w@{w}}
{\bf UWORD} {\bf w}
\end{CompactItemize}
\vspace{0.4cm}\hrule\vspace{0.2cm}
\subsection*{Detailed Description}
Useful definition for fixed point values.

\vspace{0.4cm}\hrule\vspace{0.2cm}
The documentation for this union was generated from the following file:\begin{CompactItemize}
\item
{\bf asm/types.h}\end{CompactItemize}


text:
def autodiscover():
    """
    Import the feeds module from all the installed apps. The assumption is that
    apps will register their feed classes in that module. If not, they're SOL.
    """
    from django.conf import settings
    for app in settings.INSTALLED_APPS:
        feeds_mod = '.'.join([app, 'feed_readers'])
        try:
            __import__(feeds_mod)
        except ImportError:
            pass

class FeedReader (object):
    def get_content(self):
        """
        Returns the content items that appear in this feed.
        """
        raise NotImplementedError()

    def all(self):
        return self.get_content()

    def get_params(self):
        """
        Return a dictionary of keyword arguments that can be used to construct
        a feed reader identical to this one. The dictionary should be JSON
        serializable.
        """
        raise NotImplementedError()

    def get_updated_since(self, previous):
        """
        Return the content items that have been updated since the given time.
        """
        raise NotImplementedError()

    def get_changes_to(self, item, since):
        """
        Returns a dictionary representing the changes to the item.  The nature
        of this dictionary may vary depending on the item type.
        """
        raise NotImplementedError()

    def get_last_updated_time(self):
        """
        Return the latest time that any content in the feed was updated.
        """
        raise NotImplementedError()

    class NotFound (Exception):
        pass

class TimestampedModelFeedReader (FeedReader):
    def __init__(self, app_label, model_name, object_id, updated_datetime_field='updated_datetime'):
        self.app_label = app_label
        self.model_name = model_name
        self.object_id = object_id
        self.updated_datetime_field = updated_datetime_field

    def get_params(self):
        return {
            'app_label': self.app_label,
            'model_name': self.model_name,
            'object_id': self.object_id,
            'updated_datetime_field': self.updated_datetime_field
        }

    def get_content(self):
        if not hasattr(self, 'object_'):
            from django.contrib.contenttypes.models import ContentType
            content_type = ContentType.objects.get(app_label=self.app_label, model=self.model_name)
            self.object_ = content_type.get_object_for_this_type(pk=self.object_id)
        return [self.object_]

    def get_updated_since(self, previous):
        content = self.get_content()
        object_ = content[0]
        if getattr(object_, self.updated_datetime_field) > previous:
            return content
        else:
            return []

    def get_changes_to(self, item, since):
        # We don't know which attributes
        item, getattr(item, self.updated_datetime_field)

class RSSFeedReader (FeedReader):
    def __init__(self, url):
        self.url = url

    def get_content(self):
        import feedparser
        self.rss = feedparser.parse(self.url)
        return self.rss.entries

    def get_last_updated_time(self):
        from dateutil.parser import parse
        updated_time = parse(self.rss['updated'])
        return updated_time

    def get_updated_since(self, previous):
        from dateutil.parser import parse
        entries = self.get_content()
        return [entry for entry in entries if parse(entry.published) > previous]

    def get_changes_to(self, entry, since):
        """
        Returns a dictionary representing the changes to the item.  The nature
        of this dictionary may vary depending on the item type.
        """
        from dateutil.parser import parse
        return entry, parse(entry.published)

from subscriptions.feeds.library import FeedLibrary
library = FeedLibrary()
library.register(RSSFeedReader, 'rss')


text:
package net.ssehub.kernel_haven.code_model;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.util.Iterator;

import org.junit.Test;

import net.ssehub.kernel_haven.util.logic.True;

/**
 * Tests the {@link CodeBlock} class.
 *
 * @author Adam
 */
public class CodeBlockTest {

    /**
     * Tests the different getters for nested elements.
     */
    @Test
    public void testStructure() {
        CodeBlock main = new CodeBlock(1, 100, new File("test.c"), True.INSTANCE, True.INSTANCE);
        CodeBlock nested1 = new CodeBlock(True.INSTANCE);
        CodeBlock nested2 = new CodeBlock(True.INSTANCE);

        main.addNestedElement(nested1);
        main.addNestedElement(nested2);

        assertThat(main.getNestedElementCount(), is(2));
        assertThat(main.getNestedElement(0), sameInstance(nested1));
        assertThat(main.getNestedElement(1), sameInstance(nested2));

        Iterator<CodeBlock> iter = main.iterator();
        assertThat(iter.hasNext(), is(true));
        assertThat(iter.next(), sameInstance(nested1));
        assertThat(iter.hasNext(), is(true));
        assertThat(iter.next(), sameInstance(nested2));
        assertThat(iter.hasNext(), is(false));
    }

}


text:
package org.apache.solr.cloud;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import javax.management.JMException;

import org.apache.zookeeper.jmx.ManagedUtil;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.SessionTracker.Session;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZkTestServer {
  public static final int TICK_TIME = 1000;

  private static Logger log = LoggerFactory.getLogger(ZkTestServer.class);

  protected final ZKServerMain zkServer = new ZKServerMain();

  private String zkDir;

  private int clientPort;

  private Thread zooThread;

  private int theTickTime = TICK_TIME;

  class ZKServerMain {

    private ServerCnxnFactory cnxnFactory;
    private ZooKeeperServer zooKeeperServer;

    protected void initializeAndRun(String[] args) throws ConfigException,
        IOException {
      try {
        ManagedUtil.registerLog4jMBeans();
      } catch (JMException e) {
        log.warn("Unable to register log4j JMX control", e);
      }

      ServerConfig config = new ServerConfig();
      if (args.length == 1) {
        config.parse(args[0]);
      } else {
        config.parse(args);
      }

      runFromConfig(config);
    }

    /**
     * Run from a ServerConfig.
     * @param config ServerConfig to use.
     * @throws IOException If there is a low-level I/O error.
     */
    public void runFromConfig(ServerConfig config) throws IOException {
      log.info("Starting server");
      try {
        // Note that this thread isn't going to be doing anything else,
        // so rather than spawning another thread, we will just call
        // run() in this thread.
        // create a file logger url from the command line args
        zooKeeperServer = new ZooKeeperServer();

        FileTxnSnapLog ftxn = new FileTxnSnapLog(new File(
            config.getDataLogDir()), new File(config.getDataDir()));
        zooKeeperServer.setTxnLogFactory(ftxn);
        zooKeeperServer.setTickTime(config.getTickTime());
        zooKeeperServer.setMinSessionTimeout(config.getMinSessionTimeout());
        zooKeeperServer.setMaxSessionTimeout(config.getMaxSessionTimeout());
        cnxnFactory = ServerCnxnFactory.createFactory();
        cnxnFactory.configure(config.getClientPortAddress(),
            config.getMaxClientCnxns());
        cnxnFactory.startup(zooKeeperServer);
        cnxnFactory.join();
        if (zooKeeperServer.isRunning()) {
          zkServer.shutdown();
        }
      } catch (InterruptedException e) {
        // warn, but generally this is ok
        log.warn("Server interrupted", e);
      }
    }

    /**
     * Shutdown the serving instance
     * @throws IOException If there is a low-level I/O error.
     */
    protected void shutdown() throws IOException {
      zooKeeperServer.shutdown();
      ZKDatabase zkDb = zooKeeperServer.getZKDatabase();
      if (zkDb != null) {
        zkDb.close();
      }
      if (cnxnFactory != null && cnxnFactory.getLocalPort() != 0) {
        waitForServerDown(getZkHost() + ":" + getPort(), 5000);
      }
      if (cnxnFactory != null) {
        cnxnFactory.shutdown();
      }
    }

    public int getLocalPort() {
      if (cnxnFactory == null) {
        throw new IllegalStateException("A port has not yet been selected");
      }
      int port;
      try {
        port = cnxnFactory.getLocalPort();
      } catch (NullPointerException e) {
        throw new IllegalStateException("A port has not yet been selected");
      }
      if (port == 0) {
        throw new IllegalStateException("A port has not yet been selected");
      }
      return port;
    }
  }

  public ZkTestServer(String zkDir) {
    this.zkDir = zkDir;
  }

  public ZkTestServer(String zkDir, int port) {
    this.zkDir = zkDir;
    this.clientPort = port;
  }

  public String getZkHost() {
    return "127.0.0.1:" + zkServer.getLocalPort();
  }

  public String getZkAddress() {
    return "127.0.0.1:" + zkServer.getLocalPort() + "/solr";
  }

  public int getPort() {
    return zkServer.getLocalPort();
  }

  public void expire(final long sessionId) {
    zkServer.zooKeeperServer.expire(new Session() {
      @Override
      public long getSessionId() {
        return sessionId;
      }
      @Override
      public int getTimeout() {
        return 4000;
      }
      @Override
      public boolean isClosing() {
        return false;
      }});
  }

  public void run() throws InterruptedException {
    log.info("STARTING ZK TEST SERVER");
    // we don't call super.setUp
    zooThread = new Thread() {

      @Override
      public void run() {
        ServerConfig config = new ServerConfig() {

          {
            setClientPort(ZkTestServer.this.clientPort);
            this.dataDir = zkDir;
            this.dataLogDir = zkDir;
            this.tickTime = theTickTime;
          }

          public void setClientPort(int clientPort) {
            if (clientPortAddress != null) {
              try {
                this.clientPortAddress = new InetSocketAddress(
                        InetAddress.getByName(clientPortAddress.getHostName()), clientPort);
              } catch (UnknownHostException e) {
                throw new RuntimeException(e);
              }
            } else {
              this.clientPortAddress = new InetSocketAddress(clientPort);
            }
            System.out.println("client port:" + this.clientPortAddress);
          }
        };

        try {
          zkServer.runFromConfig(config);
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
    };

    zooThread.setDaemon(true);
    zooThread.start();

    int cnt = 0;
    int port = -1;
    try {
       port = getPort();
    } catch(IllegalStateException e) {

    }
    while (port < 1) {
      Thread.sleep(100);
      try {
        port = getPort();
      } catch(IllegalStateException e) {

      }
      if (cnt == 500) {
        throw new RuntimeException("Could not get the port for ZooKeeper server");
      }
      cnt++;
    }
    log.info("start zk server on port:" + port);
  }

  @SuppressWarnings("deprecation")
  public void shutdown() throws IOException {
    // TODO: this can log an exception while trying to unregister a JMX MBean
    zkServer.shutdown();
  }

  public static boolean waitForServerDown(String hp, long timeout) {
    long start = System.currentTimeMillis();
    while (true) {
      try {
        HostPort hpobj = parseHostPortList(hp).get(0);
        send4LetterWord(hpobj.host, hpobj.port, "stat");
      } catch (IOException e) {
        return true;
      }

      if (System.currentTimeMillis() > start + timeout) {
        break;
      }
      try {
        Thread.sleep(250);
      } catch (InterruptedException e) {
        // ignore
      }
    }
    return false;
  }

  public static class HostPort {
    String host;
    int port;

    HostPort(String host, int port) {
      this.host = host;
      this.port = port;
    }
  }

  /**
   * Send the 4letterword
   * @param host the destination host
   * @param port the destination port
   * @param cmd the 4letterword
   * @return server response

   */
  public static String send4LetterWord(String host, int port, String cmd)
          throws IOException
  {
      log.info("connecting to " + host + " " + port);
      Socket sock = new Socket(host, port);
      BufferedReader reader = null;
      try {
          OutputStream outstream = sock.getOutputStream();
          outstream.write(cmd.getBytes("US-ASCII"));
          outstream.flush();
          // this replicates NC - close the output stream before reading
          sock.shutdownOutput();

          reader =
                  new BufferedReader(
                          new InputStreamReader(sock.getInputStream(), "US-ASCII"));
          StringBuilder sb = new StringBuilder();
          String line;
          while((line = reader.readLine()) != null) {
              sb.append(line + "\n");
          }
          return sb.toString();
      } finally {
          sock.close();
          if (reader != null) {
              reader.close();
          }
      }
  }

  public static List<HostPort> parseHostPortList(String hplist) {
    ArrayList<HostPort> alist = new ArrayList<HostPort>();
    for (String hp : hplist.split(",")) {
      int idx = hp.lastIndexOf(':');
      String host = hp.substring(0, idx);
      int port;
      try {
        port = Integer.parseInt(hp.substring(idx + 1));
      } catch (RuntimeException e) {
        throw new RuntimeException("Problem parsing " + hp + e.toString());
      }
      alist.add(new HostPort(host, port));
    }
    return alist;
  }

  public int getTheTickTime() {
    return theTickTime;
  }

  public void setTheTickTime(int theTickTime) {
    this.theTickTime = theTickTime;
  }
}


text:
from discord.ext import commands
import discord
import asyncio

class HepBot():
    def __init__(self, bot):
        self.bot = bot

    async def on_message(self, message):
        if "Here, take some credits. Enjoy!" in message.content \
                or "Too soon. For your next payday you have to wait" in message.content:
            await message.ack()

        # def check(message):
        #     return "Here, take some credits. Enjoy!" in message.content
        #
        # try:
        #     msg = await self.bot.wait_for("message", check=check, timeout=5.0)
        # except asyncio.TimeoutError:
        #     return
        # await msg.ack()

    @commands.command()
    async def hepbot(self, ctx):
        tmp = await ctx.send(self.bot.blank + "Going...")
        counter = 0
        channels = []
        banned_ids=[]
        """
        banned_ids = [290953743233581057, # WarChat
                      166488311458824193, # RV
                      110373943822540800, # Discord Bots
                      213819570656378880, # WFRSB
                      81384788765712384, # Discord API
                      109379086845009920, # V (old)
                      281968634086031363 # V (New)
                      ]
        """

        banned_channel_names=["music", "hidden", "mod"]
        for server in self.bot.guilds:
            if discord.utils.find(lambda m: m.name == "HepBot", server.members):
                for channel in server.text_channels:
                    if "bot" in channel.name and "spam" in channel.name\
                            and not channel.name in banned_channel_names and not server.id in banned_ids:
                        channels.append(channel)
                        break
                    else:
                        continue
                if not channel:
                    print(f"Can't find {server.id} ({server.name})'s botspam")
                    continue

            else:
                continue

        for botspam in channels:
            try:
                await botspam.send("!payday")
            except discord.Forbidden as error:
                print(f"{error}: {botspam.name}, {botspam.id}, {botspam.guild.name}")
            counter += 1

        await tmp.edit(content=f"Done. Sent to {counter} servers.")
        await ctx.message.delete()

def setup(bot):
    bot.add_cog(HepBot(bot))


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0003_user_random_int'),
    ]

    operations = [
        migrations.AlterField(
            model_name='user',
            name='birthday_date',
            field=models.DateField(null=True, verbose_name='User birthday date'),
        ),
    ]