text:
require 'shoes/spec_helper'

describe Shoes::InternalApp do
  include_context "dsl app"

  subject { app }

  describe "#initialize" do
    context "with defaults" do
      let(:defaults) { Shoes::InternalApp::DEFAULT_OPTIONS }

      it "sets title", :qt do
        expect(subject.app_title).to eq defaults[:title]
      end

      it "is resizable", :qt do
        expect(subject.resizable).to be_truthy
      end

      it "sets width" do
        expect(subject.width).to eq(defaults[:width])
      end

      it "sets height" do
        expect(subject.height).to eq(defaults[:height])
      end

      it "does not start as fullscreen" do
        expect(subject.start_as_fullscreen?).to be_falsey
      end
    end

    context "with custom opts" do
      let(:input_opts) { {:width => 150, :height => 2, :title => "Shoes::App Spec", :resizable => false} }

      it "sets title", :qt do
        expect(subject.app_title).to eq input_opts[:title]
      end

      it "sets resizable", :qt do
        expect(subject.resizable).to be_falsey
      end

      it "sets width" do
        expect(subject.width).to eq(input_opts[:width])
      end

      it "sets height" do
        expect(subject.height).to eq(input_opts[:height])
      end
    end
  end

  describe 'fullscreen' do
    let(:input_opts) { {:fullscreen => true} }

    it "sets fullscreen" do
      expect(subject.start_as_fullscreen?).to be_truthy
    end
  end

  describe '#contents' do
    it 'delegates to top_slot' do
      expect(subject.contents).to be(subject.top_slot.contents)
    end
  end

  describe '#clear' do
    context 'when called after the initial input block' do
      let(:input_block) {
        Proc.new do
          para "CONTENT"
          para "JUST FOR TESTING"
        end
      }

      before :each do
        expect(subject.contents.size).to eq(2)
      end

      it 'clears top_slot' do
        subject.clear
        expect(subject.contents).to be_empty
      end
    end

    context 'when called in the initial input_block' do
      let(:input_block) {
        Proc.new do
          para 'Hello there'
          clear do
            para 'see you'
          end
        end
      }

      it 'does not raise an error' do
        expect {subject}.not_to raise_error
      end

      context 'when called inside a slot' do
        let(:input_block) {
          Proc.new do
            button 'I am here'
            stack do
              button 'Hi there'
              button 'Another one'
              clear
            end
          end
        }

        it 'does not delete the slot, or an element outside the slot' do
          expect(subject.contents.size).to eq 2
        end
      end
    end

    context 'when called before a button in an initial input block' do
      let(:input_block) {
        Proc.new do
          clear
          button 'My Button'
        end
      }

      it 'allows a button to be created' do
        expect(subject.contents.size).to eq(1)
      end

      describe 'the button' do
        let(:button) { subject.contents.first }

        it 'has the top_slot as its parent' do
          expect(button.parent).to eq subject.top_slot
        end
      end
    end

  end
end


text: export const config = 'hello'

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ConnectHolland\TulipAPI\Exception;

/**
 * UnknownErrorException.
 *
 * @author Niels Nijens <niels@connectholland.nl>
 */
class UnknownErrorException extends RequestException
{
}


text:
package com.dianping.zebra.shard.jdbc;

import com.dianping.zebra.shard.jdbc.base.MultiDBBaseTestCase;
import org.junit.Assert;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.*;

/**
 * Created by wxl on 17/4/21.
 */

public class ShardRangeDefaultTest extends MultiDBBaseTestCase {

    @Override
    protected String getDBBaseUrl() {
        return "jdbc:h2:mem:";
    }

    @Override
    protected String getCreateScriptConfigFile() {
        return "mockdb-config/testRangeDefault/createtable-multidb-rangetest.xml";
    }

    @Override
    protected String getDataFile() {
        return "mockdb-config/testRangeDefault/data-multidb-rangetest.xml";
    }

    @Override
    protected String[] getSpringConfigLocations() {
        return new String[] {"mockdb-config/testRangeDefault/ctx-multidb-rangetest.xml"};
    }

    public DataSource getDataSource() {
        return (DataSource) context.getBean("zebraDS");
    }

    /**
     *           DATE          | DB | TB
     * ------------------------+----+------
     *            - 2010-01-09 |  0 |  4
     * ------------------------+----+------
     * 2010-01-10 — 2010-06-30 |  0 |  0
     * ------------------------+----+------
     * 2010-07-01 — 2010-12-31 |  0 |  1
     * ------------------------+----+------
     * 2011-01-01 — 2011-06-30 |  0 |  2
     * ------------------------+----+------
     * 2011-07-01 — 2011-12-31 |  0 |  3
     * ------------------------+----+------
     * 2012-01-01 — 2012-06-30 |  1 |  0
     * ------------------------+----+------
     * 2012-07-01 — 2012-12-31 |  1 |  1
     * ------------------------+----+------
     * 2013-01-01 — 2013-06-30 |  1 |  2
     * ------------------------+----+------
     * 2013-07-01 — 2013-12-20 |  1 |  3
     * ------------------------+----+------
     * 2013-12-21 -            |  0 |  4
     *
     */
    @Test
    public void testCross() throws SQLException {

        DataSource ds = getDataSource();
        Connection conn = ds.getConnection();
        Statement stmt = conn.createStatement();
        PreparedStatement pst = conn.prepareStatement("SELECT COUNT(*) FROM `TestTable` WHERE `createtime` = ?");
        String sql;
        ResultSet rs;

        pst.setDate(1, new Date(1264953600000L));
        rs = pst.executeQuery();
        while (rs.next()) {
            Assert.assertEquals(1, rs.getInt(1));
        }

        checkAllCount(stmt, 8);
        checkCountLess(stmt, "2010-01-10", 0, false);
        checkCountGreater(stmt, "2013-12-20", 0, false);

        checkCountBetween(stmt, "2010-01-10", "2011-12-20", 4);
        checkCountBetween(stmt, "2010-01-10", "2011-07-31", 3);
        checkCountBetween(stmt, "2012-01-10", "2013-12-20", 4);
        checkCountBetween(stmt, "2012-01-10", "2013-07-31", 3);

        checkCountBetween(stmt, "2010-06-01", "2010-06-30", 0);
        innerInsert(stmt, 1, "t-0-1_a", 1, "2010-06-30");
        checkAllCount(stmt, 9);
        checkCountBetween(stmt, "2010-06-01", "2010-06-30", 1);

        innerInsert(stmt, 1, "t-0-4", 1, "2010-01-09");
        checkAllCount(stmt, 10);
        checkCountLess(stmt, "2010-01-10", 1, false);
        checkCountGreater(stmt, "2010-01-10", 9, true);

        innerInsert(stmt, 1, "t-1-2_a", 1, "2012-12-31");
        checkAllCount(stmt, 11);
        checkCountBetween(stmt, "2012-07-01", "2012-12-31", 2);
        checkCountEqual(stmt, "2012-08-01", 1);

        innerDelete(stmt, "2012-08-01");
        checkAllCount(stmt, 10);
        checkCountEqual(stmt, "2012-08-01", 0);

        sql = "SELECT * FROM `TestTable` WHERE `createtime` = '2010-06-30'";
        rs = stmt.executeQuery(sql);
        if (rs.next()) {
            Assert.assertEquals("t-0-1_a", rs.getString(3));
        } else {
            Assert.assertTrue(false);
        }
        innerUpdate(stmt, "2010-06-30", "Name", "'t-0-1_b'");
        sql = "SELECT * FROM `TestTable` WHERE `createtime` = '2010-06-30'";
        rs = stmt.executeQuery(sql);
        if (rs.next()) {
            Assert.assertEquals("t-0-1_b", rs.getString(3));
        } else {
            Assert.assertTrue(false);
        }

        stmt.close();
        conn.close();
    }

    private void innerUpdate(Statement stmt, String createTime, String column, String value) throws SQLException {
        String sql = "UPDATE `TestTable` SET `"+column+"` = "+value+" WHERE `CreateTime` = '"+createTime+"'";
        stmt.execute(sql);
    }

    private void innerDelete(Statement stmt, String time) throws SQLException{
        String sql = "delete from `TestTable` WHERE `CreateTime` ='"+time+"'";
        stmt.execute(sql);
    }

    private void innerInsert(Statement stmt, int id, String name, int age, String time) throws SQLException{
        String sql = "insert into `TestTable`(id, name, age, createtime) " +
                "values ("+id+", '"+name+"', "+age+", '"+time+"')";
        stmt.execute(sql);
    }

    private void checkCountGreater(Statement stmt, String start, int count, boolean isInclusive) throws SQLException {
        String sql = "SELECT COUNT(*) FROM `TestTable` WHERE `createtime` > '"+start+"'";
        if(isInclusive) {
            sql = "SELECT COUNT(*) FROM `TestTable` WHERE `createtime` >= '"+start+"'";
        }
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            Assert.assertEquals(count, rs.getInt(1));
        }
    }

    private void checkCountLess(Statement stmt, String start, int count, boolean isInclusive) throws SQLException {
        String sql = "SELECT COUNT(*) FROM `TestTable` WHERE `createtime` < '"+start+"'";
        if(isInclusive) {
            sql = "SELECT COUNT(*) FROM `TestTable` WHERE `createtime` <= '"+start+"'";
        }
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            Assert.assertEquals(count, rs.getInt(1));
        }
    }

    @SuppressWarnings("unused")
    private void checkCountByRange(Statement stmt, String start, String end, int count) throws SQLException {
        String sql = "SELECT COUNT(*) FROM `TestTable` WHERE `createtime` >= '"+start+"' AND `createtime` <= '"+end+"'";
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            Assert.assertEquals(count, rs.getInt(1));
        }
    }

    private void checkCountBetween(Statement stmt, String start, String end, int count) throws SQLException {
        String sql = "SELECT COUNT(*) FROM `TestTable` WHERE `createtime` BETWEEN '"+start+"' AND '"+end+"'";
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            Assert.assertEquals(count, rs.getInt(1));
        }
    }

    @SuppressWarnings("unused")
    private void checkCountByRange(Statement stmt, String start, boolean startInclusive, String end, boolean endInclusive, int count) throws SQLException {
        String sql = "SELECT COUNT(*) FROM `TestTable` WHERE `createtime` > '"+start+"'";
        if(startInclusive) {
            sql = "SELECT COUNT(*) FROM `TestTable` WHERE `createtime` >= '"+start+"'";
        }
        if(endInclusive) {
            sql += " AND `createtime` <= '"+end+"'";
        } else {
            sql += " AND `createtime` < '"+end+"'";
        }
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            Assert.assertEquals(count, rs.getInt(1));
        }
    }

    private void checkCountEqual(Statement stmt,  String start, int count) throws SQLException {
        String sql = "SELECT COUNT(*) FROM `TestTable` WHERE `CreateTime` = '"+start+"'";
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            Assert.assertEquals(count, rs.getInt(1));
        }
    }

    private void checkAllCount(Statement stmt, int count) throws SQLException {
        String sql = "SELECT COUNT(*) FROM `TestTable`";
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            Assert.assertEquals(count, rs.getInt(1));
        }
    }

}


