text:
package com.company;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

class PanelAdd extends JDialog {

    public PanelAdd(JFrame owner, ArrayList<Student> list) {
        super(owner, "Add", true);

        JLabel labelFirstName = new JLabel(Student.HEADER[0] + ":");
        JLabel labelLastName = new JLabel(Student.HEADER[1] + ":");
        JLabel labelMiddleName = new JLabel(Student.HEADER[2] + ":");
        JLabel labelId = new JLabel(Student.HEADER[3] + ":");
        JLabel labelCourse = new JLabel(Student.HEADER[4] + ":");
        JLabel labelCountry = new JLabel(Student.HEADER[5] + ":");
        JLabel labelGender = new JLabel(Student.HEADER[6] + ":");
        JLabel labelMark = new JLabel(Student.HEADER[7] + ":");
        int size = 12;
        JTextField textFieldFirstName = new JTextField(size);
        JTextField textFieldLastName = new JTextField(size);
        JTextField textFieldMiddleName = new JTextField(size);
        JTextField textFieldId = new JTextField(size);
        JComboBox courseCombo = new JComboBox(Student.COURSES);
        JComboBox countryCombo = new JComboBox(Student.COUNTRIES);
        JComboBox genderCombo = new JComboBox(Student.GENDERS);
        JComboBox markCombo = new JComboBox(Student.MARKS);

        JPanel panelTop = new JPanel(new GridLayout(4, 2));
        panelTop.add(labelFirstName);
        panelTop.add(textFieldFirstName);

        panelTop.add(labelLastName);
        panelTop.add(textFieldLastName);

        panelTop.add(labelMiddleName);
        panelTop.add(textFieldMiddleName);

        panelTop.add(labelId);
        panelTop.add(textFieldId);

        panelTop.add(labelCourse);
        panelTop.add(courseCombo);

        panelTop.add(labelCountry);
        panelTop.add(countryCombo);

        panelTop.add(labelGender);
        panelTop.add(genderCombo);

        panelTop.add(labelMark);
        panelTop.add(markCombo);

        JButton ok = new JButton("OK");
        ok.addActionListener(e -> {
            setVisible(false);

            Student student = new Student();
            student.setLast_name(textFieldFirstName.getText());
            student.setFirst_name(textFieldLastName.getText());
            student.setMiddle_name(textFieldMiddleName.getText());
            student.setId(textFieldId.getText());
            student.setCourse(courseCombo.getSelectedItem().toString());
            student.setCountry(countryCombo.getSelectedItem().toString());
            student.setGender(genderCombo.getSelectedItem().toString());
            student.setMark(Double.valueOf(markCombo.getSelectedItem().toString()));

            textFieldFirstName.setText("");
            textFieldLastName.setText("");
            textFieldMiddleName.setText("");
            textFieldId.setText("");
            courseCombo.setSelectedIndex(0);
            countryCombo.setSelectedIndex(0);
            genderCombo.setSelectedIndex(0);
            markCombo.setSelectedIndex(0);

            list.add(student);
            MyClientThread.communicate(student);
        });

        JButton cancel = new JButton("Cancel");
        cancel.addActionListener(e -> setVisible(false));

        JPanel panelBottom = new JPanel();
        panelBottom.add(ok);
        panelBottom.add(cancel);

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(panelTop, BorderLayout.CENTER);
        panel.add(panelBottom, BorderLayout.SOUTH);
        add(panel);
        setBounds(500, 300, 475, 230);
        setResizable(false);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Index</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Index

periodicjs.ext.mailer

A basic mailer extension that allows for you to configure custom mail transports, and sends mail via nodemailer.

 API Documentation

Installation

$ npm install periodicjs.ext.mailer

Usage

Sending Test Mail Routes

JavaScript

module.exports = function(periodic){
    var mailRouter = periodic.express.Router(),
            mailController = require('./controller/mailer')(periodic);
    mailRouter.post('/testmail', mailController.sendmail);
    periodic.app.use('/p-admin/mailer',mailRouter);
};

Configure

you can define your own nodemailer transports, after the extension has been installed, the transport configuration is located in content/config/extensions/periodicjs.ext.mailer/transport.json

Example Transports

tranport.json
These are nodemailer transports.

{
    "development":{
        "type":"sendmail",
        "transportoptions":{
            "debug":true,
            "args":["-t","-i"]
        }
    },
    "development-example2":{
        "type":"SMTP",
        "transportoptions":{
            "service": "SendGrid",
          "auth": {
        "user": "username",
        "pass": "password"
          }
        }
    }
}

Development

Make sure you have grunt installed

$ npm install -g grunt-cli

Then run grunt watch

$ grunt watch

For generating documentation

$ grunt doc
$ jsdoc2md lib/**/*.js > doc/api.md

Notes

Check out https://github.com/typesettin/periodicjs for the full Periodic Documentation

Index

Modules

mailerController

mailer

    Documentation generated by JSDoc 3.2.2 on Sun Oct 12 2014 16:20:05 GMT-0400 (EDT)

redpajama_set_name: RedPajamaGithub


text:
module AnsiblePlaybookHelper
  include_concern 'TextualSummary'
end


text:
package jetbrains.buildServer.nuget.common;

/**
 * Can be used in case of conflicts.
 */
public class PackageExistsException extends Exception {
  public PackageExistsException(String message) {
    super(message);
  }

  public PackageExistsException(String message, Throwable cause) {
    super(message, cause);
  }
}


text:
import {
  Component,
  OnInit,
  AfterViewChecked,
  Input,
  Output,
  EventEmitter,
  AnimationTransitionEvent,
} from '@angular/core';
import { trigger, state, style, animate, transition, keyframes } from '@angular/animations';
import { Slide } from '../../../models/slide.type';
import { carouselState } from '../../../models/carousel.state';

@Component({
  selector: 'app-carousel',
  templateUrl: './carousel.component.html',
  styleUrls: ['./carousel.component.css'],
  animations: [
    trigger('flyInOut', [
      state(carouselState.left, style({
        transform: 'translateX(-100%)',
      })),
      state(carouselState.center, style({
        transform: 'translateX(0)',
      })),
      state(carouselState.right, style({
        transform: 'translateX(100%)',
      })),
      transition('center <=> *', [
        animate('1000ms ease')
      ]),
      transition('void => *', [
        animate(1)
      ]),
    ])
  ],
})
export class CarouselComponent implements OnInit, AfterViewChecked {
  @Input() slide: Slide;
  @Output() clickable = new EventEmitter();
  constructor() { }

  ngOnInit() {
    this.slide.isActive = this.slide.isActive || false;
  }

  ngAfterViewChecked() {
    this.slide.state = this.slide.toState || this.slide.state;
  }

  transitionStart($event, slide) {
    this.clickable.emit(false);
  }

  transitionDone($event: AnimationTransitionEvent, slide: Slide) {
    if ($event.fromState === carouselState.center) {
      if ($event.toState === carouselState.left || $event.toState === carouselState.right) {
        slide.isActive = false;
        slide.state = carouselState.center;
      }
    }
    slide.toState = null;
    this.clickable.emit(true);
  }
}


text:
Osp.Core.Mixin.define("borrowNone.DB",
{
	members:
	{
		updateExportFile: function()
		{
			var dir = 'documents/borrowNone/data',
				file = null,
				fileSystemAPI = deviceapis.filesystem,
				self = this,
				title = '',
				message = '',
				style = 'ok';

			function onSuccess(dir)
			{
				file = dir.resolve('export.db');

				self.writeToFile(file);
			}

			function onError(e)
			{
				self.setLoading(false);
				console.log("updateExportFile() > Error Code: " + e.code);
				console.log("updateExportFile() > Error Message: " + e.message);

				switch(e.message)
				{
					case 'NOT_FOUND_ERR':
						message = self.getMessage('IDS_ERROR_EXPORT_FILE_NOT_FOUND');
						break;

					case 'SECURITY_ERR':
						message = self.getMessage('IDS_ERROR_EXPORT_MISSING_PERMISSION');
						break;

					default:
						message = self.getMessage('IDS_ERROR_UNKNOWN_ERROR');
						break;
				}

				title = self.getMessage('IDS_ERROR_EXPORT'),

				self.showPopup(title, message, 'ok');
			}

			fileSystemAPI.resolve(onSuccess, onError, dir, "rw");
		},

		writeToFile: function(file)
		{
			var db = localStorage.getItem('db'),
				self = this,
				exportObject = {},
				title = '',
				message = '';

			exportObject.results = JSON.parse(db).results;

			function streamCB(fileStream)
			{
				try
				{
					fileStream.write(JSON.stringify(exportObject));
					fileStream.close();

					self.setLoading(false);

					if(!self.importButton.isEnabled())
					{
						self.importButton.setEnabled(true);
					}

					title = self.getMessage('IDS_EXPORT');
					message = self.getMessage('IDS_EXPORT_COMPLETED');

					self.showPopup(title, message, 'none', 2000);
				}
				catch (e)
				{
					self.setLoading(false);
					console.log("writeToFile("+file+") > Error Code: " + e.code);
					console.log("writeToFile("+file+") > Error Message: " + e.message);
				}
			}

			function streamError(e)
			{
				self.setLoading(false);
				console.log("writeToFile("+file+") > Error Code: " + e.code);
				console.log("writeToFile("+file+") > Error Message: " + e.message);

				switch(e.message)
				{
					case 'NOT_FOUND_ERR':
						message = self.getMessage('IDS_ERROR_EXPORT_FILE_NOT_FOUND');
						break;

					case 'SECURITY_ERR':
						message = self.getMessage('IDS_ERROR_EXPORT_MISSING_PERMISSION');
						break;

					default:
						message = self.getMessage('IDS_ERROR_UNKNOWN_ERROR');
						break;
				}

				title = self.getMessage('IDS_ERROR_EXPORT'),

				self.showPopup(title, message,'ok');
			}

			file.openStream(streamCB, streamError, 'w', 'UTF-8');
		},

		createFile: function() {
			var file = null,
				fileSystemAPI = deviceapis.filesystem,
				dir = 'documents/borrowNone/data',
				self = this;

			function onSuccess(dir) {
				try {
					file = dir.createFile('export.db');

					if(file)
					{
						self.writeToFile(file);
					}
				}
				catch (e)
				{
					self.setLoading(false);
					console.log("createFile() > Error Code: " + e.code);
					console.log("createFile() > Error Message: " + e.message);
				}
			}

			function onError(e)
			{
				self.setLoading(false);
				console.log("createFile() > Error Code: " + e.code);
				console.log("createFile() > Error Message: " + e.message);

				switch(e.message)
				{
					case 'NOT_FOUND_ERR':
						message = self.getMessage('IDS_ERROR_EXPORT_FILE_NOT_FOUND');
						break;

					case 'SECURITY_ERR':
						message = self.getMessage('IDS_ERROR_EXPORT_MISSING_PERMISSION');
						break;

					default:
						message = self.getMessage('IDS_ERROR_UNKNOWN_ERROR');
						break;
				}

				title = self.getMessage('IDS_ERROR_EXPORT'),

				self.showPopup(title, message,'ok');
			}

			fileSystemAPI.resolve(onSuccess, onError, dir, "rw");
		},

		createDirectory: function() {
			var dir = null,
				fileSystemAPI = deviceapis.filesystem,
				dirname = 'documents',
				self = this,
				title = '',
				message = '';

			function onSuccess(dir)
			{
				try
				{
					newDir = dir.createDirectory("borrowNone/data");

					if(newDir)
					{
						localStorage.setItem("exportFolder", "1");
						self.createFile();
					}
				}
				catch (e)
				{
					self.setLoading(false);
					console.log("createDirectory() > Error Code: " + e.code);
					console.log("createDirectory() > Error Message: " + e.message);
				}
			}

			function onError(e)
			{
				self.setLoading(false);
				console.log("createDirectory() > Error Code: " + e.code);
				console.log("createDirectory() > Error Message: " + e.message);

				switch(e.message)
				{
					case 'NOT_FOUND_ERR':
						message = self.getMessage('IDS_ERROR_EXPORT_FILE_NOT_FOUND');
						break;

					case 'SECURITY_ERR':
						message = self.getMessage('IDS_ERROR_EXPORT_MISSING_PERMISSION');
						break;

					default:
						message = self.getMessage('IDS_ERROR_UNKNOWN_ERROR');
						break;
				}

				title = self.getMessage('IDS_ERROR_EXPORT'),

				self.showPopup(title, message,'ok');
			}

			fileSystemAPI.resolve(onSuccess, onError, dirname, "rw");
		},

		exportDB: function()
		{
			var exportFolder = localStorage.getItem("exportFolder");

			this.setLoading(true);

			if(exportFolder)
			{
				this.updateExportFile();
			}
			else
			{
				this.createDirectory();
			}
		},

		importDB: function()
		{
			this.setLoading(true);

			var self = this,
				fileSystemAPI = deviceapis.filesystem,
				location = 'documents/borrowNone/data',
				file = null,
				title = '',
				message = '',
				results = null,
				saveObject = {},
				db = localStorage.getItem('db'),
				imported = 0,
				check = null;

			function writeToDB(content)
			{
				if(content)
				{
					content = JSON.parse(content).results;

					if(!db)
					{
						saveObject.results = cnt;

						localStorage.setItem('db', JSON.stringify(saveObject));
					}
					else
					{
						try {
							results = JSON.parse(db).results;

							for(var i = 0; i < content.length; i++)
							{
								check = self.containsObject(content[i], results);

								if(!check)
								{
									results.push(content[i]);
									imported++;
								}
							}

							saveObject.results = results;

							localStorage.setItem('db', JSON.stringify(saveObject));
						}
						catch(e)
						{
							self.setLoading(false);

							title = self.getMessage('IDS_ERROR_IMPORT'),
							message = self.getMessage('IDS_ERROR_IMPORT_FILE_CORRUPTED');

							self.showPopup(title, e.message,'ok');
						}
					}

					self.loadDB();

					self.exportButton.setEnabled(true);

					localStorage.setItem("exportFolder", "1");

					title = self.getMessage('IDS_IMPORT');
					message = self.getMessage('IDS_IMPORT_COMPLETED');
					message2 = imported === 1 ? imported +" "+self.getMessage('IDS_IMPORTED_ITEMS') : imported +" "+self.getMessage('IDS_IMPORTED_ITEM');

					self.showPopup(title, message, 'none', 2000);

					setTimeout(function() {
						self.showPopup(title, message2, 'none', 2000);
					}, 2200);
				}
				else
				{
					title = self.getMessage('IDS_ERROR_IMPORT'),
					message = self.getMessage('IDS_ERROR_IMPORT_FILE_CORRUPTED');

					self.showPopup(title, message,'ok');
				}
			}

			function onSuccess(dir)
			{
				try
				{
					file = dir.resolve('export.db');

					file.readAsText(writeToDB, onError, 'UTF-8');
				}
				catch (e)
				{
					self.setLoading(false);

					self.showPopup(self.getMessage('IDS_ERROR'), e.message,'ok');
				}
			}

			function onError(e)
			{
				self.setLoading(false);

				self.showPopup(self.getMessage('IDS_ERROR'), e.message,'ok');
			}

			fileSystemAPI.resolve(onSuccess, onError, location, 'r');
		},

		/**
		 * Save a JSON to database.
		 * If no index available then it must be a new item. Else it is an existing item and must be updated
		 * @param {Object} data
		 * @param {Number} index
		 * @since 1.0.0
		 * @author Marco Büttner
		 * @public
		 */
		saveEntry: function(data, index)
		{
			var db = localStorage.getItem('db'),
				enableNotify = localStorage.getItem('enableNotify'),
				deviceInteractionAPI = deviceapis.deviceinteraction,
				saveItem = {},
				dbResults = null,
				saveArray = null;

			if(!db) // empty database
			{
				saveArray = [];
				saveArray[0] = data;
				saveItem.results = saveArray; // prepare datbase with key "results"
			}
			else
			{
				dbResults = JSON.parse(db).results; // read out database by "results" key

				if(index) // if item has an index then update item by index
				{
					dbResults[index] = data;
				}
				else // else add item on the end
				{
					dbResults.push(data);
				}

				saveItem.results = dbResults; // prepare database with key "results"
			}

			localStorage.setItem('db', JSON.stringify(saveItem)); // save buffer item "saveItem" to database (as string)

			if(enableNotify) // use enable notification on settings
			{
				function notifySuccess()
				{
					console.log("[borrowNone.db.js] saveEntry > success");
				}

				function notifyError(e)
				{
					console.log("notify error > "+e.message);
				}
				deviceInteractionAPI.startNotify(notifySuccess, notifyError, 700);
			}

			this.loadDB(); // reload db

			if(index)
			{
				db = localStorage.getItem('db'); // query db

				var data  = JSON.parse(db).results, // query results
					itemData = data[index], // query one specific item
					eventId = itemData.eventId !== -1 ? itemData.eventId : ""; // if eventId available then use it else make a emptry string
					endDate = itemData.endDate !== -1 ? new Date(itemData.endDate).toLocaleDateString() : ""; // if eventId available then use it else make a emptry string

				// set changed data
				this.detailPicLabelValue.setBackgroundImage(itemData.pic);
				this.detailTypeLabelValue.setText(itemData.type);
				this.detailPersonLabelValue.setText(itemData.person);
				this.detailStartDateLabelValue.setText(new Date(itemData.date).toLocaleDateString());
				this.detailEndDateLabelValue.setText(endDate);
				this.detailNoteLabelValue.setText(itemData.note);
				this.detailIdLabelValue.setText(index);
				this.detailEventIdLabelValue.setText(eventId);
				this.detailTitleLabelValue.setText(itemData.title);

				// modify header
				this.BackButtonHeader();
				this.headerObj.setTitleText(itemData.title);

				// modify footer
				this.EditDeleteButtons();

				// show detail page and hide all other pages
				this.hideAllPages();
				this.showPage(this.detailPanel);

				this.PAGE.CURRENT = null; // set to default
			}
			else
			{
				this.clearForm();

				// MODIFY HEADER
				this.DefaultHeader();

				// MODIFY FOOTER
				this.AddDeleteButtons();

				// change back to borrow or loan page - depens of the new type
				this.hideAllPages();

				if(data.type === 1 || data.type === 'borrow')
				{
					this.PAGE.CURRENT = 'borrowList';
					this.showPage(this.borrowList);
				}
				else
				{
					this.PAGE.CURRENT = 'loanList';

					this.showPage(this.loanList);

					this.headerObj.setItemSelected(1);
				}
			}
		},

		isDBEmpty: function()
		{
			var db = localStorage.getItem('db');

			if(db && db === "{}" || !db)
			{
				return true;
			}
			else
			{
				return false;
			}
		},

		containsObject: function(obj, list) {
			var i;
			for (i = 0; i < list.length; i++)
			{
				if (JSON.stringify(list[i]) === JSON.stringify(obj)) {
					return true;
				}
			}

			return false;
		}
	}
});


text:
class Object
  def deep_clone; Marshal::load(Marshal.dump(self)); end
end

module ClassAttributes

  def cattr(*args, &block)
    (class << self; self; end).class_eval do
      attr_accessor *args
    end
    @cattr ||= []
    @cattr.concat(args)
  end

  def iattr(*args, &block)
    (class << self; self; end).class_eval do
      attr_accessor *args
    end
    @iattr ||= []
    @iattr.concat(args)
  end

  def oattr(*args, &block)
    (class << self; self; end).class_eval do
      attr_accessor *args
    end
    @oattr ||= []
    @oattr.concat(args)
  end

  def oattr_i(*args, &block)
    (class << self; self; end).class_eval do
      attr_accessor *args
    end
    @oattr_i ||= []
    @oattr_i.concat(args)
  end

  def co_attr(*args, &block)
    cattr(*args,&block)
    oattr(*args,&block)
  end

  def co_attr_i(*args, &block)
    iattr(*args,&block)
    oattr_i(*args,&block)
  end

  alias_method :class_inherited_attribute_shared,                 :cattr
  alias_method :class_inherited_attribute_independant,            :iattr

  alias_method :object_inherited_attribute_shared,                :oattr
  alias_method :object_inherited_attribute_independant,           :oattr_i

  alias_method :class_and_object_shared_inherited_attribute,      :co_attr
  alias_method :class_and_object_independant_inherited_attribute, :co_attr_i

  def inherited(subclass)
    super(subclass) if respond_to?('super')
    iattr.each do |a|
      # puts "a=#{a}"
      subclass.send("#{a}=", send(a).deep_clone)
      subclass.send("iattr", a.to_sym)
    end
    cattr.each do |a|
      subclass.send("#{a}=", send(a))
      subclass.send("cattr", a.to_sym)
    end
    oattr.each do |a|
      subclass.send("oattr", a.to_sym)
    end
    oattr_i.each do |a|
      subclass.send("oattr_i", a.to_sym)
    end
    subclass.send(:inherit) if subclass.respond_to?('inherit')
  end

  def inherit(*args, &block)
    super if respond_to?('super')
  end
end

module ObjectPreInitialize
  private
  def pre_initialize(*args, &block)
    super if respond_to?('super')

    class_attrs = self.class.cattr + self.class.iattr

    self.class.oattr.each do |a|
      sac = self.class.send(a)
      eval "@#{a.to_s}=sac" if class_attrs.include? a
    end

    self.class.oattr_i.each do |a|
      sac = self.class.send(a)
      eval "@#{a.to_s}=sac.deep_clone" if class_attrs.include? a
    end
  end

  # def postinitialize(*args, &block)
  # end
end

module OverloadNew
  def new(*args, &block)
    newObj = self.allocate
    newObj.send :extend, ObjectPreInitialize
    newObj.send :pre_initialize, *args, &block
    newObj.send :initialize,     *args, &block
    # newObj.send :postinitialize, *args, &block
    return newObj
  end
end

def has_class_attributes
  extend ClassAttributes
end

def has_class_object_attributes
  extend ClassAttributes
  extend OverloadNew
end


text:
package org.keycloak.social.linkedin;

import com.fasterxml.jackson.databind.JsonNode;
import org.jboss.logging.Logger;
import org.keycloak.broker.oidc.AbstractOAuth2IdentityProvider;
import org.keycloak.broker.oidc.OAuth2IdentityProviderConfig;
import org.keycloak.broker.oidc.mappers.AbstractJsonUserAttributeMapper;
import org.keycloak.broker.provider.BrokeredIdentityContext;
import org.keycloak.broker.provider.IdentityBrokerException;
import org.keycloak.broker.provider.util.SimpleHttp;
import org.keycloak.broker.social.SocialIdentityProvider;
import org.keycloak.events.EventBuilder;
import org.keycloak.models.KeycloakSession;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Iterator;

/**
 * LinkedIn social provider. See https://developer.linkedin.com/docs/oauth2
 *
 * @author Vlastimil Elias (velias at redhat dot com)
 */
public class LinkedInIdentityProvider extends AbstractOAuth2IdentityProvider<OAuth2IdentityProviderConfig> implements SocialIdentityProvider<OAuth2IdentityProviderConfig> {

	private static final Logger log = Logger.getLogger(LinkedInIdentityProvider.class);

	public static final String AUTH_URL = "https://www.linkedin.com/oauth/v2/authorization";
	public static final String TOKEN_URL = "https://www.linkedin.com/oauth/v2/accessToken";
	public static final String PROFILE_URL = "https://api.linkedin.com/v2/me";
	public static final String EMAIL_URL = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
	public static final String EMAIL_SCOPE = "r_emailaddress";
	public static final String DEFAULT_SCOPE = "r_liteprofile " + EMAIL_SCOPE;

	public LinkedInIdentityProvider(KeycloakSession session, OAuth2IdentityProviderConfig config) {
		super(session, config);
		config.setAuthorizationUrl(AUTH_URL);
		config.setTokenUrl(TOKEN_URL);
		config.setUserInfoUrl(PROFILE_URL);
		// email scope is mandatory in order to resolve the username using the email address
		if (!config.getDefaultScope().contains(EMAIL_SCOPE)) {
			config.setDefaultScope(config.getDefaultScope() + " " + EMAIL_SCOPE);
		}
	}

	@Override
	protected boolean supportsExternalExchange() {
		return true;
	}

	@Override
	protected String getProfileEndpointForValidation(EventBuilder event) {
		return PROFILE_URL;
	}

	@Override
	protected BrokeredIdentityContext extractIdentityFromProfile(EventBuilder event, JsonNode profile) {
		BrokeredIdentityContext user = new BrokeredIdentityContext(getJsonProperty(profile, "id"));

		user.setFirstName(getFirstMultiLocaleString(profile, "firstName"));
		user.setLastName(getFirstMultiLocaleString(profile, "lastName"));
		user.setIdpConfig(getConfig());
		user.setIdp(this);

		AbstractJsonUserAttributeMapper.storeUserProfileForMapper(user, profile, getConfig().getAlias());

		return user;
	}

	@Override
	protected BrokeredIdentityContext doGetFederatedIdentity(String accessToken) {
		log.debug("doGetFederatedIdentity()");
		try {
			BrokeredIdentityContext identity = extractIdentityFromProfile(null, doHttpGet(PROFILE_URL, accessToken));

			identity.setEmail(fetchEmailAddress(accessToken, identity));

			if (identity.getUsername() == null) {
				identity.setUsername(identity.getEmail());
			}

			return identity;
		} catch (Exception e) {
			throw new IdentityBrokerException("Could not obtain user profile from linkedIn.", e);
		}
	}

	@Override
	protected String getDefaultScopes() {
		return DEFAULT_SCOPE;
	}

	private String fetchEmailAddress(String accessToken, BrokeredIdentityContext identity) {
		if (identity.getEmail() == null && getConfig().getDefaultScope() != null && getConfig().getDefaultScope().contains(EMAIL_SCOPE)) {
			try {
				JsonNode emailAddressNode = doHttpGet(EMAIL_URL, accessToken).findPath("emailAddress");

				if (emailAddressNode != null) {
					return emailAddressNode.asText();
				}
			} catch (IOException cause) {
				throw new RuntimeException("Failed to retrieve user email", cause);
			}
		}

		return null;
	}

	private JsonNode doHttpGet(String url, String bearerToken) throws IOException {
		JsonNode response = SimpleHttp.doGet(url, session).header("Authorization", "Bearer " + bearerToken).asJson();

		if (response.hasNonNull("serviceErrorCode")) {
			throw new IdentityBrokerException("Could not obtain response from [" + url + "]. Response from server: " + response);
		}

		return response;
	}

	private String getFirstMultiLocaleString(JsonNode node, String name) {
		JsonNode claim = node.get(name);

		if (claim != null) {
			JsonNode localized = claim.get("localized");

			if (localized != null) {
				Iterator<JsonNode> iterator = localized.iterator();

				if (iterator.hasNext()) {
					return iterator.next().asText();
				}
			}
		}

		return null;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Relisten.Api;
using Relisten.Api.Models;
using Relisten.Api.Models.Api;
using Relisten.Data;

namespace Relisten.Controllers
{
    [Produces("application/json")]
    [Route("api")]
    public class ArtistsController : RelistenBaseController
    {
        private readonly SetlistSongService setlistSongService;
        private readonly ShowService showService;
        private readonly SourceService sourceService;
        private readonly TourService tourService;
        private readonly UpstreamSourceService upstreamSourceService;
        private readonly VenueService venueService;
        private readonly YearService yearService;

        public ArtistsController(
            RedisService redis,
            DbService db,
            ArtistService artistService,
            YearService yearService,
            VenueService venueService,
            SetlistSongService setlistSongService,
            TourService tourService,
            UpstreamSourceService upstreamSourceService,
            ShowService showService,
            SourceService sourceService,
            RedisService redisService
        ) : base(redis, db, artistService)
        {
            this.yearService = yearService;
            this.venueService = venueService;
            this.setlistSongService = setlistSongService;
            this.tourService = tourService;
            this.upstreamSourceService = upstreamSourceService;
            this.showService = showService;
            this.sourceService = sourceService;
        }

        [HttpGet("v2/artists")]
        [HttpGet("v3/artists")]
        [ProducesResponseType(typeof(IEnumerable<ArtistWithCounts>), 200)]
        public async Task<IActionResult> Get()
        {
            return JsonSuccess(await _artistService.AllWithCounts<ArtistWithCounts>());
        }

        [HttpGet("v2/artists/{artistIdOrSlug}")]
        [HttpGet("v3/artists/{artistIdOrSlug}")]
        [ProducesResponseType(typeof(ArtistWithCounts), 200)]
        [ProducesResponseType(typeof(ResponseEnvelope<bool>), 404)]
        public async Task<IActionResult> Get(string artistIdOrSlug)
        {
            var art = (await _artistService.AllWithCounts<ArtistWithCounts>(new List<string> {artistIdOrSlug}))
                .FirstOrDefault();
            if (art != null)
            {
                return JsonSuccess(art);
            }

            return JsonNotFound(false);
        }

        public static string FullArtistCacheKey(Artist art)
        {
            return $"full-artist:{art.uuid.ToString()}";
        }

        [HttpGet("v3/artists/{artistUuid}/normalized")]
        [ProducesResponseType(typeof(FullArtist), 200)]
        [ProducesResponseType(typeof(ResponseEnvelope<bool>), 404)]
        public async Task<IActionResult> GetFullArtist(string artistUuid)
        {
            var art = (await _artistService.AllWithCounts<ArtistWithCounts>(new List<string> {artistUuid}))
                .FirstOrDefault();

            if (art == null)
            {
                return JsonNotFound(false);
            }

            var cacheKey = FullArtistCacheKey(art);
            var cacheResult = await redis.db.StringGetAsync(cacheKey);

            if (cacheResult.HasValue && !cacheResult.IsNullOrEmpty)
            {
                return Content(cacheResult, "application/json");
            }

            var yearsTask = yearService.AllForArtist(art);
            var venuesTask = venueService.AllForArtist(art);
            var songsTask = setlistSongService.AllForArtistWithPlayCount(art);
            var toursTask = tourService.AllForArtistWithShowCount(art);
            var showsTask = showService.ShowsForCriteria(art, "s.artist_id = @artistId", new {artistId = art.id},
                includeNestedObject: false);

            await Task.WhenAll(yearsTask, venuesTask, songsTask, toursTask, showsTask);

            var resp = new FullArtist()
            {
                artist = art,
                years = yearsTask.Result.ToList(),
                venues = venuesTask.Result.ToList(),
                songs = songsTask.Result.ToList(),
                tours = toursTask.Result.ToList(),
                shows = showsTask.Result.ToList(),
            };

            var json = JsonConvert.SerializeObject(
                resp, RelistenApiJsonOptionsWrapper.ApiV3SerializerSettings);

            await redis.db.StringSetAsync(cacheKey, json, TimeSpan.FromHours(24));

            return Content(json, "application/json");
        }

        [ApiExplorerSettings(IgnoreApi = true)]
        [HttpPost("v2/artists")]
        [Authorize]
        public async Task<IActionResult> CreateArtist([FromBody] CreateUpdateArtistDto artist)
        {
            artist.SlimArtist.id = 0;

            var art = await _artistService.Save(artist.SlimArtist);
            await upstreamSourceService.ReplaceUpstreamSourcesForArtist(art, artist.SlimUpstreamSources);

            return JsonSuccess(await _artistService.FindArtistById(art.id));
        }

        [ApiExplorerSettings(IgnoreApi = true)]
        [HttpPut("v2/artists/{artistIdOrSlug}")]
        [Authorize]
        public async Task<IActionResult> UpdateArtist([FromBody] CreateUpdateArtistDto artist)
        {
            var art = await _artistService.Save(artist.SlimArtist);
            await upstreamSourceService.ReplaceUpstreamSourcesForArtist(art, artist.SlimUpstreamSources);

            return JsonSuccess(await _artistService.FindArtistById(art.id));
        }
    }

    public class CreateUpdateArtistDto
    {
        public SlimArtistWithFeatures SlimArtist { get; set; }
        public IEnumerable<SlimArtistUpstreamSource> SlimUpstreamSources { get; set; }
    }
}


text:
module TestFtpd

  class FileSystemProvider
    attr_reader :path, :server, :ftp_name, :ftp_size, :ftp_date

    def initialize(path, server)
      @path = path
      @server = server
      @ftp_name = path.split('/').last
      @ftp_name = '/' unless @ftp_name
      @ftp_dir = File.directory?(path)
      @ftp_size = File.size?(path)
      @ftp_size = 0 unless @ftp_size
      @ftp_date = Time.now
      @ftp_date = File.mtime(path) if File.exist?(path)
    end

    def directory?
      @ftp_dir
    end

    def ftp_parent(root = nil)
      return root if root && root.path == path
      path_parts = path.split('/')
      return nil unless path_parts.pop
      return nil if path_parts.size <= 1
      FileSystemProvider.new(path_parts.join('/'), server)
    end

    def ftp_list(filter = nil)
      if filter
        if File.directory?(File.join(path, filter))
          entries = Dir.entries(File.join(path, filter)).map { |name| File.join(filter, name) }
        else
          entries = Dir.glob(File.join(path, filter)).map { |name| File.basename(name) }
        end
      else
        entries = Dir.entries(path)
      end
      entries = entries.reject { |name| %w{. ..}.include?(File.basename(name)) } unless server.config.fetch(:include_dot_folders, false)
      entries.map do |name|
        FileSystemProvider.new(File.join(path, name), server)
      end
    end

    def ftp_create(name, dir = false)
      return FileSystemProvider.new(path + '/' + name, server) unless dir
      Dir.mkdir(path + '/' + name)
      FileSystemProvider.new(path + '/' + name, server)
    rescue
      return false
    end

    def ftp_retrieve(output)
      File.open(path, 'r') { |io| output << io.read }
    end

    def ftp_store(input)
      return false unless File.open(path, 'w') do |f|
        f.write input.read
      end
      @ftp_size = File.size?(path)
      @ftp_date = File.mtime(path) if File.exist?(path)
    end

    def ftp_rename(to_name)
      to_path = File.join(File.dirname(path), to_name)
      FileUtils.mv(path, to_path)
      true
    end

    def ftp_delete(dir = false)
      if dir
        FileUtils.remove_dir(path)
      else
        FileUtils.remove_file(path)
      end
      true
    end

    def self.format_list_entry(file_system_provider)
      raw = (file_system_provider.directory?) ? 'd': '-'
      raw += 'rw-rw-rw- 1 ftp ftp '
      raw += file_system_provider.ftp_size.to_s + ' '
      raw += file_system_provider.ftp_date.strftime('%b %d %H:%M') + ' '
      raw += file_system_provider.ftp_name
      raw += "\r\n"
      raw
    end

    def self.format_nlst_entry(file_system_provider)
      raw = file_system_provider.ftp_name
      raw += "\r\n"
      raw
    end
  end

end


text:
import os
import random
import string
import time
import uuid

from loguru import logger

def get_httpbin_server():
    return "https://httpbin.org"

def setup_testcase(variables):
    logger.info(f"setup_testcase, variables: {variables}")
    variables["request_id_prefix"] = str(int(time.time()))

def teardown_testcase():
    logger.info(f"teardown_testcase.")

def setup_teststep(request, variables):
    logger.info(f"setup_teststep, request: {request}, variables: {variables}")
    request.setdefault("headers", {})
    request_id_prefix = variables["request_id_prefix"]
    request["headers"]["HRUN-Request-ID"] = request_id_prefix + "-" + str(uuid.uuid4())

def teardown_teststep(response):
    logger.info(f"teardown_teststep, response status code: {response.status_code}")

def sum_two(m, n):
    return m + n

def sum_status_code(status_code, expect_sum):
    """ sum status code digits
        e.g. 400 => 4, 201 => 3
    """
    sum_value = 0
    for digit in str(status_code):
        sum_value += int(digit)

    assert sum_value == expect_sum

def is_status_code_200(status_code):
    return status_code == 200

os.environ["TEST_ENV"] = "PRODUCTION"

def skip_test_in_production_env():
    """ skip this test in production environment
    """
    return os.environ["TEST_ENV"] == "PRODUCTION"

def get_user_agent():
    return ["iOS/10.1", "iOS/10.2"]

def gen_app_version():
    return [{"app_version": "2.8.5"}, {"app_version": "2.8.6"}]

def get_account():
    return [
        {"username": "user1", "password": "111111"},
        {"username": "user2", "password": "222222"},
    ]

def get_account_in_tuple():
    return [("user1", "111111"), ("user2", "222222")]

def gen_random_string(str_len):
    random_char_list = []
    for _ in range(str_len):
        random_char = random.choice(string.ascii_letters + string.digits)
        random_char_list.append(random_char)

    random_string = "".join(random_char_list)
    return random_string

def setup_hook_add_kwargs(request):
    request["key"] = "value"

def setup_hook_remove_kwargs(request):
    request.pop("key")

def teardown_hook_sleep_N_secs(response, n_secs):
    """ sleep n seconds after request
    """
    if response.status_code == 200:
        time.sleep(0.1)
    else:
        time.sleep(n_secs)

def hook_print(msg):
    print(msg)

def modify_request_json(request, os_platform):
    request["json"]["os_platform"] = os_platform

def setup_hook_httpntlmauth(request):
    if "httpntlmauth" in request:
        from requests_ntlm import HttpNtlmAuth

        auth_account = request.pop("httpntlmauth")
        request["auth"] = HttpNtlmAuth(
            auth_account["username"], auth_account["password"]
        )

def alter_response(response):
    response.status_code = 500
    response.headers["Content-Type"] = "html/text"
    response.body["headers"]["Host"] = "127.0.0.1:8888"
    response.new_attribute = "new_attribute_value"
    response.new_attribute_dict = {"key": 123}

def alter_response_302(response):
    response.status_code = 500
    response.headers["Content-Type"] = "html/text"
    response.text = "abcdef"
    response.new_attribute = "new_attribute_value"
    response.new_attribute_dict = {"key": 123}

def alter_response_error(response):
    # NameError
    not_defined_variable

def gen_variables():
    return {"var_a": 1, "var_b": 2}


text:
set -e

if [ ! $1 = "travis_build" ];
then
    virtualenv ENV --system-site-packages
    . ENV/bin/activate
fi

mkdir -p -m 777 /var/log/fiware-cloto
mkdir -p target/site/cobertura
mkdir -p target/surefire-reports

pip install -r requirements.txt
pip install -r requirements_dev.txt

#PYCLIPS installation
wget -O pyclips.tar.gz http://downloads.sourceforge.net/project/pyclips/pyclips/pyclips-1.0/pyclips-1.0.7.348.tar.gz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fpyclips%2Ffiles%2Fpyclips%2Fpyclips-1.0%2F&ts=1423484225&use_mirror=softlayer-ams
sleep 15
tar -xvzf pyclips.tar.gz
cd pyclips
python setup.py build
python setup.py install
cd ..

export DJANGO_SETTINGS_MODULE=fiware_cloto.cloto_settings.settings_tests
export CLOTO_SETTINGS_FILE=$(pwd)/fiware_cloto/cloto_settings/fiware-cloto.cfg
export PYTHONPATH=$(pwd)/fiware_cloto/:$PYTHONPATH
echo $PYTHONPATH
echo $DJANGO_SETTINGS_MODULE
export SETTINGS_TYPE=test
python fiware_cloto/manage.py makemigrations cloto
python fiware_cloto/manage.py migrate
python fiware_cloto/manage.py test
coverage report -m

if [ ! $1 = "travis_build" ];
then
    deactivate
    echo "Deactivate completed"
else
    echo "Travis does not have deactivate command for no reason :SS"
fi


text:
import pyglet
import glooey
import vecrec

window = pyglet.window.Window()
batch = pyglet.graphics.Batch()

full = vecrec.Rect.from_pyglet_window(window)
left = vecrec.Rect(full.left, full.bottom, full.width/2, full.height)
right = vecrec.Rect(full.left, full.bottom, full.width/2, full.height)
right.left = left.right
left.shrink(50)
right.shrink(50)

glooey.drawing.Rectangle(left, batch=batch)
glooey.drawing.Rectangle(right, batch=batch)

@window.event
def on_draw():
    window.clear()
    batch.draw()

pyglet.app.run()


text:
package ca.marvinp.projecteuler.misc;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Timer {

  private long startTime;
  private long stopTime;
  private boolean isRunning;

  public Timer() {
    this.startTime = 0;
    this.stopTime = 0;
    isRunning = false;
  }

  public void start() {
    this.startTime = System.currentTimeMillis();
    isRunning = true;
  }

  public void stop() {
    this.stopTime = System.currentTimeMillis();
    isRunning = false;
  }

  public String getElapsedTime() {
    long elapsedTime = 0;
    StringBuilder sb = new StringBuilder();
    NumberFormat formatter = new DecimalFormat("#0.000");

    if (isRunning) {
      elapsedTime = System.currentTimeMillis() - startTime;
    } else {
      elapsedTime = stopTime - startTime;
    }
    // long seconds = elapsedTime/1000;
    float seconds = (float) (elapsedTime / 1000.0);

    sb.append("Elapsed time: ");
    sb.append(elapsedTime + " ms (");
    sb.append(formatter.format(seconds) + " sec)");
    return sb.toString();
  }

}


text:
CREATE TABLE Player(
   name text NOT NULL,
   id text NOT NULL,
   PRIMARY KEY(id)
);

CREATE TABLE League(
   name text NOT NULL,
   PRIMARY KEY(name)
);

CREATE TABLE Format(
   name text NOT NULL,
   PRIMARY KEY(name)
);

CREATE TABLE Division(
   name text NOT NULL,
   PRIMARY KEY(name)
);

CREATE TABLE Team(
   name text NOT NULL,
   id int NOT NULL,
   PRIMARY KEY(id)
);

CREATE TABLE Class(
   name text NOT NULL,
   PRIMARY KEY(name)
);

CREATE TABLE PlaysOn(
   player text NOT NULL,
   team int NOT NULL,
   FOREIGN KEY(player) REFERENCES Player(id),
   FOREIGN KEY(team) REFERENCES Team(id),
   PRIMARY KEY(player, team)
);

CREATE TABLE TeamFormat(
   team int NOT NULL,
   format text NOT NULL,
   FOREIGN KEY(team) REFERENCES team(id),
   FOREIGN KEY(format) REFERENCES format(name),
   PRIMARY KEY(team, format)
);

CREATE TABLE LeagueDivision(
   league text NOT NULL,
   division text NOT NULL,
   rank int NOT NULL,
   FOREIGN KEY(league) REFERENCES League(name),
   FOREIGN KEY(division) REFERENCES Division(name),
   PRIMARY KEY(league,division)
);

CREATE TABLE LeagueFormat(
   league text NOT NULL,
   format text NOT NULL,
   FOREIGN KEY(league) REFERENCES League(name),
   FOREIGN KEY(format) REFERENCES Format(name),
   PRIMARY KEY(league, format)
);

CREATE TABLE PlaysFormat(
   player text NOT NULL,
   class text NOT NULL,
   format text NOT NULL,
   kills int,
   assists int,
   deaths int,
   kad float,
   healsPerMin float,
   damagePerMin float,
   ubers int,
   drops int,
   FOREIGN KEY(player) REFERENCES Player(id),
   FOREIGN KEY(class) REFERENCES Class(name),
   FOREIGN KEY(format) REFERENCES Format(name),
   PRIMARY KEY(playerID, class, format)
);

CREATE TABLE TeamDivision(
   team int NOT NULL,
   division text NOT NULL,
   league text NOT NULL,
   FOREIGN KEY(team) REFERENCES Team(id),
   FOREIGN KEY(league,division) REFERENCES LeagueDivision(league,division),
   PRIMARY KEY(team,division,league)
);


text:
'''
Created on Jun 23, 2013

@author: Cam Moore
'''
from apps.widgets.smartgrid_design.models import DesignerLevel, DesignerColumnGrid, DesignerGrid
from apps.managers.predicate_mgr import predicate_mgr
from apps.widgets.notifications.models import UserNotification
from apps.widgets.smartgrid_play_tester.models import TesterActionSubmittion
from apps.managers.smartgrid_mgr import smartgrid_mgr

def annotate_action_details(user, action):
    """Retrieve the action details for the given user evaluated in the testing environment"""
    if action.type == "commitment":
        submittions = TesterActionSubmittion.objects.filter(user=user, action=action).\
            order_by("-submission_date")
        # calculate the task duration
        action.duration = action.commitment_length
    else:
        submittions = TesterActionSubmittion.objects.filter(user=user, action=action)
        # calculate the task duration
        if action.type == "activity":
            duration = action.expected_duration
        else:  # is event
            if action.type in ("event", "excursion"):
                duration = action.expected_duration
            else:
                duration = 0

        hours = duration / 60
        minutes = duration % 60
        action.duration = ""
        if hours > 1:
            action.duration = "%d hours" % hours
        elif hours > 0:
            action.duration = "%d hour" % hours
        if minutes > 0:
            action.duration += " %d minutes" % minutes

    if submittions:
        action.member = submittions[0]
        action.is_unlock = True
        action.completed = True
    else:
        action.member = None
        action.is_unlock = is_unlock(user, action)
        for loc in DesignerGrid.objects.filter(action=action):
            action.is_unlock = action.is_unlock and is_level_unlock(user, loc.level, action.draft)
        action.completed = False
    action.availablity = availablity(action)
    return action

def can_add_commitment(user):
    """Returns true for all users."""
    _ = user
    return True

def is_level_unlock(user, level, draft):
    """return True if the level is unlock."""
    return level and predicate_mgr.eval_play_tester_predicates(level.unlock_condition, user, draft)

def get_submitted_actions(user, draft_slug):
    """returns the completed action for the user. It is stored as a dict of action slugs and
    its member status."""
#     actions = cache_mgr.get_cache('smartgrid-completed-%s' % user.username)
    draft = smartgrid_mgr.get_designer_draft(draft_slug)
    actions = {}
    for member in TesterActionSubmittion.objects.filter(draft=draft, user=user).\
        select_related("action").order_by("-submission_date"):
        slug = member.action.slug
        if  member.action.type != "commitment":
            actions[slug] = {"approval_status": member.approval_status,
                             }
        elif slug not in actions:
            actions[slug] = {"days_left": member.days_left(),
                             "award_date": member.award_date,
                             }
#         cache_mgr.set_cache('smartgrid-completed-%s' % user, actions, 1800)
    return actions

def is_unlock(user, action):
    """Returns the unlock status of the user action."""
    return eval_unlock(user, action)

def eval_unlock(user, action):
    """Determine the unlock status of a task by dependency expression"""
    predicates = action.unlock_condition
    if not predicates:
        return False
    draft = smartgrid_mgr.get_designer_draft(action.draft)
    return predicate_mgr.eval_play_tester_predicates(predicates, user, draft)

def availablity(action):
    """Returns -1 if the current date is before pub_date, 0 if action is available,
    and 1 if action is expired."""
    _ = action
    return 0

def get_designer_grid(draft, user):  # pylint: disable=R0914,R0912
    """Returns the play tester version of the Smart Grid Game for the given draft."""
    levels = []
    for level in DesignerLevel.objects.filter(draft=draft):
        level.is_unlock = predicate_mgr.eval_play_tester_predicates(level.unlock_condition,
                                                                    user=user,
                                                                    draft_slug=draft.slug)
        if level.is_unlock:  # only include unlocked levels
            if level.unlock_condition != "True":
                contents = "%s is unlocked." % level
                obj, created = UserNotification.objects.\
                    get_or_create(recipient=user,
                                  contents=contents,
                                  level=UserNotification.LEVEL_CHOICES[2][0])
                if created:  # only show the notification if it is new
                    obj.display_alert = True
                    obj.save()
            level_ret = []
            level.is_complete = True
            level_ret.append(level)
            level_ret.append(DesignerColumnGrid.objects.filter(draft=draft, level=level))
#                level_ret.append(Grid.objects.filter(level=level))

            max_column = len(DesignerColumnGrid.objects.filter(draft=draft, level=level))
            max_row = 0
            just_actions = []
            # update each action
            for row in DesignerGrid.objects.filter(draft=draft, level=level):
                action = smartgrid_mgr.get_designer_action(draft=draft, slug=row.action.slug)
                action.row = row.row
                if row.row > max_row:
                    max_row = row.row
                action.column = row.column
                if row.column > max_column:
                    max_column = row.column
                action = annotate_action_details(user, action)
                # if there is one action is not completed, set the level to in-completed
                if not action.completed:
                    level.is_complete = False
                just_actions.append(action)
            level_ret.append(just_actions)
            columns = []
            for cat in level_ret[1]:
                if cat.column not in columns:
                    columns.append(cat.column)
            for act in level_ret[2]:
                if act.column not in columns:
                    columns.append(act.column)
            level_ret.append(columns)
            level_ret.append(max_column)
            level_ret.append(max_row)
            levels.append(level_ret)
        else:
            level_ret = []
            level_ret.append(level)
            level_ret.append([])
            level_ret.append([])
            level_ret.append([])
            level_ret.append(0)
            level_ret.append(0)
            levels.append(level_ret)
    return levels
# pylint: enable=R0914,R0912

def can_complete_commitment(user, commitment):
    """Returns true."""
    _ = user
    _ = commitment
    return False


text:
"""
==================================
Reading epochs from a raw FIF file
==================================

This script shows how to read the epochs from a raw file given
a list of events. For illustration, we compute the evoked responses
for both MEG and EEG data by averaging all the epochs.

"""
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Matti Hamalainen <msh@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)

import mne
from mne import io
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

###############################################################################
# Set parameters
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id, tmin, tmax = 1, -0.2, 0.5

# Setup for reading the raw data
raw = io.Raw(raw_fname)
events = mne.read_events(event_fname)

# Set up pick list: EEG + MEG - bad channels (modify to your needs)
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                       exclude='bads')

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=picks, baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
evoked = epochs.average()  # average epochs to get the evoked response

###############################################################################
# Show result
evoked.plot()


text:
import re
from fabkit import filer, sudo, env
from fablib.base import SimpleBase
from oslo_config import cfg
from fablib.python import Python

CONF = cfg.CONF

class FabServer(SimpleBase):
    def __init__(self):
        self.data_key = 'fabkit_tools'

        self.data = {
            'port': 8080,
            'user': 'nobody',
            'group': 'nobody',
            'prefix': '/opt/fabkit',
            'task_patterns': 'local.*,check.*',
            'processes': 5,
            'threads': 1,
        }

        self.packages = {
            'CentOS Linux 7.*': [
                'epel-release',
                'httpd',
                'mod_wsgi',
                'nodejs',
                'npm',
            ],
            'Ubuntu 14.*': [
                'apache2',
                'libapache2-mod-wsgi',
                'nodejs',
                'npm',
            ]
        }

        self.services = {
            'CentOS Linux 7.*': [
                'httpd',
                'fabnode',
            ],
            'Ubuntu 14.*': [
                'apache2',
            ]
        }

    def init_before(self):
        self.python = Python(self.data['prefix'])

    def init_after(self):
        self.data['owner'] = '{0}:{1}'.format(self.data['user'], self.data['group'])
        self.data['host'] = env.host

    def setup(self):
        data = self.init()
        self.install_packages()

        var_dir = CONF.client.package_var_dir
        common_repo = '{0}/fabkit-repo-common'.format(var_dir)
        server_repo = '{0}/fabkit-repo-server'.format(var_dir)
        filer.template('{0}/fabfile.ini'.format(server_repo), data=data)

        sudo('rm -rf {0}/fabfile && '
             'cp -r {1}/fabfile {0}/fabfile && '
             'chown -R {2}:{3} {0}/fabfile'.format(
                 server_repo, common_repo, data['user'], data['group']))

        if re.match('CentOS .*', env.node['os']):
            log_prefix = '/var/log/httpd/{0}'.format(env.user)
            data.update({
                'repo': server_repo,
                'python_path': self.python.get_site_packages(),
                'error_log': 'fabkit-error.log'.format(log_prefix),
                'custom_log': 'fabkit-access.log'.format(log_prefix),
            })

            if filer.template(src='httpd.conf',
                              dest='/etc/httpd/conf.d/fabkit_httpd.conf'.format(env.user),
                              data=data):
                self.handlers['restart_httpd'] = True

        self.exec_handlers()

        if env.host == env.hosts[0]:
            sudo("cd {0}/fabfile/core/webapp && "
                 "{1}/bin/python manage.py migrate --noinput".format(
                     server_repo, CONF.client.package_prefix))

            sudo("cd {0}/fabfile/core/webapp && "
                 "echo \"from django.contrib.auth.models import User;"
                 "User.objects.create_superuser('admin', 'admin@example.com', 'admin')\""
                 " | {1}/bin/python manage.py shell".format(
                     server_repo, CONF.client.package_prefix))

        self.start_services().enable_services()

        self.restart_services()

        sudo('/opt/fabkit/bin/fabserver -l')


text:
#include <unity/lib/toolkit_class_base.hpp>

namespace graphlab {
toolkit_class_base::~toolkit_class_base() { }

std::vector<std::string> toolkit_class_base::list_keys() {
  return {"list_functions",
    "call_function",
    "list_get_properties",
    "list_set_properties",
    "set_property",
    "get_property",
    "get_docstring",
    "__name__",
    "__uid__"};
}

variant_type toolkit_class_base::get_value(std::string key, variant_map_type& arg) {
  perform_registration();
  if (key == "list_functions") {
    return to_variant(list_functions());
  } else if (key == "list_get_properties") {
    return to_variant(list_get_properties());
  } else if (key == "list_set_properties") {
    return to_variant(list_set_properties());
  } else if (key == "call_function") {
    // dispatches to a user defined function
    if (!arg.count("__function_name__")) {
      throw("Invalid function call format");
    }
    std::string function_name = variant_get_value<std::string>(arg["__function_name__"]);
    return to_variant(call_function(function_name, arg));
  } else if (key == "set_property") {
    // dispatches to a user defined set property
    if (!arg.count("__property_name__")) {
      throw("Invalid function call format");
    }
    std::string property_name = variant_get_value<std::string>(arg["__property_name__"]);
    return to_variant(set_property(property_name, arg));
  } else if (key == "get_property") {
    // dispatches to a user defined get property
    if (!arg.count("__property_name__")) {
      throw("Invalid function call format");
    }
    std::string property_name = variant_get_value<std::string>(arg["__property_name__"]);
    return to_variant(get_property(property_name, arg));
  } else if (key == "get_docstring") {
    // dispatches to a user defined get property
    if (!arg.count("__symbol__")) {
      throw("Invalid function call format");
    }
    std::string symbol = variant_get_value<std::string>(arg["__symbol__"]);
    return to_variant(get_docstring(symbol));
  } else if (key == "__name__") {
    return name();
  } else if (key == "__uid__") {
    return uid();
  } else {
    return variant_type();
  }
}

void toolkit_class_base::save_impl(oarchive& oarc) const { }

void toolkit_class_base::load_version(iarchive& iarc, size_t version) { }

size_t toolkit_class_base::get_version() const {
  return 0;
}

std::map<std::string, std::vector<std::string>> toolkit_class_base::list_functions() {
  perform_registration();
  return m_function_args;
}

std::vector<std::string> toolkit_class_base::list_get_properties() {
  perform_registration();
  std::vector<std::string> ret;
  for(const auto& i: m_get_property_list) ret.push_back(i.first);
  return ret;
  return std::vector<std::string>();
}

std::vector<std::string> toolkit_class_base::list_set_properties() {
  perform_registration();
  std::vector<std::string> ret;
  for(const auto& i: m_set_property_list) ret.push_back(i.first);
  return ret;
}

variant_type toolkit_class_base::call_function(std::string function,
                                               variant_map_type argument) {
  perform_registration();
  if (m_function_list.count(function)) {
    return m_function_list[function](this, argument);
  } else {
    throw(std::string("No such property"));
  }
}

variant_type toolkit_class_base::get_property(std::string property,
                                                      variant_map_type argument) {
  perform_registration();
  if (m_get_property_list.count(property)) {
    return m_get_property_list[property](this, argument);
  } else {
    throw(std::string("No such property"));
  }
}

/**
 * Sets a property.
 */
variant_type toolkit_class_base::set_property(std::string property,
                                                      variant_map_type argument) {
  perform_registration();
  if (m_set_property_list.count(property)) {
    return m_set_property_list[property](this, argument);
  } else {
    throw(std::string("No such property"));
  }
}

std::string toolkit_class_base::get_docstring(std::string symbol) {
  if (m_docstring.count(symbol)) {
    return m_docstring.at(symbol);
  } else {
    return "";
  }
}

void toolkit_class_base::register_function(std::string fnname,
                                           std::vector<std::string> arguments,
                                           std::function<variant_type(toolkit_class_base*, variant_map_type)> fn) {

  auto last_colon = fnname.find_last_of(":");
  if (last_colon != std::string::npos) fnname = fnname.substr(last_colon + 1);

  m_function_args[fnname] = arguments;
  m_function_list[fnname] = fn;
}

/**
 * Adds a property setter with the specified name.
 */
void toolkit_class_base::register_setter(std::string propname,
                                         std::function<variant_type(toolkit_class_base*, variant_map_type)> setfn) {
  m_set_property_list[propname] = setfn;
}

/**
 * Adds a property getter with the specified name.
 */
void toolkit_class_base::register_getter(std::string propname,
                                         std::function<variant_type(toolkit_class_base*, variant_map_type)> getfn) {
  m_get_property_list[propname] = getfn;
}

void toolkit_class_base::register_docstring(std::pair<std::string, std::string> fnname_docstring) {
  std::string fnname;
  std::string docstring;
  std::tie(fnname, docstring) = fnname_docstring;
  auto last_colon = fnname.find_last_of(":");
  if (last_colon != std::string::npos) fnname = fnname.substr(last_colon + 1);
  m_docstring[fnname] = docstring;
}

} // namespace graphlab


text:
using EasyDb.Data;
using EasyDb.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyDb.Data
{
    public class DatabaseInteractor
    {
        private string _connectionString;

        public DatabaseInteractor()
        {
            if (File.Exists(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile))
            {
                _connectionString = ConfigurationManager.ConnectionStrings["EasyDb"].ConnectionString;
            }
        }

        /// <summary>
        /// Used when changing server to populate databases
        /// </summary>
        /// <param name="serverName"></param>
        /// <param name="ignoreDatabase">Used to distinguish signature from other constructor</param>
        public DatabaseInteractor(string serverName, bool ignoreDatabase)
        {
            _connectionString = string.Format(@"Server={0};Trusted_Connection=True;", serverName);
        }

        public DatabaseInteractor(string dbName)
        {
            _connectionString = string.Format(@"Server={0};Trusted_Connection=True;database={1}", Properties.Settings.Default.DefaultServer, dbName);
        }

        private void ExecuteCommand(SqlCommand command)
        {
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                command.Connection = conn;
                conn.Open();
                command.ExecuteNonQuery();
            }
        }

        public ObservableCollection<string> GetDatabases()
        {
            ObservableCollection<string> databases = new ObservableCollection<string>();
            using (SqlConnection conn = new SqlConnection(this._connectionString))
            {
                conn.Open();
                SqlCommand command = new SqlCommand("SELECT name FROM sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')", conn);

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        databases.Add(reader["Name"].ToString());
                    }
                }
            }
            return databases;
        }

