text:
[CmdletBinding()]
# Suppressing this because we need to generate a mocked credentials that will be passed along to the examples that are needed in the tests.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
param()

$script:moduleRoot = Split-Path $PSScriptRoot -Parent

Describe 'xSQLServer module common tests' {
    Context -Name 'When there are example file for resource' {
            <#
                For Appveyor builds copy the module to the system modules directory so it falls
                in to a PSModulePath folder and is picked up correctly.
            #>
            if ($env:APPVEYOR)
            {
                $powershellModulePath = Join-Path -Path (($env:PSModulePath -split ';')[0]) -ChildPath 'xSQLServer'
                Copy-item -Path $env:APPVEYOR_BUILD_FOLDER -Destination $powershellModulePath -Recurse -Force
            }

            $mockPassword = ConvertTo-SecureString '&iPm%M5q3K$Hhq=wcEK' -AsPlainText -Force
            $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList @('username', $mockPassword)
            $mockConfigData = @{
                AllNodes = @(
                    @{
                        NodeName = "localhost"
                        PSDscAllowPlainTextPassword = $true
                    }
                )
            }

            $exampleFile = Get-ChildItem -Path "$script:moduleRoot\Examples\Resources" -Filter "*.ps1" -Recurse

            foreach ($exampleToValidate in $exampleFile)
            {
                $exampleDescriptiveName = Join-Path -Path (Split-Path $exampleToValidate.Directory -Leaf) -ChildPath (Split-Path $exampleToValidate -Leaf)

                It "Should compile MOFs for example '$exampleDescriptiveName' correctly" {
                    {
                        . $exampleToValidate.FullName

                        $exampleCommand = Get-Command Example -ErrorAction SilentlyContinue
                        if ($exampleCommand)
                        {
                            try
                            {
                                $params = @{}
                                $exampleCommand.Parameters.Keys | Where-Object { $_ -like '*Account' -or ($_ -like '*Credential' -and $_ -ne 'PsDscRunAsCredential')  } | ForEach-Object -Process {
                                    $params.Add($_, $mockCredential)
                                }

                                Example @params -ConfigurationData $mockConfigData -OutputPath 'TestDrive:\' -ErrorAction Continue -WarningAction SilentlyContinue | Out-Null
                            }
                            finally
                            {
                                # Remove the function we dot-sourced so next example file doesn't use the previous Example-function.
                                Remove-Item function:Example
                            }
                        }
                        else
                        {
                            throw "The example '$exampleDescriptiveName' does not contain a function 'Example'."
                        }
                    } | Should Not Throw
                }
        }

        if ($env:APPVEYOR -eq $true)
        {
            Remove-item -Path $powershellModulePath -Recurse -Force -Confirm:$false

            # Restore the module in 'memory' to ensure other tests after this test have access to it
            Import-Module -Name "$script:moduleRoot\xSQLServer.psd1" -Global -Force
        }
    }
}


text:
package cn.alandelip.teachingsupportapp.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import org.json.JSONException;
import org.json.JSONObject;

import cn.alandelip.teachingsupportapp.R;

/**
 * @author v-zhuxu on 6/20/2017.
 */
public class AuthUtils {
    private static final String PREFIX = "Basic ";

    public static String generateToken(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(context.getString(R.string.app_preference), Context.MODE_PRIVATE);
        String username = sharedPreferences.getString(context.getString(R.string.username), "");
        String password = sharedPreferences.getString(context.getString(R.string.password), "");
        return PREFIX + Base64.encodeToString((username + ":" + password).getBytes(), Base64.DEFAULT).trim();//to remove the invisible char 0x0a at the end
    }
}

redpajama_set_name: RedPajamaGithub


text:
const base = require('../../jest.config.base.js');

module.exports = {
  ...base,
  name: 'typedoc-gitlab-wiki-theme',
  displayName: 'typedoc-gitlab-wiki-theme',
};


text:
layout: post
date: 2015-10-22
title: "Pronovias AJUAR Sleeveless Ankle-Length Sheath/Column"
category: Pronovias
tags: [Pronovias,Sheath/Column,Bateau,Ankle-Length,Sleeveless]
---
### Pronovias AJUAR
Just **$289.99**
###   Sleeveless Ankle-Length Sheath/Column

BRANDS	Pronovias

Silhouette	Sheath/Column

Neckline	Bateau

Hemline/Train	Ankle-Length

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/pronovias/4440-pronovias-ajuar.html](https://www.readybrides.com/en/pronovias/4440-pronovias-ajuar.html)


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/privacy/dlp/v2/dlp.proto

namespace Google\Cloud\Dlp\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * An expression, consisting or an operator and conditions.
 *
 * Generated from protobuf message google.privacy.dlp.v2.RecordCondition.Expressions
 */
class RecordCondition_Expressions extends \Google\Protobuf\Internal\Message
{
    /**
     * The operator to apply to the result of conditions. Default and currently
     * only supported value is `AND`.
     *
     * Generated from protobuf field .google.privacy.dlp.v2.RecordCondition.Expressions.LogicalOperator logical_operator = 1;
     */
    private $logical_operator = 0;
    protected $type;

    public function __construct() {
        \GPBMetadata\Google\Privacy\Dlp\V2\Dlp::initOnce();
        parent::__construct();
    }

    /**
     * The operator to apply to the result of conditions. Default and currently
     * only supported value is `AND`.
     *
     * Generated from protobuf field .google.privacy.dlp.v2.RecordCondition.Expressions.LogicalOperator logical_operator = 1;
     * @return int
     */
    public function getLogicalOperator()
    {
        return $this->logical_operator;
    }

    /**
     * The operator to apply to the result of conditions. Default and currently
     * only supported value is `AND`.
     *
     * Generated from protobuf field .google.privacy.dlp.v2.RecordCondition.Expressions.LogicalOperator logical_operator = 1;
     * @param int $var
     * @return $this
     */
    public function setLogicalOperator($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\Dlp\V2\RecordCondition_Expressions_LogicalOperator::class);
        $this->logical_operator = $var;

        return $this;
    }

    /**
     * Generated from protobuf field .google.privacy.dlp.v2.RecordCondition.Conditions conditions = 3;
     * @return \Google\Cloud\Dlp\V2\RecordCondition_Conditions
     */
    public function getConditions()
    {
        return $this->readOneof(3);
    }

    /**
     * Generated from protobuf field .google.privacy.dlp.v2.RecordCondition.Conditions conditions = 3;
     * @param \Google\Cloud\Dlp\V2\RecordCondition_Conditions $var
     * @return $this
     */
    public function setConditions($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\RecordCondition_Conditions::class);
        $this->writeOneof(3, $var);

        return $this;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->whichOneof("type");
    }

}


text:
package com.echo.holographlibrary;

/**
 * Created by Aaron on 19/10/2014.
 */
public class BarStackSegment {
    public int Value;
    public int Color;
    public BarStackSegment(int val, int color){
        Value = val;
        Color = color;
    }
}


text:
layout: post
title: Mass Undelete from the Recycle Bin
date: 2015-02-20 11:03:47.000000000 -05:00
categories: blog
---

This is more "e-discovery" than forensics but I recently had a case where I needed to 1,300 files that were in a user's Recycle Bin.

It was not overly important to the user's management when they were originally created or when it was deleted. They just wanted to review the documents. So I took an hour and hammered out this beast.


text:
// Copyright 2017 Google Inc.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

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

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// [START app]
'use strict';

// [START setup]
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cors = require('cors');
const request = require('request');
const storage = require('@google-cloud/storage');
const config = require('./local.json');
const storageClient = storage({projectId: config.cloud_project_id, keyfileName: './keyfile.json'});
const app = express();
const port = normalizePort(process.env.PORT || 3000);

/*
* Port Settings
*
*/

app.enable('trust proxy');
app.set('port', port);

function normalizePort(val) {
  const port = parseInt(val, 10);

  // NAMED PORT
  if (isNaN(port)) {
    return val;
  }

  // CUSTOM PORT
  if (port >= 0) {
    return port;
  }

  return false;
}

/*
* View Engine
*
*/

app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));

/*
* Middleware
*
*/

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());

/*
* API Route for Video Data
*
*
*/

app.get('/api/videos', (req, res) => {
  const storageBucket = storageClient.bucket(config.video_bucket);

  storageBucket.getFiles(function(err, files) {
    if (!err) {
      let fileArray = [];

      files.forEach(function(file) {
        const videoAnnotationBucket = storageClient.bucket(config.video_json_bucket);
        const baseFileName = file.metadata.name.substring(0, file.metadata.name.indexOf('.'));
        const videoAnnotationFilename = (file.metadata.name).replace('/', '').replace('.', '') + '.json';
        const annotationFile = videoAnnotationBucket.file(videoAnnotationFilename);

        // GET ANNONATIONS FOR EACH FILE
        annotationFile.get(function(error, fileData) {
          if (error) {
            console.log('error getting file', error);
          }
          else {
            const remoteJsonUrl = fileData.metadata.mediaLink;

            request({
              url: remoteJsonUrl,
              json: true
            },
            function(jsonReadErr, jsonResp, body) {
              if (!jsonReadErr) {
                fileArray.push({
                  name: file.metadata.name,
                  link: file.metadata.mediaLink,
                  url_safe_id: (file.metadata.name).replace('/', '-').replace('.','-'),
                  annotations: body.annotation_results[0],
                  thumbnail: `https://storage.googleapis.com/${config.thumbnail_bucket}/${baseFileName}.png`,
                  preview: `https://storage.googleapis.com/${config.thumbnail_bucket}/${baseFileName}-preview.png`
                });

                // RETURN PAYLOAD
                if (fileArray.length == files.length) {
                  res.send(fileArray);
                }
              }
            });
          }
        });
      });
    }
    else {
      console.log('GCS error getting files', err);
    }
  });
});

