text:
module ActiveRecord
  class PredicateBuilder # :nodoc:
    @handlers = []

    autoload :RelationHandler, 'active_record/relation/predicate_builder/relation_handler'
    autoload :ArrayHandler, 'active_record/relation/predicate_builder/array_handler'

    def self.resolve_column_aliases(klass, hash)
      hash = hash.dup
      hash.keys.grep(Symbol) do |key|
        if klass.attribute_alias? key
          hash[klass.attribute_alias(key)] = hash.delete key
        end
      end
      hash
    end

    def self.build_from_hash(klass, attributes, default_table)
      queries = []

      attributes.each do |column, value|
        table = default_table

        if value.is_a?(Hash)
          if value.empty?
            queries << '1=0'
          else
            table       = Arel::Table.new(column, default_table.engine)
            association = klass._reflect_on_association(column.to_sym)

            value.each do |k, v|
              queries.concat expand(association && association.klass, table, k, v)
            end
          end
        else
          column = column.to_s

          if column.include?('.')
            table_name, column = column.split('.', 2)
            table = Arel::Table.new(table_name, default_table.engine)
          end

          queries.concat expand(klass, table, column, value)
        end
      end

      queries
    end

    def self.expand(klass, table, column, value)
      queries = []

      # Find the foreign key when using queries such as:
      # Post.where(author: author)
      #
      # For polymorphic relationships, find the foreign key and type:
      # PriceEstimate.where(estimate_of: treasure)
      if klass && reflection = klass._reflect_on_association(column.to_sym)
        base_class = polymorphic_base_class_from_value(value)
        if reflection.polymorphic? && base_class
          queries << build(table[reflection.foreign_type], base_class)
        end

        column = reflection.foreign_key

        if base_class
          primary_key = reflection.association_primary_key(base_class)
          value = convert_value_to_association_ids(value, primary_key)
        end
      end

      queries << build(table[column], value)
      queries
    end

    def self.polymorphic_base_class_from_value(value)
      case value
      when Relation
        value.klass.base_class
      when Array
        val = value.compact.first
        val.class.base_class if val.is_a?(Base)
      when Base
        value.class.base_class
      end
    end

    def self.references(attributes)
      attributes.map do |key, value|
        if value.is_a?(Hash)
          key
        else
          key = key.to_s
          key.split('.').first if key.include?('.')
        end
      end.compact
    end

    # Define how a class is converted to Arel nodes when passed to +where+.
    # The handler can be any object that responds to +call+, and will be used
    # for any value that +===+ the class given. For example:
    #
    #     MyCustomDateRange = Struct.new(:start, :end)
    #     handler = proc do |column, range|
    #       Arel::Nodes::Between.new(column,
    #         Arel::Nodes::And.new([range.start, range.end])
    #       )
    #     end
    #     ActiveRecord::PredicateBuilder.register_handler(MyCustomDateRange, handler)
    def self.register_handler(klass, handler)
      @handlers.unshift([klass, handler])
    end

    register_handler(BasicObject, ->(attribute, value) { attribute.eq(value) })
    # FIXME: I think we need to deprecate this behavior
    register_handler(Class, ->(attribute, value) { attribute.eq(value.name) })
    register_handler(Base, ->(attribute, value) { attribute.eq(value.id) })
    register_handler(Range, ->(attribute, value) { attribute.in(value) })
    register_handler(Relation, RelationHandler.new)
    register_handler(Array, ArrayHandler.new)

    private

    def self.build(attribute, value)
      handler_for(value).call(attribute, value)
    end
    private_class_method :build

    def self.handler_for(object)
      @handlers.detect { |klass, _| klass === object }.last
    end
    private_class_method :handler_for

    def self.convert_value_to_association_ids(value, primary_key)
      case value
      when Relation
        value.select(primary_key)
      when Array
        value.map { |v| convert_value_to_association_ids(v, primary_key) }
      when Base
        value.read_attribute(primary_key)
      else
        value
      end
    end
  end
end


text:
package sb.tasks.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import sb.tasks.model.Task;

public interface Agent {

    Iterable<TaskResult> perform(Task task) throws IOException;

    default Iterable<TaskResult> toIterable(TaskResult obj) {
        List<TaskResult> result = new ArrayList<>();
        result.add(obj);
        return result;
    }

    final class EMPTY implements Agent {
        @Override
        public Iterable<TaskResult> perform(Task task) {
            return Collections.emptyList();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{% extends "style/base_section.html" %}
{# This is for editing information for the currently logged in WebUser #}

{% load crispy_forms_tags %}
{% load hq_shared_tags %}
{% load i18n %}

{% block stylesheets %}
    <style>

        #phone-numbers-list form {
            display: inline;
            padding-left: .1em;
        }
    </style>
{% endblock %}

{% block js-inline %} {{ block.super }}
    <script>
        $('#id_language').select2();

        $('form[name="user_information"]').on("change", null, null, function() {
            $(":submit").prop("disabled", false);
        }).on("input", null, null, function() {
            $(":submit").prop("disabled", false);
        })

        $('#generate-api-key').click(function() {
            var apiDiv = $(this).parent().parent().parent();
            $.post('{% url 'new_api_key' %}', '', function(data) {
                apiDiv.find('.form-control-static').text(data);
            });
        });
    </script>
{% endblock %}
b3
{% block modals %}{{ block.super }}
{% if user_type == 'web' %}
    {% include 'users/partial/basic_info_modals.html' %}
{% endif %}
{% endblock %}

{% block page_content %}
    {% crispy form form.new_helper %}
    {% if user_type == 'web' %}
        {% include 'users/partial/manage_my_numbers.html' %}
    {% endif %}
{% endblock %}


text:
package org.onosproject.ovsdb.controller;

import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Objects;

/**
 * The class representing a ovsdb port. This class is immutable.
 */
public final class OvsdbPort {

    private final OvsdbPortNumber portNumber;
    private final OvsdbPortName portName;

    /**
     * Constructor from  OvsdbPortNumber portNumber, OvsdbPortName portName.
     *
     * @param portNumber the portNumber to use
     * @param portName the portName to use
     */
    public OvsdbPort(OvsdbPortNumber portNumber, OvsdbPortName portName) {
        checkNotNull(portNumber, "portNumber is not null");
        checkNotNull(portName, "portName is not null");
        this.portNumber = portNumber;
        this.portName = portName;
    }

    /**
     * Gets the port number of port.
     *
     * @return the port number of port
     */
    public OvsdbPortNumber portNumber() {
        return portNumber;
    }

    /**
     * Gets the port name of port.
     *
     * @return the port name of port
     */
    public OvsdbPortName portName() {
        return portName;
    }

    @Override
    public int hashCode() {
        return Objects.hash(portNumber, portName);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof OvsdbPort) {
            final OvsdbPort otherOvsdbPort = (OvsdbPort) obj;
            return Objects.equals(this.portNumber, otherOvsdbPort.portNumber)
                    && Objects.equals(this.portName, otherOvsdbPort.portName);
        }
        return false;
    }

    @Override
    public String toString() {
        return toStringHelper(this)
                .add("portNumber", String.valueOf(portNumber.value()))
                .add("portName", portName.value()).toString();
    }
}


text:
class TestTabStripModelObserver::RenderViewHostInitializedObserver
    : public content::RenderViewHostObserver {
 public:
  RenderViewHostInitializedObserver(content::RenderViewHost* render_view_host,
                                    content::JsInjectionReadyObserver* observer)
      : content::RenderViewHostObserver(render_view_host),
        injection_observer_(observer) {
  }

  // content::RenderViewHostObserver:
  virtual void RenderViewHostInitialized() OVERRIDE {
    injection_observer_->OnJsInjectionReady(render_view_host());
  }

 private:
  content::JsInjectionReadyObserver* injection_observer_;

  DISALLOW_COPY_AND_ASSIGN(RenderViewHostInitializedObserver);
};

TestTabStripModelObserver::TestTabStripModelObserver(
    TabStripModel* tab_strip_model,
    content::JsInjectionReadyObserver* js_injection_ready_observer)
    : TestNavigationObserver(1),
      tab_strip_model_(tab_strip_model),
      injection_observer_(js_injection_ready_observer) {
  registrar_.Add(this, content::NOTIFICATION_RENDER_VIEW_HOST_CREATED,
                 content::NotificationService::AllSources());

  tab_strip_model_->AddObserver(this);
}

TestTabStripModelObserver::~TestTabStripModelObserver() {
  tab_strip_model_->RemoveObserver(this);
}

void TestTabStripModelObserver::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CREATED) {
    rvh_observer_.reset(
        new RenderViewHostInitializedObserver(
            content::Source<content::RenderViewHost>(source).ptr(),
            injection_observer_));
  } else {
    content::TestNavigationObserver::Observe(type, source, details);
  }
}

void TestTabStripModelObserver::TabBlockedStateChanged(
    content::WebContents* contents, int index) {
  // Need to do this later - the print preview dialog has not been created yet.
  MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&TestTabStripModelObserver::ObservePrintPreviewDialog,
                 base::Unretained(this),
                 contents));
}

void TestTabStripModelObserver::ObservePrintPreviewDialog(
    content::WebContents* contents) {
  printing::PrintPreviewDialogController* dialog_controller =
      printing::PrintPreviewDialogController::GetInstance();
  if (!dialog_controller)
    return;
  content::WebContents* preview_dialog =
      dialog_controller->GetPrintPreviewForContents(contents);
  if (!preview_dialog)
    return;
  RegisterAsObserver(content::Source<content::NavigationController>(
      &preview_dialog->GetController()));
}