        /// <summary>
        /// Gets all tables for the specified database
        /// </summary>
        /// <returns></returns>
        public DataTable GetTables()
        {
            DataTable tables = new DataTable();
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                tables = conn.GetSchema("Tables");
            }
            return tables;
        }

        /// <summary>
        /// Gets all columns for a table
        /// </summary>
        /// <returns></returns>
        public DataTable GetColumns(string tablename)
        {
            DataTable columns = new DataTable();
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                string[] restrictions = new string[4] { null, null, tablename, null };
                conn.Open();
                columns = conn.GetSchema("Columns", restrictions);
            }
            return columns;
        }

        /// <summary>
        /// Gets all the data in a table
        /// </summary>
        /// <returns></returns>
        public DataTable GetTableData(string tablename, string columnClause)
        {

            DataTable data = new DataTable();
            string query = string.Format("SELECT {0} from {1}", columnClause, tablename);

            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                SqlCommand command = new SqlCommand(query, conn);
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(command);
                da.Fill(data);
            }
            return data;
        }

        /// <summary>
        /// Gets all templates
        /// </summary>
        /// <returns></returns>
        public List<Template> GetTemplates()
        {
            List<Template> templates = new List<Template>();
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                SqlCommand command = new SqlCommand("GetTemplates", conn) { CommandType = CommandType.StoredProcedure };

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Template template = new Template();
                        template.Id = (int)reader["Id"];
                        template.Name = (string)reader["Name"];
                        template.IsStandard = (bool)reader["IsStandardTemplate"];
                        TemplateType type = (TemplateType)reader["LanguageId"];
                        template.Type = (LanguageType)reader["LanguageId"];
                        if (template.Type == LanguageType.SQL)
                        {
                            SqlTemplate sqlTemplate = new SqlTemplate();
                            if (reader["SqlTemplateId"] != DBNull.Value)
                            {
                                sqlTemplate.Id = (int)reader["SqlTemplateId"];
                                sqlTemplate.AddAnsiNull = (bool)reader["AddAnsiNulls"];
                                sqlTemplate.AddQuotedIdentifier = (bool)reader["AddQuotedIdentifier"];
                                sqlTemplate.IncludeBeginEnd = (bool)reader["IncludeBeginEnd"];
                                sqlTemplate.IncludeIfExistsDrop = (bool)reader["IncludeIfExistsDrop"];
                                sqlTemplate.IncludeDrop = (bool)reader["IncludeDrop"];
                                sqlTemplate.PrefixNameWith = (reader["PrefixNameWith"] == DBNull.Value) ? "" : reader["PrefixNameWith"].ToString();
                                sqlTemplate.PrefixNameForBulkSaveWith = (reader["PrefixNameWith"] == DBNull.Value) ? "" : reader["PrefixNameForBulkSaveWith"].ToString();
                                sqlTemplate.ObjectType = (SqlObjectType)(reader["ObjectTypeId"]);
                                sqlTemplate.StatementType = (reader["StatementTypeId"] == DBNull.Value) ? 0 : (SqlStatementType)reader["StatementTypeId"];
                                sqlTemplate.UseParametersToGenerateData = (reader["UseParametersToGenerateData"] == DBNull.Value) ? false : (bool)reader["UseParametersToGenerateData"];
                                template.RulesTemplate = sqlTemplate;
                            }
                        }
                        else if (template.Type == LanguageType.CSharp)
                        {
                            CSharpTemplate cSharpTemplate = new CSharpTemplate();
                            cSharpTemplate.Id = reader.GetInt("CSharpTemplateId");
                            cSharpTemplate.ClassNameSuffix = reader.GetString("ClassNameSuffix");
                            cSharpTemplate.Namespace = reader.GetString("Namespace");
                            cSharpTemplate.IncludeUsings = reader.GetBool("IncludeUsings");
                            cSharpTemplate.IncludeProperties = reader.GetBool("IncludeProperties");
                            cSharpTemplate.IncludeEmptyConstructor = reader.GetBool("IncludeEmptyConstructor");
                            cSharpTemplate.IncludeOtherConstructor = reader.GetBool("IncludeOtherConstructor");
                            template.RulesTemplate = cSharpTemplate;
                        }
                        templates.Add(template);
                    }
                }
            }
            return templates;
        }

        /// <summary>
        /// Updates a template
        /// </summary>
        /// <returns></returns>
        public void UpdateTemplate(Template template)
        {
            SqlCommand command = new SqlCommand("EditTemplates") { CommandType = CommandType.StoredProcedure };
            command.Parameters.AddWithValue("@Id", template.Id);
            command.Parameters.AddWithValue("@IsStandardTemplate", template.IsStandard);
            command.Parameters.AddWithValue("@Name", template.Name);
            command.Parameters.AddWithValue("@LanguageId", (int)template.Type);
            ExecuteCommand(command);
        }

        /// <summary>
        /// Updates a SqlTemplate
        /// </summary>
        /// <returns></returns>
        public void UpdateSqlTemplate(SqlTemplate sqlTemplate)
        {
            SqlCommand command = new SqlCommand("EditSqlTemplate") { CommandType = CommandType.StoredProcedure };
            command.Parameters.AddWithValue("@Id", sqlTemplate.Id);
            command.Parameters.AddWithValue("@AddAnsiNulls", sqlTemplate.AddAnsiNull);
            command.Parameters.AddWithValue("@AddQuotedIdentifier", sqlTemplate.AddQuotedIdentifier);
            command.Parameters.AddWithValue("@IncludeBeginEnd", sqlTemplate.IncludeBeginEnd);
            command.Parameters.AddWithValue("@IncludeDrop", sqlTemplate.IncludeDrop);
            command.Parameters.AddWithValue("@IncludeIfExistsDrop", sqlTemplate.IncludeIfExistsDrop);
            command.Parameters.AddWithValue("@ObjectTypeId", (int)sqlTemplate.ObjectType);
            command.Parameters.AddWithValue("@PrefixNameForBulkSaveWith", sqlTemplate.PrefixNameForBulkSaveWith);
            command.Parameters.AddWithValue("@PrefixNameWith", sqlTemplate.PrefixNameWith);
            command.Parameters.AddWithValue("@StatementTypeId", (int)sqlTemplate.StatementType);
            command.Parameters.AddWithValue("@UseParametersToGenerateData", sqlTemplate.UseParametersToGenerateData);
            ExecuteCommand(command);
        }

        /// <summary>
        /// Updates a CSharpTemplate
        /// </summary>
        /// <returns></returns>
        public void UpdateCSharpTemplate(CSharpTemplate cSharpTemplate)
        {
            SqlCommand command = new SqlCommand("EditCSharpTemplate") { CommandType = CommandType.StoredProcedure };
            command.Parameters.AddWithValue("@Id", cSharpTemplate.Id);
            command.Parameters.AddWithValue("@ClassNameSuffix", cSharpTemplate.ClassNameSuffix);
            command.Parameters.AddWithValue("@Namespace", cSharpTemplate.Namespace);
            command.Parameters.AddWithValue("@IncludeUsings", cSharpTemplate.IncludeUsings);
            command.Parameters.AddWithValue("@IncludeProperties", cSharpTemplate.IncludeProperties);
            command.Parameters.AddWithValue("@IncludeEmptyConstructor", cSharpTemplate.IncludeEmptyConstructor);
            command.Parameters.AddWithValue("@IncludeOtherConstructor", cSharpTemplate.IncludeOtherConstructor);
            ExecuteCommand(command);
        }

        /// <summary>
        /// Gets all languages
        /// </summary>
        /// <returns></returns>
        public List<string> GetLanguages()
        {
            List<string> languages = new List<string>();
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                SqlCommand command = new SqlCommand("GetLanguages", conn) { CommandType = CommandType.StoredProcedure };

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        languages.Add(reader["Name"].ToString());
                    }
                }
            }
            return languages;
        }

        /// <summary>
        /// Gets all templates
        /// </summary>
        /// <returns></returns>
        public ObservableCollection<SqlColumnDescription> GetSqlColumnDescriptions()
        {
            ObservableCollection<SqlColumnDescription> columnDescriptions = new ObservableCollection<SqlColumnDescription>();
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                SqlCommand command = new SqlCommand("SELECT * FROM ColumnDescriptions", conn);

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        SqlColumnDescription columnDescription = new SqlColumnDescription(
                            (int)reader["Value"], (string)reader["Description"], (string)reader["DataType"]);
                        columnDescriptions.Add(columnDescription);
                    }
                }
            }
            return columnDescriptions;
        }

        /// <summary>
        /// Gets all the identiy columns for a given table
        /// </summary>
        /// <returns></returns>
        public List<string> GetIdentityColumns(string tableName)
        {
            List<string> identityColumns = new List<string>();
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                string queryString = string.Format("SELECT name FROM sys.columns WHERE object_id = object_id('{0}') AND is_identity = 1", tableName);

                SqlCommand command = new SqlCommand(queryString, conn);

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        identityColumns.Add(reader["name"].ToString());
                    }
                }
            }
            return identityColumns;
        }
    }
}