/*
* Route for all other pages
*
*
*/

app.use('*', require('./routes/index'));

module.exports = app;


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = safeJsonParse;
/**
* @typedef {object} Response
* @property {Error} error - JSON.parse exception
* @property {object} result - parsed JSON
*/

/**
* parse JSON without throwing an exception
* @param {string} jsonStr - stringified json
* @return {Response} - response object
*/
function safeJsonParse(jsonStr) {
    let result = null;
    try {
        result = JSON.parse(jsonStr);
    } catch (e) {
        return { error: e, result };
    }
    return { error: null, result };
}


text:
import { GraphQLList, GraphQLObjectType, GraphQLSchema } from 'graphql';
import { WeavingConfig } from '../../../src/config/weaving-config';
import { testTypes } from '../../helpers/test-types';

export async function getConfig(): Promise<WeavingConfig> {
    return {
        endpoints: [
            {
                namespace: 'staticData',
                url: "http://localhost:1337/graphql",
                typePrefix: 'CountryNS'
            },
            {
                schema: new GraphQLSchema({
                    query: new GraphQLObjectType({
                        name: 'Query',
                        fields: {
                            horst: {
                                type: testTypes.personType,
                                resolve: () => ({nationality: 'DE', name: "Horst"})
                            },
                            allPeople: {
                                type: new GraphQLList(testTypes.personType),
                                resolve: () => ([
                                    {nationality: 'DE', name: "Horst"},
                                    {nationality: 'DE', name: "Helga"},
                                    {nationality: 'FR', name: "Jacqueline"}])
                            }
                        }
                    })
                }),
                fieldMetadata: {
                    "Person.nationality": {
                        "link": {
                            "field": "staticData.allCountries",
                            "argument": "filter.identCode_in",
                            "keyField": "identCode",
                            "batchMode": true
                        }
                    }
                }
            }
        ]
    };
}


text:
package Hosting::Default;

use Mojo::Base 'Mojolicious::Controller';

sub dynamic {
    my $self = shift;

    $self->stash(msg => "we are the default");

    my $path = Mojo::Util::class_to_file(__PACKAGE__);

    return($self->render("$path/home"));
}

sub static {
    my $self = shift;

    my $path = Mojo::Util::class_to_file(__PACKAGE__);

    $self->app->log->debug($path);

    return($self->render_static("$path/file.txt"));
}

1;


text:
<?php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Zend\Http\Request;
use \OAuth_io\OAuth;
use Zend\Http\Response;

class IndexController extends AbstractActionController {
    private $oauth;
    private $error = false;

    public function __construct() {
        session_start();
        if (file_exists(__DIR__ . '/../../../config/config.php')) {

            // Requires a config array containing your
            // app key and app secret from oauth.io
            $config = require (__DIR__ . '/../../../config/config.php');

            // This creates an instance of the OAuth SDK
            $this->oauth = new OAuth();

            // Disables the SSL certificate verification if you're
            // running a private oauthd instance, with no verified
            // certificate.
            // SSL verification is active by default.
            $this->oauth->setSslVerification($config['ssl_verification']);

            // Sets the oauthd URL. This step is not compulsory if
            // the URL is https://oauth.io.
            $this->oauth->setOAuthdUrl($config['oauthd_url']);

            // Initializes the SDK
            $this->oauth->initialize($config['app_key'], $config['app_secret']);
        } else {
            $this->error = true;
        }
    }

    /**
     * GET /
     *
     * Returns the index.html page with the login button
     */
    public function indexAction() {
        return new ViewModel(array('error' => $this->error));
    }

    /**
     * GET /oauth/token
     *
     * Returns a state token generated by OAuth.io
     */
    public function tokenAction() {
        // This generates a token and stores it in the session
        $token = $this->oauth->generateStateToken();

        $array = array(
            'token' => $token
        );
        $json = new JsonModel($array);
        return $json;
    }

    /**
     * POST /oauth/signin
     *
     * Waits for a 'code' parameter, that must have been
     * given by oauth.io in the front-end. Authenticates
     * the user by retrieving an access token and storing
     * it in the session.
     */
    public function authAction() {
        $code = $this->getRequest()->getPost('code');

        // This sends the code to OAuth.io, retrieves the access token
        // and stores it in the session for use in other endpoints
        $request_object = $this->oauth->auth('google', array(
            'code' => $code
        ));
        $credentials = $request_object->getCredentials();
        $json = new JsonModel($credentials);

        // Checks if the response gave an access token (for OAuth2 in that case)
        // which works as we're using Facebook.
        if (!isset($credentials['access_token'])) {
            $this->getResponse()->setStatusCode(400);
        }
        return $json;
    }

    /**
     * GET /me
     *
     * Returns information about the user if the latter
     * has been authenticated through the auth action.
     */
    public function requestAction() {
        // This creates a request object that contains the methods
        // get|post|put|patch|del|me to perform API requests
        // thanks to the credentials stored in the session
        $request_object = $this->oauth->auth('google');

        // This performs a request on the unified user info endpoint
        // to get his name, email and avatar, regardless of the provider's
        // implementation
        $me = $request_object->me(array(
            'name',
            'email',
            'avatar'
        ));

        $json = new JsonModel($me);
        return $json;
    }
}


text:
using namespace MX;
using namespace MX::Graphic;

SpecificActorCreator::SpecificActorCreator(LScriptObject& script)
    : ActorCreator(script)
{
    int total_sum = 0;
    auto& actors = script.property_object("Actors")->array();
    for (auto& actor : actors)
    {
        using Pair = std::pair<Entry, int>;
        Pair pair;
        if (!PropertyLoader<Pair>::load(pair, actor))
        {
            auto actor_object = actor->to_object<ScriptableSpriteActor>();
            if (actor_object)
            {
                total_sum++;
                _actors.push_back(std::make_pair(actor_object, 1));
            }
            continue;
        }

        total_sum += pair.second;
        _actors.push_back(pair);
    }

    _remainingToGenerate = _maxActors = total_sum;
}

class SwitchActorCreator : public ActorCreator
{
public:
    SwitchActorCreator(LScriptObject& script)
        : ActorCreator(script)
    {
        script.load_property(_condition, "Condition");
        script.load_property_children(_entries, "Case");
        script.load_property(_defaultCase, "Default");
    }

    std::shared_ptr<ScriptableSpriteActor> onCreateActor() override
    {
        float cond = *_condition;

        auto it = _entries.find(cond);
        if (it == _entries.end())
        {
            return _defaultCase.CreateActor();
        }
        return it->second.CreateActor();
    }

    ActorCreator::pointer clone() override { return std::make_shared<SwitchActorCreator>(*this); }

    using Entry = ActorCreatorEntry;

    Scriptable::Value::pointer _condition;
    std::map<float, Entry> _entries;
    Entry _defaultCase;
};

RandomActorCreator::RandomActorCreator()
{
}

RandomActorCreator::RandomActorCreator(LScriptObject& script)
    : ActorCreator(script)
{
    script.load_property(_randomActors, "Actors");
}

void ActorCreatorInit::Init()
{
    ScriptClassParser::AddCreator(L"Scene.ActorFactory.Creator.Switch", new OutsideScriptClassCreatorContructor<SwitchActorCreator>());
    ScriptClassParser::AddCreator(L"Scene.ActorFactory.Creator.Random", new OutsideScriptClassCreatorContructor<RandomActorCreator>());
    ScriptClassParser::AddCreator(L"Scene.ActorFactory.Creator.Specific", new OutsideScriptClassCreatorContructor<SpecificActorCreator>());
}


text:
//-----------------------------------------------------------------------
// <copyright file="EndOfTrackMetaMidiEvent.cs" company="Stephen Toub">
//     Copyright (c) Stephen Toub. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System.IO;

namespace MidiSharp.Events.Meta
{
    /// An end of track meta event message.
    public sealed class EndOfTrackMetaMidiEvent : MetaMidiEvent
    {
        /// The meta id for this event.
        internal const byte MetaId = 0x2F;

        /// Intializes the end of track meta event.
        /// <param name="deltaTime">The amount of time before this event.</param>
        public EndOfTrackMetaMidiEvent(long deltaTime) : base(deltaTime, MetaId) { }

        /// Write the event to the output stream.
        /// <param name="outputStream">The stream to which the event should be written.</param>
        public override void Write(Stream outputStream)
        {
            base.Write(outputStream);
            outputStream.WriteByte(0x00);
        }

