text:
package com.amazonaws.util.awsclientgenerator.domainmodels.endpoints;

import lombok.Data;

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class EndpointTests {
    static String formatString(String str){
        if (str.contains("\n") || str.contains("\"") || str.contains("\n") || str.contains("\t")) {
            return "R\"(" + str + ")\"";
        } else {
            return "\"" + str + "\"";
        }
    }

    @Data
    public static class EndpointTestParameter {
        enum ParameterType {
            BOOLEAN,
            INTEGER,
            STRING
        }

        ParameterType type;
        String name;
        Boolean boolValue;
        Integer intValue;
        String strValue;

        public String getAsCppSourceString(boolean isEndpointProperty) throws Exception {
            String typeAlias = isEndpointProperty ? "EpProp" : "EpParam";
            if (ParameterType.BOOLEAN == this.type) {
                String val = boolValue ? "true" : "false";
                return new StringBuilder(typeAlias).append("(\"").append(name).append("\", ").append(val).append(")").toString();
            } else if (ParameterType.INTEGER == this.type) {
                return new StringBuilder(typeAlias).append("(\"").append(name).append("\",").append(intValue.toString()).append(")").toString();
            } else if (ParameterType.STRING == this.type) {
                String strValueEscaped = (strValue.contains("\"") || strValue.contains("\\")) ? "R\"(" + strValue + ")\"" : "\"" + strValue + "\"";
                return new StringBuilder(typeAlias).append("(\"").append(name).append("\", ").append(strValueEscaped).append(")").toString();
            }
            throw new Exception("EndpointTestParameter value not set!");
        }

        public String getAsCppSourceString() throws Exception {
            return getAsCppSourceString(false);
        }
    }

    public static class EndpointTestParams extends HashMap<String, EndpointTestParameter> {
        public String getAsCppSourceString(boolean isEndpointProperty, int indent) throws Exception {
            StringBuilder builder = new StringBuilder().append("{");
            String separator = "";
            int onPreviousLinesLength = 0;
            for (Map.Entry<String, EndpointTestParameter> paramEntry : this.entrySet()) {
                builder.append(separator);
                builder.append(paramEntry.getValue().getAsCppSourceString(isEndpointProperty));
                if (builder.length() > onPreviousLinesLength + 100) {
                    onPreviousLinesLength = builder.length();
                    separator = ",\n" + String.join("", Collections.nCopies(indent + 1, " "));;
                } else {
                    separator = ", ";
                }
            }
            builder.append("}");
            return builder.toString();
        }

        public String getAsCppSourceString(int indent) throws Exception {
            return getAsCppSourceString(false, indent);
        }
    }

    @Data
    public static class OperationInput {
        String operationName;
        EndpointTestParams clientParams;
        EndpointTestParams operationParams;
        EndpointTestParams builtinParams;

        public String getAsCppSourceString(int indent) throws Exception {
            StringBuilder builder = new StringBuilder("{");
            builder.append("/*operationName*/\"").append(operationName).append("\"");
            List<AbstractMap.SimpleEntry<String, EndpointTestParams>> allParams =
                    Arrays.asList(new AbstractMap.SimpleEntry<>("clientParams", clientParams),
                            new AbstractMap.SimpleEntry<>("operationParams", operationParams),
                            new AbstractMap.SimpleEntry<>("builtinParams", builtinParams));

            for(AbstractMap.SimpleEntry<String, EndpointTestParams> paramEntry : allParams) {
                String indentStr = String.join("", Collections.nCopies(indent + 2, " "));
                builder.append(",\n");
                builder.append(indentStr);
                builder.append("/*").append(paramEntry.getKey()).append("*/");
                if (paramEntry.getValue() != null)
                {
                    builder.append(paramEntry.getValue().getAsCppSourceString(indent+2));
                } else {
                    builder.append("{}");
                }
            }
            builder.append("}");
            return builder.toString();
        }
    }

    @Data
    public static class OperationInputs extends ArrayList<OperationInput> {
        public String getAsCppSourceString(int indent) throws Exception {
            if (this.isEmpty()) {
                return "{}";
            }
            StringBuilder builder = new StringBuilder("{");
            for(OperationInput value : this) {
                builder.append(value.getAsCppSourceString(indent+2));
            }
            builder.append("}");
            return builder.toString();
        }
    }

    @Data
    public class TestCase {
        @Data
        public class Expect {
            @Data
            public class Endpoint {
                String url;
                Map<String, List<EndpointTestParams>> properties;
                Map<String, List<String>> headers;

                public String getAsCppSourceString(int indent) throws Exception {
                    StringBuilder builder = new StringBuilder().append("{");
                    if (url != null && !url.isEmpty()) {
                        builder.append("/*epUrl*/\"").append(url).append("\"");
                    } else {
                        builder.append("{/*No endpoint expected*/}");
                    }
                    // properties begin
                    String indentStr = String.join("", Collections.nCopies(indent + 3, " "));
                    builder.append(",\n");
                    builder.append(indentStr);
                    builder.append("{/*properties*/");
                    if (properties != null && !properties.isEmpty()) {
                        String separator = "";
                        for (Map.Entry<String, List<EndpointTestParams>> propEntry : properties.entrySet()) {
                            builder.append(separator);
                            builder.append("{\"").append(propEntry.getKey()).append("\", ");
                            for (EndpointTestParams epParam : propEntry.getValue()) {
                                builder.append(epParam.getAsCppSourceString(true, indent + 22 + propEntry.getKey().length()));
                            }
                            builder.append("}");
                            separator = "," + indentStr + " ";
                        }
                    }
                    builder.append("}"); // end of properties
                    indentStr = String.join("", Collections.nCopies(indent + 3, " "));
                    builder.append(",\n");
                    builder.append(indentStr);
                    builder.append("{/*headers*/");
                    if (headers != null && !headers.isEmpty()) {
                        String separator = "";
                        for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
                            builder.append(separator);
                            builder.append("{\"").append(headerEntry.getKey()).append("\", ");
                            builder.append("{"); // inner list of header under that key begin
                            String innerSeparator = "";
                            for (String header : headerEntry.getValue()) {
                                builder.append(innerSeparator);
                                builder.append("\"").append(header).append("\"");
                                innerSeparator = ", ";
                            }
                            builder.append("}"); // inner list of header under that key end
                            builder.append("}"); // header entry end
                            separator = ", ";
                        }
                    }
                    builder.append("}"); // end of headers
                    builder.append("}"); // end of whole expected endpoint entry

                    return builder.toString();
                }
            }

            Endpoint endpoint;
            String error;

            public String getAsCppSourceString(int indent) throws Exception {
                StringBuilder builder = new StringBuilder("{");

                if (endpoint != null && !endpoint.url.isEmpty() && error!= null && !error.isEmpty()) {
                    throw new RuntimeException("Cannot expect computed endpoint and an error together: url: '" + endpoint.url +
                            "', and error: '" + error + "'");
                }

                if (endpoint != null) {
                    builder.append(endpoint.getAsCppSourceString(indent));
                } else {
                    builder.append("{/*No endpoint expected*/}");
                }
                builder.append(", ");
                if (error != null && !error.isEmpty()) {
                    builder.append("/*error*/").append(formatString(error));
                } else {
                    builder.append("{/*No error*/}");
                }
                builder.append("}");
                return builder.toString();
            }
        }

        String documentation;
        EndpointTestParams params;
        List<String> tags;
        Expect expect;
        OperationInputs operationInputs;
    }

    String version;
    List<TestCase> testCases;
}


text:
namespace brightray {

using content::BrowserThread;
using content::MediaStreamDevices;

namespace {

// Finds a device in |devices| that has |device_id|, or NULL if not found.
const content::MediaStreamDevice* FindDeviceWithId(
    const content::MediaStreamDevices& devices,
    const std::string& device_id) {
  content::MediaStreamDevices::const_iterator iter = devices.begin();
  for (; iter != devices.end(); ++iter) {
    if (iter->id == device_id) {
      return &(*iter);
    }
  }
  return NULL;
}

const MediaStreamDevices& EmptyDevices() {
  static MediaStreamDevices* devices = new MediaStreamDevices;
  return *devices;
}

}  // namespace

MediaCaptureDevicesDispatcher* MediaCaptureDevicesDispatcher::GetInstance() {
  return Singleton<MediaCaptureDevicesDispatcher>::get();
}

MediaCaptureDevicesDispatcher::MediaCaptureDevicesDispatcher()
    : is_device_enumeration_disabled_(false) {
  // MediaCaptureDevicesDispatcher is a singleton. It should be created on
  // UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

MediaCaptureDevicesDispatcher::~MediaCaptureDevicesDispatcher() {}

const MediaStreamDevices&
MediaCaptureDevicesDispatcher::GetAudioCaptureDevices() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (is_device_enumeration_disabled_)
    return EmptyDevices();
  return content::MediaCaptureDevices::GetInstance()->GetAudioCaptureDevices();
}

const MediaStreamDevices&
MediaCaptureDevicesDispatcher::GetVideoCaptureDevices() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (is_device_enumeration_disabled_)
    return EmptyDevices();
  return content::MediaCaptureDevices::GetInstance()->GetVideoCaptureDevices();
}

void MediaCaptureDevicesDispatcher::GetDefaultDevices(
    bool audio,
    bool video,
    content::MediaStreamDevices* devices) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(audio || video);

  if (audio) {
    const content::MediaStreamDevice* device = GetFirstAvailableAudioDevice();
    if (device)
      devices->push_back(*device);
  }

  if (video) {
    const content::MediaStreamDevice* device = GetFirstAvailableVideoDevice();
    if (device)
      devices->push_back(*device);
  }
}

const content::MediaStreamDevice*
MediaCaptureDevicesDispatcher::GetRequestedAudioDevice(
    const std::string& requested_audio_device_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  const content::MediaStreamDevices& audio_devices = GetAudioCaptureDevices();
  const content::MediaStreamDevice* const device =
      FindDeviceWithId(audio_devices, requested_audio_device_id);
  return device;
}

const content::MediaStreamDevice*
MediaCaptureDevicesDispatcher::GetFirstAvailableAudioDevice() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  const content::MediaStreamDevices& audio_devices = GetAudioCaptureDevices();
  if (audio_devices.empty())
    return NULL;
  return &(*audio_devices.begin());
}

