text:
@interface DossierViewController ()

@property (nonatomic, strong) IBOutlet UILabel *nameLabel;
@property (nonatomic, strong) IBOutlet UIImageView *headshotImageView;
@property (nonatomic, strong) IBOutlet JSKViewStack *serviceRecordViewStack;

@property (nonatomic, strong) UIFont *font;

- (void)addServiceRecordEntry:(NSString *)message;
- (void)generateServiceRecord;

@end

@implementation DossierViewController

@synthesize nameLabel = m_nameLabel;
@synthesize headshotImageView = m_headshotImageView;
@synthesize serviceRecordViewStack = m_serviceRecordViewStack;
@synthesize delegate = m_delegate;
@synthesize font = m_font;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.title = NSLocalizedString(@"Dossier", @"Dossier  --  title");

    PlayerEnvoy *playerEnvoy = [self.delegate supplyPlayerEnvoy:self];
    [self.nameLabel setText:playerEnvoy.playerName];
    [self.headshotImageView setImage:playerEnvoy.image];

    [self.serviceRecordViewStack setBackgroundColor:[UIColor clearColor]];
    [self.serviceRecordViewStack setShouldNotShrinkToFit:YES];

    [self generateServiceRecord];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private

- (void)generateServiceRecord
{
    GameEnvoy *gameEnvoy = [SystemMessage gameEnvoy];
    if (!gameEnvoy)
    {
        return;
    }

    NSString *playerID = [self.delegate supplyPlayerEnvoy:self].intramuralID;

    NSUInteger successfulMissions = 0;
    NSUInteger failedMissions = 0;
    NSUInteger successfulMissionsCoordinated = 0;
    NSUInteger failedMissionsCoordinated = 0;

    for (MissionEnvoy *missionEnvoy in gameEnvoy.missionEnvoys)
    {
        BOOL wasOnTeam = NO;
        BOOL wasCoordinater = NO;
        if (missionEnvoy.isComplete)
        {
            for (PlayerEnvoy *teamMember in missionEnvoy.teamMembers)
            {
                if ([teamMember.intramuralID isEqualToString:playerID])
                {
                    // This player was in the mission.
                    wasOnTeam = YES;
                    break;
                }
            }
            if ([missionEnvoy.coordinator.intramuralID isEqualToString:playerID])
            {
                wasCoordinater = YES;
            }
        }

        if (wasOnTeam)
        {
            if (missionEnvoy.didSucceed)
            {
                successfulMissions++;
            }
            else
            {
                failedMissions++;
            }
        }

        if (wasCoordinater)
        {
            if (missionEnvoy.didSucceed)
            {
                successfulMissionsCoordinated++;
            }
            else
            {
                failedMissionsCoordinated++;
            }
        }

    }

    if (successfulMissions + failedMissions + successfulMissionsCoordinated + failedMissionsCoordinated == 0)
    {
        return;
    }

    NSString *coordinatedPrefix = NSLocalizedString(@"Coordinated", @"Coordinated  --  label prefix");
    NSString *participatedPrefix = NSLocalizedString(@"Participated in", @"Participated in  --  label prefix");
    NSString *successfulSuffix = NSLocalizedString(@"successful missions.", @"successful missions.  --  label suffix");
    NSString *failedSuffix = NSLocalizedString(@"failed missions.", @"failed missions.  --  label suffix");
    NSString *successfulSuffixSingular = NSLocalizedString(@"successful mission.", @"successful mission.  --  label suffix");
    NSString *failedSuffixSingular = NSLocalizedString(@"failed mission.", @"failed mission.  --  label suffix");

    if (successfulMissions > 0)
    {
        NSString *spellOut = [SystemMessage spellOutInteger:successfulMissions];
        NSString *suffix = nil;
        if (successfulMissions == 1)
        {
            suffix = successfulSuffixSingular;
        }
        else
        {
            suffix = successfulSuffix;
        }
        NSString *entry = [[NSString alloc] initWithFormat:@"%@ %@ %@", participatedPrefix, spellOut, suffix];
        [self addServiceRecordEntry:entry];
    }

    if (failedMissions > 0)
    {
        NSString *spellOut = [SystemMessage spellOutInteger:failedMissions];
        NSString *suffix = nil;
        if (failedMissions == 1)
        {
            suffix = failedSuffixSingular;
        }
        else
        {
            suffix = failedSuffix;
        }
        NSString *entry = [[NSString alloc] initWithFormat:@"%@ %@ %@", participatedPrefix, spellOut, suffix];
        [self addServiceRecordEntry:entry];
    }

    if (successfulMissionsCoordinated > 0)
    {
        NSString *spellOut = [SystemMessage spellOutInteger:successfulMissionsCoordinated];
        NSString *suffix = nil;
        if (successfulMissionsCoordinated == 1)
        {
            suffix = successfulSuffixSingular;
        }
        else
        {
            suffix = successfulSuffix;
        }
        NSString *entry = [[NSString alloc] initWithFormat:@"%@ %@ %@", coordinatedPrefix, spellOut, suffix];
        [self addServiceRecordEntry:entry];
    }

    if (failedMissionsCoordinated > 0)
    {
        NSString *spellOut = [SystemMessage spellOutInteger:failedMissionsCoordinated];
        NSString *suffix = nil;
        if (failedMissionsCoordinated == 1)
        {
            suffix = failedSuffixSingular;
        }
        else
        {
            suffix = failedSuffix;
        }
        NSString *entry = [[NSString alloc] initWithFormat:@"%@ %@ %@", coordinatedPrefix, spellOut, suffix];
        [self addServiceRecordEntry:entry];
    }
}

- (void)addServiceRecordEntry:(NSString *)message
{
    CGRect labelFrame = CGRectMake(10.0f, 10.0f, self.serviceRecordViewStack.frame.size.width - 20.0f, 25.0f);
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    [label setText:message];
    if (!self.font)
    {
        UIFont *font = [UIFont fontWithName:@"GillSans" size:15];
        self.font = font;
    }
    [label setFont:self.font];
//    [label setFont:[UIFont systemFontOfSize:13.0f]];
    [self.serviceRecordViewStack addView:label];
}

@end


text:
#ifndef CachePolicy_h
#define CachePolicy_h

namespace WebCore {

    enum CachePolicy {
        CachePolicyCache,
        CachePolicyVerify,
        CachePolicyRevalidate,
        CachePolicyReload,
        CachePolicyHistoryBuffer
    };

}

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Rad\Network\Http\Cookie;

use Rad\Core\Exception\BaseException;

/**
 * Cookie Exception
 *
 * @package Rad\Network\Http\Cookie
 */
class Exception extends BaseException
{

}


text:
var mysql = require('mysql');
var session = require('express-session');
var config = require('./config');
var md5 = require('md5');
var async = require('async');

//NOTE: DO NOT require('./user') HERE. User already depends on openchat

var OpenChat = function(conversationId, userId, title, type, checkpoint, partnerId) {
    this.conversationId = conversationId;
    this.userId = userId;
    this.title = title;
    this.type = type;
    this.checkpoint = checkpoint;
    this.partnerId = partnerId;
}

OpenChat.IM = 0;
OpenChat.CHATROOM = 1;

OpenChat.mapOpenChatQuery = function(sql, params, callback) {
    var connection = mysql.createConnection(config.siteDatabaseOptions);

    connection.connect(function(err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            callback(err, null);
            return;
        }

        connection.query(sql, params,
            function(err, results) {
                if (err) {
                    connection.end();
                    callback(err, null);
                    return;
                }

                var ret = [];
                for (var i = 0, len = results.length; i < len; i++) {
                    var result = results[i];

                    ret.push(
                      new OpenChat(result.conversation_id, result.user_id,
                        result.title, result.type, result.checkpoint,
                        result.partner_id));
                }

                connection.end();

                callback(null, ret);
            }
        );
    });
}

OpenChat.getOpenChats = function(userId, callback) {
    OpenChat.mapOpenChatQuery(
        "SELECT * FROM open_chats " +
        "WHERE user_id = ? ", [userId], callback
    );
}

/**
 * Starts a new IM between two users generating
 * the proper chat ID for the conversation
 */
OpenChat.startIM = function(userA, userB, callback) {
    //hash as:
    //find the lowest user UUID and make that user
    //userA, then the conversation ID becomes...
    // md5([userA_id][userA_salt][userB_id][userB_salt])
    if (userB.UUID < userA.UUID) {
        var temp = userA;
        userA = userB;
        userB = temp;
    }

    var convId = md5(userA.UUID + userA.salt + userB.UUID + userB.salt);

    var atitle = "IM with " + userB.username;
    var btitle = "IM with " + userA.username;

    //create the new chat for both sides
    OpenChat.createNewChat(convId, userA.UUID, atitle, false, OpenChat.IM, userB.UUID,
        function(err) {
            if (err && err.code != 'ER_DUP_ENTRY') { //we'll get dup if a user tries to start the same IM twice
                callback(err, null);
                return;
            }

            OpenChat.createNewChat(convId, userB.UUID, btitle, false, OpenChat.IM, userA.UUID,
                function(err) {
                    if (err && err.code != 'ER_DUP_ENTRY') {
                        callback(err);
                        return;
                    }

                    //success
                    callback(null, convId);
                }
            );
        }
    );
}

OpenChat.createNewChat = function(conversationId, userId, title, public, type, partnerId, callback) {
    var connection = mysql.createConnection(config.siteDatabaseOptions);

    connection.connect(function(err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            callback(err);
            return;
        }

        async.series([
            function (callback) {
                var sql = "INSERT INTO open_chats(user_id, conversation_id, title, type, partner_id) " +
                          "VALUES(?, ?, ?, ?, ?);";

                var query = connection.query(sql, [userId, conversationId, title, type, partnerId],
                    function(err, results) {
                        if (err) {
                            connection.end();
                            callback(err);
                            return;
                        }

                        callback(null);
                });
            },

            function (callback) {
                if (public) {
                    var sql = "INSERT INTO public_chats(conversation_id, title, user_count) " +
                              "VALUES(?, ?, 1) " +
                              "ON DUPLICATE KEY UPDATE user_count = user_count + 1;";

                    var query = connection.query(sql, [conversationId, title],
                        function(err, results) {
                            if (err) {
                                connection.end();
                                callback(err);
                                return;
                            }

                            callback(null);
                            connection.end();
                    });

                } else {
                    callback(null);
                    connection.end();
                }

            },
        ], function done(err) {
            callback(err);
        });

    });
}

OpenChat.findChatInfo = function(userId, conversationId, callback) {
    OpenChat.mapOpenChatQuery(
        "SELECT * FROM open_chats " +
        "WHERE user_id = ? AND conversation_id = ? ", [userId, conversationId],
        function(err, info) {
            if (err || !info) {
                callback(err, info);
                return;
            }

            callback(null, info[0]);
        }
    );
}

/**
 * Adds the given user to a chat room
 */
OpenChat.joinRoom = function(roomName, public, userId, callback) {
    //hash as: md5(roomName)
    var convId = md5(roomName);
    var atitle = roomName;

    //create the new chat for the user
    OpenChat.createNewChat(convId, userId, atitle, public, OpenChat.CHATROOM, null,
        function(err) {
            if (err && err.code != 'ER_DUP_ENTRY') { //we'll get dup if a user tries to start the same room twice
                callback(err, null);
                return;
            }

            //success
            callback(null, convId);
        }
    );
}

/**
 * Removes the given user from a chat
 */