        /// Creates a deep copy of the MIDI event.
        /// <returns>A deep clone of the MIDI event.</returns>
        public override MidiEvent DeepClone()
        {
            return new EndOfTrackMetaMidiEvent(DeltaTime);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue_grey" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
            <TextView
                android:id="@+id/login_intro"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_margin="15dip"
                android:layout_weight="1"
                style="@style/immopolyHeading1"
                android:text="@string/user_signup_app_name"
                android:textSize="34dp" />
            <ProgressBar
                android:id="@+id/login_progress"
                style="@android:style/Widget.ProgressBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:visibility="gone" />
            <Button
                android:id="@+id/register"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:onClick="registerUser"
                android:text="@string/register_short"
                style="@style/immopolyButton"
                android:textSize="20dip" />
        </LinearLayout>
        <EditText
            android:id="@+id/user_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/username_hint"
            android:imeOptions="actionNext"
            android:singleLine="true" >
        </EditText>
        <EditText
            android:id="@+id/user_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password_hint"
            android:imeOptions="actionDone"
            android:inputType="textPassword"
            android:singleLine="true" >
        </EditText>
        <EditText
            android:id="@+id/user_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/user_email_hint_login"
            android:imeOptions="actionDone"
            android:inputType="textEmailAddress"
            android:singleLine="true" />
        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:onClick="loginUser"
            android:text="@string/login"
            style="@style/immopolyButton"
            android:textSize="20dip" />
        <Button
            android:id="@+id/forgot_password"
            style="@style/immopolyButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:onClick="recoverPassword"
            android:text="@string/forgot_passwd"
            android:textSize="20dip" />
    </LinearLayout>
</ScrollView>


text: export { default } from 'shared/mixins/safe-style';


text:
<?php

namespace Password;

class Generator
{
    protected $minLength = 8;
    protected $numberOfUpperCaseLetters = 0;
    protected $numberOfNumbers = 0;
    protected $numberOfSymbols = 0;
    protected $lowerCaseLetters = 'abcdefghijklmnopqrstuvwxyz';
    protected $upperCaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    protected $numbers = '0123456789';
    protected $symbols = '#@_!.+-';

    public function setMinLength($minLength)
    {
        $this->minLength = $minLength;

        return $this;
    }

    public function setNumberOfUpperCaseLetters($numberOfUpperCaseLetters)
    {
        $this->numberOfUpperCaseLetters = $numberOfUpperCaseLetters;

        return $this;
    }

    public function setNumberOfNumbers($numberOfNumbers)
    {
        $this->numberOfNumbers = $numberOfNumbers;

        return $this;
    }

    public function setNumberOfSymbols($numberOfSymbols)
    {
        $this->numberOfSymbols = $numberOfSymbols;

        return $this;
    }

    public function generate()
    {
        $password = $this->generateUpperCaseLetters() . $this->generateNumbers() . $this->generateSymbols();
        $password = $this->completeWithLowerCaseLetters($password);
        return str_shuffle($password);
    }

    protected function generateUpperCaseLetters()
    {
        $password = '';
        for ($i = 0; $i < $this->numberOfUpperCaseLetters; $i++) {
            $password .= $this->upperCaseLetters[(rand() % strlen($this->upperCaseLetters))];
        }

        return $password;
    }

    protected function generateSymbols()
    {
        $password = '';
        for ($i = 0; $i < $this->numberOfSymbols; $i++) {
            $password .= $this->symbols[(rand() % strlen($this->symbols))];
        }

        return $password;
    }

    protected function generateNumbers()
    {
        $password = '';
        for ($i = 0; $i < $this->numberOfNumbers; $i++) {
            $password .= $this->numbers[(rand() % strlen($this->numbers))];
        }

        return $password;
    }

    protected function completeWithLowerCaseLetters($password)
    {
        while (strlen($password) < $this->minLength) {
            $password .= $this->lowerCaseLetters[(rand() % strlen($this->lowerCaseLetters))];
        }

        return $password;
    }
}


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

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<testcase>
  <info>
    <p>
      This test checks that IDs coming from a block properly appear in the IF output.
    </p>
  </info>
  <fo>
    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
      <fo:layout-master-set>
        <fo:simple-page-master master-name="page"
          page-height="320pt" page-width="420pt" margin="10pt">
          <fo:region-body/>
        </fo:simple-page-master>
      </fo:layout-master-set>

      <fo:page-sequence master-reference="page">
        <fo:flow flow-name="xsl-region-body">
          <fo:block>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce rutrum leo a diam
            bibendum auctor. Vivamus porttitor sollicitudin tortor eu vulputate.</fo:block>
          <fo:block space-before="10pt" id="outer-block_1" color="purple">In vel libero libero, a semper
            est. Vivamus dapibus ante id lorem mattis eget mattis urna sodales.
            <fo:block id="inner-block_1" color="blue" start-indent="2em">Vestibulum nec dui urna, in
              porta mi. Proin varius egestas erat. Donec pharetra iaculis dolor, ut rutrum nunc
              facilisis at.</fo:block>
            Proin ante eros, consequat eget semper a, molestie non arcu. Praesent hendrerit dolor vel
            leo luctus dapibus.</fo:block>
          <fo:block space-before="10pt">Nullam quam nisl, iaculis ut fermentum et, vestibulum id elit.
            Suspendisse fermentum fermentum ullamcorper.</fo:block>
          <fo:block space-before="10pt" color="purple" id="block_1">Sed ultrices posuere posuere.
            Praesent vitae ligula odio.</fo:block>
        </fo:flow>
      </fo:page-sequence>

      <fo:page-sequence master-reference="page">
        <fo:flow flow-name="xsl-region-body">
          <fo:block>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce rutrum leo a diam
            bibendum auctor. Vivamus porttitor sollicitudin tortor eu vulputate.</fo:block>
          <fo:block space-before="10pt" id="outer-block_2" color="purple">In vel libero libero, a semper
            est. Vivamus dapibus ante id lorem mattis eget mattis urna sodales.
            <fo:block color="black" start-indent="2em">Mauris tincidunt, risus eget vulputate elementum,
              turpis lorem aliquet purus, eu sagittis neque sapien vel lectus.
              <fo:block id="inner-block_2" color="blue" start-indent="4em">Vestibulum nec dui urna, in
                porta mi. Proin varius egestas erat. Donec pharetra iaculis dolor, ut rutrum nunc
                facilisis at.</fo:block>
              Proin ante eros, consequat eget semper a, molestie non arcu. Praesent hendrerit dolor vel
              leo luctus dapibus.</fo:block>
            Vivamus ut sollicitudin metus. Curabitur sit amet aliquam enim.</fo:block>
          <fo:block space-before="10pt">Nullam quam nisl, iaculis ut fermentum et, vestibulum id elit.
            Suspendisse fermentum fermentum ullamcorper.</fo:block>
          <fo:block space-before="10pt" color="purple" id="block_2">Vivamus tellus libero, porttitor a
            lacinia a, tempor eu dui. Pellentesque fermentum odio tempor lorem interdum
            pharetra.</fo:block>
          <fo:block space-before="10pt">Donec auctor venenatis convallis.</fo:block>
        </fo:flow>
      </fo:page-sequence>

    </fo:root>
  </fo>
  <if-checks xmlns:if="http://xmlgraphics.apache.org/fop/intermediate">

    <!-- Page 1 -->
    <eval expected="16"        xpath="count(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'])"/>

    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][1])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][2])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][3])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][4])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][5])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][6])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][7])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][8])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][9])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][10])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][11])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][12])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][13])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][14])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][15])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[1]/descendant::*[local-name() = 'text' or local-name() = 'id'][16])"/>

    <eval expected="outer-block_1"   xpath="//if:page-sequence[1]/descendant::*[local-name() = 'id'][1]/@name"/>
    <eval expected="inner-block_1"   xpath="//if:page-sequence[1]/descendant::*[local-name() = 'id'][2]/@name"/>
    <eval expected="outer-block_1"   xpath="//if:page-sequence[1]/descendant::*[local-name() = 'id'][3]/@name"/>
    <eval expected=""                xpath="//if:page-sequence[1]/descendant::*[local-name() = 'id'][4]/@name"/>
    <eval expected="block_1"         xpath="//if:page-sequence[1]/descendant::*[local-name() = 'id'][5]/@name"/>

    <!-- Page 2 -->
    <eval expected="22"        xpath="count(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'])"/>

    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][1])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][2])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][3])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][4])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][5])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][6])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][7])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][8])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][9])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][10])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][11])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][12])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][13])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][14])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][15])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][16])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][17])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][18])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][19])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][20])"/>
    <eval expected="id"   xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][21])"/>
    <eval expected="text" xpath="local-name(//if:page-sequence[2]/descendant::*[local-name() = 'text' or local-name() = 'id'][22])"/>

    <eval expected="outer-block_2"   xpath="//if:page-sequence[2]/descendant::*[local-name() = 'id'][1]/@name"/>
    <eval expected="inner-block_2"   xpath="//if:page-sequence[2]/descendant::*[local-name() = 'id'][2]/@name"/>
    <eval expected="outer-block_2"   xpath="//if:page-sequence[2]/descendant::*[local-name() = 'id'][3]/@name"/>
    <eval expected=""                xpath="//if:page-sequence[2]/descendant::*[local-name() = 'id'][4]/@name"/>
    <eval expected="block_2"         xpath="//if:page-sequence[2]/descendant::*[local-name() = 'id'][5]/@name"/>
    <eval expected=""                xpath="//if:page-sequence[2]/descendant::*[local-name() = 'id'][6]/@name"/>

  </if-checks>
</testcase>


text:
<?php

namespace PommProject\ModelManager\Test\Unit\ModelLayer;

use PommProject\Foundation\Session\Connection;
use PommProject\Foundation\Session\Session;
use PommProject\ModelManager\Tester\ModelSessionAtoum;