const content::MediaStreamDevice*
MediaCaptureDevicesDispatcher::GetRequestedVideoDevice(
    const std::string& requested_video_device_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  const content::MediaStreamDevices& video_devices = GetVideoCaptureDevices();
  const content::MediaStreamDevice* const device =
      FindDeviceWithId(video_devices, requested_video_device_id);
  return device;
}

const content::MediaStreamDevice*
MediaCaptureDevicesDispatcher::GetFirstAvailableVideoDevice() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  const content::MediaStreamDevices& video_devices = GetVideoCaptureDevices();
  if (video_devices.empty())
    return NULL;
  return &(*video_devices.begin());
}

void MediaCaptureDevicesDispatcher::DisableDeviceEnumerationForTesting() {
  is_device_enumeration_disabled_ = true;
}

void MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged() {
}

void MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged() {
}

void MediaCaptureDevicesDispatcher::OnMediaRequestStateChanged(
    int render_process_id,
    int render_view_id,
    int page_request_id,
    const GURL& security_origin,
    const content::MediaStreamDevice& device,
    content::MediaRequestState state) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}

void MediaCaptureDevicesDispatcher::OnAudioStreamPlaying(
    int render_process_id,
    int render_frame_id,
    int stream_id,
    const ReadPowerAndClipCallback& power_read_callback) {
}

void MediaCaptureDevicesDispatcher::OnAudioStreamStopped(
    int render_process_id,
    int render_frame_id,
    int stream_id) {
}

void MediaCaptureDevicesDispatcher::OnCreatingAudioStream(
    int render_process_id,
    int render_view_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}

}  // namespace brightray

redpajama_set_name: RedPajamaGithub


text:
  L'Argentière-la-Bessée est
      une ville localisée dans le département des Hautes-Alpes en Provence-Alpes-Côte d'Azur. On dénombrait 2 302 habitants en 2008.

À coté de L'Argentière-la-Bessée sont positionnées géographiquement les communes de
Vallouise située à 8 km, 707 habitants,
Villar-Saint-Pancrace située à 10 km, 1 459 habitants,
Saint-Crépin localisée à 10 km, 583 habitants,
Les Vigneaux à 3 km, 453 habitants,
Freissinières située à 4 km, 183 habitants,
Champcella située à 7 km, 166 habitants,
 entre autres. De plus, L'Argentière-la-Bessée est située à seulement douze km de Briançon.

Le parc de logements, à L'Argentière-la-Bessée, se décomposait en 2011 en 584 appartements et 725 maisons soit
 un marché relativement équilibré.

La ville est équipée en ce qui concerne la formation de un collège.
S'agissant ceux d'entre nous ayant moins de 6 ans, la ville est pourvue de deux maternelles et une école primaire.
L'Argentière-la-Bessée propose les installations permettant une vie locale facilitée.
Si vous avez un projet d'achat immobilier à L'Argentière-la-Bessée, vous devrez impérativement regarder la valeur des équipements éducatifs

La ville propose de multiples  équipements, elle propose entre autres un bassin de natation, deux terrains de tennis, un terrain de sport et six boucles de randonnée.

À L'Argentière-la-Bessée, la valeur moyenne à l'achat d'un appartement se situe à 1 535 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2 563 € du m². À la location la valeur moyenne se situe à 7,83 € du m² par mois.

À L'Argentière-la-Bessée le salaire moyen mensuel par habitant se situe à approximativement 1 944 €  net. Ceci est au dessous de la moyenne du pays.


text:
from pyrekall.models.processes import Process
from pyrekall.models.sample import Sample
from pyrekall.models.executable import PE

import unittest
import os

class MockSample(Sample):
    def __init__(self, path):
        super(MockSample, self).__init__(path=path)

    def _compute_checksums(self):
        self._md5 = "9fb971822dcb393f930227c8854f7679"
        self._sha1 = "6783d95883a32762042cae731887ae3693b030c1"
        self._sha256 = "5f19ff1333fc3901fbf3fafb50d2adb0c495cf6d33789e5a959499a92aeefe77"

class ProcessTestCases(unittest.TestCase):
    _multiprocess_can_split_ = True

    filename = os.path.join(os.path.dirname(__file__), "../../samples/stuxnet.vmem")
    sample = MockSample(path=filename)
    process = sample.get_process_by_name("lsass.exe")

    def test_name(self):
        self.assertEqual("lsass.exe", self.process.name)

    def test_pid(self):
        self.assertEqual(680, self.process.pid)

    def test_ppid(self):
        self.assertEqual(624, self.process.ppid)

    def test_number_of_handles(self):
        self.assertEqual(342, self.process.number_of_handles)

    def test_number_of_active_threads(self):
        self.assertEqual(19, self.process.number_of_active_threads)

    def test_path(self):
        self.assertEqual("C:\\WINDOWS\\system32\\lsass.exe", self.process.path)

    def test_command_line(self):
        self.assertEqual("C:\\WINDOWS\\system32\\lsass.exe", self.process.command_line)

    def test_current_directory(self):
        self.assertEqual("C:\\WINDOWS\\system32\\", self.process.current_directory)

    def test_dll_path(self):
        self.assertEqual('C:\\WINDOWS\\system32;C:\\WINDOWS\\system32;C:\\WINDOWS\\system;C:\\WINDOWS;.;C:\\Perl\\'
                         'site\\bin;C:\\Perl\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\'
                         'Python26;C:\\Program Files\\TortoiseSVN\\bin', self.process.dll_path)

    def test_create_time(self):
        self.assertEqual(1288372134, self.process.create_time)

    def test_exit_time(self):
        self.assertEqual(None, self.process.exit_time)

    def test_virtual_offset(self):
        self.assertEqual(2179399712L, self.process.virtual_offset)

    def test_physical_offset(self):
        self.assertEqual(34013216L, self.process.physical_offset)

    def test_address_space_initialized(self):
        self.assertEqual(True, self.process.address_space_initialized)

    def test_has_address_space(self):
        self.assertEqual(True, self.process.has_address_space)

    def test_sub_system_major_version(self):
        self.assertEqual(4, self.process.sub_system_major_version)

    def test_sub_system_minor_version(self):
        self.assertEqual(0, self.process.sub_system_minor_version)

    def test_sub_system_version(self):
        self.assertEqual(1024, self.process.sub_system_version)

    def test_parent(self):
        self.assertTrue(isinstance(self.process, Process))
        self.assertTrue(isinstance(self.process.parent, Process))
        self.assertEqual(self.process.ppid, self.process.parent.pid)

    def test_children(self):
        p = self.sample.get_process_by_name("services.exe")
        self.assertTrue(isinstance(p, Process))
        self.assertTrue(isinstance(p.children, list))
        self.assertEqual(14, len(p.children))

        expected = {1664, 868, 1032, 940, 844, 1816, 1200, 1080, 1928, 756, 856, 1412, 188, 1580}
        results = set(map(lambda p: p.pid, p.children))
        self.assertEqual(expected, results)

    def test_environment_variables(self):
        e = self.process.get_environment_variables()
        self.assertTrue(isinstance(e, dict))
        self.assertEqual(21, len(e))

        expected = {'FP_NO_HOST_CHECK', 'TMP', 'COMPUTERNAME', 'ComSpec', 'TEMP', 'windir', 'VS100COMNTOOLS',
                        'SystemDrive', 'PROCESSOR_ARCHITECTURE', 'NUMBER_OF_PROCESSORS', 'CommonProgramFiles',
                        'ALLUSERSPROFILE', 'PROCESSOR_IDENTIFIER', 'PROCESSOR_LEVEL', 'ProgramFiles',
                        'PROCESSOR_REVISION', 'PATHEXT', 'SystemRoot', 'USERPROFILE', 'OS', 'Path'}

        results = set(e.keys())
        self.assertEqual(expected, results)

    def test_get_executable(self):
        e = self.process.get_executable()
        self.assertTrue(isinstance(e, PE))


text:
<?php

namespace InteractiveValley\ProductosBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ProductosBundle extends Bundle
{
}


text:
layout: post
title: smoking domination
titleinfo: pornvd
desc: Watch smoking domination. Pornhub is the ultimate xxx porn and sex site.
---

smoking domination

Watch smoking domination. Pornhub is the ultimate xxx porn and sex site.


text:
var artistController = require('../controllers/artist-controller');
var likeController = require('../controllers/like-controller');
var genreController = require('../controllers/genre-controller');
var authController = require('../controllers/auth-controller');
var queue = require('../workers/queue');

module.exports = function(app, passport) {
  app.get('/auth/facebook', passport.authenticate('facebook', { scope : ['user_likes', 'user_location'] }));

  app.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    failureRedirect : '/' }),
    authController.login
  );

  app.get('/api/logout',                 authController.logout);

  app.post('/api/like/:id',              likeController.setLike);
  app.get('/api/like',                   likeController.getLikes);

  app.get('/api/artist/recommendations', artistController.getArtistRecommendations);
  app.get('/api/artist/:id',             artistController.getArtist);
  app.get('/api/artist/:id/genre',       artistController.getGenreOfArtist);

  app.get('/api/genre',                  genreController.getGenres);
  app.get('/api/genre/artists',          genreController.getArtistsByGenre);

  app.get('*', function(req, res) {
    return res.render('index.html');
  });
};


text:
package com.comcast.drivethru;

import com.comcast.drivethru.client.DefaultEasyRestClient;
import com.comcast.drivethru.client.DefaultRestClient;

/**
 * Factory for creating various HttpClients.
 *
 * @author Clark Malmgren
 */
public class RestFactory {

    /**
     * Get a new {@link RestClient} with the given defaultBaseUrl.
     *
     * @param defaultBaseUrl
     *            the default base URL to use for the created HttpClient
     *
     * @return a new {@link RestClient}
     */
    public RestClient getClient(String defaultBaseUrl) {
        return new DefaultRestClient(defaultBaseUrl);
    }

    /**
     * Get a new {@link EasyRestClient} with the given REST type and
     * defaultBaseUrl.
     *
     * @param type
     *            the Java object type used for default REST GET calls
     * @param defaultBaseUrl
     *            the default base URL to use for the created HttpClient
     *
     * @return a new {@link EasyRestClient}
     */
    public <T> EasyRestClient<T> getEasyClient(Class<T> type, String defaultBaseUrl) {
        return new DefaultEasyRestClient<>(type, defaultBaseUrl);
    }
}


text:
'use strict';

const express = require('express');
const router = express.Router();
const ctrl = require('../controllers/trade');