text:
An OAuth shim for [hello.js OAuth JavaScript SDK](http://github.com/MrSwitch/hello.js/). This is a fork from [rjstanford/hello-oauth-shim](https://github.com/rjstanford/hello-oauth-shim).

### Usage

Point the SDK to this project instance.
```
oauth_proxy=<url of where this code is run>
```
(See [hello.js OAuth JavaScript SDK](http://github.com/MrSwitch/hello.js/) How-to)

### Service

Run on local machine.
```
mvn appengine:devserver
```


text:
import json
import hmac, hashlib
import threading
import http, http.server
from halibot import HalModule, Message

def make_issues_report(event, payload):
	title = payload['issue']['title']
	user = payload['sender']['login']
	repo = payload['repository']['full_name']

	if payload['action'] == 'opened':
		return 'New issue "{}" opened by {} in {}.'.format(title, user, repo)

	if payload['action'] == 'reopened':
		return 'Issue "{}" reopened by {} in {}.'.format(title, user, repo)

	if payload['action'] == 'closed':
		return 'Issue "{}" closed by {} in {}.'.format(title, user, repo)

	return None

def make_pr_report(event, payload):
	title = payload['pull_request']['title']
	user = payload['sender']['login']
	repo = payload['repository']['full_name']

	if payload['action'] == 'opened':
		return 'Pull request "{}" opened by {} in {}.'.format(title, user, repo)

	if payload['action'] == 'reopened':
		return 'Pull request "{}" reopened by {} in {}.'.format(title, user, repo)

	if payload['action'] == 'closed':
		merged = '' if payload['pull_request']['merged'] else 'not '
		return 'Pull request "{}" closed and {}merged by {} in {}.'.format(title, merged, user, repo)

	return None

def make_report(event, payload):
	fun = {
		'issues': make_issues_report,
		'pull_request': make_pr_report,
	}.get(event, None)

	if fun == None:
		return None

	return fun(event, payload)

class GithubHookHandler(http.server.BaseHTTPRequestHandler):

	def do_POST(self):
		module = self.server.module
		config = module.config

		# filter out non-github events
		if not 'X-Github-Event' in self.headers:
			# Ignore and timeout
			module.log.info('Received something that is not a github event, ignoring.')
			return

		length = int(self.headers['Content-Length'])
		data = self.rfile.read(length)

		# Do hmac verification if enabled
		# Enabling recommend so people don't send random garbage to the endpoint
		if 'secret' in config:
			h = hmac.new(config['secret'].encode(), msg=data, digestmod=hashlib.sha1)
			expect = 'sha1=' + h.hexdigest()

			if expect != self.headers['X-Hub-Signature']:
				module.log.warning('HMAC signature mismatch!')
				return

		# TODO read charset from header
		payload = json.loads(data.decode('utf-8'))

		event = self.headers['X-Github-Event']
		action = payload.get('action', None)

		module.log.debug('Received {} {} event.'.format(event, action))

		# ignore events we didn't ask for
		events = module.events
		if event in events and action in events[event]:
			report = make_report(event, payload)

			# Ignore events we don't know how to handle
			if report != None:
				msg = Message(body=report, author='halibot')
				module.log.debug('Reporting event to ' + config['dest'])
				module.send_to(msg, [ config['dest'] ])
			else:
				module.log.warning('Could not form report for "{} {}"'.format(event, action))

		self.send_response(204)
		self.end_headers()

class Github(HalModule):

	options = {
		'secret': {
			'type'   : 'string',
			'prompt' : 'Shared secret',
		},
		'dest': {
			'type'   : 'string',
			'prompt' : 'Destination',
		},
		'port': {
			'type'   : 'int',
			'prompt' : 'Port to listen on',
			'default': 9000,
		},
	}

	# Override the configure method so we can do more complicated configuration prompts
	@classmethod
	def configure(cls, config):
		(name, config) = super(Github, Github).configure(config)

		def promptYn(prompt):
			yn = input(prompt + '? [Y/n] ')
			if len(yn) < 1: return True
			return yn[0].upper() == 'Y'

		issues = []
		prs = []

		if promptYn('List for opened issues'):   issues.append('opened')
		if promptYn('List for reopened issues'): issues.append('reopened')
		if promptYn('List for closed issues'):   issues.append('closed')
		if promptYn('List for opened pull requests'):   prs.append('opened')
		if promptYn('List for reopened pull requests'): prs.append('reopened')
		if promptYn('List for closed pull requests'):   prs.append('closed')

		config['events'] = {
			'issues': issues,
			'pull_request': prs,
		}

		return (name, config)

	def init(self):
		self.events = self.config.get('events', {})

		addr = ('', self.config.get('port', 9000))
		self.server = http.server.HTTPServer(addr, GithubHookHandler)
		self.server.module = self
		self.thread = threading.Thread(target=self.server.serve_forever)
		self.thread.start()

	def shutdown(self):
		self.server.shutdown()
		self.thread.join()


text:
namespace spot
{
  /// \ingroup twa_generic
  /// \brief Make a BFS in a spot::tgba to compute a twa_run::steps.
  ///
  /// This class should be used to compute the shortest path
  /// between a state of a spot::tgba and the first transition or
  /// state that matches some conditions.
  ///
  /// These conditions should be specified by defining bfs_steps::match()
  /// in a subclass.  Also the search can be restricted to some set of
  /// states with a proper definition of bfs_steps::filter().
  class SPOT_API bfs_steps
  {
  public:
    bfs_steps(const const_twa_ptr& a);
    virtual ~bfs_steps();

    /// \brief Start the search from \a start, and append the
    /// resulting path (if any) to \a l.
    ///
    /// \return the destination state of the last step (not included
    /// in \a l) if a matching path was found, or 0 otherwise.
    const state* search(const state* start, twa_run::steps& l);

    /// \brief Return a state* that is unique for \a a.
    ///
    /// bfs_steps does not do handle the memory for the states it
    /// generates, this is the job of filter().  Here \a s is a new
    /// state* that search() has just allocated (using
    /// twa_succ_iterator::dst()), and the return of this
    /// function should be a state* that does not need to be freed by
    /// search().
    ///
    /// If you already have a map or a set which uses states as keys,
    /// you should probably arrange for filter() to return these keys,
    /// and destroy \a s.  Otherwise you will have to define such a
    /// set, just to be able to destroy all the state* in a subclass.
    ///
    /// This function can return 0 if the given state should not be
    /// explored.
    virtual const state* filter(const state* s) = 0;

    /// \brief Whether a new transition completes a path.
    ///
    /// This function is called immediately after each call to
    /// filter() that does not return 0.
    ///
    /// \param step the source state (as returned by filter()), and the
    ///             labels of the outgoing transition
    /// \param dest the destination state (as returned by filter())
    /// \return true iff a path that included this step should be accepted.
    ///
    /// The search() algorithms stops as soon as match() returns true,
    /// and when this happens the list argument of search() is be
    /// augmented with the shortest past that ends with this
    /// transition.
    virtual bool match(twa_run::step& step, const state* dest) = 0;

    /// \brief Append the resulting path to the resulting run.
    ///
    /// This is called after match() has returned true, to append the
    /// resulting path to \a l.  This seldom needs to be overridden,
    /// unless you do not want \a l to be updated (in which case an empty
    /// finalize() will do).
    virtual void finalize(const std::map<const state*, twa_run::step,
                                         state_ptr_less_than>& father,
                          const twa_run::step& s,
                          const state* start,
                          twa_run::steps& l);

  protected:
    const_twa_ptr a_;                ///< The spot::tgba we are searching into.
  };
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

namespace ReleaseNotesUtil
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            if (!((args.Length == 4 && args[0] == "getrulesjson")
                  || ((args.Length == 4 || args.Length == 5) && args[0] == "diffrules")))
            {
                PrintUsage();
                return;
            }

            string command = args[0];
            switch (command)
            {
                case "getrulesjson":
                    GetRulesJson(args[1], args[2], args[3]);
                    break;

                case "diffrules":
                    DiffRules(args[1], args[2], args[3], args.Length > 4 ? args[4] : null);
                    break;

                default:
                    throw new ArgumentException($"Unhandled command {command}");
            }
        }

        private static void PrintUsage()
        {
            Console.WriteLine("Usage: ReleaseNoteUtil command commandArgs ...");
            Console.WriteLine("  getrulesjson pathToNugetInstalledPackages netAnalyzersVersion out.json");
            Console.WriteLine("  diffrules old.json new.json out.md");
        }

        private static void GetRulesJson(string nugetInstalledPackagesPath, string version, string outputPath)
        {
            IEnumerable<string> dllPaths = GetNetAnalyzerBinaries(nugetInstalledPackagesPath, version);
            RuleFileContent ruleFileContent = new RuleFileContent
            {
                Rules = GetRules(dllPaths)
            };
            ruleFileContent.Rules.Sort(CategoryThenIdComparer.Instance);
            WriteRuleFileContent(ruleFileContent, outputPath);
        }

        private static void DiffRules(
            string oldRulesJsonPath,
            string newRulesJsonPath,
            string outputPath,
            string? latestRulesJsonPath = null)
        {
            RuleFileContent oldContent = ReadRuleFileContent(oldRulesJsonPath);
            RuleFileContent newContent = ReadRuleFileContent(newRulesJsonPath);

            // If we have the latest rules, we can backfill missing help link URLs.
            if (!string.IsNullOrWhiteSpace(latestRulesJsonPath))
            {
                RuleFileContent latestContent = ReadRuleFileContent(latestRulesJsonPath);
                Dictionary<string, RuleInfo> latestRulesById = latestContent.Rules.Where(r => r.Id != null).ToDictionary(r => r.Id!);
                foreach (RuleInfo rule in oldContent.Rules.Concat(newContent.Rules))
                {
                    if (string.IsNullOrWhiteSpace(rule.HelpLink)
                        && rule.Id != null
                        && latestRulesById.TryGetValue(rule.Id, out RuleInfo? latestRule))
                    {
                        rule.HelpLink = latestRule.HelpLink;
                    }
                }
            }

            Dictionary<string, RuleInfo> oldRulesById = oldContent.Rules.Where(r => r.Id != null).ToDictionary(r => r.Id!);
            Dictionary<string, RuleInfo> newRulesById = newContent.Rules.Where(r => r.Id != null).ToDictionary(r => r.Id!);
            IEnumerable<RuleInfo> addedRules =
                newContent.Rules
                    .Where(r => r.Id != null && !oldRulesById.ContainsKey(r.Id));
            IEnumerable<RuleInfo> removedRules =
                oldContent.Rules
                    .Where(r => r.Id != null && !newRulesById.ContainsKey(r.Id));
            IEnumerable<RuleInfo> changedRules =
                newContent.Rules
                    .Where(r => r.Id != null &&
                                oldRulesById.TryGetValue(r.Id, out RuleInfo? oldRule)
                                && r.IsEnabledByDefault != oldRule.IsEnabledByDefault);
            StringBuilder sb = new StringBuilder();
            GenerateAddRemovedRulesDiffMarkdown(sb, "### Added", addedRules);
            GenerateAddRemovedRulesDiffMarkdown(sb, "### Removed", removedRules);
            GenerateChangedRulesDiffMarkdown(sb, "### Changed", changedRules);
            File.WriteAllText(outputPath, sb.ToString());
        }

        private static void WriteRuleFileContent(RuleFileContent ruleFileContent, string outputPath)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RuleFileContent));
            using FileStream fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None);
            serializer.WriteObject(fs, ruleFileContent);
        }

        private static RuleFileContent ReadRuleFileContent(string path)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RuleFileContent));
            using FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            return (RuleFileContent)serializer.ReadObject(fs);
        }

        private static void GenerateAddRemovedRulesDiffMarkdown(StringBuilder sb, string heading, IEnumerable<RuleInfo> rules)
        {
            if (!rules.Any())
            {
                return;
            }

            IEnumerable<RuleInfo> sortedRules = rules.OrderBy(r => r, CategoryThenIdComparer.Instance);

            sb.AppendLine(heading);
            string? previousCategory = null;
            foreach (RuleInfo rule in sortedRules)
            {
                if (rule.Category != previousCategory)
                {
                    sb.AppendLine($"- {rule.Category}");
                    previousCategory = rule.Category;
                }

                sb.AppendLine($"  - {rule.IdWithHelpLinkMarkdown}: {rule.Title}{(rule.IsEnabledByDefault ? " -- **Enabled by default**" : "")}");
            }
        }

        private static void GenerateChangedRulesDiffMarkdown(StringBuilder sb, string heading, IEnumerable<RuleInfo> rules)
        {
            if (!rules.Any())
            {
                return;
            }

            IEnumerable<RuleInfo> sortedRules = rules.OrderBy(r => r, CategoryThenIdComparer.Instance);

            sb.AppendLine(heading);
            string? previousCategory = null;
            foreach (RuleInfo rule in sortedRules)
            {
                if (rule.Category != previousCategory)
                {
                    sb.AppendLine($"- {rule.Category}");
                    previousCategory = rule.Category;
                }

                sb.AppendLine($"  - {rule.IdWithHelpLinkMarkdown}: {rule.Title} -- {(rule.IsEnabledByDefault ? "Now **enabled by default**" : "Now disabled by default")}");
            }
        }

        private static IEnumerable<string> GetNetAnalyzerBinaries(string nugetInstalledPackagesPath, string version)
        {
            if (!Directory.Exists(nugetInstalledPackagesPath))
            {
                throw new ArgumentException($"'{nugetInstalledPackagesPath}' is not a directory or doesn't exist");
            }

            string[] roslynAnalyzerPackages = new string[] {
                "Microsoft.CodeQuality.Analyzers",
                "Microsoft.NetCore.Analyzers",
                "Microsoft.NetFramework.Analyzers",
                "Text.Analyzers",   // deprecated
                "Microsoft.CodeAnalysis.VersionCheckAnalyzer",
            };
            foreach (string roslynAnalyzerPackage in roslynAnalyzerPackages)
            {
                string packageWithVersion = $"{roslynAnalyzerPackage}.{version}";
                string packageDirectory = Path.Combine(nugetInstalledPackagesPath, packageWithVersion);
                foreach (string dllFile in GetAllAnalyzerBinaries(packageDirectory))
                {
                    yield return dllFile;
                }
            }
        }

        private static readonly string[] LanguageDirectoryNames = new string[] { "cs", "vb" };

        private static IEnumerable<string> GetAllAnalyzerBinaries(string nugetInstalledPackagePath)
        {
            // Assuming analyzers are located in directories as in
            // https://github.com/dotnet/roslyn-analyzers/blob/32d8f1e397439035f0ecb5f61a9e672225f0ecdb/tools/AnalyzerCodeGenerator/template/src/REPLACE.ME/Core/install.ps1
            string analyzersDirectory = Path.Combine(nugetInstalledPackagePath, "analyzers");
            if (!Directory.Exists(analyzersDirectory))
            {
                yield break;
            }

            foreach (string frameworkDirectory in Directory.EnumerateDirectories(analyzersDirectory))
            {
                foreach (string dllFile in Directory.EnumerateFiles(frameworkDirectory, "*.dll"))
                {
                    yield return dllFile;
                }

                foreach (string languageName in LanguageDirectoryNames)
                {
                    string languageDirectory = Path.Combine(frameworkDirectory, languageName);
                    if (Directory.Exists(languageDirectory))
                    {
                        foreach (string languageDllFile in Directory.EnumerateFiles(languageDirectory, "*.dll"))
                        {
                            yield return languageDllFile;
                        }
                    }
                }
            }
        }

        private static List<RuleInfo> GetRules(IEnumerable<string> dllPaths)
        {
            List<RuleInfo> ruleInfos = new List<RuleInfo>();
            foreach (string dllPath in dllPaths)
            {
                AnalyzerFileReference analyzerFileReference = new AnalyzerFileReference(
                    dllPath,
                    AnalyzerAssemblyLoader.Instance);
                ImmutableArray<DiagnosticAnalyzer> analyzers = analyzerFileReference.GetAnalyzersForAllLanguages();
                IEnumerable<DiagnosticDescriptor> descriptors =
                    analyzers
                        .SelectMany(a => a.SupportedDiagnostics)
                        .Distinct(DiagnosticIdComparer.Instance);
                HashSet<string> fixableDiagnosticIds =
                    analyzerFileReference
                        .GetFixers()
                        .SelectMany(fixer => fixer.FixableDiagnosticIds).ToHashSet();
                Console.WriteLine($"{dllPath} has {analyzers.Length} analyzers, {descriptors.Count()} diagnostics, and {fixableDiagnosticIds.Count} fixers");
                foreach (DiagnosticDescriptor descriptor in descriptors)
                {
                    if (ruleInfos.Any(r => r.Id == descriptor.Id))
                    {
                        continue;
                    }

                    ruleInfos.Add(
                        new RuleInfo(
                            descriptor.Id,
                            descriptor.Title.ToString(CultureInfo.InvariantCulture),
                            descriptor.Category,
                            descriptor.IsEnabledByDefault,
                            fixableDiagnosticIds.Contains(descriptor.Id),
                            descriptor.MessageFormat.ToString(CultureInfo.InvariantCulture),
                            descriptor.Description.ToString(CultureInfo.InvariantCulture),
                            descriptor.HelpLinkUri));
                }
            }

            return ruleInfos;
        }

        private static void AnalyzerFileReference_AnalyzerLoadFailed(object sender, AnalyzerLoadFailureEventArgs e)
        {
            Console.WriteLine($"Analyzer load failed: ErrorCode: {e.ErrorCode} Message: {e.Message} Exception:{e.Exception}");
        }
    }
}