text:
import { expect, assert } from 'chai';
let sinon = require('sinon');
require('sinon-as-promised');

import * as redis from 'redis';
import { Config } from '../../../../config/config';

import { Redis } from '../../../../config/libs/redis';

describe('Redis class', () => {
  let redisClient: any;
  let config: any;
  let createStub: any;
  let eventType: string;
  let fakeError = new Error('fake error msg');

  let stubs: any[] = [];

  beforeEach(() => {
    eventType = 'ready';
    config = {
      redis: {
        auth: {
          enabled: false,
          pass: 'changeme'
        }
      }
    };
    redisClient = {
      auth: sinon.spy(),
      on: (event: string, cb: Function) => {
        if (event === eventType) {
          cb(fakeError);
        } else if (event === eventType) {
          cb();
        }
      },
      quit: sinon.spy()
    };
    createStub = sinon.stub(redis, 'createClient').returns(redisClient);
    stubs.push(createStub);
    stubs.push(sinon.stub(Config, 'config').returns(config));
  });

  afterEach(() => {
    stubs.forEach((stub) => {
      stub.restore();
    });
    stubs = [];

    Redis.disconnect();
  });

  describe('Singleton staffs', () => {
    it('.getInstance(), should return an Redis instance.', () => {
      expect(Redis.getInstance()).instanceOf(Redis);
    });

    it('new Config instance should get an error', () => {
      expect(() => { new Redis(); }).throws('Error: Instantiation failed: Use Redis.getInstance() instead of new.');
    });
  });

  describe('.connect', () => {
    it('should call auth if auth is enabled', () => {
      config.redis.auth.enabled = true;
      Redis.connect();
      assert(redisClient.auth.called);
    });

    it('should not connect multiple times', () => {
      Redis.connect();
      Redis.connect();
      assert(createStub.calledOnce);
    });

    it('should resolve redis client', () => {
      Redis.connect()
      .then((client) => {
        expect(client).to.equals(redisClient);
      });
    });

    it('should reject with error', () => {
      eventType = 'error';
      Redis.connect()
      .catch((err) => {
        expect(err).to.equals(fakeError);
      });
    });
  });

  describe('.disconnect', () => {
    it('should call redis client quit', () => {
      Redis.connect();
      Redis.disconnect();
      assert(redisClient.quit.called);
    });

    it('should not call redis client quit if not connected', () => {
      Redis.disconnect();
      assert(!redisClient.quit.called);
    });
  });

  describe('.getClient', () => {
    it('should return redis client', () => {
      Redis.connect();
      expect(Redis.getClient()).to.equal(redisClient);
    });

    it('should get undefined if Redis is not connected', () => {
      expect(Redis.getClient()).to.equal(undefined);
    });

    it('should get {} if Redis is disconnected', () => {
      Redis.connect();
      Redis.disconnect();
      expect(Redis.getClient()).to.equal(undefined);
    });
  });
});