// The first parameter is the destination of the info.
// On slash ('/') when there is a GET/POST do ctrl.whatever
router.get(`/`, ctrl.index);
router.post(`/`, ctrl.buy);

module.exports = router;


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

namespace Squid
{
    /// <summary>
    /// The Tooltip base class. Inherit this to create custom Tooltip controls.
    /// </summary>
    public abstract class Tooltip : Frame
    {
        /// <summary>
        /// Gets or sets the offset.
        /// </summary>
        /// <value>The offset.</value>
        public Point Offset { get; set; }

        /// <summary>
        /// Gets or sets the alignment.
        /// </summary>
        /// <value>The alignment.</value>
        public Alignment Alignment { get; set; }

        ///// <summary>
        ///// Gets or sets a value indicating whether [auto layout].
        ///// </summary>
        ///// <value><c>true</c> if [auto layout]; otherwise, <c>false</c>.</value>
        //public bool AutoLayout { get; set; }

        public Tooltip()
        {
            //AutoLayout = true;
            Alignment = Alignment.BottomRight;
            Offset = new Point(-8, -8);
        }

        /// <summary>
        /// Sets the context.
        /// </summary>
        /// <param name="context">The context.</param>
        public abstract void SetContext(Control context);

        public virtual void LayoutTooltip()
        {
            Point p = Gui.MousePosition;

            switch (Alignment)
            {
                case Alignment.TopLeft:
                    p = Gui.MousePosition;
                    break;
                case Alignment.TopRight:
                    p = Gui.MousePosition - new Point(Size.x, 0);
                    break;
                case Alignment.TopCenter:
                    p = Gui.MousePosition - new Point(Size.x / 2, 0);
                    break;
                case Alignment.MiddleLeft:
                    p = Gui.MousePosition - new Point(0, Size.y / 2);
                    break;
                case Alignment.MiddleRight:
                    p = Gui.MousePosition - new Point(Size.x, Size.y / 2);
                    break;
                case Alignment.MiddleCenter:
                    p = Gui.MousePosition - new Point(Size.x / 2, Size.y / 2);
                    break;
                case Alignment.BottomRight:
                    p = Gui.MousePosition - new Point(Size.x, Size.y);
                    break;
                case Alignment.BottomLeft:
                    p = Gui.MousePosition - new Point(0, Size.y);
                    break;
                case Alignment.BottomCenter:
                    p = Gui.MousePosition - new Point(Size.x / 2, Size.y);
                    break;
            }

            p += Offset;

            if (p.x < 0) p.x = 0;
            if (p.y < 0) p.y = 0;

            Point p2 = p + Size;

            if (p2.x > Desktop.Size.x)
                p.x = Desktop.Size.x - Size.x;

            if (p2.y > Desktop.Size.y)
                p.y = Desktop.Size.y - Size.y;

            Position = p;
            PerformUpdate();
        }
    }
}


text:
//
//  SHConstants.h
//  SHModelObject
//
//  Created by SHAN UL HAQ on 4/4/15.
//  Copyright (c) 2015 grevolution. All rights reserved.
//

#ifndef SHModelObject_SHConstants_h
#define SHModelObject_SHConstants_h

/**
 *  Date option conversion enum to be passed to the serializer constructer
 */
typedef enum {
    kDateConverstionFromNSStringToNSStringOption = 0,      // do not convert, keep NSString as it is.
    kDateConverstionFromNSStringToNSDateOption = 1,        // convert NSString to NSDate
    kDateConverstionFromNSStringToNSTimeIntervalOption = 2 // convert NSString to NSTimeInterval
} kDateConversionOption;

/**
 *  enum for identifying the input date type.
 */
typedef NS_ENUM(int, kInputDateFormat) {
    kInputDateFormatJSON = 1,
    kInputDateFormatDotNetSimple = 2,
    kInputDateFormatDotNetWithTimeZone = 3,
    kInputDateFormatCustom = -1,
};

#endif


text:
::
:: Copyright 2014-2015 CyberVision, Inc.
::
:: Licensed 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.
::

@echo off

setlocal

call env.bat
SET BUILD_HOME=%CD%
SET BUILD_TYPE=debug

if "%1" == "" goto startBuild
if /i %1 == release call :setRelease

:startBuild

call :buildKaaThirdparty
goto :eof

:setRelease
  SET BUILD_TYPE=release
goto :eof

:buildKaaThirdparty
   echo Building Kaa thirdparty components...
   call :buildAvro
   call :buildBotan
goto :eof

:buildAvro
 echo Building Avro...

 SET AVRO_SRC=avro-src-1.7.5

 IF EXIST %AVRO_SRC%\NUL (
   call :deleteDir %AVRO_SRC%
 )

 7z x -y %AVRO_SRC%.tar.gz
 7z x -y %AVRO_SRC%.tar

 md %AVRO_SRC%\lang\c++\build.win
 cd %AVRO_SRC%\lang\c++\build.win

 if %BUILD_TYPE%==debug (
    cmake .. -DCMAKE_INSTALL_PREFIX:PATH=%AVRO_ROOT_DIR% -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Debug
 ) else (
    cmake .. -DCMAKE_INSTALL_PREFIX:PATH=%AVRO_ROOT_DIR% -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release
 )
 nmake install

 cd %BUILD_HOME%

goto :eof

:buildBotan

 echo Building Botan...

 SET BOTAN_SRC=Botan-1.10.9

 IF EXIST %BOTAN_SRC%\NUL (
   call :deleteDir %BOTAN_SRC%
 )

 7z x -y -obotan_archive Botan-1.10.9.tgz
 7z x -y -o. botan_archive\Botan-1.10.9.tgz

 cd %BOTAN_SRC%

 if %BUILD_TYPE%==debug (
   python configure.py --cc=msvc --cpu=i386 --prefix=%BOTAN_ROOT% --enable-debug
 ) else (
   python configure.py --cc=msvc --cpu=i386 --prefix=%BOTAN_ROOT%
 )

 nmake install

 cd %BUILD_HOME%

goto :eof

