text:
using namespace std;

//----------------------------------------------------------------------
// Constructors:
//----------------------------------------------------------------------

//----------------------------------------------------------------------
TableFunction::TableFunction() {
  mappingTable = NULL;
  deleteMappingTable();
  interpolation_model = 5;
};

//----------------------------------------------------------------------
TableFunction::TableFunction(string filename) {
  mappingTable = NULL;
  loadMappingTableFromFile(filename);
  interpolation_model = 5;
};

//----------------------------------------------------------------------
TableFunction::TableFunction(Table& tab) {
  mappingTable = new Table(tab);
  interpolation_model = 5;
};

//----------------------------------------------------------------------
TableFunction::~TableFunction() { deleteMappingTable(); };

//----------------------------------------------------------------------
bool TableFunction::isMappingTableLoaded() {return mappingTable;};

//----------------------------------------------------------------------
void TableFunction::deleteMappingTable()
// Release memory and set variables to initial values.
{
  if (isMappingTableLoaded()) delete mappingTable;
  mappingTable = NULL;
}

//----------------------------------------------------------------------
void TableFunction::loadMappingTableFromFile(string mappingTable_filename)
// The TableFunction mappingTable file (mappingTable_filename) is assumed to be a n-column file:
{
  // delete old mappingTable first
  deleteMappingTable();
  // get new ones
  mappingTable = new Table;
  mappingTable->loadTableFromFile(mappingTable_filename);
};

//----------------------------------------------------------------------
void TableFunction::setMappingTable(long i, double x, double y)
// The pair (x,y) is set to the i-th row of the table. i starts from 1.
{
  if(!isMappingTableLoaded()) mappingTable = new Table;
  mappingTable->set(1,i,x);
  mappingTable->set(2,i,y);
}

//----------------------------------------------------------------------
void TableFunction::resetMappingTable(long i, double defaultValue)
// Reset the table to have i rows, and all filled with defaultValue.
{
  deleteMappingTable();
  mappingTable = new Table(2,i,defaultValue);
}

//----------------------------------------------------------------------
double TableFunction::map(double x)
// Return the value of function at x
// -- x: input value
// -- mode: used in interpolation. 1: linear direct, 2: linear mono
//   5: cubic direct, 6: cubic mono
{
  if (isMappingTableLoaded())
  {
    return mappingTable->interp(1,2,x,interpolation_model);
  }
  else
  {
    cout << "TableFunction::map error: no mappingTable loaded." << endl;
  }
  return 0;
}

//----------------------------------------------------------------------
double TableFunction::invert(double y)
// Return the inverse value of y
//
{
  if (isMappingTableLoaded())
  {
    return mappingTable->invert(1,2,y,interpolation_model);
  }
  else
  {
    cout << "TableFunction::invert error: no mappingTable loaded." << endl;
  }
  return 0;
}

//----------------------------------------------------------------------
// Return X and Y vectors
//----------------------------------------------------------------------
vector<double>* TableFunction::getX() {return mappingTable->getColumn(1);}
vector<double>* TableFunction::getY() {return mappingTable->getColumn(2);}

//----------------------------------------------------------------------
void TableFunction::printFunction(ostream& os) { mappingTable->printTable(os); }

//----------------------------------------------------------------------
// Return info
double TableFunction::getXMin() { return mappingTable->getFirst(1); }
double TableFunction::getXMax() { return mappingTable->getLast(1); }
double TableFunction::getYMin() { return mappingTable->getFirst(2); }
double TableFunction::getYMax() { return mappingTable->getLast(2); }
long TableFunction::getNumberOfRows() { return mappingTable->getNumberOfRows(); }


text:
<?php
namespace ProjectRena\Task\Cronjobs;

use ProjectRena\RenaApp;

/**
 * Takes API Keys and checks them for accessmask, and a few other things
 */
class apiKeyCheckerCronjob
{

    /**
     * @param $pid
     * @param $md5
     */
    public static function execute($pid, $md5)
    {
        /** @var RenaApp $app */
        $app = RenaApp::getInstance();
        if ($app->Storage->get("Api904") >= date("Y-m-d H:i:s"))
            return;

        $apiKeys = $app->Db->query("SELECT keyID, vCode FROM apiKeys WHERE lastValidation < date_sub(now(), INTERVAL 6 HOUR) ORDER BY lastValidation DESC LIMIT 500", array(), 0);
        if ($apiKeys) {
            foreach ($apiKeys as $api) {
                $keyID = $api["keyID"];
                $vCode = $api["vCode"];
                // Update the lastValidation to in ten minutes, just so we don't insert it again and again
                \Resque::enqueue("important", "\\ProjectRena\\Task\\Resque\\updateApiKeys", array("keyID" => $keyID, "vCode" => $vCode));
            }
        }
        exit();
    }