text:
package javax.management.relation;

/**
 * This exception is raised when an invalid Relation Service is provided.
 *
 * @since 1.5
 */
public class InvalidRelationServiceException extends RelationException {

    /* Serial version */
    private static final long serialVersionUID = 3400722103759507559L;

    /**
     * Default constructor, no message put in exception.
     */
    public InvalidRelationServiceException() {
        super();
    }

    /**
     * Constructor with given message put in exception.
     *
     * @param message the detail message.
     */
    public InvalidRelationServiceException(String message) {
        super(message);
    }
}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_NETWORK_FORM_DATA_ENCODER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_NETWORK_FORM_DATA_ENCODER_H_

#include "third_party/blink/renderer/platform/network/encoded_form_data.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"

namespace WTF {
class TextEncoding;
}

namespace blink {

class PLATFORM_EXPORT FormDataEncoder {
  STATIC_ONLY(FormDataEncoder);

 public:
  // Specifies how to handle CRs and LFs. When NormalizeCRLF is passed, the
  // method replaces the following characters with a CRLF pair:
  // - a CR not followed by an LF
  // - an LF not preceded by a CR
  enum Mode { kNormalizeCRLF, kDoNotNormalizeCRLF };

  static WTF::TextEncoding EncodingFromAcceptCharset(
      const String& accept_charset,
      const WTF::TextEncoding& fallback_encoding);

  // Helper functions used by HTMLFormElement for multi-part form data
  static Vector<char> GenerateUniqueBoundaryString();
  static void BeginMultiPartHeader(Vector<char>&,
                                   const std::string& boundary,
                                   const std::string& name);
  static void AddBoundaryToMultiPartHeader(Vector<char>&,
                                           const std::string& boundary,
                                           bool is_last_boundary = false);
  static void AddFilenameToMultiPartHeader(Vector<char>&,
                                           const WTF::TextEncoding&,
                                           const String& filename);
  static void AddContentTypeToMultiPartHeader(Vector<char>&,
                                              const String& mime_type);
  static void FinishMultiPartHeader(Vector<char>&);

  // Helper functions used by HTMLFormElement for non multi-part form data. Mode
  // argument is not used for TextPlain type.
  static void AddKeyValuePairAsFormData(
      Vector<char>&,
      const std::string& key,
      const std::string& value,
      EncodedFormData::EncodingType = EncodedFormData::kFormURLEncoded,
      Mode = kNormalizeCRLF);
  static void EncodeStringAsFormData(Vector<char>&, const std::string&, Mode);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_NETWORK_FORM_DATA_ENCODER_H_


text:
from functools import wraps

def custom_api(allowed=None):
    """
    Decorator for customized api end point that does method check,
    authentication and throttle_check.

    Takes an ``allowed`` parameter, which should be a list of lowercase HTTP
    methods to check against.

    The func should return a dict as result data.
    """
    def _custom_api_decorator(func):
        @wraps(func)
        def _wrapper(self, request, **kwargs):
            self.method_check(request, allowed=allowed)
            self.is_authenticated(request)
            self.throttle_check(request)

            result = func(self, request, **kwargs)

            self.log_throttled_access(request)
            return self.create_response(request, result)
        return _wrapper
    return _custom_api_decorator


text:
package br.com.cybereagle.androidlibrary.util;

import java.util.List;

import android.database.Cursor;

public class CollectorUtils {

	private static final String REQUIRED_CONSTRUCTOR_MESSAGE = "O objeto deve possuir um construtor público sem argumentos";

	public static interface ObjectFiller<T>{
		void fill(T object, Cursor cursor);
	}

	public static <T> void collectFromCursor(List<T> objects, Cursor cursor, ObjectFiller<T> objectFiller, Class<T> clazz){
		int i=0;
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext(), i++) {
			T object = null;
			if(i < objects.size()){
				object = objects.get(i);
			}
			else{
				try {
					object = (T) clazz.newInstance();
					objects.add(object);
				} catch (InstantiationException e) {
					throw new IllegalArgumentException(REQUIRED_CONSTRUCTOR_MESSAGE);
				} catch (IllegalAccessException e) {
					throw new IllegalArgumentException(REQUIRED_CONSTRUCTOR_MESSAGE);
				}
			}
			objectFiller.fill(object, cursor);
		}
	}

}


text:
let expect = require('chai').expect;

import { RangeHelper } from '../../lib/range-helper';

describe('RangeHelper', function() {

    describe('#convertRangeToMinMaxObject', function() {

        it('should return a min/max-object for input with the format <min-max>', function() {
            let result = RangeHelper.convertRangeToMinMaxObject('3-7', false);
            expect(result.min).to.equal(3);
            expect(result.max).to.equal(7);
        });

        it('should return a min/max-object for input with the format <number>', function() {
            let result = RangeHelper.convertRangeToMinMaxObject('5', false);
            expect(result.min).to.equal(5);
            expect(result.max).to.equal(5);
        });

        it('should return the fallbackObject for invalid input', function() {
            let result = RangeHelper.convertRangeToMinMaxObject('invalid', {min: 3, max: 7});
            expect(result.min).to.equal(3);
            expect(result.max).to.equal(7);
        });

    });

});


text:
A REST API for arkweb.

## Endpoints

/health - Returns the string 'Ok'. Use to see if the site is up.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
LensSupport (jung2 2.0.1 API)
</TITLE>

<META NAME="keywords" CONTENT="edu.uci.ics.jung.visualization.transform.LensSupport interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

edu.uci.ics.jung.visualization.transform

Interface LensSupport

All Known Implementing Classes:
AbstractLensSupport, LayoutLensSupport, MagnifyImageLensSupport, ViewLensSupport

public interface LensSupport

basic API for implementing lens projection support

Author:

Tom Nelson

Method Summary

 void
activate()

 void
activate(boolean state)

 void
deactivate()

 ModalGraphMouse
getGraphMouse()