OpenChat.leaveChat = function(conversationId, userId, callback) {
    var connection = mysql.createConnection(config.siteDatabaseOptions);

    connection.connect(function(err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            callback(err);
            return;
        }

        async.series([
            function (callback) {
                var sql = "DELETE FROM open_chats WHERE user_id = ? AND conversation_id = ?;";

                connection.query(sql, [userId, conversationId],
                    function(err, results) {
                        if (err) {
                            connection.end();
                            callback(err);
                            return;
                        }

                        callback(null);
                });
            },

            function (callback) {
                var sql = "UPDATE public_chats SET user_count = user_count - 1 " +
                            "WHERE conversation_id = ?;";

                connection.query(sql, [conversationId],
                    function(err, results) {
                        if (err) {
                            connection.end();
                            callback(err);
                            return;
                        }

                        callback(null);
                });
            },

            function (callback) {
                var sql = "DELETE FROM public_chats " +
                            "WHERE conversation_id = ? AND user_count = 0;";

                connection.query(sql, [conversationId],
                    function(err, results) {
                        if (err) {
                            connection.end();
                            callback(err);
                            return;
                        }

                        callback(null);
                });
            },

        ], function done(err) {
            connection.end();
            callback(err);
        });

    });
}

OpenChat.setCheckpoint = function(conversationId, userId, checkpoint, callback) {
    var connection = mysql.createConnection(config.siteDatabaseOptions);

    connection.connect(function(err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            callback(err);
            return;
        }

        var sql = "UPDATE open_chats SET checkpoint = ? WHERE user_id = ? AND conversation_id = ?;";

        connection.query(sql, [checkpoint, userId, conversationId],
            function(err, results) {
                if (err) {
                    connection.end();
                    callback(err);
                    return;
                }

                callback(null);
                connection.end();
        });
    });
}

module.exports = OpenChat;


text:
How can it be used locally and remotely?
========================================

The bluesky ecosystem provides several modes for accessing data:

* Access Central DataBroker via a Generic Remote Client --- This includes
  Remote Desktop, Jupyter, and SSH.
* Portable DataBroker with Local Data --- Let users use ``databroker`` on their
  laptops and/or on servers at their home institutions, with all the relevant
  data copied locally and no need for a network connection.
* Portable DataBroker with Remote Data --- Let users use ``databroker`` on their
  laptops and/or on servers at their home institutions, pulling data from an
  HTTP server on demand, and optionally caching it locally.
* Traditional File Export --- Export data to files for existing software that
  expects files in a certain format named a certain way.

Access Central DataBroker via a Generic Remote Client
-----------------------------------------------------

In this mode, users do not install ``databroker`` locally. They use any remote
client---such as Remote Desktop, Jupyter, or SSH---to access a Python
environment on the source machine, and use ``databroker`` there, which
presumably has fast access to the data storage and some compute resources.

Portable DataBroker with Local Data
-----------------------------------

DataBroker is not itself a data store; it is a Python library for accessing
data across a variety of data stores. Therefore, it can be run on a laptop
without network connectivity, accessing data stored in ordinary files or in
a local database. Both are officially supported.

The process involves:

#. Identify a subset of the data to be copied locally from the source
   institution, given as a query (e.g. a time range) or a list of unique
   identifiers. Export the documents into a file-based format (typically
   msgpack). Copy any of the large "external" files (e.g. TIFF or HDF5 files
   generated by large detectors).
#. Transfer all of this to the target machine, perhaps via ``rsync`` or Globus.
   Place a configuration file discoverable by ``databroker`` that points to the
   location where the files were transferred.
#. Install the Python library ``databroker`` on the target machine using pip or
   conda.

DataBroker can work on top of a directory of ordinary files just fine; it even
supports the same queries that it would normally run on a database---just less
efficiently. Optionally, ingest the documents into a local database to support
more efficient queries.

The small utility
`databroker-pack <https://blueskyproject.io/databroker-pack>`_ streamlines the
process of "packing" some data from data broker into portable files and
"unpacking" them at their destination.

Portable DataBroker with Remote Data
------------------------------------

In this mode, data copying would happen invisibility to the user and only on
demand. The process involves:

#. Install the Python library ``databroker`` on the target machine using pip or
   conda.
#. Provide databroker with the URL of a remote "remote data catalog" running
   that the source facility.

The user experience from there is exactly the same where the data happens to be
local or remote. Thus, users could write code in one mode and seamless
transition to the other.

Data is downloaded on demand, and it may be cached locally so that it need not
be repeatedly downloaded. This requires a stable URL and a reliable network
connection. There are *no instances of this mode* known at this time, but all
the software pieces to achieve it exist. It is on the project roadmap.

Traditional File Export
-----------------------

Export the data to files (e.g. TIFFs and/or CSVs) with the metadata of your
choice encoded in filenames. This mode forfeits much of the power of databroker
and the bluesky ecosystem generally, but it is important for supporting
existing workflows and software that expects files in a certain format named a
certain way.

We expect this mode to become less useful as data sizes increase and scientific
software literacy grows over time. It is a bridge.

Streaming Export
^^^^^^^^^^^^^^^^

This means exporting the data during data acquisition such that partial results
are available for reading. The bluesky
`suitcase <https://blueskyproject.io/suitcase/>`_ project provides a pattern
for doing this and ready-to-use implementations for popular formats.

The streaming export tools may also be used after data acquisition.

Prompt Export
^^^^^^^^^^^^^

This means exporting the data at the end of data acquisition. (To be precise,
at the end of each "Bluesky Run". The scope of a "Run" is up to the details of
the data acquisition procedure.) This is typically much simpler than streaming
export and can be implemented *ad hoc* by accessing the data from databroker
and writing out a file using the relevant Python I/O library.


text:
--
-- Test access privileges
--
set optimizer=off;
-- Clean up in case a prior regression run failed

-- Suppress NOTICE messages when users/groups don't exist
SET client_min_messages TO 'error';

DROP ROLE IF EXISTS regressgroup1;
DROP ROLE IF EXISTS regressgroup2;

DROP ROLE IF EXISTS regressuser1;
DROP ROLE IF EXISTS regressuser2;
DROP ROLE IF EXISTS regressuser3;
DROP ROLE IF EXISTS regressuser4;
DROP ROLE IF EXISTS regressuser5;

RESET client_min_messages;

-- test proper begins here

CREATE USER regressuser1;
CREATE USER regressuser2;
CREATE USER regressuser3;
CREATE USER regressuser4;
CREATE USER regressuser5;
CREATE USER regressuser5;	-- duplicate

CREATE GROUP regressgroup1;
CREATE GROUP regressgroup2 WITH USER regressuser1, regressuser2;

ALTER GROUP regressgroup1 ADD USER regressuser4;

ALTER GROUP regressgroup2 ADD USER regressuser2;	-- duplicate
ALTER GROUP regressgroup2 DROP USER regressuser2;
GRANT regressgroup2 TO regressuser4 WITH ADMIN OPTION;

-- test owner privileges

SET SESSION AUTHORIZATION regressuser1;
SELECT session_user, current_user;

CREATE TABLE atest1 ( a int, b text );
SELECT * FROM atest1;
INSERT INTO atest1 VALUES (1, 'one');
DELETE FROM atest1;
UPDATE atest1 SET b = 'blech' WHERE a = 213;
TRUNCATE atest1;
LOCK atest1 IN ACCESS EXCLUSIVE MODE;

REVOKE ALL ON atest1 FROM PUBLIC;
SELECT * FROM atest1;

GRANT ALL ON atest1 TO regressuser2;
GRANT SELECT ON atest1 TO regressuser3, regressuser4;
SELECT * FROM atest1;

CREATE TABLE atest2 (col1 varchar(10), col2 boolean);
GRANT SELECT ON atest2 TO regressuser2;
GRANT UPDATE ON atest2 TO regressuser3;
GRANT INSERT ON atest2 TO regressuser4;
GRANT TRUNCATE ON atest2 TO regressuser5;

SET SESSION AUTHORIZATION regressuser2;
SELECT session_user, current_user;

-- try various combinations of queries on atest1 and atest2

SELECT * FROM atest1; -- ok
SELECT * FROM atest2; -- ok
INSERT INTO atest1 VALUES (2, 'two'); -- ok
INSERT INTO atest2 VALUES ('foo', true); -- fail
INSERT INTO atest1 SELECT 1, b FROM atest1; -- ok
UPDATE atest1 SET b = 'twotwo' WHERE a = 2; -- ok
UPDATE atest2 SET col2 = NOT col2; -- fail
SELECT * FROM atest1 FOR UPDATE; -- ok
SELECT * FROM atest2 FOR UPDATE; -- fail
DELETE FROM atest2; -- fail
TRUNCATE atest2; -- fail
LOCK atest2 IN ACCESS EXCLUSIVE MODE; -- fail
COPY atest2 FROM stdin; -- fail
GRANT ALL ON atest1 TO PUBLIC; -- fail

-- checks in subquery, both ok
SELECT * FROM atest1 WHERE ( b IN ( SELECT col1 FROM atest2 ) );
SELECT * FROM atest2 WHERE ( col1 IN ( SELECT b FROM atest1 ) );

SET SESSION AUTHORIZATION regressuser3;
SELECT session_user, current_user;

SELECT * FROM atest1; -- ok
SELECT * FROM atest2; -- fail
INSERT INTO atest1 VALUES (2, 'two'); -- fail
INSERT INTO atest2 VALUES ('foo', true); -- fail
INSERT INTO atest1 SELECT 1, b FROM atest1; -- fail
UPDATE atest1 SET b = 'twotwo' WHERE a = 2; -- fail
UPDATE atest2 SET col2 = NULL; -- ok
UPDATE atest2 SET col2 = NOT col2; -- fails; requires SELECT on atest2
UPDATE atest2 SET col2 = true FROM atest1 WHERE atest1.a = 5; -- ok
SELECT * FROM atest1 FOR UPDATE; -- fail
SELECT * FROM atest2 FOR UPDATE; -- fail
DELETE FROM atest2; -- fail
TRUNCATE atest2; -- fail
LOCK atest2 IN ACCESS EXCLUSIVE MODE; -- ok
COPY atest2 FROM stdin; -- fail

-- checks in subquery, both fail
SELECT * FROM atest1 WHERE ( b IN ( SELECT col1 FROM atest2 ) );
SELECT * FROM atest2 WHERE ( col1 IN ( SELECT b FROM atest1 ) );

SET SESSION AUTHORIZATION regressuser4;
COPY atest2 FROM stdin; -- ok
bar	true
\.
SELECT * FROM atest1; -- ok

-- groups

SET SESSION AUTHORIZATION regressuser3;
CREATE TABLE atest3 (one int, two int, three int);
GRANT DELETE ON atest3 TO GROUP regressgroup2;

SET SESSION AUTHORIZATION regressuser1;

SELECT * FROM atest3; -- fail
DELETE FROM atest3; -- ok

-- views

SET SESSION AUTHORIZATION regressuser3;

CREATE VIEW atestv1 AS SELECT * FROM atest1; -- ok
/* The next *should* fail, but it's not implemented that way yet. */
CREATE VIEW atestv2 AS SELECT * FROM atest2;
CREATE VIEW atestv3 AS SELECT * FROM atest3; -- ok

SELECT * FROM atestv1; -- ok
SELECT * FROM atestv2; -- fail
GRANT SELECT ON atestv1, atestv3 TO regressuser4;
GRANT SELECT ON atestv2 TO regressuser2;

SET SESSION AUTHORIZATION regressuser4;

SELECT * FROM atestv1; -- ok
SELECT * FROM atestv2; -- fail
SELECT * FROM atestv3; -- ok

CREATE VIEW atestv4 AS SELECT * FROM atestv3; -- nested view
SELECT * FROM atestv4; -- ok
GRANT SELECT ON atestv4 TO regressuser2;

SET SESSION AUTHORIZATION regressuser2;

-- Two complex cases:

SELECT * FROM atestv3; -- fail
SELECT * FROM atestv4; -- ok (even though regressuser2 cannot access underlying atestv3)