    /**
     * Defines how often the cronjob runs, every 1 second, every 60 seconds, every 86400 seconds, etc.
     */
    public static function getRunTimes()
    {
        return 60; // Never runs
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace Woopsa
{
    internal class CustomThreadPoolThread : IDisposable
    {
        public CustomThreadPoolThread(string threadName, ThreadPriority priority)
        {
            _startEvent = new AutoResetEvent(false);
            _terminateEvent = new ManualResetEvent(false);
            Priority = priority;
            _isIdle = true;
            ThreadName = threadName;
        }

        public void ExecuteUserWorkItem(WaitCallback callBack, object parameter = null)
        {
            if (_isIdle)
            {
                _isIdle = false;
                if (_thread == null)
                {
                    _thread = new Thread(Execute);
                    _thread.Priority = Priority;
                    _thread.Name = ThreadName;
                    _thread.Start();
                }
                _callBack = callBack;
                _parameter = parameter;
                _startEvent.Set();
            }
            else
                throw new Exception("Cannot execute user work item on a busy CustomThreadPoolThread");
        }
        public void Terminate()
        {
            _terminateEvent.Set();
        }

        public bool Join(TimeSpan timeout)
        {
            return _thread.Join(timeout);
        }

        public bool IsIdle { get { return _isIdle; } }

        public event EventHandler Idle;

        public ThreadPriority Priority { get; private set; }
        public string ThreadName { get; private set; }

        private void OnIdle()
        {
            _isIdle = true;
            if (Idle != null)
                Idle(this, new EventArgs());
        }
        private void Execute()
        {
            for (;;)
            {
                try
                {
                    int index = WaitHandle.WaitAny(new WaitHandle[] { _terminateEvent, _startEvent });
                    if (index == 0) // _terminateEvent
                        break;
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
                _callBack(_parameter);
                OnIdle();
            }
        }

        public void Dispose()
        {
            Terminate();
            _thread.Join();
            _startEvent.Dispose();
            _terminateEvent.Dispose();
        }

        bool _isIdle;
        Thread _thread;
        AutoResetEvent _startEvent;
        ManualResetEvent _terminateEvent;
        WaitCallback _callBack;
        object _parameter;
    }
    public class CustomThreadPool : IDisposable
    {
        public const int DefaultThreadPoolSize = -1; // Use the operating system default value
        public CustomThreadPool(string name, int threadPoolSize = DefaultThreadPoolSize, ThreadPriority priority = ThreadPriority.Normal)
        {
            if (threadPoolSize == DefaultThreadPoolSize)
            {
                int n;
                ThreadPool.GetMaxThreads(out _threadPoolSize, out n);
            }
            else
            {
                Debug.Assert(threadPoolSize > 0);
                _threadPoolSize = threadPoolSize;
            }
            _threads = new List<CustomThreadPoolThread>();
            _semaphore = new Semaphore(_threadPoolSize, _threadPoolSize);
            Priority = priority;
            Name = name;
        }

        public ThreadPriority Priority { get; private set; }
        public string Name { get; private set; }

        public bool StartUserWorkItem(WaitCallback callBack, object parameter, TimeSpan timeout)
        {
            CustomThreadPoolThread thread = GetNextIdleThread(timeout);
            if (thread != null)
                thread.ExecuteUserWorkItem(callBack, parameter);
            return thread != null;
        }

        public bool StartUserWorkItem(WaitCallback callBack, object parameter = null)
        {
            return StartUserWorkItem(callBack, parameter, InfiniteTimeSpan);
        }

        public bool StartUserWorkItem(WaitCallback callBack, TimeSpan timeout)
        {
            return StartUserWorkItem(callBack, null, timeout);
        }

        private void OnIdle(object sender, EventArgs e)
        {
            _semaphore.Release();
        }
        private CustomThreadPoolThread GetNextIdleThread(TimeSpan timeout)
        {
            if (_semaphore.WaitOne(timeout))
            {
                lock (_threads)
                {
                    if (_aborting)
                        return null;
                    CustomThreadPoolThread thread = null;
                    foreach (var item in _threads)
                        if (item.IsIdle)
                        {
                            thread = item;
                            break;
                        }
                    if (thread == null)
                    {
                        Debug.Assert(_threads.Count <= _threadPoolSize);
                        _lastThreadIndex++;
                        thread = new CustomThreadPoolThread(Name + _lastThreadIndex.ToString(), Priority);
                        thread.Idle += OnIdle;
                        _threads.Add(thread);
                    }
                    return thread;
                }
            }
            else
                return null;
        }

        public void Terminate()
        {
            lock (_threads)
            {
                _aborting = true;
                foreach (var item in _threads)
                {
                    item.Terminate();
                }
            }
        }

        public bool Join(TimeSpan timeout)
        {
            DateTime waitStart = DateTime.Now;
            CustomThreadPoolThread[] threads;
            lock (_threads)
                threads = _threads.ToArray();
            _aborting = true;
            foreach (var item in threads)
            {
                TimeSpan remaining;
                if (timeout != InfiniteTimeSpan)
                {
                    TimeSpan elapsed = DateTime.Now - waitStart;
                    remaining = timeout - elapsed;
                    if (remaining < TimeSpan.Zero)
                        remaining = TimeSpan.Zero;
                }
                else
                    remaining = InfiniteTimeSpan;
                if (!item.Join(remaining))
                    return false;
            }

            return true;
        }
        public void Join()
        {
            Join(InfiniteTimeSpan);
        }

        #region IDisposable
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                Terminate();
                foreach (var item in _threads)
                {
                    item.Dispose();
                }
                _semaphore.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        private int _lastThreadIndex;
        private List<CustomThreadPoolThread> _threads;
        private Semaphore _semaphore;
        private bool _aborting;
        private int _threadPoolSize;

        static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, Timeout.Infinite);

    }
}


text:
require 'eventmachine'

module SockJS
  class DelayedResponseBody
    include EventMachine::Deferrable

    attr_accessor :session

    def initialize
      @status = :created
    end

    def call(body)
      body.each do |chunk|
        self.write(chunk)
      end
    end

    def write(chunk)
      unless @status == :open
        raise "Body isn't open (status: #{@status}, trying to write #{chunk.inspect})"
      end

      unless chunk.respond_to?(:bytesize)
        raise "Chunk is supposed to respond to #bytesize, but it doesn't.\nChunk: #{chunk.inspect} (#{chunk.class})"
      end

      SockJS.debug "body#write #{chunk.inspect}"

      self.write_chunk(chunk)
    end

    def each(&block)
      SockJS.debug "Opening the response."
      @status = :open
      @body_callback = block
    end

    def succeed(from_server = true)
      SockJS.debug "Closing the response."
      if $DEBUG and false
        SockJS.debug caller[0..-8].map { |item| item.sub(Dir.pwd + "/lib/", "") }.inspect
      end

      @status = :closed
      super
    end

    def finish(data = nil)
      if @status == :closed
        raise "Body is already closed!"
      end

      self.write(data) if data

      self.succeed(true)
    end

    def closed?
      @status == :closed
    end

    protected
    def write_chunk(chunk)
      self.__write__(chunk)
    end

    def __write__(data)
      SockJS.debug "Data to client %% #{data.inspect}"
      @body_callback.call(data)
    end
  end

  # https://github.com/rack/rack/blob/master/lib/rack/chunked.rb
  class DelayedResponseChunkedBody < DelayedResponseBody
    TERM ||= "\r\n"
    TAIL ||= "0#{TERM}#{TERM}"

    def finish(data = nil)
      if @status == :closed
        raise "Body is already closed!"
      end

      self.write(data) if data
      self.__write__(TAIL)

      self.succeed(true)
    end

    protected
    def write_chunk(chunk)
      data = [chunk.bytesize.to_s(16), TERM, chunk, TERM].join
      self.__write__(data)
    end
  end
end


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['checkingsourcetables'] = 'İlkin cədvəl strukturunun yoxlanması';
$string['copyingtable'] = '{$a} cədvəlinin köçürülməsi';
$string['copyingtables'] = 'Cədvəl məzmununun köçürülməsi';
$string['creatingtargettables'] = 'Hədəf verilənlər bazasında cədvəlin yaradılması';
$string['dbexport'] = 'Verilənlər bazasının eksportu';
$string['dbtransfer'] = 'Verilənlər bazasının ötürülməsi';
$string['differenttableexception'] = '{$a} cədvəlinin strukturu uyğun gəlmir';
$string['done'] = 'Yerinə yetirildi';
$string['exportschemaexception'] = 'Cari verilənlər bazasının strukturu bütün install.xml.-daki fayllarla uyğün gəlmir.
 {$a}';
$string['importschemaexception'] = 'Cari verilənlər bazasının strukturu bütün install.xml.-daki fayllarla uyğün gəlmir.
 {$a}';
$string['importversionmismatchexception'] = '{$a->currentver}  cari versiyası eksport olunmuş {$a->schemaver} versiyayla uyğun gəlmir.';
$string['malformedxmlexception'] = 'XML düzgün deyil, davam etmək mümkün olmadı';
$string['unknowntableexception'] = 'Eksport faylında naməlum {$a} cədvəli aşkarlanmışdır';


text:
NS_ASSUME_NONNULL_BEGIN

@interface _LNWeakRef : NSObject

@property (nonatomic, weak) id object;

+ (instancetype)refWithObject:(id)object;

@end

NS_ASSUME_NONNULL_END


text:
id: redis-cache
title: "Druid Redis Cache"
---

<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

To use this Apache Druid extension, make sure to [include](../../development/extensions.md#loading-extensions) `druid-redis-cache` extension.

A cache implementation for Druid based on [Redis](https://github.com/antirez/redis).

Below are the configuration options known to this module.

Note that just adding these properties does not enable the cache. You still need to add the `druid.<process-type>.cache.useCache` and `druid.<process-type>.cache.populateCache` properties for the processes you want to enable the cache on as described in the [cache configuration docs](../../configuration/index.html#cache-configuration).

A possible configuration would be to keep the properties below in your `common.runtime.properties` file (present on all processes) and then add `druid.<nodetype>.cache.useCache` and `druid.<nodetype>.cache.populateCache` in the `runtime.properties` file of the process types you want to enable caching on.

## Configuration

|`common.runtime.properties`|Description|Default|Required|
|--------------------|-----------|-------|--------|
|`druid.cache.host`|Redis server host|None|yes|
|`druid.cache.port`|Redis server port|None|yes|
|`druid.cache.expiration`|Expiration(in milliseconds) for cache entries|24 * 3600 * 1000|no|
|`druid.cache.timeout`|Timeout(in milliseconds) for get cache entries from Redis|2000|no|
|`druid.cache.maxTotalConnections`|Max total connections to Redis|8|no|
|`druid.cache.maxIdleConnections`|Max idle connections to Redis|8|no|
|`druid.cache.minIdleConnections`|Min idle connections to Redis|0|no|

## Enabling

To enable the redis cache, include this module on the loadList and set `druid.cache.type` to `redis` in your properties.

## Metrics

In addition to the normal cache metrics, the redis cache implementation also reports the following in both `total` and `delta`

|Metric|Description|Normal value|
|------|-----------|------------|
|`query/cache/redis/*/requests`|Count of requests to redis cache|whatever request to redis will increase request count by 1|


text:
require 'notifyor/util/os_analyzer'
module Notifyor
  module Growl
    extend self

    def adapter
      return @adapter if @adapter
      self.adapter =
          case ::Notifyor::Util::OSAnalyzer.os
            when :macosx
              :terminal_notifier
            when :linux
              :libnotify_notifier
            when :unix
              :libnotify_notifier
            else
              raise 'Operating system not recognized.'
          end
      @adapter
    end

    def adapter=(adapter_name)
      case adapter_name
        when Symbol, String
          require "notifyor/growl/adapters/#{adapter_name}"
          @adapter = Notifyor::Growl::Adapters.const_get("#{adapter_name.to_s.split('_').collect(&:capitalize).join}")
        else
          raise "Missing adapter #{adapter_name}"
      end
    end

    def create_growl(title, message)
      adapter.create_growl(title, message)
    end

  end
end


text:
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports TestHelper

Namespace BasicAnalyzers.Test
    <TestClass>
    Public Class CompilationStartedAnalyzerUnitTests
        Inherits DiagnosticVerifier
        <TestMethod>
        Public Sub Test1()
            Dim test = "
Namespace MyInterfaces
	Public Interface [Interface]
	End Interface

	Class MyInterfaceImpl
		Implements [Interface]
	End Class

	Class MyInterfaceImpl2
		Implements [Interface]
	End Class
End Namespace"
            Dim expected = New DiagnosticResult() With {
                .Id = DiagnosticIds.CompilationStartedAnalyzerRuleId,
                .Message = String.Format(My.Resources.CompilationStartedAnalyzerMessageFormat, "MyInterfaceImpl2", CompilationStartedAnalyzer.DontInheritInterfaceTypeName),
                .Severity = DiagnosticSeverity.Warning,
                .Locations = {New DiagnosticResultLocation("Test0.vb", 10, 8)}
            }

            VerifyBasicDiagnostic(test, expected)
        End Sub

        Protected Overrides Function GetBasicDiagnosticAnalyzer() As DiagnosticAnalyzer
            Return New CompilationStartedAnalyzer()
        End Function
    End Class
End Namespace


text:
class Profile < ActiveRecord::Base
  geocoded_by :full_address   # can also be an IP address
  after_validation :geocode #, if: ->(obj){ obj.full_address.present? and obj.full_address.changed? }

  acts_as_messageable
  acts_as_ordered_taggable # Alias for acts_as_taggable_on :tags
  acts_as_ordered_taggable_on :skills, :interests

  validates :name, presence: true, on: [:create,:update]
  validates :street, presence: true, on: [:create,:update]
  validates :city, presence: true, on: [:create,:update]
  validates :state, presence: true, on: [:create,:update]
  validates :home_phone, presence: true, on: [:create,:update]
  validates :terms, presence: true, on: :create

  validates :email,
            :presence => true,
            :format => { :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/ ,
                         :message => 'Invalid e-mail! Please provide a valid e-mail address'},
            :on => [:create, :update]

  include PgSearch

  belongs_to :user
  has_one :job
  has_one :bio
  has_many :gigs
  has_one :experience
  has_one :schedule
  has_many :galleries

  has_many :availability

  pg_search_scope :profile_search, :against => [:first_name, :last_name]

  def mailboxer_name
    self.name
  end

  def mailboxer_email(object)
    self.email
  end

  #Returning the email address of the model if an email should be sent for this object (Message or Notification).
  #If no mail has to be sent, return nil.
  # def mailboxer_email(object)
  #   #Check if an email should be sent for that object
  #   #if true
  #   return "define_email@on_your.model"
  #   #if false
  #   #return nil
  # end
end


text:
package ru.mail.teamcity.ssh.web;

import jetbrains.buildServer.controllers.ActionErrors;
import jetbrains.buildServer.controllers.BaseController;
import jetbrains.buildServer.users.SUser;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import jetbrains.buildServer.web.openapi.WebControllerManager;
import jetbrains.buildServer.web.util.SessionUser;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.servlet.ModelAndView;
import ru.mail.teamcity.ssh.config.HostBean;
import ru.mail.teamcity.ssh.config.HostManager;
import ru.mail.teamcity.ssh.config.HostNotFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import java.util.HashMap;
import java.util.Map;

/**
 * User: g.chernyshev
 * Date: 11/05/15
 * Time: 10:22
 */
public class WebSshShellPage extends BaseController {

    @NotNull
    private final PluginDescriptor pluginDescriptor;

    public WebSshShellPage(
            @NotNull WebControllerManager webControllerManager,
            @NotNull PluginDescriptor pluginDescriptor
    ) {
        this.pluginDescriptor = pluginDescriptor;
        webControllerManager.registerController("/webSshShell.html", this);
    }

    @Nullable
    @Override
    protected ModelAndView doHandle(@NotNull HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse) {
        Map<String, Object> params = new HashMap<>();

        SUser user = SessionUser.getUser(httpServletRequest);
        HostBean host = null;
        ActionErrors errors = new ActionErrors();

        String id = httpServletRequest.getParameter("id");
        String ip = httpServletRequest.getParameter("ip");

        try {
            if ((id != null) && StringUtils.isNotEmpty(id)) {
                host = HostManager.load(user, id);
            } else if ((ip != null) && StringUtils.isNotEmpty(ip)) {
                host = HostManager.findHostByIp(user, ip);
            }
        } catch (JAXBException e) {
            e.printStackTrace();
            errors.addError("Xml error", "Looks, like you xml is invalid:" + e.getMessage());
        } catch (HostNotFoundException e) {
            e.printStackTrace();
            errors.addError("Host not found", "Can't get host! Please, check parameters 'id' or 'ip' are correct.");
        }

        params.put("bean", host);
        params.put("errors", errors);
        return new ModelAndView(pluginDescriptor.getPluginResourcesPath("webSshShell.jsp"), params);
    }
}


text:
class CVideoSourceManager :
	public CUnknown,
	public IDisplayVideoSourceManager
{
public:

	CVideoSourceManager(IDisplayLock* pLock, IDisplayVideoSink* pVideoSink);
	virtual ~CVideoSourceManager();

	// IUnknown implementation
	DECLARE_IUNKNOWN
	STDMETHODIMP NonDelegatingQueryInterface(REFIID, void**);

	void Cleanup();

	STDMETHOD(AddVideoSource)(IBaseFilter* pVMRFilter, IDisplayVideoSource** ppVidSrc);
	STDMETHOD(RemoveVideoSource)(IDisplayVideoSource* pVidSrc);
	STDMETHOD(GetVideoSourceCount)(LONG* plCount);
	STDMETHOD(GetVideoSourceByIndex)(LONG lIndex, IDisplayVideoSource** ppVideoSource);

	STDMETHOD(BeginDeviceLoss)();
	STDMETHOD(EndDeviceLoss)(IUnknown* pDevice);

	void SetLock(IDisplayLock* pLock)
	{
		m_pLock = pLock;
	}

private:

	typedef std::vector<IDisplayVideoSource*> VideoSources;
	VideoSources m_videoSources;

	IDisplayVideoSink *m_pVideoSink;
	IDisplayLock *m_pLock;
};

#endif	// _VIDEOSOURCE_MGR_H


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

namespace BluetoothLE.Example.Models
{
	public class Grouping<K, T> : ObservableCollection<T>
	{
		public Grouping(K key) : base()
		{
			Key = key;
		}

		public Grouping(K key, IEnumerable<T> items) : base(items)
		{
			Key = key;
		}

		public K Key { get; private set; }
	}
}


text:
namespace Gtk {
	class Box;
	class ComboBoxText;
	class Overlay;
	class EventBox;
	class Image;
}
namespace Gdk {
	class Cursor;
}

namespace et {
namespace edit {

//---------------------------------
// EditorToolNode
//
// Node that contains a tool
//
class EditorToolNode final : public EditorNode
{
	// definitions
	//-------------
	RTTR_ENABLE(EditorNode)
	RTTR_REGISTRATION_FRIEND
	friend class EditorNodeHierachy;

	// construct destruct
	//--------------------
public:
	EditorToolNode() : EditorNode() {}
	EditorToolNode(EditorToolNode const& other);
	~EditorToolNode();

	// editor node interface
	//-----------------------
	bool IsLeaf() const override { return true; }
private:
	void InitInternal(EditorBase* const editor) override;

	// functionality
	//---------------
	void CreateTool();
public:
	void DestroyTool();
private:
	void CreateToolbar();
	void OnToolComboChanged();
	void AddToolbarContent();
	void ReorderToolbar();
public:
	void InitHierachyUI();

	// accessors
	//-----------
public:
	E_EditorTool GetType() const { return m_Type; }
	Gtk::Overlay* GetOverlay() const { return m_Overlay; }
	void SetFeedbackState(ToolNodeFeedback::E_State const state);
	ToolNodeFeedback& GetFeedback() { return m_Feedback; }
	EditorBase* GetEditor() const { return m_Editor; }

	// Data
	///////

private:
	// reflected
	E_EditorTool m_Type = E_EditorTool::Invalid;
	bool m_IsToolbarVisible = true;
	bool m_IsToolbarTop = false;

	// model
	std::unique_ptr<I_EditorTool> m_Tool;
	EditorBase* m_Editor = nullptr;

	Glib::RefPtr<Gio::SimpleActionGroup> m_ToolbarActionGroup;

	// ui
	Gtk::Overlay* m_Overlay = nullptr;

	Gtk::Box* m_Container = nullptr;

	Gtk::EventBox* m_ToolbarEventBox = nullptr;
	Gtk::Box* m_Toolbar = nullptr;
	Gtk::ComboBoxText* m_ToolSelector = nullptr;
	Gtk::Widget* m_ToolbarContent = nullptr;

	Gtk::Frame* m_InnerFrame = nullptr;

	Gtk::EventBox* m_ToolbarUnhide = nullptr;
	Gtk::Image* m_ToolbarUnhideImage = nullptr;
	bool m_MouseOverUnhide = false;
	Glib::RefPtr<Gdk::Cursor> m_CursorUnhide;

	ToolHierachyHandle m_Handle1;
	ToolHierachyHandle m_Handle2;

	ToolNodeFeedback m_Feedback;
};

} // namespace edit
} // namespace et


text:
package de.atomfrede.mate.application.wicket.footer;

import org.apache.wicket.markup.html.panel.Panel;

/**
* The default page footer.
*
* @author miha
* @version 1.0
*/
public class Footer extends Panel {

    /**
* Construct.
*
* @param markupId The components markup id.
*/
    public Footer(String markupId) {
        super(markupId);
    }

}


text:
import { Component, Input } from '@angular/core';

import { ExampleComponent } from '../example.component';

const template = `

Movable with handle

  Only the handle element can be used for moving.

  <button (click)="toggle = !toggle">toggle enabled state</button>

`;

@Component({
  selector: 'app-example2',
  template: template
})
export class Example2Component extends ExampleComponent {
  public template = template;

  @Input()
  public toggle = true;
}


text:
by [Evan Leong](https://gohighbrow.com/team/evan-leong/)

![Intro to iOS development](https://4cawmi2va33i3w6dek1d7y1m-wpengine.netdna-ssl.com/wp-content/uploads/2017/06/Technology_Intro-to-iOS-development_page-1024x384.png)

This course is for beginner developers who have an interest in developing iOS apps with Swift. Through the next 10 awesome emails, you'll learn the basic components of Swift, the language used to build iOS and macOS apps. We'll teach you core concepts through a series of analogies. Since these are digested through emails, this course is not intended to get you writing full-fledged programs with functional code, but rather, to introduce the concepts that will allow you to confidently dive nose first into learning iOS development and eventually build your own custom apps.

- [Episode 1](episode-01.md)
- [Episode 2](episode-02.md)
- [Episode 3](episode-03.md)
- [Episode 4](episode-04.md)
- [Episode 5](episode-05.md)
- [Episode 6](episode-06.md)
- [Episode 7](episode-07.md)
- [Episode 8](episode-08.md)
- [Episode 9](episode-09.md)
- [Episode 10](episode-10.md)


text:
import datetime
import os

from base64 import b64encode

import django.dispatch

from django.core.exceptions import ObjectDoesNotExist
from django.core.files.storage import default_storage as storage
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.functional import cached_property
from django.utils.translation import ugettext

import jinja2
import six
import waffle

from django_extensions.db.fields.json import JSONField
from django_statsd.clients import statsd

import olympia.core.logger

from olympia import activity, amo
from olympia.amo.decorators import use_primary_db
from olympia.amo.fields import PositiveAutoField
from olympia.amo.models import (
    BasePreview, ManagerBase, ModelBase, OnChangeMixin)
from olympia.amo.urlresolvers import reverse
from olympia.amo.utils import sorted_groupby, utc_millesecs_from_epoch
from olympia.applications.models import AppVersion
from olympia.constants.licenses import LICENSES_BY_BUILTIN
from olympia.files import utils
from olympia.files.models import File, cleanup_file
from olympia.translations.fields import (
    LinkifiedField, PurifiedField, TranslatedField, save_signal)

from .compare import version_dict, version_int

log = olympia.core.logger.getLogger('z.versions')

# Valid source extensions. Used in error messages to the user and to skip
# early in source_upload_path() if necessary, but the actual validation is
# more complex and done in olympia.devhub.WithSourceMixin.clean_source
VALID_SOURCE_EXTENSIONS = ('.zip', '.tar.gz', '.tar.bz2',)

class VersionManager(ManagerBase):

    def __init__(self, include_deleted=False):
        ManagerBase.__init__(self)
        self.include_deleted = include_deleted

    def get_queryset(self):
        qs = super(VersionManager, self).get_queryset()
        if not self.include_deleted:
            qs = qs.exclude(deleted=True)
        return qs.transform(Version.transformer)

    def valid(self):
        return self.filter(
            files__status__in=amo.VALID_FILE_STATUSES).distinct()

    def latest_public_compatible_with(self, application, appversions):
        """Return a queryset filtering the versions so that they are public,
        listed, and compatible with the application and appversions parameters
        passed. The queryset is ordered by creation date descending, allowing
        the caller to get the latest compatible version available.

        application is an application id
        appversions is a dict containing min and max values, as version ints.
        """
        return Version.objects.filter(
            apps__application=application,
            apps__min__version_int__lte=appversions['min'],
            apps__max__version_int__gte=appversions['max'],
            channel=amo.RELEASE_CHANNEL_LISTED,
            files__status=amo.STATUS_PUBLIC,
        ).order_by('-created')

def source_upload_path(instance, filename):
    # At this point we already know that ext is one of VALID_SOURCE_EXTENSIONS
    # because we already checked for that in
    # /src/olympia/devhub/forms.py#WithSourceMixin.clean_source.
    for ext in VALID_SOURCE_EXTENSIONS:
        if filename.endswith(ext):
            break

    return os.path.join(
        u'version_source',
        utils.id_to_path(instance.pk),
        u'{0}-{1}-src{2}'.format(
            instance.addon.slug,
            instance.version,
            ext)
    )

class VersionCreateError(ValueError):
    pass

@python_2_unicode_compatible
class Version(OnChangeMixin, ModelBase):
    id = PositiveAutoField(primary_key=True)
    addon = models.ForeignKey(
        'addons.Addon', related_name='versions', on_delete=models.CASCADE)
    license = models.ForeignKey('License', null=True)
    release_notes = PurifiedField(db_column='releasenotes')
    approval_notes = models.TextField(
        db_column='approvalnotes', default='', null=True)
    version = models.CharField(max_length=255, default='0.1')
    version_int = models.BigIntegerField(null=True, editable=False)

    nomination = models.DateTimeField(null=True)
    reviewed = models.DateTimeField(null=True)

    deleted = models.BooleanField(default=False)

    source = models.FileField(
        upload_to=source_upload_path, null=True, blank=True)

    channel = models.IntegerField(choices=amo.RELEASE_CHANNEL_CHOICES,
                                  default=amo.RELEASE_CHANNEL_LISTED)

    git_hash = models.CharField(max_length=40, blank=True)
    source_git_hash = models.CharField(max_length=40, blank=True)

    # The order of those managers is very important: please read the lengthy
    # comment above the Addon managers declaration/instantiation.
    unfiltered = VersionManager(include_deleted=True)
    objects = VersionManager()

    class Meta(ModelBase.Meta):
        db_table = 'versions'
        # This is very important: please read the lengthy comment in Addon.Meta
        # description
        base_manager_name = 'unfiltered'
        ordering = ['-created', '-modified']

    def __init__(self, *args, **kwargs):
        super(Version, self).__init__(*args, **kwargs)
        self.__dict__.update(version_dict(self.version or ''))

    def __str__(self):
        return jinja2.escape(self.version)

    def save(self, *args, **kw):
        if not self.version_int and self.version:
            v_int = version_int(self.version)
            # Magic number warning, this is the maximum size
            # of a big int in MySQL to prevent version_int overflow, for
            # people who have rather crazy version numbers.
            # http://dev.mysql.com/doc/refman/5.5/en/numeric-types.html
            if v_int < 9223372036854775807:
                self.version_int = v_int
            else:
                log.error('No version_int written for version %s, %s' %
                          (self.pk, self.version))
        super(Version, self).save(*args, **kw)
        return self

    @classmethod
    def from_upload(cls, upload, addon, selected_apps, channel,
                    parsed_data=None):
        """
        Create a Version instance and corresponding File(s) from a
        FileUpload, an Addon, a list of compatible app ids, a channel id and
        the parsed_data generated by parse_addon().

        Note that it's the caller's responsability to ensure the file is valid.
        We can't check for that here because an admin may have overridden the
        validation results.
        """
        assert parsed_data is not None

        if addon.status == amo.STATUS_DISABLED:
            raise VersionCreateError(
                'Addon is Mozilla Disabled; no new versions are allowed.')

        license_id = None
        if channel == amo.RELEASE_CHANNEL_LISTED:
            previous_version = addon.find_latest_version(
                channel=channel, exclude=())
            if previous_version and previous_version.license_id:
                license_id = previous_version.license_id
        approval_notes = None
        if parsed_data.get('is_mozilla_signed_extension'):
            approval_notes = (u'This version has been signed with '
                              u'Mozilla internal certificate.')
        version = cls.objects.create(
            addon=addon,
            approval_notes=approval_notes,
            version=parsed_data['version'],
            license_id=license_id,
            channel=channel,
        )
        log.info(
            'New version: %r (%s) from %r' % (version, version.id, upload))
        activity.log_create(amo.LOG.ADD_VERSION, version, addon)

        if addon.type == amo.ADDON_STATICTHEME:
            # We don't let developers select apps for static themes
            selected_apps = [app.id for app in amo.APP_USAGE]

        compatible_apps = {}
        for app in parsed_data.get('apps', []):
            if app.id not in selected_apps:
                # If the user chose to explicitly deselect Firefox for Android
                # we're not creating the respective `ApplicationsVersions`
                # which will have this add-on then be listed only for
                # Firefox specifically.
                continue

            compatible_apps[app.appdata] = ApplicationsVersions(
                version=version, min=app.min, max=app.max, application=app.id)
            compatible_apps[app.appdata].save()

        # See #2828: sometimes when we generate the filename(s) below, in
        # File.from_upload(), cache-machine is confused and has trouble
        # fetching the ApplicationsVersions that were just created. To work
        # around this we pre-generate version.compatible_apps and avoid the
        # queries completely.
        version._compatible_apps = compatible_apps

        # For backwards compatibility. We removed specific platform
        # support during submission but we don't handle it any different
        # beyond that yet. That means, we're going to simply set it
        # to `PLATFORM_ALL` and also have the backend create separate
        # files for each platform. Cleaning that up is another step.
        # Given the timing on this, we don't care about updates to legacy
        # add-ons as well.
        # Create relevant file and update the all_files cached property on the
        # Version, because we might need it afterwards.
        version.all_files = [File.from_upload(
            upload=upload, version=version, platform=amo.PLATFORM_ALL.id,
            parsed_data=parsed_data
        )]

        version.inherit_nomination(from_statuses=[amo.STATUS_AWAITING_REVIEW])
        version.disable_old_files()
        # After the upload has been copied to all platforms, remove the upload.
        storage.delete(upload.path)
        version_uploaded.send(sender=version)

        # Extract this version into git repository
        extract_version_to_git_repository(version, upload)

        # Generate a preview and icon for listed static themes
        if (addon.type == amo.ADDON_STATICTHEME and
                channel == amo.RELEASE_CHANNEL_LISTED):
            theme_data = parsed_data.get('theme', {})
            generate_static_theme_preview(theme_data, version.pk)

        # Track the time it took from first upload through validation
        # (and whatever else) until a version was created.
        upload_start = utc_millesecs_from_epoch(upload.created)
        now = datetime.datetime.now()
        now_ts = utc_millesecs_from_epoch(now)
        upload_time = now_ts - upload_start

        log.info('Time for version {version} creation from upload: {delta}; '
                 'created={created}; now={now}'
                 .format(delta=upload_time, version=version,
                         created=upload.created, now=now))
        statsd.timing('devhub.version_created_from_upload', upload_time)

        return version

    def license_url(self, impala=False):
        return reverse('addons.license', args=[self.addon.slug, self.version])

    def get_url_path(self):
        if self.channel == amo.RELEASE_CHANNEL_UNLISTED:
            return ''
        return reverse('addons.versions', args=[self.addon.slug, self.version])

    def delete(self, hard=False):
        # To avoid a circular import
        from .tasks import delete_preview_files

        log.info(u'Version deleted: %r (%s)' % (self, self.id))
        activity.log_create(amo.LOG.DELETE_VERSION, self.addon,
                            str(self.version))

        if hard:
            super(Version, self).delete()
        else:
            # By default we soft delete so we can keep the files for comparison
            # and a record of the version number.
            self.files.update(status=amo.STATUS_DISABLED)
            self.deleted = True
            self.save()

            previews_pks = list(
                VersionPreview.objects.filter(version__id=self.id)
                              .values_list('id', flat=True))

            for preview_pk in previews_pks:
                delete_preview_files.delay(preview_pk)

    @property
    def is_user_disabled(self):
        return self.files.filter(status=amo.STATUS_DISABLED).exclude(
            original_status=amo.STATUS_NULL).exists()

    @is_user_disabled.setter
    def is_user_disabled(self, disable):
        # User wants to disable (and the File isn't already).
        if disable:
            activity.log_create(amo.LOG.DISABLE_VERSION, self.addon, self)
            for file in self.files.exclude(status=amo.STATUS_DISABLED).all():
                file.update(original_status=file.status,
                            status=amo.STATUS_DISABLED)
        # User wants to re-enable (and user did the disable, not Mozilla).
        else:
            activity.log_create(amo.LOG.ENABLE_VERSION, self.addon, self)
            for file in self.files.exclude(
                    original_status=amo.STATUS_NULL).all():
                file.update(status=file.original_status,
                            original_status=amo.STATUS_NULL)

    @property
    def current_queue(self):
        """Return the current queue, or None if not in a queue."""
        from olympia.reviewers.models import (
            ViewFullReviewQueue, ViewPendingQueue)

        if self.channel == amo.RELEASE_CHANNEL_UNLISTED:
            # Unlisted add-ons and their updates are automatically approved so
            # they don't get a queue.
            # TODO: when we've finished with unlisted/listed versions the
            # status of an all-unlisted addon will be STATUS_NULL so we won't
            # need this check.
            return None

        if self.addon.status == amo.STATUS_NOMINATED:
            return ViewFullReviewQueue
        elif self.addon.status == amo.STATUS_PUBLIC:
            return ViewPendingQueue

        return None

    @cached_property
    def all_activity(self):
        from olympia.activity.models import VersionLog  # yucky
        al = (VersionLog.objects.filter(version=self.id).order_by('created')
              .select_related('activity_log', 'version'))
        return al

    @property
    def compatible_apps(self):
        # Dicts, search providers and personas don't have compatibility info.
        # Fake one for them.
        if self.addon and self.addon.type in amo.NO_COMPAT:
            return {app: None for app in amo.APP_TYPE_SUPPORT[self.addon.type]}
        # Otherwise, return _compatible_apps which is a cached property that
        # is filled by the transformer, or simply calculated from the related
        # compat instances.
        return self._compatible_apps

    @cached_property
    def _compatible_apps(self):
        """Get a mapping of {APP: ApplicationsVersions}."""
        avs = self.apps.select_related('version')
        return self._compat_map(avs)

    @cached_property
    def compatible_apps_ordered(self):
        apps = self.compatible_apps.items()
        return sorted(apps, key=lambda v: v[0].short)

    def compatible_platforms(self):
        """Returns a dict of compatible file platforms for this version.

        The result is based on which app(s) the version targets.
        """
        app_ids = [a.application for a in self.apps.all()]
        targets_mobile = amo.ANDROID.id in app_ids
        targets_other = any((id_ != amo.ANDROID.id) for id_ in app_ids)
        all_plats = {}
        if targets_other:
            all_plats.update(amo.DESKTOP_PLATFORMS)
        if targets_mobile:
            all_plats.update(amo.MOBILE_PLATFORMS)
        return all_plats

    @cached_property
    def is_compatible_by_default(self):
        """Returns whether or not the add-on is considered compatible by
        default."""
        # Use self.all_files directly since that's cached and more potentially
        # prefetched through a transformer already
        return not any([
            file for file in self.all_files
            if file.binary_components or file.strict_compatibility])

    def is_compatible_app(self, app):
        """Returns True if the provided app passes compatibility conditions."""
        if self.addon.type in amo.NO_COMPAT:
            return True
        appversion = self.compatible_apps.get(app)
        if appversion and app.id in amo.D2C_MIN_VERSIONS:
            return (version_int(appversion.max.version) >=
                    version_int(amo.D2C_MIN_VERSIONS.get(app.id, '*')))
        return False

    def compat_override_app_versions(self):
        """Returns the incompatible app versions range(s).

        If not ranges, returns empty list.  Otherwise, this will return all
        the app version ranges that this particular version is incompatible
        with.
        """
        overrides = list(self.addon.compatoverride_set.all())

        if not overrides:
            return []

        app_versions = []
        for co in overrides:
            for range in co.collapsed_ranges():
                if (version_int(range.min) <= version_int(self.version) <=
                        version_int(range.max)):
                    app_versions.extend([(a.min, a.max) for a in range.apps])
        return app_versions

    @cached_property
    def all_files(self):
        """Shortcut for list(self.files.all()). Cached."""
        return list(self.files.all())

    @property
    def current_file(self):
        """Shortcut for selecting the first file from self.all_files"""
        return self.all_files[0]

    @cached_property
    def supported_platforms(self):
        """Get a list of supported platform names."""
        return list(set(amo.PLATFORMS[f.platform] for f in self.all_files))

    @property
    def status(self):
        return [
            f.STATUS_CHOICES.get(f.status, ugettext('[status:%s]') % f.status)
            for f in self.all_files]

    @property
    def statuses(self):
        """Unadulterated statuses, good for an API."""
        return [(f.id, f.status) for f in self.all_files]

    def is_public(self):
        # To be public, a version must not be deleted, must belong to a public
        # addon, and all its attached files must have public status.
        try:
            return (not self.deleted and self.addon.is_public() and
                    all(f.status == amo.STATUS_PUBLIC for f in self.all_files))
        except ObjectDoesNotExist:
            return False

    @property
    def is_restart_required(self):
        return any(file_.is_restart_required for file_ in self.all_files)

    @property
    def is_webextension(self):
        return any(file_.is_webextension for file_ in self.all_files)

    @property
    def is_mozilla_signed(self):
        """Is the file a special "Mozilla Signed Extension"

        See https://wiki.mozilla.org/Add-ons/InternalSigning for more details.
        We use that information to workaround compatibility limits for legacy
        add-ons and to avoid them receiving negative boosts compared to
        WebExtensions.

        See https://github.com/mozilla/addons-server/issues/6424
        """
        return all(
            file_.is_mozilla_signed_extension for file_ in self.all_files)

    @property
    def has_files(self):
        return bool(self.all_files)

    @property
    def is_unreviewed(self):
        return bool(list(filter(
            lambda f: f.status in amo.UNREVIEWED_FILE_STATUSES, self.all_files
        )))

    @property
    def is_all_unreviewed(self):
        return not bool([f for f in self.all_files if f.status not in
                         amo.UNREVIEWED_FILE_STATUSES])

    @property
    def is_jetpack(self):
        return all(f.jetpack_version for f in self.all_files)

    @property
    def sources_provided(self):
        return bool(self.source)

    @classmethod
    def _compat_map(cls, avs):
        apps = {}
        for av in avs:
            app_id = av.application
            if app_id in amo.APP_IDS:
                apps[amo.APP_IDS[app_id]] = av
        return apps

    @classmethod
    def transformer(cls, versions):
        """Attach all the compatible apps and files to the versions."""
        if not versions:
            return

        ids = set(v.id for v in versions)
        avs = (ApplicationsVersions.objects.filter(version__in=ids)
               .select_related('min', 'max'))
        files = File.objects.filter(version__in=ids)

        def rollup(xs):
            groups = sorted_groupby(xs, 'version_id')
            return dict((k, list(vs)) for k, vs in groups)

        av_dict, file_dict = rollup(avs), rollup(files)

        for version in versions:
            v_id = version.id
            version._compatible_apps = cls._compat_map(av_dict.get(v_id, []))
            version.all_files = file_dict.get(v_id, [])
            for f in version.all_files:
                f.version = version

    @classmethod
    def transformer_activity(cls, versions):
        """Attach all the activity to the versions."""
        from olympia.activity.models import VersionLog  # yucky

        ids = set(v.id for v in versions)
        if not versions:
            return

        al = (VersionLog.objects.filter(version__in=ids).order_by('created')
              .select_related('activity_log', 'version'))

        def rollup(xs):
            groups = sorted_groupby(xs, 'version_id')
            return {k: list(vs) for k, vs in groups}

        al_dict = rollup(al)

        for version in versions:
            v_id = version.id
            version.all_activity = al_dict.get(v_id, [])

    def disable_old_files(self):
        """
        Disable files from versions older than the current one and awaiting
        review. Used when uploading a new version.

        Does nothing if the current instance is unlisted.
        """
        if self.channel == amo.RELEASE_CHANNEL_LISTED:
            qs = File.objects.filter(version__addon=self.addon_id,
                                     version__lt=self.id,
                                     version__deleted=False,
                                     status__in=[amo.STATUS_AWAITING_REVIEW,
                                                 amo.STATUS_PENDING])
            # Use File.update so signals are triggered.
            for f in qs:
                f.update(status=amo.STATUS_DISABLED)

    def reset_nomination_time(self, nomination=None):
        if not self.nomination or nomination:
            nomination = nomination or datetime.datetime.now()
            # We need signal=False not to call update_status (which calls us).
            self.update(nomination=nomination, _signal=False)

    def inherit_nomination(self, from_statuses=None):
        last_ver = (Version.objects.filter(addon=self.addon,
                                           channel=amo.RELEASE_CHANNEL_LISTED)
                    .exclude(nomination=None).exclude(id=self.pk)
                    .order_by('-nomination'))
        if from_statuses:
            last_ver = last_ver.filter(files__status__in=from_statuses)
        if last_ver.exists():
            self.reset_nomination_time(nomination=last_ver[0].nomination)

    @property
    def unreviewed_files(self):
        """A File is unreviewed if its status is amo.STATUS_AWAITING_REVIEW."""
        return self.files.filter(status=amo.STATUS_AWAITING_REVIEW)

    @property
    def is_ready_for_auto_approval(self):
        """Return whether or not this version could be *considered* for
        auto-approval.

        Does not necessarily mean that it would be auto-approved, just that it
        passes the most basic criteria to be considered a candidate by the
        auto_approve command."""
        return (
            self.addon.status in (amo.STATUS_PUBLIC, amo.STATUS_NOMINATED) and
            self.addon.type in (
                amo.ADDON_EXTENSION, amo.ADDON_LPAPP, amo.ADDON_DICT) and
            self.is_webextension and
            self.is_unreviewed and
            self.channel == amo.RELEASE_CHANNEL_LISTED)

    @property
    def was_auto_approved(self):
        """Return whether or not this version was auto-approved."""
        from olympia.reviewers.models import AutoApprovalSummary
        try:
            return self.is_public() and AutoApprovalSummary.objects.filter(
                version=self).get().verdict == amo.AUTO_APPROVED
        except AutoApprovalSummary.DoesNotExist:
            pass
        return False

    def get_background_images_encoded(self, header_only=False):
        if not self.has_files:
            return {}
        file_obj = self.all_files[0]
        return {
            name: b64encode(background)
            for name, background in utils.get_background_images(
                file_obj, theme_data=None, header_only=header_only).items()}

def generate_static_theme_preview(theme_data, version_pk):
    """This redirection is so we can mock generate_static_theme_preview, where
    needed, in tests."""
    # To avoid a circular import
    from . import tasks
    tasks.generate_static_theme_preview.delay(theme_data, version_pk)

def extract_version_to_git_repository(version, upload):
    """Extract and commit ``version`` into our git-storage backend."""
    from . import tasks
    if waffle.switch_is_active('enable-uploads-commit-to-git-storage'):
        tasks.extract_version_to_git.delay(
            version_id=version.pk,
            author_id=upload.user.pk if upload.user else None)

class VersionPreview(BasePreview, ModelBase):
    version = models.ForeignKey(Version, related_name='previews')
    position = models.IntegerField(default=0)
    sizes = JSONField(default={})
    colors = JSONField(default=None, null=True)
    media_folder = 'version-previews'

    class Meta:
        db_table = 'version_previews'
        ordering = ('position', 'created')

    @cached_property
    def caption(self):
        """We only don't support defining a caption for previews because
        they're auto-generated.  This is for compatibility with Addon Preview
        objects. (it's a cached_property so it can be set transparently)"""
        return None

models.signals.post_delete.connect(VersionPreview.delete_preview_files,
                                   sender=VersionPreview,
                                   dispatch_uid='delete_preview_files')

@use_primary_db
def update_status(sender, instance, **kw):
    if not kw.get('raw'):
        try:
            instance.addon.reload()
            instance.addon.update_status()
        except models.ObjectDoesNotExist:
            log.info('Got ObjectDoesNotExist processing Version change signal',
                     exc_info=True)
            pass

def inherit_nomination(sender, instance, **kw):
    """
    For new versions pending review, ensure nomination date
    is inherited from last nominated version.
    """
    if kw.get('raw'):
        return
    addon = instance.addon
    if (instance.nomination is None and
            addon.status in amo.UNREVIEWED_ADDON_STATUSES):
        instance.inherit_nomination()

def update_incompatible_versions(sender, instance, **kw):
    """
    When a new version is added or deleted, send to task to update if it
    matches any compat overrides.
    """
    try:
        if not instance.addon.type == amo.ADDON_EXTENSION:
            return
    except ObjectDoesNotExist:
        return

    from olympia.addons import tasks
    tasks.update_incompatible_appversions.delay([instance.id])

def cleanup_version(sender, instance, **kw):
    """On delete of the version object call the file delete and signals."""
    if kw.get('raw'):
        return
    for file_ in instance.files.all():
        cleanup_file(file_.__class__, file_)

def clear_compatversion_cache_on_save(sender, instance, created, **kw):
    """Clears compatversion cache if new Version created."""
    try:
        if not instance.addon.type == amo.ADDON_EXTENSION:
            return
    except ObjectDoesNotExist:
        return

    if not kw.get('raw') and (created or instance.deleted):
        instance.addon.invalidate_d2c_versions()

def clear_compatversion_cache_on_delete(sender, instance, **kw):
    """Clears compatversion cache when Version deleted."""
    try:
        if not instance.addon.type == amo.ADDON_EXTENSION:
            return
    except ObjectDoesNotExist:
        return

    if not kw.get('raw'):
        instance.addon.invalidate_d2c_versions()

version_uploaded = django.dispatch.Signal()
models.signals.pre_save.connect(
    save_signal, sender=Version, dispatch_uid='version_translations')
models.signals.post_save.connect(
    update_status, sender=Version, dispatch_uid='version_update_status')
models.signals.post_save.connect(
    inherit_nomination, sender=Version,
    dispatch_uid='version_inherit_nomination')
models.signals.post_save.connect(
    update_incompatible_versions, sender=Version,
    dispatch_uid='version_update_incompat')
models.signals.post_save.connect(
    clear_compatversion_cache_on_save, sender=Version,
    dispatch_uid='clear_compatversion_cache_save')

models.signals.pre_delete.connect(
    cleanup_version, sender=Version, dispatch_uid='cleanup_version')
models.signals.post_delete.connect(
    update_status, sender=Version, dispatch_uid='version_update_status')
models.signals.post_delete.connect(
    update_incompatible_versions, sender=Version,
    dispatch_uid='version_update_incompat')
models.signals.post_delete.connect(
    clear_compatversion_cache_on_delete, sender=Version,
    dispatch_uid='clear_compatversion_cache_del')

class LicenseManager(ManagerBase):
    def builtins(self, cc=False):
        return self.filter(
            builtin__gt=0, creative_commons=cc).order_by('builtin')

@python_2_unicode_compatible
class License(ModelBase):
    OTHER = 0

    id = PositiveAutoField(primary_key=True)
    name = TranslatedField()
    url = models.URLField(null=True)
    builtin = models.PositiveIntegerField(default=OTHER)
    text = LinkifiedField()
    on_form = models.BooleanField(
        default=False, help_text='Is this a license choice in the devhub?')
    some_rights = models.BooleanField(
        default=False,
        help_text='Show "Some Rights Reserved" instead of the license name?')
    icons = models.CharField(
        max_length=255, null=True,
        help_text='Space-separated list of icon identifiers.')
    creative_commons = models.BooleanField(default=False)

    objects = LicenseManager()

    class Meta:
        db_table = 'licenses'

    def __str__(self):
        license = self._constant or self
        return six.text_type(license.name)

    @property
    def _constant(self):
        return LICENSES_BY_BUILTIN.get(self.builtin)

models.signals.pre_save.connect(
    save_signal, sender=License, dispatch_uid='license_translations')

@python_2_unicode_compatible
class ApplicationsVersions(models.Model):
    id = PositiveAutoField(primary_key=True)
    application = models.PositiveIntegerField(choices=amo.APPS_CHOICES,
                                              db_column='application_id')
    version = models.ForeignKey(
        Version, related_name='apps', on_delete=models.CASCADE)
    min = models.ForeignKey(AppVersion, db_column='min',
                            related_name='min_set')
    max = models.ForeignKey(AppVersion, db_column='max',
                            related_name='max_set')

    class Meta:
        db_table = u'applications_versions'
        unique_together = (("application", "version"),)

    def get_application_display(self):
        return six.text_type(amo.APPS_ALL[self.application].pretty)

    def get_latest_application_version(self):
        return (
            AppVersion.objects
            .filter(
                ~models.Q(version__contains='*'),
                application=self.application)
            .order_by('-version_int')
            .first())

    def __str__(self):
        if (self.version.is_compatible_by_default and
                self.version.is_compatible_app(amo.APP_IDS[self.application])):
            return ugettext(u'{app} {min} and later').format(
                app=self.get_application_display(),
                min=self.min
            )
        return u'%s %s - %s' % (self.get_application_display(),
                                self.min, self.max)


text:
package org.zaproxy.zap.extension.saml.ui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Map;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.saml.*;

public class SamlManualEditor extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTextPane msgPane;
    private JButton btnResend;
    private JButton btnReset;
    private SAMLMessage samlMessage;

    private JTextPane respHeadTextPane;
    private JTextPane respBodyTextPane;
    private JTabbedPane tabbedPane;
    private JScrollPane msgScrollPane;
    private JScrollPane attribScrollPane;

    private boolean msgUpdating;

    /** Create the frame. */
    public SamlManualEditor(final SAMLMessage samlMessage) {
        setTitle(SamlI18n.getMessage("saml.editor.title"));
        this.samlMessage = samlMessage;
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(50, 50, 800, 700);
        JPanel contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        contentPane.add(tabbedPane, BorderLayout.CENTER);

        final JPanel reqPanel = new JPanel();
        tabbedPane.addTab(SamlI18n.getMessage("saml.editor.tab.request"), null, reqPanel, null);
        reqPanel.setLayout(new BorderLayout(0, 0));

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        reqPanel.add(topPanel, BorderLayout.NORTH);

        JLabel lblNote = new JLabel(SamlI18n.getMessage("saml.editor.headerwarn"));
        topPanel.add(lblNote);

        JPanel centerPanel = new JPanel();
        reqPanel.add(centerPanel, BorderLayout.CENTER);
        centerPanel.setLayout(new GridLayout(2, 1, 0, 10));

        msgScrollPane = new JScrollPane();
        centerPanel.add(msgScrollPane);

        attribScrollPane = new JScrollPane();
        centerPanel.add(attribScrollPane);

        JPanel bottomPanel = new JPanel();
        reqPanel.add(bottomPanel, BorderLayout.SOUTH);

        btnResend = new JButton(SamlI18n.getMessage("saml.editor.btn.resend"));
        bottomPanel.add(btnResend);

        btnReset = new JButton(SamlI18n.getMessage("saml.editor.btn.reset"));
        bottomPanel.add(btnReset);

        btnResend.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent event) {
                        // wait till the message is updated
                        while (msgUpdating) {
                            try {
                                Thread.sleep(50);
                            } catch (InterruptedException ignored) {
                            }
                        }
                        try {
                            SAMLResender.resendMessage(
                                    SamlManualEditor.this.samlMessage.getChangedMessage());
                            updateResponse(SamlManualEditor.this.samlMessage.getChangedMessage());
                            btnResend.setEnabled(false);
                            btnReset.setEnabled(false);
                        } catch (SAMLException e) {
                            JOptionPane.showMessageDialog(
                                    reqPanel,
                                    e.getMessage(),
                                    SamlI18n.getMessage("saml.editor.msg.cantresend"),
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    }
                });
        btnReset.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        SamlManualEditor.this.samlMessage.resetChanges();
                        updateFields();
                    }
                });

        JPanel respPanel = new JPanel();
        tabbedPane.addTab(SamlI18n.getMessage("saml.editor.tab.response"), null, respPanel, null);
        respPanel.setLayout(new GridLayout(2, 1, 0, 15));

        JScrollPane resHeadScrollPane = new JScrollPane();
        respPanel.add(resHeadScrollPane);

        respHeadTextPane = new JTextPane();
        resHeadScrollPane.setViewportView(respHeadTextPane);

        JScrollPane resBodyScrollPane = new JScrollPane();
        respPanel.add(resBodyScrollPane);

        respBodyTextPane = new JTextPane();
        resBodyScrollPane.setViewportView(respBodyTextPane);
        updateFields();
    }

    /** Update the UI fields with the new values. To be called on value changes */
    private void updateFields() {
        msgPane = new JTextPane();
        msgScrollPane.setViewportView(msgPane);
        msgPane.setText(samlMessage.getSamlMessageString());
        msgPane.addFocusListener(
                new FocusListener() {
                    @Override
                    public void focusGained(FocusEvent e) {
                        msgUpdating = true;
                    }

                    @Override
                    public void focusLost(FocusEvent e) {
                        samlMessage.setSamlMessageString(msgPane.getText());
                        // todo: check for validity
                        updateFields();
                        msgUpdating = false;
                    }
                });

        Map<String, Attribute> samlAttributes;
        samlAttributes = samlMessage.getAttributeMap();

        JPanel attributesPane = new JPanel();
        attribScrollPane.setViewportView(attributesPane);

        // 1 row per attribute and 1 for relay state. if the total < 10 set it to 10 to have a
        // better layout
        attributesPane.setLayout(
                new java.awt.GridLayout(Math.max(10, samlAttributes.size() + 1), 1, 5, 5));

        // text field to change relay state
        JSplitPane relayStatePane = new JSplitPane();
        JLabel lblRelayState = new JLabel();
        final JTextField txtRelayStateValue = new JTextField();

        relayStatePane.setDividerLocation(300);
        relayStatePane.setDividerSize(0);

        lblRelayState.setText(SamlI18n.getMessage("saml.editor.relaystate"));
        relayStatePane.setLeftComponent(lblRelayState);

        txtRelayStateValue.setText(samlMessage.getRelayState());
        relayStatePane.setRightComponent(txtRelayStateValue);

        // update the saml message on attribute value changes
        txtRelayStateValue.addFocusListener(
                new FocusListener() {
                    @Override
                    public void focusGained(FocusEvent e) {
                        msgUpdating = true;
                    }

                    @Override
                    public void focusLost(FocusEvent e) {
                        samlMessage.setRelayState(txtRelayStateValue.getText());
                        msgUpdating = false;
                    }
                });
        attributesPane.add(relayStatePane);

        // Text fields to change other attributes

        for (final Attribute attribute : samlAttributes.values()) {
            JSplitPane sPane = new JSplitPane();
            JLabel lbl = new JLabel();
            final JTextField txtValue = new JTextField();

            sPane.setDividerLocation(300);
            sPane.setDividerSize(0);

            lbl.setText(attribute.getViewName());
            sPane.setLeftComponent(lbl);

            txtValue.setText(attribute.getValue().toString());
            sPane.setRightComponent(txtValue);

            // update the saml message on attribute value changes
            txtValue.addFocusListener(
                    new FocusListener() {
                        @Override
                        public void focusGained(FocusEvent e) {
                            msgUpdating = true;
                        }

                        @Override
                        public void focusLost(FocusEvent e) {
                            samlMessage.changeAttributeValueTo(
                                    attribute.getName(), txtValue.getText());
                            msgPane.setText(samlMessage.getSamlMessageString());
                            msgUpdating = false;
                        }
                    });
            attributesPane.add(sPane);
        }
    }

    /**
     * Update the response
     *
     * @param msg
     */
    private void updateResponse(HttpMessage msg) {
        respBodyTextPane.setText(msg.getResponseBody().toString());
        respHeadTextPane.setText(msg.getResponseHeader().toString());
        tabbedPane.setSelectedIndex(1);
    }
}


text:
[![Build Status](https://travis-ci.org/blakeyc/oxr-cli.svg?branch=master)](https://travis-ci.org/blakeyc/oxr-cli)

>Command line utility to extract data from https://openexchangerates.org/ API.

**Note**: You need to register an account to get an app_id from Open Exchange Rates. Some features are not available to free accounts, please see the Open Exchange Rates documentation for more details.

## Install

Download binaries directly from the releases page, or alternatively clone and build from
source, see below for details.

TODO: Publish to homebrew etc...

## Usage

### Commands

    oxr [flags]
    oxr --help
    oxr --version

### Flags

`--app_id` Your application ID from Open Exchange Rates API.

`--job` Name of the job to run (latest|historical|timeseries).

`--output` Path to the file you wish to write results to.

`--dates` Date of historical exchange rates, can supply multiple dates (YYYY-MM-DD).

`--start` Start date of time series query (YYYY-MM-DD).

`--end` End date of time series query (YYYY-MM-DD).

`--base` Currency to use as the base, defaults to USD

`--fields` Define the list of fields to output in file (base,currency,rate,timestamp,date)

### Example's

#### Latest
    oxr --job latest --app_id YOUR_APP_ID --output PATH_TO_FILE

#### Latest, Selecting Fields
    oxr --job latest --app_id YOUR_APP_ID --output PATH_TO_FILE --fields base,currency,rate

#### Historical
    oxr --job historical --dates 2017-01-01 --app_id YOUR_APP_ID --output PATH_TO_FILE

#### Historical Range of Dates
    oxr --job historical --dates 2017-01-01,2017-01-02 --app_id YOUR_APP_ID --output PATH_TO_FILE

#### Time Series
    oxr --job timeseries --start 2017-01-01 --end 2017-01-31 --app_id YOUR_APP_ID --output PATH_TO_FILE

## Build

To run or build from source clone the repo and run `make build` this will also install the dependencies listed below.
The executables will be output to the `./dist` directory for darwin, linux and windows.

### Dependencies

    go get github.com/mvillalba/go-openexchangerates/oxr


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

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.templates.TemplateVariableResolver;
import org.eclipse.php.internal.ui.PHPUiPlugin;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;

//import org.eclipse.jdt.internal.ui.JavaPlugin;

/**
 * A proposal for insertion of template variables.
 */
public class TemplateVariableProposal implements ICompletionProposal {

	private TemplateVariableResolver fResolver;
	private int fOffset;
	private int fLength;
	private ITextViewer fViewer;

	private Point fSelection;
	private final boolean fIncludeBrace;

	/**
	 * Creates a template variable proposal.
	 *
	 * @param variable
	 *            the template variable
	 * @param offset
	 *            the offset to replace
	 * @param length
	 *            the length to replace
	 * @param viewer
	 *            the viewer
	 * @param includeBrace
	 *            whether to also replace the ${
	 */
	public TemplateVariableProposal(TemplateVariableResolver variable, int offset, int length, ITextViewer viewer,
			boolean includeBrace) {
		fResolver = variable;
		fOffset = offset;
		fLength = length;
		fViewer = viewer;
		fIncludeBrace = includeBrace;
	}

	/*
	 * @see ICompletionProposal#apply(IDocument)
	 */
	@Override
	public void apply(IDocument document) {

		try {
			String variable;
			String type = fResolver.getType();
			if (type.equals("dollar")) //$NON-NLS-1$
				variable = "$$"; //$NON-NLS-1$
			else if (fIncludeBrace)
				variable = "${" + type + '}'; //$NON-NLS-1$
			else
				variable = type;
			document.replace(fOffset, fLength, variable);
			fSelection = new Point(fOffset + variable.length(), 0);

		} catch (BadLocationException e) {
			PHPUiPlugin.log(e);

			Shell shell = fViewer.getTextWidget().getShell();
			MessageDialog.openError(shell, TemplatePreferencesMessages.TemplateVariableProposal_error_title,
					e.getMessage());
		}
	}

	/*
	 * @see ICompletionProposal#getSelection(IDocument)
	 */
	@Override
	public Point getSelection(IDocument document) {
		return fSelection;
	}

	/*
	 * @see ICompletionProposal#getAdditionalProposalInfo()
	 */
	@Override
	public String getAdditionalProposalInfo() {
		return fResolver.getDescription();
	}

	/*
	 * @see ICompletionProposal#getDisplayString()
	 */
	@Override
	public String getDisplayString() {
		return fResolver.getType();
	}

	/*
	 * @see ICompletionProposal#getImage()
	 */
	@Override
	public Image getImage() {
		return null;
	}

	/*
	 * @see ICompletionProposal#getContextInformation()
	 */
	@Override
	public IContextInformation getContextInformation() {
		return null;
	}
}


text:
char *execname = NULL;

int main (int argc, char **argv) {
   (void) argc; // warning: unused parameter 'argc'
   execname = basename (argv[0]);

   // Declare the box and initialize it.
   cbox *box = new_cbox();
   printf ("box = %p\n", box);

   // Perform a couple of operations on it.
   put_cbox (box, 1024);
   printf ("box value is %d\n", get_cbox (box));

   // Free up the box.
   free_cbox (box);

   return EXIT_SUCCESS;
}


text:
package com.kotcrab.vis.runtime.system.inflater;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Music;
import com.kotcrab.vis.runtime.RuntimeConfiguration;
import com.kotcrab.vis.runtime.assets.PathAsset;
import com.kotcrab.vis.runtime.component.AssetReference;
import com.kotcrab.vis.runtime.component.VisMusic;
import com.kotcrab.vis.runtime.component.proto.ProtoVisMusic;

/**
 * Inflates {@link ProtoVisMusic} into {@link VisMusic}
 * @author Kotcrab
 */
public class MusicInflater extends InflaterSystem {
	private ComponentMapper<AssetReference> assetCm;
	private ComponentMapper<VisMusic> musicCm;
	private ComponentMapper<ProtoVisMusic> protoCm;

	private RuntimeConfiguration configuration;
	private AssetManager manager;

	public MusicInflater (RuntimeConfiguration configuration, AssetManager manager) {
		super(Aspect.all(ProtoVisMusic.class, AssetReference.class));
		this.configuration = configuration;
		this.manager = manager;
	}

	@Override
	protected void inserted (int entityId) {
		AssetReference assetRef = assetCm.get(entityId);
		ProtoVisMusic protoVisMusic = protoCm.get(entityId);

		PathAsset asset = (PathAsset) assetRef.asset;

		Music music = manager.get(asset.getPath(), Music.class);
		if (music == null) throw new IllegalStateException("Can't load scene, music is missing: " + asset.getPath());
		VisMusic musicComponent = musicCm.create(entityId);
		musicComponent.music = music;
		protoVisMusic.fill(musicComponent);
		if (musicComponent.playOnStart) musicComponent.music.play();

		protoCm.remove(entityId);
	}
}


text:
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: This header should never be used directly from leaf code!!!
// Instead, just add the file memoverride.cpp into your project and all this
// will automagically be used
//
// $NoKeywords: $
//=============================================================================//

#ifndef TIER0_MEMALLOC_H
#define TIER0_MEMALLOC_H

#ifdef _WIN32
#pragma once
#endif

#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE)

#include <stddef.h>
#include "tier0/mem.h"

struct _CrtMemState;

#define MEMALLOC_VERSION 1

typedef size_t (*MemAllocFailHandler_t)( size_t );

//-----------------------------------------------------------------------------
// NOTE! This should never be called directly from leaf code
// Just use new,delete,malloc,free etc. They will call into this eventually
//-----------------------------------------------------------------------------
abstract_class IMemAlloc
{
public:
	// Release versions
	virtual void *Alloc( size_t nSize ) = 0;
	virtual void *Realloc( void *pMem, size_t nSize ) = 0;
	virtual void Free( void *pMem ) = 0;
    virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize ) = 0;

	// Debug versions
    virtual void *Alloc( size_t nSize, const char *pFileName, int nLine ) = 0;
    virtual void *Realloc( void *pMem, size_t nSize, const char *pFileName, int nLine ) = 0;
    virtual void  Free( void *pMem, const char *pFileName, int nLine ) = 0;
    virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize, const char *pFileName, int nLine ) = 0;

	// Returns size of a particular allocation
	virtual size_t GetSize( void *pMem ) = 0;

    // Force file + line information for an allocation
    virtual void PushAllocDbgInfo( const char *pFileName, int nLine ) = 0;
    virtual void PopAllocDbgInfo() = 0;

	// FIXME: Remove when we have our own allocator
	// these methods of the Crt debug code is used in our codebase currently
	virtual long CrtSetBreakAlloc( long lNewBreakAlloc ) = 0;
	virtual	int CrtSetReportMode( int nReportType, int nReportMode ) = 0;
	virtual int CrtIsValidHeapPointer( const void *pMem ) = 0;
	virtual int CrtIsValidPointer( const void *pMem, unsigned int size, int access ) = 0;
	virtual int CrtCheckMemory( void ) = 0;
	virtual int CrtSetDbgFlag( int nNewFlag ) = 0;
	virtual void CrtMemCheckpoint( _CrtMemState *pState ) = 0;

	// FIXME: Make a better stats interface
	virtual void DumpStats() = 0;

	// FIXME: Remove when we have our own allocator
	virtual void* CrtSetReportFile( int nRptType, void* hFile ) = 0;
	virtual void* CrtSetReportHook( void* pfnNewHook ) = 0;
	virtual int CrtDbgReport( int nRptType, const char * szFile,
			int nLine, const char * szModule, const char * pMsg ) = 0;

	virtual int heapchk() = 0;

	virtual bool IsDebugHeap() = 0;

	virtual void GetActualDbgInfo( const char *&pFileName, int &nLine ) = 0;
	virtual void RegisterAllocation( const char *pFileName, int nLine, int nLogicalSize, int nActualSize, unsigned nTime ) = 0;
	virtual void RegisterDeallocation( const char *pFileName, int nLine, int nLogicalSize, int nActualSize, unsigned nTime ) = 0;

	virtual int GetVersion() = 0;

	virtual void CompactHeap() = 0;

	// Function called when malloc fails or memory limits hit to attempt to free up memory (can come in any thread)
	virtual MemAllocFailHandler_t SetAllocFailHandler( MemAllocFailHandler_t pfnMemAllocFailHandler ) = 0;
};

//-----------------------------------------------------------------------------
// Singleton interface
//-----------------------------------------------------------------------------
MEM_INTERFACE IMemAlloc *g_pMemAlloc;

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

inline void *MemAlloc_AllocAligned( size_t size, size_t align )
{
	unsigned char *pAlloc, *pResult;

	if (!IsPowerOfTwo(align))
		return NULL;

	align = (align > sizeof(void *) ? align : sizeof(void *)) - 1;

	if ( (pAlloc = (unsigned char*)g_pMemAlloc->Alloc( sizeof(void *) + align + size ) ) == (unsigned char*)NULL)
		return NULL;

	pResult = (unsigned char*)( (unsigned)(pAlloc + sizeof(void *) + align ) & ~align );
	((unsigned char**)(pResult))[-1] = pAlloc;

	return (void *)pResult;
}

inline void *MemAlloc_AllocAligned( size_t size, size_t align, const char *pszFile, int nLine )
{
	unsigned char *pAlloc, *pResult;

	if (!IsPowerOfTwo(align))
		return NULL;

	align = (align > sizeof(void *) ? align : sizeof(void *)) - 1;

	if ( (pAlloc = (unsigned char*)g_pMemAlloc->Alloc( sizeof(void *) + align + size, pszFile, nLine ) ) == (unsigned char*)NULL)
		return NULL;

	pResult = (unsigned char*)( (unsigned)(pAlloc + sizeof(void *) + align ) & ~align );
	((unsigned char**)(pResult))[-1] = pAlloc;

	return (void *)pResult;
}

inline void MemAlloc_FreeAligned( void *pMemBlock )
{
	unsigned *pAlloc;

	if ( pMemBlock == NULL )
		return;

	pAlloc = (unsigned *)pMemBlock;

	// pAlloc points to the pointer to starting of the memory block
	pAlloc = (unsigned *)(((unsigned)pAlloc & ~( sizeof(void *) - 1 ) ) - sizeof(void *));

	// pAlloc is the pointer to the start of memory block
	pAlloc = *( (unsigned **)pAlloc );
	g_pMemAlloc->Free( (void *)pAlloc );
}

inline size_t MemAlloc_GetSizeAligned( void *pMemBlock )
{
	unsigned *pAlloc;

	if ( pMemBlock == NULL )
		return 0;

	pAlloc = (unsigned *)pMemBlock;

	// pAlloc points to the pointer to starting of the memory block
	pAlloc = (unsigned *)(((unsigned)pAlloc & ~( sizeof(void *) - 1 ) ) - sizeof(void *));

	// pAlloc is the pointer to the start of memory block
	pAlloc = *((unsigned **)pAlloc );
	return g_pMemAlloc->GetSize( (void *)pAlloc ) - ( (byte *)pMemBlock - (byte *)pAlloc );
}

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

#if (defined(_DEBUG) || defined(USE_MEM_DEBUG))
#define MEM_ALLOC_CREDIT_(tag)	CMemAllocAttributeAlloction memAllocAttributeAlloction( tag, __LINE__ )
#define MemAlloc_PushAllocDbgInfo( pszFile, line ) g_pMemAlloc->PushAllocDbgInfo( pszFile, line )
#define MemAlloc_PopAllocDbgInfo() g_pMemAlloc->PopAllocDbgInfo()
#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) g_pMemAlloc->RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime )
#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) g_pMemAlloc->RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime )
#else
#define MEM_ALLOC_CREDIT_(tag)	((void)0)
#define MemAlloc_PushAllocDbgInfo( pszFile, line ) ((void)0)
#define MemAlloc_PopAllocDbgInfo() ((void)0)
#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#endif

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

class CMemAllocAttributeAlloction
{
public:
	CMemAllocAttributeAlloction( const char *pszFile, int line )
	{
		MemAlloc_PushAllocDbgInfo( pszFile, line );
	}

	~CMemAllocAttributeAlloction()
	{
		MemAlloc_PopAllocDbgInfo();
	}
};

#define MEM_ALLOC_CREDIT()	MEM_ALLOC_CREDIT_(__FILE__)

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

#if defined(_WIN32) && ( defined(_DEBUG) || defined(USE_MEM_DEBUG) )

	#ifdef _XBOX
		#define MEM_DEBUG_CLASSNAME
	#endif

	#pragma warning(disable:4290)
	#pragma warning(push)
	#include <typeinfo.h>

	// MEM_DEBUG_CLASSNAME is opt-in.
	// Note: typeid().name() is not threadsafe, so if the project needs to access it in multiple threads
	// simultaneously, it'll need a mutex.
	#if defined(_CPPRTTI) && defined(MEM_DEBUG_CLASSNAME)
		#define MEM_ALLOC_CREDIT_CLASS()	MEM_ALLOC_CREDIT_( typeid(*this).name() )
		#define MEM_ALLOC_CLASSNAME(type) (typeid((type*)(0)).name())
	#else
		#define MEM_ALLOC_CREDIT_CLASS()	MEM_ALLOC_CREDIT_( __FILE__ )
		#define MEM_ALLOC_CLASSNAME(type) (__FILE__)
	#endif

	// MEM_ALLOC_CREDIT_FUNCTION is used when no this pointer is available ( inside 'new' overloads, for example )
	#ifdef _MSC_VER
		#define MEM_ALLOC_CREDIT_FUNCTION()		MEM_ALLOC_CREDIT_( __FUNCTION__ )
	#else
		#define MEM_ALLOC_CREDIT_FUNCTION() (__FILE__)
	#endif

	#pragma warning(pop)
#else
	#define MEM_ALLOC_CREDIT_CLASS()
	#define MEM_ALLOC_CLASSNAME(type) NULL
	#define MEM_ALLOC_CREDIT_FUNCTION()
#endif

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

#if (defined(_DEBUG) || defined(USE_MEM_DEBUG))
struct MemAllocFileLine_t
{
	const char *pszFile;
	int line;
};

#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag ) \
	static CUtlMap<void *, MemAllocFileLine_t, int> g_##tag##Allocs( DefLessFunc( void *) ); \
	static const char *g_psz##tag##Alloc = strcpy( (char *)g_pMemAlloc->Alloc( strlen( #tag "Alloc" ) + 1, "intentional leak", 0 ), #tag "Alloc" );

#define MemAlloc_RegisterExternalAllocation( tag, p, size ) \
	if ( !p ) \
		; \
	else \
	{ \
		MemAllocFileLine_t fileLine = { g_psz##tag##Alloc, 0 }; \
		g_pMemAlloc->GetActualDbgInfo( fileLine.pszFile, fileLine.line ); \
		if ( fileLine.pszFile != g_psz##tag##Alloc ) \
		{ \
			g_##tag##Allocs.Insert( p, fileLine ); \
		} \
		\
		MemAlloc_RegisterAllocation( fileLine.pszFile, fileLine.line, size, size, 0); \
	}

#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) \
	if ( !p ) \
		; \
	else \
	{ \
		MemAllocFileLine_t fileLine = { g_psz##tag##Alloc, 0 }; \
		CUtlMap<void *, MemAllocFileLine_t, int>::IndexType_t iRecordedFileLine = g_##tag##Allocs.Find( p ); \
		if ( iRecordedFileLine !=  g_##tag##Allocs.InvalidIndex() ) \
		{ \
			fileLine = g_##tag##Allocs[iRecordedFileLine]; \
			g_##tag##Allocs.RemoveAt( iRecordedFileLine ); \
		} \
		\
		MemAlloc_RegisterDeallocation( fileLine.pszFile, fileLine.line, size, size, 0); \
	}

#else

#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag )
#define MemAlloc_RegisterExternalAllocation( tag, p, size ) ((void)0)
#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) ((void)0)

#endif

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

#endif // !STEAM && !NO_MALLOC_OVERRIDE

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

#if !defined(STEAM) && defined(NO_MALLOC_OVERRIDE)

#define MEM_ALLOC_CREDIT_(tag)	((void)0)
#define MEM_ALLOC_CREDIT()	MEM_ALLOC_CREDIT_(__FILE__)
#define MEM_ALLOC_CREDIT_CLASS()
#define MEM_ALLOC_CLASSNAME(type) NULL

#endif !STEAM && NO_MALLOC_OVERRIDE

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

#endif /* TIER0_MEMALLOC_H */


text:
(function () {
    "use strict";
    angular
        .module("entelectFines")
        .controller("Login", ["$location",
                              "toaster",
                              "localStorageService",
                              "userResource",
                              "usSpinnerService",
                              Login]);

    function Login($location, toaster, localStorageService, userResource, usSpinnerService) {
        var vm = this;
        localStorageService.clearAll();
        if (localStorageService.get('user') == null) {
            toaster.error('User Not Signed In', 'Please Login To Access Site');
        }
        vm.loggedIn = false;
        vm.login = login;
        vm.username = "";
        vm.password = "";

        function login() {
            startSpin();
            var loginModel = {
                Username: vm.username,
                Password: vm.password
            };
            var promise = userResource.save({
                    action: "AuthenticateUser"
                },
                loginModel
            );
            promise.$promise.then(function (data) {
                    var user = localStorageService.get('user');
                    user = data;
                    localStorageService.set('user', user);
                    $location.path("/Fines");
                    toaster.pop('success', "Login Success", "Successfully Logged In");
                },
                function () {
                    stopSpin();
                    toaster.pop('error', "Login Failure", "Incorrect Login Details");
                });
        }

        function startSpin() {
            usSpinnerService.spin('spinner-1');
        }

        function stopSpin() {
            usSpinnerService.stop('spinner-1');
        }
    }
}());


text:
require "capnode/version"
require File.expand_path("../capnode/git.rb", __FILE__)
require File.expand_path("../capnode/setup.rb", __FILE__)
require File.expand_path("../capnode/npm.rb", __FILE__)

module Capnode
  # Your code goes here...
end

Capistrano::Configuration.instance(true).load do
  set :use_sudo, false

  default_environment["http_proxy"] = fetch("http_proxy") if exists?("http_proxy")
  default_environment["https_proxy"] = fetch("https_proxy") if exists?("https_proxy")

  namespace :deploy do
    desc 'finalize_update'
    task :finalize_update, :roles => :app do
      #do nothing
    end
  end
end