text:
<?php

use Phalcon\Mvc\Micro;
use Phalcon\Logger\Adapter\File as Logger;

error_reporting(E_ALL);

define('APP_PATH', realpath('..'));

try {

    /**
     * Read the configuration
     */
    $config = include APP_PATH . "/app/config/config.php";

    /**
     * Read auto-loader
     */
    include APP_PATH . "/app/config/loader.php";

    /**
     * Read services
     */
    include APP_PATH . "/app/config/services.php";

    /**
     * Handle the request
     */

    $app = new Micro();

    $app->setDI($di);

    include APP_PATH . "/app/micro/main.php";

    $app->handle();

} catch (\Exception $e) {
    $logger = new Logger(APP_PATH . '/app/logs/error.log');
    $logger->error($e->getMessage());
    $logger->error($e->getTraceAsString());
    $response = new \Response();
    $response->redirect('/505.html');
    $response->send();
}


text:
package com.thoughtworks.go.server.service;

import com.thoughtworks.go.config.AdminRole;
import com.thoughtworks.go.config.AdminUser;
import com.thoughtworks.go.config.Approval;
import com.thoughtworks.go.config.AuthConfig;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.GoConfigDao;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.RoleConfig;
import com.thoughtworks.go.config.RoleUser;
import com.thoughtworks.go.config.StageConfig;
import com.thoughtworks.go.helper.StageConfigMother;
import com.thoughtworks.go.util.GoConfigFileHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static com.thoughtworks.go.config.PipelineConfigs.DEFAULT_GROUP;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:WEB-INF/applicationContext-global.xml",
        "classpath:WEB-INF/applicationContext-dataLocalAccess.xml",
        "classpath:WEB-INF/applicationContext-acegi-security.xml",
        "classpath:testPropertyConfigurer.xml"
})
public class StageApprovalAuthorizationTest {
    private static final GoConfigFileHelper CONFIG_HELPER = new GoConfigFileHelper();
    private static final String PIPELINE_NAME = "cruise";