SELECT * FROM atest2; -- ok
SELECT * FROM atestv2; -- fail (even though regressuser2 can access underlying atest2)

-- privileges on functions, languages

-- switch to superuser
\c -

REVOKE ALL PRIVILEGES ON LANGUAGE sql FROM PUBLIC;
GRANT USAGE ON LANGUAGE sql TO regressuser1; -- ok
GRANT USAGE ON LANGUAGE c TO PUBLIC; -- fail

SET SESSION AUTHORIZATION regressuser1;
GRANT USAGE ON LANGUAGE sql TO regressuser2; -- fail
CREATE FUNCTION testfunc1(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql CONTAINS SQL;
CREATE FUNCTION testfunc2(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql CONTAINS SQL;

REVOKE ALL ON FUNCTION testfunc1(int), testfunc2(int) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION testfunc1(int), testfunc2(int) TO regressuser2;
GRANT USAGE ON FUNCTION testfunc1(int) TO regressuser3; -- semantic error
GRANT ALL PRIVILEGES ON FUNCTION testfunc1(int) TO regressuser4;
GRANT ALL PRIVILEGES ON FUNCTION testfunc_nosuch(int) TO regressuser4;

CREATE FUNCTION testfunc4(boolean) RETURNS text
  AS 'select col1 from atest2 where col2 = $1;'
  LANGUAGE sql SECURITY DEFINER READS SQL DATA;
GRANT EXECUTE ON FUNCTION testfunc4(boolean) TO regressuser3;

SET SESSION AUTHORIZATION regressuser2;
SELECT testfunc1(5), testfunc2(5); -- ok
CREATE FUNCTION testfunc3(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql CONTAINS SQL; -- fail

SET SESSION AUTHORIZATION regressuser3;
SELECT testfunc1(5); -- fail
SELECT col1 FROM atest2 WHERE col2 = true; -- fail
SELECT testfunc4(true); -- ok

SET SESSION AUTHORIZATION regressuser4;
SELECT testfunc1(5); -- ok

DROP FUNCTION testfunc1(int); -- fail

\c -

DROP FUNCTION testfunc1(int); -- ok
-- restore to sanity
GRANT ALL PRIVILEGES ON LANGUAGE sql TO PUBLIC;

-- truncate
SET SESSION AUTHORIZATION regressuser5;
TRUNCATE atest2; -- ok
TRUNCATE atest3; -- fail

-- has_table_privilege function

-- bad-input checks
select has_table_privilege(NULL,'pg_authid','select');
select has_table_privilege('pg_shad','select');
select has_table_privilege('nosuchuser','pg_authid','select');
select has_table_privilege('pg_authid','sel');
select has_table_privilege(-999999,'pg_authid','update');
select has_table_privilege(1,'select');

-- superuser
\c -

select has_table_privilege(current_user,'pg_authid','select');
select has_table_privilege(current_user,'pg_authid','insert');

select has_table_privilege(t2.oid,'pg_authid','update')
from (select oid from pg_roles where rolname = current_user) as t2;
select has_table_privilege(t2.oid,'pg_authid','delete')
from (select oid from pg_roles where rolname = current_user) as t2;

-- 'rule' privilege no longer exists, but for backwards compatibility
-- has_table_privilege still recognizes the keyword and says FALSE
select has_table_privilege(current_user,t1.oid,'rule')
from (select oid from pg_class where relname = 'pg_authid') as t1;
select has_table_privilege(current_user,t1.oid,'references')
from (select oid from pg_class where relname = 'pg_authid') as t1;

select has_table_privilege(t2.oid,t1.oid,'select')
from (select oid from pg_class where relname = 'pg_authid') as t1,
  (select oid from pg_roles where rolname = current_user) as t2;
select has_table_privilege(t2.oid,t1.oid,'insert')
from (select oid from pg_class where relname = 'pg_authid') as t1,
  (select oid from pg_roles where rolname = current_user) as t2;

select has_table_privilege('pg_authid','update');
select has_table_privilege('pg_authid','delete');
select has_table_privilege('pg_authid','truncate');

select has_table_privilege(t1.oid,'select')
from (select oid from pg_class where relname = 'pg_authid') as t1;
select has_table_privilege(t1.oid,'trigger')
from (select oid from pg_class where relname = 'pg_authid') as t1;

-- non-superuser
SET SESSION AUTHORIZATION regressuser3;

select has_table_privilege(current_user,'pg_class','select');
select has_table_privilege(current_user,'pg_class','insert');

select has_table_privilege(t2.oid,'pg_class','update')
from (select oid from pg_roles where rolname = current_user) as t2;
select has_table_privilege(t2.oid,'pg_class','delete')
from (select oid from pg_roles where rolname = current_user) as t2;

select has_table_privilege(current_user,t1.oid,'references')
from (select oid from pg_class where relname = 'pg_class') as t1;

select has_table_privilege(t2.oid,t1.oid,'select')
from (select oid from pg_class where relname = 'pg_class') as t1,
  (select oid from pg_roles where rolname = current_user) as t2;
select has_table_privilege(t2.oid,t1.oid,'insert')
from (select oid from pg_class where relname = 'pg_class') as t1,
  (select oid from pg_roles where rolname = current_user) as t2;

select has_table_privilege('pg_class','update');
select has_table_privilege('pg_class','delete');
select has_table_privilege('pg_class','truncate');

select has_table_privilege(t1.oid,'select')
from (select oid from pg_class where relname = 'pg_class') as t1;
select has_table_privilege(t1.oid,'trigger')
from (select oid from pg_class where relname = 'pg_class') as t1;

select has_table_privilege(current_user,'atest1','select');
select has_table_privilege(current_user,'atest1','insert');

select has_table_privilege(t2.oid,'atest1','update')
from (select oid from pg_roles where rolname = current_user) as t2;
select has_table_privilege(t2.oid,'atest1','delete')
from (select oid from pg_roles where rolname = current_user) as t2;

select has_table_privilege(current_user,t1.oid,'references')
from (select oid from pg_class where relname = 'atest1') as t1;

select has_table_privilege(t2.oid,t1.oid,'select')
from (select oid from pg_class where relname = 'atest1') as t1,
  (select oid from pg_roles where rolname = current_user) as t2;
select has_table_privilege(t2.oid,t1.oid,'insert')
from (select oid from pg_class where relname = 'atest1') as t1,
  (select oid from pg_roles where rolname = current_user) as t2;

select has_table_privilege('atest1','update');
select has_table_privilege('atest1','delete');
select has_table_privilege('atest1','truncate');

select has_table_privilege(t1.oid,'select')
from (select oid from pg_class where relname = 'atest1') as t1;
select has_table_privilege(t1.oid,'trigger')
from (select oid from pg_class where relname = 'atest1') as t1;

-- Grant options

SET SESSION AUTHORIZATION regressuser1;

CREATE TABLE atest4 (a int);

GRANT SELECT ON atest4 TO regressuser2 WITH GRANT OPTION;
GRANT UPDATE ON atest4 TO regressuser2;
GRANT SELECT ON atest4 TO GROUP regressgroup1 WITH GRANT OPTION;

SET SESSION AUTHORIZATION regressuser2;

GRANT SELECT ON atest4 TO regressuser3;
GRANT UPDATE ON atest4 TO regressuser3; -- fail

SET SESSION AUTHORIZATION regressuser1;

REVOKE SELECT ON atest4 FROM regressuser3; -- does nothing
SELECT has_table_privilege('regressuser3', 'atest4', 'SELECT'); -- true
REVOKE SELECT ON atest4 FROM regressuser2; -- fail
REVOKE GRANT OPTION FOR SELECT ON atest4 FROM regressuser2 CASCADE; -- ok
SELECT has_table_privilege('regressuser2', 'atest4', 'SELECT'); -- true
SELECT has_table_privilege('regressuser3', 'atest4', 'SELECT'); -- false

SELECT has_table_privilege('regressuser1', 'atest4', 'SELECT WITH GRANT OPTION'); -- true

-- Admin options

SET SESSION AUTHORIZATION regressuser4;
CREATE FUNCTION dogrant_ok() RETURNS void LANGUAGE sql SECURITY DEFINER AS
	'GRANT regressgroup2 TO regressuser5';
GRANT regressgroup2 TO regressuser5; -- ok: had ADMIN OPTION
SET ROLE regressgroup2;
GRANT regressgroup2 TO regressuser5; -- fails: SET ROLE suspended privilege

SET SESSION AUTHORIZATION regressuser1;
GRANT regressgroup2 TO regressuser5; -- fails: no ADMIN OPTION
SELECT dogrant_ok();			-- ok: SECURITY DEFINER conveys ADMIN
SET ROLE regressgroup2;
GRANT regressgroup2 TO regressuser5; -- fails: SET ROLE did not help

SET SESSION AUTHORIZATION regressgroup2;
GRANT regressgroup2 TO regressuser5; -- ok: a role can self-admin
CREATE FUNCTION dogrant_fails() RETURNS void LANGUAGE sql SECURITY DEFINER AS
	'GRANT regressgroup2 TO regressuser5';
SELECT dogrant_fails();			-- fails: no self-admin in SECURITY DEFINER
DROP FUNCTION dogrant_fails();

SET SESSION AUTHORIZATION regressuser4;
DROP FUNCTION dogrant_ok();
REVOKE regressgroup2 FROM regressuser5;

-- test that dependent privileges are revoked (or not) properly
\c -

set session role regressuser1;
create table dep_priv_test (a int);
grant select on dep_priv_test to regressuser2 with grant option;
grant select on dep_priv_test to regressuser3 with grant option;
set session role regressuser2;
grant select on dep_priv_test to regressuser4 with grant option;
set session role regressuser3;
grant select on dep_priv_test to regressuser4 with grant option;
set session role regressuser4;
grant select on dep_priv_test to regressuser5;
\dp dep_priv_test
set session role regressuser2;
revoke select on dep_priv_test from regressuser4 cascade;
\dp dep_priv_test
set session role regressuser3;
revoke select on dep_priv_test from regressuser4 cascade;
\dp dep_priv_test
set session role regressuser1;
drop table dep_priv_test;

-- clean up

\c regression

DROP FUNCTION testfunc2(int);
DROP FUNCTION testfunc4(boolean);

DROP VIEW atestv1;
DROP VIEW atestv2;
-- this should cascade to drop atestv4
DROP VIEW atestv3 CASCADE;
-- this should complain "does not exist"
DROP VIEW atestv4;

DROP TABLE atest1;
DROP TABLE atest2;
DROP TABLE atest3;
DROP TABLE atest4;

DROP GROUP regressgroup1;
DROP GROUP regressgroup2;

REVOKE USAGE ON LANGUAGE sql FROM regressuser1;
DROP USER regressuser1;
DROP USER regressuser2;
DROP USER regressuser3;
DROP USER regressuser4;
DROP USER regressuser5;
reset optimizer;


text:
echo "Loading 1-wire kernel modules and listing active devices"
sudo modprobe w1-gpio
sudo modprobe w1-therm

list=`ls /sys/bus/w1/devices`;
if [[ -z $list ]]; then
    echo "no devices";
else
    echo $list;
fi


text:
/*
PSEUDOCODE
An object for th grocery list would make the most sense because it can hold properties
such as quantity.
Array would not be able to do this as intuitively.

DEFINE var 'groceryList'
	SET EQUAL to object
		ADD items into 'groceryList'
			ADD quantity to items

DEFINE function 'add' with two arguments 'item' (string) and 'quantity' (integer)
	ADD new item with quantity to 'groceryList'

DEFINE function 'remove' with one argument 'item' (string)
	REMOVE item from 'groceryList'

DEFINE function 'update' with two arguments 'item' (string) and 'quantity' (integer)
	FIND 'item' in 'groceryList'
		UPDATE with new 'quantity'

DEFINE function 'print'
	PRINT 'groceryList', make look pretty

*/

/* Initial Solution */
// var groceryList = {
// 	'Apples': 8,
// 	'Oranges': 5
// }

// var add = function(item,quantity) {
// 	groceryList[item] = quantity;
// }

// var remove = function(item) {
// 	delete groceryList[item];
// }

// var update = function(item,quantity) {
// 	groceryList[item] = quantity;
// }

// var print = function(list) {
// 	console.log('   GROCERY LIST   ');
// 	console.log('==================')
// 	for (var item in list) {
// 		console.log(item + ': ' + list[item])
// 	}
// 	console.log('==================')
// }

/* Refactored Solution */
var groceryList = {
	'Apples': 8,
	'Oranges': 5
}

var addAndUpdate = function(item,quantity) {
	groceryList[item] = quantity;
}

var remove = function(item) {
	delete groceryList[item];
}

var print = function(list) {
	console.log('   GROCERY LIST   ');
	console.log('==================')
	for (var item in list) {
		console.log(item + ': ' + list[item])
	}
	console.log('==================')
}

/* DRIVER CODE */
addAndUpdate('Grapes',10);
console.log(groceryList);
remove('Apples');
console.log(groceryList);
addAndUpdate('Oranges',999);
console.log(groceryList);
print(groceryList);

/* Reflection */
/*
Q: What concepts did you solidify in working on this challenge?
(reviewing the passing of information, objects, constructors, etc.)
A: More of the 'for...in' loop issues I was having. Not sure why I find this such a
weird concept to wrap my mind around. Also accessing property values in object.

Q: What was the most difficult part of this challenge?
A: Accessing property values in objects took me longer than I'd care to admit.

Q: Did an array or object make more sense to use and why?
A: An object made a lot more sense, although an array would've been easier to access IMO.
An object can hold many properties per a given element such as quantity in this case. An aray
is a list. Although I guess I could've done an array of objects or an array of arrays.
*/


text:
alias g='git'

# Base commands
alias gco='git checkout'
alias gf='git fetch --prune'
alias gm='git merge'
alias gl='git pull'
alias gp='git push'
alias gcp='git cherry-pick'
alias gr='git remote'

# Add
alias ga='git add'
alias gaa='git add --all'
alias gap='git add --patch'

# Branch
alias gb='git branch'
alias gbr='git branch'
alias gba='git branch -a'
#alias gbr='git branch --remote'
alias gc!='git commit -v --amend'

# Commit
alias gc='git commit -v'
alias gci='git commit'
alias gca!='git commit -v -a --amend'
alias gca='git commit -v -a'
alias gcmsg='git commit -m'

# Rebase
alias grb='git rebase'
alias grba='git rebase --abort'
alias grbc='git rebase --continue'
alias grbi='git rebase -i'

# Diff
alias gd='git diff'
alias gdc='git diff --cached'
alias gdt='git diff-tree --no-commit-id --name-only -r'
alias gdt='git difftool'

# Stashing
alias gsta='git stash'
alias gstd='git stash drop'
alias gstp='git stash pop'
alias gsts='git stash show --text'

# Status
alias gst='git status'
alias gss='git status -s'

# Log
alias glg='git log --stat --max-count=10'
alias glgg='git log --graph --max-count=10'
alias glgga='git log --graph --decorate --all'
alias glo='git log --oneline --decorate --color'
alias glog='git log --oneline --decorate --color --graph'
alias gcount='git shortlog -sn'
alias gwc='git whatchanged -p --abbrev-commit --pretty=medium'
alias glol='log --graph --decorate --pretty=oneline --abbrev-commit'
alias glola='log --graph --decorate --pretty=oneline --abbrev-commit --all'

# Cleaning
alias ggc='git gc'

# Other (unsorted)
alias gcl='git config --list'
alias gclean='git reset --hard && git clean -dfx'
alias gcm='git checkout master'
alias glr='git pull --rebase'
alias grh='git reset HEAD'
alias grhh='git reset HEAD --hard'
alias grmv='git remote rename'
alias grrm='git remote remove'
alias grset='git remote set-url'
alias grup='git remote update'
alias grv='git remote -v'
alias gvt='git verify-tag'

# Will cd into the top of the current repository
# or submodule.
alias grt='cd $(git rev-parse --show-toplevel || echo ".")'

# Ignore changes to files (and the opposite)
alias gignore='git update-index --assume-unchanged'
alias gunignore='git update-index --no-assume-unchanged'

# List temporarily ignored files
alias gignored='git ls-files -v | grep "^[[:lower:]]"'


text:
__author__ = 'Tomasz Godzik'

import math
import random

def dist(x1, x2, y1, y2):
    return math.sqrt(
        math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))

#calculate a time cost of a route
def evaluate_route(route, problem, penalty=True, penalty_cost=10000):
    #total distance
    cost = 0
    time = 0
    additional = 0
    current_cargo = problem.capacity
    current_x = problem.depotx
    current_y = problem.depoty
    for i in route:
        #check if we have enough cargo (check if possible - multiple goes?)
        if current_cargo > problem.customers[i].demand:
            #calculate the distance from one customer to another
            time += dist(problem.customers[i].x, current_x, problem.customers[i].y, current_y)
        else:
            # cost of going back to customer
            time += dist(problem.depotx, current_x, problem.depoty, current_y)
            time += dist(problem.customers[i].x, problem.depotx, problem.customers[i].y, problem.depoty)
            current_cargo = problem.capacity

        #drop cargo
        current_cargo -= problem.customers[i].demand

        #change current location
        current_x = problem.customers[i].x
        current_y = problem.customers[i].y

        #if we have to wait

        time = max(problem.customers[i].ready, time)
        #if we are late, add penalty
        additional += max(0, (time - problem.customers[i].due) * penalty_cost)

        #time it takes to drop it
        time += problem.customers[i].service

    time += dist(current_x, problem.depotx, current_y, problem.depoty)
    if penalty:
        return time + additional
    else:
        return time

#calculate the total distance traveled on one route
def total_dist(route, problem):
    #total distance
    cost = 0
    current_cargo = problem.capacity
    current_x = problem.depotx
    current_y = problem.depoty
    for i in route:
        #check if we have enough cargo (check if possible - multiple goes?)
        if current_cargo > problem.customers[i].demand:
            #calculate the distance from one customer to another
            cost += dist(problem.customers[i].x, current_x, problem.customers[i].y, current_y)
        else:
            # cost of going back to customer
            cost += dist(problem.depotx, current_x, problem.depoty, current_y)
            cost += dist(problem.customers[i].x, problem.depotx, problem.customers[i].y, problem.depoty)
            current_cargo = problem.capacity

        #drop cargo
        current_cargo -= problem.customers[i].demand

        #change current location
        current_x = problem.customers[i].x
        current_y = problem.customers[i].y

    cost += dist(current_x, problem.depotx, current_y, problem.depoty)
    return cost

#we calculate the fitness function
def evaluate(problem, ind):
    a = len(ind)
    b = 0
    for i in ind:
        b += evaluate_route(i, problem)
    return b, a

#we calculate the total distance covered
def calculate_dist(problem, ind):
    a = len(ind)
    b = 0
    for i in ind:
        b += total_dist(i, problem)
    return b, a

def mutate_swap(ind):
    route1 = random.randint(0, len(ind) - 1)
    route2 = random.randint(0, len(ind) - 1)

    client1 = random.randint(0, len(ind[route1]) - 1)
    client2 = random.randint(0, len(ind[route2]) - 1)

    tmp = ind[route1][client1]
    ind[route1][client1] = ind[route2][client2]
    ind[route2][client2] = tmp

    return ind,

def mutate_inverse(ind):
    which = random.randint(0, len(ind) - 1)
    ind[which] = ind[which][::-1]
    return ind,

def mutate_insert(ind, max_vehicles):
    route = random.randint(0, len(ind) - 1)
    client = random.randint(0, len(ind[route]) - 1)
    found = ind[route][client]

    if random.random() < (1.0 / (2.0 * len(ind))) and len(ind) < max_vehicles:
        ind.append([found])
    else:
        new_route = random.randint(0, len(ind) - 1)
        place = random.randint(0, len(ind[new_route]))
        ind[new_route].insert(place, found)

    ind[route].remove(found)

    if len(ind[route]) == 0:
        ind.remove(ind[route])

    return ind,

def mutate_displace(ind, max_vehicles):
    route = random.randint(0, len(ind) - 1)
    rfrom = random.randint(0, len(ind[route]) - 1)
    rto = random.randint(rfrom + 1, len(ind[route]))
    subroute = ind[route][rfrom:rto]
    ind[route] = ind[route][0:rfrom] + (ind[route][rto:len(ind[route])])

    if random.random() < (1.0 / (2.0 * len(ind))) and len(ind) < max_vehicles:
        ind.append(subroute)
    else:
        new_route = random.randint(0, len(ind) - 1)
        place = random.randint(0, len(ind[new_route]))
        ind[new_route] = ind[new_route][0:place] + subroute + ind[new_route][place:len(ind[new_route])]

    if len(ind[route]) == 0:
        ind.remove(ind[route])
    return ind,

def mutate(max_v, ind, swap_rate=0.1, inverse_rate=0.5, insert_rate=0.1, displace_rate=0.15):
    if random.random() <= swap_rate:
        ind, = mutate_swap(ind)
    if random.random() <= inverse_rate:
        ind, = mutate_inverse(ind)
    if random.random() <= insert_rate:
        ind, = mutate_insert(ind, max_v)
    if random.random() <= displace_rate:
        ind, = mutate_displace(ind, max_v)
    return ind,

# czy to dobrze dziala
def cross_over(problem, ind1, ind2):
    route = random.randint(0, len(ind1) - 1)
    rfrom = random.randint(0, len(ind1[route]) - 1)
    rto = random.randint(rfrom + 1, len(ind1[route]))
    subroute = ind1[route][rfrom:rto]
    whereto = (0, 0)
    min_dist = dist(problem.customers[ind2[0][0]].x, problem.customers[subroute[0]].x, problem.customers[ind2[0][0]].y,
                    problem.customers[subroute[0]].y)
    for i in ind2:
        for j in i:
            if j in subroute:
                i.remove(j)
            else:
                tmp_dist = dist(problem.customers[j].x, problem.customers[subroute[0]].x, problem.customers[j].y,
                                problem.customers[subroute[0]].y)
                if tmp_dist < min_dist:
                    min_dist = tmp_dist
                    whereto = (ind2.index(i), i.index(j))
        if len(i) == 0:
            ind2.remove(i)

    ind2[whereto[0]] = ind2[whereto[0]][0:whereto[1]] + subroute + ind2[whereto[0]][whereto[1]:len(ind2[whereto[0]])]
    return ind1, ind2

#function to tell apart 2 solutions
def pareto_similar(ind1, ind2):
    for i in ind1:
        if ind2.count(i) == 0:
            return False
    return True


text:
require 'spec_helper'

module AlchemyCrm
  describe ContactsController do

    before(:all) do
      Alchemy::PageLayout.add([
        {"name" => 'newsletter_signup', "elements" => ['newsletter_signup_form'], "autogenerate" => ["newsletter_signup_form"]},
        {"name" => 'newsletter_signout', "elements" => ['newsletter_signout_form'], "autogenerate" => ["newsletter_signout_form"]},
        {"name" => 'newsletter_mails', "elements" => ['newsletter_signup_mail', 'newsletter_signout_mail'], "autogenerate" => ["newsletter_signup_mail", "newsletter_signout_mail"]}
      ])
      @language_root = Alchemy::Page.create!(:name => 'Language Root', :page_layout => 'standard', :parent_id => Alchemy::Page.root.id, :language => Alchemy::Language.get_default)
      @signup_page = Alchemy::Page.create!(:name => 'Newsletter Signup', :page_layout => 'newsletter_signup', :parent_id => @language_root.id, :language => @language_root.language, :public => true)
      @signout_page = Alchemy::Page.create!(:name => 'Newsletter Signout', :page_layout => 'newsletter_signout', :parent_id => @language_root.id, :language => @language_root.language, :public => true)
      @mail_page = Alchemy::Page.create!(:name => 'Newsletter Mails', :page_layout => 'newsletter_mails', :parent_id => @language_root.id, :language => @language_root.language)
      @contact_params = {:email => 'jon@doe.com', :firstname => 'Jon', :lastname => 'Doe', :salutation => 'mr'}
      @newsletter = Newsletter.create!(:name => 'Newsletter', :layout => 'standard')
    end

    describe '#signup' do

      before(:each) do
        post :signup, {:contact => @contact_params, :use_route => :alchemy_crm}
      end

      it "should create the contact from params." do
        Contact.find_by_email('jon@doe.com').should_not be_nil
      end

      it "should deliver the signup mail." do
        ActionMailer::Base.deliveries.collect(&:subject).should include("Signup mail")
      end

    end

    describe '#verify' do

      before(:all) do
        @contact = Contact.create!({:email => 'jon@doe.com', :firstname => 'Jon', :lastname => 'Doe', :salutation => 'mr'})
      end

      context "receiving hash from existing contact" do

        render_views

        before(:each) do
          @element = @signup_page.elements.find_by_name(:newsletter_signup_form)
          @element.content_by_name('verified_text').essence.update_attribute(:body, 'you are now verified')
          post :verify, {:token => @contact.email_sha1, :use_route => :alchemy_crm}
        end

        it "should verify the contact." do
          @contact.reload
          @contact.verified.should be(true)
        end

        it "should display custom 'verified' text." do
          verified_text = Regexp.new(Regexp.escape(@element.ingredient('verified_text')))
          response.body.should match(verified_text)
        end

      end

      context "receiving hash from existing contact and newsletter ids" do

        before(:each) do
          @subscription = Subscription.create!(:contact => @contact, :newsletter => @newsletter)
          @newsletter_ids = @contact.subscriptions.collect(&:newsletter_id)
          post :verify, {:token => @contact.email_sha1, :newsletter_ids => @newsletter_ids, :use_route => :alchemy_crm}
        end

        it "should verify all subscriptions from contact." do
          @contact.subscriptions.where(:verified => true).collect(&:newsletter_id).should == @newsletter_ids
        end

      end

      context "receiving hash from not existing contact" do

        it "should raise routing error." do
          lambda {
            post :verify, {:token => 'f4k3h4ckh4sh', :use_route => :alchemy_crm}
          }.should raise_error(ActionController::RoutingError)
        end

      end

      context "not receiving any newsletter_ids" do

        before(:each) do
          @subscription = Subscription.create!(:contact => @contact, :newsletter => @newsletter)
          post :verify, {:token => @contact.email_sha1, :use_route => :alchemy_crm}
        end

        it "should verify all subscriptions from contact." do
          @contact.subscriptions.where(:verified => true).count.should == @contact.subscriptions.count
        end

      end

      after(:all) do
        @contact.destroy
      end

    end

    describe '#signout' do

      context "receiving an unknown email" do

        it "should display error notice." do
          post :signout, {:email => 'not@know.com', :use_route => :alchemy_crm}
          flash[:notice].should match(I18n.t(:contact_unknown, scope: 'alchemy_crm'))
        end

      end

      context "receiving an email for verified contact" do

        before(:each) do
          @contact = Contact.create!({:email => 'jon@doe.com', :firstname => 'Jon', :lastname => 'Doe', :salutation => 'mr', :verified => true})
        end

        it "should deliver signout mail." do
          post :signout, {:email => 'jon@doe.com', :use_route => :alchemy_crm}
          ActionMailer::Base.deliveries.collect(&:subject).should include("Signout mail")
        end

      end

      context "receiving an email for known, but not verified contact" do

        before(:each) do
          @contact = Contact.create!({:email => 'jon@doe.com', :firstname => 'Jon', :lastname => 'Doe', :salutation => 'mr'})
        end

        it "should display error notice." do
          post :signout, {:email => @contact.email, :use_route => :alchemy_crm}
          flash[:notice].should match(I18n.t(:contact_unknown, scope: 'alchemy_crm'))
        end

      end

    end

    describe '#disable' do

      before(:all) do
        @contact = Contact.create!({:email => 'jon@doe.com', :firstname => 'Jon', :lastname => 'Doe', :salutation => 'mr', :verified => true})
      end

      context "receiving hash from existing contact" do

        render_views

        before(:each) do
          @element = @signout_page.elements.find_by_name(:newsletter_signout_form)
          @element.content_by_name('disabled_text').essence.update_attribute(:body, 'you are now disabled')
          post :disable, {:token => @contact.email_sha1, :use_route => :alchemy_crm}
        end

        it "should disable the contact." do
          @contact.reload
          @contact.disabled.should be(true)
          @contact.verified.should be(false)
        end

        it "should display custom 'disabled' text." do
          disabled_text = Regexp.new(Regexp.escape(@element.ingredient('disabled_text')))
          response.body.should match(disabled_text)
        end

      end

      context "receiving hash from existing contact" do

        before(:each) do
          @subscription = Subscription.create!(:contact => @contact, :newsletter => @newsletter)
          post :disable, {:token => @contact.email_sha1, :use_route => :alchemy_crm}
        end

        it "should delete all subscriptions from contact." do
          @contact.subscriptions.should be_empty
        end

      end

      context "receiving hash from not existing contact" do

        it "should raise routing error." do
          lambda {
            post :disable, {:token => 'f4k3h4ckh4sh', :use_route => :alchemy_crm}
          }.should raise_error(ActionController::RoutingError)
        end

      end

      after(:all) do
        @contact.destroy
      end

    end

    after(:all) do
      @language_root.destroy
      Contact.destroy_all
    end

  end
end


text:
python jsonrpc.py 4448 ffff.pipelinelist
python jsonrpc.py 4448 ffff.pipelinelist "{\"enabled\":1}"


text:
'use strict';

const models = require('./index');

/**
 * Class representing a ServiceBusMessage.
 */
class ServiceBusMessage {
  /**
   * Create a ServiceBusMessage.
   * @member {object} [authentication] Gets or sets the Service Bus
   * authentication.
   * @member {string} [authentication.sasKey] Gets or sets the SAS key.
   * @member {string} [authentication.sasKeyName] Gets or sets the SAS key
   * name.
   * @member {string} [authentication.type] Gets or sets the authentication
   * type. Possible values include: 'NotSpecified', 'SharedAccessKey'
   * @member {object} [brokeredMessageProperties] Gets or sets the brokered
   * message properties.
   * @member {string} [brokeredMessageProperties.contentType] Gets or sets the
   * content type.
   * @member {string} [brokeredMessageProperties.correlationId] Gets or sets
   * the correlation ID.
   * @member {boolean} [brokeredMessageProperties.forcePersistence] Gets or
   * sets the force persistence.
   * @member {string} [brokeredMessageProperties.label] Gets or sets the label.
   * @member {string} [brokeredMessageProperties.messageId] Gets or sets the
   * message ID.
   * @member {string} [brokeredMessageProperties.partitionKey] Gets or sets the
   * partition key.
   * @member {string} [brokeredMessageProperties.replyTo] Gets or sets the
   * reply to.
   * @member {string} [brokeredMessageProperties.replyToSessionId] Gets or sets
   * the reply to session ID.
   * @member {date} [brokeredMessageProperties.scheduledEnqueueTimeUtc] Gets or
   * sets the scheduled enqueue time UTC.
   * @member {string} [brokeredMessageProperties.sessionId] Gets or sets the
   * session ID.
   * @member {moment.duration} [brokeredMessageProperties.timeToLive] Gets or
   * sets the time to live.
   * @member {string} [brokeredMessageProperties.to] Gets or sets the to.
   * @member {string} [brokeredMessageProperties.viaPartitionKey] Gets or sets
   * the via partition key.
   * @member {object} [customMessageProperties] Gets or sets the custom message
   * properties.
   * @member {string} [message] Gets or sets the message.
   * @member {string} [namespace] Gets or sets the namespace.
   * @member {string} [transportType] Gets or sets the transport type. Possible
   * values include: 'NotSpecified', 'NetMessaging', 'AMQP'
   */
  constructor() {
  }

  /**
   * Defines the metadata of ServiceBusMessage
   *
   * @returns {object} metadata of ServiceBusMessage
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ServiceBusMessage',
      type: {
        name: 'Composite',
        className: 'ServiceBusMessage',
        modelProperties: {
          authentication: {
            required: false,
            serializedName: 'authentication',
            type: {
              name: 'Composite',
              className: 'ServiceBusAuthentication'
            }
          },
          brokeredMessageProperties: {
            required: false,
            serializedName: 'brokeredMessageProperties',
            type: {
              name: 'Composite',
              className: 'ServiceBusBrokeredMessageProperties'
            }
          },
          customMessageProperties: {
            required: false,
            serializedName: 'customMessageProperties',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          message: {
            required: false,
            serializedName: 'message',
            type: {
              name: 'String'
            }
          },
          namespace: {
            required: false,
            serializedName: 'namespace',
            type: {
              name: 'String'
            }
          },
          transportType: {
            required: false,
            serializedName: 'transportType',
            type: {
              name: 'Enum',
              allowedValues: [ 'NotSpecified', 'NetMessaging', 'AMQP' ]
            }
          }
        }
      }
    };
  }
}

module.exports = ServiceBusMessage;


text:
import test from 'ava';

test('it should work', t => {
  t.true(true);
});


text:
Linear Algebra Functions
========================

Provides Vector operations, Equation (Line) operations and functions to work with Systems of equations to produce Triangular Form, Reduced Row-Echelon Form and carry out Gaussian elimination.

Written to complete the Udacity Linear Algebra course at https://www.udacity.com/course/linear-algebra-refresher-course--ud953

See `cmd/main.go` for how the quizes are completed.

Examples
========

```go
result, err := linear.NewVector(8.218, -9.341).Add(linear.NewVector(-1.129, 2.111))
angle, err := linear.NewVector(3.183, -7.627).AngleBetween(linear.NewVector(-2.668, 5.319))
```

```go
line1 := linear.NewEquation(linear.NewVector(7.204, 3.182), 8.68) // 7.204x + 3.182y = 8.68
line2 := linear.NewEquation(linear.NewVector(8.172, 4.114), 9.883)
intersection, intersects, equal, err := line1.IntersectionWith(line2)
```


text:
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.RecoveryServices;
    using Microsoft.Azure.Management.RecoveryServices.SiteRecovery;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Protection container mapping object.
    /// </summary>
    public partial class ProtectionContainerMapping : Resource
    {
        /// <summary>
        /// Initializes a new instance of the ProtectionContainerMapping class.
        /// </summary>
        public ProtectionContainerMapping()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ProtectionContainerMapping class.
        /// </summary>
        /// <param name="id">Resource Id</param>
        /// <param name="name">Resource Name</param>
        /// <param name="type">Resource Type</param>
        /// <param name="location">Resource Location</param>
        /// <param name="properties">The custom data.</param>
        public ProtectionContainerMapping(string id = default(string), string name = default(string), string type = default(string), string location = default(string), ProtectionContainerMappingProperties properties = default(ProtectionContainerMappingProperties))
            : base(id, name, type, location)
        {
            Properties = properties;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the custom data.
        /// </summary>
        [JsonProperty(PropertyName = "properties")]
        public ProtectionContainerMappingProperties Properties { get; set; }

    }
}


text:
package com.ltsllc.miranda.timer.messages;

import com.ltsllc.miranda.Message;
import com.ltsllc.miranda.timer.messages.ScheduleMessage;

import java.util.concurrent.BlockingQueue;

/**
 * Created by Clark on 2/19/2017.
 */
public class SchedulePeriodicMessage extends ScheduleMessage {
    private long period;
    private long delay;

    public void setPeriod(long period) {
        this.period = period;
    }

    public long getDelay() {
        return delay;
    }

    public void setDelay(long delay) {
        this.delay = delay;
    }

    public SchedulePeriodicMessage(BlockingQueue<Message> senderQueue, Object sender, long delay,
                                   long period, Message message, BlockingQueue<Message> receiver) {
        super(Subjects.SchedulePeriodic, senderQueue, sender, receiver, message);

        setPeriod(period);
        setDelay(delay);
    }

    public long getPeriod() {
        return period;
    }
}


text:
This module will provide a restful service endpoint to the serialservo module.

## Install

```bash
npm install serialservo-server
```

## Typical Usage

Just add the following and run it.

```javascript
var SerialServoServer = require("serialservo-server");
var sscServer = new SerialServoServer();
sscServer.run();
```

Alternately you can work with options to override defaults.

```javascript
var SerialServoServer = require("serialservo-server");
var configOptions = {
                        httpPort: 9090,
                        loggingEnabled: false,
                        portName: '/dev/ttyUSB1',
                        serialPortOptions: {
                            baudRate: 9600
                        },
                        staticDir: 'somedirector',
                        httpPort: 3000
                    };
var sscServer = new SerialServoServer(configOptions);
sscServer.run();
```

For more information on the serial servo controller review the documentation on the module 'serialservo'.

## License

The MIT License (MIT)

Copyright (c) 2016 Scott Preston

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
var fs            = require('fs'),
    path          = require('path'),
    et            = require('elementtree'),
    util          = require('../util'),
    events        = require('../events'),
    shell         = require('shelljs'),
    child_process = require('child_process'),
    Q             = require('q'),
    ConfigParser  = require('../ConfigParser'),
    CordovaError  = require('../../CordovaError'),
    xml           = require('../../util/xml-helpers'),
    config        = require('../config'),
    hooker        = require('../hooker');

module.exports = function wp8_parser(project) {
    try {
        // TODO : Check that it's not a wp8 project?
        var csproj_file   = fs.readdirSync(project).filter(function(e) { return e.match(/\.csproj$/i); })[0];
        if (!csproj_file) throw new CordovaError('No .csproj file in "'+project+'"');
        this.wp8_proj_dir = project;
        this.csproj_path  = path.join(this.wp8_proj_dir, csproj_file);
        this.sln_path     = path.join(this.wp8_proj_dir, csproj_file.replace(/\.csproj/, '.sln'));
    } catch(e) {
        throw new CordovaError('The provided path "' + project + '" is not a Windows Phone 8 project. ' + e);
    }
    this.manifest_path  = path.join(this.wp8_proj_dir, 'Properties', 'WMAppManifest.xml');
};

// Returns a promise.
module.exports.check_requirements = function(project_root) {
    events.emit('log', 'Checking wp8 requirements...');
    var lib_path = util.getDefaultPlatformLibPath(project_root, 'wp8');
    var custom_path = config.has_custom_path(project_root, 'wp8');
    if (custom_path) {
        lib_path = path.join(custom_path, 'wp8');
    }
    var command = '"' + path.join(lib_path, 'bin', 'check_reqs') + '"';
    events.emit('verbose', 'Running "' + command + '" (output to follow)');
    var d = Q.defer();
    child_process.exec(command, function(err, output, stderr) {
        events.emit('verbose', output);
        if (err) {
            d.reject(new CordovaError('Requirements check failed: ' + output + stderr));
        } else {
            d.resolve();
        }
    });
    return d.promise;
};

module.exports.prototype = {
    update_from_config:function(config) {
        //check config parser
        if (config instanceof ConfigParser) {
        } else throw new Error('update_from_config requires a ConfigParser object');

        //Get manifest file
        var manifest = xml.parseElementtreeSync(this.manifest_path);

        //Update app version
        var version = config.version();
        manifest.find('.//App').attrib.Version = version;

        // Update app name by editing app title in Properties\WMAppManifest.xml
        var name = config.name();
        var prev_name = manifest.find('.//App[@Title]')['attrib']['Title'];
        if(prev_name != name) {
            //console.log("Updating app name from " + prev_name + " to " + name);
            manifest.find('.//App').attrib.Title = name;
            manifest.find('.//App').attrib.Publisher = name + " Publisher";
            manifest.find('.//App').attrib.Author = name + " Author";
            manifest.find('.//PrimaryToken').attrib.TokenID = name;
            //update name of sln and csproj.
            name = name.replace(/(\.\s|\s\.|\s+|\.+)/g, '_'); //make it a ligitamate name
            prev_name = prev_name.replace(/(\.\s|\s\.|\s+|\.+)/g, '_');
            // TODO: might return .sln.user? (generated file)
            var sln_name = fs.readdirSync(this.wp8_proj_dir).filter(function(e) { return e.match(/\.sln$/i); })[0];
            var sln_path = path.join(this.wp8_proj_dir, sln_name);
            var sln_file = fs.readFileSync(sln_path, 'utf-8');
            var name_regex = new RegExp(prev_name, "g");
            fs.writeFileSync(sln_path, sln_file.replace(name_regex, name), 'utf-8');
            shell.mv('-f', this.csproj_path, path.join(this.wp8_proj_dir, name + '.csproj'));
            this.csproj_path = path.join(this.wp8_proj_dir, name + '.csproj');
            shell.mv('-f', sln_path, path.join(this.wp8_proj_dir, name + '.sln'));
            this.sln_path    = path.join(this.wp8_proj_dir, name + '.sln');
        }

        // Update package name by changing:
        /*  - CordovaAppProj.csproj
         *  - MainPage.xaml
         *  - MainPage.xaml.cs
         *  - App.xaml
         *  - App.xaml.cs
         */
         var pkg = config.packageName();
         var csproj = xml.parseElementtreeSync(this.csproj_path);
         prev_name = csproj.find('.//RootNamespace').text;
         if(prev_name != pkg) {
            //console.log("Updating package name from " + prev_name + " to " + pkg);
            //CordovaAppProj.csproj
            csproj.find('.//RootNamespace').text = pkg;
            csproj.find('.//AssemblyName').text = pkg;
            csproj.find('.//XapFilename').text = pkg + '.xap';
            csproj.find('.//SilverlightAppEntry').text = pkg + '.App';
            fs.writeFileSync(this.csproj_path, csproj.write({indent: 4}), 'utf-8');
            //MainPage.xaml
            var mainPageXAML = xml.parseElementtreeSync(path.join(this.wp8_proj_dir, 'MainPage.xaml'));
            mainPageXAML.getroot().attrib['x:Class'] = pkg + '.MainPage';
            fs.writeFileSync(path.join(this.wp8_proj_dir, 'MainPage.xaml'), mainPageXAML.write({indent: 4}), 'utf-8');
            //MainPage.xaml.cs
            var mainPageCS = fs.readFileSync(path.join(this.wp8_proj_dir, 'MainPage.xaml.cs'), 'utf-8');
            var namespaceRegEx = new RegExp('namespace ' + prev_name);
            fs.writeFileSync(path.join(this.wp8_proj_dir, 'MainPage.xaml.cs'), mainPageCS.replace(namespaceRegEx, 'namespace ' + pkg), 'utf-8');
            //App.xaml
            var appXAML = xml.parseElementtreeSync(path.join(this.wp8_proj_dir, 'App.xaml'));
            appXAML.getroot().attrib['x:Class'] = pkg + '.App';
            fs.writeFileSync(path.join(this.wp8_proj_dir, 'App.xaml'), appXAML.write({indent: 4}), 'utf-8');
            //App.xaml.cs
            var appCS = fs.readFileSync(path.join(this.wp8_proj_dir, 'App.xaml.cs'), 'utf-8');
            fs.writeFileSync(path.join(this.wp8_proj_dir, 'App.xaml.cs'), appCS.replace(namespaceRegEx, 'namespace ' + pkg), 'utf-8');
         }

         //Write out manifest
         fs.writeFileSync(this.manifest_path, manifest.write({indent: 4}), 'utf-8');

        // Update icons
        var icons = config.getIcons('wp8');
        var platformRoot = this.wp8_proj_dir;
        var appRoot = util.isCordova(platformRoot);

        // icons, that should be added to platform
        // @param dest {string} Path to copy icon to, relative to platform root
        var platformIcons = [
            {dest: "ApplicationIcon.png", width: 99, height: 99},
            {dest: "Background.png", width: 159, height: 159},
        ];

        platformIcons.forEach(function (item) {
            icon = icons.getIconBySize(item.width, item.height) || icons.getDefault();
            if (icon){
                var src = path.join(appRoot, icon.src),
                    dest = path.join(platformRoot, item.dest);
                events.emit('verbose', 'Copying icon from ' + src + ' to ' + dest);
                shell.cp('-f', src, dest);
            }
        });

    },
    // Returns the platform-specific www directory.
    www_dir:function() {
        var defaultAppId = util.getDefaultAppId(this.wp8_proj_dir);
        return path.join(this.wp8_proj_dir, 'xface3', defaultAppId);
    },
    config_xml:function() {
        return path.join(this.wp8_proj_dir, 'config.xml');
    },
    // copy files from merges directory to actual www dir
    copy_merges:function(merges_sub_path) {
        var merges_path = path.join(util.appDir(util.isCordova(this.wp8_proj_dir)), 'merges', merges_sub_path);
        if (fs.existsSync(merges_path)) {
            var overrides = path.join(merges_path, '*');
            shell.cp('-rf', overrides, this.www_dir());
        }
    },

    // Used for creating platform_www in projects created by older versions.
    cordovajs_path:function(libDir) {
        var jsPath = path.join(libDir, 'xFaceLib', 'xFaceLib', 'xface.js');
        return path.resolve(jsPath);
    },

    // Replace the www dir with contents of platform_www and app www and updates the csproj file.
    update_www:function() {
        var projectRoot = util.isCordova(this.wp8_proj_dir);
        var app_www = util.projectWww(projectRoot);
        var platform_www = path.join(this.wp8_proj_dir, 'platform_www');
        var xface3_dir = path.join(this.wp8_proj_dir, 'xface3');

        // Clear the www dir
        shell.rm('-rf', xface3_dir);
        shell.mkdir(xface3_dir);
        // Copy over all app www assets
        shell.cp('-rf', path.join(app_www, '*'), xface3_dir);

        // Copy all files from merges directories - wp generic first, then wp8 specific.
        this.copy_merges('wp');
        this.copy_merges('wp8');

        // Copy over stock platform www assets (xface.js)
        var appIds = require('../../plugman/util/multiapp-helpers').getInstalledApps(this.wp8_proj_dir, 'wp8');
        var xface3Dir = path.dirname(this.www_dir());
        appIds.forEach(function(id) {
            var appPath = path.join(xface3Dir, id);
            shell.cp('-rf', path.join(platform_www, '*'), appPath);
        });
    },

    // calls the nessesary functions to update the wp8 project
    // Returns a promise.
    update_project:function(cfg) {
        try {
            this.update_from_config(cfg);
        } catch(e) {
            return Q.reject(e);
        }

        // trigger an event in case anyone needs to modify the contents of the www folder before we package it.
        var that = this;
        var projectRoot = util.isCordova(process.cwd());

        var hooks = new hooker(projectRoot);
        return hooks.fire('pre_package', { wwwPath:this.www_dir(), platforms: ['wp8']  })
        .then(function() {
            util.deleteSvnFolders(that.www_dir());
        });
    }
};


text:
#include <aws/network-firewall/NetworkFirewallRequest.h>

namespace Aws
{
namespace NetworkFirewall
{
} // namespace NetworkFirewall
} // namespace Aws


text:
module NavigationHelpers
  # Maps a name to a path. Used by the
  #
  #   When /^I go to (.+)$/ do |page_name|
  #
  # step definition in web_steps.rb
  #
  def path_to(page_name)
    case page_name

    when /the home\s?page/
      '/'

    when /the users page/
      users_path

    when /the user page for "([^"]+)"/
      user_path(User.find_by_login($1))

    when /the login page/
      login_path

    when /my profile/
      user_path(User.last)

    # Add more mappings here.
    # Here is an example that pulls values out of the Regexp:
    #
    #   when /^(.*)'s profile page$/i
    #     user_profile_path(User.find_by_login($1))

    else
      raise "Can't find mapping from \"#{page_name}\" to a path.\n" +
        "Now, go and add a mapping in #{__FILE__}"
    end
  end
end

World(NavigationHelpers)


text:
.. azkaban documentation master file, created by
   sphinx-quickstart on Thu Mar  6 16:04:56 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

AzkabanCLI
==========

A lightweight Azkaban_ client providing:

* A command line interface to run jobs, upload projects, and more.

  .. code-block:: bash

    $ azkaban --project=my_project upload archive.zip
    Project my_project successfully uploaded (id: 1, size: 205kB, version: 1).
    Details at https://azkaban.server.url/manager?project=my_project

    $ azkaban --project=my_project run my_flow
    Flow my_flow successfully submitted (execution id: 48).
    Details at https://azkaban.server.url/executor?execid=48

* A convenient and extensible way to build project configuration files.

  .. code-block:: python

    from azkaban import PigJob, Project
    from getpass import getuser

    PROJECT = Project('sample', root=__file__)

    # default options for all jobs
    DEFAULTS = {
      'user.to.proxy': getuser(),
      'param': {
        'input_root': 'sample_dir/',
        'n_reducers': 20,
      },
      'jvm.args.mapred': {
        'max.split.size': 2684354560,
        'min.split.size': 2684354560,
      },
    }

    # list of pig job options
    OPTIONS = [
      {'pig.script': 'first.pig'},
      {'pig.script': 'second.pig', 'dependencies': 'first.pig'},
      {'pig.script': 'third.pig', 'param': {'foo': 48}},
      {'pig.script': 'fourth.pig', 'dependencies': 'second.pig,third.pig'},
    ]

    for option in OPTIONS:
      PROJECT.add_job(option['pig.script'], PigJob(DEFAULTS, option))

Table of contents
-----------------

.. toctree::
  :maxdepth: 2

  quickstart
  api
  extensions

Indices and tables
------------------

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

.. _Azkaban: http://data.linkedin.com/opensource/azkaban


text:
<?php
namespace TYPO3\CMS\Core\Log;

/**
 * Global LogManager that keeps track of global logging information.
 *
 * Inspired by java.util.logging
 */
class LogManager implements \TYPO3\CMS\Core\SingletonInterface, LogManagerInterface
{
    /**
     * @var string
     */
    const CONFIGURATION_TYPE_WRITER = 'writer';

    /**
     * @var string
     */
    const CONFIGURATION_TYPE_PROCESSOR = 'processor';

    /**
     * Loggers to retrieve them for repeated use.
     *
     * @var array
     */
    protected $loggers = [];

    /**
     * Default / global / root logger.
     *
     * @var \TYPO3\CMS\Core\Log\Logger
     */
    protected $rootLogger = null;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->rootLogger = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(Logger::class, '');
        $this->loggers[''] = $this->rootLogger;
    }

    /**
     * For use in unit test context only. Resets the internal logger registry.
     *
     * @return void
     */
    public function reset()
    {
        $this->loggers = [];
    }

    /**
     * Gets a logger instance for the given name.
     *
     * \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Log\LogManager::class)->getLogger('main.sub.subsub');
     *
     * $name can also be submitted as a underscore-separated string, which will
     * be converted to dots. This is useful to call this method with __CLASS__
     * as parameter.
     *
     * @param string $name Logger name, empty to get the global "root" logger.
     * @return \TYPO3\CMS\Core\Log\Logger Logger with name $name
     */
    public function getLogger($name = '')
    {
        /** @var $logger \TYPO3\CMS\Core\Log\Logger */
        $logger = null;
        // Transform namespaces and underscore class names to the dot-name style
        $separators = ['_', '\\'];
        $name = str_replace($separators, '.', $name);
        if (isset($this->loggers[$name])) {
            $logger = $this->loggers[$name];
        } else {
            // Lazy instantiation
            /** @var $logger \TYPO3\CMS\Core\Log\Logger */
            $logger = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(Logger::class, $name);
            $this->loggers[$name] = $logger;
            $this->setWritersForLogger($logger);
            $this->setProcessorsForLogger($logger);
        }
        return $logger;
    }

    /**
     * For use in unit test context only.
     *
     * @param string $name
     * @return void
     */
    public function registerLogger($name)
    {
        $this->loggers[$name] = null;
    }

    /**
     * For use in unit test context only.
     *
     * @return array
     */
    public function getLoggerNames()
    {
        return array_keys($this->loggers);
    }

    /**
     * Appends the writers to the given logger as configured.
     *
     * @param \TYPO3\CMS\Core\Log\Logger $logger Logger to configure
     * @return void
     */
    protected function setWritersForLogger(Logger $logger)
    {
        $configuration = $this->getConfigurationForLogger(self::CONFIGURATION_TYPE_WRITER, $logger->getName());
        foreach ($configuration as $severityLevel => $writer) {
            foreach ($writer as $logWriterClassName => $logWriterOptions) {
                /** @var $logWriter \TYPO3\CMS\Core\Log\Writer\WriterInterface */
                $logWriter = null;
                try {
                    $logWriter = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($logWriterClassName, $logWriterOptions);
                    $logger->addWriter($severityLevel, $logWriter);
                } catch (\Psr\Log\InvalidArgumentException $e) {
                    $logger->warning('Instantiation of LogWriter "' . $logWriterClassName . '" failed for logger ' . $logger->getName() . ' (' . $e->getMessage() . ')');
                } catch (\TYPO3\CMS\Core\Log\Exception\InvalidLogWriterConfigurationException $e) {
                    $logger->warning('Instantiation of LogWriter "' . $logWriterClassName . '" failed for logger ' . $logger->getName() . ' (' . $e->getMessage() . ')');
                }
            }
        }
    }

    /**
     * Appends the processors to the given logger as configured.
     *
     * @param \TYPO3\CMS\Core\Log\Logger $logger Logger to configure
     * @return void
     */
    protected function setProcessorsForLogger(Logger $logger)
    {
        $configuration = $this->getConfigurationForLogger(self::CONFIGURATION_TYPE_PROCESSOR, $logger->getName());
        foreach ($configuration as $severityLevel => $processor) {
            foreach ($processor as $logProcessorClassName => $logProcessorOptions) {
                /** @var $logProcessor \TYPO3\CMS\Core\Log\Processor\ProcessorInterface */
                $logProcessor = null;
                try {
                    $logProcessor = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($logProcessorClassName, $logProcessorOptions);
                    $logger->addProcessor($severityLevel, $logProcessor);
                } catch (\Psr\Log\InvalidArgumentException $e) {
                    $logger->warning('Instantiation of LogProcessor "' . $logProcessorClassName . '" failed for logger ' . $logger->getName() . ' (' . $e->getMessage() . ')');
                } catch (\TYPO3\CMS\Core\Log\Exception\InvalidLogProcessorConfigurationException $e) {
                    $logger->warning('Instantiation of LogProcessor "' . $logProcessorClassName . '" failed for logger ' . $logger->getName() . ' (' . $e->getMessage() . ')');
                }
            }
        }
    }

    /**
     * Returns the configuration from $TYPO3_CONF_VARS['LOG'] as
     * hierarchical array for different components of the class hierarchy.
     *
     * @param string $configurationType Type of config to return (writer, processor)
     * @param string $loggerName Logger name
     * @throws \Psr\Log\InvalidArgumentException
     * @return array
     */
    protected function getConfigurationForLogger($configurationType, $loggerName)
    {
        // Split up the logger name (dot-separated) into its parts
        $explodedName = explode('.', $loggerName);
        // Search in the $TYPO3_CONF_VARS['LOG'] array
        // for these keys, for example "writerConfiguration"
        $configurationKey = $configurationType . 'Configuration';
        $configuration = $GLOBALS['TYPO3_CONF_VARS']['LOG'];
        $result = $configuration[$configurationKey] ?: [];
        // Walk from general to special (t3lib, t3lib.db, t3lib.db.foo)
        // and search for the most specific configuration
        foreach ($explodedName as $partOfClassName) {
            if (!empty($configuration[$partOfClassName][$configurationKey])) {
                $result = $configuration[$partOfClassName][$configurationKey];
            }
            $configuration = $configuration[$partOfClassName];
        }
        // Validate the config
        foreach ($result as $level => $unused) {
            try {
                LogLevel::validateLevel($level);
            } catch (\Psr\Log\InvalidArgumentException $e) {
                throw new \Psr\Log\InvalidArgumentException('The given severity level "' . htmlspecialchars($level) . '" for ' . $configurationKey . ' of logger "' . $loggerName . '" is not valid.', 1326406447);
            }
        }
        return $result;
    }
}


