text:
from django.contrib import admin
from imagekit.admin import AdminThumbnail

from .models import CrimeType, Claim, ClaimState

class CrimeTypeAdmin(admin.ModelAdmin):
    list_display = ("name", "enabled")
    ordering = ('-enabled',)

    def has_delete_permission(self, request, obj=None):
        return False

class MediaInline(admin.TabularInline):
    model = Claim.media.through
    raw_id_fields = ('mediafilemodel',)
    readonly_fields = ('admin_thumbnail',)
    admin_thumbnail = AdminThumbnail(image_field=lambda obj: obj.mediafilemodel.thumbnail)

class ClaimStateInline(admin.TabularInline):
    model = ClaimState
    readonly_fields = ('logged_at',)

class ClaimAdmin(admin.ModelAdmin):
    list_display = ('pk', 'user', 'city', 'created_at', 'status')
    inlines = [MediaInline, ClaimStateInline]
    exclude = ('media',)
    raw_id_fields = ('user',)
    readonly_fields = ('created_at', 'modified_at', 'authorized_at')
    list_filter = ('status', 'crimetypes')
    search_fields = ('id', 'license_plates', 'city', 'address', 'user__email', 'user__last_name')

admin.site.register(CrimeType, CrimeTypeAdmin)
admin.site.register(Claim, ClaimAdmin)


text:
// ================================================================================
// ==      This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås      ==
// ==                     See tb_core.h for more information.                    ==
// ================================================================================

#ifndef TB_PARSER_H
#define TB_PARSER_H

#include "../tb_value.h"
#include "../tb_tempbuffer.h"
#include "../tb_str.h"

namespace tb {

/** Unescape backslash codes. This is done in place using the string both as source
    and destination. */
void UnescapeString(char *str);

/** Check if buf is pointing at a end quote. It may need to iterate
    buf backwards toward buf_start to check if any preceding backslashes
    make it a escaped quote (which should not be the end quote) */
bool IsEndQuote(const char *buf_start, const char *buf, const char quote_type);

class TBParserTarget
{
public:
    virtual ~TBParserTarget() {}
    virtual void OnError(int line_nr, const char *error) = 0;
    virtual void OnComment(int line_nr, const char *comment) = 0;
    virtual void OnToken(int line_nr, const char *name, TBValue &value) = 0;
    virtual void Enter() = 0;
    virtual void Leave() = 0;
};

class TBParserStream
{
public:
    virtual ~TBParserStream() {}
    virtual int GetMoreData(char *buf, int buf_len) = 0;
};

class TBParser
{
public:
    enum STATUS {
        STATUS_OK,
        STATUS_OUT_OF_MEMORY,
        STATUS_PARSE_ERROR
    };
    TBParser() {}
    STATUS Read(TBParserStream *stream, TBParserTarget *target);
private:
    int current_indent;
    int current_line_nr;
    TBStr multi_line_token;
    TBTempBuffer multi_line_value;
    int multi_line_sub_level;
    bool pending_multiline;
    void OnLine(char *line, TBParserTarget *target);
    void OnCompactLine(char *line, TBParserTarget *target);
    void OnMultiline(char *line, TBParserTarget *target);
    void ConsumeValue(TBValue &dst_value, char *&line);
};

}; // namespace tb

#endif // TB_PARSER_H

redpajama_set_name: RedPajamaGithub


text:
package com.esri.mapred;

import com.esri.hadoop.quadtree.PointData;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;

import java.io.IOException;

/**
 */
public class QuadTreeInputFormat
        extends FileInputFormat<LongWritable, PointData>
{
    @Override
    protected boolean isSplitable(
            final FileSystem fs,
            final Path path)
    {
        return false;
    }

    @Override
    public RecordReader<LongWritable, PointData> getRecordReader(
            final InputSplit inputSplit,
            final JobConf jobConf,
            final Reporter reporter) throws IOException
    {
        return new QuadTreeRecordReader(inputSplit, jobConf);
    }
}


text:
import sys

class Term():
	def __init__(self, coefficient, power, next=None):
		self.coefficient = coefficient
		self.power = power
		self.next = next

	def eval(self, x):
		"""
		Evaulate monomial at given value of x
		"""
		if self.power is 0:
			return self.coefficient
		return (self.coefficient) * (x ** self.power)

	def __str__(self):
		"""
		Return string representation of monomial
		"""
		monomial = ''
		if self.coefficient == 0:
			return monomial

		sign = '+' if self.coefficient >= 0 else '-'
		monomial += ' {0} '.format(sign)

		if abs(self.coefficient) > 1:
			monomial += str(abs(self.coefficient))

		if self.power > 1:
			monomial += 'x^{0}'.format(abs(self.power))
		elif self.power == 1:
			monomial += 'x'

		return monomial

class Polynomial():
	def __init__(self, head=None, copy=None):
		self.head = head
		self.size = 0

		if copy:
			node = copy.head
			while node:
				self.insert(node.coefficient, node.power)
				node = node.next

	def eval(self, x):
		val = 0
		node = self.head
		for i in range(0, self.size):
			val += node.eval(x)
			node = node.next
		return val

	def insert(self, coefficient, power):
		"""
		Inserts terms in descending order by power
		and adds coeffecients for duplicate powers
		"""
		node = self.head
		term = Term(coefficient, power)

		if not node:
			self.head = term
			self.size += 1
		elif term.power > node.power:
			term.next = self.head
			self.head = term
			self.size += 1
		else:
			while node.next and term.power <= node.next.power:
				node = node.next
			if term.power == node.power:
				node.coefficient += term.coefficient
			else:
				term.next = node.next
				node.next = term
				self.size += 1

	def __add__(self, other):
		"""
		Add two polynomials together
		p1 + p2
		"""
		new = Polynomial(copy=self)
		node = other.head
		while node is not None:
			new.insert(node.coefficient, node.power)
			node = node.next
		return new

	def __sub__(self, other):
		"""
		Subtract one polynomial from another
		p1 - p2
		"""
		new = Polynomial(copy=self)
		node = other.head
		while node is not None:
			new.insert(-1 * node.coefficient, node.power)
			node = node.next
		return new

	def __mul__(self, other):
		"""
		Multiply one polynomial by another
		p1 * p2
		"""
		new = Polynomial()
		n1 = self.head
		while n1:
			n2 = other.head
			while n2:
				new.insert(n1.coefficient * n2.coefficient, n1.power + n2.power)
				n2 = n2.next
			n1 = n1.next
		return new

	def __pow__(self, power):
		"""
		Raise a polynomial to a power
		p1 ** 2
		"""
		if power == 0:
			new = Polynomial()
			new.insert(1, 0)
			return new
		elif power < 0:
			return 'Power cannot be negative'
		else:
			new = Polynomial(copy=self)
			for i in range(0, power - 1):
				new = new * self
			return new

	def __str__(self):
		node = self.head
		if node is None:
			return '[]'
		expression = ''
		for i in range(0, self.size):
			expression += str(node)
			node = node.next
		expression = expression[3:]
		if self.head.coefficient < 0:
			expression = '-{0}'.format(expression)
		return expression

def create_polynomial(line):
	polynomial = Polynomial()
	nums = line.split(' ')
	for i in range(0, len(nums), 2):
		polynomial.insert(int(nums[i]), int(nums[i + 1]))
	return polynomial

def heading(text):
	print text
	print '-'* len(text)

def output(text, equation):
	heading(text)
	print equation
	print 'x = {0}, {1}'.format(1, equation.eval(1))
	print 'x = {0}, {1}'.format(2, equation.eval(2))
	print 'x = {0}, {1}'.format(3, equation.eval(3))
	print 'x = {0}, {1}'.format(10, equation.eval(10))
	print

if __name__ == '__main__':
	if len(sys.argv) == 1:
		print 'Please specify an input file'
		sys.exit(1)
	elif len(sys.argv) > 2:
		print 'Too many arguments'
		sys.exit(1)

	try:
		with open(sys.argv[1], 'r') as f:
			line1 = f.readline().strip()
			line2 = f.readline().strip()
	except:
		print 'File not found'
		sys.exit(1)

	if line1 and line2:
		p1 = create_polynomial(line1)
		p2 = create_polynomial(line2)

		output('Polynomial 1', p1)

		output('Polynomial 2', p2)

		p3 = p1 + p2
		output('({0}) + ({1})'.format(p1, p2), p3)

		p4 = p1 - p2
		output('({0}) - ({1})'.format(p1, p2), p4)

		p5 = p1 * p2
		output('({0}) * ({1})'.format(p1, p2), p5)

		heading('({0})^5'.format(p1))
		print p1 ** 5
		print

		heading('({0})^(({1})|x={2})'.format(p1, p2, 5))
		print p1 ** p2.eval(5)
		print

		heading('(({0})^5)|x=2'.format(p1))
		print (p1 ** 5).eval(2)


text:
using System;
using System.Collections.Generic;
using XenAdmin.Core;
using XenAPI;

namespace XenAdmin.Actions
{
    public class EnableHostAction:HostAbstractAction
    {
        private readonly bool _resumeVMs;

        public EnableHostAction(Host host, bool resumeVMs,Func<Pool, Host, long, long, bool> acceptNTolChangesOnEnable)
            : base(host.Connection, Messages.HOST_ENABLE, Messages.WAITING, null, acceptNTolChangesOnEnable)
        {
            if (host == null)
                throw new ArgumentNullException("host");
            _resumeVMs = resumeVMs;
            this.Host = host;
            AddCommonAPIMethodsToRoleCheck();
            ApiMethodsToRoleCheck.Add("pool.ha_compute_hypothetical_max_host_failures_to_tolerate");
            ApiMethodsToRoleCheck.Add("pool.set_ha_host_failures_to_tolerate");

            ApiMethodsToRoleCheck.Add("vm.assert_agile");
            ApiMethodsToRoleCheck.Add("vm.pool_migrate");
            ApiMethodsToRoleCheck.Add("vm.start_on");
            ApiMethodsToRoleCheck.Add("vm.resume_on");

            ApiMethodsToRoleCheck.Add("host.remove_from_other_config");
            ApiMethodsToRoleCheck.Add("host.enable");
        }

        protected override void Run()
        {
            this.Description = string.Format(Messages.HOSTACTION_EXITING_MAINTENANCE_MODE, Helpers.GetName(Host));

            Enable(0, _resumeVMs ? 10 : 100, true);

            if (_resumeVMs)
            {
                List<VM> migratedVMs = Host.GetMigratedEvacuatedVMs();
                List<VM> haltedVMs = Host.GetHaltedEvacuatedVMs();
                List<VM> suspendedVMs = Host.GetSuspendedEvacuatedVMs();
                Host.ClearEvacuatedVMs(Session);

                if (migratedVMs.Count + haltedVMs.Count + suspendedVMs.Count > 0)
                {
                    int start = 10;
                    int each = 90 / (migratedVMs.Count + haltedVMs.Count + suspendedVMs.Count);

                    foreach (VM vm in migratedVMs)
                    {
                        RelatedTask = XenAPI.VM.async_live_migrate(Session, vm.opaque_ref, Host.opaque_ref);
                        PollToCompletion(start, start + each);
                        start += each;
                    }

                    foreach (VM vm in haltedVMs)
                    {
                        RelatedTask = XenAPI.VM.async_start_on(Session, vm.opaque_ref, Host.opaque_ref, false, false);
                        PollToCompletion(start, start + each);
                        start += each;
                    }

                    foreach (VM vm in suspendedVMs)
                    {
                        RelatedTask = XenAPI.VM.async_resume_on(Session, vm.opaque_ref, Host.opaque_ref, false, false);
                        PollToCompletion(start, start + each);
                        start += each;
                    }
                }
                else
                {
                    Host.ClearEvacuatedVMs(Session);
                }
            }

            this.Description = string.Format(Messages.HOSTACTION_EXITED_MAINTENANCE_MODE, Helpers.GetName(Host));
        }
    }
}