class ModelLayer extends ModelSessionAtoum
{
    public function setUp()
    {
        $this
            ->buildSession()
            ->getConnection()
            ->executeAnonymousQuery(<<<EOSQL
create schema pomm_test;
create table pomm_test.pika (id serial primary key);
create table pomm_test.chu (id serial primary key, pika_id int not null references pomm_test.pika (id) deferrable);
EOSQL
            )
        ;
    }

    public function tearDown()
    {
        $this
            ->buildSession()
            ->getConnection()
            ->executeAnonymousQuery('drop schema pomm_test cascade;')
            ;
    }

    public function afterTestMethod($method)
    {
        /*
         * This is to ensure the transaction is terminated even if a test fails
         * so the ClientHolder can shutdown correctly.
         */
        $this->getModelLayer()->rollbackTransaction();
    }

    protected function initializeSession(Session $session)
    {
    }

    public function getModelLayer()
    {
        $model_layer = $this->buildSession()->getModelLayer('PommProject\ModelManager\Test\Fixture\SimpleModelLayer');
        $this
            ->object($model_layer)
            ->isInstanceOf('\PommProject\ModelManager\ModelLayer\ModelLayer')
            ;

        return $model_layer;
    }

    public function testSetDeferrable()
    {
        $model_layer = $this->getModelLayer();
        $this
            ->object(
                $model_layer
                    ->setDeferrable(['pomm_test.chu_pika_id_fkey'], Connection::CONSTRAINTS_DEFERRED)
            )
            ->isEqualTo($model_layer)
            ->exception(function () use ($model_layer) {
                $model_layer->setDeferrable(['pomm_test.chu_pika_id_fkey'], 'chu');
            })
            ->isInstanceOf('\PommProject\ModelManager\Exception\ModelLayerException')
            ->message->contains("'chu' is not a valid constraint modifier")
            ;
    }

    public function testTransaction()
    {
        $model_layer = $this->getModelLayer();
        $this
            ->boolean($model_layer->startTransaction())
            ->isTrue()
            ->boolean($model_layer->setSavepoint('12 345'))
            ->isTrue()
            ->boolean($model_layer->releaseSavepoint('12 345'))
            ->isTrue()
            ->boolean($model_layer->setSavepoint('chu'))
            ->isTrue()
            ->boolean($model_layer->rollbackTransaction('chu'))
            ->isTrue()
            ->variable($model_layer->sendNotify('plop', 'whatever'))
            ->isNull()
            ->boolean($model_layer->isTransactionOk())
            ->isTrue()
            ->exception(function () use ($model_layer) { $model_layer->releaseSavepoint('not exist'); })
            ->isInstanceOf('\PommProject\Foundation\Exception\SqlException')
            ->boolean($model_layer->isInTransaction())
            ->isTrue()
            ->boolean($model_layer->isTransactionOk())
            ->isFalse()
            ->object($model_layer->commitTransaction())
            ->isIdenticalTo($model_layer)
            ->array($model_layer->sendNotify('plop', 'whatever'))
            ->contains('whatever')
            ;
    }

    protected function testSetTransactionIsolationLevelDataProvider()
    {
        return [
            Connection::ISOLATION_READ_COMMITTED,
            Connection::ISOLATION_REPEATABLE_READ,
            Connection::ISOLATION_SERIALIZABLE,
        ];
    }

    public function testSetTransactionIsolationLevel($level)
    {
        $model_layer = $this->getModelLayer();
        $model_layer->startTransaction();
        $this
            ->object($model_layer->setTransactionIsolationLevel($level))
            ->string($this->getTransactionIsolationLevel($model_layer))
            ->isEqualTo(strtolower($level))
            ;
        $model_layer->rollbackTransaction();
    }

    protected function getTransactionIsolationLevel($model_layer)
    {
        return $model_layer->getSession()
            ->getQueryManager()
            ->query('show transaction_isolation')
            ->current()['transaction_isolation']
            ;
    }

    public function testSetTransactionAccessMode()
    {
        $model_layer = $this->getModelLayer();
        $model_layer->startTransaction();
        $this
            ->object($model_layer->setTransactionAccessMode(Connection::ACCESS_MODE_READ_WRITE))
            ->string($this->getTransactionAccessModel($model_layer))
            ->isEqualTo('off')
            ->object($model_layer->setTransactionAccessMode(Connection::ACCESS_MODE_READ_ONLY))
            ->string($this->getTransactionAccessModel($model_layer))
            ->isEqualTo('on')
            ;
    }

    protected function getTransactionAccessModel($model_layer)
    {
        return $model_layer->getSession()
            ->getQueryManager()
            ->query('show transaction_read_only')
            ->current()['transaction_read_only']
            ;
    }
}


text:
layout: post
title: Rapid growth and new leadership roles
author: Seth Etter
slug: rapid-growth-and-new-leadership-roles
---