text:
<!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

     https://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.
-->
<project name="eclipse-plugin-build" xmlns:ivy="ivy">

    <!-- Load Ivy Ant tasks -->
    <taskdef uri="ivy" resource="org/apache/ivy/ant/antlib.xml"/>
    <!-- If Ivy is not in Ant's classpath, get the jar of Ivy and use the following -->
    <!-- taskdef rather than the above one -->
    <!--path id="ivy.classpath">
        <fileset dir="${basedir}">
            <include name="ivy.jar"/>
        </fileset>
    </path>
    <taskdef uri="ivy" resource="org/apache/ivy/ant/antlib.xml" classpathref="ivy.classpath" /-->

    <!-- Load the properties where is defined the eclipse home -->
    <property file="${basedir}/ivysettings.properties"/>

    <target name="clean" description="Clean the build directory">
        <delete dir="${basedir}/target"/>
    </target>

    <target name="buildobr" description="Build the obr index">
        <!-- build the repo.xml which aggregate every metadata of the Eclipse plugins -->
        <mkdir dir="${basedir}/target"/>
        <ivy:buildobr baseDir="${eclipse.home}" basePath="${eclipse.home}" out="${basedir}/target/repo-eclipse.xml" indent="true"/>
    </target>

    <target name="ivy:configure">
        <!-- classical ivy configuration -->
        <ivy:configure file="ivysettings.xml"/>
    </target>

    <target name="ivy:resolve" depends="ivy:configure">
        <!-- classical resolve and cache-path -->
        <ivy:resolve file="ivy.xml" conf="*"/>
        <ivy:cachepath pathid="compile.classpath" conf="compile" useOrigin="true"/>
    </target>

    <target name="compile" depends="ivy:resolve" description="Compile the Eclipse plugin">
        <mkdir dir="${basedir}/target/classes"/>
        <!-- simple javac (WARNING: contrary to the JDT, javac doesn't understand OSGi's accessibility (private packages)) -->
        <javac srcdir="${basedir}/src" classpathref="compile.classpath" destdir="${basedir}/target/classes" debug="true" includeAntRuntime="false"/>
        <copy todir="${basedir}/target/classes">
            <fileset dir="${basedir}/src">
                <include name="**"/>
                <exclude name="**/*.java"/>
                <exclude name="**/package.html"/>
            </fileset>
            <fileset dir="${basedir}">
                <include name="plugin.xml"/>
            </fileset>
        </copy>
    </target>

    <target name="build" depends="compile" description="Build the Eclipse plugin">
        <!-- simple jaring -->
        <jar basedir="${basedir}/target/classes" destfile="${basedir}/target/${ant.project.name}.jar" manifest="META-INF/MANIFEST.MF"/>
    </target>