:deleteDir
 del /s /f /q %1\*.*
 for /f %%f in ('dir /ad /b %1\') do rd /s /q %1\%%f
 rd /s /q %1
goto :eof

endlocal


text:
<?php

/*
 *---------------------------------------------------------------
 * CONFIGURATION
 *---------------------------------------------------------------
 *
 * Different variables to be configured
 */

// The directory where your pointclouds are saved
define("DATAFOLDER", "data");

// The filenames of the pointclouds
define("PCFILE", "pc.csv");
define("PCINFO", "info.csv");
define("PCIMG", "img.png");

// Can be development or production
define("ENVIRONMENT", "development");

// The development url
define("DEVELURL", "http://localhost/srv.uib.es/pointclouds/");

// The production url
define("PRODURL", "http://srv.uib.es/pointclouds/");

/*
 *---------------------------------------------------------------
 * URL PARSER
 *---------------------------------------------------------------
 *
 * Parses the url and load the correct page.
 */

// Parse the url
include('app/helpers/url.php');
$pathInfo = parsePath();

// Load pages
if (sizeof($pathInfo['call_parts']) > 0) {
  $page = $pathInfo['call_parts'][0];
  switch ($page) {
    case 'view':
      $pcFolder = (isset($_REQUEST['c']) ? $_REQUEST['c'] : null);
      include('app/views/viewer.php');
      break;
    case '404':
      include('app/views/404.php');
      break;
    default:
      include('app/views/home.php');
      break;
  }
}
else {
  include('app/views/home.php');
}

?>


text:
using System;
using System.Reflection;
using System.Security.Cryptography;

namespace Leak.Meta.Store
{
    public static class HashExtensions
    {
        private static readonly MethodInfo hashCore;
        private static readonly MethodInfo hashFinal;

        static HashExtensions()
        {
            Type target = typeof(HashAlgorithm);
            BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;

            hashCore = target.GetMethod("HashCore", flags);
            hashFinal = target.GetMethod("HashFinal", flags);
        }

        public static void Push(this HashAlgorithm algorithm, byte[] data, int offset, int count)
        {
            hashCore.Invoke(algorithm, new object[] { data, offset, count });
        }

        public static byte[] Complete(this HashAlgorithm algorithm)
        {
            return (byte[])hashFinal.Invoke(algorithm, new object[] { });
        }
    }
}


text:
from setuptools import setup, find_packages
import os

setup(
    name='rasblite',
    version='1.0.0',
    url='https://github.com/timrainbow/rasblite',
    download_url='https://github.com/timrainbow/rasblite/archive/1.0.0.tar.gz',
    license='MIT License',
    author='Tim Rainbow',
    author_email='tim@timrainbow.com',
    description='Lightweight RESTful API Server Builder',
    keywords = ['REST', 'RESTFul', 'testing', 'Lightweight', 'HTTP', 'server', 'builder'],
    entry_points={
        'console_scripts': [
            'rasblite-run = rasblite.run:command_line_run',
            ],
        },
    packages=find_packages(exclude=('tests', 'docs')),
    package_data={'rasblite': ['rasblite/resources/*.ico']},
    include_package_data=True,
    classifiers=[
        'Programming Language :: Python :: 3 :: Only',
        'Development Status :: 5 - Production/Stable',
        'Natural Language :: English',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: Unix',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content']
)


text:
/**
 * @overview
 */

/**
 * Creates an "accept share" dialog.
 * @class
 * This class represents an "accept share" dialog.
 *
 * @param	{DwtControl}	parent		the parent
 * @param	{String}	className		the class name
 *
 * @extends		DwtDialog
 */
ZmAcceptShareDialog = function(parent, className) {
	className = className || "ZmAcceptShareDialog";
	DwtDialog.call(this, {parent:parent, className:className, title:ZmMsg.acceptShare,
						  standardButtons:[DwtDialog.YES_BUTTON, DwtDialog.NO_BUTTON], id: "ZmAcceptShare"});
	this.setButtonListener(DwtDialog.YES_BUTTON, new AjxListener(this, this._handleYesButton));
	this.setButtonListener(DwtDialog.NO_BUTTON, new AjxListener(this, this._handleNoButton));

	this.setView(this._createView());

	// create formatters
	this._headerFormatter = new AjxMessageFormat(ZmMsg.acceptShareHeader);
	this._detailsFormatter = new AjxMessageFormat(ZmMsg.acceptShareDetails);
};

ZmAcceptShareDialog.prototype = new DwtDialog;
ZmAcceptShareDialog.prototype.constructor = ZmAcceptShareDialog;

// Constants

ZmAcceptShareDialog._ACTIONS = {};
ZmAcceptShareDialog._ACTIONS[ZmShare.ROLE_NONE]		= ZmMsg.acceptShareDetailsNone;
ZmAcceptShareDialog._ACTIONS[ZmShare.ROLE_VIEWER]	= ZmMsg.acceptShareDetailsViewer;
ZmAcceptShareDialog._ACTIONS[ZmShare.ROLE_MANAGER]	= ZmMsg.acceptShareDetailsManager;
ZmAcceptShareDialog._ACTIONS[ZmShare.ROLE_ADMIN]	= ZmMsg.acceptShareDetailsAdmin;

// Public methods

/**
 * Pops-up the dialog.
 *
 * @param	{ZmShare}		share		the share
 * @param	{String}		fromAddr	the from address
 */
ZmAcceptShareDialog.prototype.popup =
function(share, fromAddr) {

	this._share = share;
	this._fromAddr = fromAddr;
	this._headerEl.innerHTML = this._headerFormatter.format([share.grantor.name || share.grantor.email, AjxStringUtil.htmlEncode(share.link.name)]);

	var role = ZmShare._getRoleFromPerm(share.link.perm);
	var params = [
		ZmShare.getRoleName(role),
		ZmAcceptShareDialog._ACTIONS[role]   // TODO: Be able to generate custom perms list
	];
	this._detailsEl.innerHTML = this._detailsFormatter.format(params);
	this._questionEl.innerHTML = "<b>" + ZmMsg.acceptShareQuestion + "</b>";

	var namePart = share.grantor.name || (share.grantor.email && share.grantor.email.substr(0, share.grantor.email.indexOf('@')));
	this._nameEl.value = ZmShare.getDefaultMountpointName(namePart, share.link.name);

	this._reply.setReplyType(ZmShareReply.NONE);
	this._reply.setReplyNote("");

	var orgType = ZmOrganizer.TYPE[share.link.view];
	var icon = null;
	var orgClass = ZmOrganizer.ORG_CLASS[orgType];
	if (orgClass) {
		var orgPackage = ZmOrganizer.ORG_PACKAGE[orgType];
		if (orgPackage) {
			AjxDispatcher.require(orgPackage);
			//to fix bug 55320 - got rid of the calling getIcon on the prototype hack - that caused isRemote to set _isRemote on the prototype thus causing every object to have it by default set.
			var sample = new window[orgClass]({}); //get a sample object just for the icon
			sample._isRemote = true; //hack - so it would get the remote version of the icon
			icon = sample.getIcon();
		}
	}
	this._color.setImage(icon);
	this._color.setValue(ZmOrganizer.DEFAULT_COLOR[orgType]);

	DwtDialog.prototype.popup.call(this);
};

/**
 * Sets the accept listener.
 *
 * @param	{AjxListener}		listener		the listener
 */
ZmAcceptShareDialog.prototype.setAcceptListener =
function(listener) {
	this.removeAllListeners(ZmAcceptShareDialog.ACCEPT);
	if (listener) {
		this.addListener(ZmAcceptShareDialog.ACCEPT, listener);
	}
};

// Protected methods

ZmAcceptShareDialog.prototype._handleYesButton =
function(ev) {
	var replyType = this._reply.getReplyType();
	var notes = (replyType == ZmShareReply.QUICK) ? this._reply.getReplyNote(): "";
	var callback = new AjxCallback(this, this._yesButtonCallback, [ev]);
	this._share.accept(this._nameEl.value, this._color.getValue(), replyType, notes, callback, this._fromAddr);
};

ZmAcceptShareDialog.prototype._yesButtonCallback =
function(ev) {
	// notify accept listener and clear
	this.notifyListeners(ZmAcceptShareDialog.ACCEPT, ev);
	this.setAcceptListener(null);
	this.popdown();
};

ZmAcceptShareDialog.prototype._handleNoButton =
function(ev) {
	this.popdown();
};

ZmAcceptShareDialog.prototype._getSeparatorTemplate =
function() {
	return "";
};

ZmAcceptShareDialog.prototype._createView =
function() {
	var view = new DwtComposite(this);

	this._headerEl = document.createElement("DIV");
	this._headerEl.style.marginBottom = "0.5em";
	this._detailsEl = document.createElement("DIV");
	this._detailsEl.style.marginBottom = "1em";
	this._detailsEl.id = "ZmAcceptShare_details";
	this._questionEl = document.createElement("DIV");
	this._questionEl.style.marginBottom = "0.5em";
	this._questionEl.id = "ZmAcceptShare_questions";
	this._nameEl = document.createElement("INPUT");
	this._nameEl.style.width = "20em";
	this._nameEl.id = "ZmAcceptShare_name";
	var nameElement = this._nameEl;

	this._color = new ZmColorButton({parent:this, id: "ZmAcceptShare_color"});

	var props = this._propSheet = new DwtPropertySheet(view);
	var propsEl = props.getHtmlElement();
	propsEl.style.marginBottom = "0.5em";
	propsEl.id = "ZmAcceptShare_props";
	props.addProperty(ZmMsg.nameLabel, nameElement);
	props.addProperty(ZmMsg.colorLabel, this._color);

	this._reply = new ZmShareReply(view);

	var settings = document.createElement("DIV");
	settings.style.marginLeft = "1.5em";
	settings.id = "ZmAcceptShare_settings";
	settings.appendChild(propsEl);
	settings.appendChild(this._reply.getHtmlElement());

	var el = view.getHtmlElement();
	el.appendChild(this._headerEl);
	el.appendChild(this._detailsEl);
	el.appendChild(this._questionEl);
	el.appendChild(settings);
	return view;
};


text:
<?php

class AccountPage extends Page {

	// Properties
	private $existingPasswordError;
	private $newPasswordError;
	private $confirmPasswordError;
	private $passwordChangeMessage;
	private $userDeleteError;
	private $userEnableError;
	private $userEnableSuccess;
	private $userDeleteSuccess;
	private $profileImageError;

	private $firstName;
	private $firstNameError;
	private $lastName;
	private $lastNameError;
	private $bio;
	private $bioError;
	private $job;
	private $jobError;

	private $staffErrorMessage;
	private $staffSuccessMessage;

	private $newDealDateError;
	private $totalErrors = 0;

	private $dealImageError;

	private $userFirstNameError;
	private $userLastNameError;
	private $userBioError;
	private $userImageError;
	private $userFirstName;
	private $userLastName;
	private $userBio;

	private $userSuccess;
	private $userFail;

	public function __construct($model) {
		parent::__construct($model);

		// If the user has submitted the password change form
		if( isset($_POST['existing-password']) ) {
			$this->processPasswordChange();
		}

		// If the user is inserting / updating additional info
		if( isset($_POST['user-data']) ) {
			$this->processAdditionalInfo();
		}

		// If user is an admin
		if( isset($_SESSION['privilege']) && $_SESSION['privilege'] == 'admin' ) {

			// If the admin submitted the delete function
			if( isset($_POST['delete-account']) ) {
				$this->processDeleteAccount();
			}

			// If the admin submitted the enable function
			if( isset($_POST['enable-account']) ) {
				$this->processEnableAccount();
			}

			// If the admin has submitted the add staff form
			if( isset($_POST['add-staff']) ) {
				$this->processAddStaff();
			}

			// If the add deal form has been submitted
			if( isset($_POST['add-deal']) ) {
				// echo '<pre>';
				// print_r($_POST);
				// die();
				$this->processAddDeal();
			}

		}

	}

	public function contentHTML() {

		// Make sure the user is logged in
		// If not then offer them a login or registration link
		if( !isset($_SESSION['username']) ) {
			echo 'You need to be logged in';
			return;
		}

		include 'templates/accountpage.php';

		// If user is an admin
		if( $_SESSION['privilege'] == 'admin' ) {

			include 'templates/admincontrols.php';

		}

	}

	private function processPasswordChange() {

		// Make life easier
		$existingPass = $_POST['existing-password'];
		$newPass      = $_POST['new-password'];
		$confirmPass  = $_POST['confirm-password'];

		// Validate
		if( strlen($existingPass) == 0 ) {
			$this->existingPasswordError = 'Required';
		} elseif( !$this->model->checkPassword($existingPass) ) {
			$this->existingPasswordError = 'Incorrect password';
		}

		if( strlen($newPass) < 8 ) {
			$this->newPasswordError = 'Needs to be more than 8 characters';
		}

		if( strlen($confirmPass) < 8 ) {
			$this->confirmPasswordError = 'Needs to be more than 8 characters';
		} elseif( $confirmPass != $newPass ) {
			$this->confirmPasswordError = 'Does not match the new password';
		}

		// If no errors
		if( $this->existingPasswordError == '' && $this->newPasswordError == '' && $this->confirmPasswordError == '' ) {

			// Update the password
			$result = $this->model->updatePassword();

			// If updating the password was a success
			if( $result ) {
				$this->passwordChangeMessage = 'Successfully changed your password!';
			} else {
				$this->passwordChangeMessage = 'Something went wrong updating your password...';
			}

		}

	}

	private function processDeleteAccount() {

		// Get the username to delete from the form
		$username = $_POST['username'];

		// If the username is the same as the person who is logged in
		if( $username == $_SESSION['username'] ) {
			$this->userDeleteError = 'You cannot delete your own account!';
		}

		// If no errors
		if( $this->userDeleteError == '' ) {
			// Send it to the model for deleting
			$this->model->deleteAccount($username);
			$this->userDeleteSuccess = 'Successfully disabled the account!';
		}

	}

	private function processEnableAccount() {

		// Validation
		if( isset($_POST['username']) ) {
			$username = $_POST['username'];
		} else {
			$this->userEnableError = 'No username selected!';
		}

		// If there are no errors
		if( $this->userEnableError == '' ) {
			$this->model->enableAccount($username);
			$this->userEnableSuccess = 'Successfully enabled the account!';
		}

	}

	private function processAddStaff() {

		// Make forms sticky
		$this->firstName = trim($_POST['first-name']);
		$this->lastName  = trim($_POST['last-name']);
		$this->bio       = trim($_POST['bio']);
		$this->job       = trim($_POST['job-title']);

		// Validate the form and make sure the user has provided all the appropriate fields
		if( strlen($this->firstName) < 2 ) {
			$this->firstNameError = 'Name must be at least 2 characters';
		} elseif( strlen($this->firstName) > 20 ) {
			$this->firstNameError = 'Name must be at most 20 characters';
		} elseif( !preg_match('/^[a-zA-Z-]{2,20}$/', $this->firstName) ) {
			$this->firstNameError = 'Only allowed letters and hyphens. No spaces.';
		}

		if( strlen($this->lastName) < 2 ) {
			$this->lastNameError = 'Name must be at least 2 characters';
		} elseif( strlen($this->lastName) > 20 ) {
			$this->lastNameError = 'Name must be at most 20 characters';
		} elseif( !preg_match('/^[a-zA-Z-]{2,20}$/', $this->lastName) ) {
			$this->lastNameError = 'Only allowed letters and hyphens. No spaces.';
		}

		if( strlen($this->bio) > 200 ) {
			$this->bioError = 'Bio must be at most 200 characters. You have gone over by '.(strlen($this->bio) - 200);
		} elseif( !preg_match('/^[\w.\-\s]{2,200}$/', $this->bio ) ) {
			$this->bioError = 'Only allowed letters, hyphens, spaces and full stops.';
		}

		if( strlen($this->job) > 30 ) {
			$this->jobError = 'Job must be at most 30 characters. You have '.strlen($this->job);
		} elseif( !preg_match('/^[\w\-\s\.]{2,30}$/', $this->job) ) {
			$this->jobError = 'Only allowed letters, hyphens, spaces and full stops.';
		}

		// Make life easier
		$file      = $_FILES['profile-image'];
		$imageName = $file['name'];

		// If the user has not provided an image
		if( $imageName == '' ) {
			$this->profileImageError = 'Required!';
		} elseif( 	$this->firstNameError == ''
					&& $this->lastNameError == ''
					&& $this->bioError == ''
					&& $this->jobError == '' ) {

			// Require the image upload class
			require 'vendor/ImageUploader.php';

			// Instantiate (create) the class
			$imageUploader = new ImageUploader();

			// Make a new file name based on the staff members name
			$fileName = $this->firstName.'-'.$this->lastName;

			// Upload the image and make sure all went well
			$result = $imageUploader->upload( 'profile-image', 'img/staff/original/', $fileName );

			// If something went wrong
			if( !$result ) {
				$this->profileImageError = $imageUploader->errorMessage;
			} else {
				$newImage = $imageUploader->getImageName();
				$imageUploader->resize( 'img/staff/original/'.$newImage, 320, 'img/staff/thumbnails/', $newImage );
			}

			// If there are no errors then insert a new staff member!
			if( $this->profileImageError == '' ) {
				$result = $this->model->addNewStaff( $newImage );

				// If success
				if( $result ) {
					$this->staffSuccessMessage = 'Success!';
				} else {
					$this->staffErrorMessage = 'Something went wrong in the database :(';
				}

			}

		}

	}

	private function processAddDeal() {

		// Sticky forms

		// Validation

		// Make sure the start date is before the end date
		$startDate 	= $_POST['start-year'].'-'.$_POST['start-month'].'-'.$_POST['start-day'];
		$startDate .= ' '.$_POST['start-hour'].':'.$_POST['start-minute'].':'.$_POST['start-second'];

		$endDate 	= $_POST['end-year'].'-'.$_POST['end-month'].'-'.$_POST['end-day'];
		$endDate .= ' '.$_POST['end-hour'].':'.$_POST['end-minute'].':'.$_POST['end-second'];

		if( new DateTime($startDate) > new DateTime($endDate) ) {
			$this->newDealDateError = 'End date is before start date';
			$this->totalErrors++;
		} elseif( new DateTime() > new DateTime($endDate) ) {
			$this->newDealDateError = 'End date is before today';
			$this->totalErrors++;
		}

		// If a file has not been provided
		if( $_FILES['image']['error'] == 4 ) {
			$this->dealImageError = 'Image required!';
			$this->totalErrors++;
		} elseif( $this->totalErrors == 0 ) {

			// Attempt to upload the file
			require 'vendor/ImageUploader.php';

			// Create an instance of the image uploader
			$imageUploader = new ImageUploader();

			// Attempt to upload the image
			$uploadResult = $imageUploader->upload('image', 'img/deals/original/');

			// If something went wrong
			if( $uploadResult == false ) {
				$this->dealImageError = $imageUploader->errorMessage;
				$this->totalErrors++;
			} else {

				// Get the name of the file that was just uploaded
				$imageName = $imageUploader->getImageName();
				$_POST['newFileName'] = $imageName;

				// Resize the image into a thumbnail
				$imageUploader->resize('img/deals/original/'.$imageName, 628, 'img/deals/thumbnails/', $imageName);

			}

		}

		// Add the deal
		if($this->totalErrors == 0) {
			$this->model->addNewDeal();
		}

	}

	private function processAdditionalInfo() {

		// Validation
		if( strlen($_POST['first-name']) < 2 ) {
			$this->userFirstNameError = 'Needs to be at least 2 characters';
			$this->totalErrors++;
		} elseif( strlen($_POST['first-name']) > 20 ) {
			$this->userFirstNameError = 'Needs to be at most 20 characters';
			$this->totalErrors++;
		} elseif( !preg_match('/^[a-zA-Z \-]{2,20}$/', $_POST['first-name']) ) {
			$this->userFirstNameError = 'Can only use characters of the alphabet, spaces and hyphens';
			$this->totalErrors++;
		}

		if( strlen($_POST['last-name']) < 2 ) {
			$this->userLastNameError = 'Needs to be at least 2 characters';
			$this->totalErrors++;
		} elseif( strlen($_POST['last-name']) > 20 ) {
			$this->userLastNameError = 'Needs to be at most 20 characters';
			$this->totalErrors++;
		} elseif( !preg_match('/^[a-zA-Z \-]{2,20}$/', $_POST['last-name']) ) {
			$this->userLastNameError = 'Can only use characters of the alphabet, spaces and hyphens';
			$this->totalErrors++;
		}

		if( strlen($_POST['bio']) > 2000 ) {
			$this->userBioError = 'Cannot be more than 2000 characters';
			$this->totalErrors++;
		}

		// Attempt to upload the image
		if( $this->totalErrors == 0 && isset($_FILES['profile-image']) && $_FILES['profile-image']['name'] != '' ) {

			// Require the image uploader
			require 'vendor/ImageUploader.php';

			// Create instance of the Image Uploader
			$imageUploader = new ImageUploader();

			// Attempt to upload the file
			$result = $imageUploader->upload('profile-image', 'img/profile-images/original/');

			// If the upload was a success
			if( $result == true ) {

				// Get the file name
				$imageName = $imageUploader->getImageName();

				// Prepare the variables
				$fileLocation = "img/profile-images/original/$imageName";
				$destination = "img/profile-images/avatar/";

				// Make the avatar version
				$imageUploader->resize($fileLocation, 320, $destination, $imageName);

				// Make the icon version
				$destination = "img/profile-images/icon/";
				$imageUploader->resize($fileLocation, 32, $destination, $imageName);

				$_POST['newUserImage'] = $imageName;
			} else {
				// Something went wrong
				$this->totalErrors++;
				$this->userImageError = $imageUploader->errorMessage;
			}

		}

		if( $this->totalErrors == 0 ) {
			$result = $this->model->additionalInfo();

			// If the result was good
			if( $result ) {
				$this->userSuccess = 'Successfully changed your info';
			} else {
				$this->userFail = 'Info not updated';
			}

		}

	}

}


text:
Quick start
===========

  * The presentation can be found
    [here](http://moble.github.io/MatchedFiltering/Presentation.slides.html).
  * A preview of the notebook can be seen
    [here](http://nbviewer.ipython.org/github/moble/MatchedFiltering/blob/gh-pages/MatchedFiltering.ipynb),
    but note that there are cool interactive things that are missing
    unless you download and run it yourself.

Details
=======

This package is designed to be a simple demonstration of the principles of matched filtering.  It
uses the analogy of LIGO as a microphone to explain the basic ideas, using a microphone attached to
the computer to study data as a function of time, noise sources, and real signals, as well as
headphones or a speaker to play back those signals and others.  Examples are given where a signal is
buried in the noise and extracted using matched filtering.  Real LIGO data and accurate
gravitational waveforms are also included with this code, and used for further examples to complete
the analogy.  The concepts introduced here can be applied far more widely in all areas of data
analysis.

Fourier transforms are introduced, starting with a simple example of a pure tone (which can be
played by the computer), and progressing to Fourier transforms of noise and gravitational-wave
signals.  The matched filter is then introduced by progressively building the formula with simple
explanations for each term.  Discussion of these concepts is interwoven with practice using them.

The material is presented as a Jupyter notebook — which looks and acts basically like Mathematica.
The notebook includes text explaining the concepts and code.  This allows the explanations to be
included (with latex equations) right among the code, and all in a live python session.  No
familiarity with python is necessary for the student, though the computer will need to be set up by
someone with good technical skills.

A second notebook is also included for more demonstrations of the Fourier transform.  This notebook
makes it easy to record a sound — tuning forks, musical instruments, or whatever the student is
curious about — and look at its Fourier transform.  This encourages the student to play with the
ideas a little, experimenting to gain understanding.

To run the code
===============

If you are reading this README from the github project page, you should first download the package
to your own computer with something like
```bash
git clone --depth 1 https://github.com/moble/MatchedFiltering.git
```
Otherwise, you are presumably reading this in the code itself.

You also need `ipython`, `matplotlib`, `numpy`, `scipy`, `h5py`, `jupyter`, a very recent (>5.0)
version of `ipywidgets`, and `widgetsnbextension` installed.  The easiest way to do all this is to
just [install `conda`](https://www.continuum.io/downloads) and run

```bash
conda update -c conda-forge -y --all
conda install -c conda-forge ipython jupyter notebook scipy matplotlib ipywidgets widgetsnbextension
```
Otherwise, all of these packages can also be installed using `pip`.

Now, from the `MatchedFiltering` directory, issue the command
```bash
    jupyter notebook MatchedFiltering.ipynb
```
This will start an ipython session, but should switch to your default web browser, where you will
interact with the session.

Notes for classroom use
=======================

There are three reasonable ways to deliver this demonstration to students: as a presentation,
individually on the students' personal computers, and together in a computer lab.

Most likely, the presentation option is the least useful to students.  Most students benefit
enormously from being able to interact with the notebook personally.  They will be more interested,
able to read along at their own pace, and play with the parameters.  If this is just not possible,
it would be best to go slowly and ask lots of questions of the students, possibly allowing one
student to actually run the commands while the teacher engages from off to the side.

A preferable option may be having the students download and run the code themselves.  The only
caveat here is that the students will need to install the dependencies.
With [anaconda](https://store.continuum.io/anaconda/), this is not a problem.  Assuming the students
can run it, there are questions included in the notebook.  Their answers could be turned in as a
homework assignment, or a quiz given on the material to ensure that students actually go through the
notebook.

If this will be presented together in a computer lab, it is best if things are set up as much as
possible on each computer beforehand.  The computers need to be using different accounts (with home
directories not on a shared file system), or ipython will get screwed up and run into errors.


text: html5boilerplate + roots.io/sage gulp setup


text:
using System;
using System.Threading.Tasks;
using Moq;
using AutoFixture.Xunit2;
using SlackConnector.Connections;
using SlackConnector.Connections.Clients.Channel;
using SlackConnector.Connections.Models;
using SlackConnector.Connections.Sockets;
using SlackConnector.Models;
using SlackConnector.Tests.Unit.TestExtensions;
using Xunit;
using Shouldly;

namespace SlackConnector.Tests.Unit.SlackConnectionTests
{
    public class ArchiveChannelTests
    {
        [Theory, AutoMoqData]
        private async Task should_be_successful(
            [Frozen]Mock<IConnectionFactory> connectionFactory,
            Mock<IChannelClient> channelClient,
            Mock<IWebSocketClient> webSocket,
            SlackConnection slackConnection)
        {
            // given
            const string slackKey = "key-yay";
            const string channelName = "public-channel-name";

            var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey };
            await slackConnection.Initialise(connectionInfo);

            connectionFactory
                .Setup(x => x.CreateChannelClient())
                .Returns(channelClient.Object);

            // when
             await slackConnection.ArchiveChannel(channelName);

            // then
            channelClient.Verify(x => x.ArchiveChannel(slackKey, channelName), Times.Once);
        }

        [Theory, AutoMoqData]
        private async Task should_throw_exception_given_null_channel_name(
            Mock<IWebSocketClient> webSocket,
            SlackConnection slackConnection)
        {
            // given
            var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object };
            await slackConnection.Initialise(connectionInfo);

            // when
            var exception = await Assert.ThrowsAsync<ArgumentNullException>(() => slackConnection.ArchiveChannel(null));

            // then
            exception.Message.ShouldBe("Value cannot be null.\r\nParameter name: channelName");
        }

        [Theory, AutoMoqData]
        private async Task should_throw_exception_given_empty_channel_name(Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
        {
            // given
            var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object };
            await slackConnection.Initialise(connectionInfo);

            // when
            var exception = await Assert.ThrowsAsync<ArgumentNullException>(() => slackConnection.ArchiveChannel(string.Empty));

            // then
            exception.Message.ShouldBe("Value cannot be null.\r\nParameter name: channelName");
        }
    }
}


text:
struct QMOD {
  bool read;
  bool write;
  bool execute;
};

class QLdd {
 public:

  QLdd(QString fileName, QString lddDirPath);
  virtual ~QLdd();

  int64_t getFileSize() const;
  const QString &getStringFileSize() const;

  void fillDependency(QTreeWidget &treeWidget);

  void fillExportTable(QListWidget &listWidget, const QString& filter);

  QString getPathOfBinary();
  QString getBinaryName();

  const QString &getCreatedTime();
  const QString &getAccessTime();
  const QString &getModifyTime();

  QString getInfo();

  const QMOD &getOwnerMod() const;
  void setOwnerMod(const QMOD &ownerMod);

  const QMOD &getGroupMod() const;
  void setGroupMod(const QMOD &groupMod);

  const QMOD &getOtherMod() const;
  void setOtherMod(const QMOD &otherMod);

  const QString &getOwnerName() const;
  void setOwnerName(const QString &ownerName);

  const QString &getGroupName() const;
  void setGroupName(const QString &groupName);

 private:
  QString _fileName;
  QFileInfo _fileInfo;
  bool _link;
  QString _tmCreate;
  QString _tmAccess;
  QString _tmModify;
  QString _lddDirPath;
  QString _fileSize;
  QMOD _ownerMod{};
  QMOD _groupMod{};
  QMOD _otherMod{};
  QString _ownerName;
  QString _groupName;
  QString getHumanReadableDataSize() const;
};

#endif  // QLDD_H


text:
.class final Landroid/service/notification/StatusBarNotification$1;
.super Ljava/lang/Object;
.source "StatusBarNotification.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/service/notification/StatusBarNotification;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Landroid/service/notification/StatusBarNotification;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 129
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/service/notification/StatusBarNotification;
    .locals 1
    .parameter "parcel"

    .prologue
    .line 132
    new-instance v0, Landroid/service/notification/StatusBarNotification;

    invoke-direct {v0, p1}, Landroid/service/notification/StatusBarNotification;-><init>(Landroid/os/Parcel;)V

    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 129
    invoke-virtual {p0, p1}, Landroid/service/notification/StatusBarNotification$1;->createFromParcel(Landroid/os/Parcel;)Landroid/service/notification/StatusBarNotification;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/service/notification/StatusBarNotification;
    .locals 1
    .parameter "size"

    .prologue
    .line 137
    new-array v0, p1, [Landroid/service/notification/StatusBarNotification;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 129
    invoke-virtual {p0, p1}, Landroid/service/notification/StatusBarNotification$1;->newArray(I)[Landroid/service/notification/StatusBarNotification;

    move-result-object v0

    return-object v0
.end method


text:
{% load i18n %}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<title>Sign in with your OpenID</title>

Sign in with your OpenID

{% if form.errors %}

{% trans "Please correct errors below:" %}

    {% if form.openid_identifier.errors %}
    {{ form.openid_identifier.errors|join:", " }}
    {% endif %}
    {% if form.next.errors %}
    {{ form.next.errors|join:", " }}
    {% endif %}

{% endif %}
<form name="fopenid" action="{{ action }}" method="post">
    {% csrf_token %}
    <fieldset>
        <legend>{% trans "Sign In Using Your OpenID" %}</legend>

            {% trans "OpenID:" %}

            {{ form.openid_identifier }}

            <input name="bsignin" type="submit" value="{% trans "Sign in" %}">

 {% if next %}
        <input type="hidden" name="next" value="{{ next }}" />
 {% endif %}
    </fieldset>
</form>


text:
/*
    FriendActivityController: A controller that handles activity of friends that is a part of friends tab in dashboard.html
*/
angular.module('app')
  .constant('friendactivity', {
    page_size: 5,
    url_base: 'https://envirocar.org/api/stable/users/',
    friend: '/friendActivities?',
    avatar: '/avatar'

  });
  angular.module('app')
  .controller('FriendActivityController', ['$scope', '$http', '$rootScope',
    '$stateParams',
    '$state', 'friendactivity',
    function ($scope, $http, $rootScope, $stateParams, $state, friendactivity) {
      $scope.totalLoading = true;
      $scope.fetchingResults = false;
      $scope.show_no_my_activity = false
      $scope.originaluser = false
      $scope.events = []
      var eventshelper = []
      $scope.busy = false
      $scope.page = 0
      $scope.page_size = friendactivity.page_size
      $http.defaults.headers.common = {
        'X-User': $rootScope.globals.currentUser.username,
        'X-Token': $rootScope.globals.currentUser.authdata
      }
      var username
      if ($stateParams.user == '') {
        $scope.originaluser = true
        username = $rootScope.globals.currentUser.username
      } else {
        $scope.originaluser = false
        username = $stateParams.user
        return
      }

      var fetchFlag = 0;
      $scope.nextpage = function () {
        if(fetchFlag == 1)
        {
          $scope.fetchingResults = true;
        }
        $scope.page++
        var url = friendactivity.url_base + username +
        friendactivity.friend
        $http.get(url + 'limit=' + $scope.page_size + '&page=' + $scope.page)
          .success(function (data, status, headers, config) {
            if (data.activities.length == 0) {
              $scope.show_no_my_activity = true
            }
            for (var i = 0; i < data.activities.length; i++) {
              var helper = {}
              helper['time'] = data.activities[i].time
              helper['name'] = data.activities[i].user.name
              helper['profileurl'] = friendactivity.url_base + helper['name'] + friendactivity.avatar
              helper['date'] = new Date(data.activities[i].time).toLocaleString()
              helper['color'] = '#8CBF3F'
              if (data.activities[i].type == 'FRIENDED_USER') {
                helper['type'] = 0
                helper['topic'] = 'New Friend Activity'
                helper['color'] = '#0065A0'
                if ($rootScope.globals.currentUser.username != data.activities[i].other.name)
                  helper['name'] = data.activities[i].user.name + ' is now friends with ' + data.activities[i].other.name
                else
                  helper['name'] = data.activities[i].user.name +
                  ' is now friends with you'
                helper['trackidlink'] = '';
                helper['icon'] = 'people';

              } else if (data.activities[i].type == 'CREATED_TRACK') {
                helper['type'] = 1
                helper['color'] = '#0065A0'
                helper['topic'] = 'New Track Upload'
                helper['icon'] = 'add_circle';
                helper['trackidlink'] = (data.activities[i].track !=
                undefined) ? data.activities[i].track.id :
                  'Invalid ID'
              } else if (data.activities[i].type == 'CHANGED_PROFILE') {
                helper['type'] = 0;
                helper['icon'] = 'update';
                helper['topic'] = data.activities[i].user.name +
                'Updated profile'
              } else if (data.activities[i].type == 'UNFRIENDED_USER') {
                continue
              } else if (data.activities[i].type == 'CREATED_GROUP') {
                helper['type'] = 0;
                helper['icon'] = 'speaker_groups';
                helper['topic'] = data.activities[i].user.name +
                ' created a Group'
              } else if (data.activities[i].type == 'CHANGED_GROUP') {
                helper['type'] = 0;
                helper['icon'] = 'speaker_groups';
                helper['topic'] = data.activities[i].user.name + ' changed the group'
              } else if (data.activities[i].type == 'JOINED_GROUP') {
                helper['type'] = 0;
                helper['icon'] = 'group_add';
                helper['topic'] = data.activities[i].user.name +
                ' joined the Group'
              } else if (data.activities[i].type == 'LEFT_GROUP') {
                helper['type'] = 0
                helper['topic'] = data.activities[i].user.name +
                ' left the Group'
              } else if (data.activities[i].type == 'DELETED_GROUP') {
                helper['type'] = 0
                helper['topic'] = data.activities[i].user.name +
                ' deleted the group'
              }
              eventshelper.push(helper)
            }
            $scope.events = eventshelper
            fetchFlag = 1;
            $scope.fetchingResults = false;
            $scope.totalLoading = false;
          })
      }
      $scope.nextpage($scope.page)
      $scope.goToActivity = function (activity, trackid) {
        // redirect ro a page only if it is a chart event.
        if (activity == 1) {
          $state.go('home.chart', {
            'trackid': trackid
          })
        }
      }
    }
  ]);


text:
package com.thedairyfarm.subscription;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.TextView;

import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.thedairyfarm.BaseActivity;
import com.thedairyfarm.Constants;
import com.thedairyfarm.R;
import com.thedairyfarm.retrofit.model.MySubscriptionResponse;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ManageSubscriptionActivity extends BaseActivity {
    @BindView(R.id.txt_view_screen_label)
    TextView toolbarTitleLabel;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.calendar_view)
    MaterialCalendarView customCalendarView;

    private String startDate, endDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_subscription);
        ButterKnife.bind(this);

        setUpToolbar("Manage Subscription");

        setUpCalendarView();
    }

    private void getExtraIntentData(){
        Intent intent = getIntent();
        MySubscriptionResponse.Subscription subscription = (MySubscriptionResponse.Subscription)
                intent.getSerializableExtra(Constants.EXTRA_SUBSCRIPTION_OPTION);
        if (subscription != null){
            startDate = subscription.getStartDate();
            endDate = subscription.getEndDate();
        }
    }

    /**
     * This method is used for setting up custom calendar view for
     * custom order
     */
    private void setUpCalendarView(){
        customCalendarView.setShowOtherDates(MaterialCalendarView.SHOW_ALL);
        customCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_MULTIPLE);
        customCalendarView.addDecorator(new DisableOldDateDecorator());
        customCalendarView.addDecorator(new EnableFutureDateDecorator());

        Calendar calendar = Calendar.getInstance();
        customCalendarView.setSelectedDate(calendar.getTime());

        Calendar instance1 = Calendar.getInstance();
        instance1.set(instance1.get(Calendar.YEAR), Calendar.JANUARY, 1);

        Calendar instance2 = Calendar.getInstance();
        instance2.set(instance2.get(Calendar.YEAR), Calendar.DECEMBER, 31);

        customCalendarView.state().edit()
                .setMinimumDate(instance1.getTime())
                .setMaximumDate(instance2.getTime())
                .commit();
    }

    /**
     * This static class is used for disabling date selection for older
     * date from today.
     */
    private class DisableOldDateDecorator implements DayViewDecorator {
        @Override
        public boolean shouldDecorate(CalendarDay day) {
            return day.isInRange(CalendarDay.from(new Date(startDate)), CalendarDay.today());
        }

        @Override
        public void decorate(DayViewFacade view) {
            view.setBackgroundDrawable(ContextCompat.getDrawable(ManageSubscriptionActivity.this,
                    R.drawable.drawable_unselected_date));
            view.setDaysDisabled(true);
        }
    }

    /**
     * This static class is used for disabling date selection for older
     * date from today.
     */
    private class EnableFutureDateDecorator implements DayViewDecorator {
        @Override
        public boolean shouldDecorate(CalendarDay day) {
            return day.isAfter(CalendarDay.today());
        }

        @Override
        public void decorate(DayViewFacade view) {
            view.setDaysDisabled(false);
        }
    }
}


text:
'use strict';

var _extends = require('babel-runtime/helpers/extends')['default'];

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _BootstrapMixin = require('./BootstrapMixin');

var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);