text:
module Azure::StreamAnalytics::Mgmt::V2016_03_01
  module Models
    #
    # Describes a Service Bus Queue output data source.
    #
    class ServiceBusQueueOutputDataSource < OutputDataSource

      include MsRestAzure

      def initialize
        @type = "Microsoft.ServiceBus/Queue"
      end

      attr_accessor :type

      # @return [String] The namespace that is associated with the desired
      # Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT
      # (CreateOrReplace) requests.
      attr_accessor :service_bus_namespace

      # @return [String] The shared access policy name for the Event Hub,
      # Service Bus Queue, Service Bus Topic, etc. Required on PUT
      # (CreateOrReplace) requests.
      attr_accessor :shared_access_policy_name

      # @return [String] The shared access policy key for the specified shared
      # access policy. Required on PUT (CreateOrReplace) requests.
      attr_accessor :shared_access_policy_key

      # @return [String] The name of the Service Bus Queue. Required on PUT
      # (CreateOrReplace) requests.
      attr_accessor :queue_name

      # @return [Array<String>] A string array of the names of output columns
      # to be attached to Service Bus messages as custom properties.
      attr_accessor :property_columns

      #
      # Mapper for ServiceBusQueueOutputDataSource class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'Microsoft.ServiceBus/Queue',
          type: {
            name: 'Composite',
            class_name: 'ServiceBusQueueOutputDataSource',
            model_properties: {
              type: {
                client_side_validation: true,
                required: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              },
              service_bus_namespace: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.serviceBusNamespace',
                type: {
                  name: 'String'
                }
              },
              shared_access_policy_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.sharedAccessPolicyName',
                type: {
                  name: 'String'
                }
              },
              shared_access_policy_key: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.sharedAccessPolicyKey',
                type: {
                  name: 'String'
                }
              },
              queue_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.queueName',
                type: {
                  name: 'String'
                }
              },
              property_columns: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.propertyColumns',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
// MvxStoreLocationWatcher.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com

using MvvmCross.Platform.Exceptions;
using MvvmCross.Platform.WindowsCommon.Platform;
using System;
using Windows.Devices.Geolocation;

namespace MvvmCross.Plugins.Location.WindowsStore
{
    public sealed class MvxStoreLocationWatcher : MvxLocationWatcher
    {
        private Geolocator _geolocator;

        public MvxStoreLocationWatcher()
        {
            EnsureStopped();
        }

        protected override void PlatformSpecificStart(MvxLocationOptions options)
        {
            if (_geolocator != null)
                throw new MvxException("You cannot start the MvxLocation service more than once");

            _geolocator = new Geolocator
            {
                DesiredAccuracy = options.Accuracy == MvxLocationAccuracy.Fine ? PositionAccuracy.High : PositionAccuracy.Default,
                MovementThreshold = options.MovementThresholdInM,
                ReportInterval = (uint)options.TimeBetweenUpdates.TotalMilliseconds
            };

            _geolocator.StatusChanged += OnStatusChanged;
            _geolocator.PositionChanged += OnPositionChanged;
        }

        public override MvxGeoLocation CurrentLocation
        {
            get
            {
                if (_geolocator == null)
                    throw new MvxException("Location Manager not started");

#warning This Await here feels very dangerous - would be better to add an async API for location
                var storeLocation = _geolocator.GetGeopositionAsync().Await();
                if (storeLocation == null)
                    return null;

                return CreateLocation(storeLocation.Coordinate);
            }
        }

        protected override void PlatformSpecificStop()
        {
            EnsureStopped();
        }

        private void EnsureStopped()
        {
            if (_geolocator != null)
            {
                // TODO - is this enough to stop it?
                _geolocator.PositionChanged -= OnPositionChanged;
                _geolocator.StatusChanged -= OnStatusChanged;
                _geolocator = null;
            }
        }

        private void OnPositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            var location = CreateLocation(args.Position.Coordinate);
            SendLocation(location);
        }

        private void OnStatusChanged(Geolocator geolocator, StatusChangedEventArgs args)
        {
            switch (args.Status)
            {
                case PositionStatus.Ready:
                case PositionStatus.Initializing:
                    Permission = MvxLocationPermission.Granted;
                    break;

                case PositionStatus.NoData:
                    // TODO - trace could be useful here?
                    SendError(MvxLocationErrorCode.PositionUnavailable);
                    break;

                case PositionStatus.Disabled:
                case PositionStatus.NotInitialized:
                case PositionStatus.NotAvailable:
                    Permission = MvxLocationPermission.Denied;
                    // TODO - trace could be useful here?
                    SendError(MvxLocationErrorCode.ServiceUnavailable);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        private MvxGeoLocation CreateLocation(Geocoordinate coordinate)
        {
            var position = new MvxGeoLocation { Timestamp = coordinate.Timestamp };
            var coords = position.Coordinates;

            // TODO - allow nullables - https://github.com/slodge/MvvmCross/issues/94
            coords.Altitude = coordinate.Altitude ?? 0.0;
            coords.Latitude = coordinate.Latitude;
            coords.Longitude = coordinate.Longitude;
            coords.Speed = coordinate.Speed ?? 0.0;
            coords.Accuracy = coordinate.Accuracy;
            coords.AltitudeAccuracy = coordinate.AltitudeAccuracy ?? double.MaxValue;

            return position;
        }
    }
}


text:
This dasboard is based on [GithubSurvivor by 99designs](https://github.com/99designs/githubsurvivor) (at least the UI design and the dashboard idea). The difference is that, this is an **Android JS App** instead of python web application

Why it is for? You do not want to always have a lot of tabs open and observe if there are any merge requests in your project or the build is currently failing. This dashboard will solve your problems! One place to join them all!

Why this approach instead of an app? You can run this on a device like hackberry connected with a monitor (or you phone), without any server for hosting the backend, only the tools you use itself. The second difference are the backends which this dashboard integrates. For now it uses **Youtrack** and **Gitlab**. Additionally it is possible to integrate as an issues backend **Redmine** with Backlogs extension installed.

Also there are some differences how the calculations are made, for e.g. Hall of Fame/Shame.

### Hall of Fame

Hall of Fame/Shame is currently calculated by the amount of issues resolved in current sprint. It does not matter if they're bugs, tasks, etc.

### Bugs

Bugs are also calculated by default using **Youtrack**. As a first graph you'll have number of bugs openned/closed in a current sprint only. The second graph will show summarized bugs for last X days set in settings.js file.

### Merge Requests

It shows number of merge requests open. Currently implemented to support **Gitlab** as a backend. Feel free to implement additional backends if you would like.

### Build status

If your build will fail you'll fail the game, so watch out. Build status currently implemented using **Jenkins** as a backend.

## Where the backends should go?

If you would like to implement a new backend, you should put it in a file where it belongs to as a service. For example, if you would like to implement issues for Github you should create new service in ```issues/github.js``` with a name ```issuesGithub``` in a module ```ftDashboard.issues.github```. You can put also additional services there. To change the implementation you should change the main file for a module, in this case it would be ```issues/issues.js```. This way the details of an implementation won't leak into the controller.

## Tests

Simplest way to run tests is to run either

```
make tests
```

either directly through npm:

```
npm test
```


text:
require "volley"
require "volley/dsl"

class Jobs::Volley::Base < Job
  def init
    #::Volley::Dsl::VolleyFile.init
    ::Volley::Dsl::VolleyFile.load("#{Rails.root}/config/volley/volleyfile", primary: true)
  end

  def publisher
    init
    ::Volley::Dsl.publisher
  end
end


text:
All Messaging samples include a shared C# file, [Main.cs](Main.cs) that resides in the
"common" repository folder. It implements a class AppEntryPoint with
a static Main method that the CLR picks up as the main entry point for
the app.

The reason for having a shared entry point to simplify and unify the
handling of the required configuration information for Service Bus that is created
by the [setup script](../README.md) and held in the user profile directory.

The implementation assumes that the sample implements a class Program
with an instance method Run() and will call that method after handling
the configuration data. The specific, invoked Run() method will differ
by the kind of sample and is therefore defined by an interface that Program
is expected to implement.

The entry point can also be used for Windows Forms apps and other apps requiring the
[STAThread] declaration by defining the "STA" symbol in the project settings.

The code first reads the settings from the "azure-msg-config.properties" file that
it expects in the root of the user's profile folder. The expected format for the text file
are lines holding {property}={value}, separated by line-breaks.

The settings can also be set (or overridden) with environment variables set before
the program is invoked:

| Property               |  Description                                                         |
|------------------------|----------------------------------------------------------------------|
| SERVICEBUS_NAMESPACE   | Service Bus namespace name, without domain suffix                    |
| SERVICEBUS_ENTITY_PATH | Name of the configured entity to use for this sample                 |
| SERVICEBUS_FQDN_SUFFIX | Service Bus host name suffix, typically "servicebus.windows.net"     |
| SERVICEBUS_SEND_KEY    | SAS key value of the "samplesend" and "rootsamplesend" SAS rules     |
| SERVICEBUS_LISTEN_KEY  | SAS key value of the "samplelisten" and "rootsamplelisten" SAS rules |
| SERVICEBUS_MANAGE_KEY  | SAS key value of the "samplemanage" and "rootsamplemanage" SAS rules |


text:
package org.jetbrains.plugins.scala
package codeInsight
package intention
package types

import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.command.undo.UndoUtil.markPsiFileForUndo
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.api.base.ScStableCodeReferenceElement
import org.jetbrains.plugins.scala.lang.psi.api.base.types.{ScParenthesisedTypeElement, ScReferenceableInfixTypeElement}

/** Converts type element `(A @@ B)` to `@@[A, B]` */
class ConvertFromInfixIntention extends PsiElementBaseIntentionAction {
  def getFamilyName = "Use Prefix Type Syntax"

  override def getText: String = getFamilyName

  def isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean = {
    element match {
      case Parent(Both(_: ScStableCodeReferenceElement, Parent(Parent(_: ScReferenceableInfixTypeElement)))) => true
      case _ => false
    }
  }

  override def invoke(project: Project, editor: Editor, element: PsiElement): Unit = {
    val infixTypeElement = Option(element).filter(_.isValid)
      .flatMap(_.parentOfType(classOf[ScReferenceableInfixTypeElement], strict = false))
      .getOrElse(return)

    val replacement = infixTypeElement.computeDesugarizedType
      .getOrElse(return)

    val elementToReplace = infixTypeElement.getParent match {
      case x: ScParenthesisedTypeElement => x
      case _ => infixTypeElement
    }

    elementToReplace.replace(replacement)
    markPsiFileForUndo(replacement.getContainingFile)
  }
}


text:
require 'spec_helper'

class DummyContext; end

describe "Haml::Helpers" do
  let(:view) { DummyContext.new.extend Haml::Helpers }

  describe "#layout" do
    subject { view.layout(:bar) }
    it { should == "<?php use_layout('bar') ?>" }
  end

  describe "#partial" do
    context "without locals" do
      subject { view.partial(:foo) }
      it { should == "<?php render_partial('foo') ?>" }
    end

    context "with single local variable" do
      subject { view.partial(:foo, :bar => "$bat") }
      it { should == "<?php render_partial('foo', array('bar' => $bat)) ?>" }
    end

    context "with complext local variable set" do
      subject { view.partial(:foo, :bar => "$bat", :baz => ['foo', 1]) }
      it { should == "<?php render_partial('foo', array('bar' => $bat, 'baz' => array('foo', 1))) ?>" }
    end
  end

  describe "#yield_content" do
    context "when fragment name passed" do
      subject { view.yield_content(:foo) }
      it { should == "<?php yield('foo') ?>" }
    end

    context "without fragment name" do
      subject { view.yield_content }
      it { should == "<?php yield() ?>" }
    end
  end

  describe "#content_for" do
    context "content as string, no locals" do
      subject { haml("- content_for(:foo, 'bar')") }
      it { should == "<?php content_for('foo', function() { ?>\nbar\n<?php }) ?>\n" }
    end

    context "content as string, with locals" do
      subject { haml("- content_for(:foo, 'bar', :use => '$bat')") }
      it { should == "<?php content_for('foo', function() use($bat) { ?>\nbar\n<?php }) ?>\n" }
    end

    context "content as string, with multipe locals" do
      subject { haml("- content_for(:foo, 'bar', :use => %w($bat $baz))") }
      it { should == "<?php content_for('foo', function() use($bat, $baz) { ?>\nbar\n<?php }) ?>\n" }
    end

    context "content as block" do
      subject { haml("- content_for(:foo) do\n  %h1 bar") }
      it { should == "<?php content_for('foo', function() { ?>\n
bar
\n<?php }) ?>\n" }
    end