    private AuthConfig authConfigWithUserJez = new AuthConfig(new AdminUser(new CaseInsensitiveString("jez")));
    private AuthConfig authConfigWithAdminRole = new AuthConfig(new AdminRole(new CaseInsensitiveString("adminRole")));

    @Autowired private GoConfigDao goConfigDao;
    @Autowired private SecurityService securityService;
    private static final String STAGE_NAME = "dev";

    @Before
    public void setUp() throws Exception {
        CONFIG_HELPER.usingCruiseConfigDao(goConfigDao);
        CONFIG_HELPER.onSetUp();
        CONFIG_HELPER.addPipeline(PIPELINE_NAME, STAGE_NAME);
    }

    @After
    public void tearDown() throws Exception {
        CONFIG_HELPER.onTearDown();
    }

    @Test
    public void shouldAuthorizeIfUserIsInApprovalList() throws Exception {
        CONFIG_HELPER.addSecurityWithAdminConfig();
        StageConfig stage = StageConfigMother.custom("ft", authConfigWithUserJez);
        PipelineConfig pipeline = CONFIG_HELPER.addStageToPipeline(PIPELINE_NAME, stage);

        assertThat("User jez should have permission on ft stage",
                securityService.hasOperatePermissionForStage(CaseInsensitiveString.str(pipeline.name()), CaseInsensitiveString.str(stage.name()), "jez"), is(true));
    }

