text:
require "active_support/concern"

module Railjet
  module Presenter
    extend ActiveSupport::Concern

    def initialize(object)
      @object = object
    end

    attr_reader :object

    def as_json(*)
      raise NotImplementedError
    end

    module ClassMethods
      def present_collection(objects)
        objects.map { |o| present(o) }
      end

      def present(object)
        new(object)
      end

      def object(name)
        alias_method name, :object
      end
    end

    module WithContext
      extend ActiveSupport::Concern
      include Railjet::Presenter

      included do
        attr_reader :context
        private     :context
      end

      def initialize(context, object)
        @context = context
        super(object)
      end

      module ClassMethods
        def present_collection(context, objects)
          objects.map { |o| present(context, o) }
        end

        def present(context, object)
          new(context, object)
        end

        def context(*context_members)
          delegate *context_members, to: :context
        end
      end

      module Factory
        extend ActiveSupport::Concern

        module ClassMethods
          def present_collection(context, objects)
            objects.map { |o| present(context, o) }
          end

          def present(context, object)
            presenter_class(object).new(context, object)
          end

          def presenter_class(object)
            raise NotImplementedError
          end
        end
      end
    end

    module Factory
      extend ActiveSupport::Concern

      module ClassMethods
        def present_collection(objects)
          objects.map { |o| present(o) }
        end

        def present(object)
          presenter_class(object).new(object)
        end

        def presenter_class(object)
          raise NotImplementedError
        end
      end
    end
  end
end


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Response extends Kohana_Response {}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __OEBTEXTSTREAM_H__
#define __OEBTEXTSTREAM_H__

#include <vector>
#include <string>

#include "../util/MergedStream.h"

class OEBTextStream : public MergedStream {

public:
	OEBTextStream(const ZLFile &opfFile);

private:
	void resetToStart();
	shared_ptr<ZLInputStream> nextStream();

private:
	std::string myFilePrefix;
	std::vector<std::string> myXHTMLFileNames;
	std::size_t myIndex;
};

#endif /* __OEBTEXTSTREAM_H__ */


text:
param(
    [switch]
    $NoBuild
)

if (!$NoBuild) {
    cake .\build-debug.cake
}

Clear-Host
.\Edison.Console\bin\Debug\Edison.Console.exe --ef .\Edisonfile --tproj engine


text:
package io.lumify.miniweb;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import javax.servlet.http.HttpServletRequest;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;

@RunWith(JUnit4.class)
public class RouteTest {
    private String path;
    private Handler handler;

    @Before
    public void before() {
        handler = mock(Handler.class);
        path = "/test";
    }

    @Test
    public void testRouteMiss() {
        Route r = new Route(Route.Method.GET, path, handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn("/foo");
        when(request.getContextPath()).thenReturn("");
        assertFalse(r.isMatch(request));
    }

    @Test
    public void testExactRouteMatch() {
        Route r = new Route(Route.Method.GET, path, handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path);
        when(request.getContextPath()).thenReturn("");
        assertTrue(r.isMatch(request));
    }

    @Test
    public void testRouteMatchWithComponents() {
        Route r = new Route(Route.Method.GET, path + "/{id}", handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path + "/25");
        when(request.getContextPath()).thenReturn("");
        assertTrue(r.isMatch(request));
        verify(request).setAttribute("id", "25");
    }

    @Test
    public void testComplexComponentAttributeSetting() {
        Route r = new Route(Route.Method.GET, path + "/{model}/edit/{_id}", handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path + "/person/edit/25");
        when(request.getContextPath()).thenReturn("");
        assertTrue(r.isMatch(request));
        verify(request).setAttribute("model", "person");
        verify(request).setAttribute("_id", "25");
    }

    @Test
    public void testWithEscapedSlash() {
        Route r = new Route(Route.Method.GET, path + "/{id}/test", handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path + "/12%2F34/test");
        when(request.getContextPath()).thenReturn("");
        assertTrue(r.isMatch(request));
        verify(request).setAttribute("id", "12/34");
    }

    @Test
    public void testComponentAsBaseFilename() {
        Route r = new Route(Route.Method.GET, path + "/{file}.ext", handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path + "/less.ext");
        when(request.getContextPath()).thenReturn("");
        assertTrue(r.isMatch(request));
        verify(request).setAttribute("file", "less");
    }

    public void testWithRegexSpecialCharacters() {
        Route r = new Route(Route.Method.GET, path + "\\^$.|?*+()[]", handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path + "\\^$.|?*+()[]");
        when(request.getContextPath()).thenReturn("");
        assertTrue(r.isMatch(request));
    }

    @Test
    public void testRestStyleUrlWithSpecialCharactersAndKnownTail() {
        Route r = new Route(Route.Method.GET, path + "/{resourceName}/data.json", handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path + "/test@test.com/other/data.json");
        when(request.getContextPath()).thenReturn("");
        assertTrue(r.isMatch(request));
        verify(request).setAttribute("resourceName", "test@test.com/other");
    }

    @Test
    public void testRestStyleUrlWithSpecialCharacters() {
        Route r = new Route(Route.Method.GET, path + "/{resourceName*}/{file}.{ext}", handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path + "/test@test.com/other/less.ext");
        when(request.getContextPath()).thenReturn("");
        assertTrue(r.isMatch(request));
        verify(request).setAttribute("resourceName", "test@test.com/other");
        verify(request).setAttribute("file", "less");
        verify(request).setAttribute("ext", "ext");
    }

    @Test
    public void testRegexRoute() {
        Route r = new Route(Route.Method.GET, path + "/{resourceName<[0-9]*>}/end", handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path + "/1283723/end");
        when(request.getContextPath()).thenReturn("");
        assertTrue(r.isMatch(request));
        verify(request).setAttribute("resourceName", "1283723");
    }

    @Test
    public void testRegexRouteNoMatch() {
        Route r = new Route(Route.Method.GET, path + "/{resourceName<[0-9]*>}/end", handler);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn(path + "/128a3723/end");
        when(request.getContextPath()).thenReturn("");
        assertFalse(r.isMatch(request));
    }
}


text:
goog.provide('webfont.DomHelper');

/**
 * Handles common DOM manipulation tasks. The aim of this library is to cover
 * the needs of typical font loading. Not more, not less.
 * @param {Window} mainWindow The main window webfontloader.js is loaded in.
 * @param {Window=} opt_loadWindow The window we'll load the font into. By
 *   default, the main window is used.
 * @constructor
 */
webfont.DomHelper = function(mainWindow, opt_loadWindow) {
  this.mainWindow_ = mainWindow;
  this.loadWindow_ = opt_loadWindow || mainWindow;

  /** @type {string} */
  this.protocol_;

  /** @type {Document} */
  this.document_ = this.loadWindow_.document;
};

goog.scope(function () {
  var DomHelper = webfont.DomHelper;

  /**
   * Creates an element.
   * @param {string} elem The element type.
   * @param {Object=} opt_attr A hash of attribute key/value pairs.
   * @param {string=} opt_innerHtml Contents of the element.
   * @return {Element} the new element.
   */
  DomHelper.prototype.createElement = function(elem, opt_attr,
      opt_innerHtml) {
    var domElement = this.document_.createElement(elem);

    if (opt_attr) {
      for (var attr in opt_attr) {
        // protect against native prototype augmentations
        if (opt_attr.hasOwnProperty(attr)) {
          if (attr == "style") {
            this.setStyle(domElement, opt_attr[attr]);
          } else {
            domElement.setAttribute(attr, opt_attr[attr]);
          }
        }
      }
    }
    if (opt_innerHtml) {
      domElement.appendChild(this.document_.createTextNode(opt_innerHtml));
    }
    return domElement;
  };

  /**
   * Inserts an element into the document. This is intended for unambiguous
   * elements such as html, body, head.
   * @param {string} tagName The element name.
   * @param {Element} e The element to append.
   * @return {boolean} True if the element was inserted.
   */
  DomHelper.prototype.insertInto = function(tagName, e) {
    var t = this.document_.getElementsByTagName(tagName)[0];

    if (!t) { // opera allows documents without a head
      t = document.documentElement;
    }

    // This is safer than appendChild in IE. appendChild causes random
    // JS errors in IE. Sometimes errors in other JS exectution, sometimes
    // complete 'This page cannot be displayed' errors. For our purposes,
    // it's equivalent because we don't need to insert at any specific
    // location.
    t.insertBefore(e, t.lastChild);
    return true;
  };

  /**
   * Calls a function when the body tag exists.
   * @param {function()} callback The function to call.
   */
  DomHelper.prototype.whenBodyExists = function(callback) {
    var that = this;
    var check = function() {
      if (that.document_.body) {
        callback();
      } else {
        setTimeout(check, 0);
      }
    }
    check();
  };

  /**
   * Removes an element from the DOM.
   * @param {Element} node The element to remove.
   * @return {boolean} True if the element was removed.
   */
  DomHelper.prototype.removeElement = function(node) {
    if (node.parentNode) {
      node.parentNode.removeChild(node);
      return true;
    }
    return false;
  };

  /**
   * @deprecated Use updateClassName().
   *
   * Appends a name to an element's class attribute.
   * @param {Element} e The element.
   * @param {string} name The class name to add.
   */
  DomHelper.prototype.appendClassName = function(e, name) {
    this.updateClassName(e, [name]);
  };

  /**
   * @deprecated Use updateClassName().
   *
   * Removes a name to an element's class attribute.
   * @param {Element} e The element.
   * @param {string} name The class name to remove.
   */
  DomHelper.prototype.removeClassName = function(e, name) {
    this.updateClassName(e, null, [name]);
  };

  /**
   * Updates an element's class attribute in a single change. This
   * allows multiple updates in a single class name change so there
   * is no chance for a browser to relayout in between changes.
   *
   * @param {Element} e The element.
   * @param {Array.<string>=} opt_add List of class names to add.
   * @param {Array.<string>=} opt_remove List of class names to remove.
   */
  DomHelper.prototype.updateClassName = function (e, opt_add, opt_remove) {
    var add = opt_add || [],
        remove = opt_remove || [];

    var classes = e.className.split(/\s+/);

    for (var i = 0; i < add.length; i += 1) {
      var found = false;

      for (var j = 0; j < classes.length; j += 1) {
        if (add[i] === classes[j]) {
          found = true;
          break;
        }
      }

      if (!found) {
        classes.push(add[i]);
      }
    }

    var remainingClasses = [];

    for (var i = 0; i < classes.length; i += 1) {
      var found = false;

      for (var j = 0; j < remove.length; j += 1) {
        if (classes[i] === remove[j]) {
          found = true;
          break;
        }
      }

      if (!found) {
        remainingClasses.push(classes[i]);
      }
    }

    e.className = remainingClasses.join(' ')
                    .replace(/\s+/g, ' ')
                    .replace(/^\s+|\s+$/, '');
  };

  /**
   * Returns true if an element has a given class name and false otherwise.
   * @param {Element} e The element.
   * @param {string} name The class name to check for.
   * @return {boolean} Whether or not the element has this class name.
   */
  DomHelper.prototype.hasClassName = function(e, name) {
    var classes = e.className.split(/\s+/);
    for (var i = 0, len = classes.length; i < len; i++) {
      if (classes[i] == name) {
        return true;
      }
    }
    return false;
  };

  /**
   * Sets the style attribute on an element.
   * @param {Element} e The element.
   * @param {string} styleString The style string.
   */
  DomHelper.prototype.setStyle = function(e, styleString) {
    e.style.cssText = styleString;
  };

  /**
   * @return {Window} The main window webfontloader.js is loaded in (for config).
   */
  DomHelper.prototype.getMainWindow = function() {
    return this.mainWindow_;
  };

  /**
   * @return {Window} The window that we're loading the font(s) into.
   */
  DomHelper.prototype.getLoadWindow = function() {
    return this.loadWindow_;
  };

  /**
   * @return {string} The protocol (http: or https:) to request resources in.
   */
  DomHelper.prototype.getProtocol = function() {
    if (typeof this.protocol_ === 'string') {
      return this.protocol_;
    } else {
      var protocol = this.loadWindow_.location.protocol;
      // For empty iframes, fallback to main window's protocol.
      if (protocol == 'about:') {
        protocol = this.mainWindow_.location.protocol;
      }
      return protocol == 'https:' ? 'https:' : 'http:';
    }
  };

  /**
   * Explicitly set the protocol instead of automatic detection.
   *
   * @param {string} protocol
   */
  DomHelper.prototype.setProtocol = function (protocol) {
    if (/^http(s)?:$/.test(protocol)) {
      this.protocol_ = protocol;
    }
  };

  /**
   * Returns the secure status of the current document.
   * @return {boolean} true if the current document is served securely.
   */
  DomHelper.prototype.isHttps = function() {
    return this.getProtocol() === 'https:';
  };

  /**
   * Returns the hostname of the current document.
   * @return {string} hostname.
   */
  DomHelper.prototype.getHostName = function() {
    return this.getLoadWindow().location.hostname || this.getMainWindow().location.hostname;
  };

  /**
   * Creates a style element.
   * @param {string} css Contents of the style element.
   * @return {Element} a DOM element.
   */
  DomHelper.prototype.createStyle = function(css) {
    var e = this.createElement('style');

    e.setAttribute('type', 'text/css');
    if (e.styleSheet) { // IE
      e.styleSheet.cssText = css;
    } else {
      e.appendChild(document.createTextNode(css));
    }
    return e;
  };

  /**
   * Loads an external stylesheet.
   *
   * @param {string} href the URL of the stylesheet
   * @param {function(Error)=} opt_callback Called when the stylesheet has loaded or failed to
   * load. Note that the callback is *NOT* guaranteed to be called in all browsers. The first
   * argument to the callback is an error object that is falsy when there are no errors and
   * truthy when there are.
   * @param {boolean=} opt_async True if the stylesheet should be loaded asynchronously. Defaults to false.
   * @return {Element} The link element
   */
  DomHelper.prototype.loadStylesheet = function (href, opt_callback, opt_async) {
    var link = this.createElement('link', {
      'rel': 'stylesheet',
      'href': href,
      'media': (opt_async ? 'only x' : 'all')
    });

    var sheets = this.document_.styleSheets;

    var done = false;

    link.onload = function () {
      if (!done) {
        done = true;

        if (opt_callback) {
          opt_callback(null);
        }
      }
    };

    link.onerror = function () {
      if (!done) {
        done = true;

        if (opt_callback) {
          opt_callback(new Error('Stylesheet failed to load'));
        }
      }
    };

    function onAvailable(callback) {
      for (var i = 0; i < sheets.length; i++) {
        if (sheets[i].href && sheets[i].href.indexOf(href) !== -1) {
          return callback();
        }
      }

      setTimeout(function () {
        onAvailable(callback);
      }, 0);
    }

    this.insertInto('head', link);

    if (opt_async) {
      onAvailable(function () {
        link.media = "all";
      });
    }

    return link;
  };

  /**
   * Loads an external script file.
   * @param {string} src URL of the script.
   * @param {function(Error)=} opt_callback callback when the script has loaded. The first argument to
   * the callback is an error object that is falsy when there are no errors and truthy when there are.
   * @param {number=} opt_timeout The number of milliseconds after which the callback will be called
   * with a timeout error. Defaults to 5 seconds.
   * @return {Element} The script element
   */
  DomHelper.prototype.loadScript = function(src, opt_callback, opt_timeout) {
    var head = this.document_.getElementsByTagName('head')[0];

    if (head) {
      var script = this.createElement('script', {
        'src': src
      });
      var done = false;
      script.onload = script.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
          done = true;
          if (opt_callback) {
            opt_callback(null);
          }
          script.onload = script.onreadystatechange = null;
          // Avoid a bizarre issue with unclosed <base> tag in IE6 - http://blog.dotsmart.net/2008/04/
          if (script.parentNode.tagName == 'HEAD') head.removeChild(script);
        }
      };
      head.appendChild(script);

      setTimeout(function () {
        if (!done) {
          done = true;
          if (opt_callback) {
            opt_callback(new Error('Script load timeout'));
          }
        }
      }, opt_timeout || 5000);

      return script;
    }

    return null;
  };
});