text:
import sys
sys.path.append('dependencies/ipyxact')

import argparse
from ipyxact.ipyxact import Component

from mako.lookup import TemplateLookup
from mako.template import Template
from mako.runtime import Context

parser = argparse.ArgumentParser(description='Generate registers')
parser.add_argument('xml_path', metavar='<xml>', type=argparse.FileType('r'), nargs=1,
                    help='path to IP-XACT XML file to be read')
args = parser.parse_args()

component = Component()
component.load(args.xml_path[0].name)
addressBlock = component.memoryMaps.memoryMap[0].addressBlock[0]

lookup = TemplateLookup('templates')
buffer = open('reg_block.svh', 'w')

for reg in addressBlock.register:
    template = lookup.get_template('uvm_reg.mako')
    ctx = Context(buffer, reg=reg)
    template.render_context(ctx)
    buffer.write('\n\n\n\n')

template = lookup.get_template('uvm_reg_block.mako')
ctx = Context(buffer, addressBlock=addressBlock)
template.render_context(ctx)


text:
package com.navercorp.pinpoint.web.vo.install;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.navercorp.pinpoint.common.server.util.json.TypeRef;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Map;

/**
 * @author Taejin Koo
 */
public class AgentInstallationInfoTest {
    private final Logger logger = LogManager.getLogger(this.getClass());

    @Test
    public void testName() throws Exception {
        AgentInstallationInfo agentInstallInfo = new AgentInstallationInfo(new GithubAgentDownloadInfo("1.0.0", "downloadUrl"));

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(agentInstallInfo);
        Map<String, Object> map = objectMapper.readValue(jsonString, TypeRef.map());

        logger.debug(map);

        Assertions.assertTrue(map.containsKey("version"));
        Assertions.assertTrue(map.containsKey("downloadUrl"));
        Assertions.assertTrue(map.containsKey("installationArgument"));
    }

}


text: from .sell import SellAdminModel


text:
package org.apache.spark.sql.sources.v2;

import org.apache.spark.annotation.Evolving;

/**
 * A mix-in interface for {@link TableProvider}. Data sources can implement this interface to
 * propagate session configs with the specified key-prefix to all data source operations in this
 * session.
 */
@Evolving
public interface SessionConfigSupport extends TableProvider {

  /**
   * Key prefix of the session configs to propagate, which is usually the data source name. Spark
   * will extract all session configs that starts with `spark.datasource.$keyPrefix`, turn
   * `spark.datasource.$keyPrefix.xxx -> yyy` into `xxx -> yyy`, and propagate them to all
   * data source operations in this session.
   */
  String keyPrefix();
}


text:
package de.alpharogroup.user.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

import de.alpharogroup.auth.interfaces.Permission;
import de.alpharogroup.db.entity.BaseEntity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * The entity class {@link Permissions} is keeping the information for the permissions of a role or
 * roles.
 */
@Entity
@Table(name = "permissions")
@Getter
@Setter
@NoArgsConstructor
public class Permissions extends BaseEntity<Integer> implements Permission, Cloneable
{

	/** The serial Version UID */
	private static final long serialVersionUID = 1L;
	/** A description for the permission. */
	@Column(name = "description", length = 64)
	private String description;
	/** The name from the permission. */
	@Column(name = "permissionName", length = 64, unique = true)
	private String permissionName;
	/** A shortcut for the permission. */
	@Column(name = "shortcut", length = 10, unique = true)
	private String shortcut;

}


text:
package client

const (
	BasicLoginType              = "basicLogin"
	BasicLoginFieldDescription  = "description"
	BasicLoginFieldPassword     = "password"
	BasicLoginFieldResponseType = "responseType"
	BasicLoginFieldTTLMillis    = "ttl"
	BasicLoginFieldUsername     = "username"
)

type BasicLogin struct {
	Description  string `json:"description,omitempty" yaml:"description,omitempty"`
	Password     string `json:"password,omitempty" yaml:"password,omitempty"`
	ResponseType string `json:"responseType,omitempty" yaml:"responseType,omitempty"`
	TTLMillis    int64  `json:"ttl,omitempty" yaml:"ttl,omitempty"`
	Username     string `json:"username,omitempty" yaml:"username,omitempty"`
}