var Alert = _react2['default'].createClass({
  displayName: 'Alert',

  mixins: [_BootstrapMixin2['default']],

  propTypes: {
    onDismiss: _react2['default'].PropTypes.func,
    dismissAfter: _react2['default'].PropTypes.number,
    closeLabel: _react2['default'].PropTypes.string
  },

  getDefaultProps: function getDefaultProps() {
    return {
      bsClass: 'alert',
      bsStyle: 'info',
      closeLabel: 'Close Alert'
    };
  },

  renderDismissButton: function renderDismissButton() {
    return _react2['default'].createElement(
      'button',
      {
        type: 'button',
        className: 'close',
        onClick: this.props.onDismiss,
        'aria-hidden': 'true' },
      _react2['default'].createElement(
        'span',
        null,
        '×'
      )
    );
  },

  renderSrOnlyDismissButton: function renderSrOnlyDismissButton() {
    return _react2['default'].createElement(
      'button',
      {
        type: 'button',
        className: 'close sr-only',
        onClick: this.props.onDismiss },
      this.props.closeLabel
    );
  },

  render: function render() {
    var classes = this.getBsClassSet();
    var isDismissable = !!this.props.onDismiss;

    classes['alert-dismissable'] = isDismissable;

    return _react2['default'].createElement(
      'div',
      _extends({}, this.props, { role: 'alert', className: _classnames2['default'](this.props.className, classes) }),
      isDismissable ? this.renderDismissButton() : null,
      this.props.children,
      isDismissable ? this.renderSrOnlyDismissButton() : null
    );
  },

  componentDidMount: function componentDidMount() {
    if (this.props.dismissAfter && this.props.onDismiss) {
      this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter);
    }
  },

  componentWillUnmount: function componentWillUnmount() {
    clearTimeout(this.dismissTimer);
  }
});