</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Brachiola gambiae J. Weiser & Z. Žižka

### Remarks
null


text:
package com.evolveum.polygon.connector.siebel;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Locale;
import java.util.WeakHashMap;

import org.identityconnectors.common.logging.Log;
import org.identityconnectors.framework.common.exceptions.ConfigurationException;
import org.identityconnectors.framework.spi.AbstractConfiguration;
import org.identityconnectors.framework.spi.ConfigurationProperty;
import org.identityconnectors.framework.spi.StatefulConfiguration;

import com.evolveum.polygon.connector.siebel.util.Pair;

import static java.nio.file.Files.exists;
import static java.nio.file.Files.isDirectory;
import static java.util.Collections.newSetFromMap;
import static java.util.Collections.synchronizedSet;
import static org.identityconnectors.common.StringUtil.isEmpty;

/**
 * Configuration of the Siebel Connector.
 *
 * @author Marián Petráš
 */
public class SiebelConfiguration extends AbstractConfiguration implements StatefulConfiguration {

	private static final String[] SUPPORTED_WS_PROTOCOLS = {"HTTP", "HTTPS"};   //must be in uppercase

	static final int DEFAULT_MAX_PAGE_SIZE = 100;

    private static final Log LOG = Log.getLog(SiebelConfiguration.class);