text:
        Cluster
        <help-field key="pipeline.config.resizeAsg.cluster"></help-field>

        <input type="text" required ng-model="stage.cluster"
          class="form-control input-sm" />

      Account

        <account-select-field component="stage" field="credentials" accounts="accounts" provider="'cf'" on-change="resizeAsgStageCtrl.accountUpdated()" required></account-select-field>

      Regions

(Select an Account)

        <checklist items="regions" model="stage.regions" inline="true" include-select-all-button="true"></checklist>

        Target

        <target-select model="stage" options="resizeTargets"></target-select>

      Action
        <help-field key="pipeline.config.resizeAsg.action"></help-field>

        <select class="form-control input-sm"
                required
                ng-model="stage.action"
                ng-change="resizeAsgStageCtrl.updateResizeType()"
                ng-options="a.val as a.label for a in scaleActions">
          <option>Select an action...</option>
        </select>

        Type
        Additional Capacity

          <select class="form-control input-sm"
                  required
                  ng-model="stage.resizeType"
                  ng-change="resizeAsgStageCtrl.updateResizeType()"
                  ng-options="t.val as t.label for t in resizeTypes">
            <option>Select an action...</option>
          </select>

          Resize Percentage

            <input type="number" min="0" ng-model="stage.scalePct"
                   class="form-control input-sm" />

          This is the percentage by which the target server group's capacity will be increased

          Resize-by Amount

            <input type="number" min="0" ng-model="stage.scaleNum"
                   class="form-control input-sm" />

          This is the exact amount by which the target server group's capacity will be increased

Min

Max

Desired

        Match Capacity

            <input type="number" ng-model="stage.capacity.min"
                   class="form-control input-sm" />

            <input type="number" ng-model="stage.capacity.max"
                   class="form-control input-sm" />

            <input type="number" ng-model="stage.capacity.desired"
                   class="form-control input-sm" />

        This is the exact amount to which the target server group will be scaled


text:
package com.lonelyplanet.openplanet.client.apis

import com.lonelyplanet.openplanet.client.{IncludeParameter, OpenPlanetClient, Slugs}
import spray.json.JsValue

import scala.collection.immutable.Seq

trait OpSlugs extends Slugs {
  val client: OpenPlanetClient

  override def slug(id: String, include: Seq[IncludeParameter] = Seq.empty): JsValue = {
    client.getSingle(s"/slugs/$id", include)
  }
}