    @Test
    public void shouldAuthorizeIfRoleIsInApprovalList() throws Exception {
        CONFIG_HELPER.addSecurityWithAdminConfig();
        CONFIG_HELPER.addRole(new RoleConfig(new CaseInsensitiveString("adminRole"), new RoleUser(new CaseInsensitiveString("tester"))));

        StageConfig stage = StageConfigMother.custom("test", authConfigWithAdminRole);
        PipelineConfig pipeline = CONFIG_HELPER.addStageToPipeline(PIPELINE_NAME, stage);

        assertThat("User tester should have permission on test stage",
                securityService.hasOperatePermissionForStage(CaseInsensitiveString.str(pipeline.name()), CaseInsensitiveString.str(stage.name()), "tester"), is(true));

    }

    @Test
    public void shouldUsePipelineGroupAuthorizationIfNoStageAuthorizationDefined() throws Exception {
        CONFIG_HELPER.addSecurityWithAdminConfig();
        CONFIG_HELPER.setOperatePermissionForGroup(DEFAULT_GROUP, "user1");

        assertThat(securityService.hasOperatePermissionForStage(PIPELINE_NAME, STAGE_NAME, "user1"), is(true));
        assertThat(securityService.hasOperatePermissionForStage(PIPELINE_NAME, STAGE_NAME, "anyone"), is(false));
    }