 LensTransformer
getLensTransformer()

Method Detail

activate

void activate()

deactivate

void deactivate()

activate

void activate(boolean state)

getLensTransformer

LensTransformer getLensTransformer()

getGraphMouse

ModalGraphMouse getGraphMouse()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2010 null. All Rights Reserved.


text:
module OpenID
  VERSION = "2.1.8"
end

require "openid/consumer"
require 'openid/server'


text: A suite of launch agents for OSX that I use on various computer.


text:
MPTransition
=====================
__Update__: MPTransition now comprises MPFoldTransition and MPFlipTransition

__Update 2__: For a touch gesture-enabled container controller with page-flipping (not just a transition), see [MPFlipViewController](https://github.com/mpospese/MPFlipViewController)

MPFoldTransition is a set of classes to add folding-style transitions to iOS 5 projects.
![iPhone Fold](http://markpospesel.files.wordpress.com/2012/05/iphone-fold2.png)
MPFlipTransition is a set of classes to add page-flipping transitions to iOS 5 projects.
![iPhone Flip](http://markpospesel.files.wordpress.com/2012/05/iphone-flip-3.png)
I built it using ARC (and for the demo portion storyboards) strictly for convenience, so it uses iOS 5.  I imagine the relevant code (minus the UIStoryboardSegue helper classes) could be easily ported to iOS 4.3 under ARC, or ported to iOS 4.0 with memory management inserted.  (_Hint:_ If you're porting to non-ARC, you'll need to retain [sourceView superView] in the init method.)

Features
---------
* Convenience methods to extend UIViewController to present/dismiss a view controller modally using fold/flip transitions
* Convenience methods to extend UINavigationController to push/pop view controllers onto the navigation stack using fold/flip transitions
* Convenience methods to transition between any 2 UIViewControllers or UIViews
* 3 Custom UIStoryboardSegue subclasses to easily add folding/flipping transitions via Interface Builder in your storyboards
* Fully customizable to adjust style, duration, timing curves, and completion action
* Blocks-based: many methods include a completion block parameter following the pattern of block-based animations introduced in iOS 4.

Fold Styles
---------
Currently there are 3 style bits that can be combined for 8 different styles.
* __Direction:__ Fold vs. Unfold
![Fold vs. Unfold](http://markpospesel.files.wordpress.com/2012/05/fold-vs-unfold2.png)
* __Mode:__ Normal vs. Cubic
![Normal vs. Cubic](http://markpospesel.files.wordpress.com/2012/05/normal-vs-cubic2.png)
* __Orientation:__ Vertical vs. Horizontal
![Vertical vs. Horizontal](http://markpospesel.files.wordpress.com/2012/05/vertical-vs-horizontal2.png)

Flip Styles
---------
Currently there are 3 style bits that can be combined for 8 different styles.
* __Direction:__ Forward vs. Backward
![Forward vs. Backward](http://markpospesel.files.wordpress.com/2012/05/forward-vs-backward-3.png)
* __Orientation:__ Horizontal vs. Vertical
![Horizontal vs. Vertical](http://markpospesel.files.wordpress.com/2012/05/horizontal-vs-vertical-3.png)
* __Perspective:__ Normal vs. Reverse
![Normal vs. Reverse](http://markpospesel.files.wordpress.com/2012/05/normal-vs-reverse-3.png)

Requirements
-----------
* Xcode 4.4 or higher
* LLVM compiler
* iOS 5 or higher

How To Use
---------
See the "MPFoldTransition.h" (and "MPFlipTransition.h") header file(s) for methods and use the demo project as a reference.  The Segue classes (under directory of the same name) are optional, only if you want to include storyboard support.  Otherwise you just need the classes under the bottommost MPFoldTransition directory.

Licensing
---------
Read Source Code License.rtf, but the gist is:
* Anyone can use it for any type of project
* All I ask for is attribution somewhere

Support, bugs and feature requests
----------------------------------
There is absolutely no support offered with this component. You're on your own! If you want to submit a feature request, please do so via [the issue tracker on github](https://github.com/mpospese/MPFoldTransition/issues).

If you want to submit a bug report, please also do so via the issue tracker, including a diagnosis of the problem and a suggested fix (in code). If you're using MPTransition, you're a developer - so I expect you to do your homework and provide a fix along with each bug report. You can also submit pull requests or patches.

Please don't submit bug reports without fixes!

(The preceding blurb provided courtesy of the legendary [Matt Gemmell](https://github.com/mattgemmell/))

Best,
Mark Pospesel

Website: http://markpospesel.com/
Contact: http://markpospesel.com/about
Twitter: http://twitter.com/mpospese
Hire Me: http://crazymilksoftware.com/


text:
import { commitMutation, Environment, graphql } from "relay-runtime"
import { FollowArtistMutation } from "__generated__/FollowArtistMutation.graphql"

export type FollowArtistMutationProps = (
  relayEnvironment: Environment,
  id: string,
  isFollowed?: boolean
) => Promise<unknown>

export const followArtistMutation: FollowArtistMutationProps = (
  relayEnvironment: Environment,
  id: string,
  isFollowed: boolean = false
) => {
  return new Promise((resolve, reject) => {
    commitMutation<FollowArtistMutation>(relayEnvironment, {
      onCompleted: (res, errors) => {
        if (errors !== null) {
          reject(errors)
          return
        }

        resolve(res)
      },
      mutation: graphql`
        mutation FollowArtistMutation($input: FollowArtistInput!)
          @raw_response_type {
          followArtist(input: $input) {
            artist {
              id
              isFollowed
            }
          }
        }
      `,
      // FIXME: Why is optimistic response not working in UI?
      optimisticResponse: {
        followArtist: {
          artist: {
            id,
            isFollowed: !isFollowed,
          },
        },
      },
      variables: {
        input: {
          artistID: id,
          unfollow: isFollowed,
        },
      },
    })
  })
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Biznes\DatabaseBundle\Entity\UsersAddresses" table="users_addresses">
    <unique-constraints>
      <unique-constraint name="id_user_UNIQUE" columns="id_user"/>
    </unique-constraints>
    <id name="idUserAddress" type="integer" column="id_user_address">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="street" type="string" column="street" length="35" nullable="false">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="nrHouse" type="string" column="nr_house" length="3" nullable="false">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="nrFlat" type="string" column="nr_flat" length="3" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="city" type="string" column="city" length="35" nullable="false">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="postCode" type="string" column="post_code" length="6" nullable="true">
      <options>
        <option name="fixed">1</option>
      </options>
    </field>
    <field name="country" type="string" column="country" length="30" nullable="false">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <many-to-one field="idUser" target-entity="Users" fetch="LAZY">
      <join-columns>
        <join-column name="id_user" referenced-column-name="id_user"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>


text:
require 'midpay'
module Midpay
  module Strategies
    class Kuaiqian

      GATEWAY = "https://www.99bill.com/gateway/recvMerchantInfoAction.htm"

      REQUEST_PARAM_KEYS = %w[
        inputCharset bgUrl pageUrl version language signType merchantAcctId
        payerName payerContactType payerContact orderId orderAmount orderTime
        productName productNum productId productDesc ext1 ext2 payType redoFlag pid
      ]

      RETURN_PARAM_KEYS = %w[
        merchantAcctId version language signType payType bankId orderId orderTime
        orderAmount dealId bankDealId dealTime payAmount fee ext1 ext2 payResult errorCode
      ]

      include Midpay::Strategy

      set :inputCharset, "1" #utf-8
      set :version, "v2.0"
      set :language, "1" #zh_CN
      set :signType, "1" #MD5
      set :payType, "00"
      set :redoFlag, "0"

      def request_phase response
        response.redirect kuaiqian_request_url
      end

      def callback_phase pi
        raise Midpay::Errors::InvalidSignature.new unless request_params[:sign] == request_params.sign(:signType){|h| kuaiqian_sign_str(RETURN_PARAM_KEYS,h) }
        pi.raw_data = request_params.symbolize_keys
        pi.success = (pi.raw_data['payResult'] == "10")
      end

      def kuaiqian_request_params
        params = request_data
        params.merge_if!(arguments.merge(merchantAcctId: options.app_key, pageUrl: callback_url))
        params.sign!(:signMsg, kuaiqian_sign_type(params[:signType])) do |hash|
          kuaiqian_sign_str(REQUEST_PARAM_KEYS, hash)
        end
      end

      def kuaiqian_request_url
        GATEWAY + '?' + kuaiqian_request_params.to_query
      end

      def kuaiqian_sign_str keys, hash
        keys.collect{|k| hash[k].to_s.empty? ? nil : [k, hash[k]]}.compact.push(["key",options.app_secret]).collect{|i| i.join("=") }.join("&")
      end

      def kuaiqian_sign_type sign_type
        {
          "1" => "MD5"
        }[sign_type.to_s]
      end
    end
  end
end
::Midpay[:kuaiqian] = ::Midpay::Strategies::Kuaiqian


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
Pilzthiere o. Schleimpilze, 127.

#### Original name
Aphelidium Zopf, 1885

### Remarks
null


text:
<?php

namespace Drupal\basic_auth\Tests;

@trigger_error(__NAMESPACE__ . '\BasicAuthTestTrait is deprecated in Drupal 8.3.0 and will be removed before Drupal 9.0.0. Use \Drupal\Tests\basic_auth\Traits\BasicAuthTestTrait instead. See https://www.drupal.org/node/2862800.', E_USER_DEPRECATED);

/**
 * Provides common functionality for Basic Authentication test classes.
 *
 * @deprecated in Drupal 8.3.0 and will be removed before Drupal 9.0.0.
 *   Use \Drupal\Tests\basic_auth\Traits\BasicAuthTestTrait instead.
 *
 * @see https://www.drupal.org/node/2862800
 */
trait BasicAuthTestTrait {

  /**
   * Retrieves a Drupal path or an absolute path using basic authentication.
   *
   * @param \Drupal\Core\Url|string $path
   *   Drupal path or URL to load into the internal browser.
   * @param string $username
   *   The username to use for basic authentication.
   * @param string $password
   *   The password to use for basic authentication.
   * @param array $options
   *   (optional) Options to be forwarded to the url generator.
   *
   * @return string
   *   The retrieved HTML string, also available as $this->getRawContent().
   */
  protected function basicAuthGet($path, $username, $password, array $options = []) {
    return $this->drupalGet($path, $options, $this->getBasicAuthHeaders($username, $password));
  }

  /**
   * Executes a form submission using basic authentication.
   *
   * @param string $path
   *   Location of the post form.
   * @param array $edit
   *   Field data in an associative array.
   * @param string $submit
   *   Value of the submit button whose click is to be emulated.
   * @param string $username
   *   The username to use for basic authentication.
   * @param string $password
   *   The password to use for basic authentication.
   * @param array $options
   *   Options to be forwarded to the url generator.
   * @param string $form_html_id
   *   (optional) HTML ID of the form to be submitted.
   * @param string $extra_post
   *   (optional) A string of additional data to append to the POST submission.
   *
   * @return string
   *   The retrieved HTML string.
   *
   * @see \Drupal\simpletest\WebTestBase::drupalPostForm()
   */
  protected function basicAuthPostForm($path, $edit, $submit, $username, $password, array $options = [], $form_html_id = NULL, $extra_post = NULL) {
    return $this->drupalPostForm($path, $edit, $submit, $options, $this->getBasicAuthHeaders($username, $password), $form_html_id, $extra_post);
  }

  /**
   * Returns HTTP headers that can be used for basic authentication in Curl.
   *
   * @param string $username
   *   The username to use for basic authentication.
   * @param string $password
   *   The password to use for basic authentication.
   *
   * @return array
   *   An array of raw request headers as used by curl_setopt().
   */
  protected function getBasicAuthHeaders($username, $password) {
    // Set up Curl to use basic authentication with the test user's credentials.
    return ['Authorization: Basic ' . base64_encode("$username:$password")];
  }

}


text:
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/* JOrbis
 * Copyright (C) 2000 ymnk, JCraft,Inc.
 *
 * Written by: 2000 ymnk<ymnk@jcraft.com>
 *
 * Many thanks to
 *   Monty <monty@xiph.org> and
 *   The XIPHOPHORUS Company http://www.xiph.org/ .
 * JOrbis has been based on their awesome works, Vorbis codec.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

package com.jcraft.jogg;

// DECODING PRIMITIVES: packet streaming layer

// This has two layers to place more of the multi-serialno and paging
// control in the application's hands.  First, we expose a data buffer
// using ogg_decode_buffer().  The app either copies into the
// buffer, or passes it directly to read(), etc.  We then call
// ogg_decode_wrote() to tell how many bytes we just added.
//
// Pages are returned (pointers into the buffer in ogg_sync_state)
// by ogg_decode_stream().  The page is then submitted to
// ogg_decode_page() along with the appropriate
// ogg_stream_state* (ie, matching serialno).  We then get raw
// packets out calling ogg_stream_packet() with a
// ogg_stream_state.  See the 'frame-prog.txt' docs for details and
// example code.

public class SyncState{

  public byte[] data;
  int storage;
  int fill;
  int returned;

  int unsynced;
  int headerbytes;
  int bodybytes;

  public int clear(){
    data=null;
    return (0);
  }

  public int buffer(int size){
    // first, clear out any space that has been previously returned
    if(returned!=0){
      fill-=returned;
      if(fill>0){
        System.arraycopy(data, returned, data, 0, fill);
      }
      returned=0;
    }

    if(size>storage-fill){
      // We need to extend the internal buffer
      int newsize=size+fill+4096; // an extra page to be nice
      if(data!=null){
        byte[] foo=new byte[newsize];
        System.arraycopy(data, 0, foo, 0, data.length);
        data=foo;
      }
      else{
        data=new byte[newsize];
      }
      storage=newsize;
    }

    return (fill);
  }

  public int wrote(int bytes){
    if(fill+bytes>storage)
      return (-1);
    fill+=bytes;
    return (0);
  }

  // sync the stream.  This is meant to be useful for finding page
  // boundaries.
  //
  // return values for this:
  // -n) skipped n bytes
  //  0) page not ready; more data (no bytes skipped)
  //  n) page synced at current location; page length n bytes
  private Page pageseek=new Page();
  private byte[] chksum=new byte[4];

  public int pageseek(Page og){
    int page=returned;
    int next;
    int bytes=fill-returned;

    if(headerbytes==0){
      int _headerbytes, i;
      if(bytes<27)
        return (0); // not enough for a header

      /* verify capture pattern */
      if(data[page]!='O'||data[page+1]!='g'||data[page+2]!='g'
          ||data[page+3]!='S'){
        headerbytes=0;
        bodybytes=0;

        // search for possible capture
        next=0;
        for(int ii=0; ii<bytes-1; ii++){
          if(data[page+1+ii]=='O'){
            next=page+1+ii;
            break;
          }
        }
        //next=memchr(page+1,'O',bytes-1);
        if(next==0)
          next=fill;

        returned=next;
        return (-(next-page));
      }
      _headerbytes=(data[page+26]&0xff)+27;
      if(bytes<_headerbytes)
        return (0); // not enough for header + seg table

      // count up body length in the segment table

      for(i=0; i<(data[page+26]&0xff); i++){
        bodybytes+=(data[page+27+i]&0xff);
      }
      headerbytes=_headerbytes;
    }

    if(bodybytes+headerbytes>bytes)
      return (0);

    // The whole test page is buffered.  Verify the checksum
    synchronized(chksum){
      // Grab the checksum bytes, set the header field to zero

      System.arraycopy(data, page+22, chksum, 0, 4);
      data[page+22]=0;
      data[page+23]=0;
      data[page+24]=0;
      data[page+25]=0;

      // set up a temp page struct and recompute the checksum
      Page log=pageseek;
      log.header_base=data;
      log.header=page;
      log.header_len=headerbytes;

      log.body_base=data;
      log.body=page+headerbytes;
      log.body_len=bodybytes;
      log.checksum();

      // Compare
      if(chksum[0]!=data[page+22]||chksum[1]!=data[page+23]
          ||chksum[2]!=data[page+24]||chksum[3]!=data[page+25]){
        // D'oh.  Mismatch! Corrupt page (or miscapture and not a page at all)
        // replace the computed checksum with the one actually read in
        System.arraycopy(chksum, 0, data, page+22, 4);
        // Bad checksum. Lose sync */

        headerbytes=0;
        bodybytes=0;
        // search for possible capture
        next=0;
        for(int ii=0; ii<bytes-1; ii++){
          if(data[page+1+ii]=='O'){
            next=page+1+ii;
            break;
          }
        }
        //next=memchr(page+1,'O',bytes-1);
        if(next==0)
          next=fill;
        returned=next;
        return (-(next-page));
      }
    }

    // yes, have a whole page all ready to go
    {
      page=returned;

      if(og!=null){
        og.header_base=data;
        og.header=page;
        og.header_len=headerbytes;
        og.body_base=data;
        og.body=page+headerbytes;
        og.body_len=bodybytes;
      }

      unsynced=0;
      returned+=(bytes=headerbytes+bodybytes);
      headerbytes=0;
      bodybytes=0;
      return (bytes);
    }
  }

  // sync the stream and get a page.  Keep trying until we find a page.
  // Supress 'sync errors' after reporting the first.
  //
  // return values:
  //  -1) recapture (hole in data)
  //   0) need more data
  //   1) page returned
  //
  // Returns pointers into buffered data; invalidated by next call to
  // _stream, _clear, _init, or _buffer

  public int pageout(Page og){
    // all we need to do is verify a page at the head of the stream
    // buffer.  If it doesn't verify, we look for the next potential
    // frame

    while(true){
      int ret=pageseek(og);
      if(ret>0){
        // have a page
        return (1);
      }
      if(ret==0){
        // need more data
        return (0);
      }

      // head did not start a synced page... skipped some bytes
      if(unsynced==0){
        unsynced=1;
        return (-1);
      }
      // loop. keep looking
    }
  }

  // clear things to an initial state.  Good to call, eg, before seeking
  public int reset(){
    fill=0;
    returned=0;
    unsynced=0;
    headerbytes=0;
    bodybytes=0;
    return (0);
  }

  public void init(){
  }

  public int getDataOffset(){
    return returned;
  }

  public int getBufferOffset(){
    return fill;
  }
}


text:
class DonationsController < ApplicationController
  def create
  	@advertisement = Advertisement.find(params[:advertisement_id])
  	@organization = advertisement.organization_id
  	@amout = @advertisement.count * 0.1
  	@donation = Donation.new(advertisement_id: @advertisement.id, company_id: current_company.id, amout: @amout)
    if @advertisement.save
      render json: {success: true}
    else
      render json: {sucess: false}
    end
  end

  def get_amount
  	render json: {"donation" {"amount": "@amount"}}
  end

end


text:
package org.terracotta.dynamic_config.cli.converter;

import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;
import org.junit.Test;
import org.terracotta.dynamic_config.api.model.ConfigFormat;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.terracotta.dynamic_config.api.model.ConfigFormat.CONFIG;
import static org.terracotta.dynamic_config.api.model.ConfigFormat.JSON;
import static org.terracotta.dynamic_config.api.model.ConfigFormat.PROPERTIES;
import static org.terracotta.testing.ExceptionMatcher.throwing;

/**
 * @author Mathieu Carbou
 */
public class ConfigFormatConverterTest {
  @Test
  public void convert() {
    IStringConverter<ConfigFormat> converter = new ConfigFormatConverter();
    assertThat(converter.convert("name"), is(equalTo(CONFIG)));
    assertThat(converter.convert("cfg"), is(equalTo(CONFIG)));
    assertThat(converter.convert("conf"), is(equalTo(CONFIG)));
    assertThat(converter.convert("config"), is(equalTo(CONFIG)));
    assertThat(converter.convert("json"), is(equalTo(JSON)));
    assertThat(converter.convert("index"), is(equalTo(PROPERTIES)));
    assertThat(converter.convert("properties"), is(equalTo(PROPERTIES)));
    assertThat(() -> converter.convert(""), is(throwing(instanceOf(ParameterException.class))));
  }
}


text:
package main

import (
	"encoding/json"
	"encoding/xml"
	"fmt"
	"os"
	"text/template"

	"github.com/kleister/kleister-go/kleister"
	"gopkg.in/urfave/cli.v2"
)

// tmplClientList represents a row within client listing.
var tmplClientList = "Slug: \x1b[33m{{ .Slug }}\x1b[0m" + `
ID: {{ .ID }}
Name: {{ .Name }}
`

// tmplClientShow represents a client within details view.
var tmplClientShow = "Slug: \x1b[33m{{ .Slug }}\x1b[0m" + `
ID: {{ .ID }}
Name: {{ .Name }}
UUID: {{ .Value }}{{ with .Packs }}
Packs: {{ packlist . }}{{ end }}
Created: {{ .CreatedAt.Format "Mon Jan _2 15:04:05 MST 2006" }}
Updated: {{ .UpdatedAt.Format "Mon Jan _2 15:04:05 MST 2006" }}
`

// tmplClientPackList represents a row within client pack listing.
var tmplClientPackList = "Slug: \x1b[33m{{ .Pack.Slug }}\x1b[0m" + `
ID: {{ .Pack.ID }}
Name: {{ .Pack.Name }}
`

// Client provides the sub-command for the client API.
func Client() *cli.Command {
	return &cli.Command{
		Name:  "client",
		Usage: "client related sub-commands",
		Subcommands: []*cli.Command{
			{
				Name:      "list",
				Aliases:   []string{"ls"},
				Usage:     "list all clients",
				ArgsUsage: " ",
				Flags: []cli.Flag{
					&cli.StringFlag{
						Name:  "format",
						Value: tmplClientList,
						Usage: "custom output format",
					},
					&cli.StringFlag{
						Name:  "output",
						Value: "text",
						Usage: "output as format, json or xml",
					},
				},
				Action: func(c *cli.Context) error {
					return Handle(c, ClientList)
				},
			},
			{
				Name:      "show",
				Usage:     "display a client",
				ArgsUsage: " ",
				Flags: []cli.Flag{
					&cli.StringFlag{
						Name:  "id, i",
						Value: "",
						Usage: "client id or slug to show",
					},
					&cli.StringFlag{
						Name:  "format",
						Value: tmplClientShow,
						Usage: "custom output format",
					},
					&cli.StringFlag{
						Name:  "output",
						Value: "text",
						Usage: "output as format, json or xml",
					},
				},
				Action: func(c *cli.Context) error {
					return Handle(c, ClientShow)
				},
			},
			{
				Name:      "delete",
				Aliases:   []string{"rm"},
				Usage:     "delete a client",
				ArgsUsage: " ",
				Flags: []cli.Flag{
					&cli.StringFlag{
						Name:  "id, i",
						Value: "",
						Usage: "client id or slug to delete",
					},
				},
				Action: func(c *cli.Context) error {
					return Handle(c, ClientDelete)
				},
			},
			{
				Name:      "update",
				Usage:     "update a client",
				ArgsUsage: " ",
				Flags: []cli.Flag{
					&cli.StringFlag{
						Name:  "id, i",
						Value: "",
						Usage: "client id or slug to update",
					},
					&cli.StringFlag{
						Name:  "slug",
						Value: "",
						Usage: "provide a slug",
					},
					&cli.StringFlag{
						Name:  "name",
						Value: "",
						Usage: "provide a name",
					},
					&cli.StringFlag{
						Name:  "uuid",
						Value: "",
						Usage: "provide a uuid",
					},
				},
				Action: func(c *cli.Context) error {
					return Handle(c, ClientUpdate)
				},
			},
			{
				Name:      "create",
				Usage:     "create a client",
				ArgsUsage: " ",
				Flags: []cli.Flag{
					&cli.StringFlag{
						Name:  "slug",
						Value: "",
						Usage: "provide a slug",
					},
					&cli.StringFlag{
						Name:  "name",
						Value: "",
						Usage: "provide a name",
					},
					&cli.StringFlag{
						Name:  "uuid",
						Value: "",
						Usage: "provide a uuid",
					},
				},
				Action: func(c *cli.Context) error {
					return Handle(c, ClientCreate)
				},
			},
			{
				Name:  "pack",
				Usage: "pack assignments",
				Subcommands: []*cli.Command{
					{
						Name:      "list",
						Aliases:   []string{"ls"},
						Usage:     "list assigned packs",
						ArgsUsage: " ",
						Flags: []cli.Flag{
							&cli.StringFlag{
								Name:  "id, i",
								Value: "",
								Usage: "client id or slug to list packs",
							},
							&cli.StringFlag{
								Name:  "format",
								Value: tmplClientPackList,
								Usage: "custom output format",
							},
							&cli.StringFlag{
								Name:  "output",
								Value: "text",
								Usage: "output as format, json or xml",
							},
						},
						Action: func(c *cli.Context) error {
							return Handle(c, ClientPackList)
						},
					},
					{
						Name:      "append",
						Usage:     "append a pack to client",
						ArgsUsage: " ",
						Flags: []cli.Flag{
							&cli.StringFlag{
								Name:  "id, i",
								Value: "",
								Usage: "client id or slug to append to",
							},
							&cli.StringFlag{
								Name:  "pack, p",
								Value: "",
								Usage: "pack id or slug to append",
							},
						},
						Action: func(c *cli.Context) error {
							return Handle(c, ClientPackAppend)
						},
					},
					{
						Name:      "remove",
						Aliases:   []string{"rm"},
						Usage:     "remove a pack from client",
						ArgsUsage: " ",
						Flags: []cli.Flag{
							&cli.StringFlag{
								Name:  "id, i",
								Value: "",
								Usage: "client id or slug to remove from",
							},
							&cli.StringFlag{
								Name:  "pack, p",
								Value: "",
								Usage: "pack id or slug to remove",
							},
						},
						Action: func(c *cli.Context) error {
							return Handle(c, ClientPackRemove)
						},
					},
				},
			},
		},
	}
}

// ClientList provides the sub-command to list all clients.
func ClientList(c *cli.Context, client kleister.ClientAPI) error {
	records, err := client.ClientList()

	if err != nil {
		return err
	}

	switch c.String("output") {
	case "json":
		res, err := json.MarshalIndent(records, "", "  ")

		if err != nil {
			return err
		}

		fmt.Fprintf(os.Stdout, "%s\n", res)
	case "xml":
		res, err := xml.MarshalIndent(records, "", "  ")

		if err != nil {
			return err
		}

		fmt.Fprintf(os.Stdout, "%s\n", res)
	case "text":
		if len(records) == 0 {
			fmt.Fprintf(os.Stderr, "empty result\n")
			return nil
		}

		tmpl, err := template.New(
			"_",
		).Funcs(
			globalFuncMap,
		).Funcs(
			sprigFuncMap,
		).Parse(
			fmt.Sprintf("%s\n", c.String("format")),
		)

		if err != nil {
			return err
		}

		for _, record := range records {
			err := tmpl.Execute(os.Stdout, record)

			if err != nil {
				return err
			}
		}
	default:
		return fmt.Errorf("invalid output type")
	}

	return nil
}

// ClientShow provides the sub-command to show client details.
func ClientShow(c *cli.Context, client kleister.ClientAPI) error {
	record, err := client.ClientGet(
		GetIdentifierParam(c),
	)

	if err != nil {
		return err
	}

	switch c.String("output") {
	case "json":
		res, err := json.MarshalIndent(record, "", "  ")

		if err != nil {
			return err
		}

		fmt.Fprintf(os.Stdout, "%s\n", res)
	case "xml":
		res, err := xml.MarshalIndent(record, "", "  ")

		if err != nil {
			return err
		}

		fmt.Fprintf(os.Stdout, "%s\n", res)
	case "text":
		tmpl, err := template.New(
			"_",
		).Funcs(
			globalFuncMap,
		).Funcs(
			sprigFuncMap,
		).Parse(
			fmt.Sprintf("%s\n", c.String("format")),
		)

		if err != nil {
			return err
		}

		return tmpl.Execute(os.Stdout, record)
	default:
		return fmt.Errorf("invalid output type")
	}

	return nil
}

// ClientDelete provides the sub-command to delete a client.
func ClientDelete(c *cli.Context, client kleister.ClientAPI) error {
	err := client.ClientDelete(
		GetIdentifierParam(c),
	)

	if err != nil {
		return err
	}

	fmt.Fprintf(os.Stderr, "successfully deleted\n")
	return nil
}

// ClientUpdate provides the sub-command to update a client.
func ClientUpdate(c *cli.Context, client kleister.ClientAPI) error {
	record, err := client.ClientGet(
		GetIdentifierParam(c),
	)

	if err != nil {
		return err
	}

	changed := false

	if val := c.String("name"); c.IsSet("name") && val != record.Name {
		record.Name = val
		changed = true
	}

	if val := c.String("uuid"); c.IsSet("uuid") && val != record.Value {
		record.Value = val
		changed = true
	}

	if val := c.String("slug"); c.IsSet("slug") && val != record.Slug {
		record.Slug = val
		changed = true
	}

	if changed {
		_, patch := client.ClientPatch(
			record,
		)

		if patch != nil {
			return patch
		}

		fmt.Fprintf(os.Stderr, "successfully updated\n")
	} else {
		fmt.Fprintf(os.Stderr, "nothing to update!\n")
	}

	return nil
}

// ClientCreate provides the sub-command to create a client.
func ClientCreate(c *cli.Context, client kleister.ClientAPI) error {
	record := &kleister.Client{}

	if val := c.String("name"); c.IsSet("name") && val != "" {
		record.Name = val
	} else {
		return fmt.Errorf("you must provide a name")
	}

	if val := c.String("uuid"); c.IsSet("uuid") && val != "" {
		record.Value = val
	} else {
		return fmt.Errorf("you must provide a uuid")
	}

	if val := c.String("slug"); c.IsSet("slug") && val != "" {
		record.Slug = val
	}

	_, err := client.ClientPost(
		record,
	)

	if err != nil {
		return err
	}

	fmt.Fprintf(os.Stderr, "successfully created\n")
	return nil
}

// ClientPackList provides the sub-command to list packs of the client.
func ClientPackList(c *cli.Context, client kleister.ClientAPI) error {
	records, err := client.ClientPackList(
		kleister.ClientPackParams{
			Client: GetIdentifierParam(c),
		},
	)

	if err != nil {
		return err
	}

	switch c.String("output") {
	case "json":
		res, err := json.MarshalIndent(records, "", "  ")

		if err != nil {
			return err
		}

		fmt.Fprintf(os.Stdout, "%s\n", res)
	case "xml":
		res, err := xml.MarshalIndent(records, "", "  ")

		if err != nil {
			return err
		}

		fmt.Fprintf(os.Stdout, "%s\n", res)
	case "text":
		if len(records) == 0 {
			fmt.Fprintf(os.Stderr, "empty result\n")
			return nil
		}

		tmpl, err := template.New(
			"_",
		).Funcs(
			globalFuncMap,
		).Funcs(
			sprigFuncMap,
		).Parse(
			fmt.Sprintf("%s\n", c.String("format")),
		)

		if err != nil {
			return err
		}

		for _, record := range records {
			err := tmpl.Execute(os.Stdout, record)

			if err != nil {
				return err
			}
		}
	default:
		return fmt.Errorf("invalid output type")
	}

	return nil
}

// ClientPackAppend provides the sub-command to append a pack to the client.
func ClientPackAppend(c *cli.Context, client kleister.ClientAPI) error {
	err := client.ClientPackAppend(
		kleister.ClientPackParams{
			Client: GetIdentifierParam(c),
			Pack:   GetPackParam(c),
		},
	)

	if err != nil {
		return err
	}

	fmt.Fprintf(os.Stderr, "successfully appended to client\n")
	return nil
}

// ClientPackRemove provides the sub-command to remove a pack from the client.
func ClientPackRemove(c *cli.Context, client kleister.ClientAPI) error {
	err := client.ClientPackDelete(
		kleister.ClientPackParams{
			Client: GetIdentifierParam(c),
			Pack:   GetPackParam(c),
		},
	)

	if err != nil {
		return err
	}

	fmt.Fprintf(os.Stderr, "successfully removed from client\n")
	return nil
}


text:
using Arragro.Core.Identity.Models;
using ArragroCMS.BusinessLayer.Domains;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using System;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;

namespace ArragroCMS.Web.Management.Extensions
{
    public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
    {
        private readonly Users _users;
        private readonly SignInManager<User> _signInManager;

        public CustomCookieAuthenticationEvents(
            Users users,
            SignInManager<User> signInManager)
        {
            _users = users;
            _signInManager = signInManager;
        }

        private Task CookieEventHandler(RedirectContext<CookieAuthenticationOptions> ctx, HttpStatusCode httpStatusCode)
        {
            if (ctx.Response.StatusCode == (int)HttpStatusCode.OK)
            {
                ctx.Response.StatusCode = (int)httpStatusCode;
            }
            return Task.FromResult(0);
        }

        public override Task RedirectToAccessDenied(RedirectContext<CookieAuthenticationOptions> context)
        {
            return CookieEventHandler(context, HttpStatusCode.Unauthorized);
        }

        public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
        {
            return CookieEventHandler(context, HttpStatusCode.Forbidden);
        }

        public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
        {
            if (context.Principal.Identity.IsAuthenticated)
            {
                var userPrincipal = context.Principal;

                var modifiedDate = (from c in userPrincipal.Claims
                                    where c.Type == "ModifiedDate"
                                    select c.Value).FirstOrDefault();

                string email = null;

                var claim = userPrincipal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Email);
                if (claim != null)
                    email = claim.Value;

                if (email == null)
                    throw new Exception($"User Principal for '{userPrincipal.Identity.AuthenticationType}' isn't supported");

                var user = await _users.GetAsync(email);

                if (string.IsNullOrEmpty(modifiedDate) ||
                    !_users.ValidateLastChanged(user, modifiedDate))
                {
                    context.ReplacePrincipal(await _users.GetClaimsPrincipal(user));
                    context.ShouldRenew = true;
                }
            }
        }
    }
}


text:
package app.bindingModels;

import com.google.gson.annotations.Expose;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Set;

@Component
public class UserDto {

    @Expose
    private Long id;

    @Expose
    private String firstName;

    @Expose
    private String lastName;

    @Expose
    private BigDecimal age;

    @Expose
    private Set<ProductDto> soldProducts;

    public UserDto() {
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public BigDecimal getAge() {
        return age;
    }

    public void setAge(BigDecimal age) {
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Set<ProductDto> getSoldProducts() {
        return soldProducts;
    }

    public void setSoldProducts(Set<ProductDto> soldProducts) {
        this.soldProducts = soldProducts;
    }
}


text:
package com.amazonaws.services.amplify.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * The result structure for the generate access logs request.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GenerateAccessLogsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The pre-signed URL for the requested access logs.
     *

     */
    private String logUrl;

    /**
     *

     * The pre-signed URL for the requested access logs.
     *

     *
     * @param logUrl
     *        The pre-signed URL for the requested access logs.
     */

    public void setLogUrl(String logUrl) {
        this.logUrl = logUrl;
    }

    /**
     *

     * The pre-signed URL for the requested access logs.
     *

     *
     * @return The pre-signed URL for the requested access logs.
     */

    public String getLogUrl() {
        return this.logUrl;
    }

    /**
     *

     * The pre-signed URL for the requested access logs.
     *

     *
     * @param logUrl
     *        The pre-signed URL for the requested access logs.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GenerateAccessLogsResult withLogUrl(String logUrl) {
        setLogUrl(logUrl);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getLogUrl() != null)
            sb.append("LogUrl: ").append(getLogUrl());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GenerateAccessLogsResult == false)
            return false;
        GenerateAccessLogsResult other = (GenerateAccessLogsResult) obj;
        if (other.getLogUrl() == null ^ this.getLogUrl() == null)
            return false;
        if (other.getLogUrl() != null && other.getLogUrl().equals(this.getLogUrl()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getLogUrl() == null) ? 0 : getLogUrl().hashCode());
        return hashCode;
    }

    @Override
    public GenerateAccessLogsResult clone() {
        try {
            return (GenerateAccessLogsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package org.dlangplugin.psi.impl;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static org.dlangplugin.psi.DTokenTypes.*;
import org.dlangplugin.psi.*;

public class DLangClassDeclarationImpl extends DLangCompositeElementImpl implements DLangClassDeclaration {

  public DLangClassDeclarationImpl(ASTNode node) {
    super(node);
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof DLangVisitor) ((DLangVisitor)visitor).visitClassDeclaration(this);
    else super.accept(visitor);
  }

  @Override
  @Nullable
  public DLangAggregateBody getAggregateBody() {
    return findChildByClass(DLangAggregateBody.class);
  }

  @Override
  @Nullable
  public DLangBaseClassList getBaseClassList() {
    return findChildByClass(DLangBaseClassList.class);
  }

  @Override
  @Nullable
  public DLangClassTemplateDeclaration getClassTemplateDeclaration() {
    return findChildByClass(DLangClassTemplateDeclaration.class);
  }

  @Override
  @Nullable
  public DLangComponentName getComponentName() {
    return findChildByClass(DLangComponentName.class);
  }

  public String getName() {
    return DLangPsiImplUtil.getName(this);
  }

  public PsiElement setName(String newName) {
    return DLangPsiImplUtil.setName(this, newName);
  }

  public PsiElement getNameIdentifier() {
    return DLangPsiImplUtil.getNameIdentifier(this);
  }

  public DLangClassPresentation getPresentation() {
    return DLangPsiImplUtil.getPresentation(this);
  }

}


text:
jQuery(function(){
    var nomination_template = '<fieldset id="nomination_{0}"> \
          <legend>Nomination {0}</legend> \
           \
            full name \
            <input type="text" name="full_name_{0}" value="" class="required capitalize" /> \
             \
           \
           \
            company \
            <input type="text" name="company_{0}" value="" class="required capitalize" /> \
             \
           \
           \
            designation \
            <input type="text" name="designation_{0}" value="" class="required capitalize" /> \
             \
           \
           \
            email \
            <input type="text" name="email_{0}" value="" class="required email" /> \
             \
           \
           \
            phone \
            <input type="text" name="phone_number_{0}" value="" class="required phone" /> \
            Add nomination \
           \
        </fieldset>',
        nominations_count = 1,
        training_announcement_key = jQuery("#form_training_registration").attr('key'),
        elements = {
            formTrainingRegistration: jQuery('#form_training_registration')
        };

    jQuery('#form_training_registration a[href="#add_nomination"]').live('click', function(event){
        event.preventDefault();
        event.stopPropagation();
        ++nominations_count;

        var elem = jQuery(this),
            html = jQuery.format(nomination_template, nominations_count),
            fieldset = elem.parents('fieldset');
        fieldset.after(html);
        jQuery('#form_training_registration input[name="name_' + nominations_count + '"]').focus();
        jQuery('#form_training_registration input[name="nominations_count"]').val(nominations_count);
        jQuery('#form_training_registration input[name="email_' + nominations_count + '"]').rules("add", {
            required: true,
            remote: {
                url: "/training_announcements/check_email_available/",
                type: "post",
                data: {
                    training_announcement_key: training_announcement_key,
                    index: nominations_count
                }
            },
            messages: {
                remote: "Please choose a new email address.  This one is already registered for this event."
            }
        });
        return false;
    });

    /*jQuery('#form_training_registration input[name="email_' + nominations_count + '"]').rules("add", {
        required: true,
        remote: {
            url: "/training_announcements/check_email_available/",
            type: "post",
            data: {
                training_announcement_key: training_announcement_key,
                index: nominations_count
            }
        },
        messages: {
            remote: "Please choose a new email address.  This one is already registered for this event."
        }
    });*/
    elements.formTrainingRegistration.validate();
});


text:
package block

import (
	"bufio"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"unicode"
	"unsafe"

	"github.com/rekby/gpt"
	"github.com/u-root/u-root/pkg/mount"
	"github.com/u-root/u-root/pkg/pci"
	"golang.org/x/sys/unix"
)

var (
	// LinuxMountsPath is the standard mountpoint list path
	LinuxMountsPath = "/proc/mounts"

	// Debug function to override for verbose logging.
	Debug = func(string, ...interface{}) {}

	// SystemPartitionGUID is the GUID of EFI system partitions
	// EFI System partitions have GUID C12A7328-F81F-11D2-BA4B-00A0C93EC93B
	SystemPartitionGUID = gpt.Guid([...]byte{
		0x28, 0x73, 0x2a, 0xc1,
		0x1f, 0xf8,
		0xd2, 0x11,
		0xba, 0x4b,
		0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b,
	})
)

// BlockDev maps a device name to a BlockStat structure for a given block device
type BlockDev struct {
	Name   string
	FSType string
	FsUUID string
}

// Device makes sure the block device exists and returns a handle to it.
//
// maybeDevpath can be path like /dev/sda1, /sys/class/block/sda1 or just sda1.
// We will just use the last component.
func Device(maybeDevpath string) (*BlockDev, error) {
	devname := filepath.Base(maybeDevpath)
	if _, err := os.Stat(filepath.Join("/sys/class/block", devname)); err != nil {
		return nil, err
	}

	devpath := filepath.Join("/dev/", devname)
	if uuid, err := getFSUUID(devpath); err == nil {
		return &BlockDev{Name: devname, FsUUID: uuid}, nil
	}
	return &BlockDev{Name: devname}, nil
}

// String implements fmt.Stringer.
func (b *BlockDev) String() string {
	if len(b.FSType) > 0 {
		return fmt.Sprintf("BlockDevice(name=%s, fs_type=%s, fs_uuid=%s)", b.Name, b.FSType, b.FsUUID)
	}
	return fmt.Sprintf("BlockDevice(name=%s, fs_uuid=%s)", b.Name, b.FsUUID)
}

// DevicePath is the path to the actual device.
func (b BlockDev) DevicePath() string {
	return filepath.Join("/dev/", b.Name)
}

// Name implements mount.Mounter.
func (b *BlockDev) DevName() string {
	return b.Name
}

// Mount implements mount.Mounter.
func (b *BlockDev) Mount(path string, flags uintptr, opts ...func() error) (*mount.MountPoint, error) {
	devpath := filepath.Join("/dev", b.Name)
	if len(b.FSType) > 0 {
		return mount.Mount(devpath, path, b.FSType, "", flags, opts...)
	}

	return mount.TryMount(devpath, path, "", flags, opts...)
}

// GPTTable tries to read a GPT table from the block device described by the
// passed BlockDev object, and returns a gpt.Table object, or an error if any
func (b *BlockDev) GPTTable() (*gpt.Table, error) {
	fd, err := os.Open(b.DevicePath())
	if err != nil {
		return nil, err
	}
	defer fd.Close()

	blkSize, err := b.BlockSize()
	if err != nil {
		blkSize = 512
	}

	if _, err := fd.Seek(int64(blkSize), io.SeekStart); err != nil {
		return nil, err
	}
	table, err := gpt.ReadTable(fd, uint64(blkSize))
	if err != nil {
		return nil, err
	}
	return &table, nil
}

// PhysicalBlockSize returns the physical block size.
func (b *BlockDev) PhysicalBlockSize() (int, error) {
	f, err := os.Open(b.DevicePath())
	if err != nil {
		return 0, err
	}
	defer f.Close()
	return unix.IoctlGetInt(int(f.Fd()), unix.BLKPBSZGET)
}

// BlockSize returns the logical block size (BLKSSZGET).
func (b *BlockDev) BlockSize() (int, error) {
	f, err := os.Open(b.DevicePath())
	if err != nil {
		return 0, err
	}
	defer f.Close()
	return unix.IoctlGetInt(int(f.Fd()), unix.BLKSSZGET)
}

// KernelBlockSize returns the soft block size used inside the kernel (BLKBSZGET).
func (b *BlockDev) KernelBlockSize() (int, error) {
	f, err := os.Open(b.DevicePath())
	if err != nil {
		return 0, err
	}
	defer f.Close()
	return unix.IoctlGetInt(int(f.Fd()), unix.BLKBSZGET)
}

func ioctlGetUint64(fd int, req uint) (uint64, error) {
	var value uint64
	_, _, err := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(unsafe.Pointer(&value)))
	if err != 0 {
		return 0, err
	}
	return value, nil
}

// Size returns the size in bytes.
func (b *BlockDev) Size() (uint64, error) {
	f, err := os.Open(b.DevicePath())
	if err != nil {
		return 0, err
	}
	defer f.Close()

	sz, err := ioctlGetUint64(int(f.Fd()), unix.BLKGETSIZE64)
	if err != nil {
		return 0, &os.PathError{
			Op:   "get size",
			Path: b.DevicePath(),
			Err:  os.NewSyscallError("ioctl(BLKGETSIZE64)", err),
		}
	}
	return sz, nil
}

// ReadPartitionTable prompts the kernel to re-read the partition table on this block device.
func (b *BlockDev) ReadPartitionTable() error {
	f, err := os.OpenFile(b.DevicePath(), os.O_RDWR, 0)
	if err != nil {
		return err
	}
	defer f.Close()
	return unix.IoctlSetInt(int(f.Fd()), unix.BLKRRPART, 0)
}

// PCIInfo searches sysfs for the PCI vendor and device id.
// We fill in the PCI struct with just those two elements.
func (b *BlockDev) PCIInfo() (*pci.PCI, error) {
	p, err := filepath.EvalSymlinks(filepath.Join("/sys/class/block", b.Name))
	if err != nil {
		return nil, err
	}
	// Loop through devices until we find the actual backing pci device.
	// For Example:
	// /sys/class/block/nvme0n1p1 usually resolves to something like
	// /sys/devices/pci..../.../.../nvme/nvme0/nvme0n1/nvme0n1p1. This leads us to the
	// first partition of the first namespace of the nvme0 device. In this case, the actual pci device and vendor
	// is found in nvme, three levels up. We traverse back up to the parent device
	// and we keep going until we find a device and vendor file.
	dp := filepath.Join(p, "device")
	vp := filepath.Join(p, "vendor")
	found := false
	for p != "/sys/devices" {
		// Check if there is a vendor and device file in this directory.
		if d, err := os.Stat(dp); err == nil && !d.IsDir() {
			if v, err := os.Stat(vp); err == nil && !v.IsDir() {
				found = true
				break
			}
		}
		p = filepath.Dir(p)
		dp = filepath.Join(p, "device")
		vp = filepath.Join(p, "vendor")
	}
	if !found {
		return nil, fmt.Errorf("Unable to find backing pci device with device and vendor files for %v", b.Name)
	}

	return pci.OnePCI(p)
}

func getFSUUID(devpath string) (string, error) {
	file, err := os.Open(devpath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	fsuuid, err := tryFAT32(file)
	if err == nil {
		return fsuuid, nil
	}
	fsuuid, err = tryFAT16(file)
	if err == nil {
		return fsuuid, nil
	}
	fsuuid, err = tryEXT4(file)
	if err == nil {
		return fsuuid, nil
	}
	fsuuid, err = tryXFS(file)
	if err == nil {
		return fsuuid, nil
	}
	return "", fmt.Errorf("unknown UUID (not vfat, ext4, nor xfs)")
}

// See https://www.nongnu.org/ext2-doc/ext2.html#DISK-ORGANISATION.
const (
	// Offset of superblock in partition.
	ext2SprblkOff = 1024

	// Offset of magic number in suberblock.
	ext2SprblkMagicOff  = 56
	ext2SprblkMagicSize = 2

	ext2SprblkMagic = 0xEF53

	// Offset of UUID in superblock.
	ext2SprblkUUIDOff  = 104
	ext2SprblkUUIDSize = 16
)

func tryEXT4(file io.ReaderAt) (string, error) {
	var off int64

	// Read magic number.
	b := make([]byte, ext2SprblkMagicSize)
	off = ext2SprblkOff + ext2SprblkMagicOff
	if _, err := file.ReadAt(b, off); err != nil {
		return "", err
	}
	magic := binary.LittleEndian.Uint16(b[:2])
	if magic != ext2SprblkMagic {
		return "", fmt.Errorf("ext4 magic not found")
	}

	// Filesystem UUID.
	b = make([]byte, ext2SprblkUUIDSize)
	off = ext2SprblkOff + ext2SprblkUUIDOff
	if _, err := file.ReadAt(b, off); err != nil {
		return "", err
	}

	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]), nil
}

// See https://de.wikipedia.org/wiki/File_Allocation_Table#Aufbau.
const (
	fat12Magic = "FAT12   "
	fat16Magic = "FAT16   "

	// Offset of magic number.
	fat16MagicOff  = 0x36
	fat16MagicSize = 8

	// Offset of filesystem ID / serial number. Treated as short filesystem UUID.
	fat16IDOff  = 0x27
	fat16IDSize = 4
)

func tryFAT16(file io.ReaderAt) (string, error) {
	// Read magic number.
	b := make([]byte, fat16MagicSize)
	if _, err := file.ReadAt(b, fat16MagicOff); err != nil {
		return "", err
	}
	magic := string(b)
	if magic != fat16Magic && magic != fat12Magic {
		return "", fmt.Errorf("fat16 magic not found")
	}

	// Filesystem UUID.
	b = make([]byte, fat16IDSize)
	if _, err := file.ReadAt(b, fat16IDOff); err != nil {
		return "", err
	}

	return fmt.Sprintf("%02x%02x-%02x%02x", b[3], b[2], b[1], b[0]), nil
}

// See https://de.wikipedia.org/wiki/File_Allocation_Table#Aufbau.
const (
	fat32Magic = "FAT32   "

	// Offset of magic number.
	fat32MagicOff  = 0x52
	fat32MagicSize = 8

	// Offset of filesystem ID / serial number. Treated as short filesystem UUID.
	fat32IDOff  = 67
	fat32IDSize = 4
)

func tryFAT32(file io.ReaderAt) (string, error) {
	// Read magic number.
	b := make([]byte, fat32MagicSize)
	if _, err := file.ReadAt(b, fat32MagicOff); err != nil {
		return "", err
	}
	magic := string(b)
	if magic != fat32Magic {
		return "", fmt.Errorf("fat32 magic not found")
	}

	// Filesystem UUID.
	b = make([]byte, fat32IDSize)
	if _, err := file.ReadAt(b, fat32IDOff); err != nil {
		return "", err
	}

	return fmt.Sprintf("%02x%02x-%02x%02x", b[3], b[2], b[1], b[0]), nil
}

const (
	xfsMagic     = "XFSB"
	xfsMagicSize = 4
	xfsUUIDOff   = 32
	xfsUUIDSize  = 16
)

func tryXFS(file io.ReaderAt) (string, error) {
	// Read magic number.
	b := make([]byte, xfsMagicSize)
	if _, err := file.ReadAt(b, 0); err != nil {
		return "", err
	}
	magic := string(b)
	if magic != xfsMagic {
		return "", fmt.Errorf("xfs magic not found")
	}

	// Filesystem UUID.
	b = make([]byte, xfsUUIDSize)
	if _, err := file.ReadAt(b, xfsUUIDOff); err != nil {
		return "", err
	}

	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]), nil
}

// BlockDevices is a list of block devices.
type BlockDevices []*BlockDev

// GetBlockDevices iterates over /sys/class/block entries and returns a list of
// BlockDev objects, or an error if any
func GetBlockDevices() (BlockDevices, error) {
	var blockdevs []*BlockDev
	var devnames []string

	root := "/sys/class/block"
	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		rel, err := filepath.Rel(root, path)
		if err != nil {
			return err
		}
		if rel == "." {
			return nil
		}
		devnames = append(devnames, rel)
		dev, err := Device(rel)
		if err != nil {
			return err
		}
		blockdevs = append(blockdevs, dev)
		return nil
	})
	if err != nil {
		return nil, err
	}
	return blockdevs, nil
}

// FilterName returns a list of BlockDev objects whose underlying
// block device has a Name with the given Name
func (b BlockDevices) FilterName(name string) BlockDevices {
	partitions := make(BlockDevices, 0)
	for _, device := range b {
		if device.Name == name {
			partitions = append(partitions, device)
		}
	}
	return partitions
}

// FilterNames filters block devices by the given list of device names (e.g.
// /dev/sda1 sda2 /sys/class/block/sda3).
func (b BlockDevices) FilterNames(names ...string) BlockDevices {
	m := make(map[string]struct{})
	for _, n := range names {
		m[filepath.Base(n)] = struct{}{}
	}

	var devices BlockDevices
	for _, device := range b {
		if _, ok := m[device.Name]; ok {
			devices = append(devices, device)
		}
	}
	return devices
}

// FilterFSUUID returns a list of BlockDev objects whose underlying block
// device has a filesystem with the given FSUUID.
func (b BlockDevices) FilterFSUUID(fsuuid string) BlockDevices {
	partitions := make(BlockDevices, 0)
	for _, device := range b {
		if device.FsUUID == fsuuid {
			partitions = append(partitions, device)
		}
	}
	return partitions
}

// FilterZeroSize attempts to find block devices that have at least one block
// of content.
//
// This serves to eliminate block devices that have no backing storage, but
// appear in /sys/class/block anyway (like some loop, nbd, or ram devices).
func (b BlockDevices) FilterZeroSize() BlockDevices {
	var nb BlockDevices
	for _, device := range b {
		if n, err := device.Size(); err != nil || n == 0 {
			continue
		}
		nb = append(nb, device)
	}
	return nb
}

// FilterHavingPartitions returns BlockDevices with have the specified
// partitions. (e.g. f(1, 2) {sda, sda1, sda2, sdb} -> {sda})
func (b BlockDevices) FilterHavingPartitions(parts []int) BlockDevices {
	devices := make(BlockDevices, 0)
	for _, device := range b {
		hasParts := true
		for _, part := range parts {
			if _, err := os.Stat(filepath.Join("/sys/class/block",
				composePartName(device.Name, part))); err != nil {
				hasParts = false
				break
			}
		}
		if hasParts {
			devices = append(devices, device)
		}
	}
	return devices
}

// FilterPartID returns partitions with the given partition ID GUID.
func (b BlockDevices) FilterPartID(guid string) BlockDevices {
	var names []string
	for _, device := range b {
		table, err := device.GPTTable()
		if err != nil {
			continue
		}
		for i, part := range table.Partitions {
			if part.IsEmpty() {
				continue
			}
			if strings.EqualFold(part.Id.String(), guid) {
				names = append(names, composePartName(device.Name, i+1))
			}
		}
	}
	return b.FilterNames(names...)
}

// FilterPartType returns partitions with the given partition type GUID.
func (b BlockDevices) FilterPartType(guid string) BlockDevices {
	var names []string
	for _, device := range b {
		table, err := device.GPTTable()
		if err != nil {
			continue
		}
		for i, part := range table.Partitions {
			if part.IsEmpty() {
				continue
			}
			if strings.EqualFold(part.Type.String(), guid) {
				names = append(names, composePartName(device.Name, i+1))
			}
		}
	}
	return b.FilterNames(names...)
}

// FilterPartLabel returns a list of BlockDev objects whose underlying block
// device has the given partition label. The name comparison is case-insensitive.
func (b BlockDevices) FilterPartLabel(label string) BlockDevices {
	var names []string
	for _, device := range b {
		table, err := device.GPTTable()
		if err != nil {
			continue
		}
		for i, part := range table.Partitions {
			if part.IsEmpty() {
				continue
			}
			if strings.EqualFold(part.Name(), label) {
				names = append(names, composePartName(device.Name, i+1))
			}
		}
	}
	return b.FilterNames(names...)
}

// FilterBlockPCIString parses a string in the format vendor:device,vendor:device
// and returns a list of BlockDev objects whose backing pci devices do not match
// the vendor:device pairs passed in. All values are treated as hex.
// E.g. 0x8086:0xABCD,8086:0x1234
func (b BlockDevices) FilterBlockPCIString(blocklist string) (BlockDevices, error) {
	pciList, err := parsePCIBlockList(blocklist)
	if err != nil {
		return nil, err
	}
	return b.FilterBlockPCI(pciList), nil
}

// FilterBlockPCI returns a list of BlockDev objects whose backing
// pci devices do not match the blocklist of PCI devices passed in.
// FilterBlockPCI discards entries which have a matching PCI vendor
// and device ID as an entry in the blocklist.
func (b BlockDevices) FilterBlockPCI(blocklist pci.Devices) BlockDevices {
	type mapKey struct {
		vendor, device uint16
	}
	m := make(map[mapKey]bool)

	for _, v := range blocklist {
		m[mapKey{v.Vendor, v.Device}] = true
	}
	Debug("block map is %v", m)

	partitions := make(BlockDevices, 0)
	for _, device := range b {
		p, err := device.PCIInfo()
		if err != nil {
			// In the case of an error, we err on the safe side and choose not to block it.
			// Not all block devices are backed by a pci device, for example SATA drives.
			Debug("Failed to find PCI info; %v", err)
			partitions = append(partitions, device)
			continue
		}
		if _, ok := m[mapKey{p.Vendor, p.Device}]; !ok {
			// Not in blocklist, we're good to go
			Debug("Not blocking device %v, with pci %v, not in map", device, p)
			partitions = append(partitions, device)
		} else {
			log.Printf("Blocking device %v since it appears in blocklist", device.Name)
		}
	}
	return partitions
}

// parsePCIBlockList parses a string in the format vendor:device,vendor:device
// and returns a list of PCI devices containing the vendor and device pairs to block.
func parsePCIBlockList(blockList string) (pci.Devices, error) {
	pciList := pci.Devices{}
	bL := strings.Split(blockList, ",")
	for _, b := range bL {
		p := strings.Split(b, ":")
		if len(p) != 2 {
			return nil, fmt.Errorf("BlockList needs to be of format vendor1:device1,vendor2:device2...! got %v", blockList)
		}
		// Check that values are hex and convert them to sysfs formats
		// This accepts 0xABCD and turns it into 0xabcd
		// abcd also turns into 0xabcd
		v, err := strconv.ParseUint(strings.TrimPrefix(p[0], "0x"), 16, 16)
		if err != nil {
			return nil, fmt.Errorf("BlockList needs to contain a hex vendor ID, got %v, err %v", p[0], err)
		}

		d, err := strconv.ParseUint(strings.TrimPrefix(p[1], "0x"), 16, 16)
		if err != nil {
			return nil, fmt.Errorf("BlockList needs to contain a hex device ID, got %v, err %v", p[1], err)
		}

		pciList = append(pciList, &pci.PCI{Vendor: uint16(v), Device: uint16(d)})
	}
	return pciList, nil
}

// composePartName returns the partition name described by the parent devName
// and partNo counting from 1. It is assumed that device names ending in a
// number like nvme0n1 have partitions named like nvme0n1p1, nvme0n1p2, ...
// and devices ending in a letter like sda have partitions named like
//
//	sda1, sda2, ...
func composePartName(devName string, partNo int) string {
	r := []rune(devName[len(devName)-1:])
	if unicode.IsDigit(r[0]) {
		return fmt.Sprintf("%sp%d", devName, partNo)
	}
	return fmt.Sprintf("%s%d", devName, partNo)
}

// GetMountpointByDevice gets the mountpoint by given
// device name. Returns on first match
func GetMountpointByDevice(devicePath string) (*string, error) {
	file, err := os.Open(LinuxMountsPath)
	if err != nil {
		return nil, err
	}

	defer file.Close()
	scanner := bufio.NewScanner(file)

	for scanner.Scan() {
		deviceInfo := strings.Fields(scanner.Text())
		if deviceInfo[0] == devicePath {
			return &deviceInfo[1], nil
		}
	}

	return nil, errors.New("Mountpoint not found")
}


text:
module Doukaku.PoorManTest (tests) where

import Distribution.TestSuite
import Doukaku.TestHelper
import qualified Doukaku.PoorMan as PoorMan
import Data.List (sort)
import Data.List.Split (splitOn)

tests :: IO [Test]
tests = createTests $ newDoukakuTest {
  tsvPath = "test/Doukaku/poorman.tsv"
  , solve = PoorMan.solve
  , eq = eq'
  }
  where
    x `eq'` y = normarize x == normarize y
    normarize = sort . map normarize' . splitOn ","
    normarize' = concat . sort . twopieces
    twopieces :: String -> [String]
    twopieces [] = []
    twopieces ('-':ys) = ('-':[]) : twopieces ys
    twopieces (x:y:ys) = (x:y:[]) : twopieces ys


text:
layout: post
title: "How we built a distributed, self-funded, family-friendly, profitable startup"
tags:
- Startups
- HowTo
- External Writing
thumbnail_path: blog/gruntwork/logo_with_text_new_website_small.png
external_url: "https://blog.gruntwork.io/how-we-built-a-distributed-self-funded-family-friendly-profitable-startup-93635feb5ace"
---

We started Gruntwork in 2016 with two goals: (1) make it 10x easier to understand, build, and deploy software and (2)
build a company where we can work on interesting projects, with interesting people, while leading interesting lives.
This blog post is primarily going to focus on how we're trying to accomplish #2.

Read on to learn how we built a startup that is distributed, self-funded, family-friendly, and profitable:

{% include figure.html path=page.thumbnail_path caption=page.title url=page.external_url %}

If you want to learn more about startups, check out my book, *[Hello, Startup: A Programmer's Guide to Building
Products, Technologies, and Teams](https://www.hello-startup.net/)*.


text:
module Vines
  class Stanza
    class Message
      module Offline
        extend self

        def process(message)
          return unless message.local?
          return unless message.recipients.empty?

          if user = message.storage(message.to.domain).find_user(message.to)
            message.store
          elsif !message.restored?
            message.share
          end
        end

      end
    end
  end
end


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),

            // new JMS\DiExtraBundle\JMSDiExtraBundle($this),
            // new JMS\AopBundle\JMSAopBundle(),

            new Mopa\Bundle\BootstrapBundle\MopaBootstrapBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
            new FOS\MessageBundle\FOSMessageBundle(),

            // new FOS\RestBundle\FOSRestBundle(),
            // new FOS\CommentBundle\FOSCommentBundle(),
            new JMS\SerializerBundle\JMSSerializerBundle($this),
            new Gregwar\CaptchaBundle\GregwarCaptchaBundle(),

            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
            new FOS\UserBundle\FOSUserBundle() ,
            new App\UserBundle\AppUserBundle() ,
            new App\AdminBundle\AppAdminBundle() ,
            // new App\WebBundle\AppWebBundle() ,
        );

        $env    = $this->getEnvironment() ;

        if (  in_array($env, array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        if( 'test' === $env ) {
            $bundles[]  = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle() ;
            $bundles[]  = new Liip\FunctionalTestBundle\LiipFunctionalTestBundle() ;
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}