text:
void externalDACInit()
{
  GPIO_InitTypeDef GPIO_InitStructure;
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD,ENABLE);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2|GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_6|GPIO_Pin_7;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;   //速度100MHz
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出
  GPIO_Init(GPIOD,&GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(GPIOD,&GPIO_InitStructure);
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.consolefire.data.commando;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author sabuj.das
 */
public class DataCommandoUiContext {
    private static DataCommandoUiContext context;
    private AppSettings appSettings;

    private DataCommandoUiContext() {

    }

    /**
     * @return the context
     */
    public static DataCommandoUiContext getContext() {
        if (null != context) {
            return context;
        }
        synchronized (DataCommandoUiContext.class) {
            context = new DataCommandoUiContext();
        }
        return context;
    }

    public AppSettings getAppSettings() {
        return appSettings;
    }

    public void initContext() {
        File settingsFile = new File(DataCommandoUiConstants.SETTINGS_FILE_NAME);
        if(settingsFile.exists()){
            this.appSettings = readAppSettings(settingsFile);
        } else {
            this.appSettings = AppSettings.DEFAULT_SETTINGS;
        }
        initLogger();
    }

    public void saveContext(){
        writeAppSettings(appSettings);
    }

    private AppSettings readAppSettings(File file){
        AppSettings appSettings = null;
        ObjectInputStream inputStream = null;
        try{
            inputStream = new ObjectInputStream(
                    new FileInputStream(file));
            appSettings = (AppSettings) inputStream.readObject();
        } catch (Exception ex){
            return AppSettings.DEFAULT_SETTINGS;
        } finally {
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException ignore) {
                }
            }
        }
        return appSettings;
    }

    private void writeAppSettings(AppSettings settings){
        File settingsFile = new File(DataCommandoUiConstants.SETTINGS_FILE_NAME);
        File dir = settingsFile.getParentFile();
        if(!dir.exists()){
            dir.mkdirs();
        }
        ObjectOutputStream outputStream = null;
        try{
            outputStream = new ObjectOutputStream(
                    new FileOutputStream(settingsFile));
            outputStream.writeObject(settings);
        } catch (Exception ex){

        } finally {
            if(null != outputStream){
                try {
                    outputStream.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    private void initLogger() {
        Properties log4jProperties = new Properties();
        log4jProperties.setProperty("log4j.rootLogger", appSettings.getLogLevel() + ", APP_LOG");
        log4jProperties.setProperty("log4j.appender.APP_LOG", "org.apache.log4j.RollingFileAppender");
        log4jProperties.setProperty("log4j.appender.APP_LOG.layout", "org.apache.log4j.PatternLayout");
        log4jProperties.setProperty("log4j.appender.APP_LOG.layout.ConversionPattern", appSettings.getLoggerPattern());
        log4jProperties.setProperty("log4j.appender.APP_LOG.file", appSettings.getLogFileName());
        log4jProperties.setProperty("log4j.appender.APP_LOG.MaxFileSize", appSettings.getMaxLogFileSize());
        log4jProperties.setProperty("log4j.appender.APP_LOG.maxBackupIndex", "" + appSettings.getMaxLogFileCount());

        PropertyConfigurator.configure(log4jProperties);
    }

    public void updateSettings(AppSettings appSettings){
        this.appSettings.setLafClassName(appSettings.getLafClassName());
        this.appSettings.setLastAccessedPathName(appSettings.getLastAccessedPathName());
        this.appSettings.setLogFileName(appSettings.getLogFileName());
        this.appSettings.setLogLevel(appSettings.getLogLevel());
        this.appSettings.setLoggerPattern(appSettings.getLoggerPattern());
        this.appSettings.setMaxLogFileCount(appSettings.getMaxLogFileCount());
        this.appSettings.setMaxLogFileSize(appSettings.getMaxLogFileSize());
        initLogger();
    }

    public AppSettings copyAppSettings(){
        AppSettings settings = new AppSettings();
        settings.setLafClassName(this.appSettings.getLafClassName());
        settings.setLastAccessedPathName(this.appSettings.getLastAccessedPathName());
        settings.setLogFileName(this.appSettings.getLogFileName());
        settings.setLogLevel(this.appSettings.getLogLevel());
        settings.setLoggerPattern(this.appSettings.getLoggerPattern());
        settings.setMaxLogFileCount(this.appSettings.getMaxLogFileCount());
        settings.setMaxLogFileSize(this.appSettings.getMaxLogFileSize());

        return settings;
    }
}


text:
University of Washington
------------------------
- Cindy Xin Yi
- Jake Sanders
- Jacob Nelson
- Brandon Holt
- Brandon Myers
- Luis Ceze
- Mark Oskin
- Simon Kahan

Oracle
------
- Hassan Chafi
- Tim Harris


text:
var fs = require("fs");
var path = require("path");

module.exports = function(DB){
  return [
    { path: '/api/exercises', dataCall: DB.Exercises.get, apiMethod: "get" },
    { path: '/api/exercises/:id', dataCall: DB.Exercises.getById, apiMethod: "getByParam", param: "id", errStatus: 404  },

    { path: '/api/correction/pending/:exercise', dataCall: DB.Corrections.getNumPending,
      apiMethod: "getByParam", param: "exercise", errStatus: 404  },
    { path: '/api/correction', dataCall: DB.Corrections.getStatus, apiMethod: "getBySessionUID" },
    { path: '/api/correction/next/:exercise', dataCall: DB.Corrections.lockNextSolutionForTutor,
      apiMethod: "getBySessionUIDAndParam", param: "exercise", errStatus: 404 },
    { path: '/api/correction/pdf/:solution', dataCall: function(solution_id, res){
      return DB.Corrections.getPDFForID(solution_id).then(function(pdf){
        res.setHeader('Content-disposition', 'attachment; filename=' + solution_id + '.pdf');
        res.setHeader('Content-type', 'application/pdf');
        if(pdf && pdf != ""){
          res.send(pdf);
        } else {
          res.send(fs.readFileSync(path.normalize(__dirname + "/../test.pdf")));
        }
      });
    }, apiMethod: "getResByParam", param:"solution" },
    { path: '/api/correction/finalize', dataCall: function(tutor, solutionId){
        return DB.Corrections.checkResults(solutionId).then(function(){
            return DB.Corrections.finishSolution(tutor, solutionId)
          })
      },
      apiMethod: "putBySessionUIDAndParam", param: "solution", errStatus: 400 },
    { path: '/api/correction/unfinished/:exercise', dataCall: DB.Corrections.getUnfinishedSolutionsForTutor,
      apiMethod: "getBySessionUIDAndParam", param: "exercise" },
      { path: '/api/correction/finished/:exercise', dataCall: DB.Corrections.getFinishedSolutionsForTutor,
        apiMethod: "getBySessionUIDAndParam", param: "exercise" },
    { path: '/api/correction/store', dataCall: DB.Corrections.setResultForExercise,
      apiMethod: "putBySessionUIDAndParams", params: ["solution", "results"], errStatus: 404 },

    { path: '/api/tutor', dataCall: DB.Users.getTutor, apiMethod: "getBySessionUID" },

    { path: '/api/solutions/by/user/:user', dataCall: DB.Corrections.getUserSolutions,
      apiMethod: "getByParam", param: "user" },
    { path: '/api/solution/for/user/:user/exercise/:exercise', dataCall: DB.Corrections.getUserExerciseSolution,
        apiMethod: "getByParams", params: ["user","exercise"] },
    { path: '/api/solution/:id', dataCall: DB.Corrections.getSolutionById,
      apiMethod: "getByParam", param: "id", errStatus: 404 },
    { path: '/api/corrections/unfinished', dataCall: DB.Corrections.getUnfinishedSolutionsForTutor,
      apiMethod: "getBySessionUID" }
  ];
};


text:
#include <assert.h>
#include <sstream>
#include <cstdlib>
#include "SearchController.h"
#include "../../benchmark/search/SearchBenchmark.h"

#include "../../generator/UniformGenerator.h"
#include "../../generator/KroneckerGenerator.h"

namespace dgmark {

	GraphGenerator* SearchController::createGenerator()
	{
		Log log(comm);
		#ifdef GENERATOR_TYPE_UNIFORM
		{
			log << "Using uniform gerenator\n";
			return new UniformGenerator(comm);
		}
		#elif GENERATOR_TYPE_KRONECKER
		{
			log << "Using Kronecker gerenator\n";
			return new KroneckerGenerator(comm);
		}
		#else
		{
			log << "\n\nCan't determine graph generator no create\n";
			log << "Generator was not defined in makefile";
			log << " (variable GRAPH_GENERATOR_TYPE)\n\n";
			assert(false);
			return 0;
		}
		#endif
	}

	SearchController::SearchController(Intracomm *comm, int argc, char **argv) :
	Controller(comm, argc, argv)
	{
		generator = createGenerator();
	}

	SearchController::SearchController(const SearchController& orig) :
	Controller(orig)
	{
		generator = createGenerator();
	}

	SearchController::~SearchController()
	{
		delete generator;
	}

	void SearchController::run(vector<Task*> *tasks)
	{
		Graph *graph = generator->generate(grade, density);

		vector<Benchmark*> *benchmarks = new vector<Benchmark*>(0);

		for (vector<Task*>::iterator taskIt = tasks->begin(); taskIt < tasks->end(); ++taskIt) {
			Task *task = *taskIt;
			assert(task->getTaskType() == SEARCH);
			Benchmark* benchmark = new SearchBenchmark(comm, (SearchTask*) task, graph, numStarts);
			benchmarks->push_back(benchmark);
		}

		Controller::run(benchmarks);
		Controller::clean(benchmarks);

		graph->clear();
		delete graph;
	}

	void SearchController::clean(vector<Task*> *tasks)
	{
		for (size_t taskId = 0; taskId < tasks->size(); ++taskId) {
			delete (tasks->at(taskId));
		}
		delete tasks;
	}

	string SearchController::getSpecificStatistics()
	{
		stringstream out;
		out.precision(CONTROLLER_PRECISION);
		out.setf(ios::fixed, ios::floatfield);

		out << "#\n";
		out << "#Duration of processes\n";
		out << "#\n";
		out << "time.graph.generation = " << generator->getGenerationTime() << "\n";
		out << "time.graph.distribution = " << generator->getDistributionTime() << "\n";

		return out.str();
	}

}


text:
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/', ['as' => 'home', function()
{
	return View::make('home');
}]);

Route::get('login', ['as' => 'login', 'uses' => 'SessionsController@create']);
Route::get('logout', ['as' => 'logout', 'uses' => 'SessionsController@destroy']);

Route::resource('sessions', 'SessionsController');


text:
require 'ls-sparkle/shelve_utils'

module LsSparkle
  class Clean
    def initialize(args={})
      @fu=ShelveUtils.new
    end

    def disinfect
      @fu.check_shelves
      @fu.pickup_the_mess
    end

    def white_glove

    end

    def start
      self.disinfect
    end

    def local_methods
      self.methods.sort - Object.methods
    end
  end
end


text:
{% extends "dashboard/base.html" %}
{% load prices_i18n %}
{% load i18n %}
{% load materializecss %}
{% load staticfiles %}
{% load attributes %}

{% block title %}
  {% if product_class.pk %}
    {{ product_class }}
  {% else %}
    {% trans "Add new product type" context "Product class page title" %}
  {% endif %}
  - {% trans "Products" context "Dashboard products list" %} - {{ block.super }}
{% endblock %}

{% block body_class %}body-products{% endblock %}

{% block menu_product_classes_class %}active{% endblock %}

{% block header_menu %}
  {% url "dashboard:product-class-list" as url %}
  {% include "dashboard/includes/_back-link.html" with url=url %}
{% endblock %}

{% block breadcrumbs %}

        {% trans "Product types" context "Dashboard product types list" %}

        <svg data-src="{% static "dashboard/images/arrow_left.svg" %}" fill="#fff" width="20px" height="20px" />

        {% if product_class.pk %}
          {{ product_class }}
        {% else %}
          {% trans 'Add new product type' context "Product class breadcrumbs" %}
        {% endif %}

{% endblock %}

{% block header_extra %}
  {% if product_class.pk %}

      <svg data-src="{% static "dashboard/images/more_vert.svg" %}" height="24" width="24" />

          {% trans "Remove product type" context "Product class action" %}

  {% endif %}
{% endblock %}

{% block content %}

        <form method="post" id="form-product" enctype="multipart/form-data" novalidate>

            {% csrf_token %}

              {{ form.name|materializecss }}

                  {{ form.product_attributes|materializecss:"input-field s12" }}

                  {{ form.variant_attributes|materializecss:"input-field s12" }}

                  {{ form.is_shipping_required|materializecss }}

                  {{ form.has_variants|materializecss }}

            {% if product_class.pk %}

                {% trans "Cancel" context "Dashboard cancel action" %}

              <button type="submit" class="btn waves-effect waves-light">
                {% trans "Update" context "Dashboard update action" %}
              </button>
            {% else %}

                {% trans "Cancel" context "Dashboard cancel action" %}

              <button type="submit" class="btn waves-effect waves-light">
                {% trans "Create" context "Dashboard create action" %}
              </button>
            {% endif %}

        </form>

        <svg data-src="{% static "dashboard/images/help.svg" %}" width="18" height="18" />
        {% blocktrans trimmed context "Product class help text" %}
        Product Type is a template used for creating new products.
        It also controls which attributes can be used during product creation process.
        {% endblocktrans %}

{% endblock %}


text:
module Rack
  module OAuth2
    module Server
      class Token
        class RefreshToken < Abstract::Handler
          def call(env)
            @request  = Request.new(env)
            @response = Response.new(request)
            super
          end

          class Request < Token::Request
            attr_required :refresh_token

            def initialize(env)
              super
              @grant_type    = :refresh_token
              @refresh_token = params['refresh_token']
              attr_missing!
            end
          end
        end
      end
    end
  end
end


text:
readonly ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SH_DIR="${ROOT_DIR}/scripts"
readonly TMP_DIR=/tmp
readonly DEMO_FILENAME="${TMP_DIR}/runner_demo.html"
readonly DEMO_URL="file://${DEMO_FILENAME}"

source "${SH_DIR}/build_tagged_images.sh"
source "${SH_DIR}/containers_up_healthy_and_clean.sh"
source "${SH_DIR}/echo_versioner_env_vars.sh"
export $(echo_versioner_env_vars)

on_Mac() { [ "$(uname)" == "Darwin" ]; }
run_demo() { docker exec -it test_runner_client ruby /runner/source/demo.rb > "${DEMO_FILENAME}"; }

build_tagged_images
server_up_healthy_and_clean
client_up_healthy_and_clean
run_demo
if on_Mac ; then
  open "${DEMO_URL}"
else
  echo "Demo URL is ${DEMO_URL}"
fi


text:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var FB = require('fb');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use(function (req, res, next) {
    res.setHeader("X-Frame-Options", "*");
    return next();
});

app.use('/', routes);
app.get('/fb', function (req, res) {
    FB.api('/me', {
        access_token: req.query.accessToken
    }, function (response) {
        res.json({
            name: response.name,
            pictureURL: 'https://graph.facebook.com/' + response.id + '/picture?type=large'
        });
    });

});

/// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.listen(8080);


text:
{% load contains %}
{% spaceless %}
{% if filtered == "True" and field.value|containedin:matchedValues %}
    {{ field.value }}
{% else %}
    {{ field.value }}
{% endif %}
{% endspaceless %}


text:
namespace v8 {
namespace internal {

inline Intl::Type Intl::TypeFromInt(int type_int) {
  STATIC_ASSERT(Intl::Type::kNumberFormat == 0);
  DCHECK_LE(Intl::Type::kNumberFormat, type_int);
  DCHECK_GT(Intl::Type::kTypeCount, type_int);
  return static_cast<Intl::Type>(type_int);
}

inline Intl::Type Intl::TypeFromSmi(Smi* type) {
  return TypeFromInt(Smi::ToInt(type));
}

}  // namespace internal
}  // namespace v8

#endif  // V8_OBJECTS_INTL_OBJECTS_INL_H_


text:
var path = require("path");
var debug = require("debug")("metalsmith-vextab");
var childProcess = require('child_process');
var phantomPath = require('phantomjs').path;
var execSync = require("execSync");

module.exports = plugin;

function plugin(options) {
    options = options || {};
    options.startDelimiter = options.startDelimiter || "<vextab>";
    options.endDelimiter = options.endDelimiter || "</vextab>";
    options.width = options.width || 600;
    options.logo = !!options.logo;

    return function (files, metalsmith, done) {
        Object.keys(files).forEach(function (file) {
            debug("Converting file: %s", file);
            convert(files[file], options);
        });
        done();
    };
}

var renderJsPath = path.join(__dirname, "render.js");
var renderHtmlPath = path.join(__dirname, "render.html");

function convert(data, options) {
    // Split the string at the start delimiters
    var substrings = data.contents.toString().split(options.startDelimiter);
    if (substrings.length < 2) {
        return;
    }

    for (var i = 1; i < substrings.length; i += 2) {
        // If the start and end delimiters are different,
        // split each substring at the end delimiter.
        if (options.startDelimiter !== options.endDelimiter) {
            var splitEnd = substrings[i].split(options.endDelimiter);
            if (splitEnd.length === 2) {
                substrings[i] = splitEnd[0];
                substrings.splice(i + 1, 0, splitEnd[1]);
            }
            else {
                substrings.splice(i, 0, "");
            }
        }

        var src = substrings[i].trim();
        if (src.length) {
            substrings[i] = execSync.exec(
                phantomPath + " " +
                renderJsPath + " " +
                renderHtmlPath + " " +
                "'" + JSON.stringify(options) + "' " +
                "'" + src.replace("'", "\\'") + "'"
            ).stdout;
        }
    }

    data.contents = new Buffer(substrings.join(""));
}


text:
static INLINE void initHead(table_head *head) {
	memset(head, 0, sizeof(*head));
	head->magicNumber = 0x5f0f3cf5;
	head->unitsPerEm = 1000;
}
static INLINE void disposeHead(table_head *head) {
	// trivial
}
caryll_standardRefType(table_head, table_iHead, initHead, disposeHead);

table_head *otfcc_readHead(const otfcc_Packet packet, const otfcc_Options *options) {
	FOR_TABLE('head', table) {
		font_file_pointer data = table.data;
		uint32_t length = table.length;

		if (length < 54) {
			logWarning("table 'head' corrupted.\n");
		} else {
			table_head *head;
			NEW(head);
			head->version = read_32s(data);
			head->fontRevison = read_32u(data + 4);
			head->checkSumAdjustment = read_32u(data + 8);
			head->magicNumber = read_32u(data + 12);
			head->flags = read_16u(data + 16);
			head->unitsPerEm = read_16u(data + 18);
			head->created = read_64u(data + 20);
			head->modified = read_64u(data + 28);
			head->xMin = read_16u(data + 36);
			head->yMin = read_16u(data + 38);
			head->xMax = read_16u(data + 40);
			head->yMax = read_16u(data + 42);
			head->macStyle = read_16u(data + 44);
			head->lowestRecPPEM = read_16u(data + 46);
			head->fontDirectoryHint = read_16u(data + 48);
			head->indexToLocFormat = read_16u(data + 50);
			head->glyphDataFormat = read_16u(data + 52);
			return head;
		}
	}
	return NULL;
}

static const char *headFlagsLabels[] = {"baselineAtY_0",
                                        "lsbAtX_0",
                                        "instrMayDependOnPointSize",
                                        "alwaysUseIntegerSize",
                                        "instrMayAlterAdvanceWidth",
                                        "designedForVertical",
                                        "_reserved1",
                                        "designedForComplexScript",
                                        "hasMetamorphosisEffects",
                                        "containsStrongRTL",
                                        "containsIndicRearrangement",
                                        "fontIsLossless",
                                        "fontIsConverted",
                                        "optimizedForCleartype",
                                        "lastResortFont"};
static const char *macStyleLabels[] = {"bold", "italic", "underline", "outline", "shadow", "condensed", "extended"};

void otfcc_dumpHead(const table_head *table, json_value *root, const otfcc_Options *options) {
	if (!table) return;
	loggedStep("head") {
		json_value *head = json_object_new(15);
		json_object_push(head, "version", json_double_new(otfcc_from_fixed(table->version)));
		json_object_push(head, "fontRevison", json_double_new(otfcc_from_fixed(table->fontRevison)));
		json_object_push(head, "flags", otfcc_dump_flags(table->flags, headFlagsLabels));
		json_object_push(head, "unitsPerEm", json_integer_new(table->unitsPerEm));
		json_object_push(head, "created", json_integer_new(table->created));
		json_object_push(head, "modified", json_integer_new(table->modified));
		json_object_push(head, "xMin", json_integer_new(table->xMin));
		json_object_push(head, "xMax", json_integer_new(table->xMax));
		json_object_push(head, "yMin", json_integer_new(table->yMin));
		json_object_push(head, "yMax", json_integer_new(table->yMax));
		json_object_push(head, "macStyle", otfcc_dump_flags(table->macStyle, macStyleLabels));
		json_object_push(head, "lowestRecPPEM", json_integer_new(table->lowestRecPPEM));
		json_object_push(head, "fontDirectoryHint", json_integer_new(table->fontDirectoryHint));
		json_object_push(head, "indexToLocFormat", json_integer_new(table->indexToLocFormat));
		json_object_push(head, "glyphDataFormat", json_integer_new(table->glyphDataFormat));
		json_object_push(root, "head", head);
	}
}

table_head *otfcc_parseHead(const json_value *root, const otfcc_Options *options) {
	table_head *head = table_iHead.create();
	json_value *table = NULL;
	if ((table = json_obj_get_type(root, "head", json_object))) {
		loggedStep("head") {
			head->version = otfcc_to_fixed(json_obj_getnum_fallback(table, "version", 0));
			head->fontRevison = otfcc_to_fixed(json_obj_getnum_fallback(table, "fontRevison", 0));
			head->flags = otfcc_parse_flags(json_obj_get(table, "flags"), headFlagsLabels);
			head->unitsPerEm = json_obj_getnum_fallback(table, "unitsPerEm", 0);
			head->created = json_obj_getnum_fallback(table, "created", 0);
			head->modified = json_obj_getnum_fallback(table, "modified", 0);
			head->xMin = json_obj_getnum_fallback(table, "xMin", 0);
			head->xMax = json_obj_getnum_fallback(table, "xMax", 0);
			head->yMin = json_obj_getnum_fallback(table, "yMin", 0);
			head->yMax = json_obj_getnum_fallback(table, "yMax", 0);
			head->macStyle = otfcc_parse_flags(json_obj_get(table, "macStyle"), macStyleLabels);
			head->lowestRecPPEM = json_obj_getnum_fallback(table, "lowestRecPPEM", 0);
			head->fontDirectoryHint = json_obj_getnum_fallback(table, "fontDirectoryHint", 0);
			head->indexToLocFormat = json_obj_getnum_fallback(table, "indexToLocFormat", 0);
			head->glyphDataFormat = json_obj_getnum_fallback(table, "glyphDataFormat", 0);
		}
	}
	return head;
}

caryll_Buffer *otfcc_buildHead(const table_head *head, const otfcc_Options *options) {
	caryll_Buffer *buf = bufnew();
	if (!head) return buf;
	bufwrite32b(buf, head->version);
	bufwrite32b(buf, head->fontRevison);
	bufwrite32b(buf, head->checkSumAdjustment);
	bufwrite32b(buf, head->magicNumber);
	bufwrite16b(buf, head->flags);
	bufwrite16b(buf, head->unitsPerEm);
	bufwrite64b(buf, head->created);
	bufwrite64b(buf, head->modified);
	bufwrite16b(buf, head->xMin);
	bufwrite16b(buf, head->yMin);
	bufwrite16b(buf, head->xMax);
	bufwrite16b(buf, head->yMax);
	bufwrite16b(buf, head->macStyle);
	bufwrite16b(buf, head->lowestRecPPEM);
	bufwrite16b(buf, head->fontDirectoryHint);
	bufwrite16b(buf, head->indexToLocFormat);
	bufwrite16b(buf, head->glyphDataFormat);
	return buf;
}


text:
import angr
import claripy

FIND_ADDR = 0x0804849F
AVOID_ADDR = 0x080484A9
proj = angr.Project('args', load_options={'auto_load_libs':False})
arg1 = claripy.BVS('arg1', 10*8)
state = proj.factory.full_init_state(args=['./args', arg1])
path_group = proj.factory.path_group(state)
# Step until the explorer finds one of the addresses we are looking for or all paths are deadended
path_group.explore(find=FIND_ADDR, avoid=AVOID_ADDR)

solution_path = path_group.found[0]
solution_state = solution_path.state

print solution_state.se.any_str(arg1).rstrip(chr(0))
# Prints: +42*2¦¦3¦0
# Let's test:
# >> ./args +42*2
# >> echo $?
# 1


text:
Detect palindrome products in a given range.

A palindromic number is a number that remains the same when its digits are
reversed. For example, `121` is a palindromic number but `112` is not.

Given a range of numbers, find the largest and smallest palindromes which
are products of numbers within that range.

Your solution should return the largest and smallest palindromes, along with the
factors of each within the range. If the largest or smallest palindrome has more
than one pair of factors within the range, then return all the pairs.

## Example 1

Given the range `[1, 9]` (both inclusive)...

And given the list of all possible products within this range:
`[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 15, 21, 24, 27, 20, 28, 32, 36, 25, 30, 35, 40, 45, 42, 48, 54, 49, 56, 63, 64, 72, 81]`

The palindrome products are all single digit numbers (in this case):
`[1, 2, 3, 4, 5, 6, 7, 8, 9]`

The smallest palindrome product is `1`. Its factors are `(1, 1)`.
The largest palindrome product is `9`. Its factors are `(1, 9)` and `(3, 3)`.

## Example 2

Given the range `[10, 99]` (both inclusive)...

The smallest palindrome product is `121`. Its factors are `(11, 11)`.
The largest palindrome product is `9009`. Its factors are `(91, 99)`.

## Setup

Go through the project setup instructions for Xcode using Swift:

http://exercism.io/languages/swift
http://exercism.io/languages/swift/tests

Notably from the source directory:

`swift test` runs tests
`swift package generate-xcodeproj` creates an Xcode project

## Source

Problem 4 at Project Euler [http://projecteuler.net/problem=4](http://projecteuler.net/problem=4)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
package org.apache.reef.wake.impl;

import org.apache.reef.tang.annotations.Parameter;
import org.apache.reef.wake.AbstractEStage;
import org.apache.reef.wake.EventHandler;
import org.apache.reef.wake.StageConfiguration.Capacity;
import org.apache.reef.wake.StageConfiguration.StageHandler;
import org.apache.reef.wake.StageConfiguration.StageName;

import javax.inject.Inject;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Single thread stage that runs the event handler.
 *
 * @param <T> type
 */
public final class SingleThreadStage<T> extends AbstractEStage<T> {
  private static final Logger LOG = Logger.getLogger(SingleThreadStage.class.getName());

  private final BlockingQueue<T> queue;
  private final Thread thread;
  private final AtomicBoolean interrupted;

  /**
   * Constructs a single thread stage.
   *
   * @param handler  the event handler to execute
   * @param capacity the queue capacity
   */
  @Inject
  public SingleThreadStage(@Parameter(StageHandler.class) final EventHandler<T> handler,
                           @Parameter(Capacity.class) final int capacity) {
    this(handler.getClass().getName(), handler, capacity);
  }

  /**
   * Constructs a single thread stage.
   *
   * @param name     the stage name
   * @param handler  the event handler to execute
   * @param capacity the queue capacity
   */
  @Inject
  public SingleThreadStage(@Parameter(StageName.class) final String name,
                           @Parameter(StageHandler.class) final EventHandler<T> handler,
                           @Parameter(Capacity.class) final int capacity) {
    super(name);
    queue = new ArrayBlockingQueue<T>(capacity);
    interrupted = new AtomicBoolean(false);
    thread = new Thread(new Producer<T>(name, queue, handler, interrupted));
    thread.setName("SingleThreadStage<" + name + ">");
    thread.start();
    StageManager.instance().register(this);
  }

  /**
   * Puts the value to the queue, which will be processed by the handler later.
   * if the queue is full, IllegalStateException is thrown
   *
   * @param value the value
   * @throws IllegalStateException
   */
  @Override
  public void onNext(final T value) {
    beforeOnNext();
    queue.add(value);
  }

  /**
   * Closes the stage.
   *
   * @throws Exception
   */
  @Override
  public void close() throws Exception {
    if (closed.compareAndSet(false, true)) {
      interrupted.set(true);
      thread.interrupt();
    }
  }

  /**
   * Takes events from the queue and provides them to the handler.
   */
  private class Producer<U> implements Runnable {

    private final String name;
    private final BlockingQueue<U> queue;
    private final EventHandler<U> handler;
    private final AtomicBoolean interrupted;

    Producer(final String name, final BlockingQueue<U> queue, final EventHandler<U> handler,
             final AtomicBoolean interrupted) {
      this.name = name;
      this.queue = queue;
      this.handler = handler;
      this.interrupted = interrupted;
    }

    @Override
    public void run() {
      while (true) {
        try {
          final U value = queue.take();
          handler.onNext(value);
          SingleThreadStage.this.afterOnNext();
        } catch (final InterruptedException e) {
          if (interrupted.get()) {
            LOG.log(Level.FINEST, name + " Closing Producer due to interruption");
            break;
          }
        } catch (final Throwable t) {
          LOG.log(Level.SEVERE, name + " Exception from event handler", t);
          throw t;
        }
      }
    }
  }

}


text:
import logging
import socket
import sys
import time

from twitter.common.log.formatters.base import format_message

class GlogFormatter(logging.Formatter):
  """
    Format a log in Google style format:
    [DIWEF]mmdd hh:mm:ss.uuuuuu pid file:line] msg
  """
  SCHEME = 'google'
  LOG_LINE_FORMAT = "[DIWEF]mmdd hh:mm:ss.uuuuuu pid file:line] msg"

  LEVEL_MAP = {
    logging.FATAL: 'F',
    logging.ERROR: 'E',
    logging.WARN:  'W',
    logging.INFO:  'I',
    logging.DEBUG: 'D'
  }

  @classmethod
  def logfile_preamble(cls):
    return ''.join('%s\n' % line for line in [
      'Log file created at: %s' % time.strftime('%Y/%m/%d %H:%M:%S', time.localtime()),
      'Running on machine: %s' % socket.gethostname(),
      cls.LOG_LINE_FORMAT,
      'Command line: %s' % ' '.join(sys.argv)])

  def __init__(self):
    logging.Formatter.__init__(self)

  def format(self, record):
    try:
      level = GlogFormatter.LEVEL_MAP[record.levelno]
    except:
      level = '?'
    date = time.localtime(record.created)
    date_usec = (record.created - int(record.created)) * 1e6
    record_message = '%c%02d%02d %02d:%02d:%02d.%06d %s %s:%d] %s' % (
       level, date.tm_mon, date.tm_mday, date.tm_hour, date.tm_min, date.tm_sec, date_usec,
       record.process if record.process is not None else '?????',
       record.filename,
       record.lineno,
       format_message(record))
    record.getMessage = lambda: record_message
    return logging.Formatter.format(self, record)


text:
function Controller() {
    function downloadEntry() {
        var net = require("net");
        net.apiCall(Alloy.Globals.gateway + "glibrary/links2/" + Alloy.Globals.repository + "/" + id + "/", function(response) {
            var replicaWindow = Alloy.createController("replicaWindow", response).getView();
            replicaWindow.title = metadata.FileName;
            replicaWindow.open();
        });
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "entryDetailWindow";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    var __defers = {};
    $.__views.entryDetailWindow = Ti.UI.createWindow({
        backgroundColor: "white",
        id: "entryDetailWindow"
    });
    $.__views.entryDetailWindow && $.addTopLevelView($.__views.entryDetailWindow);
    $.__views.thumb = Ti.UI.createImageView({
        top: 5,
        height: 120,
        id: "thumb"
    });
    $.__views.details = Ti.UI.createTableView({
        style: Titanium.UI.iPhone.TableViewStyle.GROUPED,
        headerView: $.__views.thumb,
        id: "details"
    });
    $.__views.entryDetailWindow.add($.__views.details);
    exports.destroy = function() {};
    _.extend($, $.__views);
    var metadata = arguments[0].metadata;
    var id = arguments[0].id;
    $.thumb.image = Ti.Utils.base64decode(metadata["/" + Alloy.Globals.repository + "/Thumbs:Data"]);
    for (var i in metadata) if (0 != i.indexOf("/")) {
        var row = Ti.UI.createTableViewRow({
            minRowHeight: 40
        });
        row.add(Ti.UI.createLabel({
            text: i,
            left: 5,
            height: 40,
            font: {
                fontWeight: "bold",
                fontSize: "12"
            }
        }));
        metadata[i] && row.add(Ti.UI.createLabel({
            text: metadata[i],
            right: 5,
            left: 130,
            height: Ti.UI.SIZE,
            font: {
                fontSize: "12"
            }
        }));
        $.details.appendRow(row);
    }
    $.entryDetailWindow.addEventListener("open", function() {
        var actionBar;
        if ($.entryDetailWindow.activity) {
            actionBar = $.entryDetailWindow.activity.actionBar;
            if (actionBar) {
                actionBar.displayHomeAsUp = true;
                actionBar.onHomeIconItemSelected = function() {
                    $.entryDetailWindow.close();
                };
                $.entryDetailWindow.getActivity().onCreateOptionsMenu = function(e) {
                    var filtersBtn = e.menu.add({
                        title: "Download",
                        showAsAction: Ti.Android.SHOW_AS_ACTION_ALWAYS,
                        icon: "/cloud_download.png"
                    });
                    filtersBtn.addEventListener("click", function() {
                        downloadEntry();
                    });
                };
                $.entryDetailWindow.getActivity().invalidateOptionsMenu();
            }
        } else Ti.API.error("Can't access action bar on a lightweight window.");
    });
    __defers["$.__views.downloadEntry!click!downloadEntry"] && $.__views.downloadEntry.addEventListener("click", downloadEntry);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
default_target: all
.PHONY : default_target

#=============================================================================
# Special targets provided by cmake.

# Disable implicit rules so canonical targets will work.
.SUFFIXES:

# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =

.SUFFIXES: .hpux_make_needs_suffix_list

# Suppress display of executed commands.
$(VERBOSE).SILENT:

# A target that is always out of date.
cmake_force:
.PHONY : cmake_force

#=============================================================================
# Set environment variables for the build.

# The shell in which to execute make rules.
SHELL = /bin/sh

# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake

# The command to remove a file.
RM = /usr/bin/cmake -E remove -f

# Escaping for special characters.
EQUALS = =

# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/pi/206/workspace/test/openp2p

# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/pi/206/workspace/test/openp2p/build

#=============================================================================
# Targets provided globally by CMake.

# Special rule for the target edit_cache
edit_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..."
	/usr/bin/cmake -i .
.PHONY : edit_cache

# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast

# Special rule for the target rebuild_cache
rebuild_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
	/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache

# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast

# Special rule for the target test
test:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..."
	/usr/bin/ctest --force-new-ctest-process $(ARGS)
.PHONY : test

# Special rule for the target test
test/fast: test
.PHONY : test/fast

# The main all target
all: cmake_check_build_system
	cd /home/pi/206/workspace/test/openp2p/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/pi/206/workspace/test/openp2p/build/CMakeFiles /home/pi/206/workspace/test/openp2p/build/src/OpenP2P/Buffer/CMakeFiles/progress.marks
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f CMakeFiles/Makefile2 src/OpenP2P/Buffer/all
	$(CMAKE_COMMAND) -E cmake_progress_start /home/pi/206/workspace/test/openp2p/build/CMakeFiles 0
.PHONY : all

# The main clean target
clean:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f CMakeFiles/Makefile2 src/OpenP2P/Buffer/clean
.PHONY : clean

# The main clean target
clean/fast: clean
.PHONY : clean/fast

# Prepare targets for installation.
preinstall: all
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f CMakeFiles/Makefile2 src/OpenP2P/Buffer/preinstall
.PHONY : preinstall

# Prepare targets for installation.
preinstall/fast:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f CMakeFiles/Makefile2 src/OpenP2P/Buffer/preinstall
.PHONY : preinstall/fast

# clear depends
depend:
	cd /home/pi/206/workspace/test/openp2p/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend

# Convenience name for target.
src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/rule:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f CMakeFiles/Makefile2 src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/rule
.PHONY : src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/rule

# Convenience name for target.
openp2p-buffer: src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/rule
.PHONY : openp2p-buffer

# fast build rule for target.
openp2p-buffer/fast:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build
.PHONY : openp2p-buffer/fast

Buffer.o: Buffer.cpp.o
.PHONY : Buffer.o

# target to build an object file
Buffer.cpp.o:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/Buffer.cpp.o
.PHONY : Buffer.cpp.o

Buffer.i: Buffer.cpp.i
.PHONY : Buffer.i

# target to preprocess a source file
Buffer.cpp.i:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/Buffer.cpp.i
.PHONY : Buffer.cpp.i

Buffer.s: Buffer.cpp.s
.PHONY : Buffer.s

# target to generate assembly for a file
Buffer.cpp.s:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/Buffer.cpp.s
.PHONY : Buffer.cpp.s

BufferBuilder.o: BufferBuilder.cpp.o
.PHONY : BufferBuilder.o

# target to build an object file
BufferBuilder.cpp.o:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/BufferBuilder.cpp.o
.PHONY : BufferBuilder.cpp.o

BufferBuilder.i: BufferBuilder.cpp.i
.PHONY : BufferBuilder.i

# target to preprocess a source file
BufferBuilder.cpp.i:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/BufferBuilder.cpp.i
.PHONY : BufferBuilder.cpp.i

BufferBuilder.s: BufferBuilder.cpp.s
.PHONY : BufferBuilder.s

# target to generate assembly for a file
BufferBuilder.cpp.s:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/BufferBuilder.cpp.s
.PHONY : BufferBuilder.cpp.s

BufferIterator.o: BufferIterator.cpp.o
.PHONY : BufferIterator.o

# target to build an object file
BufferIterator.cpp.o:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/BufferIterator.cpp.o
.PHONY : BufferIterator.cpp.o

BufferIterator.i: BufferIterator.cpp.i
.PHONY : BufferIterator.i

# target to preprocess a source file
BufferIterator.cpp.i:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/BufferIterator.cpp.i
.PHONY : BufferIterator.cpp.i

BufferIterator.s: BufferIterator.cpp.s
.PHONY : BufferIterator.s

# target to generate assembly for a file
BufferIterator.cpp.s:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/BufferIterator.cpp.s
.PHONY : BufferIterator.cpp.s

BufferedStream.o: BufferedStream.cpp.o
.PHONY : BufferedStream.o

# target to build an object file
BufferedStream.cpp.o:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/BufferedStream.cpp.o
.PHONY : BufferedStream.cpp.o

BufferedStream.i: BufferedStream.cpp.i
.PHONY : BufferedStream.i

# target to preprocess a source file
BufferedStream.cpp.i:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/BufferedStream.cpp.i
.PHONY : BufferedStream.cpp.i

BufferedStream.s: BufferedStream.cpp.s
.PHONY : BufferedStream.s

# target to generate assembly for a file
BufferedStream.cpp.s:
	cd /home/pi/206/workspace/test/openp2p/build && $(MAKE) -f src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/build.make src/OpenP2P/Buffer/CMakeFiles/openp2p-buffer.dir/BufferedStream.cpp.s
.PHONY : BufferedStream.cpp.s

# Help Target
help:
	@echo "The following are some of the valid targets for this Makefile:"
	@echo "... all (the default if no target is provided)"
	@echo "... clean"
	@echo "... depend"
	@echo "... edit_cache"
	@echo "... openp2p-buffer"
	@echo "... rebuild_cache"
	@echo "... test"
	@echo "... Buffer.o"
	@echo "... Buffer.i"
	@echo "... Buffer.s"
	@echo "... BufferBuilder.o"
	@echo "... BufferBuilder.i"
	@echo "... BufferBuilder.s"
	@echo "... BufferIterator.o"
	@echo "... BufferIterator.i"
	@echo "... BufferIterator.s"
	@echo "... BufferedStream.o"
	@echo "... BufferedStream.i"
	@echo "... BufferedStream.s"
.PHONY : help

#=============================================================================
# Special targets to cleanup operation of make.

# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
	cd /home/pi/206/workspace/test/openp2p/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system


text:
package com.google.code.ant.growlnotify;

import java.io.IOException;
import java.util.ArrayList;

class Growl
{

    public void sendNotification (GrowlNotification notification) throws GrowlException
    {
        ArrayList args = new ArrayList();
        args.add("growlnotify");
        args.add("-m");
        args.add(notification.msg);
        args.add("-n");
        args.add(notification.appName);
        args.add("-t");
        args.add(notification.title);
        if (notification.sticky)
        {
            args.add("-s");
        }

        if (notification.img != null)
        {
            args.add("--image");
            args.add(notification.img);
        }

        try
        {
            Process exec = Runtime.getRuntime().exec((String[]) args.toArray(new String[] {}));
        }
        catch (IOException e)
        {
            throw new GrowlException(e);
        }
    }
}

// add images
// add filter list


text:
/*	$NetBSD: c-stack.c,v 1.1.1.1 2003/01/26 00:43:15 wiz Exp $	*/

/* Stack overflow handling.

   Copyright (C) 2002 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

/* Written by Paul Eggert.  */

/* This module assumes that each stack frame is smaller than a page.
   If you use alloca, dynamic arrays, or large local variables, your
   program may extend the stack by more than a page at a time.  If so,
   the code below may incorrectly report a program error, or worse
   yet, may not detect the overflow at all.  To avoid this problem,
   don't use large local arrays.  */

#if HAVE_CONFIG_H
# include <config.h>
#endif

#include "gettext.h"
#define _(msgid) gettext (msgid)

#include <errno.h>
#ifndef ENOTSUP
# define ENOTSUP EINVAL
#endif

#if HAVE_INTTYPES_H
# include <inttypes.h>
#else
# if HAVE_STDINT_H
#  include <stdint.h>
# endif
#endif

#include <signal.h>
#include <stdlib.h>
#include <string.h>

#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif

#include "c-stack.h"
#include "exitfail.h"

extern char *program_name;

#if HAVE_XSI_STACK_OVERFLOW_HEURISTIC

# include <ucontext.h>

/* Storage for the alternate signal stack.  */
static union
{
  char buffer[SIGSTKSZ];

  /* These other members are for proper alignment.  There's no
     standard way to guarantee stack alignment, but this seems enough
     in practice.  */
  long double ld;
  uintmax_t u;
  void *p;
} alternate_signal_stack;

/* Direction of the C runtime stack.  This function is
   async-signal-safe.  */

# if STACK_DIRECTION
#  define find_stack_direction(ptr) STACK_DIRECTION
# else
static int
find_stack_direction (char const *addr)
{
  char dummy;
  return ! addr ? find_stack_direction (&dummy) : addr < &dummy ? 1 : -1;
}
# endif

/* The SIGSEGV handler.  */
static void (* volatile segv_action) (int, siginfo_t *, void *);

/* Handle a segmentation violation and exit.  This function is
   async-signal-safe.  */

static void
segv_handler (int signo, siginfo_t *info, void *context)
{
  /* Clear SIGNO if it seems to have been a stack overflow.  */
  if (0 < info->si_code)
    {
      /* If the faulting address is within the stack, or within one
	 page of the stack end, assume that it is a stack
	 overflow.  */
      ucontext_t const *user_context = context;
      char const *stack_min = user_context->uc_stack.ss_sp;
      size_t stack_size = user_context->uc_stack.ss_size;
      char const *faulting_address = info->si_addr;
      size_t s = faulting_address - stack_min;
      size_t page_size = sysconf (_SC_PAGESIZE);
      if (find_stack_direction (0) < 0)
	s += page_size;
      if (s < stack_size + page_size)
	signo = 0;
    }

  segv_action (signo, info, context);
}

#endif /* HAVE_XSI_STACK_OVERFLOW_HEURISTIC */

/* Translated messages for program errors and stack overflow.  Do not
   translate them in the signal handler, since gettext is not
   async-signal-safe.  */
static char const * volatile program_error_message;
static char const * volatile stack_overflow_message;

/* Output an error message, then exit with status EXIT_FAILURE if it
   appears to have been a stack overflow, or with a core dump
   otherwise.  This function is async-signal-safe.  */

void
c_stack_die (int signo, siginfo_t *info, void *context)
{
  char const *message =
    signo ? program_error_message : stack_overflow_message;
  write (STDERR_FILENO, program_name, strlen (program_name));
  write (STDERR_FILENO, ": ", 2);
  write (STDERR_FILENO, message, strlen (message));
  write (STDERR_FILENO, "\n", 1);
  if (! signo)
    _exit (exit_failure);
#if HAVE_SIGINFO_T
  if (context && info && 0 <= info->si_code)
    {
      /* Re-raise the exception at the same address.  */
      char *addr = info->si_addr;
      *addr = 0;
    }
#endif
  kill (getpid (), signo);
}

/* Set up ACTION so that it is invoked on C stack overflow.  Return -1
   (setting errno) if this cannot be done.

   ACTION must invoke only async-signal-safe functions.  ACTION
   together with its callees must not require more than SIGSTKSZ bytes
   of stack space.  */

int
c_stack_action (void (*action) (int, siginfo_t *, void *))
{
#if ! HAVE_XSI_STACK_OVERFLOW_HEURISTIC
  errno = ENOTSUP;
  return -1;
#else
  struct sigaction act;
  stack_t st;
  int r;

  st.ss_flags = 0;
  st.ss_sp = alternate_signal_stack.buffer;
  st.ss_size = sizeof alternate_signal_stack.buffer;
  r = sigaltstack (&st, 0);
  if (r != 0)
    return r;

  program_error_message = _("program error");
  stack_overflow_message = _("stack overflow");
  segv_action = action;

  sigemptyset (&act.sa_mask);

  /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER, but this
     is not true on Solaris 8 at least.  It doesn't hurt to use
     SA_NODEFER here, so leave it in.  */
  act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;

  act.sa_sigaction = segv_handler;
  return sigaction (SIGSEGV, &act, 0);
#endif
}

#if DEBUG

#include <stdio.h>

int volatile exit_failure;

static long
recurse (char *p)
{
  char array[500];
  array[0] = 1;
  return *p + recurse (array);
}

char *program_name;

int
main (int argc, char **argv)
{
  program_name = argv[0];
  c_stack_action (c_stack_die);
  return recurse ("\1");
}

#endif /* DEBUG */

/*
Local Variables:
compile-command: "gcc -D_GNU_SOURCE -DDEBUG \
  -DHAVE_INTTYPES_H -DHAVE_SIGINFO_T \
  -DHAVE_XSI_STACK_OVERFLOW_HEURISTIC -DHAVE_UNISTD_H \
  -Wall -W -g c-stack.c -o c-stack"
End:
*/


text:
<?php

namespace Respect\Validation\Rules\SubdivisionCode;

use Respect\Validation\Rules\AbstractSearcher;

/**
 * Validator for Swaziland subdivision code.
 *
 * ISO 3166-1 alpha-2: SZ
 *
 * @link http://www.geonames.org/SZ/administrative-division-swaziland.html
 */
class SzSubdivisionCode extends AbstractSearcher
{
    public $haystack = [
        'HH', // Hhohho
        'LU', // Lubombo
        'MA', // Manzini
        'SH', // Shishelweni
    ];

    public $compareIdentical = true;
}


text:
/* Generated By:JJTree: Do not edit this line. ASTFilename.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
public
class ASTFilename extends SimpleNode {
  public ASTFilename(int id) {
    super(id);
  }

  public ASTFilename(acmeParser p, int id) {
    super(p, id);
  }

}
/* JavaCC - OriginalChecksum=81f7178b76699aa0eee6856c045ecb44 (do not edit this line) */


text:
<!DOCTYPE html>

    <meta content="text/html; charset=utf-8" http-equiv="content-type">
    <title>Ximnasio dos Verbos</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <link rel="stylesheet" href="assets/css/main.css">

         Menú

Comezo

Procurar

            Alternancia vocalica

            Verbos irregulares

Trucos

            Alternancia vocalica

            Verbos irregulares

Adestramento

            Alternancia vocalica

            Verbos irregulares

Xogos

            Alternancia vocálica

            Verbos irregulares

Créditos

O proxecto

Quen somos?

Xogos

Xa estás na última fase. Non che queda case nada para te
              converteres nun Jedi do verbo. Os teus abdominais verbais xa
              se están a marcar e axiña poderás retrucar como un/ha regueifeirx
              con anos de experiencia.

              Estás a piques de entrar no nivel Sés.

Escolle unha opción:

Alternancia
                    vocálica

Verbos irregulares