text:
HolePicker is a Ruby gem for quickly checking all your `Gemfile.lock` files for gem versions with known vulnerabilities.

[![Gem Version](https://badge.fury.io/rb/holepicker.png)](http://badge.fury.io/rb/holepicker)

[![Build Status](https://travis-ci.org/jsuder/holepicker.png?branch=master)](https://travis-ci.org/jsuder/holepicker)

[![Code Climate](https://codeclimate.com/github/jsuder/holepicker.png)](https://codeclimate.com/github/jsuder/holepicker)

## Important: project status

This project isn't currently maintained. [If someone takes it over](https://github.com/jsuder/holepicker/issues/21) I'll transfer the repo to them, but for now I've disabled the online data file on purpose so that you don't get false reports, since the file isn't updated anymore and is missing some latest vulnerabilities.

## The story

The beginning of 2013 was a [really bad time](http://www.kalzumeus.com/2013/01/31/what-the-rails-security-issue-means-for-your-startup/) for the Ruby community. In the first few weeks of the year at least 7 serious security issues were found, and Rails had to be updated 4 times so far because of this. It's probably not the end. It's hard to keep track of all the issues and remember which gem versions are OK and which aren't, especially if you have several older and newer Ruby or Rails projects to maintain. So I wrote this tool in order to help with identifying which gems in your projects' gemfiles need to be updated.

## Details

The idea is that there is a [JSON file](https://github.com/jsuder/holepicker/blob/master/lib/holepicker/data/data.json)\* stored in this repository that lists all the recent security-related updates to popular gems: date of the release, URL of the announcement, and a list of affected gems and updated versions. HolePicker provides a command line tool that **downloads the latest data file from GitHub every time**, scans your `Gemfile.lock` files and checks if they contain vulnerable gem versions.

The reason I've done it this way is to make it easier to run the checks against the very latest version of the vulnerability list. It's kind of important to be sure that you haven't missed any last minute updates, and it would be annoying to have to check for new gem versions every time you want to run the tool (and you might not even remember to do that).

If for some reason you don't want to download the JSON file every time, you can use the [`-o` option](#full-option-list). Also, the JSON file specifies the minimum compatible gem version that it can work with, so if new kind of information is added to the file that requires the gem to be updated in order to parse it, the gem will let you know.

Of course the whole system still relies on me manually adding entries to the JSON file and pushing it to GitHub. I'll try to do that quickly, my trusty [@rails_bot](https://github.com/jsuder/rails-retweeter-bot) notifies me pretty quickly when something really bad is happening. If for some reason I don't update the list in time, by all means please send me a pull request.

(\*) YAML obviously wouldn't be appropriate, if you know what I mean.

## Running the tool

HolePicker should run on any fairly recent Ruby (1.9.x, 2.0) or JRuby.

To install the tool, just run:

    gem install holepicker

There are two main modes of operation:

### Scanning projects directly

This can be used to scan project directories on your development machine:

    holepicker ~/Projects

You can also scan all apps deployed to a production or demo server; in this case, it's recommended to use the `-c` (`--current`) option in order to skip the old releases in `releases` directories and only scan the `current` directories (I'm assuming you use Capistrano for deployment, because who doesn't?).

    holepicker -c /var/www

HolePicker will return a non-zero status code if vulnerabilities are found, so you could wrap it in some kind of script that's run periodically from cron that notifies you when something is wrong.

### Scanning Nginx/Apache config directory

You might have a lot of random apps deployed in the `/var/www` directory, but only some of them currently enabled in the Nginx config files. In this case, you might want to only check the apps that are actually running. To do that, use the `-f` (`--follow-roots`) option and point HolePicker to your HTTP server's config directory. It will find all the `root` or `DocumentRoot` directives and follow the paths to find the gemfiles of enabled apps.

    holepicker -f /etc/nginx/sites-enabled

## Results

This is more or less what you will get if you run HolePicker in a directory with some old Rails projects:

![screenshot](http://f.cl.ly/items/1l3C2c2s0r1k3v033B34/Screen%20Shot%202013-02-16%20at%2001.43.39.png)

## Running on app startup

If you want to check your gems when your app is started, add HolePicker to your Gemfile and then call `HolePicker::Scanner#scan` in a file that's loaded at app startup (e.g. in Rails projects you can add an initializer in `config/initializers`):

```rb
HolePicker::Scanner.new('Gemfile.lock').scan or abort
```

You may want to pass `:offline` or `:ignored_gems` options or change logger settings too - see [`bin/holepicker` source](https://github.com/jsuder/holepicker/blob/master/bin/holepicker) for more info.

## Integration with capistrano

To automatically check for vulnerabilities before deployment, you can add the HolePicker Capistrano recipe:

1. Add `gem 'holepicker'` to your `Gemfile` (preferably with `:require => false`)
2. Add `require 'holepicker/capistrano'` to your `config/deploy.rb`

This will introduce a `cap holepicker` task which will be executed before the deploy.

## Full option list

`-a`, `--all`

By default, HolePicker will skip directories like `.git`, `tmp`, `cached-copy` etc. when searching for gemfiles. This option turns this feature off.

`-c`, `--current`

Look only for gemfiles that are located directly in a `current` directory.

`-f`, `--follow-roots`

Look for `root`/`DocumentRoot` directives in config files at given locations instead of gemfiles directly.

`-i`, `--ignore gem1,gem2,gem3`

Ignore the gems passed in the parameter.

`--no-color`

Disable output coloring (by default green is used for good gemfiles and red is used for bad gemfiles and errors).

`-o`, `--offline`

Use an offline copy of the data file - useful if you really need to run the tool, but the network or GitHub is down.

`-s`, `--silent`

Silent mode - disable info-level messages ("Looking for gemfiles...") and only print errors and found vulnerabilities.

## Similar projects

There are a few other projects with a similar purpose, take a look if HolePicker isn't exactly what you need:

* [bundler-audit](https://github.com/postmodern/bundler-audit) - lets you scan the project in current directory
* [bundler-organization_audit](https://github.com/grosser/bundler-organization_audit) - scans all your projects on GitHub
* [ruby-advisory-db](https://github.com/rubysec/ruby-advisory-db) - a shared database of vulnerabilities - I'll try to integrate holepicker with it later
* [gemcanary](https://gemcanary.com/) - a web service that notifies you by email when a new vulnerability is found in a gem used by one of your apps
* [gems-status](https://github.com/jordimassaguerpla/gems-status) - a more general tool for checking everything that might be wrong with your gems (work in progress)

## Credits & contributing

Created by [Jakub Suder](http://psionides.eu), licensed under MIT License.

Any feedback and help is welcome, if you have an idea how to improve this tool, let me know or send me an issue or a pull request.

If you hear about a security update to a Ruby gem which I have missed, please send me a pull request with an update to the [json file](https://github.com/jsuder/holepicker/blob/master/lib/holepicker/data/data.json) (check out the documentation about the [file structure](https://github.com/jsuder/holepicker/wiki/JSON-structure)).

And BTW, big thanks to all the smart people that find and fix all these issues - I hope you won't find much more, but please keep looking.


text:
package ru.otus.kirillov.controllers.http;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import ru.otus.kirillov.model.commands.CommandInvoker;
import ru.otus.kirillov.model.commands.ModelRequest;
import ru.otus.kirillov.model.commands.ModelResult;
import ru.otus.kirillov.model.commands.common.AuthenticationRequest;
import ru.otus.kirillov.model.commands.common.ErroneousModelResult;
import ru.otus.kirillov.view.View;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class GetCacheStatsServlet extends AbstractServlet {

    private static final Logger log = LogManager.getLogger();

    @Autowired
    private CommandInvoker invoker;

    @Value("${frontend.cache-stats.port}")
    private String cacheStatPortNumber;

    @Value("${frontend.cache-stats.endpoint}")
    private String endpoint;

    @Value("${frontend.host}")
    private String host;

    @Value("${frontend.port}")
    private String portNumber;

    @Value("${frontend.cache-stats.refresh.delay}")
    private String cacheInfoRefreshDelayInMsl;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if (!checkAuthentication(req)) {
            resp.sendRedirect("/main");
            return;
        }
        ModelResult commandModelResult = auth(createRequest(req));
        if (commandModelResult instanceof ErroneousModelResult) {
            resp.sendRedirect("/error?error-msg="+((ErroneousModelResult) commandModelResult).getCause());
            return;
        }

        String page = getPage(req);
        doAnswer(resp, page);
    }

    private ModelRequest createRequest(HttpServletRequest rq) {
        return AuthenticationRequest.of(getSessionId(rq), getUserName(rq));
    }

    private ModelResult auth(ModelRequest rq) {
        return invoker.execute(rq);
    }

    private String getPage(HttpServletRequest rq) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("isAuth", true);
        paramMap.put("username", getUserName(rq));
        paramMap.put("cacheStatsPort", cacheStatPortNumber);
        paramMap.put("cacheStatsEndpoint", endpoint);
        paramMap.put("host", host);
        paramMap.put("port", portNumber);
        paramMap.put("cacheStatsDelay", cacheInfoRefreshDelayInMsl);
        paramMap.put("sessionIdKey", COOKIE_SESSION_ID_PARAM_NAME);
        paramMap.put("userNameKey", COOKIE_USERNAME_PARAM_NAME);
        return templateEngine.getPage(View.CACHE_STATS, paramMap);
    }
}


text:
package org.basex.query.func.fn;

import static org.basex.util.Token.*;

import java.math.*;

import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.value.item.*;
import org.basex.util.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 */
public final class FnParseIetfDate extends StandardFunc {
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    final Item it = exprs[0].atomItem(qc, info);
    return it == null ? null : new DateParser(toToken(it), info).parse();
  }

  /** Date parser. */
  private static final class DateParser extends InputParser {
    /** Days. */
    private static final String[] DAYS = {
      "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday",
      "mon", "tue", "wed", "thu", "fri", "sat", "sun"
    };
    /** Months. */
    private static final String[] MONTHS = {
      "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"
    };
    /** Timezones. */
    private static final String[] TZNAMES = {
      "utc", "ut", "gmt", "est", "edt", "cst", "cdt", "mst", "mdt", "pst", "pdt"
    };
    /** Associated times. */
    private static final int[] TIMES = {
      0, 0, 0, -300, -240, -360, -300, -420, -360, -480, -420
    };

    /** Original string. */
    private final byte[] original;
    /** Input info. */
    private final InputInfo info;

    /** Day. */
    private int day;
    /** Month. */
    private int month;
    /** Year. */
    private int year;
    /** Hours. */
    private int hours;
    /** Minutes. */
    private int minutes;
    /** Seconds. */
    private BigDecimal seconds = BigDecimal.ZERO;
    /** Timezone. */
    private Integer zone;

    /**
     * Constructor.
     * @param input input
     * @param info input info
     */
    private DateParser(final byte[] input, final InputInfo info) {
      super(string(lc(input)).trim());
      original = input;
      this.info = info;
    }

    /**
     * Parses the input and returns a dateTime item.
     * @return dateTime item
     * @throws QueryException query exception
     */
    private Dtm parse() throws QueryException {
      input();
      final TokenBuilder tb = new TokenBuilder();
      addNumber(tb, year, 4).add('-');
      addNumber(tb, month, 2).add('-');
      addNumber(tb, day, 2).add('T');
      addNumber(tb, hours, 2).add(':');
      addNumber(tb, minutes, 2).add(':');
      final int sec = seconds.intValue();
      addNumber(tb, sec, 2);
      if(seconds.scale() > 0) {
        tb.add(seconds.subtract(BigDecimal.valueOf(sec)).toString().substring(1));
      }
      final int z = zone == null ? 0 : zone;
      if(z == 0) {
        tb.add('Z');
      } else {
        tb.add(z < 0 ? '-' : '+');
        addNumber(tb, Math.abs(z / 60), 2).add(':');
        addNumber(tb, Math.abs(z % 60), 2);
      }
      try {
        return new Dtm(tb.finish(), info);
      } catch(final QueryException ex) {
        throw QueryError.IETF_INV_X.get(info, original);
      }
    }

    /**
     * Parses the input.
     * @throws QueryException query exception
     */
    private void input() throws QueryException {
      skipWs();
      boolean f = false;
      for(final String d : DAYS) {
        if(consume(d)) {
          f = true;
          break;
        }
      }
      consume(',');
      if(f && !skipWs()) throw error("whitespace");
      if(datespec()) {
        if(!skipWs()) throw error("whitespace");
        if(!time()) throw error("time");
      } else if(!asctime()) {
        throw error("day, or name of month");
      }
      skipWs();
      if(more()) throw error("end of input");
    }

    /**
     * Parses a date.
     * @return success flag
     * @throws QueryException query exception
     */
    private boolean datespec() throws QueryException {
      if(!daynum()) return false;
      if(!dsep()) throw error("'-'");
      if(!monthname()) throw error("name of month");
      if(!dsep()) throw error("'-'");
      if(!year()) throw error("year");
      return true;
    }

    /**
     * Parses a time and date.
     * @return success flag
     * @throws QueryException query exception
     */
    private boolean asctime() throws QueryException {
      if(!monthname()) return false;
      if(!dsep()) throw error("'-'");
      if(!daynum()) throw error("day");
      if(!skipWs()) throw error("whitespace");
      if(!time()) throw error("time");
      if(!skipWs()) throw error("whitespace");
      if(!year()) throw error("year");
      return true;
    }

    /**
     * Parses a time.
     * @return success flag
     * @throws QueryException query exception
     */
    private boolean time() throws QueryException {
      if(!hours()) return false;
      if(!consume(':') || !minutes()) throw error("minutes");
      if(consume(':') && !seconds()) throw error("seconds");
      final int ip = pos;
      skipWs();
      if(!timezone()) pos = ip;
      return true;
    }

    /**
     * Parses a day.
     * @return success flag
     */
    private boolean daynum() {
      if(!digit(curr())) return false;
      final int d = number();
      day = digit(curr()) ? d * 10 + number() : d;
      return true;
    }

    /**
     * Parses a separator.
     * @return success flag
     */
    private boolean dsep() {
      final boolean s = skipWs();
      if(consume('-')) {
        skipWs();
        return true;
      }
      return s;
    }

    /**
     * Parses a month.
     * @return success flag
     */
    private boolean monthname() {
      final int ml = MONTHS.length;
      int m = -1;
      while(++m < ml && !consume(MONTHS[m]));
      if(m == ml) return false;
      month = m + 1;
      return true;
    }

    /**
     * Parses a year.
     * @return success flag
     */
    private boolean year() {
      final int d1 = twoDigits();
      if(d1 == -1) return false;
      final int d2 = twoDigits();
      year = d2 == -1 ? d1 + 1900 : d1 * 100 + d2;
      return true;
    }

    /**
     * Parses hours.
     * @return success flag
     */
    private boolean hours() {
      final int d = twoDigits();
      if(d == -1) return false;
      hours = d;
      return true;
    }

    /**
     * Parses minutes.
     * @return success flag
     */
    private boolean minutes() {
      final int d = twoDigits();
      if(d == -1) return false;
      minutes = d;
      return true;
    }

    /**
     * Parses seconds.
     * @return success flag
     * @throws QueryException query exception
     */
    private boolean seconds() throws QueryException {
      final int d = twoDigits();
      if(d == -1) return false;
      BigDecimal bd = BigDecimal.valueOf(d);
      if(consume('.')) {
        if(!digit(curr())) throw error("digit");
        BigDecimal f = BigDecimal.TEN;
        while(digit(curr())) {
          bd = bd.add(BigDecimal.valueOf(number()).divide(f));
          f = f.multiply(BigDecimal.TEN);
        }
      }
      seconds = bd;
      return true;
    }

    /**
     * Parses a timezone.
     * @return success flag
     * @throws QueryException query exception
     */
    private boolean timezone() throws QueryException {
      if(tzname()) return true;
      if(!tzoffset()) return false;
      final int ip = pos;
      skipWs();
      if(consume('(')) {
        skipWs();
        if(!tzname()) throw error("timezone");
        skipWs();
        if(!consume(')')) throw error("')'");
      } else {
        pos = ip;
      }
      return true;
    }

    /**
     * Parses a timezone name.
     * @return success flag
     */
    private boolean tzname() {
      final int tl = TZNAMES.length;
      int t = -1;
      while(++t < tl && !consume(TZNAMES[t]));
      if(t == tl) return false;
      if(zone == null) zone = TIMES[t];
      return true;
    }

    /**
     * Parses a timezone offset.
     * @return success flag
     * @throws QueryException query exception
     */
    private boolean tzoffset() throws QueryException {
      final int m = consume('-') ? -1 : 1;
      if(m == 1 && !consume('+')) return false;
      final int d = twoDigits();
      if(d == -1) throw error("timezone digits");
      zone = m * d * 60;
      consume(':');
      final int n = twoDigits();
      if(n != -1) zone += m * n;
      return true;
    }

    /**
     * Parses two digits.
     * @return number or {@code -1}
     */
    private int twoDigits() {
      return digit(curr()) && digit(next()) ? number() * 10 + number() : -1;
    }

    /**
     * Consumes a whitespace character.
     * @return success flag
     */
    private boolean skipWs() {
      if(!more() || !ws(curr())) return false;
      do consume(); while(more() && ws(curr()));
      return true;
    }

    /**
     * Adds a number to a string.
     * @param tb token builder
     * @param num number
     * @param digits minimum number of digits to add
     * @return token builder
     */
    private static TokenBuilder addNumber(final TokenBuilder tb, final int num, final int digits) {
      final byte[] tmp = token(num);
      for(int n = tmp.length; n < digits; n++) tb.add('0');
      return tb.add(tmp);
    }

    /**
     * Returns an error.
     * @param msg message
     * @return error
     */
    private QueryException error(final String msg) {
      return QueryError.IETF_PARSE_X_X_X.get(info, msg, curr(), original);
    }

    /**
     * Consumes a digit and returns the numeric representation.
     * @return number
     */
    private int number() {
      return consume() - '0';
    }
  }
}


text:
package com.lpiem.apps.loupelec.utilities.camera;

import android.hardware.Camera;
import android.widget.Toast;

import com.lpiem.apps.loupelec.R;
import com.lpiem.apps.loupelec.dao.datasources.MediaDataSource;
import com.lpiem.apps.loupelec.fragments.CameraFragment;
import com.lpiem.apps.loupelec.utilities.MessageActivity;

import java.io.File;

/**
 * CameraPicture Class
 */
public class CameraPicture implements Camera.PictureCallback {
    /*
    Fields
     */
    private CameraFragment mFragment = null;
    private final MediaDataSource mMediaDataSource;

    /*
    Methods
     */

    /**
     * Constructor
     * @param fragment CameraFragment
     */
    public CameraPicture(CameraFragment fragment){
        mMediaDataSource = new MediaDataSource(fragment.getActivity());
        mFragment = fragment;
    }

    /**
     * onPictureTaken Method (Override)
     * @param picture byte[]
     * @param camera Camera
     */
    @Override
    public void onPictureTaken(byte[] picture, Camera camera) {
        //Execute AsyncTask
        new SavePicture(mFragment.getActivity(), this).execute(picture);

        //Restart Preview
        camera.startPreview();
    }

    /**
     * onPostExecute Capture
     * @param file File
     */
    public void onPostExecute(File file){
        //Create media in BDD
        mMediaDataSource.createMedia(file.getName(), file.getAbsolutePath(), null);

        //Show Message End capture
        Toast.makeText(mFragment.getActivity(), mFragment.getString(R.string.camera_toast_end_capture), Toast.LENGTH_SHORT).show();

        //Refresh list
        mFragment.getListener().onFragmentInteraction(MessageActivity.RELOAD_LIST, null);
    }
}


text:
package com.centurylink.mdw.util;

import com.centurylink.mdw.model.JsonArray;
import com.centurylink.mdw.model.JsonObject;
import com.centurylink.mdw.model.Jsonable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Helper methods and access to JSON configuration values.
 * Takes into account PaaS vs File-based configurations.
 */
public class JsonUtil {

    public static JSONObject getJson(Map<String,String> map) throws JSONException {
        if (map == null)
            return null;
        JSONObject jsonObj = new JsonObject();
        for (String key : map.keySet()) {
            String value = map.get(key);
            if (value != null)
                jsonObj.put(key, value);
        }
        return jsonObj;
    }

    public static Map<String,String> getMap(JSONObject jsonObj) throws JSONException {
        Map<String,String> map = new HashMap<>();
        String[] names =  JSONObject.getNames(jsonObj);
        if (names != null) {
            for (String name : names)
                map.put(name, jsonObj.getString(name));
        }
        return map;
    }

    public static Map<String,JSONObject> getJsonObjects(JSONObject json) throws JSONException {
        Map<String,JSONObject> objects = new HashMap<>();
        Iterator<?> keys = json.keys();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            objects.put(key, json.getJSONObject(key));
        }
        return objects;
    }

    public static JsonArray getJsonArray(List<? extends Jsonable> jsonables) throws JSONException {
        JSONArray jsonArray = new JSONArray();
        for (Jsonable jsonable : jsonables) {
            jsonArray.put(jsonable.getJson());
        }
        return new JsonArray(jsonArray);
    }

    public static boolean isJson(File file) throws IOException {
        if (!file.isFile())
            return false;
        try (FileInputStream fis = new FileInputStream(file);
             InputStreamReader reader = new InputStreamReader(fis, "UTF-8")) {
            char[] chars = new char[1];
            if (reader.read(chars) == -1)
                return false;
            return chars[0] == '{';
        }
    }
}


text:
from trove.common import cfg
from trove.common.strategies import base
from trove.guestagent import api as guest_api
from trove.openstack.common import log as logging

LOG = logging.getLogger(__name__)
CONF = cfg.CONF

class MongoDbGuestAgentStrategy(base.BaseGuestAgentStrategy):

    @property
    def guest_client_class(self):
        return MongoDbGuestAgentAPI

class MongoDbGuestAgentAPI(guest_api.API):

    def add_shard(self, replica_set_name, replica_set_member):
        LOG.debug("Adding shard with replSet %(replica_set_name)s and member "
                  "%(replica_set_member)s for instance %(id)s" % {
                  'replica_set_name': replica_set_name,
                  'replica_set_member': replica_set_member,
                  'id': self.id})
        return self._call("add_shard", guest_api.AGENT_HIGH_TIMEOUT,
                          replica_set_name=replica_set_name,
                          replica_set_member=replica_set_member)

    def add_members(self, members):
        LOG.debug("Adding members %(members)s on instance %(id)s" % {
            'members': members, 'id': self.id})
        return self._call("add_members", guest_api.AGENT_HIGH_TIMEOUT,
                          members=members)

    def add_config_servers(self, config_servers):
        LOG.debug("Adding config servers %(config_servers)s for instance "
                  "%(id)s" % {'config_servers': config_servers,
                              'id': self.id})
        return self._call("add_config_servers", guest_api.AGENT_HIGH_TIMEOUT,
                          config_servers=config_servers)

    def cluster_complete(self):
        LOG.debug("Notify regarding cluster install completion")
        return self._call("cluster_complete", guest_api.AGENT_LOW_TIMEOUT)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <logbulk.version>0.1.0-dev</logbulk.version>
    <lombok.version>1.16.14</lombok.version>
    <nuprocess.version>1.1.0</nuprocess.version>
  </properties>
  <groupId>io.techcode.logbulk</groupId>
  <artifactId>logbulk-plugin-exec</artifactId>
  <version>0.1.0-dev</version>

  <dependencies>
    <!-- RUN -->
    <dependency>
      <groupId>io.techcode.logbulk</groupId>
      <artifactId>logbulk</artifactId>
      <version>${logbulk.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.zaxxer</groupId>
      <artifactId>nuprocess</artifactId>
      <version>${nuprocess.version}</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>

    <!-- TEST -->
    <dependency>
      <groupId>io.techcode.logbulk</groupId>
      <artifactId>logbulk-test</artifactId>
      <version>${logbulk.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <defaultGoal>clean package</defaultGoal>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19.1</version>
        <configuration>
          <argLine>
            -Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.SLF4JLogDelegateFactory
          </argLine>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <minimizeJar>false</minimizeJar>
              <artifactSet>
                <includes>
                  <include>com.zaxxer:nuprocess</include>
                </includes>
              </artifactSet>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
package me.pjq.omniture;

import android.content.Context;

/**
 * Wrapper for the Omniture Android SDK APIs.
 *
 * Refer to http://microsite.omniture.com/t2/help/en_US/mobile/android/methods.html
 *
 * Created by pengjianqing on 6/12/14.
 */
public class OmnitureManager {
    private static OmnitureManager INSTANCE;
    private AnalyticsInterface analytics;
    private TargetInterface target;
    private AudienceManagerInterface audienceManager;
    private ConfigInterface config;

    public OmnitureManager(){
        analytics = new MyAnalytics();
        target = new MyTarget();
        audienceManager = new MyAudienceManager();
        config = new MyConfig();
    }

    public void setContext(Context context ){
        config.setContext(context);
    }

    public static OmnitureManager getInstance(){
        if (null == INSTANCE){
            INSTANCE = new OmnitureManager();
        }

        return INSTANCE;
    }

    public AnalyticsInterface getAnalytics(){
        return analytics;
    }

    public TargetInterface getTarget(){
        return target;
    }

    public AudienceManagerInterface getAudienceManager(){
        return audienceManager;
    }

    public ConfigInterface getConfig() {
        return config;
    }

    public void onResume(){
        config.collectLifecycleData();
    }

    public void onPause(){
        config.pauseCollectingLifecycleData();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>agorava-meetup-api</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Agorava Meetup - API</name>
    <parent>
        <groupId>org.agorava</groupId>
        <artifactId>agorava-meetup-parent</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.agorava</groupId>
            <artifactId>agorava-core-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
        </dependency>
    </dependencies>
</project>


text:
package webx

import (
	"strconv"
	"strings"
)

type APIService struct {
	Exclusive   bool
	Prefix      string
	registered  bool
	middlewares []APIHandle
	route       map[string]map[string]*apiHandler
}

type apiHandler struct {
	handle     APIHandle
	privileges map[string]struct{}
}

type APIHandle func(*Context)

func (s *APIService) Use(middleware APIHandle) {
	s.middlewares = append(s.middlewares, middleware)
}

func (s *APIService) OPTIONS(endpoint string, cors *CORS) {
	if cors == nil {
		return
	}

	s.register("OPTIONS", endpoint, func(ctx *Context) {
		w := ctx.ResponseWriter
		wh := w.Header()

		if len(cors.Origin) > 0 {
			wh.Set("Access-Control-Allow-Origin", cors.Origin)
			wh.Set("Vary", "Origin")

			if len(cors.Methods) > 0 {
				wh.Set("Access-Control-Allow-Methods", strings.Join(cors.Methods, ", "))
			}
			if len(cors.Headers) > 0 {
				wh.Set("Access-Control-Allow-Headers", strings.Join(cors.Headers, ", "))
			}
			if cors.Credentials {
				wh.Set("Access-Control-Allow-Credentials", "true")
			}
			if cors.MaxAge > 0 {
				wh.Set("Access-Control-Max-Age", strconv.Itoa(cors.MaxAge))
			}
		}

		w.WriteHeader(204)
	}, nil)
}

func (s *APIService) HEAD(endpoint string, handle APIHandle, privilegeIds ...string) {
	s.register("HEAD", endpoint, handle, privilegeIds)
}

func (s *APIService) GET(endpoint string, handle APIHandle, privilegeIds ...string) {
	s.register("GET", endpoint, handle, privilegeIds)
}

func (s *APIService) POST(endpoint string, handle APIHandle, privilegeIds ...string) {
	s.register("POST", endpoint, handle, privilegeIds)
}

func (s *APIService) PUT(endpoint string, handle APIHandle, privilegeIds ...string) {
	s.register("PUT", endpoint, handle, privilegeIds)
}

func (s *APIService) PATCH(endpoint string, handle APIHandle, privilegeIds ...string) {
	s.register("PATCH", endpoint, handle, privilegeIds)
}

func (s *APIService) DELETE(endpoint string, handle APIHandle, privilegeIds ...string) {
	s.register("DELETE", endpoint, handle, privilegeIds)
}

func (s *APIService) register(method string, endpoint string, handle APIHandle, privilegeIds []string) {
	if len(endpoint) == 0 || handle == nil {
		return
	}

	var privileges map[string]struct{}
	if len(privilegeIds) > 0 {
		privileges = map[string]struct{}{}
		for _, pid := range privilegeIds {
			if len(pid) > 0 {
				privileges[pid] = struct{}{}
			}
		}
	}

	if s.route == nil {
		s.route = map[string]map[string]*apiHandler{}
	}
	if s.route[method] == nil {
		s.route[method] = map[string]*apiHandler{}
	}
	s.route[method][endpoint] = &apiHandler{privileges: privileges, handle: handle}

	if !s.Exclusive && !s.registered {
		apiss = append(apiss, s)
		s.registered = true
	}
}


text:
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include <multiboot2.h>

#include <arch/armv8/kernel_multiboot2.h>

// Dump the Multiboot2 structure
void multiboot2_dump(struct multiboot_tag *first_tag,
                               const size_t size)
{
    size_t processed = 0;
    char description[256];

    printf("%s: %p:%ld\n", __func__, first_tag, size);
    while (processed < size) {
        switch (first_tag->type) {
            case MULTIBOOT_TAG_TYPE_CMDLINE: {
                snprintf(description, sizeof(description), "CMDLINE: [%s]",
                    ((struct multiboot_tag_string *)first_tag)->string);
            } break;
            case MULTIBOOT_TAG_TYPE_EFI64: {
                snprintf(description, sizeof(description), "EFI64: pointer=%lx",
                    ((struct multiboot_tag_efi64 *)first_tag)->pointer);
            } break;
            case MULTIBOOT_TAG_TYPE_ACPI_NEW: {
                snprintf(description, sizeof(description), "ACPI new:");
            } break;
            case MULTIBOOT_TAG_TYPE_EFI_MMAP: {
                snprintf(description, sizeof(description), "EFI MMAP: size=%d version=%d",
                    ((struct multiboot_tag_efi_mmap *)first_tag)->descr_size,
                    ((struct multiboot_tag_efi_mmap *)first_tag)->descr_vers);
            } break;
            case MULTIBOOT_TAG_TYPE_MODULE_64: {
                snprintf(description, sizeof(description), "MODULE 64: mod_start=%lx  mod_end=%lx cmdline=[%s]",
                    ((struct multiboot_tag_module_64 *)first_tag)->mod_start,
                    ((struct multiboot_tag_module_64 *)first_tag)->mod_end,
                    ((struct multiboot_tag_module_64 *)first_tag)->cmdline);
            } break;
            case MULTIBOOT_TAG_TYPE_END: {
                snprintf(description, sizeof(description), "END");
            } break;
            default: {
                snprintf(description, sizeof(description), "[%d]", first_tag->type);
            } break;
        }
        printf("%p:%4ld:  tag %d:%d  %s\n", first_tag, processed, first_tag->type, first_tag->size, description);
        if (first_tag->type == MULTIBOOT_TAG_TYPE_END)
            break;
        processed += first_tag->size;
        first_tag = (void *)first_tag + first_tag->size;
    }
}

struct multiboot_tag * multiboot2_find_tag(struct multiboot_tag *first_tag,
                               const size_t size, const multiboot_uint16_t type)
{
    size_t processed = 0;

    while (processed < size) {
        /* encountered the end tag */
        if (first_tag->type == MULTIBOOT_TAG_TYPE_END) {
            return NULL;
        } else if (first_tag->type == type) {
            return first_tag;
        }
        processed += first_tag->size;
        first_tag = (void *)first_tag + first_tag->size;
    }

    return NULL;
}

struct multiboot_tag_string * multiboot2_find_cmdline(
                             struct multiboot_tag *first_tag, const size_t size)
{
    return (struct multiboot_tag_string *)multiboot2_find_tag(first_tag, size,
        MULTIBOOT_TAG_TYPE_CMDLINE);
}

struct multiboot_tag_module_64 * multiboot2_find_module_64(
       struct multiboot_tag *first_tag, const size_t size, const char *pathname)
{
    size_t len = strlen(pathname);
    size_t position = 0;
    struct multiboot_tag *tag;

    tag = multiboot2_find_tag(first_tag, size, MULTIBOOT_TAG_TYPE_MODULE_64);
    while (tag) {
        struct multiboot_tag_module_64 *module_64 = (struct multiboot_tag_module_64 *)tag;
        // Strip off trailing whitespace
        char *modname = module_64->cmdline;
        char *endstr;
        endstr = strchr(modname, ' ');
        if (!endstr) {
            endstr = modname + strlen(modname);
        }

        if(!strncmp(endstr - len, pathname, len)) {
            return module_64;
        }
        tag = (void *)tag + tag->size;
        position += tag->size;
        tag = multiboot2_find_tag(tag, size - position, MULTIBOOT_TAG_TYPE_MODULE_64);
    }
    return NULL;
}


text:
enum BreakpadForkBehavior {
  DONOTHING = 0,
  UNINSTALL,
  RESETEXCEPTIONPORT
};

enum BreakpadForkTestCrashPoint {
  DURINGLAUNCH = 5,
  AFTERLAUNCH = 6,
  BETWEENFORKEXEC = 7
};

@interface Controller : NSObject {
  IBOutlet NSWindow *window_;
  IBOutlet NSWindow *forkTestOptions_;

  BreakpadRef breakpad_;

  enum BreakpadForkBehavior bpForkOption;

  BOOL useVFork;
  enum BreakpadForkTestCrashPoint progCrashPoint;
}

- (IBAction)crash:(id)sender;
- (IBAction)forkTestOptions:(id)sender;
- (IBAction)forkTestGo:(id)sender;
- (IBAction)showForkTestWindow:(id) sender;
- (void)generateReportWithoutCrash:(id)sender;
- (void)awakeFromNib;

@end


text:
package nytteklasser;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;

public class Afspilning {
  private static MediaPlayer mp;

  /**
   * Sætter volumen lidt op under afspilning af lyd, hvis der er helt skruet ned
   * Minimumsværdi er angivet i procenter af fuld styrke
   * @param ctx Kontekst, f.eks. aktivitet (huskes ikke)
   * @param procent værdi mellem 0 og 100
   */
  public static void tjekVolumenErMindst(Context ctx, int procent) {
    AudioManager audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);

    int aktuelVærdi = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    int maxVærdi = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    if (aktuelVærdi < procent * maxVærdi / 100) {
      audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, procent * maxVærdi / 100, AudioManager.FLAG_SHOW_UI);
    }
  }

  public static void start(MediaPlayer mp1) {
    start(mp1, null);
  }

  public static void start(MediaPlayer mp1, final MediaPlayer.OnCompletionListener ocl) {
    stop();
    try {
      if (mp1 == null) return;
      mp = mp1;
      mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mpx) {
          try {
            if (ocl != null) ocl.onCompletion(null);
            mp.reset();
            mp.release();
            mp = null;
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      });
      mp.start();
    } catch (Exception e) {
      e.printStackTrace();  // fang alle fejl og log dem, men lad være at crashe app'en
    }
  }

  public static void stop() {
    if (mp != null) try {
      mp.stop(); // Stop tidligere afspilning
      mp.reset();
      mp.release();
      mp = null;
    } catch (Exception e) {
      e.printStackTrace();  // fang alle fejl og log dem, men lad være at crashe app'en
    }
  }
}


text:
namespace mojo {
namespace internal {

scoped_refptr<base::SequencedTaskRunner>
GetTaskRunnerToUseFromUserProvidedTaskRunner(
    scoped_refptr<base::SequencedTaskRunner> runner) {
  if (runner)
    return runner;
  return base::SequencedTaskRunner::GetCurrentDefault();
}

}  // namespace internal
}  // namespace mojo


text:
title: "Translating German to English"
date: 2022-04-03T01:02:16-04:00
tags:
  - german
showtoc: true
---

I've been trying to learn German on my own, without taking formal classes. I should write a post about this sometime.

For now, in this post I will briefly list the resources I use to translate German to English and/or to look up the definition of German words in German.

<!--more-->

## [Google Translate](https://translate.google.com/)

Everyone knows Google Translate, right? Direct link for `DE->EN` translations: https://translate.google.com/?sl=de&tl=en/

Google Translate is my to go swiss-army knife one-size-fits-all application whenever I need to translate something without thinking too much. It is decent for **words** and for **phrases, sentences and expressions**, giving you: (i) translation, (ii) synonyms / alternate translations, (iii) dictionary definition and (iv) pronounciation.

A quicker shortcut to use on the go is [Google](https://www.google.com/) itself: A query like [`translate strasse from german`](https://www.google.com/search?q=translate+strasse+from+german) works as you would expect, and it even displays an `Open in Google Translate` button for further tweaking.

## [dict.cc](https://www.dict.cc/)

Dict.cc is great to look up **detailed** definitions of German words and idioms. It's a superb dictionary (_Wörterbuch_). Example query: [strasse](https://www.dict.cc/?s=strasse). It has apps for Android and iOS, both of which support offline lookups.

## [DeepL](https://www.deepl.com/translator)

DeepL Translate is the new kid in town (released on 2017), "The world's most accurate translator" as they describe themselves. It's free, but with some limitations. Apparently they use some heavy machine learning machinery different than Google's that may yield better ("more natural") results in some situations. I like to keep it around as an alternative to Google Translate when its translations aren't satisfactory, but I don't use it much.

## [Google Dictionary](https://chrome.google.com/webstore/detail/google-dictionary-by-goog/mgijmajocgfcbeboacabfgobmjgjcoja?hl=en)

When using Google Chrome the **Google Dictionary** extension is handy to quickly look up word definitions without leaving the current page. A double click in a word triggers a pop-up balloon with a concise definition.

As a bonus it doubles down as an English dictionary.

## [Apple Dictionary](https://apple.com/)

On Apple operating systems, including [iOS](https://support.apple.com/en-ca/guide/pages-ipad/tan9ef3ea9f8/ipados) and [macOS](https://support.apple.com/en-ca/guide/mac-help/mchl3983326c/mac), one can out-of-the-box force touch a word which yields a behavior very similar to Google Dictionary ("Look Up").


text:
/*
 * DITNetworkManager.h
 */

#include <netinet/in.h>

#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>

extern NSString *const kNetworkStateChangedNotification;
extern NSString *const kNetworkStateChangedKey;

typedef enum {
	NotReachable = 0,
	ReachableViaWiFi,
	ReachableViaWWAN
} NetworkStatus;

/* Network state machine constants */
enum {
	kNetworkManagerDisconnected = 0,
	kNetworkManagerConnected    = 1
};

@interface DITNetworkManager : NSObject {

    SCNetworkReachabilityRef _networkAccessReachability;
    BOOL                     _hasNetwork;
    NetworkStatus            _networkStatus;
}

@property(assign) BOOL          hasNetwork;
@property(assign) NetworkStatus networkStatus;

/* Singleton access */
+ (DITNetworkManager*)defaultManager;

/* listen to network state related notifications on address 0.0.0.0 */
- (BOOL)installNetworkMonitoring;

@end


text:
<!-- Checklist For PRs

* Ensure you've written tests where applicable
* Add a CHANGELOG.md entry describing your change, thank yourself!
* Document any changes to metrics or configuration
-->

#### Summary
<!-- Simple summary of what the code does or what you have changed. -->

#### Motivation
<!-- Why are you making this change? -->

#### Test plan
<!-- How did you test this change? This can be as simple as "I wrote automated tests." -->

#### Rollout/monitoring/revert plan
<!-- Instructions for deploying, monitoring, and reverting this change. -->


text:
module Languages
  module Prefix
    #
    # /opt/languages
    # C:\languages
    #
    def default_prefix_base
      if Chef::Platform.windows?
        ::File.join(ENV['SYSTEMDRIVE'], 'languages')
      else
        '/opt/languages'
      end
    end

    #
    # /opt/languages/<LANGUAGE>/<VERSION>
    # C:\languages\<LANGUAGE>\<VERSION>
    #
    def default_prefix(version)
      # Infer the language from the class name
      #
      # Takes something like `Chef::Resource::RubyInstall`
      # and returns `Ruby`
      #
      language = self.class.to_s.split('::').last.split(/(?=[A-Z])/).first
      ::File.join(default_prefix_base, language.downcase, version)
    end
  end
end


text:
import fs = require('fs')
const config = require('config')
const replace = require('replace')
const utils = require('../utils')

const customizeApplication = () => {
  if (config.get('application.name')) {
    customizeTitle()
  }
  if (config.get('application.logo')) {
    void customizeLogo()
  }
  if (config.get('application.favicon')) {
    void customizeFavicon()
  }
  if (config.get('application.theme')) {
    customizeTheme()
  }
  if (config.get('application.cookieConsent')) {
    customizeCookieConsentBanner()
  }
  if (config.get('application.promotion')) {
    void customizePromotionVideo()
    void customizePromotionSubtitles()
  }
  if (config.get('hackingInstructor')) {
    void customizeHackingInstructorAvatar()
  }
  if (config.get('application.chatBot')) {
    void customizeChatbotAvatar()
  }
}

const customizeLogo = async () => {
  await retrieveCustomFile('application.logo', 'frontend/dist/frontend/assets/public/images')
}

const customizeChatbotAvatar = async () => {
  const avatarImage = await retrieveCustomFile('application.chatBot.avatar', 'frontend/dist/frontend/assets/public/images')
  fs.copyFileSync('frontend/dist/frontend/assets/public/images/' + avatarImage, 'frontend/dist/frontend/assets/public/images/ChatbotAvatar.png')
}

const customizeHackingInstructorAvatar = async () => {
  const avatarImage = await retrieveCustomFile('hackingInstructor.avatarImage', 'frontend/dist/frontend/assets/public/images')
  fs.copyFileSync('frontend/dist/frontend/assets/public/images/' + avatarImage, 'frontend/dist/frontend/assets/public/images/hackingInstructor.png')
}

const customizeFavicon = async () => {
  const favicon = await retrieveCustomFile('application.favicon', 'frontend/dist/frontend/assets/public')
  replace({
    regex: /type="image\/x-icon" href="assets\/public\/.*"/,
    replacement: `type="image/x-icon" href="assets/public/${favicon}"`,
    paths: ['frontend/dist/frontend/index.html'],
    recursive: false,
    silent: true
  })
}

const customizePromotionVideo = async () => {
  await retrieveCustomFile('application.promotion.video', 'frontend/dist/frontend/assets/public/videos')
}

const customizePromotionSubtitles = async () => {
  await retrieveCustomFile('application.promotion.subtitles', 'frontend/dist/frontend/assets/public/videos')
}

const retrieveCustomFile = async (sourceProperty: string, destinationFolder: string) => {
  let file = config.get(sourceProperty)
  if (utils.isUrl(file)) {
    const filePath = file
    file = utils.extractFilename(file)
    await utils.downloadToFile(filePath, destinationFolder + '/' + file)
  }
  return file
}

const customizeTitle = () => {
  const title = `<title>${config.get('application.name')}</title>`
  replace({
    regex: /<title>.*<\/title>/,
    replacement: title,
    paths: ['frontend/dist/frontend/index.html'],
    recursive: false,
    silent: true
  })
}

const customizeTheme = () => {
  const bodyClass = '"mat-app-background ' + config.get('application.theme') + '-theme"'
  replace({
    regex: /"mat-app-background .*-theme"/,
    replacement: bodyClass,
    paths: ['frontend/dist/frontend/index.html'],
    recursive: false,
    silent: true
  })
}

const customizeCookieConsentBanner = () => {
  const popupProperty = '"popup": { "background": "' + config.get('application.cookieConsent.backgroundColor') + '", "text": "' + config.get('application.cookieConsent.textColor') + '" }'
  replace({
    regex: /"popup": { "background": ".*", "text": ".*" }/,
    replacement: popupProperty,
    paths: ['frontend/dist/frontend/index.html'],
    recursive: false,
    silent: true
  })
  const buttonProperty = '"button": { "background": "' + config.get('application.cookieConsent.buttonColor') + '", "text": "' + config.get('application.cookieConsent.buttonTextColor') + '" }'
  replace({
    regex: /"button": { "background": ".*", "text": ".*" }/,
    replacement: buttonProperty,
    paths: ['frontend/dist/frontend/index.html'],
    recursive: false,
    silent: true
  })
  const contentProperty = '"content": { "message": "' + config.get('application.cookieConsent.message') + '", "dismiss": "' + config.get('application.cookieConsent.dismissText') + '", "link": "' + config.get('application.cookieConsent.linkText') + '", "href": "' + config.get('application.cookieConsent.linkUrl') + '" }'
  replace({
    regex: /"content": { "message": ".*", "dismiss": ".*", "link": ".*", "href": ".*" }/,
    replacement: contentProperty,
    paths: ['frontend/dist/frontend/index.html'],
    recursive: false,
    silent: true
  })
}

module.exports = customizeApplication


text:
[Grunt homepage](http://gruntjs.com/) | [Documentation table of contents](toc.md)

# Getting Started With Grunt

Grunt is a task-based command line build tool written in JavaScript. *[Why does grunt exist?](/)*

## Installing the CLI
In order to use grunt, you'll want to install the command line interface (CLI) globally.

```bash
npm install -g grunt-cli
```

This will put the `grunt` command in your system path, allowing it to be run from anywhere.

**Notes:** You may need to use `sudo` or run your command shell as Administrator to do this. Also, if you have installed grunt globally in the past, you will need to remove it with `npm uninstall -g grunt` first.

## How the CLI works

Each time `grunt` is run, it looks for a [Gruntfile] in the current folder. If none is found, it will traverse up the directory tree trying to find one. Because of this, you can run `grunt` from any subfolder in your project.

If a [Gruntfile] is found, the CLI loads a local installation of the grunt library, applies the configuration from your [Gruntfile], and executes any tasks you've requested for it to run.

## Preparing a grunt project
A typical setup will involve adding two files to your project: [package.json] and [the Gruntfile][Gruntfile].

**[package.json]**: This file is used by [npm] to store metadata for projects published as npm modules.  You will list grunt and the grunt plugins your project needs as [devDependencies] in this file.

**[The Gruntfile][Gruntfile]**: This file is named `Gruntfile.js` or `Gruntfile.coffee` and is used by grunt to configure or define tasks and load grunt plugins.

## package.json

The `package.json` file belongs in the root directory of your project, next to [the Gruntfile][Gruntfile], and should be committed with your project source.  Running `npm install` in the same folder as a `package.json` file will install the correct version of each dependency listed within.

Here are a few ways to create a `package.json` file for your project:

* A `package.json` file is automatically generated by most [init task] templates.
* The [npm init] command will create a basic `package.json` file for you.
* Start with the example below, and expand as needed, following this [specification][json].

```js
{
  "name": "my-project-name",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.0",
    "grunt-contrib-jshint": "~0.1.0",
    "grunt-contrib-nodeunit": "~0.1.0"
  }
}
```

### Adding dependencies
The easiest way to add grunt and grunt plugins to an existing `package.json` is with the command `npm install <module> --save-dev`.  Not only will this install `<module>` locally, but it will automatically be added to the [devDependencies] section, using a [tilde version range].

For example, this will install the latest version of grunt in your project folder, adding it to your devDependencies:

```bash
npm install grunt --save-dev
```

The same can be done for grunt plugins. Be sure to commit the updated `package.json` file with your project when you're done!

## The Gruntfile
The `Gruntfile.js` or `Gruntfile.coffee` file is a valid JavaScript or CoffeeScript file, placed in the root directory of your project—next to the `package.json` file—and should be committed with your project source.

A Gruntfile is comprised of the following parts:

* The "wrapper" function
* Project and task configuration
* Loading grunt plugins and tasks
* Custom inline tasks

### An example Gruntfile
In the following Gruntfile, project metadata is imported into the grunt config from a `package.json` file, and the [grunt-contrib-uglify plugin] `uglify` task is configured to minify a source file and generate a banner comment dynamically using that metadata.

```js
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      dist: {
        src: 'src/<%= pkg.name %>.js',
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    }
  });

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Default task(s).
  grunt.registerTask('default', ['uglify']);

};
```

### The "wrapper" function
Every Gruntfile (and grunt plugin) uses this basic format, and all of your grunt code must be specified inside this function:

```js
module.exports = function(grunt) {
  // Do grunt-related things in here
};
```

### Project and task configuration
Most grunt tasks rely on configuration data defined in an object passed to the [grunt.initConfig] method.

In this example, `grunt.file.readJSON('package.json')` imports the JSON metadata stored in `package.json` into the grunt config. Because `<% %>` template strings may reference any config properties, configuration data like filepaths and file lists may be specified this way to reduce repetition.

You may store any arbitrary data inside of the configuration object, and as long as it doesn't conflict with properties your tasks require, it will be otherwise ignored. Also, because this is JavaScript, you're not limited to JSON; you may use any valid JS here. You can even programmatically generate the configuration if necessary.

Like most tasks, the [grunt-contrib-uglify plugin] `uglify` task expects its configuration to be specified in a property of the same name. Here, the `banner` option is specified, along with a single uglify target named `dist` that minifies a single source file to a single destination file.

((( link out to the options object page and file lists page )))

```js
// Project configuration.
grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  uglify: {
    options: {
      banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
    },
    dist: {
      src: 'src/<%= pkg.name %>.js',
      dest: 'dist/<%= pkg.name %>.min.js'
    }
  }
});
```

### Loading grunt plugins and tasks
Many commonly used tasks like [concatenation], [minification][grunt-contrib-uglify plugin] and [linting] are available as [grunt plugins]. As long as a plugin is specified in `package.json` as a dependency, and has been installed via `npm install`, it may be enabled inside your [Gruntfile] with a simple command:

```js
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
```

Tasks defined in external `.js` files can be loaded from with the [grunt.loadTasks] method.

**Note:** You can list all available tasks with the command `grunt --help`.

### Custom inline tasks
If your project only uses tasks provided by [grunt plugins], you might not need to define any custom tasks. That being said, if you want grunt to perform one or more tasks by default when running `grunt` with no arguments, you'll need to create a default task.

To do this, create an [alias task][custom tasks].  In the example below, when running `grunt` (or `grunt default`) at the command line, the uglify task will be run. This is functionally the same as running `grunt uglify`.

```js
// Default task(s).
grunt.registerTask('default', ['uglify']);
```

If you want to run multiple tasks in succession with a single command, just add more tasks to the array, with any arguments they might need.

```js
// Build my project
grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
```

If you don't need pre-made tasks, and you don't want to [load your custom tasks from an external folder][grunt.loadTasks], you can register tasks right inside your [Gruntfile].

Here is an extremely simple example [Gruntfile] that doesn't even utilize task configuration:

```js
module.exports = function(grunt) {

  // A very basic default task.
  grunt.registerTask('default', 'Log some stuff.', function() {
    grunt.log.write('Logging some stuff...').ok();
  });

};
```

For more information about writing custom tasks or grunt plugins, check out the [developer documentation].

[Gruntfile]: #the-gruntfile
[package.json]: #packagejson
[npm]: https://npmjs.org/
[devDependencies]: https://npmjs.org/doc/json.html#devDependencies
[json]: https://npmjs.org/doc/json.html
[npm init]: https://npmjs.org/doc/init.html
[init task]: task_init.md
[tilde version range]: https://npmjs.org/doc/json.html#Tilde-Version-Ranges
[grunt.initConfig]: api.md
[grunt-contrib-uglify plugin]: http://github.com/gruntjs/grunt-contrib-uglify
[concatenation]: https://github.com/gruntjs/grunt-contrib-concat
[linting]: https://github.com/gruntjs/grunt-contrib-jshint
[grunt.loadTasks]: https://github.com/gruntjs/grunt/blob/devel/docs/api.md#loading-externally-defined-tasks
[grunt plugins]: TODO
[custom tasks]: TODO
[developer documentation]: TODO


text:
package org.eclipse.php.internal.ui.text;

import java.io.IOException;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.wst.sse.ui.internal.derived.SingleCharReader;

/**
 * Reads from a document either forwards or backwards. May be configured to skip
 * comments and strings.
 */
public class PHPCodeReader extends SingleCharReader {

	/** The EOF character */
	public static final int EOF = -1;

	private boolean fSkipComments = false;
	private boolean fSkipStrings = false;
	private boolean fForward = false;

	private IDocument fDocument;
	private int fOffset;

	private int fEnd = -1;
	private int fCachedLineNumber = -1;
	private int fCachedLineOffset = -1;

	public PHPCodeReader() {
	}

	/**
	 * Returns the offset of the last read character. Should only be called
	 * after read has been called.
	 */
	public int getOffset() {
		return fForward ? fOffset - 1 : fOffset;
	}

	public void configureForwardReader(IDocument document, int offset,
			int length, boolean skipComments, boolean skipStrings)
			throws IOException {
		fDocument = document;
		fOffset = offset;
		fSkipComments = skipComments;
		fSkipStrings = skipStrings;

		fForward = true;
		fEnd = Math.min(fDocument.getLength(), fOffset + length);
	}

	public void configureBackwardReader(IDocument document, int offset,
			boolean skipComments, boolean skipStrings) throws IOException {
		fDocument = document;
		fOffset = offset;
		fSkipComments = skipComments;
		fSkipStrings = skipStrings;

		fForward = false;
		try {
			fCachedLineNumber = fDocument.getLineOfOffset(fOffset);
		} catch (BadLocationException x) {
			throw new IOException(x.getMessage());
		}
	}

	/*
	 * @see Reader#close()
	 */
	public void close() throws IOException {
		fDocument = null;
	}

	/*
	 * @see SingleCharReader#read()
	 */
	public int read() throws IOException {
		try {
			return fForward ? readForwards() : readBackwards();
		} catch (BadLocationException x) {
			throw new IOException(x.getMessage());
		}
	}

	private void gotoCommentEnd() throws BadLocationException {
		while (fOffset < fEnd) {
			char current = fDocument.getChar(fOffset++);
			if (current == '*') {
				if (fOffset < fEnd && fDocument.getChar(fOffset) == '/') {
					++fOffset;
					return;
				}
			}
		}
	}

	private void gotoStringEnd(char delimiter) throws BadLocationException {
		while (fOffset < fEnd) {
			char current = fDocument.getChar(fOffset++);
			if (current == '\\') {
				// ignore escaped characters
				++fOffset;
			} else if (current == delimiter) {
				return;
			}
		}
	}

	private void gotoLineEnd() throws BadLocationException {
		int line = fDocument.getLineOfOffset(fOffset);
		fOffset = fDocument.getLineOffset(line + 1);
	}

	private int readForwards() throws BadLocationException {
		while (fOffset < fEnd) {
			char current = fDocument.getChar(fOffset++);

			switch (current) {
			case '/':

				if (fSkipComments && fOffset < fEnd) {
					char next = fDocument.getChar(fOffset);
					if (next == '*') {
						// a comment starts, advance to the comment end
						++fOffset;
						gotoCommentEnd();
						continue;
					} else if (next == '/') {
						// '//'-comment starts, advance to the line end
						gotoLineEnd();
						continue;
					}
				}

				return current;

			case '"':
			case '\'':

				if (fSkipStrings) {
					gotoStringEnd(current);
					continue;
				}

				return current;
			}

			return current;
		}

		return EOF;
	}

	private void handleSingleLineComment() throws BadLocationException {
		int line = fDocument.getLineOfOffset(fOffset);
		if (line < fCachedLineNumber) {
			fCachedLineNumber = line;
			fCachedLineOffset = fDocument.getLineOffset(line);
			int offset = fOffset;
			while (fCachedLineOffset < offset) {
				char current = fDocument.getChar(offset--);
				if (current == '/' && fCachedLineOffset <= offset
						&& fDocument.getChar(offset) == '/') {
					fOffset = offset;
					return;
				}
			}
		}
	}

	private void gotoCommentStart() throws BadLocationException {
		while (0 < fOffset) {
			char current = fDocument.getChar(fOffset--);
			if (current == '*' && 0 <= fOffset
					&& fDocument.getChar(fOffset) == '/')
				return;
		}
	}

	private void gotoStringStart(char delimiter) throws BadLocationException {
		while (0 < fOffset) {
			char current = fDocument.getChar(fOffset);
			if (current == delimiter) {
				if (!(0 <= fOffset && fDocument.getChar(fOffset - 1) == '\\'))
					return;
			}
			--fOffset;
		}
	}

	private int readBackwards() throws BadLocationException {

		while (0 < fOffset) {
			--fOffset;

			handleSingleLineComment();

			char current = fDocument.getChar(fOffset);
			switch (current) {
			case '/':

				if (fSkipComments && fOffset > 1) {
					char next = fDocument.getChar(fOffset - 1);
					if (next == '*') {
						// a comment ends, advance to the comment start
						fOffset -= 2;
						gotoCommentStart();
						continue;
					}
				}

				return current;

			case '"':
			case '\'':

				if (fSkipStrings) {
					--fOffset;
					gotoStringStart(current);
					continue;
				}

				return current;
			}

			return current;
		}

		return EOF;
	}
}


text:
package weixin.idea.photo.common;

public interface PhotoConstant {

	/**微相微模板根路径*/
	public static final String PHOTO_ROOT_URL = "/template/photo";
	/**微相册默认样式 */
	public static final String PHOTO_DEFAULT_STYLE = "default";
	/**微相册html文件夹 */
	public static final String HTML = "html";
	/**微相册数据 */
	public static final String photoAlbumData = "photoAlbumData";
	/**相片数据 */
	public static final String photoData = "photoData";
	/**资源相对路径*/
	public static final String RES = "res";
	/**微相微模板根路径*/
	public static final String PHOTO_ROOT_PATH = "template/photo";
}


text:
//******************************************************************************************************
//  JsonHelpers.cs - Gbtc
//
//  Copyright © 2021, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
//  file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  05/18/2021 - J. Ritchie Carroll
//       Generated original version of source code.
//
//******************************************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

// ReSharper disable ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable ClassNeverInstantiated.Local
namespace UpdateCOMTRADECounters
{
    internal static class JsonHelpers
    {
        private class ProtocolOrigins
        {
            public IList<string> allowed_origins { get; set; }
            public string protocol { get; set; }
        }

        private class ExemptDomainFilesTypes
        {
            public string file_extension { get; set; }
            public IList<string> domains { get; set; }
        }

        public static string InjectProtocolOrigins(string protocolOriginsJson, string targetAllowedOrigin, string protocol)
        {
            List<ProtocolOrigins> protocolOrigins = JsonConvert.DeserializeObject<List<ProtocolOrigins>>(protocolOriginsJson);
            bool foundProtocol = false;

            foreach (ProtocolOrigins current in protocolOrigins!)
            {
                if (!string.Equals(current.protocol, protocol, StringComparison.OrdinalIgnoreCase))
                    continue;

                foundProtocol = true;

                // Disallow single wildcard without port
                if (current.allowed_origins.Count == 1 && current.allowed_origins[0] == "*")
                {
                    current.allowed_origins[0] = targetAllowedOrigin;
                }
                else
                {
                    if (current.allowed_origins.Any(allowedOrigin => string.Equals(allowedOrigin, targetAllowedOrigin, StringComparison.OrdinalIgnoreCase)))
                        return protocolOriginsJson;

                    current.allowed_origins.Add(targetAllowedOrigin);
                }
                break;
            }

            if (!foundProtocol)
            {
                protocolOrigins.Add(new ProtocolOrigins
                {
                    allowed_origins = new[] { targetAllowedOrigin },
                    protocol = protocol
                });
            }

            return JsonConvert.SerializeObject(protocolOrigins, Formatting.None);
        }

        public static string InjectExemptDomainFilesTypes(string exemptDomainFilesTypesJson, string fileExtension, string targetDomain)
        {
            List<ExemptDomainFilesTypes> exemptDomainFilesTypes = JsonConvert.DeserializeObject<List<ExemptDomainFilesTypes>>(exemptDomainFilesTypesJson);
            bool foundFileExtension = false;

            foreach (ExemptDomainFilesTypes current in exemptDomainFilesTypes!)
            {
                if (!string.Equals(current.file_extension, fileExtension, StringComparison.OrdinalIgnoreCase))
                    continue;

                foundFileExtension = true;

                // Disallow single wildcard without port
                if (current.domains.Count == 1 && current.domains[0] == "*")
                {
                    current.domains[0] = targetDomain;
                }
                else
                {
                    if (current.domains.Any(domain => string.Equals(domain, targetDomain, StringComparison.OrdinalIgnoreCase)))
                        return exemptDomainFilesTypesJson;

                    current.domains.Add(targetDomain);
                }
                break;
            }

            if (!foundFileExtension)
            {
                exemptDomainFilesTypes.Add(new ExemptDomainFilesTypes
                {
                    file_extension = fileExtension,
                    domains = new[] { targetDomain }
                });
            }

            return JsonConvert.SerializeObject(exemptDomainFilesTypes, Formatting.None);
        }
    }
}


text:
package com.sophia.api.common;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.sophia.api.BaseController;
import com.sophia.domain.Api;

/**
 * Created by Kim on 2015/9/11.
 */
@RestController
@RequestMapping(name="API管理类",value = "/api/apiMgr")
public class ApiMgrController extends BaseController {

    @RequestMapping(name="获取所有API",value = "", method = RequestMethod.GET)
    public List<Api> getAllApi() {
        List<Api> apiList = new ArrayList<Api>();
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest req = attrs.getRequest();
        WebApplicationContext web =(WebApplicationContext)
                req.getSession().getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        Map map = web.getBeansWithAnnotation(RequestMapping.class);
        try {
            for (Iterator it=map.keySet().iterator();it.hasNext();){
                String key = (String)it.next();
                Object ctrl = (Object)map.get(key);
                RequestMapping rm = ctrl.getClass().getAnnotation(RequestMapping.class);
                if (rm==null || rm.value() == null) {
                    continue;
                }
                String uri = rm.value()[0];
                Method[] methods = ctrl.getClass().getMethods();
                for (int i = 0 ; i<methods.length; i++) {
                    RequestMapping requestMapping = methods[i].getAnnotation(RequestMapping.class);
                    if (requestMapping!=null) {
                        Api api = new Api();
                        api.setName(requestMapping.name());
                        api.setUri(uri + ((requestMapping.value().length == 0) ? "" : requestMapping.value()[0]));
                        api.setMethod((requestMapping.method().length == 0) ? RequestMethod.GET : requestMapping.method()[0]);
                        api.setCtrlName(ctrl.getClass().getName());
                        apiList.add(api);
                    }
                }
            }
        }catch (Exception ex) {
            ex.printStackTrace();
        }

        return  apiList;
    }

}


text:
HOST=""
IP=""
MASK=""
GW=""
KEYMAP=""

##################### Functions definition
function abort {
  echo "ABORTED"
  exit 1
}

function _wait {

  COUNT=$1

  for i in `seq 1 $COUNT` ;
  do
      echo "Next task comming in $(($COUNT+1-$i)) seconds. (Ctrl+c to interrupt execution)"
      sleep 1
  done

}

function _reboot {

  COUNT=$1

  for i in `seq 1 $COUNT` ;
  do
      echo "Reboot in $(($COUNT+1-$i)) seconds. (shutdown -c in other terminal to cancel.)"
      sleep 1
  done

  shutdown -r now
}

function check_result {

  RES=$1

  if [ "$RES" -eq "0" ] ; then
    echo "OK"
  else
    echo "Errors encountered while the script execution."
    abort
  fi
}

function print_usage {

  echo "Usage:"
  echo "./configure.sh --hostname HOSTNAME [--ip IP --mask MASK --gateway GW]"
  echo "More info at https://github.com/melon-boy/odroid-webserver/README.md"

}

##################### Main execution
# Parse arguments
OPTIONS=h:i:m:g:
LONGOPTIONS=hostname:,ip:,mask:,gateway:

PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTIONS --name "$0" -- "$@")

eval set -- "$PARSED"

while true; do
  case "$1" in
      -h|--hostname)
         HOST="$2"
         shift 2
         ;;
      -i|--ip)
         IP="$2"
         shift 2
         ;;
      -m|--mask)
         MASK="$2"
         shift 2
         ;;
      -g|--gateway)
        GW="$2"
        shift 2
        ;;
      --)
        shift
        break
        ;;
      *)
        abort
        ;;
    esac
done

if [ -z $HOST ] ; then
  echo "Hostname parameter missing."
  print_usage
  abort
fi

if [ ! -z $IP ] ; then
  if [ -z $MASK ] || [ -z $GW ] ; then
    echo "Network configuration is not complete. Some parameters are missing."
    print_usage
    abort
  fi
fi

# Execution of diferent scripts to configure the distro.
./dist-upgrade.sh
check_result $?
_wait 5
# securization with hostname, ip address, mask and gateway parameters.
./securization.sh $HOST $IP $MASK $GW
check_result $?
_wait 5
./install-ffmpeg.sh
check_result $?
_wait 5
./install-pkgs.sh
check_result $?
_wait 5
./install-webserver.sh
check_result $?
# Reboot needed in 10 seconds
echo "***"
echo "*** Reboot is needed: please run apt-get autoremove after system starts ***"
echo "***"
_reboot 10


text:
import { readFileSync } from 'fs';
import { join } from 'path';

import test from 'ava';
import webpack from 'webpack';
import rimraf from 'rimraf';

test('basic usage', async t => {
	await new Promise((resolve, reject) => {
		webpack({
			mode: 'development',
			devtool: false,
			entry: join(__dirname, 'src/main.js'),
			bail: true,
			output: {
				path: join(__dirname, 'dist'),
				filename: 'main.bundle.js'
			},
			module: {
				rules: [{
					test: /\.entry\.js$/,
					use: {
						loader: join(__dirname, '../index.js'),
						options: { name: '[name].spawned.js' }
					}
				}]
			}
		}, (err, stats) => {
			stats.hasErrors() ? reject(stats.toString()) : resolve(stats);
		});
	});

	const mainBundle = readFileSync(join(__dirname, 'dist/main.bundle.js'), 'utf8');
	const otherEntry = readFileSync(join(__dirname, 'dist/other.entry.spawned.js'), 'utf8');
	const hi = readFileSync(join(__dirname, 'dist/children/hi.jpg'));
	const child1 = readFileSync(join(__dirname, 'dist/children/child1.js'), 'utf8');
	const subchild = readFileSync(join(__dirname, 'dist/children/subchild/subchild.js'), 'utf8');
	const defaults = readFileSync(join(__dirname, 'dist/defaults.js'), 'utf8');
	const manifest = readFileSync(join(__dirname, 'dist/inertOut/manifest.notjson'), 'utf8');
	const defaultsWithHash = readFileSync(
		join(__dirname, process.platform === 'win32' ? 'dist/defaults.acd3bd.js' : 'dist/defaults.586ec8.js'),
		'utf8'
	);
	const defaultsInertWithHash = readFileSync(
		join(__dirname, process.platform === 'win32' ? 'dist/defaults-inert.acd3bd.js' : 'dist/defaults-inert.586ec8.js'),
		'utf8'
	);

	t.regex(mainBundle, /"other\.entry\.spawned\.js"/, 'references spawned other entry');
	t.regex(mainBundle, /"children(\/|\\\\)child1\.js"/, 'references spawned child1');
	t.regex(mainBundle, /"defaults\.js"/, 'references spawned defaults');
	t.regex(mainBundle, /"inertOut(\/|\\\\)manifest\.notjson"/, 'references spawned manifest.json');
	t.regex(
		mainBundle,
		process.platform === 'win32' ? /"defaults.acd3bd.js"/ : /"defaults.586ec8.js"/,
		'references spawned defaults with hash'
	);
	t.regex(
		mainBundle,
		process.platform === 'win32' ? /"defaults-inert.acd3bd.js"/ : /"defaults-inert.586ec8.js"/,
		'references spawned inert defaults with hash'
	);
	t.regex(mainBundle, /__webpack_require__\.p = ""/, 'publicPath is empty');

	t.regex(otherEntry, /\bfunction __webpack_require__\b/, 'has prelude');
	t.regex(otherEntry, /var foo = bar;/, 'has expected content');
	t.regex(otherEntry, /__webpack_require__\.p = ""/, 'publicPath is empty');

	t.truthy(hi, 'hi.jpg exists');

	t.regex(child1, /\bfunction __webpack_require__\b/, 'has prelude');
	t.regex(child1, /"hi\.jpg"/, 'references hi.jpg');
	t.regex(child1, /"subchild(\/|\\\\)subchild\.js"/, 'references spawned subchild');
	t.regex(child1, /__webpack_require__\.p = ""/, 'publicPath is empty');

	t.regex(subchild, /\bfunction __webpack_require__\b/, 'has prelude');
	t.regex(subchild, /var a = 'b';/, 'has expected content');
	t.regex(subchild, /__webpack_require__\.p = ""/, 'publicPath is empty');

	t.regex(defaults, /\bfunction __webpack_require__\b/, 'has prelude');
	t.regex(defaults, /var def = 'aults';/, 'has expected content');
	t.regex(defaults, /__webpack_require__\.p = ""/, 'publicPath is empty');

	t.regex(manifest, /^\{ "manifest": "json" \}\s+$/, 'manifest.json exists, is raw content');

	t.regex(defaultsWithHash, /\bfunction __webpack_require__\b/, 'has prelude');
	t.regex(defaultsWithHash, /var def = 'aults';/, 'has expected content');
	t.regex(defaultsWithHash, /__webpack_require__\.p = ""/, 'publicPath is empty');

	t.regex(defaultsInertWithHash, /^var def = 'aults';\s+$/, 'has expected, raw content');
});

test.after(t => {
	rimraf.sync(join(__dirname, 'dist'));
});