Open Wichita started during the Summer of 2015 as a half-thought-out idea to create a civic hacking community in Wichita, following in the footsteps of other [Code for America](https://codeforamerica.org) brigades around the country.

The powers of open data and grassroots efforts to improve a city with technology were wildly apparent in certain areas of the world, so why not make it happen here? It was worth a shot, at least.

**To much surprise, it grew, very quickly.**

Turns out there are a lot of individuals in Wichita who care about making their city a better place, however they can. It is this civically-focused mentality that I think sets Wichita apart from many communities. We love our community and are willing to do whatever we can to make it more awesome.

We're also willing to empower others to do the same, no matter who they are or what they do. If someone wants to accomplish something, we all band together to help them make that happen.

**That's what Open Wichita is about.**

It's been very humbling. Numerous people from various walks of life came to our meetups with awesome ideas to make Wichita better. The work that has been put in is **100% volunteer time**, driven purely by a passion to do something good for the community.

Some of the things we have going on are:

* [An initiative to lower infant mortality rates](https://openwichita.org/infant-info-project-highlight/)
* [A way to connect Wichitans with local food sources](https://openwichita.org/wichita-eagle-features-ict-food-circle/)
* [Improved digital tooling for local public transit](https://openwichita.org/busict-project-update/)
* [A partnership with KMUW to increase voter education](https://openwichita.org/open-wichita-partners-with-kmuw-89-1-on-voter-turnout/)
* [Pursuit of an Open Data policy for the city of Wichita](https://www.kansas.com/news/politics-government/article47093260.html)
* [A collaboration with Riverfest for a large scale civic hackathon](https://openwichita.org/open-wichita-in-the-news/)

..and that's not everything. Clearly, the last 6 months have been busy!

**Time to get serious.**

This kind of growth requires better organization and administration with Open Wichita. It is for that reason that specific leadership positions have been created so we can keep up with all the forward movement.

So, without further ado, here are the positions and their chosen appointees:

* **Director (Seth Etter)** - Responsible for overall organizational direction, wrangles the rest of the leadership team.
* **Project Coordinator (Michael Neth)** - Ensures individual projects can move forward and assists with new project onboarding.
* **Communications Director (Aaron Wirtz)** - Keeps Open Wichita engaged with the community through coverage of our efforts.
* **Policy Advisor (Jason Van DeCreek)** - Advises and coordinates our government policy efforts, including Open Data policy.
* **Community Engagement Director (Ben Blankley)** - Coordinates relationships with other local community organizations.
* **Data Curator (Britten Kuckelman)** - Our connection to the vast amount and variety of data sets at our disposal.
* **City Representative (Mike Mayta)** - Provides connection to local government for data, collaboration, etc.

These individuals have all been chosen because they were each already acting in this capacity and have done so by their own desire to be involved.

**Open Wichita would be nowhere without the effort of each of the individuals involved at the leadership level, project level, and otherwise.** There is no way to express my gratitude to every person who has been a part of the group up until this point. You are all truly awesome people, I can't thank you enough.

**But this is just the beginning.**

With the Open Data policy in progress, the Riverfest Hackathon on the horizon, and multiple projects being worked on, Open Wichita is on the tipping point of making a huge impact on this city.

Now is the time to get involved! [Join the group on meetup](https://meetup.com/openwichita) and come out to one of our hack nights to see what we're all about. You can also check out [several other ways of connecting](https://openwichita.org/talk). There's no time like the present!


text:
desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence do
      execute :touch, release_path.join('tmp/restart.txt')

      wait_s = 10

      application_re = Regexp.escape(fetch(:application))

      execute(%Q{sudo bash -c 'for sname in $(initctl list | grep "^#{application_re}\\-[a-zA-Z_]\\+\\-[0-9]\\+\\b" | cut -d'\\'' '\\'' -f1); do echo "RESTARTING $(hostname -f) SERVICE $sname" && service $sname restart && sleep #{wait_s}; done'})
      execute(%Q{sudo sh -c 'service #{fetch(:application)} start || true'})
    end
  end
end


text:
'use strict';

const async = require( 'async' );
const parse = require( 'csv-parser' );
const turf = require( '@turf/turf' );
const request = require( 'request' );
const cheerio = require( 'cheerio' );
const shapefile = require( 'shapefile' );
const Readable = require( 'stream' ).Readable;

const toTitleCase = function ( str ) {
	return str.replace( /\w[^\s-']*/g, function ( txt ) {
		return txt.charAt( 0 ).toUpperCase() + txt.substr( 1 ).toLowerCase();
	} );
};

module.exports = {
	usgsAreaCodeShapes: function ( done ) {

		const shapeFileUrl = 'https://www.sciencebase.gov/catalog/file/get/4f4e4a19e4b07f02db605716?f=03%2Fb4%2F1e%2F03b41ea45c1efd4e83992c806f77ce6a53fa3b5c';
		const dbfFileUrl = 'https://www.sciencebase.gov/catalog/file/get/4f4e4a19e4b07f02db605716?f=c6%2Fd4%2Fbc%2Fc6d4bc0d36c05a349a658788943cdb215451b916';

		const reference = {};

		const shapeFileStream = request( shapeFileUrl );
		const dbfFileStream = request( dbfFileUrl );

		const averageGPS = function ( geometry ) {

			let polygon = geometry.type === 'Polygon';

			let turfPolygon = null;

			if ( polygon ) {
				turfPolygon = turf.polygon( geometry.coordinates );
			} else {
				turfPolygon = turf.multiPolygon( geometry.coordinates );
			}

			let center = turf.centerOfMass( turfPolygon );

			let precision = 1000000;

			return {
				latitude: Math.round( center.geometry.coordinates[ 1 ] * precision ) / precision,
				longitude: Math.round( center.geometry.coordinates[ 0 ] * precision ) / precision
			};

		};

		shapefile.open( new Readable().wrap( shapeFileStream ), new Readable().wrap( dbfFileStream ) )
			.then( source => {

				let more = true;

				async.doWhilst( ( done ) => {

					source.read()
						.then( result => {

							more = !result.done;

							if ( !more ) {
								return done();
							}

							let data = result.value;
							let properties = data.properties;
							let geometry = data.geometry;

							reference[ properties.NPA ] = {
								stateCode: properties.STATE,
								location: averageGPS( geometry )
							};

							done();

						} )
						.catch( done );

				}, () => more, ( err ) => {
					if ( err ) {
						return done( err );
					}
					done( null, reference );
				} );

			} )
			.catch( done );

	},
	nanpa: function ( done ) {

		async.waterfall( [
			( done ) => {

				const referenceDatabase = {};

				const areaCodeReportURL = 'https://www.nationalnanpa.com/nanp1/npa_report.csv';

				request( areaCodeReportURL )
					.pipe( parse( {
						skipLines: 1
					} ) )
					.on( 'data', data => {

						if (
							data &&
							typeof data.NPA_ID === 'string' &&
							data.NPA_ID.match( /^[0-9]{3}$/ )
						) {

							let type = 'local';

							if (
								data.SERVICE.toLowerCase().match( 'toll-free' ) ||
								data.SERVICE.toLowerCase().match( 'toll free' ) ||
								data.NOTES.toLowerCase().match( 'toll-free' ) ||
								data.NOTES.toLowerCase().match( 'toll free' )
							) {
								type = 'toll-free';
							}

							if ( data.COUNTRY !== 'US' && type !== 'toll-free' ) {
								return;
							}

							let state = null;

							if ( data.LOCATION.trim().length === 2 ) {
								state = data.LOCATION.trim();
							} else if ( type !== 'toll-free' ) {
								return;
							}

							referenceDatabase[ data.NPA_ID ] = {
								type: type,
								stateCode: state
							};

						}

					} )
					.on( 'error', done )
					.on( 'end', () => {
						done( null, referenceDatabase );
					} );

			},
			( nanpa, done ) => {

				async.mapValuesLimit( nanpa, 10, ( record, areaCode, done ) => {

					async.waterfall( [
						( done ) => {
							request( {
								url: 'https://nationalnanpa.com/enas/displayNpaCityReport.do',
								method: 'POST',
								form: {
									npaId: areaCode
								}
							}, done );
						},
						( response, html, done ) => {

							if ( !response || response.statusCode !== 200 ) {
								console.error( 'Could not get city data for area code', areaCode );
								return done( null, record );
							}

							const $ = cheerio.load( html );

							const $table = $( 'tr.tableSubHead' ).parent();

							$table.children( 'tr' ).each( function ( i ) {

								if ( i === 0 || i > 1 ) {
									return;
								}

								const fields = [];
								$( this ).children( 'td' ).each( function () {
									fields.push( $( this ).text().trim() );
								} );

								if ( fields.length === 4 ) {
									record.city = toTitleCase( fields[ 1 ] );
								}

							} );

							done( null, record );
						}
					], done );

				}, done );

			}
		], done );

	}
};


text:
<!-- #docplaster -->
<!-- #docregion full -->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <!-- #docregion base -->
    <base href="/app/">
    <!-- #enddocregion base -->
    <title>Google Phone Gallery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <link rel="stylesheet" href="app.css" />

    <script src="/node_modules/core-js/client/shim.min.js"></script>
    <script src="/node_modules/zone.js/dist/zone.js"></script>
    <script src="/node_modules/systemjs/dist/system.src.js"></script>
    <!-- #enddocregion full -->
    <script src="/systemjs.config.1.js"></script>
    <!-- #docregion full
    <script src="/systemjs.config.js"></script>
    <script>
      System.import('/app');
    </script>
    <!-- #enddocregion full -->
    <script>
      System.import('/app');
    </script>
    <!-- #docregion full -->
  </head>
  <!-- #docregion appcomponent -->
  <body>
    <phonecat-app></phonecat-app>
  </body>
  <!-- #docregion appcomponent -->
</html>
<!-- #enddocregion full -->


text:
* [brew.sh](#brew.sh)

## brew.sh
------------
```bash
sh ./brew.sh
```

### My Cask Installed Apps

macOS apps with GUIs are downloaded using [Hombrew-Cask](https://github.com/caskroom/homebrew-cask).

* [alfred 3](https://www.alfredapp.com/)
* [atom](https://atom.io/)
* [bartender 2](https://www.macbartender.com/)
* [cheatsheet](https://www.mediaatelier.com/CheatSheet/)
* [CleanMyMac 3](http://macpaw.com/cleanmymac)
* [Cloud App](https://www.getcloudapp.com/)
* [dash](https://kapeli.com/dash)
* [f.lux](https://justgetflux.com/)
* [Google Chrome](https://www.google.com/chrome/)
* [Google Drive](https://www.google.com/drive/download/)
* [hyper.js](https://hyper.is/)
* [Postman](https://www.getpostman.com/)
* [RightFont](https://rightfontapp.com/)
* [Sketch](https://www.sketchapp.com/)

### My Cask Install Fonts

* [Roboto](https://fonts.google.com/specimen/Roboto)

### My mas-cli installed Mac Store Apps

Mac store apps are downloaded using [mas cli](https://github.com/mas-cli/mas)

* [Amphetamine](https://itunes.apple.com/us/app/amphetamine/id937984704?mt=12)
* [Day One](http://dayoneapp.com/)
* [Deliveries](http://junecloud.com/software/mac/deliveries.html)
* [Fantastical 2](https://flexibits.com/fantastical)
* [GoodNotes](http://www.goodnotesapp.com/)
* [Magnet](http://magnet.crowdcafe.com/)
* [Noizio](http://noiz.io/)
* [Raindrop.io](https://raindrop.io/)
* [Sip](http://sipapp.io/)
* [Slack](https://slack.com/)
* [Spark](https://sparkmailapp.com/)
* [Ulysses](https://ulyssesapp.com/)
* [Xcode](https://developer.apple.com/xcode/)


text:
YakBox
======

A YakBak emulator for Android. Record sounds, play them back in forward
and reverse, at various speeds.

# Bugs
- Recording & rotating device can sometimes cause crash, then can't
  reopen app until after reboot (can't init audio record).
    + Sometimes this happens even without rotating the device

# Todo
- post-release cleanup - code analysis
- too much processing being done on UI thread?
- write test for share
- highlight selected items in load screen
    + can't simply make a background color selector, as this overrides
      long click animation
- 'load' fragment for bigger screens
- user can rename shared recording?
- share:
    + facebook: https://developers.facebook.com/docs/sharing/android
        * can't share audio files directly. Upload to soundcloud?
    + twitter: same as fb
- centralise error toasts, put error messages in string resources
- file io on separate thread
- change to MVP architecture
- options / settings
    + don't rotate screen
    + normalise recordings
    + strip silence @ start & end


text:
package com.danidemi.templategeneratormavenplugin.generation.impl;

import com.danidemi.templategeneratormavenplugin.model.ContextModel;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;

public class EasyMerger {

    public EasyMerger() {

    }

    public StringWriter mergeTemplateIntoStringWriter(Reader inputStreamReader, ContextModel context) {
        StringWriter sw = new StringWriter();
        final VelocityContext vcontext = new VelocityContext();
        vcontext.put("source", context);
        Velocity.evaluate(vcontext, sw, "logtag", inputStreamReader);
        return sw;
    }

    public StringWriter mergeTemplateIntoStringWriter(String inputStreamReader, ContextModel contextModel) {
        return mergeTemplateIntoStringWriter( new StringReader(inputStreamReader), contextModel );
    }
}


text:
package com.wei.you.zhihu.spider.controller.v1;

import javax.validation.constraints.NotNull;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wei.you.zhihu.spider.dto.ResultDTO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-06-06T20:25:53.736+08:00")
@RequestMapping(value = "/zhihu/api/v1")
@Api(value = "user", description = "the user API")
public interface UserApi {

	@ApiOperation(value = "用户新增", notes = "用户新增", response = ResultDTO.class, tags = { "ZhihuUser", })
	@ApiResponses(value = { @ApiResponse(code = 200, message = "返回应用服务器的请求列表", response = ResultDTO.class),
			@ApiResponse(code = 200, message = "返回错误信息", response = ResultDTO.class) })

	@RequestMapping(value = "/user/add", produces = { "application/json" }, method = RequestMethod.POST)
	public ResponseEntity<ResultDTO> userAddPost(
			@NotNull @ApiParam(value = "用户名", required = false, defaultValue = "夕阳晚晴") @RequestParam(value = "username", required = false) String username,
			@NotNull @ApiParam(value = "user token", required = false, defaultValue = "xi-yang-wan-qing-30") @RequestParam(value = "userToken", required = false) String userToken,
			@NotNull @ApiParam(value = "位置", required = false) @RequestParam(value = "location", required = false) String location,
			@NotNull @ApiParam(value = "行业", required = false, defaultValue = "互联网") @RequestParam(value = "business", required = false) String business,
			@NotNull @ApiParam(value = "性别", required = false, defaultValue = "male") @RequestParam(value = "sex", required = false) String sex,
			@NotNull @ApiParam(value = "企业", required = false) @RequestParam(value = "employment", required = false) String employment,
			@NotNull @ApiParam(value = "教育", required = false) @RequestParam(value = "education", required = false) String education,
			@NotNull @ApiParam(value = "用户首页url", required = false, defaultValue = "https://www.zhihu.com/people/xi-yang-wan-qing-30/activities") @RequestParam(value = "url", required = false) String url,
			@NotNull @ApiParam(value = "答案赞同数", required = false, defaultValue = "0") @RequestParam(value = "agrees", required = false) Integer agrees,
			@NotNull @ApiParam(value = "感谢数", required = false, defaultValue = "0") @RequestParam(value = "thanks", required = false) Integer thanks,
			@NotNull @ApiParam(value = "提问数", required = false, defaultValue = "0") @RequestParam(value = "asks", required = false) Integer asks,
			@NotNull @ApiParam(value = "回答数", required = false, defaultValue = "0") @RequestParam(value = "answers", required = false) Integer answers,
			@NotNull @ApiParam(value = "文章数", required = false, defaultValue = "0") @RequestParam(value = "posts", required = false) Integer posts,
			@NotNull @ApiParam(value = "关注人数", required = false, defaultValue = "1") @RequestParam(value = "followees", required = false) Integer followees,
			@NotNull @ApiParam(value = "粉丝数量", required = false, defaultValue = "0") @RequestParam(value = "followers", required = false) Integer followers,
			@NotNull @ApiParam(value = "用户唯一标识", required = false, defaultValue = "88fb5d79df5a332cf16c8f8ad659dcf4") @RequestParam(value = "hashId", required = false) String hashId);

	@ApiOperation(value = "用户删除", notes = "用户删除", response = ResultDTO.class, tags = { "ZhihuUser", })
	@ApiResponses(value = { @ApiResponse(code = 200, message = "返回应用服务器的请求列表", response = ResultDTO.class),
			@ApiResponse(code = 200, message = "返回错误信息", response = ResultDTO.class) })

	@RequestMapping(value = "/user/delete", produces = { "application/json" }, method = RequestMethod.DELETE)
	ResponseEntity<ResultDTO> userDeleteDelete(
			@NotNull @ApiParam(value = "用户id", required = true) @RequestParam(value = "id", required = true) String id);

	@ApiOperation(value = "用户获取", notes = "用户获取", response = ResultDTO.class, tags = { "ZhihuUser", })
	@ApiResponses(value = { @ApiResponse(code = 200, message = "返回应用服务器的请求列表", response = ResultDTO.class),
			@ApiResponse(code = 200, message = "返回错误信息", response = ResultDTO.class) })

	@RequestMapping(value = "/user/get", produces = { "application/json" }, method = RequestMethod.GET)
	ResponseEntity<ResultDTO> userGetGet(
			@NotNull @ApiParam(value = "用户id", required = true, defaultValue = "8619") @RequestParam(value = "id", required = true) String id);

	@ApiOperation(value = "用户修改", notes = "用户修改", response = ResultDTO.class, tags = { "ZhihuUser", })
	@ApiResponses(value = { @ApiResponse(code = 200, message = "返回应用服务器的请求列表", response = ResultDTO.class),
			@ApiResponse(code = 200, message = "返回错误信息", response = ResultDTO.class) })

	@RequestMapping(value = "/user/edit", produces = { "application/json" }, method = RequestMethod.PUT)
	ResponseEntity<ResultDTO> userEditPut(
			@NotNull @ApiParam(value = "用户id", required = true) @RequestParam(value = "id", required = true) String id,
			@NotNull @ApiParam(value = "用户名", required = false, defaultValue = "夕阳晚晴") @RequestParam(value = "username", required = false) String username,
			@NotNull @ApiParam(value = "user token", required = false, defaultValue = "xi-yang-wan-qing-30") @RequestParam(value = "userToken", required = false) String userToken,
			@NotNull @ApiParam(value = "位置", required = false) @RequestParam(value = "location", required = false) String location,
			@NotNull @ApiParam(value = "行业", required = false, defaultValue = "互联网") @RequestParam(value = "business", required = false) String business,
			@NotNull @ApiParam(value = "性别", required = false, defaultValue = "male") @RequestParam(value = "sex", required = false) String sex,
			@NotNull @ApiParam(value = "企业", required = false) @RequestParam(value = "employment", required = false) String employment,
			@NotNull @ApiParam(value = "教育", required = false) @RequestParam(value = "education", required = false) String education,
			@NotNull @ApiParam(value = "用户首页url", required = false, defaultValue = "https://www.zhihu.com/people/xi-yang-wan-qing-30/activities") @RequestParam(value = "url", required = false) String url,
			@NotNull @ApiParam(value = "答案赞同数", required = false, defaultValue = "0") @RequestParam(value = "agrees", required = false) Integer agrees,
			@NotNull @ApiParam(value = "感谢数", required = false, defaultValue = "0") @RequestParam(value = "thanks", required = false) Integer thanks,
			@NotNull @ApiParam(value = "提问数", required = false, defaultValue = "0") @RequestParam(value = "asks", required = false) Integer asks,
			@NotNull @ApiParam(value = "回答数", required = false, defaultValue = "0") @RequestParam(value = "answers", required = false) Integer answers,
			@NotNull @ApiParam(value = "文章数", required = false, defaultValue = "0") @RequestParam(value = "posts", required = false) Integer posts,
			@NotNull @ApiParam(value = "关注人数", required = false, defaultValue = "1") @RequestParam(value = "followees", required = false) Integer followees,
			@NotNull @ApiParam(value = "粉丝数量", required = false, defaultValue = "0") @RequestParam(value = "followers", required = false) Integer followers,
			@NotNull @ApiParam(value = "用户唯一标识", required = false, defaultValue = "88fb5d79df5a332cf16c8f8ad659dcf4") @RequestParam(value = "hashId", required = false) String hashId);

	@ApiOperation(value = "用户展示", notes = "知乎用户列表", response = ResultDTO.class, tags = { "ZhihuUser", })
	@ApiResponses(value = { @ApiResponse(code = 200, message = "返回应用服务器的请求列表", response = ResultDTO.class),
			@ApiResponse(code = 200, message = "返回错误信息", response = ResultDTO.class) })

	@RequestMapping(value = "/user/list", produces = { "application/json" }, method = RequestMethod.GET)
	public ResponseEntity<ResultDTO> userListGet(
			@NotNull @ApiParam(value = "起始页", required = true) @RequestParam(value = "start", required = true, defaultValue = "1") int start,
			@NotNull @ApiParam(value = "页展示数", required = true) @RequestParam(value = "size", required = true, defaultValue = "6") int size);

}


text:
package org.locationtech.geowave.core.store.adapter;

import java.util.Arrays;
import org.locationtech.geowave.core.store.api.DataTypeAdapter;

/**
 * Given a transient store and a internal adapter store to use to map between internal IDs and
 * external IDs, we can wrap an implementation as a persistent adapter store
 */
public class AdapterStoreWrapper implements PersistentAdapterStore {
  private final TransientAdapterStore adapterStore;
  private final InternalAdapterStore internalAdapterStore;

  public AdapterStoreWrapper(
      final TransientAdapterStore adapterStore,
      final InternalAdapterStore internalAdapterStore) {
    this.adapterStore = adapterStore;
    this.internalAdapterStore = internalAdapterStore;
  }

  @Override
  public void addAdapter(final InternalDataAdapter<?> adapter) {
    adapterStore.addAdapter(adapter.getAdapter());
  }

  @Override
  public InternalDataAdapter<?> getAdapter(final Short adapterId) {
    if (adapterId == null) {
      return null;
    }
    final DataTypeAdapter<?> adapter =
        adapterStore.getAdapter(internalAdapterStore.getTypeName(adapterId));

    if (adapter instanceof InternalDataAdapter) {
      return (InternalDataAdapter<?>) adapter;
    }
    return adapter.asInternalAdapter(adapterId);
  }

  @Override
  public boolean adapterExists(final Short adapterId) {
    if (adapterId != null) {
      return internalAdapterStore.getTypeName(adapterId) != null;
    }
    return false;
  }

  @Override
  public InternalDataAdapter<?>[] getAdapters() {
    final DataTypeAdapter<?>[] adapters = adapterStore.getAdapters();
    return Arrays.stream(adapters).map(adapter -> {
      if (adapter instanceof InternalDataAdapter) {
        return (InternalDataAdapter<?>) adapter;
      }
      final Short adapterId = internalAdapterStore.getAdapterId(adapter.getTypeName());
      if (adapterId == null) {
        return null;
      }
      return adapter.asInternalAdapter(adapterId);
    }).toArray(InternalDataAdapter[]::new);
  }

  @Override
  public void removeAll() {
    adapterStore.removeAll();
  }

  @Override
  public void removeAdapter(final Short adapterId) {
    final String typeName = internalAdapterStore.getTypeName(adapterId);
    if (typeName != null) {
      adapterStore.removeAdapter(typeName);
    }
  }
}


text:
Variant ArrayPropertyEdit::get_array() const{

	Object*o = ObjectDB::get_instance(obj);
	if (!o)
		return Array();
	Variant arr=o->get(property);
	if (!arr.is_array()) {
		Variant::CallError ce;
		arr=Variant::construct(default_type,NULL,0,ce);
	}
	return arr;
}

void ArrayPropertyEdit::_notif_change() {
	_change_notify();
}
void ArrayPropertyEdit::_notif_changev(const String& p_v) {

	_change_notify(p_v.utf8().get_data());
}

void ArrayPropertyEdit::_set_size(int p_size) {

	Variant arr = get_array();
	arr.call("resize",p_size);
	Object*o = ObjectDB::get_instance(obj);
	if (!o)
		return;

	o->set(property,arr);

}

void ArrayPropertyEdit::_set_value(int p_idx,const Variant& p_value) {

	Variant arr = get_array();
	arr.set(p_idx,p_value);
	Object*o = ObjectDB::get_instance(obj);
	if (!o)
		return;

	o->set(property,arr);
}

bool ArrayPropertyEdit::_set(const StringName& p_name, const Variant& p_value){

	String pn=p_name;

	if (pn.begins_with("array/")) {

		if (pn=="array/size") {

			Variant arr = get_array();
			int size = arr.call("size");

			int newsize=p_value;
			if (newsize==size)
				return true;

			UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
			ur->create_action("Resize Array");
			ur->add_do_method(this,"_set_size",newsize);
			ur->add_undo_method(this,"_set_size",size);
			if (newsize<size) {
				for(int i=newsize;i<size;i++) {
					ur->add_undo_method(this,"_set_value",i,arr.get(i));

				}
			} else if (newsize>size && size) {

				Variant init;
				Variant::CallError ce;
				init = Variant::construct(arr.get(size-1).get_type(),NULL,0,ce);
				for(int i=size;i<newsize;i++) {
					ur->add_do_method(this,"_set_value",i,init);
				}

			}
			ur->add_do_method(this,"_notif_change");
			ur->add_undo_method(this,"_notif_change");
			ur->commit_action();
			return true;
		}
		if (pn=="array/page") {
			page=p_value;
			_change_notify();
			return true;
		}

	} else if (pn.begins_with("indices")) {

		if (pn.find("_")!=-1) {
			//type
			int idx=pn.get_slicec('/',1).get_slicec('_',0).to_int();

			int type = p_value;

			Variant arr = get_array();

			Variant value = arr.get(idx);
			if (value.get_type()!=type && type>=0 && type<Variant::VARIANT_MAX) {
				Variant::CallError ce;
				Variant new_value=Variant::construct(Variant::Type(type),NULL,0,ce);
				UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();

				ur->create_action("Change Array Value Type");
				ur->add_do_method(this,"_set_value",idx,new_value);
				ur->add_undo_method(this,"_set_value",idx,value);
				ur->add_do_method(this,"_notif_change");
				ur->add_undo_method(this,"_notif_change");
				ur->commit_action();

			}
			return true;

		} else {
			int idx=pn.get_slicec('/',1).to_int();
			Variant arr = get_array();

			Variant value = arr.get(idx);
			UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();

			ur->create_action("Change Array Value");
			ur->add_do_method(this,"_set_value",idx,p_value);
			ur->add_undo_method(this,"_set_value",idx,value);
			ur->add_do_method(this,"_notif_changev",p_name);
			ur->add_undo_method(this,"_notif_changev",p_name);
			ur->commit_action();
			return true;
		}
	}

	return false;
}

bool ArrayPropertyEdit::_get(const StringName& p_name,Variant &r_ret) const {

	Variant arr = get_array();
	//int size = arr.call("size");

	String pn=p_name;
	if (pn.begins_with("array/")) {

		if (pn=="array/size") {
			r_ret=arr.call("size");
			return true;
		}
		if (pn=="array/page") {
			r_ret=page;
			return true;
		}
	} else if (pn.begins_with("indices")) {

		if (pn.find("_")!=-1) {
			//type
			int idx=pn.get_slicec('/',1).get_slicec('_',0).to_int();
			bool valid;
			r_ret=arr.get(idx,&valid);
			if (valid)
				r_ret=r_ret.get_type();
			return valid;

		} else {
			int idx=pn.get_slicec('/',1).to_int();
			bool valid;
			r_ret=arr.get(idx,&valid);
			return valid;
		}
	}

	return false;
}

void ArrayPropertyEdit::_get_property_list( List<PropertyInfo> *p_list) const{

	Variant arr = get_array();
	int size = arr.call("size");

	p_list->push_back( PropertyInfo(Variant::INT,"array/size",PROPERTY_HINT_RANGE,"0,100000,1") );
	int pages = size/ITEMS_PER_PAGE;
	if (pages>0)
		p_list->push_back( PropertyInfo(Variant::INT,"array/page",PROPERTY_HINT_RANGE,"0,"+itos(pages)+",1") );

	int offset=page*ITEMS_PER_PAGE;

	int items=MIN(size-offset,ITEMS_PER_PAGE);

	for(int i=0;i<items;i++) {

		Variant v=arr.get(i+offset);
		if (arr.get_type()==Variant::ARRAY) {
			p_list->push_back(PropertyInfo(Variant::INT,"indices/"+itos(i+offset)+"_type",PROPERTY_HINT_ENUM,vtypes));
		}
		if (arr.get_type()!=Variant::ARRAY || v.get_type()!=Variant::NIL) {
			PropertyInfo pi(v.get_type(),"indices/"+itos(i+offset));
			if (v.get_type()==Variant::OBJECT) {
				pi.hint=PROPERTY_HINT_RESOURCE_TYPE;
				pi.hint_string="Resource";
			}
			p_list->push_back(pi);
		}
	}

}

void ArrayPropertyEdit::edit(Object* p_obj,const StringName& p_prop,Variant::Type p_deftype) {

	page=0;
	property=p_prop;
	obj=p_obj->get_instance_ID();
	default_type=p_deftype;

}

Node *ArrayPropertyEdit::get_node() {

	Object *o = ObjectDB::get_instance(obj);
	if (!o)
		return NULL;

	return o->cast_to<Node>();
}

void ArrayPropertyEdit::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("_set_size"),&ArrayPropertyEdit::_set_size);
	ObjectTypeDB::bind_method(_MD("_set_value"),&ArrayPropertyEdit::_set_value);
	ObjectTypeDB::bind_method(_MD("_notif_change"),&ArrayPropertyEdit::_notif_change);
	ObjectTypeDB::bind_method(_MD("_notif_changev"),&ArrayPropertyEdit::_notif_changev);
}

ArrayPropertyEdit::ArrayPropertyEdit()
{
	page=0;
	for(int i=0;i<Variant::VARIANT_MAX;i++) {

		if (i>0)
			vtypes+=",";
		vtypes+=Variant::get_type_name( Variant::Type(i) );
	}
	default_type=Variant::NIL;

}


text:
layout: page
title: Seattle Police Officer 6848 Terry C. Bailey
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/6848/
---

**Age as of Feb. 24, 2016:** 37


text:
"""Grupowanie hierarchiczne."""

class Bicluster:
    """
    Reprezentacja skupienia. Pole vec to uśredniony wektor (średnia
    uśrednionych wektorów obu podskupień), left - pierwsze
    podskupienie, right - drugie podskupienie, distance - odległość
    między podskupieniami, cluster_id - identyfikator skupienia.
    Dla "zdegenerowanego" skupienia jednoelementowego: left=right=None,
    vec jest po prostu jedynym elementem skupienia.
    """
    def __init__(self, vec, left=None, right=None, cluster_id=None):
        self.left = left
        self.right = right
        self.vec = vec
        self.cluster_id = cluster_id
        self.distance = None

    @staticmethod
    def create_one_element_cluster(vec, cluster_id=None):
        """Pomocnicza metoda zwracająca skupienie jednoelementowe."""
        return Bicluster(vec, cluster_id=cluster_id)

    def set_distance(self, distance):
        """
        Ustawia pomocnicze pole określające odległość między podskupieniami.
        """
        self.distance = distance

    def __eq__(self, other):
        if other:
            return (self.left == other.left
                    and self.right == other.right
                and self.vec == other.vec
                and self.cluster_id == other.cluster_id
                and self.distance == other.distance)
        else:
            return False

def average_vector_cluster_distance(first_cluster, second_cluster, distance):
    """
    Prosta funkcja określająca odległość między skupieniami
    `first_cluster` i `second_cluster` jako odległość między
    uśrednionymi wektorami. Distance to dowolna funkcja odległości
    (działająca na obiektach).
    """
    return distance(first_cluster.vec, second_cluster.vec)


text:
Structure:

```
 -----------------------------------------
| packetId | packetType | data | checksum |
 -----------------------------------------

packetId -> 4 bytes
packetType -> 4 bytes
data -> arbitrary size
checksum -> 4 bytes
```

`Packet::new(byte[], int)` and `Packet::getBytes` need to be implemented to support the above structure. The `jsocket.util.ByteUtil` class can be helpful in converting `byte[] -> int` and vice versa.

Any ACK will have a `packetId` of the original packet. Any received ACK should be validated with matching `packetId`. In addition, all sequence of packets must start with a START packet type and end with a END packet type. This is more for simplicity of code. The middle packets can be a PACKET type.


text:
require 'yaml'
require 'open-uri'
require 'hashie'
require 'pry'
require 'rainbow'
require 'securerandom'

require 'dsf/options'
require 'dsf/system_configuration'
require 'dsf/command/wrapper/metrics'
require 'dsf/command/base_command'
require 'dsf/command/setup'
require 'dsf/command/listen'
require 'dsf/command/exec'
require 'dsf/command/inspect'
require 'dsf/observers/console.rb'
require 'dsf/observers/publisher.rb'
require 'dsf/rabbit/publisher'
require 'dsf/rabbit/subscriber'
require 'dsf/redis/helper.rb'

module DSF

  def self.run
    # TODO: Move this to Exec class after refactoring
    options.unit = :init
    options.stdin_payload = $stdin.tty? ? '' : ARGF.read.chomp

    DSF::Command::BaseCommand.build(system_config, options).execute
  end

  def self.options
    @options ||= Options.new.parse(ARGV)
  end

  def self.system_config
    @system_config ||= DSF::SystemConfiguration.new(YAML.load(open(options.file)))
  end

end


text:
#ifndef QT_MAC_P_H
#define QT_MAC_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "qmacdefines_mac.h"

#ifdef __OBJC__
#include <Cocoa/Cocoa.h>
#ifdef QT_MAC_USE_COCOA
#include <objc/runtime.h>
#endif // QT_MAC_USE_COCOA
#endif

#include <CoreServices/CoreServices.h>

#include "QtCore/qglobal.h"
#include "QtCore/qvariant.h"
#include "QtCore/qmimedata.h"
#include "QtCore/qpointer.h"
#include "private/qcore_mac_p.h"

#include "QtGui/qpainter.h"

#include <Carbon/Carbon.h>

QT_BEGIN_NAMESPACE
class QWidget;
class QDragMoveEvent;

/* Event masks */
// internal Qt types

 // Event class for our own Carbon events.
#if defined(QT_NAMESPACE) && defined(QT_NAMESPACE_MAC_CRC)
// Take the CRC we generated at configure time. This *may* result in a
// collision with another value If that is the case, please change the value
// here to something other than 'Cute'.
const UInt32 kEventClassQt = QT_NAMESPACE_MAC_CRC;
#else
const UInt32 kEventClassQt = 'Cute';
#endif

enum {
    //AE types
    typeAEClipboardChanged = 1,
    //types
    typeQWidget = 1,  /* QWidget *  */
    //params
    kEventParamQWidget = 'qwid',   /* typeQWidget */
    //events
    kEventQtRequestContext = 13,
    kEventQtRequestMenubarUpdate = 14,
    kEventQtRequestShowSheet = 17,
    kEventQtRequestActivate = 18,
    kEventQtRequestWindowChange = 20
};

// Simple class to manage short-lived regions
class QMacSmartQuickDrawRegion
{
    RgnHandle qdRgn;
    Q_DISABLE_COPY(QMacSmartQuickDrawRegion)
public:
    explicit QMacSmartQuickDrawRegion(RgnHandle rgn) : qdRgn(rgn) {}
    ~QMacSmartQuickDrawRegion() {
        extern void qt_mac_dispose_rgn(RgnHandle); // qregion_mac.cpp
        qt_mac_dispose_rgn(qdRgn);
    }
    operator RgnHandle() {
        return qdRgn;
    }
};

// Class for chaining to gether a bunch of fades. It pretty much is only used for qmenu fading.
class QMacWindowFader
{
    QWidgetList m_windowsToFade;
    float m_duration;
    Q_DISABLE_COPY(QMacWindowFader)
public:
    QMacWindowFader(); // PLEASE DON'T CALL THIS.
    static QMacWindowFader *currentFader();
    void registerWindowToFade(QWidget *window);
    void setFadeDuration(float durationInSecs) { m_duration = durationInSecs; }
    float fadeDuration() const { return m_duration; }
    void performFade();
};

class Q_GUI_EXPORT QMacCocoaAutoReleasePool
{
private:
    void *pool;
public:
    QMacCocoaAutoReleasePool();
    ~QMacCocoaAutoReleasePool();

    inline void *handle() const { return pool; }
};

QString qt_mac_removeMnemonics(const QString &original); //implemented in qmacstyle_mac.cpp

class Q_GUI_EXPORT QMacWindowChangeEvent
{
private:
    static QList<QMacWindowChangeEvent*> *change_events;
public:
    QMacWindowChangeEvent() {
    }
    virtual ~QMacWindowChangeEvent() {
    }
    static inline void exec(bool ) {
    }
protected:
    virtual void windowChanged() = 0;
    virtual void flushWindowChanged() = 0;
};

class QMacCGContext
{
    CGContextRef context;
public:
    QMacCGContext(QPainter *p); //qpaintengine_mac.cpp
    inline QMacCGContext() { context = 0; }
    inline QMacCGContext(const QPaintDevice *pdev) {
        extern CGContextRef qt_mac_cg_context(const QPaintDevice *);
        context = qt_mac_cg_context(pdev);
    }
    inline QMacCGContext(CGContextRef cg, bool takeOwnership=false) {
        context = cg;
        if(!takeOwnership)
            CGContextRetain(context);
    }
    inline QMacCGContext(const QMacCGContext &copy) : context(0) { *this = copy; }
    inline ~QMacCGContext() {
        if(context)
            CGContextRelease(context);
    }
    inline bool isNull() const { return context; }
    inline operator CGContextRef() { return context; }
    inline QMacCGContext &operator=(const QMacCGContext &copy) {
        if(context)
            CGContextRelease(context);
        context = copy.context;
        CGContextRetain(context);
        return *this;
    }
    inline QMacCGContext &operator=(CGContextRef cg) {
        if(context)
            CGContextRelease(context);
        context = cg;
        CGContextRetain(context); //we do not take ownership
        return *this;
    }
};

class QMacPasteboardMime;
class QMimeData;

class QMacPasteboard
{
    struct Promise {
        Promise() : itemId(0), convertor(0) { }
        Promise(int itemId, QMacPasteboardMime *c, QString m, QVariant d, int o=0) : itemId(itemId), offset(o), convertor(c), mime(m), data(d) { }
        int itemId, offset;
        QMacPasteboardMime *convertor;
        QString mime;
        QVariant data;
    };
    QList<Promise> promises;

    OSPasteboardRef paste;
    uchar mime_type;
    mutable QPointer<QMimeData> mime;
    mutable bool mac_mime_source;
    static OSStatus promiseKeeper(OSPasteboardRef, PasteboardItemID, CFStringRef, void *);
    void clear_helper();
public:
    QMacPasteboard(OSPasteboardRef p, uchar mime_type=0);
    QMacPasteboard(uchar mime_type);
    QMacPasteboard(CFStringRef name=0, uchar mime_type=0);
    ~QMacPasteboard();

    bool hasFlavor(QString flavor) const;
    bool hasOSType(int c_flavor) const;

    OSPasteboardRef pasteBoard() const;
    QMimeData *mimeData() const;
    void setMimeData(QMimeData *mime);

    QStringList formats() const;
    bool hasFormat(const QString &format) const;
    QVariant retrieveData(const QString &format, QVariant::Type) const;

    void clear();
    bool sync() const;
};

extern QPaintDevice *qt_mac_safe_pdev; //qapplication_mac.cpp

extern OSWindowRef qt_mac_window_for(const QWidget*); //qwidget_mac.mm
extern OSViewRef qt_mac_nativeview_for(const QWidget *); //qwidget_mac.mm
extern QPoint qt_mac_nativeMapFromParent(const QWidget *child, const QPoint &pt); //qwidget_mac.mm

#ifdef check
# undef check
#endif

QFont qfontForThemeFont(ThemeFontID themeID);

QColor qcolorForTheme(ThemeBrush brush);

QColor qcolorForThemeTextColor(ThemeTextColor themeColor);

struct QMacDndAnswerRecord {
    QRect rect;
    Qt::KeyboardModifiers modifiers;
    Qt::MouseButtons buttons;
    Qt::DropAction lastAction;
    unsigned int lastOperation;
    void clear() {
        rect = QRect();
        modifiers = Qt::NoModifier;
        buttons = Qt::NoButton;
        lastAction = Qt::IgnoreAction;
        lastOperation = 0;
    }
};
extern QMacDndAnswerRecord qt_mac_dnd_answer_rec;
void qt_mac_copy_answer_rect(const QDragMoveEvent &event);
bool qt_mac_mouse_inside_answer_rect(QPoint mouse);

QT_END_NAMESPACE

#endif // QT_MAC_P_H