    /**
     * collection of connectors that will be notified whenever the configuration
     * changes
     */
    private final Collection<SiebelConnector> observingConnectors
            = synchronizedSet(newSetFromMap(new WeakHashMap<SiebelConnector, Boolean>()));

    private String wsUrlString = "";
	private URL    wsUrl = null;
	private URI    wsUri = null;
    private String username = "";
    private String password = "";
    private int    maxPageSize = DEFAULT_MAX_PAGE_SIZE;
    private int    connectTimeout = 30_000;    //milliseconds
    private int    receiveTimeout = 60_000;    //milliseconds
    private String soapLogBasedirStr;
    private Path   soapLogBasedir;

    @ConfigurationProperty(order = 1,
	                       displayMessageKey = "wsUrl.display",
                           groupMessageKey = "basic.group",
	                       helpMessageKey = "wsUrl.help",
	                       required = true)
    public String getWsUrl() {
        return wsUrlString;
    }

    public void setWsUrl(final String urlString) {
		wsUrlString = trim(urlString);

		final Pair<URL, URI> parsedWsAddress = parseURL(wsUrlString);
		if (parsedWsAddress != null) {
			wsUrl = parsedWsAddress.a;
			wsUri = parsedWsAddress.b;
		} else {
			wsUrl = null;
			wsUri = null;
		}

		notifyObservingConnectors();
    }