    @Test
    public void stageAuthorizationShouldOverrideGroupAuthorization() throws Exception {
        CONFIG_HELPER.addSecurityWithAdminConfig();
        CONFIG_HELPER.setOperatePermissionForGroup(DEFAULT_GROUP, "user1", "jez");
        CONFIG_HELPER.setOperatePermissionForStage(PIPELINE_NAME, STAGE_NAME, "jez");

        assertThat(securityService.hasOperatePermissionForStage(PIPELINE_NAME, STAGE_NAME, "jez"), is(true));
        assertThat(securityService.hasOperatePermissionForStage(PIPELINE_NAME, STAGE_NAME, "user1"), is(false));
    }

    @Test
    public void shouldUseStageAuthorizationForFirstStage() throws Exception {
        CONFIG_HELPER.addSecurityWithAdminConfig();
        CONFIG_HELPER.setOperatePermissionForStage(PIPELINE_NAME, STAGE_NAME, "jez");

        assertThat(securityService.hasOperatePermissionForFirstStage(PIPELINE_NAME, "jez"), is(true));
        assertThat(securityService.hasOperatePermissionForFirstStage(PIPELINE_NAME, "anyone"), is(false));
    }

    @Test
    public void shouldNotAuthorizeIfUserIsNotDefinedInApprovalList() throws Exception {
        CONFIG_HELPER.addSecurityWithAdminConfig();
        StageConfig stage = StageConfigMother.custom("ft", authConfigWithUserJez);
        PipelineConfig pipeline = CONFIG_HELPER.addStageToPipeline(PIPELINE_NAME, stage);

        assertThat("User hacker should not have permission on ft stage",
                securityService.hasOperatePermissionForStage(CaseInsensitiveString.str(pipeline.name()), CaseInsensitiveString.str(stage.name()), "hacker"), is(false));
    }

    @Test
    public void shouldAuthorizeIfSecurityIsTurnedOff() throws Exception {
        StageConfig stage = StageConfigMother.custom("ft", authConfigWithUserJez);
        PipelineConfig pipeline = CONFIG_HELPER.addStageToPipeline(PIPELINE_NAME, stage);

        assertThat("User hacker should have permission on ft stage since security is turned off",
                securityService.hasOperatePermissionForStage(CaseInsensitiveString.str(pipeline.name()), CaseInsensitiveString.str(stage.name()), "hacker"), is(true));
    }