    context "content as block with locals and nested php tag" do
      subject { haml("- content_for(:foo, :use => %w($bat)) do\n  = php_e '$bar'") }
      it { should == "<?php content_for('foo', function() use($bat) { ?>\n<?php echo $bar ?>\n<?php }) ?>\n" }
    end
  end
end


text:
var formatters = require('./formatters');
var utils = require('./../utils/utils');
var Method = require('./method');
var Property = require('./property');

// TODO: refactor, so the input params are not altered.
// it's necessary to make same 'extension' work with multiple providers
var extend = function (web3) {
    /* jshint maxcomplexity:5 */
    var ex = function (extension) {

        var extendedObject;
        if (extension.property) {
            if (!web3[extension.property]) {
                web3[extension.property] = {};
            }
            extendedObject = web3[extension.property];
        } else {
            extendedObject = web3;
        }

        if (extension.methods) {
            extension.methods.forEach(function (method) {
                method.attachToObject(extendedObject);
                method.setRequestManager(web3._requestManager);
            });
        }

        if (extension.properties) {
            extension.properties.forEach(function (property) {
                property.attachToObject(extendedObject);
                property.setRequestManager(web3._requestManager);
            });
        }
    };

    ex.formatters = formatters;
    ex.utils = utils;
    ex.Method = Method;
    ex.Property = Property;

    return ex;
};

module.exports = extend;


text:
ardrone
=======

Collection and visualization telemetry from ardrone.


text:
<!DOCTYPE html>
<html class="no-js" lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <base href="{{ .Site.BaseURL }}">
    <title> {{ .Site.Title }} </title>
    <link rel="canonical" href="{{ .Permalink }}">
    <link rel="stylesheet" href="/css/foundation.css" type="text/css" media="screen">
    <link rel="stylesheet" href="/css/styles.css" type="text/css" media="screen">
  </head>
  <body lang="en">


text:
class MergeRequestsLoad < BaseContext
  def execute
    type = params[:f].to_i

    merge_requests = project.merge_requests

    merge_requests = case type
                     when 1 then merge_requests
                     when 2 then merge_requests.closed
                     when 3 then merge_requests.opened.assigned(current_user)
                     else merge_requests.opened
                     end.page(params[:page]).per(20)

    merge_requests.includes(:author, :project).order("closed, created_at desc")
  end
end


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Obnovitev datoteke iz Smeti</title>
<link rel="stylesheet" type="text/css" href="../vodnik_1404.css">

Ubuntu Slovenija | Uradna spletna stran slovenske skupnosti Linux distribucije Ubuntu

Novice

Forum

Kaj je Ubuntu?

Pogosta vprašanja

Skupnost

Povezave