	URL getParsedWsUrl() {
		return wsUrl;
	}

	URI getParsedWsUri() {
		return wsUri;
	}

	/**
	 * Parses a URL string to a URL and a URI.
	 *
	 * @param  urlString  URL string to be parsed
	 * @return  pair containing the parsed URL in two forms - a URL and a URI;
	 *          or {@code null} if the URL could not be parsed
	 */
	private static Pair<URL, URI> parseURL(final String urlString) {
		Pair<URL, URI> result = null;
		if (urlString != null) {
			try {
				URL url = new URL(urlString);
				URI uri = new URI(urlString);
				LOG.ok("The URL is valid: {0}", urlString);
				result = new Pair(url, uri);
			} catch (MalformedURLException | URISyntaxException urlException) {
				LOG.info("The URL of the WS is INVALID: {0}", urlString);
			}
		}
		return result;
	}

    @ConfigurationProperty(order = 2,
	                       displayMessageKey = "username.display",
                           groupMessageKey = "basic.group",
	                       helpMessageKey = "username.help",
	                       required = true)
    public String getUsername() {
        return username;
    }

    public void setUsername(final String username) {
        this.username = (username == null) ? null : username.trim();

        notifyObservingConnectors();
    }

    @ConfigurationProperty(order = 3,
	                       displayMessageKey = "password.display",
                           groupMessageKey = "basic.group",
	                       helpMessageKey = "password.help",
	                       required = true,
                           confidential = true)
    public String getPassword() {
        return password;
    }

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