    @Test
    public void shouldAuthorizeAnyUserIfNoAuthorizationDefinedForAutoApproval() throws Exception {
        CONFIG_HELPER.addSecurityWithAdminConfig();
        StageConfig stage = StageConfigMother.custom("ft", Approval.automaticApproval());
        PipelineConfig pipeline = CONFIG_HELPER.addStageToPipeline(PIPELINE_NAME, stage);

        assertThat("Cruise should not have permission on ft stage unless configured with permission",
                securityService.hasOperatePermissionForStage(CaseInsensitiveString.str(pipeline.name()), CaseInsensitiveString.str(stage.name()), "cruise"), is(true));
    }

    @Test
    public void shouldAuthorizeUserCruiseIfUserIsAuthorisedToOperateAutoStage() throws Exception {
        CONFIG_HELPER.addSecurityWithAdminConfig();
        CONFIG_HELPER.setOperatePermissionForStage(PIPELINE_NAME, STAGE_NAME, "cruise");
        StageConfig stage = StageConfigMother.custom("ft", new Approval(new AuthConfig(new AdminUser(new CaseInsensitiveString("cruise")))));
        PipelineConfig pipeline = CONFIG_HELPER.addStageToPipeline(PIPELINE_NAME, stage);
        assertThat(securityService.hasOperatePermissionForStage(CaseInsensitiveString.str(pipeline.name()), CaseInsensitiveString.str(stage.name()), "cruise"), is(true));
        assertThat(securityService.hasOperatePermissionForStage(PIPELINE_NAME, STAGE_NAME, "anyone"), is(false));
    }

}


text:
package org.apache.spark.ml.feature

import org.apache.hadoop.fs.Path

import org.apache.spark.annotation.{Experimental, Since}
import org.apache.spark.ml.{Estimator, Model}
import org.apache.spark.ml.param.{ParamMap, Params}
import org.apache.spark.ml.param.shared.{HasInputCol, HasOutputCol}
import org.apache.spark.ml.util._
import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
import org.apache.spark.mllib.stat.Statistics
import org.apache.spark.sql._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{StructField, StructType}

/**
 * Params for [[MaxAbsScaler]] and [[MaxAbsScalerModel]].
 */
private[feature] trait MaxAbsScalerParams extends Params with HasInputCol with HasOutputCol {

   /** Validates and transforms the input schema. */
  protected def validateAndTransformSchema(schema: StructType): StructType = {
    val inputType = schema($(inputCol)).dataType
    require(inputType.isInstanceOf[VectorUDT],
      s"Input column ${$(inputCol)} must be a vector column")
    require(!schema.fieldNames.contains($(outputCol)),
      s"Output column ${$(outputCol)} already exists.")
    val outputFields = schema.fields :+ StructField($(outputCol), new VectorUDT, false)
    StructType(outputFields)
  }
}

/**
 * :: Experimental ::
 * Rescale each feature individually to range [-1, 1] by dividing through the largest maximum
 * absolute value in each feature. It does not shift/center the data, and thus does not destroy
 * any sparsity.
 */
@Experimental
class MaxAbsScaler @Since("2.0.0") (override val uid: String)
  extends Estimator[MaxAbsScalerModel] with MaxAbsScalerParams with DefaultParamsWritable {

  @Since("2.0.0")
  def this() = this(Identifiable.randomUID("maxAbsScal"))

  /** @group setParam */
  def setInputCol(value: String): this.type = set(inputCol, value)

  /** @group setParam */
  def setOutputCol(value: String): this.type = set(outputCol, value)

  @Since("2.0.0")
  override def fit(dataset: Dataset[_]): MaxAbsScalerModel = {
    transformSchema(dataset.schema, logging = true)
    val input = dataset.select($(inputCol)).rdd.map { case Row(v: Vector) => v }
    val summary = Statistics.colStats(input)
    val minVals = summary.min.toArray
    val maxVals = summary.max.toArray
    val n = minVals.length
    val maxAbs = Array.tabulate(n) { i => math.max(math.abs(minVals(i)), math.abs(maxVals(i))) }

    copyValues(new MaxAbsScalerModel(uid, Vectors.dense(maxAbs)).setParent(this))
  }

  override def transformSchema(schema: StructType): StructType = {
    validateAndTransformSchema(schema)
  }

  override def copy(extra: ParamMap): MaxAbsScaler = defaultCopy(extra)
}

@Since("1.6.0")
object MaxAbsScaler extends DefaultParamsReadable[MaxAbsScaler] {

  @Since("1.6.0")
  override def load(path: String): MaxAbsScaler = super.load(path)
}

/**
 * :: Experimental ::
 * Model fitted by [[MaxAbsScaler]].
 *
 */
@Experimental
class MaxAbsScalerModel private[ml] (
    override val uid: String,
    val maxAbs: Vector)
  extends Model[MaxAbsScalerModel] with MaxAbsScalerParams with MLWritable {

  import MaxAbsScalerModel._

  /** @group setParam */
  def setInputCol(value: String): this.type = set(inputCol, value)

  /** @group setParam */
  def setOutputCol(value: String): this.type = set(outputCol, value)

  @Since("2.0.0")
  override def transform(dataset: Dataset[_]): DataFrame = {
    transformSchema(dataset.schema, logging = true)
    // TODO: this looks hack, we may have to handle sparse and dense vectors separately.
    val maxAbsUnzero = Vectors.dense(maxAbs.toArray.map(x => if (x == 0) 1 else x))
    val reScale = udf { (vector: Vector) =>
      val brz = vector.toBreeze / maxAbsUnzero.toBreeze
      Vectors.fromBreeze(brz)
    }
    dataset.withColumn($(outputCol), reScale(col($(inputCol))))
  }

  override def transformSchema(schema: StructType): StructType = {
    validateAndTransformSchema(schema)
  }

  override def copy(extra: ParamMap): MaxAbsScalerModel = {
    val copied = new MaxAbsScalerModel(uid, maxAbs)
    copyValues(copied, extra).setParent(parent)
  }

  @Since("1.6.0")
  override def write: MLWriter = new MaxAbsScalerModelWriter(this)
}

@Since("1.6.0")
object MaxAbsScalerModel extends MLReadable[MaxAbsScalerModel] {

  private[MaxAbsScalerModel]
  class MaxAbsScalerModelWriter(instance: MaxAbsScalerModel) extends MLWriter {

    private case class Data(maxAbs: Vector)

    override protected def saveImpl(path: String): Unit = {
      DefaultParamsWriter.saveMetadata(instance, path, sc)
      val data = new Data(instance.maxAbs)
      val dataPath = new Path(path, "data").toString
      sqlContext.createDataFrame(Seq(data)).repartition(1).write.parquet(dataPath)
    }
  }

  private class MaxAbsScalerModelReader extends MLReader[MaxAbsScalerModel] {

    private val className = classOf[MaxAbsScalerModel].getName

    override def load(path: String): MaxAbsScalerModel = {
      val metadata = DefaultParamsReader.loadMetadata(path, sc, className)
      val dataPath = new Path(path, "data").toString
      val Row(maxAbs: Vector) = sqlContext.read.parquet(dataPath)
        .select("maxAbs")
        .head()
      val model = new MaxAbsScalerModel(metadata.uid, maxAbs)
      DefaultParamsReader.getAndSetParams(model, metadata)
      model
    }
  }

  @Since("1.6.0")
  override def read: MLReader[MaxAbsScalerModel] = new MaxAbsScalerModelReader

  @Since("1.6.0")
  override def load(path: String): MaxAbsScalerModel = super.load(path)
}


text:
'use strict';

/**
 * @ngdoc function
 * @name 60YeomanApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the 60YeomanApp
 */
angular.module('60YeomanApp')
  .controller('MainCtrl', function () {
    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });


text:
class SuperBuilderWithPrefixes {
	int mField;
	int xOtherField;
	java.util.List<String> mItems;
	@java.lang.SuppressWarnings("all")
	public static abstract class SuperBuilderWithPrefixesBuilder<C extends SuperBuilderWithPrefixes, B extends SuperBuilderWithPrefixesBuilder<C, B>> {
		@java.lang.SuppressWarnings("all")
		private int field;
		@java.lang.SuppressWarnings("all")
		private int otherField;
		@java.lang.SuppressWarnings("all")
		private java.util.ArrayList<String> items;
		@java.lang.SuppressWarnings("all")
		protected abstract B self();
		@java.lang.SuppressWarnings("all")
		public abstract C build();
		@java.lang.SuppressWarnings("all")
		public B field(final int field) {
			this.field = field;
			return self();
		}
		@java.lang.SuppressWarnings("all")
		public B otherField(final int otherField) {
			this.otherField = otherField;
			return self();
		}
		@java.lang.SuppressWarnings("all")
		public B item(final String item) {
			if (this.items == null) this.items = new java.util.ArrayList<String>();
			this.items.add(item);
			return self();
		}
		@java.lang.SuppressWarnings("all")
		public B items(final java.util.Collection<? extends String> items) {
			if (this.items == null) this.items = new java.util.ArrayList<String>();
			this.items.addAll(items);
			return self();
		}
		@java.lang.SuppressWarnings("all")
		public B clearItems() {
			if (this.items != null) this.items.clear();
			return self();
		}
		@java.lang.Override
		@java.lang.SuppressWarnings("all")
		public java.lang.String toString() {
			return "SuperBuilderWithPrefixes.SuperBuilderWithPrefixesBuilder(field=" + this.field + ", otherField=" + this.otherField + ", items=" + this.items + ")";
		}
	}
	@java.lang.SuppressWarnings("all")
	private static final class SuperBuilderWithPrefixesBuilderImpl extends SuperBuilderWithPrefixesBuilder<SuperBuilderWithPrefixes, SuperBuilderWithPrefixesBuilderImpl> {
		@java.lang.SuppressWarnings("all")
		private SuperBuilderWithPrefixesBuilderImpl() {
		}
		@java.lang.Override
		@java.lang.SuppressWarnings("all")
		protected SuperBuilderWithPrefixesBuilderImpl self() {
			return this;
		}
		@java.lang.Override
		@java.lang.SuppressWarnings("all")
		public SuperBuilderWithPrefixes build() {
			return new SuperBuilderWithPrefixes(this);
		}
	}
	@java.lang.SuppressWarnings("all")
	protected SuperBuilderWithPrefixes(final SuperBuilderWithPrefixesBuilder<?, ?> b) {
		this.mField = b.field;
		this.xOtherField = b.otherField;
		java.util.List<String> items;
		switch (b.items == null ? 0 : b.items.size()) {
		case 0:
			items = java.util.Collections.emptyList();
			break;
		case 1:
			items = java.util.Collections.singletonList(b.items.get(0));
			break;
		default:
			items = java.util.Collections.unmodifiableList(new java.util.ArrayList<String>(b.items));
		}
		this.mItems = items;
	}
	@java.lang.SuppressWarnings("all")
	public static SuperBuilderWithPrefixesBuilder<?, ?> builder() {
		return new SuperBuilderWithPrefixesBuilderImpl();
	}
}