exports['default'] = Alert;
module.exports = exports['default'];


text:
package training.PFT.sandbox;

/**
 * Created by User on 6/16/2016.
 */
public class Square {
  public double l;
  public Square (double l){
    this.l = l;
  }
  public double area (){
    return this.l * this.l;
  }

}


text:
<?php
//!! planned to be replaced Y! openid by the oauth1 adapter soon

/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
*  (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/

/**
* Hybrid_Providers_Yahoo provider adapter based on OAuth1 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Yahoo.html
*/
class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OpenID
{
        var $openidIdentifier = "https://open.login.yahooapis.com/openid20/www.yahoo.com/xrds";

        /**
        * finish login step
        */
        function loginFinish()
        {
                parent::loginFinish();

                $this->user->profile->emailVerified = $this->user->profile->email;

                // restore the user profile
                Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.user", $this->user );
        }
}


text:
define([
  'user/model/base',
  'util/assign',
  'moment'
], function (UserModel, assign, moment) {
  return UserModel.extend({

    defaults: assign(UserModel.prototype.defaults, {
      status: 'online',
      extended: false,
      lastOnline: moment(),
      prioritized: false
    }),

    computeds: assign(UserModel.prototype.computeds, {

      extendedClass: {
        deps: ['extended'],
        get: function (extended) {
          return extended ? '' : 'hidden ';
        }
      },

      lastOnlineScreen: {
        deps: ['status', 'lastOnline'],
        get: function (status, lastOnline) {
          return status !== 'offline' ?
            false : moment(lastOnline, moment.ISO_8601).fromNow();
        }
      },

      /**
       * Scores the status
       */
      statusOrder : {
        deps: ['status'],
        get: function (status) {
          var order = 0;
          switch (status) {
            case 'online':
              order = order + 3;
              break;
            case 'idle':
              order = order + 2;
              break;
            case 'busy':
              order = order + 1;
              break;
          }
          return order;
        }
      },

      /**
       * Scores the buddy both with status and prioritization
       */
      defaultOrder: {
        deps: ['statusOrder', 'prioritized'],
        get: function (statusOrder, prioritized) {
          if (prioritized) {
            statusOrder = statusOrder + 4;
          }

          return statusOrder;
        }
      },

      prioritizedClass: {
        deps: ['prioritized'],
        get: function (prioritized) {
          return prioritized ? 'star' : 'star-empty';
        }
      },

      statusClass: {
        deps: ['status'],
        get: function (status) {
          switch (status) {
            case 'online':
              return 'success';
            case 'idle':
              return 'info';
            case 'busy':
              return 'danger';
            default:
              return 'default'
          }
        }
      }

    })

  });
});


text:
package cn.iutils.common.utils;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

import java.net.URL;

/**
 * 邮件工具
 * @author iutils.cn
 * @version 1.0
 */
public class JMailUtils extends BaseUtils{

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args){
        //JMailUtils.sendHtmlEmail(new JMailUtils.Email(JMailUtils.smtp163,"hc279520@163.com","123456","305627617@qq.com","hc279520@163.com","程序员工具","来自程序员工具测试信","你好<br> 程序员工具"));
    }

    /**
     * 发送带附件的邮件
     * @param email 邮件对象
     * @param isURL 是否远程
     * @return
     */
    public static boolean sendMultiPartEmail(Email email,boolean isURL){
        boolean flag = false;
        try{
            MultiPartEmail multiPartEmail = new MultiPartEmail();
            multiPartEmail.setHostName(email.getHostName());
            multiPartEmail.setAuthentication(email.getUsername(), email.getPassword());//邮件服务器验证:用户名/密码
            multiPartEmail.setCharset("UTF-8");// 必须放在前面,否则乱码
            multiPartEmail.addTo(email.getTo());
            multiPartEmail.setFrom(email.getFrom(), email.getFromName());
            multiPartEmail.setSubject(email.getSubject());
            multiPartEmail.setMsg(email.getMsg());

            EmailAttachment attachment = new EmailAttachment();
            if(isURL){
                attachment.setURL(new URL(email.getAttachmentPath()));//远程文件
            }else{
                attachment.setPath(email.getAttachmentPath());// 本地文件
            }
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription(email.getAttachmentDescription());
            attachment.setName(email.getAttachmentName());

            multiPartEmail.attach(attachment);
            multiPartEmail.send();
        }catch (Exception e){
            logger.debug("邮件发送失败",e.fillInStackTrace());
        }
        return flag;
    }

    /**
     * 发送Html格式邮件
     * @param email 邮件对象
     * @return
     */
    public static boolean sendHtmlEmail(Email email){
        boolean flag = false;
        try {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setHostName(email.getHostName());
            htmlEmail.setAuthentication(email.getUsername(), email.getPassword());//邮件服务器验证:用户名/密码
            htmlEmail.setCharset("UTF-8");// 必须放在前面,否则乱码
            htmlEmail.addTo(email.getTo());
            htmlEmail.setFrom(email.getFrom(), email.getFromName());
            htmlEmail.setSubject(email.getSubject());
            htmlEmail.setMsg(email.getMsg());
            htmlEmail.send();
            flag = true;
        }catch (Exception e) {
            logger.debug("邮件发送失败",e.fillInStackTrace());
        }
        return flag;
    }

    /**
     * 发送简单的邮件
     * @param email 邮件对象
     * @return
     */
    public static boolean sendSimpleMail(Email email){
        boolean flag = false;
        try {
            SimpleEmail simpleEmail = new SimpleEmail();
            simpleEmail.setHostName(email.getHostName());
            simpleEmail.setAuthentication(email.getUsername(), email.getPassword());//邮件服务器验证:用户名/密码
            simpleEmail.setCharset("UTF-8");// 必须放在前面,否则乱码
            simpleEmail.addTo(email.getTo());
            simpleEmail.setFrom(email.getFrom(), email.getFromName());
            simpleEmail.setSubject(email.getSubject());
            simpleEmail.setMsg(email.getMsg());
            simpleEmail.send();
            flag = true;
        } catch (Exception e) {
            logger.debug("邮件发送失败",e.fillInStackTrace());
        }
        return flag;
    }

    /**
     * QQ主机
     */
    public static final String smtpqq = "smtp.qq.com";
    /**
     * 163主机
     */
    public static final String smtp163 = "smtp.163.com";
    /**
     * 126主机
     */
    public static final String smtp126 = "smtp.126.com";
    /**
     * sina主机
     */
    public static final String smtpsina = "smtp.sina.com.cn";
    /**
     * yahoo主机
     */
    public static final String smtpyahoo = "smtp.mail.yahoo.com";

    /**
     * 邮件类
     */
    public static class Email{
        String hostName;//SMTP主机地址
        String username;//用户名
        String password;//密码
        String to;//收件人
        String from;//发件人
        String fromName;//发件人昵称
        String subject;//邮件主题
        String msg;//邮件内容

        String attachmentPath;//附件地址
        String attachmentName;//附件名称
        String attachmentDescription;//附件描述

        public Email(){}

        /**
         * @param hostName SMTP主机地址
         * @param username 用户名
         * @param password 密码
         * @param to 收件人
         * @param from 发件人
         * @param fromName 发件人昵称
         * @param subject 邮件主题
         * @param msg 邮件内容
         */
        public Email(String hostName,String username,String password,String to,String from,String fromName,String subject,String msg){
            this.hostName = hostName;
            this.username = username;
            this.password = password;
            this.to = to;
            this.from = from;
            this.fromName = fromName;
            this.subject = subject;
            this.msg = msg;
        }

        public String getHostName() {
            return hostName;
        }

        public void setHostName(String hostName) {
            this.hostName = hostName;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

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

        public String getTo() {
            return to;
        }

        public void setTo(String to) {
            this.to = to;
        }

        public String getFrom() {
            return from;
        }

        public void setFrom(String from) {
            this.from = from;
        }

        public String getFromName() {
            return fromName;
        }

        public void setFromName(String fromName) {
            this.fromName = fromName;
        }

        public String getSubject() {
            return subject;
        }

        public void setSubject(String subject) {
            this.subject = subject;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public String getAttachmentPath() {
            return attachmentPath;
        }

        public void setAttachmentPath(String attachmentPath) {
            this.attachmentPath = attachmentPath;
        }

        public String getAttachmentName() {
            return attachmentName;
        }

        public void setAttachmentName(String attachmentName) {
            this.attachmentName = attachmentName;
        }

        public String getAttachmentDescription() {
            return attachmentDescription;
        }

        public void setAttachmentDescription(String attachmentDescription) {
            this.attachmentDescription = attachmentDescription;
        }
    }

}


text:
package com.microsoft.azure.cognitiveservices.vision.contentmoderator.models;

/**
 * The FindFacesFileInputOptionalParameter model.
 */
public class FindFacesFileInputOptionalParameter {
    /**
     * Whether to retain the submitted image for future use; defaults to false
     * if omitted.
     */
    private Boolean cacheImage;

    /**
     * Gets or sets the preferred language for the response.
     */
    private String thisclientacceptLanguage;

    /**
     * Get the cacheImage value.
     *
     * @return the cacheImage value
     */
    public Boolean cacheImage() {
        return this.cacheImage;
    }

    /**
     * Set the cacheImage value.
     *
     * @param cacheImage the cacheImage value to set
     * @return the FindFacesFileInputOptionalParameter object itself.
     */
    public FindFacesFileInputOptionalParameter withCacheImage(Boolean cacheImage) {
        this.cacheImage = cacheImage;
        return this;
    }

    /**
     * Get the thisclientacceptLanguage value.
     *
     * @return the thisclientacceptLanguage value
     */
    public String thisclientacceptLanguage() {
        return this.thisclientacceptLanguage;
    }

    /**
     * Set the thisclientacceptLanguage value.
     *
     * @param thisclientacceptLanguage the thisclientacceptLanguage value to set
     * @return the FindFacesFileInputOptionalParameter object itself.
     */
    public FindFacesFileInputOptionalParameter withThisclientacceptLanguage(String thisclientacceptLanguage) {
        this.thisclientacceptLanguage = thisclientacceptLanguage;
        return this;
    }

}


text:
<?php

namespace Chromabits\Nucleus\Testing\Traits;

use Exception;

/**
 * Trait ConstructorTesterTrait.
 *
 * @property array constructorTypes
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Nucleus\Testing\Traits
 */
trait ConstructorTesterTrait
{
    /**
     * @return mixed
     */
    abstract protected function make();

    /**
     * Test the constructor of an object.
     *
     * Creates a new instance by using make and optionally checks
     * if it is an instance of a set of classes and interfaces
     */
    public function testConstructor()
    {
        $instance = $this->make();

        $this->assertInternalType('object', $instance);

        if (property_exists($this, 'constructorTypes')
            && count($this->constructorTypes) > 0
        ) {
            $this->assertInstanceOf($this->constructorTypes, $instance);
        }
    }

    /**
     * Assert that the provided object is an instance of a class.
     *
     * @param string $expected
     * @param string $actual
     * @param string $message
     *
     * @return mixed
     */
    abstract public function assertInstanceOf(
        $expected,
        $actual,
        $message = ''
    );

    /**
     * Assert the provided input of a certain internal (scalar) type.
     *
     * @param string $expected
     * @param string $actual
     * @param string $message
     *
     * @return mixed
     */
    abstract public function assertInternalType(
        $expected,
        $actual,
        $message = ''
    );
}


text:
from direct.directnotify import DirectNotifyGlobal
from direct.distributed import DistributedObject
from toontown.ai import DistributedPhaseEventMgr

class DistributedMailboxZeroMgr(DistributedPhaseEventMgr.DistributedPhaseEventMgr):
    neverDisable = 1
    notify = DirectNotifyGlobal.directNotify.newCategory('DistributedMailboxZeroMgr')

    def __init__(self, cr):
        DistributedPhaseEventMgr.DistributedPhaseEventMgr.__init__(self, cr)
        cr.mailboxZeroMgr = self

    def announceGenerate(self):
        DistributedPhaseEventMgr.DistributedPhaseEventMgr.announceGenerate(self)
        messenger.send('mailboxZeroIsRunning', [self.isRunning])

    def delete(self):
        self.notify.debug('deleting mailboxzeromgr')
        messenger.send('mailboxZeroIsRunning', [False])
        DistributedPhaseEventMgr.DistributedPhaseEventMgr.delete(self)
        if hasattr(self.cr, 'mailboxZeroMgr'):
            del self.cr.mailboxZeroMgr

    def setCurPhase(self, newPhase):
        DistributedPhaseEventMgr.DistributedPhaseEventMgr.setCurPhase(self, newPhase)
        messenger.send('mailboxZeroPhase', [newPhase])

    def setIsRunning(self, isRunning):
        DistributedPhaseEventMgr.DistributedPhaseEventMgr.setIsRunning(self, isRunning)
        messenger.send('mailboxZeroIsRunning', [isRunning])


text:
package e.emjinter.vm.operations;

import e.emjinter.CodeToEmojiConverter;
import e.emjinter.Grammar;
import e.emjinter.exception.EmjInterExceptionBase;
import e.emjinter.exception.InvalidParamException;
import e.emjinter.source.IStream;
import e.emjinter.vm.IVM;

public class ModCommand extends AbstractCommand {

  public ModCommand(IVM vm)
  {
    super(vm);

    emojiCode = Grammar.CMD_MOD;
    numSymbols = 3;
  }

  @Override
  public void checkSyntax(IStream source) throws EmjInterExceptionBase {
    if(!registers.containsKey(source.checkNext(0)))
    {
      throw new InvalidParamException(String.format("Unexpected token at pos %s. Not a valid register value.",
          CodeToEmojiConverter.convert(source.getPosition())));
    }

    if(!registers.containsKey(source.checkNext(1)))
    {
      throw new InvalidParamException(String.format("Unexpected token at pos %s. Not a valid register value.",
          CodeToEmojiConverter.convert(source.getPosition())));
    }
  }

  @Override
  public void execute(IStream source) throws EmjInterExceptionBase {
    checkSyntax(source);

    int reg = source.next();
    int modReg = source.next();

    int oldVal = registers.getValue(reg);
    int modVal = registers.getValue(modReg);

    int newVal = oldVal % modVal;

    registers.updateValue(reg, newVal);
  }

}


text:
package com.hannobraun.sd.collision.phase

import com.hannobraun.sd.collision.shape.Shape

/**
 * SimpleBroadPhase is the simplest possible implementation of a broad phase. It just compiles all possible
 * pairs of the bodies it is given and returns those.
 * If any other broad phase implementation is available, it should probably be used in place of this one.
 */

class SimpleBroadPhase extends BroadPhase {

	/**
	 * Returns all possible pairs of the given bodies.
	 */

	def apply( shapes: Iterable[Shape] ) = {
		def buildPairs( list: List[Shape], pairs: List[( Shape, Shape )]): List[( Shape, Shape )] = {
			if ( list.isEmpty )
				pairs
			else
				buildPairs( list.tail, pairs:::list.tail.map( ( list.head, _ ) ) )
		}

		buildPairs( shapes.toList, Nil )
	}
}