        notifyObservingConnectors();
    }

	@ConfigurationProperty(order = 4,
	                       displayMessageKey = "maxPageSize.display",
	                       groupMessageKey = "basic.group",
	                       helpMessageKey = "maxPageSize.help",
	                       required = true,
	                       confidential = false)
	public int getMaxPageSize() {
		return maxPageSize;
	}

	public void setMaxPageSize(int maxPageSize) {
		this.maxPageSize = maxPageSize;

		notifyObservingConnectors();
	}

	@ConfigurationProperty(order = 5,
	                       displayMessageKey = "connectTimeout.display",
	                       groupMessageKey = "basic.group",
	                       helpMessageKey = "connectTimeout.help",
	                       required = true,
	                       confidential = false)
	public int getConnectTimeout() {
		return connectTimeout;
	}

	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;

		notifyObservingConnectors();
	}

	@ConfigurationProperty(order = 6,
	                       displayMessageKey = "receiveTimeout.display",
	                       groupMessageKey = "basic.group",
	                       helpMessageKey = "receiveTimeout.help",
	                       required = true,
	                       confidential = false)
	public int getReceiveTimeout() {
		return receiveTimeout;
	}

	public void setReceiveTimeout(int receiveTimeout) {
		this.receiveTimeout = receiveTimeout;

		notifyObservingConnectors();
	}

	@ConfigurationProperty(order = 7,
	                       displayMessageKey = "soapLogBasedir.display",
	                       groupMessageKey = "basic.group",
	                       helpMessageKey = "soapLogBasedir.help")
	public String getSoapLogBasedir() {
		return soapLogBasedirStr;
	}

	public void setSoapLogBasedir(final String soapLogBasedir) {
		soapLogBasedirStr = trimToNull(soapLogBasedir);

		if (soapLogBasedirStr == null) {
			this.soapLogBasedir = null;
		} else {
			try {
				this.soapLogBasedir = Paths.get(soapLogBasedirStr);
				soapLogBasedirStr = this.soapLogBasedir.toString(); //normalized
			} catch (InvalidPathException ex) {
				LOG.info(ex, "The SOAP log basedir is not a valid path.");
				this.soapLogBasedir = null;
			}
		}

		notifyObservingConnectors();
	}

	Path getSoapLogTargetPath() {
		return soapLogBasedir;
	}

	void addObservingConnector(final SiebelConnector connector) {
		observingConnectors.add(connector);
	}

	void removeObservingConnector(final SiebelConnector connector) {
		observingConnectors.remove(connector);
	}

	private void notifyObservingConnectors() {
		final SiebelConnector[] connectors
				= observingConnectors.toArray(new SiebelConnector[0]);
		for (SiebelConnector connector : connectors) {
			connector.configurationChanged();
		}
	}

	@Override
	public void release() {
		wsUrlString = null;
		wsUrl = null;
		wsUri = null;
		username = null;
		password = null;
		soapLogBasedir = null;
		soapLogBasedirStr = null;
		observingConnectors.clear();
	}

    @Override
    public void validate() {
		if (isEmpty(wsUrlString)) {
			throw new ConfigurationException("WSDL is not specified.");
		}

		if (wsUrl == null) {
			throw new ConfigurationException("WSDL URL is invalid.");
		}

		if (!isSupportedProtocol(wsUrl.getProtocol())) {
			throw new ConfigurationException("Protocol of the web service URL (" + wsUrl.getProtocol() + ") is not supported.");
		}

		if (isEmpty(username)) {
			throw new ConfigurationException("Username is not specified.");
		}

		if (isEmpty(password)) {
			throw new ConfigurationException("Password is not specified.");
		}

		if (maxPageSize <= 0) {
			throw new ConfigurationException("The maximum page size must be positive.");
		}

		if (connectTimeout < 0) {
			throw new ConfigurationException("The connection timeout must be positive.");
		}

		if (receiveTimeout < 0) {
			throw new ConfigurationException("The receive timeout must be positive.");
		}

		if (soapLogBasedirStr != null) {
			if (soapLogBasedir == null) {
				throw new ConfigurationException("The SOAP log basedir is not a valid path.");
			}

			if (!soapLogBasedir.isAbsolute()) {
				throw new ConfigurationException("The SOAP log basedir is not an absolute path.");
			}

			if (!isDirectory(soapLogBasedir)) {
				if (exists(soapLogBasedir)) {
					throw new ConfigurationException("The path to the SOAP log basedir (" + soapLogBasedirStr + ") points to an existing file.");
				}
				throw new ConfigurationException("The SOAP log basedir (" + soapLogBasedirStr + ") doesn't exist.");
			}
		}
    }

	private static boolean isSupportedProtocol(String protocol) {
		protocol = protocol.toUpperCase(Locale.US);
		for (String supported : SUPPORTED_WS_PROTOCOLS) {
			if (supported.equals(protocol)) {
				return true;
			}
		}
		return false;
	}

	private static String trim(final String str) {
		return (str != null) ? str.trim() : null;
	}

	private static String trimToNull(final String str) {
		final String result;
		if (str == null) {
			result = null;
		} else {
			String trimmed = str.trim();
			result = trimmed.isEmpty() ? null : trimmed;
		}
		return result;
	}

}


text:
from django.db import models

from konfera.models.abstract import KonferaModel

class Room(KonferaModel):
    title = models.CharField(max_length=128)
    location = models.ForeignKey('Location', related_name='rooms')
    capacity = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return self.title

    def slugify(self):
        return self.title.strip().replace(' ', '-').lower()


text:
import os
from thefuck.utils import for_app, which

@for_app('gradle')
def match(command):
    return (not which(command.script_parts[0])
            and 'not found' in command.stderr
            and os.path.isfile('gradlew'))

def get_new_command(command):
    return u'./gradlew {}'.format(' '.join(command.script_parts[1:]))


text:
require 'rbconfig'

module ::RbConfig

  #
  # Return the path to the data directory associated with the given
  # library name.
  #
  # Normally this is just:
  #
  #   "#{Config::CONFIG['datadir']}/#{name}"
  #
  # But it may be modified by packages like RubyGems and Rolls to handle
  # versioned data directories.
  #
  def self.datadir(name, versionless=false)
    if lib = Library.instance(name)
      lib.datadir(versionless)
    elsif defined?(super)
      super(name)
    else
      File.join(CONFIG['datadir'], name)
    end
  end

  #
  # Return the path to the configuration directory.
  #
  def self.confdir(name)
    if lib = Library.instance(name)
      lib.confdir
    else
      File.join(CONFIG['confdir'], name)
    end
  end

  #
  # Patterns used to identiy a Windows platform.
  #
  WIN_PATTERNS = [
    /bccwin/i,
    /cygwin/i,
    /djgpp/i,
    /mingw/i,
    /mswin/i,
    /wince/i,
  ]

  #WINDOWS_PLATFORM = !!WIN_PATTERNS.find{ |r| RUBY_PLATFORM =~ r }

  #
  # Is this a windows platform? This method compares the entires
  # in +WIN_PATTERNS+ against +RUBY_PLATFORM+.
  #
  def self.windows_platform?
    case RUBY_PLATFORM
    when *WIN_PATTERNS
      true
    else
      false
    end
  end

end