 »  Namizni vodnik Ubuntu » Datoteke »

Obnovitev datoteke iz Smeti

Če datoteko izbrišete z upravljalnikom datotek, je datoteka običajno premaknjena v Smeti, zato jo lahko obnovite.

Za obnovitev datoteke iz smeti:

Odprite Zaganjalnik in nato kliknite bližnjico Smeti, ki se nahaja na dnu zaganjalnika.

V primeru da ste datoteko izbrisali tam, desno kliknite nanjo in izberite Obnovi. Obnovljena bo v mapo iz katere je bila izbrisana.

V primeru da ste datoteko izbrisali s Shift+Delete ali iz ukazne vrstice, datoteke na ta način ni mogočne obnoviti, ker je bila trajno izbrisana. Datotek, ki so bile trajno izbrisane, ni mogoče obnoviti iz Smeti.

Na voljo so številna obnovitvena orodja, ki lahko včasih obnovijo datoteke, ki so bile trajno izbrisane. Običajno jih ni enostavno uporabiti. V primeru da ste datoteko trajno izbrisali, za nasvet vprašajte na podpornem forumu.

Več podrobnosti

Datoteke, mape in iskanje — Iskanje, izbris datotek, varnostne kopije, odstranljivi pogoni …

Pogjejte tudi

Iskanje izgubljene datoteke — Sledit tem namigom, če ne morete najti datoteke, ki ste jo ustvarili ali prejeli.

Izbris datotek in map — Odstranite datoteke ali mape, ki jih ne potrebujete več.

Material v tem dokumentu je na voljo pod prosto licenco. To je prevod dokumentacije Ubuntu, ki jo je sestavila Ubuntu dokumentacijska ekpa za Ubuntu. V slovenščino jo je prevedla skupina Ubuntu prevajalcev. Za poročanje napak v prevodih v tej dokumentaciji ali Ubuntuju pošljite sporočilo na dopisni seznam.


text:
<?php

if (!defined('_PS_VERSION_'))
	exit;

function upgrade_module_1_7_2($module_obj)
{
	$all = $module_obj->db->executeS('SELECT * FROM '._DB_PREFIX_.'easycarousels');
	$rows = array();
	foreach ($all as $a)
	{
		$settings = Tools::jsonDecode($a['settings'], true);
		$settings['tpl']['title'] = 45;
		$settings['tpl']['title_one_line'] = 1;
		$settings = Tools::jsonEncode($settings);
		$rows[] = '('.(int)$a['id_carousel'].', '.(int)$a['id_shop'].', \''.pSQL($settings).'\')';
	}
	$module_obj->db->execute('
		INSERT INTO '._DB_PREFIX_.'easycarousels (id_carousel, id_shop, settings)
		VALUES '.implode(', ', $rows).'
		ON DUPLICATE KEY UPDATE
		settings = VALUES(settings)
	');
	return true;
}


text:
package org.apache.dubbo.rpc.cluster.merger;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ResultMergerTest {

    /**
     * MergerFactory test
     */
    @Test
    public void testMergerFactoryIllegalArgumentException() {
        try {
            MergerFactory.getMerger(null);
            Assertions.fail("expected IllegalArgumentException for null argument");
        } catch (IllegalArgumentException exception) {
            Assertions.assertEquals("returnType is null", exception.getMessage());
        }
    }

    /**
     * ArrayMerger test
     */
    @Test
    public void testArrayMergerIllegalArgumentException() {
        String[] stringArray = {"1", "2", "3"};
        Integer[] integerArray = {3, 4, 5};
        try {
            Object result = ArrayMerger.INSTANCE.merge(stringArray, null, integerArray);
            Assertions.fail("expected IllegalArgumentException for different arguments' types");
        } catch (IllegalArgumentException exception) {
            Assertions.assertEquals("Arguments' types are different", exception.getMessage());
        }
    }

    /**
     * ArrayMerger test
     */
    @Test
    public void testArrayMerger() {
        String[] stringArray1 = {"1", "2", "3"};
        String[] stringArray2 = {"4", "5", "6"};
        String[] stringArray3 = {};

        Object result = ArrayMerger.INSTANCE.merge(stringArray1, stringArray2, stringArray3, null);
        Assertions.assertTrue(result.getClass().isArray());
        Assertions.assertEquals(6, Array.getLength(result));
        Assertions.assertTrue(String.class.isInstance(Array.get(result, 0)));
        for (int i = 0; i < 6; i++) {
            Assertions.assertEquals(String.valueOf(i + 1), Array.get(result, i));
        }

        Integer[] intArray1 = {1, 2, 3};
        Integer[] intArray2 = {4, 5, 6};
        Integer[] intArray3 = {7};
        // trigger ArrayMerger
        result = MergerFactory.getMerger(Integer[].class).merge(intArray1, intArray2, intArray3, null);
        Assertions.assertTrue(result.getClass().isArray());
        Assertions.assertEquals(7, Array.getLength(result));
        Assertions.assertSame(Integer.class, result.getClass().getComponentType());
        for (int i = 0; i < 7; i++) {
            Assertions.assertEquals(i + 1, Array.get(result, i));
        }

        result = ArrayMerger.INSTANCE.merge(null);
        Assertions.assertEquals(0, Array.getLength(result));

        result = ArrayMerger.INSTANCE.merge(null, null);
        Assertions.assertEquals(0, Array.getLength(result));

        result = ArrayMerger.INSTANCE.merge(null, new Object[0]);
        Assertions.assertEquals(0, Array.getLength(result));
    }

    /**
     * BooleanArrayMerger test
     */
    @Test
    public void testBooleanArrayMerger() {
        boolean[] arrayOne = {true, false};
        boolean[] arrayTwo = {false};
        boolean[] result = MergerFactory.getMerger(boolean[].class).merge(arrayOne, arrayTwo, null);
        Assertions.assertEquals(3, result.length);
        boolean[] mergedResult = {true, false, false};
        for (int i = 0; i < mergedResult.length; i++) {
            Assertions.assertEquals(mergedResult[i], result[i]);
        }

        result = MergerFactory.getMerger(boolean[].class).merge(null);
        Assertions.assertEquals(0, result.length);

        result = MergerFactory.getMerger(boolean[].class).merge(null, null);
        Assertions.assertEquals(0, result.length);
    }

    /**
     * ByteArrayMerger test
     */
    @Test
    public void testByteArrayMerger() {
        byte[] arrayOne = {1, 2};
        byte[] arrayTwo = {1, 32};
        byte[] result = MergerFactory.getMerger(byte[].class).merge(arrayOne, arrayTwo, null);
        Assertions.assertEquals(4, result.length);
        byte[] mergedResult = {1, 2, 1, 32};
        for (int i = 0; i < mergedResult.length; i++) {
            Assertions.assertEquals(mergedResult[i], result[i]);
        }

        result = MergerFactory.getMerger(byte[].class).merge(null);
        Assertions.assertEquals(0, result.length);

        result = MergerFactory.getMerger(byte[].class).merge(null, null);
        Assertions.assertEquals(0, result.length);
    }

    /**
     * CharArrayMerger test
     */
    @Test
    public void testCharArrayMerger() {
        char[] arrayOne = "hello".toCharArray();
        char[] arrayTwo = "world".toCharArray();
        char[] result = MergerFactory.getMerger(char[].class).merge(arrayOne, arrayTwo, null);
        Assertions.assertEquals(10, result.length);
        char[] mergedResult = "helloworld".toCharArray();
        for (int i = 0; i < mergedResult.length; i++) {
            Assertions.assertEquals(mergedResult[i], result[i]);
        }

        result = MergerFactory.getMerger(char[].class).merge(null);
        Assertions.assertEquals(0, result.length);

        result = MergerFactory.getMerger(char[].class).merge(null, null);
        Assertions.assertEquals(0, result.length);
    }

    /**
     * DoubleArrayMerger test
     */
    @Test
    public void testDoubleArrayMerger() {
        double[] arrayOne = {1.2d, 3.5d};
        double[] arrayTwo = {2d, 34d};
        double[] result = MergerFactory.getMerger(double[].class).merge(arrayOne, arrayTwo, null);
        Assertions.assertEquals(4, result.length);
        double[] mergedResult = {1.2d, 3.5d, 2d, 34d};
        for (int i = 0; i < mergedResult.length; i++) {
            Assertions.assertEquals(mergedResult[i], result[i], 0.0);
        }

        result = MergerFactory.getMerger(double[].class).merge(null);
        Assertions.assertEquals(0, result.length);

        result = MergerFactory.getMerger(double[].class).merge(null, null);
        Assertions.assertEquals(0, result.length);
    }

    /**
     * FloatArrayMerger test
     */
    @Test
    public void testFloatArrayMerger() {
        float[] arrayOne = {1.2f, 3.5f};
        float[] arrayTwo = {2f, 34f};
        float[] result = MergerFactory.getMerger(float[].class).merge(arrayOne, arrayTwo, null);
        Assertions.assertEquals(4, result.length);
        double[] mergedResult = {1.2f, 3.5f, 2f, 34f};
        for (int i = 0; i < mergedResult.length; i++) {
            Assertions.assertEquals(mergedResult[i], result[i], 0.0);
        }

        result = MergerFactory.getMerger(float[].class).merge(null);
        Assertions.assertEquals(0, result.length);

        result = MergerFactory.getMerger(float[].class).merge(null, null);
        Assertions.assertEquals(0, result.length);
    }

    /**
     * IntArrayMerger test
     */
    @Test
    public void testIntArrayMerger() {
        int[] arrayOne = {1, 2};
        int[] arrayTwo = {2, 34};
        int[] result = MergerFactory.getMerger(int[].class).merge(arrayOne, arrayTwo, null);
        Assertions.assertEquals(4, result.length);
        double[] mergedResult = {1, 2, 2, 34};
        for (int i = 0; i < mergedResult.length; i++) {
            Assertions.assertEquals(mergedResult[i], result[i], 0.0);
        }

        result = MergerFactory.getMerger(int[].class).merge(null);
        Assertions.assertEquals(0, result.length);

        result = MergerFactory.getMerger(int[].class).merge(null, null);
        Assertions.assertEquals(0, result.length);
    }

    /**
     * ListMerger test
     */
    @Test
    public void testListMerger() {
        List<Object> list1 = new ArrayList<Object>() {{
            add(null);
            add("1");
            add("2");
        }};
        List<Object> list2 = new ArrayList<Object>() {{
            add("3");
            add("4");
        }};

        List result = MergerFactory.getMerger(List.class).merge(list1, list2, null);
        Assertions.assertEquals(5, result.size());
        ArrayList<String> expected = new ArrayList<String>() {{
            add(null);
            add("1");
            add("2");
            add("3");
            add("4");
        }};
        Assertions.assertEquals(expected, result);

        result = MergerFactory.getMerger(List.class).merge(null);
        Assertions.assertEquals(0, result.size());

        result = MergerFactory.getMerger(List.class).merge(null, null);
        Assertions.assertEquals(0, result.size());
    }

    /**
     * LongArrayMerger test
     */
    @Test
    public void testMapArrayMerger() {
        Map<Object, Object> mapOne = new HashMap<Object, Object>() {{
            put("11", 222);
            put("223", 11);
        }};
        Map<Object, Object> mapTwo = new HashMap<Object, Object>() {{
            put("3333", 3232);
            put("444", 2323);
        }};
        Map<Object, Object> result = MergerFactory.getMerger(Map.class).merge(mapOne, mapTwo, null);
        Assertions.assertEquals(4, result.size());
        Map<String, Integer> mergedResult = new HashMap<String, Integer>() {{
            put("11", 222);
            put("223", 11);
            put("3333", 3232);
            put("444", 2323);
        }};
        Assertions.assertEquals(mergedResult, result);

        result = MergerFactory.getMerger(Map.class).merge(null);
        Assertions.assertEquals(0, result.size());

        result = MergerFactory.getMerger(Map.class).merge(null, null);
        Assertions.assertEquals(0, result.size());
    }

    /**
     * LongArrayMerger test
     */
    @Test
    public void testLongArrayMerger() {
        long[] arrayOne = {1L, 2L};
        long[] arrayTwo = {2L, 34L};
        long[] result = MergerFactory.getMerger(long[].class).merge(arrayOne, arrayTwo, null);
        Assertions.assertEquals(4, result.length);
        double[] mergedResult = {1L, 2L, 2L, 34L};
        for (int i = 0; i < mergedResult.length; i++) {
            Assertions.assertEquals(mergedResult[i], result[i], 0.0);
        }

        result = MergerFactory.getMerger(long[].class).merge(null);
        Assertions.assertEquals(0, result.length);

        result = MergerFactory.getMerger(long[].class).merge(null, null);
        Assertions.assertEquals(0, result.length);
    }

    /**
     * SetMerger test
     */
    @Test
    public void testSetMerger() {
        Set<Object> set1 = new HashSet<Object>() {{
            add(null);
            add("1");
            add("2");
        }};

        Set<Object> set2 = new HashSet<Object>() {{
            add("2");
            add("3");
        }};

        Set result = MergerFactory.getMerger(Set.class).merge(set1, set2, null);

        Assertions.assertEquals(4, result.size());
        Assertions.assertEquals(new HashSet<String>() {
            {
                add(null);
                add("1");
                add("2");
                add("3");
            }
        }, result);

        result = MergerFactory.getMerger(Set.class).merge(null);
        Assertions.assertEquals(0, result.size());

        result = MergerFactory.getMerger(Set.class).merge(null, null);
        Assertions.assertEquals(0, result.size());
    }

    /**
     * ShortArrayMerger test
     */
    @Test
    public void testShortArrayMerger() {
        short[] arrayOne = {1, 2};
        short[] arrayTwo = {2, 34};
        short[] result = MergerFactory.getMerger(short[].class).merge(arrayOne, arrayTwo, null);
        Assertions.assertEquals(4, result.length);
        double[] mergedResult = {1, 2, 2, 34};
        for (int i = 0; i < mergedResult.length; i++) {
            Assertions.assertEquals(mergedResult[i], result[i], 0.0);
        }

        result = MergerFactory.getMerger(short[].class).merge(null);
        Assertions.assertEquals(0, result.length);

        result = MergerFactory.getMerger(short[].class).merge(null, null);
        Assertions.assertEquals(0, result.length);
    }
}


text:
<?php

/**
 * PHP callback encapsulation.
 *
 * @author     David Grudl
 * @package Nette
 */
final class NCallback extends NObject
{
	/** @var string|array|Closure */
	private $cb;

	/**
	 * Do not call directly, use callback() function.
	 * @param  mixed   class, object, function, callback
	 * @param  string  method
	 */
	public function __construct($t, $m = NULL)
	{
		if ($m === NULL) {
			if (is_string($t)) {
				$t = explode('::', $t, 2);
				$this->cb = isset($t[1]) ? $t : $t[0];
			} elseif (is_object($t)) {
				$this->cb = $t instanceof Closure ? $t : array($t, '__invoke');
			} else {
				$this->cb = $t;
			}

		} else {
			$this->cb = array($t, $m);
		}

		// remove class namespace
		if (is_string($this->cb) && $a = strrpos($this->cb, '\\')) {
			$this->cb = substr($this->cb, $a + 1);

		} elseif (is_array($this->cb) && is_string($this->cb[0]) && $a = strrpos($this->cb[0], '\\')) {
			$this->cb[0] = substr($this->cb[0], $a + 1);
		}

		if (!is_callable($this->cb, TRUE)) {
			throw new InvalidArgumentException("Invalid callback.");
		}
	}

	/**
	 * Invokes callback. Do not call directly.
	 * @return mixed
	 */
	public function __invoke()
	{
		if (!is_callable($this->cb)) {
			throw new InvalidStateException("Callback '$this' is not callable.");
		}
		$args = func_get_args();
		return call_user_func_array($this->cb, $args);
	}

	/**
	 * Invokes callback.
	 * @return mixed
	 */
	public function invoke()
	{
		if (!is_callable($this->cb)) {
			throw new InvalidStateException("Callback '$this' is not callable.");
		}
		$args = func_get_args();
		return call_user_func_array($this->cb, $args);
	}

	/**
	 * Invokes callback with an array of parameters.
	 * @param  array
	 * @return mixed
	 */
	public function invokeArgs(array $args)
	{
		if (!is_callable($this->cb)) {
			throw new InvalidStateException("Callback '$this' is not callable.");
		}
		return call_user_func_array($this->cb, $args);
	}

	/**
	 * Invokes callback using named parameters.
	 * @param  array
	 * @return mixed
	 */
	public function invokeNamedArgs(array $args)
	{
		$ref = $this->toReflection();
		if (is_array($this->cb)) {
			return $ref->invokeNamedArgs(is_object($this->cb[0]) ? $this->cb[0] : NULL, $args);
		} else {
			return $ref->invokeNamedArgs($args);
		}
	}

	/**
	 * Verifies that callback can be called.
	 * @return bool
	 */
	public function isCallable()
	{
		return is_callable($this->cb);
	}

	/**
	 * Returns PHP callback pseudotype.
	 * @return string|array|Closure
	 */
	public function getNative()
	{
		return $this->cb;
	}

	/**
	 * Returns callback reflection.
	 * @return NFunctionReflection|NMethodReflection
	 */
	public function toReflection()
	{
		if (is_array($this->cb)) {
			return new NMethodReflection($this->cb[0], $this->cb[1]);
		} else {
			return new NFunctionReflection($this->cb);
		}
	}

	/**
	 * @return bool
	 */
	public function isStatic()
	{
		return is_array($this->cb) ? is_string($this->cb[0]) : is_string($this->cb);
	}

	/**
	 * @return string
	 */
	public function __toString()
	{
		if ($this->cb instanceof Closure) {
			return '{closure}';
		} elseif (is_string($this->cb) && $this->cb[0] === "\0") {
			return '{lambda}';
		} else {
			is_callable($this->cb, TRUE, $textual);
			return $textual;
		}
	}

}


text:
from django.contrib.gis.db import models
from django.conf import settings
from django.contrib.gis.measure import A, D
from lingcod.unit_converter.models import length_in_display_units, area_in_display_units

class SpacingPoint(models.Model):
    name = models.CharField(max_length=200)
    geometry = models.PointField(srid=settings.GEOMETRY_DB_SRID)
    objects = models.GeoManager()

    def __unicode__(self):
        return unicode(self.name)

def all_spacing_points_dict():
    """
    Returns a dictionary of the form: { point: 'name' } for all objects in SpacingPoint
    """
    return dict( [ (p.geometry,p.name) for p in SpacingPoint.objects.all() ] )

def add_all_spacing_points(in_dict):
    """
    Takes a dictionary of the form: { point: 'name' }, and adds all the objects in SpacingPoint
    """
    in_dict.update(all_spacing_points_dict())
    return in_dict

def distance_row_dict(from_dict, to_dict):
    """
    from_dict will be a dict with a point as the key and a label as the value.
    to_dict will be of the same format with multiple entries.
    will return a dictionary with points as keys and a dictionary as values.
    NOTE: This method assumes that the projection units are meters.
    """
    from_pnt = from_dict.keys()[0]
    for s_pnt in SpacingPoint.objects.all():
        to_dict.update({s_pnt.geometry:s_pnt.name})
    result = {}
    for point, pnt_label in to_dict.iteritems():
        result[point] = {
            'label': pnt_label,
            'distance': length_in_display_units(point.distance(from_pnt)),
            'sort': point.y
        }
    return result

def distance_row_list(from_pnt, to_list):
    """
    NOTE: This method assumes that the projection units are meters.
    """
    result = []
    for point in to_list:
        result.append(length_in_display_units(point.distance(from_pnt)))
    return result

def distance_matrix(point_list):
    result = []
    for point in point_list:
        result.append(distance_row_list(point,point_list))
    return result

def sorted_points_and_labels(in_dict):
    """
    in_dict will look like:
    { point: 'name' }
    sorted_points, sorted_labels (both lists) will be returned in a dictionary and they'll be
    ordered from North to South.
    """
    sorted_points = []
    sorted_labels = []
    y_dict = {}
    for point, name in in_dict.iteritems():
        y_dict.update( { point.y: point } )
    y_list = y_dict.keys()
    y_list.sort()
    for y in reversed(y_list):
        sorted_points.append(y_dict[y])
        sorted_labels.append(in_dict[y_dict[y]])
    return { 'points': sorted_points, 'labels': sorted_labels }

def distance_matrix_and_labels(in_dict,add_spacing_points=True):
    """
    in_dict will look like:
    { point: 'name' }
    Will return a dictionary with the keys 'labels' and 'matrix'
    """
    if add_spacing_points:
        in_dict = add_all_spacing_points(in_dict)
    spl_dict = sorted_points_and_labels(in_dict)
    dist_mat = distance_matrix(spl_dict['points'])
    return { 'labels': spl_dict['labels'], 'matrix': dist_mat }


text:
[jvm]
Content
fun [copy](copy.md)(methodName: [String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html), typeSpec: [TypeSpec](../../com.github.jonathanxd.kores.base/-type-spec/index.md)): [MethodSpec](index.md)


text:
<!DOCTYPE html>
<html ng-app="waterApp">
  <head>
      <meta charset="utf-8">
      <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
      <!-- Latest compiled and minified JavaScript -->
      <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
      <style>
      </style>
  </head>
  <body>

    <div ng-controller="MainController">
        <wid-dropdown cbs="checkboxes"></wid-dropdown>
    </div>

    <script>
    angular.module('waterApp', [])
    .controller('MainController', ['$scope', function($scope) {
        $scope.checkboxes = [
            'glen',
            'joy',
            'yollande',
            'austyn'
        ];

        $scope.$on('onclickcheckbox', function () {
          console.log('do something');
        });
    }])
    .directive('widDropdown', function() {
        return {
            restrict: 'EA',
            transclude: false,
            templateUrl: 'directive-templates/wid-dropdown.html',
            scope: {
                cbs: '='
            },
            controller: function ($scope) {
              $scope.onclick = function (item) {
                $scope.$emit('onclickcheckbox');
              }
            }
        };
    });
    </script>
  </body>
</html>


text:
package net.roboconf.maven;

import java.io.File;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.Archiver;
import org.codehaus.plexus.archiver.zip.ZipArchiver;

/**
 * The package mojo.
 * @author Vincent Zurczak - Linagora
 */
@Mojo( name="package-target", defaultPhase = LifecyclePhase.PACKAGE )
public class PackageTargetMojo extends AbstractMojo {

	@Parameter( defaultValue = "${project}", readonly = true )
	private MavenProject project;

	@Component( role = Archiver.class, hint = "zip" )
	private ZipArchiver zipArchiver;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {

		// Find all the files
		File outputDirectory = new File( this.project.getBuild().getOutputDirectory());
		File targetDir = new File( this.project.getBuild().getDirectory());
		String archiveName = this.project.getBuild().getFinalName() + ".zip";
		File archiveFile = new File( targetDir, archiveName );

		// Add the application directories
		try {
			this.zipArchiver.addDirectory( outputDirectory );
			this.zipArchiver.setCompress( true );
			this.zipArchiver.setDestFile( archiveFile );
			this.zipArchiver.createArchive();

			this.project.getArtifact().setFile( archiveFile );

		} catch( Exception e ) {
			throw new MojoExecutionException( "Exception while packaging.", e );
		}
	}
}


text:
package com.taobao.zeus.web.platform.client.app.report;

import com.taobao.zeus.web.platform.client.util.Presenter;

public interface ReportPresenter extends Presenter{

}


text:
package com.verisign.getdns.test;

import java.util.HashMap;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import com.verisign.getdns.ExtensionName;
import com.verisign.getdns.GetDNSConstants;
import com.verisign.getdns.GetDNSException;
import com.verisign.getdns.GetDNSFactory;
import com.verisign.getdns.IGetDNSContextSync;
import com.verisign.getdns.RRType;

public class GetDNSWithExtensionNegetiveTest {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	/**
	 * test with dnssec return status value
	 */
	@Test
	public void testGetDNSWithDnssecStatusExtension() {
		System.out.println("--------DNSSEC_RETURN_STATUS TEST--------------");
		final IGetDNSContextSync context = GetDNSFactory.createSync(1,null);
		HashMap<ExtensionName, Object> extensions = new HashMap<ExtensionName, Object>();
		extensions.put(ExtensionName.DNSSEC_RETURN_STATUS, GetDNSConstants.GETDNS_EXTENSION_TRUE);
		try {
			thrown.expect(GetDNSException.class);
			thrown.expect(new ErrorCodeMatcher("GETDNS_RETURN_INVALID_PARAMETER"));
			context.generalSync(null, RRType.A, extensions);
		} finally {
			context.close();
		}

	}

	/**
	 * test with dnssec return only secure
	 */
	@Test
	public void testGetDNSWithDnssecOnlySecureExtension() {
		System.out.println("--------DNSSEC_RETURN_ONLY_SECURE--------------");
		final IGetDNSContextSync context = GetDNSFactory.createSync(1,null);
		HashMap<ExtensionName, Object> extensions = new HashMap<ExtensionName, Object>();
		extensions.put(ExtensionName.DNSSEC_RETURN_ONLY_SECURE, GetDNSConstants.GETDNS_EXTENSION_TRUE);
		try {
			thrown.expect(GetDNSException.class);
			thrown.expect(new ErrorCodeMatcher("GETDNS_RETURN_INVALID_PARAMETER"));
			context.generalSync(null, RRType.A, extensions);
		} finally {
			context.close();
		}

	}

	/**
	 * test with dnssec return validation chain
	 */
	@Test
	public void testGetDNSWithDnssecValidationChainExtension() {
		System.out.println("--------DNSSEC_RETURN_VALIDATIONCHAIN--------------");
		final IGetDNSContextSync context = GetDNSFactory.createSync(1,null);
		HashMap<ExtensionName, Object> extensions = new HashMap<ExtensionName, Object>();
		extensions.put(ExtensionName.DNSSEC_RETURN_VALIDATION_CHAIN, GetDNSConstants.GETDNS_EXTENSION_TRUE);
		try {
			thrown.expect(GetDNSException.class);
			thrown.expect(new ErrorCodeMatcher("GETDNS_RETURN_INVALID_PARAMETER"));
			context.generalSync(null, RRType.A, extensions);
		} finally {
			context.close();
		}

	}
}


text:
{% load staticfiles %}

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="description" content="">
<meta name="author" content="">
<title>{% if title %}{{ title }} — {% endif %}Розклад ЗНУ</title>

<link rel="shortcut icon" href="{% static "timetable/img/favicon.ico" %}" />
<link rel="apple-touch-icon-precomposed" href="{% static "timetable/img/apple-touch-icon-precomposed.png" %}" />

<link href='http://fonts.googleapis.com/css?family=PT+Sans|PT+Sans+Caption' rel='stylesheet' type='text/css'>

<!-- Bootstrap core CSS -->
<link href="{% static "timetable/css/bootstrap.css" %}" rel="stylesheet">
<link href="{% static "timetable/css/bootstrap-theme.css" %}" rel="stylesheet">

<!-- Custom styles for this template -->
<link href="{% static "timetable/css/user.css" %}?1" rel="stylesheet">

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
	<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
	<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->


text:
using Common;
using Controllers;
using Models;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ApiHttpClient.Tests
{
    [TestFixture]
    public class RouteTests
    {
        //at least 1 route should be existing
        private Dispatcher dispatcher = Dispatcher.Create(GlobalConstants.testToken2);
        [Test]
        public async Task Getting_All_Routes()
        {
            List<IApiCallResult> routes = await dispatcher.GetMany<Route>("routes");

            List<Route> targetList = new List<Route>(routes.Cast<Route>());

            Assert.IsTrue(targetList[0].EstDistanceKm>0);

        }

        //the route gotten should be an existant one
        [Test]
        public async Task Getting_Route_By_Id_Successfully()
        {
            Route route = (Route)await dispatcher.Get<Route>("routes", "1");
            Assert.IsTrue(route != null);
            /*
            Assert.AreEqual(route.EstDistanceKm, 1236);
            Assert.AreEqual(route.EstTimeDrivingMin, 14);
            Assert.AreEqual(route.EstFuelCost, 323);
            */

        }
        /*
        [Test]
        public async Task Create_Route_Successfully()
        {
            Company c = (Company)await ApiHttpClient.Dispatcher.GetInstance().Get<Company>("companies", User.GetInstance().CompanyId);
            User.GetInstance().Company = c;

            CompanyController companyCtrl = CompanyController
                .Create(new Company("somename", "someaddress"));

            List<Load> loads = new List<Load>();
            Load load1 = new Load(1, 2, "Example load", 500, 1200, DateTime.Now, 2, 3);
            Load load2 = new Load(2, 3, "Example load", 500, 1200, DateTime.Now, 2, 3);
            loads.Add(load1);
            loads.Add(load2);
            Truck truck = new Truck("HZ-12-KFN1", 1, 234, 23, 5000, 200, 14);

            Route route = new Route();

            route.Loads = loads;
            route.Truck = truck;

            route = companyCtrl.RouteCtrl.SetEstimations(route);

            IApiCallResult newroute = await Dispatcher.GetInstance().Post("routes", route);

        }*/
    }
}


text:
{-# LANGUAGE MultiParamTypeClasses #-}

-- !!! Multi-param type classes test: ambiguity bug

-- GHC actually accepts this program because
--	q :: Collection c a => a -> Bool
-- and there is no a priori reason to suppose that
-- q would be ambiguous in every context. For example,
-- it could be fine if we had
--	instance c Int where ...
-- Of course, it'd be hard to fill in the "..." in this particular
-- case, but that relies on observations about the form of the types
-- of the class methods, surely beyond what a compiler should do.
--
-- Still, the type is ambiguous because there's nothing to fix 'c'

module ShouldFail where

class Collection c a where
    empty :: c a
    add :: a -> c a -> c a
    isempty :: c a -> Bool

singleton x = add x empty

q x = isempty (singleton x)


text:
=======
ec2-ssh
=======

.. image:: https://img.shields.io/pypi/v/ec2-ssh.svg
    :target: https://pypi.python.org/pypi/ec2-ssh

.. image:: https://travis-ci.org/adamchainz/ec2-ssh.svg?branch=master
    :target: https://travis-ci.org/adamchainz/ec2-ssh

A pair of command line utilities for finding and SSH-ing into your Amazon EC2
instances by tag (such as 'Name').

Forked from Instagram original code by YPlan.

Installation
------------

From pip:

.. code-block:: sh

    pip install ec2-ssh

Python 2 and 3 compatible.

Usage
-----

There are two utilities: ``ec2-ssh`` and ``ec2-host``.

1. ``ec2-ssh``
~~~~~~~~~~~~~~

Use the ``ec2-ssh`` command to SSH into your instances. Rather than a hostname
to SSH into, it takes a tag key (default Name) and value, looks up the
instances matching that tag, randomly picks one (if there is >1) and uses its
public hostname, or private IP if it's not public. The username is defaulted to
``ubuntu``.

For example:

.. code-block:: sh

    $ ec2-ssh myapp
    # looks up instances where Name=myapp, expands out to something like:
    # ssh ubuntu@ec2-123-45-67-89.compute-1.amazonaws.com

    $ ec2-ssh root@myapp
    # expands to
    # ssh root@ec2-123-45-67-89.compute-1.amazonaws.com

You can pass the ``-t / --tag`` option to use a different tag key to search on,
for example:

.. code-block:: sh

    $ ec2-ssh -t role myapp-frontend

All other options are passed through to SSH so you can do things like:

.. code-block:: sh

    $ ec2-ssh myapp -- sudo systemctl restart nginx
    $ ec2-ssh -vvv myapp  # why can't I connect??

2. ``ec2-host``
~~~~~~~~~~~~~~~

This tool exposes just the host-lookup logic from ``ec2-ssh`` you can use it
for other purposes. The only difference is that rather than returning just one
matching instance's hostname/IP, it will return all of them. For example:

.. code-block:: sh

    $ ec2-host  # no tag, prints all instance hosts
    ec2-123-45-67-89.compute-1.amazonaws.com
    ec2-123-45-67-90.compute-1.amazonaws.com
    ec2-123-45-67-91.compute-1.amazonaws.com

    % ec2-host myapp  # only instances where Name=myapp
    ec2-123-45-67-89.compute-1.amazonaws.com
    ec2-123-45-67-90.compute-1.amazonaws.com

    % ec2-host -t environment prod  # instances where environment=prod
    ec2-123-45-67-90.compute-1.amazonaws.com
    ec2-111-45-67-90.compute-1.amazonaws.com


text:
Parsley.addMessages('sv', {
  dateiso: "Ange ett giltigt datum (ÅÅÅÅ-MM-DD)."
});


text:
Jenkins Jira Plugin
===================

[![Documentation](https://img.shields.io/jenkins/plugin/v/jira.svg?label=Documentation)](https://plugins.jenkins.io/jira)
[![GitHub release](https://img.shields.io/github/release/jenkinsci/jira-plugin.svg?label=Release)](https://github.com/jenkinsci/jira-plugin/releases/latest)
[![Jenkins CI](https://ci.jenkins.io/buildStatus/icon?job=Plugins/jira-plugin/master)](https://ci.jenkins.io/blue/organizations/jenkins/Plugins%2Fjira-plugin/activity/)
[![Travis CI](https://travis-ci.org/jenkinsci/jira-plugin.svg?branch=master)](https://travis-ci.org/jenkinsci/jira-plugin)

[![Jenkins Plugin Installs](https://img.shields.io/jenkins/plugin/i/jira.svg?color=blue)](https://stats.jenkins.io/pluginversions/jira.html)
[![Coverage](https://coveralls.io/repos/jenkinsci/jira-plugin/badge.svg?branch=master&service=github)](https://coveralls.io/github/jenkinsci/jira-plugin?branch=master)
[![Contributors](https://img.shields.io/github/contributors/jenkinsci/jira-plugin.svg)](https://github.com/jenkinsci/jira-plugin/graphs/contributors)

### About the plugin

This plugin integrates with Jenkins the [Atlassian Jira Software](http://www.atlassian.com/software/jira/) (both Cloud and Server versions). For bug reports, see [bugs](https://issues.jenkins-ci.org/issues/?filter=14761) or [all open issues](https://issues.jenkins-ci.org/issues/?filter=14956). For documentation, see [official plugin site](https://plugins.jenkins.io/jira).

#### Reporting Bugs

Before reporting a new bug, check [currently open  issues in JIRA](https://issues.jenkins-ci.org/browse/JENKINS-64002?filter=14956).

When creating a new issue, provide as much information as possible including:

- steps to reproduce the issue and possible workarounds if known (Description field)

- Jenkins and plugin versions from [Jenkins Script console](https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+Script+Console) at `http://<jenkins-ip:8080>/script`:

```groovy
println("Jenkins:" + Jenkins.instance.getVersion())

Jenkins.instance.pluginManager.plugins.each{
  plugin ->
    println ("${plugin.getDisplayName()} (${plugin.getShortName()}): ${plugin.getVersion()}")
}
```

#### Contribute or Sponsor!

We all love Open Source, but... Open Source Software depends on contributions of fellow developers.
Please contribute by [opening Pull Requests](CONTRIBUTING.md) or if you are not a developer, consider sponsoring one of the maintainers.

### Configuring the plugin

#### Usage with Jira Cloud

With Atlassian Jira Cloud, it's not possible to create a user without an
email, so you need to create API token that will be used as a _service user_
by Jenkins to execute API calls to Jira Cloud - follow [Atlassian API tokens documentation](https://confluence.atlassian.com/cloud/api-tokens-938839638.html)

Then create a global Jenkins credential:
- put *Atlassian ID email* as username
- *API token* as password.

You can check if your API token works correctly by getting a correct
JSON issue response with this command (where TEST-1 is an example issue
in your project):

```bash
$ curl -X GET -u <email>:<API token> -H "Content-Type: application/json"  https://<YourCloudInstanceName>.atlassian.net/rest/api/latest/issue/TEST-1
```

Also make sure that CAPTCHA is not triggered for your user as this will
prevent the API token to work - see [CAPTCHA section in Atlassian REST API documentation.](https://developer.atlassian.com/cloud/jira/platform/jira-rest-api-basic-authentication/)

#### Using Jira REST API

This plugin has an optional feature to update Jira issues with a back
pointer to Jenkins build pages. This allows the submitter and watchers
to quickly find out which build they need to pick up to get the fix.

![](docs/images/Plugin_Configuration.png)

#### Jira Issue links in build Changelog

When you configure your Jira site in Jenkins, the plugin will
automatically hyperlink all matching issue names to Jira.

If you have additionally provided username/password to Jira, the
hyperlinks will also contain tooltips with the issue summary.

![](docs/images/example_annotated_changelog.png)

#### Updating Jira issues with back pointers

If you also want to use this feature, you need to supply a valid user
id/password. If you need the comment only to be visible to a certain
Jira group, e.g. *Software Development*, enter the groupname.

Now you also need to configure jobs. I figured you might not always have
write access to the Jira (say you have a Jenkins build for one of the
Apache commons project that you depend on), so that's why this is
optional.

And the following screen shows how Jira issue is updated:

![](docs/images/Jira_Comments.jpg)

By taking advantages of Jenkins'
[fingerprint](https://wiki.jenkins.io/display/JENKINS/Fingerprint)
feature, when your other projects that depend on this project pick up a
build with a fix, those build numbers can also be recorded in Jira.

This is quite handy when a bug is fixed in one of the libraries, yet the
submitter wants a fix in a different project. This happens often in my
work, where a bug is reported against JAX-WS but the fix is in JAXB.

For curious mind, see [this thread for how this works behind the scene](http://jenkins.361315.n4.nabble.com/How-can-does-Hudson-Jira-integration-works-td374680.html).

#### Referencing Jira Release version

To reference Jira Release versions in your build, you can pull these
releases directly from Jira by adding the Jira Release Version
Parameter.

This can be useful for generating release notes, trigerring
parameterized build, etc.
![](docs/images/version_parameters.png)

#### Generating Release Notes

You can also generate release notes to be used during your build. These
notes can be retrieved from an environment variable. See the [Maven Project Plugin](https://wiki.jenkins.io/display/JENKINS/Maven+Project+Plugin) for
the environment variables found within the POM.
![](docs/images/release_notes.png)

After your build has run, you can also have the plugin mark a release as
resolved. This typically will be a release you specified in your Build
Parameters.
![](docs/images/mark_as_resolved.png)

The plugin can also move certain issues matching a JQL query to a new
release version.
![](docs/images/move_issues.png)

Sample usage of generated Release Notes:

![](docs/images/release_notes_config.png)

#### Jira Authentication & Permissions required

**Note:** As a rule of thumb, **you should be always using a service
account** (instead of a personal account) to integrate Jenkins with
Jira.

Make sure that the Jira user used by Jenkins has enough permissions to
execute its actions. You can do that via Jira Permission Helper tool.

-   For creating Jira issues, the user has to be able to Create Issues
    in the specified project
-   If you additionally enter assignee or component field values, make
    sure that:
    -   both of the fields are assigned to the corresponding Jira Screen
    -   the Jira user is Assignable in the project
    -   the Jenkins Jira user can Assign issues

#### System properties

| Property Name | Functionality Change |
|---------------|----------------------|
| `-Dhudson.plugins.jira.JiraMailAddressResolver.disabled=true` | Use to disable resolving user email from Jira usernames. Currently there is no option for this in UI. |

#### Related Resources

-   Check also the Marvelution [Jenkins Integration for Jira](https://www.marvelution.com/products/jenkins-integration-for-jira/) which provides a two-way solution (Jenkins-\>Jira and Jira-\>Jenkins)
-   For Jira Workflow (Pipeline) plugin compatibility see [COMPATIBILITY.md](COMPATIBILITY.md)

#### Common issues

##### Jenkins<>Jira SSL connectivity problems

If you encounter stacktraces like this:
```
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
```

make sure the JRE/JDK that Jenkins master is running (or the Jenkins slaves are running) contain the valid CA chain certificates that Jira is running with.
You can test it using this [SSLPoke.java class](https://gist.github.com/warden/e4ef13ea60f24d458405613be4ddbc51):
```
$ wget -O SSLPoke.java https://gist.githubusercontent.com/warden/e4ef13ea60f24d458405613be4ddbc51/raw/7f258a30be4ddea7b67239b40ae305f6a2e98e0a/SSLPoke.java

$ /usr/java/jdk1.8.0_131/bin/javac SSLPoke.java

$ /usr/java/jdk1.8.0_131/jre/bin/java SSLPoke jira.domain.com 443
Successfully connected
```

References:
* [Jenkins fails with PKIX Path building error](https://stackoverflow.com/questions/52842214/jenkins-fails-with-pkix-path-building-error)
* [PKIX path building failed error message
](https://support.cloudbees.com/hc/en-us/articles/217078498-PKIX-path-building-failed-error-message)


text:
<Alloy>
	<Window class="container" title="Plots" id="plotsWin">
		<RightNavButton>
			<Button id="editPlot" title="Edit" onClick="editBtn"/>
		</RightNavButton>

		<TableView class="table" id="tbl">
			<HeaderView id="mainHeader">
				<View id="headerView">
					<Button id="addPlot" title="Add Plot" onClick="addBtn"/>
					<Label id="addPlotError" class="error" visible="false" text="*Total Coverage is less than 100%"/>
				</View>
			</HeaderView>
			<!--Placeholder row for testing screens-->
			<TableViewRow title="Row 1" id="row1"></TableViewRow>
		</TableView>
	</Window>
</Alloy>


text:
package com.ntobjectives.hackazon.network;

import android.util.Log;
import com.ntobjectives.hackazon.model.CustomerAddress;
import com.octo.android.robospice.request.retrofit.RetrofitSpiceRequest;

/**
 * Created with IntelliJ IDEA by Nick Chervyakov.
 * User: Nikolay Chervyakov
 * Date: 21.10.2014
 * Time: 18:35
 */
public class CustomerAddressAddRetrofitSpiceRequest extends RetrofitSpiceRequest<CustomerAddress, Hackazon> {
    public static final String TAG = CustomerAddressAddRetrofitSpiceRequest.class.getSimpleName();
    protected CustomerAddress address;

    public CustomerAddressAddRetrofitSpiceRequest(CustomerAddress address) {
        super(CustomerAddress.class, Hackazon.class);
        this.address = address;
    }

    @Override
    public CustomerAddress loadDataFromNetwork() throws Exception {
        Log.d(TAG, "Add customer address on network service.");
        return getService().addCustomerAddress(address);
    }
}


text:
namespace pwny
{
	class ProtectGuard
	{
	public:
		ProtectGuard(DWORD address, DWORD size);
		~ProtectGuard();

	private:
		DWORD m_address;
		DWORD m_size;
		DWORD m_oldFlags;
	};

	class Detour
	{
	public:
		Detour(DWORD address, DWORD hook);
		~Detour();

		bool IsApplied() const;
		void Apply();
		void Remove();
		DWORD GetAddress() const;

	private:
		Detour& operator=(Detour const& other);
		Detour(Detour const& other);

		std::vector<unsigned char> m_original;
		std::vector<unsigned char> m_patch;
		DWORD m_address;
		DWORD m_hook;
		bool m_applied;
	};
} // pwny


text:
namespace gfx {
struct NativePixmapHandle;
class Size;
}

namespace ui {

// The Ozone interface allows external implementations to hook into Chromium to
// provide a client pixmap for non-GPU processes.
class OZONE_EXPORT ClientNativePixmapFactory {
 public:
  static ClientNativePixmapFactory* GetInstance();
  static void SetInstance(ClientNativePixmapFactory* instance);

  static scoped_ptr<ClientNativePixmapFactory> Create();

  virtual ~ClientNativePixmapFactory();

  // Returns true if format/usage configuration is supported.
  virtual bool IsConfigurationSupported(gfx::BufferFormat format,
                                        gfx::BufferUsage usage) const = 0;

  // TODO(dshwang): implement it. crbug.com/475633
  // Import the native pixmap from |handle| to be used in non-GPU processes.
  // This function takes ownership of any file descriptors in |handle|.
  virtual scoped_ptr<ClientNativePixmap> ImportFromHandle(
      const gfx::NativePixmapHandle& handle,
      const gfx::Size& size,
      gfx::BufferUsage usage) = 0;

 protected:
  ClientNativePixmapFactory();

 private:
  DISALLOW_COPY_AND_ASSIGN(ClientNativePixmapFactory);
};

}  // namespace ui

#endif  // UI_OZONE_PUBLIC_CLIENT_NATIVE_PIXMAP_FACTORY_H_


text:
local soext = (jit.os == "OSX" and "dylib" or "so")
local function script_path() local fio = require "fio"; local b = debug.getinfo(2, "S").source:sub(2); local b_dir = fio.dirname(b); local lb = fio.readlink(b); while lb ~= nil do if not string.startswith(lb, '/') then lb = fio.abspath(fio.pathjoin(b_dir, lb)) end; b = lb; lb = fio.readlink(b) end return b:match("(.*/)") end
local function addpaths(dst, ...) local cwd = script_path() or fio.cwd() .. "/"; local pp = {}; for s in package[dst]:gmatch("([^;]+)") do pp[s] = 1 end; local add = ""; for _, p in ipairs({...}) do local ap = cwd .. p; if string.startswith(p, '/') then ap = p end; if not pp[ap] then add = add .. ap .. ";" end; end package[dst] = add .. package[dst] return end
addpaths('path', '?.lua', '?/init.lua', 'app/?.lua', 'app/?/init.lua', '.rocks/share/lua/5.1/?.lua', '.rocks/share/lua/5.1/?/init.lua', '.rocks/share/tarantool/?.lua', '.rocks/share/tarantool/?/init.lua')
addpaths('cpath', '.rocks/lib/lua/5.1/?.'..soext, '.rocks/lib/lua/?.'..soext, '.rocks/lib64/lua/5.1/?.'..soext, '.rocks/lib/tarantool/?.'..soext, '.rocks/lib64/tarantool/?.'..soext)

require 'strict'.on()
require 'package.reload'
local fio = require 'fio'

local conf_path = os.getenv('CONF')
if conf_path == nil then
    conf_path = '/etc/{{__name__}}/conf.lua'
end
local conf = require('config')(conf_path)

local app = require 'app'
if app ~= nil and app.init ~= nil then
    local ok, res = xpcall(
        function()
            return app.init(conf.get('app'))
        end,
        function(err)
            print(err .. '\n' .. debug.traceback())
            os.exit(1)
        end
    )
end

if tonumber(os.getenv('FG')) == 1 then
    if pcall(require('console').start) then
        os.exit(0)
    end
end


text:
package com.culabs.unicomportal.dao;

import com.culabs.unicomportal.model.db.DBRolePermissions;

public interface DBRolePermissionsMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table role_permissions
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table role_permissions
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int insert(DBRolePermissions record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table role_permissions
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int insertSelective(DBRolePermissions record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table role_permissions
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    DBRolePermissions selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table role_permissions
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int updateByPrimaryKeySelective(DBRolePermissions record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table role_permissions
     *
     * @mbggenerated Tue May 26 15:53:09 CST 2015
     */
    int updateByPrimaryKey(DBRolePermissions record);
}


text:
package passGen;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.image.ImageView;

public class Pass extends Application {
	int inputLength = 0; // To store the integer value of the password length
	private TextField tfPassLength = new TextField();

	@SuppressWarnings("static-access")
	@Override
	public void start(Stage primaryStage) throws Exception {

		Image lock = new Image(getClass().getResourceAsStream("../resources/icons/ic_lock.png"));
		Image copy = new Image(getClass().getResourceAsStream("../resources/icons/ic_copy.png"));
		TextField tfPassword = new TextField();
		tfPassword.setEditable(false);

                //Generate Button
		Button btGenerate = new Button("Generate");
                btGenerate.setPrefWidth(100);

                Button btCopy = new Button("", new ImageView(copy));

		CheckBox chSpecChar = new CheckBox("Special Characters");
		CheckBox chInWords = new CheckBox("Include Words");
		CheckBox chWordOnly = new CheckBox("Words Only");

		VBox checkList = new VBox(8);
		checkList.getChildren().addAll(chSpecChar, chInWords, chWordOnly);

		HBox PassLengthBox = new HBox(8), PasswordBox = new HBox(8);

                //Password Length Box
                Label lblPassLength = new Label("Password Length:");
                lblPassLength.setPrefWidth(150);
                lblPassLength.setAlignment(Pos.BASELINE_RIGHT);
                PassLengthBox.getChildren().addAll(lblPassLength, tfPassLength);
		PassLengthBox.setAlignment(Pos.CENTER_RIGHT);

                //Password Box
                Label lblPassBox = new Label("Password:");
                lblPassBox.setPrefWidth(150);
                lblPassBox.setAlignment(Pos.BASELINE_RIGHT);
		PasswordBox.getChildren().addAll(lblPassBox, tfPassword);
		PasswordBox.setAlignment(Pos.CENTER_RIGHT);
                PasswordBox.setPrefWidth(100);

		GridPane gPane = new GridPane();
		gPane.add(PassLengthBox, 0, 0); //... col, row);
		gPane.add(PasswordBox, 0, 1);
		gPane.add(btCopy, 1, 1);
		gPane.add(checkList, 0, 2);
		gPane.add(btGenerate, 1, 2);

		btCopy.setDisable(true);
		btGenerate.setDisable(true);
		tfPassLength.setOnKeyReleased(e ->{
			try {
		        // Get the password length from the text field
				if(Integer.parseInt(tfPassLength.getText()) >= 4){
					tfPassLength.setStyle("");
					inputLength = Integer.parseInt(tfPassLength.getText());
			        btGenerate.setDisable(false);
				}
				else if(Integer.parseInt(tfPassLength.getText()) < 4 || tfPassLength.getText().equals("")){
					btGenerate.setDisable(true);
					tfPassLength.setStyle("-fx-control-inner-background:#ffcdd2");
				}
		    }
			catch (NumberFormatException ex) {
			    // generic exception handling
			    ex.printStackTrace();
			}
		});

		chSpecChar.setOnAction(e -> {
			if(chSpecChar.isSelected() == true){
				chWordOnly.setDisable(true);
			}
			else if(chSpecChar.isSelected() == false && chInWords.isSelected() == false){
				chWordOnly.setDisable(false);
			}
		});
		chInWords.setOnAction(e -> {
			if(chInWords.isSelected() == true){
				chWordOnly.setDisable(true);
			}
			else if(chSpecChar.isSelected() == false && chInWords.isSelected() == false){
				chWordOnly.setDisable(false);
			}
		});
		chWordOnly.setOnAction(e -> {
			if(chWordOnly.isSelected() == true){
				chSpecChar.setDisable(true);
				chInWords.setDisable(true);
			}
			else{
				chSpecChar.setDisable(false);
				chInWords.setDisable(false);
			}
		});

		btGenerate.setOnAction(e -> {

			if(chInWords.isSelected() == false && chSpecChar.isSelected() == false && chWordOnly.isSelected() == false){
				new Password(inputLength, 0);
				tfPassword.setText(Password.getPassword());
				btCopy.setDisable(false);
			}
			else if(chSpecChar.isSelected() == true){
				new Password(inputLength, 1);
				tfPassword.setText(Password.getPassword());
				btCopy.setDisable(false);
			}
			else if(chInWords.isSelected() == true){
				// Generate type
			}
			else if(chInWords.isSelected() == true && chSpecChar.isSelected() == true){
				// Generate type
			}
			else if(chWordOnly.isSelected() == true){
				// Generate type
			}
		});

		btCopy.setOnAction(e -> Password.getCopy());

		//gPane.setGridLinesVisible(true);// Debugging

		AnchorPane mainPane = new AnchorPane();
		mainPane.setTopAnchor(gPane, 10.0);
		mainPane.setLeftAnchor(gPane, 10.0);
		mainPane.setRightAnchor(gPane, 10.0);
		mainPane.setRightAnchor(gPane, 10.0);
		mainPane.getChildren().add(gPane);

		Scene scene = new Scene(mainPane, 450, 150); // w x h
		primaryStage.setTitle("Password Generator"); // Set the stage(window) title
		primaryStage.getIcons().add(lock);
		scene.getStylesheets().add("/resources/style.css");
		primaryStage.setScene(scene); // Place the scene in the stage(window)
		primaryStage.setResizable(false);
		primaryStage.show(); // Display the stage(window)

	}

	public static void main(String[] args) {

		launch(args);
	}

	public static class Password {
		final static Clipboard clipboard = Clipboard.getSystemClipboard();
        final static ClipboardContent content = new ClipboardContent();
		CharGen characters = new CharGen();
		WordGen words = new WordGen();
		private  static String password;

		Password(){
		}

		Password(int length, int type){
			switch(type){
			case 0: // Get a string of characters with special characters included
				characters.setLength(length);
				setPassword(characters.getWithoutSpec());
				break;
			case 1: // Get a string of characters with no special characters included
				characters.setLength(length);
				setPassword(characters.getAllCharacters());
				break;

			}
		}

		public static String getPassword() {
			return password;
		}

		public void setPassword(String password) {
			this.password = password;

		}

		public static void getCopy() {
	        content.putString(getPassword());
	        clipboard.setContent(content);
		}
	}
}


text:
<tomcat-users>
    <user username="admin" password="admin" roles="manager-gui,manager-status"/>
</tomcat-users>


text:
<?php

namespace eq\datatypes;

class Mongoid extends Str
{

    public static function validate($value)
    {
        if(is_object($value) && $value instanceof \MongoId)
            return true;
        if(is_string($value) && preg_match('/^[a-z0-9]{24,24}$/', $value))
            return true;
        return false;
    }

    public static function filter($value)
    {
        return preg_replace('[^a-z0-9]', '', $value);
    }

    public static function toDb($value)
    {
        return is_object($value) && $value instanceof \MongoId ? $value : new \MongoId($value);
    }

}


text:
![aws-vpc-vpn](https://raw.githubusercontent.com/WrathOfChris/ops/master/aws-vpc-vpn/examples/aws-vpc-vpn.png)

### Build AMI images for the NAT-HUB, VPN-HUB, and NAT-VPN
- Change the vpn.hub address in group_vars/all to an ElasticIP you own.
- Change the apps.vpn-hub.address in examples/example-hub.json

```
./build.sh nat-hub all us-west-2
./build.sh vpn-hub all us-west-2
./build.sh nat-vpn all us-west-2
```

### Use cloudcaster to deploy HUB VPC and client VPC
Change the keypair names in:

- group_vars/all
- examples/example-hub.json
- examples/example-client.json

```
../cloudcaster/cloudcaster.py examples/example-hub.json
../cloudcaster/cloudcaster.py examples/example-client.json
```


text:
var Backbone = require('backbone')
    , _ = require('underscore')
    , Garam = require('../../Garam')
    ,  Cluster = require('cluster')
    , Base = require('../../Base')
    , assert = require('assert')
    , fs = require('fs')
    , async = require('async');

var DBlib = function(namespace) {
    this.namespace = namespace;
    this.sql_list = {};
};
module.exports =  DBlib;
_.extend(DBlib.prototype, Base.prototype, {
    addSQL : function(sql) {
        assert(sql.dpname);

        var db =    Garam.getDB(this.namespace);

        db.addProcedure(sql.dpname,sql);
        sql.create();

    },
    create : function(model_dir) {
        var self = this;
        var namespace = this.namespace;
        this.appDir = Garam.getInstance().get('appDir');
        this._sql = {};

        if(!fs.existsSync(this.appDir + '/model')) {
            Garam.getInstance().log.info(this.appDir + '/db make db dir');
            fs.mkdirSync(this,appDir + '/model');
        }

        if(!fs.existsSync(this.appDir + '/model/' + namespace)){
            Garam.getInstance().log.info(this.appDir + '/db/' + namespace + 'make model dir');
            fs.mkdirSync(this.appDir + '/model/' + namespace);
        }

        var dir = process.cwd()+'/'+ this.appDir + '/model/'+namespace;
        var list = fs.readdirSync(dir);
        var total =list.length;

        if(total === 0){
            Garam.getInstance().log.error('Procedure Factory is empty',namespace);
            Garam.getInstance().emit('completeWork',namespace);
            Garam.getInstance().emit('databaseOnReady',namespace);
            return;
        }

        list.forEach(function (file,i) {
            (function(job) {
                var stats = fs.statSync(dir + '/'+ file);
                if (stats.isFile()) {
                    var sql = require(dir + '/'+  file);
                    var t = new sql();

                    if(!t.dpname) {
                        Garam.getInstance().log.error(dir + '/'+  file+', dbname does not exist');
                        return;
                    }
                    self.addSQL(t);
                    if (total === (job+1)) {
                        Garam.getInstance().emit('completeWork',namespace);
                        Garam.getInstance().emit('databaseOnReady',namespace);
                    }

                } else {
                    read(file,function () {
                        if (total === (job+1)) {
                            Garam.getInstance().emit('completeWork',namespace);
                            Garam.getInstance().emit('databaseOnReady',namespace);
                        }
                    });
                }
            })(i);

            // var stats = fs.statSync(dir + '/'+ file);
            // if (stats.isFile()) {
            //     var sql = require(dir + '/'+  file);
            //     var t = new sql();
            //
            //     if(!t.dpname) {
            //         Garam.getInstance().log.error(dir + '/'+  file+', dbname does not exist');
            //         return;
            //     }
            //     self.addSQL(t);
            //
            // }
            // if (total === (i+1)) {
            //
            //     Garam.getInstance().emit('completeWork',namespace);
            //     Garam.getInstance().emit('databaseOnReady',namespace);
            // }
        });

        function read(folderName,callback) {
            var subDir = dir+'/'+folderName;
            var list = fs.readdirSync(subDir);
            var total = list.length,Transaction;
            if (list.length > 0) {
                list.forEach(function (file,i) {
                    (function (job) {
                        var stats = fs.statSync(subDir + '/'+ file);
                        if (stats.isFile()) {
                            var sql = require(subDir + '/'+ file);
                            var t = new sql();

                            if(!t.dpname) {
                                Garam.getInstance().log.error(dir + '/'+  file+', dbname does not exist');
                                return;
                            }
                            self.addSQL(t);
                            if (total === (job+1)) {

                                callback();

                            }

                        } else {
                            assert(0);
                        }
                    })(i);
                });
            }
        }

    }
});

DBlib.extend = Garam.extend;


text:
var StatsD = require('node-statsd').StatsD;

var Client = require('./client');
var Server = require('./server');
var ClientProxy = require('./client.proxy');
var ServerProxy = require('./server.proxy');
var ClientClusterProxy = require('./client.cluster.proxy');
var ServerClusterProxy = require('./server.cluster.proxy');
var logger = require('./logger');

var server;
var serverProxy;
var clientProxy;
var client;

/**
 * Converts input stats estructure to the internal structure. In converts from:
 *    name: [{path: '', methods: []}]
 *
 * To:
 *    path: { methods: [], name: ''}
 *
 * It also supports the following format:
 *
 *   name: {path: '', method: ''}
 */
function generateStatsdRoutes(stats) {
  var result = {};
  Object.keys(stats).forEach(function(name) {
    var routes = stats[name];
    if (!(routes instanceof Array)) {
      routes = [routes];
    }
    routes.forEach(function(route) {
      result[route.path] = {
        name: name,
        methods: route.method ? route.method : route.methods
      };
    });

  });
  return result;
}

function initServer(port, isCluster, statsdConfig, influxdbConfig) {
  var statsd = null;
  var statsdRoutes = null;

  if (statsdConfig) {
    if (statsdConfig.instance) {
      statsd = statsdConfig.instance;
    } else {
      statsd = new StatsD(statsdConfig.host, statsdConfig.port, statsdConfig.prefix);
      statsd.socket.on('error', function (error) {
        logger.error('Error sending stats: ', error);
      });
    }

    statsdRoutes = generateStatsdRoutes(statsdConfig.routes);
  }

  server = new Server(port, statsd, statsdRoutes, influxdbConfig);

  serverProxy = isCluster ?
    new ServerClusterProxy(server) :
    new ServerProxy(server);

  return server;
}

function initClient(isCluster) {
  clientProxy = isCluster ?
    new ClientClusterProxy() :
    new ClientProxy(serverProxy);

  client = new Client(clientProxy);

  return client;
}

module.exports.init = function init(options) {
  server = null;
  serverProxy = null;
  clientProxy = null;
  client = null;

  if (!options.cluster && options.port) {
    initServer(options.port, false, options.statsd, options.influxdb);
  }

  return initClient(options.cluster);
};

module.exports.startServer = function startServer(port, statsdConfig) {
  return initServer(port, true, statsdConfig);
};

module.exports.getServer = function getServer() {
  return server;
};

module.exports.getClient = function getClient() {
  return client;
};


text:
#include "RenderPhase.h"

//#include <Data/Params.h>
//#include <Data/DataArray.h>

namespace Frame
{

	/*
bool CRenderPhase::Init(const Data::CParams& Desc, const CRenderPath& Owner)
{
	Name = PassName;

	CStrID ShaderID = Desc.Get(CStrID("Shader"), CStrID::Empty);
	if (ShaderID.IsValid())
	{
		Shader = RenderSrv->ShaderMgr.GetTypedResource(ShaderID);
		if (!Shader->IsLoaded()) FAIL;
	}

	//!!!DUPLICATE CODE!+
	ShaderVars.BeginAdd();

	Data::CParam* pPrm;
	if (Desc.Get(pPrm, CStrID("ShaderVars")))
	{
		Data::CParams& Vars = *pPrm->GetValue<Data::PParams>();
		for (int i = 0; i < Vars.GetCount(); ++i)
		{
			Data::CParam& PrmVar = Vars.Get(i);
			CShaderVar& Var = ShaderVars.Add(PrmVar.GetName());
			Var.SetName(PrmVar.GetName());
			Var.Value = PrmVar.GetRawValue();
		}
	}

	if (Desc.Get(pPrm, CStrID("Textures")))
	{
		Data::CParams& Vars = *pPrm->GetValue<Data::PParams>();
		for (int i = 0; i < Vars.GetCount(); ++i)
		{
			Data::CParam& PrmVar = Vars.Get(i);
			CShaderVar& Var = ShaderVars.Add(PrmVar.GetName());
			Var.SetName(PrmVar.GetName());
			Var.Value = RenderSrv->TextureMgr.GetOrCreateTypedResource(CStrID(PrmVar.GetValue<CString>().CStr()));
		}
	}

	ShaderVars.EndAdd();
	//!!!DUPLICATE CODE!-

	Data::PDataArray RTNames;
	if (Desc.Get<Data::PDataArray>(RTNames, CStrID("RenderTargets")))
		for (int i = 0; i < RTNames->GetCount() && i < CRenderServer::MaxRenderTargetCount; ++i)
			RT[i] = RenderTargets[RTNames->At(i).GetValue<CStrID>()];

	ClearFlags = 0;

	if (Desc.Get(pPrm, CStrID("ClearColor")))
	{
		if (pPrm->IsA<int>()) ClearColor = pPrm->GetValue<int>();
		else if (pPrm->IsA<vector4>())
		{
			const vector4& Color = pPrm->GetValue<vector4>();
			ClearColor = N_COLORVALUE(Color.x, Color.y, Color.z, Color.w);
		}
		else Sys::Error("CRenderPhase::Init() -> Invalid type of ClearColor");
		ClearFlags |= Clear_Color;
	}

	if (Desc.Get(ClearDepth, CStrID("ClearDepth"))) ClearFlags |= Clear_Depth;

	int StencilVal;
	if (Desc.Get(StencilVal, CStrID("ClearStencil")))
	{
		ClearStencil = (U8)StencilVal;
		ClearFlags |= Clear_Stencil;
	}

	OK;

	FAIL;
}
//---------------------------------------------------------------------
	*/

}


text:
ALTER TABLE `logs` ADD COLUMN `level` ENUM('Info','Problem','Request','Suggestion','Urgent') NOT NULL DEFAULT 'Info' AFTER `state`;
UPDATE `logs` SET `level`='Info' WHERE `level_id`='1';
UPDATE `logs` SET `level`='Problem' WHERE `level_id`='2';
UPDATE `logs` SET `level`='Request' WHERE `level_id`='3';
UPDATE `logs` SET `level`='Suggestion' WHERE `level_id`='4';
UPDATE `logs` SET `level`='Urgent' WHERE `level_id`='5';
ALTER TABLE `logs` DROP COLUMN `level_id`,
 DROP INDEX `level_id_fk`,
 DROP FOREIGN KEY `level_id_fk`;


text:
package com.oracle.xmlns.internal.webservices.jaxws_databinding;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.lang.annotation.Annotation;

/**
 * This file was generated by JAXB-RI v2.2.6 and afterwards modified
 * to implement appropriate Annotation
 *
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "oneway")
public class XmlOneway implements javax.jws.Oneway {

    @Override
    public Class<? extends Annotation> annotationType() {
        return javax.jws.Oneway.class;
    }
}