text:
#ifndef ZEPHYR_INCLUDE_CONSOLE_CONSOLE_H_
#define ZEPHYR_INCLUDE_CONSOLE_CONSOLE_H_

#include <sys/types.h>
#include <zephyr/types.h>
#include <kernel.h>

#ifdef __cplusplus
extern "C" {
#endif

/** @brief Initialize console device.
 *
 *  This function should be called once to initialize pull-style
 *  access to console via console_getchar() function and buffered
 *  output using console_putchar() function. This function supersedes,
 *  and incompatible with, callback (push-style) console handling
 *  (via console_input_fn callback, etc.).
 *
 * @return 0 on success, error code (<0) otherwise
 */
int console_init(void);

/**
 * @brief Read data from console.
 *
 * @param dummy ignored, present to follow read() prototype
 * @param buf buffer to read data to
 * @param size maximum number of bytes to read
 * @return >0, number of actually read bytes (can be less than size param)
 *         =0, in case of EOF
 *         <0, in case of error (e.g. -EAGAIN if timeout expired). errno
 *             variable is also set.
 */
ssize_t console_read(void *dummy, void *buf, size_t size);

/**
 * @brief Write data to console.
 *
 * @param dummy ignored, present to follow write() prototype
 * @param buf buffer to write data to
 * @param size maximum number of bytes to write
 * @return =>0, number of actually written bytes (can be less than size param)
 *         <0, in case of error (e.g. -EAGAIN if timeout expired). errno
 *             variable is also set.
 */
ssize_t console_write(void *dummy, const void *buf, size_t size);

/** @brief Get next char from console input buffer.
 *
 *  Return next input character from console. If no characters available,
 *  this function will block. This function is similar to ANSI C
 *  getchar() function and is intended to ease porting of existing
 *  software. Before this function can be used, console_getchar_init()
 *  should be called once. This function is incompatible with native
 *  Zephyr callback-based console input processing, shell subsystem,
 *  or console_getline().
 *
 *  @return 0-255: a character read, including control characters.
 *          <0: error occurred.
 */
int console_getchar(void);

/** @brief Output a char to console (buffered).
 *
 *  Puts a character into console output buffer. It will be sent
 *  to a console asynchronously, e.g. using an IRQ handler.
 *
 *  @return <0 on error, otherwise 0.
 */
int console_putchar(char c);

/** @brief Initialize console_getline() call.
 *
 *  This function should be called once to initialize pull-style
 *  access to console via console_getline() function. This function
 *  supersedes, and incompatible with, callback (push-style) console
 *  handling (via console_input_fn callback, etc.).
 *
 *  @return N/A
 */
void console_getline_init(void);

/** @brief Get next line from console input buffer.
 *
 *  Return next input line from console. Until full line is available,
 *  this function will block. This function is similar to ANSI C
 *  gets() function (except a line is returned in system-owned buffer,
 *  and system takes care of the buffer overflow checks) and is
 *  intended to ease porting of existing software. Before this function
 *  can be used, console_getline_init() should be called once. This
 *  function is incompatible with native Zephyr callback-based console
 *  input processing, shell subsystem, or console_getchar().
 *
 *  @return A pointer to a line read, not including EOL character(s).
 *          A line resides in a system-owned buffer, so an application
 *          should finish any processing of this line immediately
 *          after console_getline() call, or the buffer can be reused.
 */
char *console_getline(void);

#ifdef __cplusplus
}
#endif

#endif /* ZEPHYR_INCLUDE_CONSOLE_CONSOLE_H_ */


text:
package com.gs.fw.common.mithra.util.fileparser;

import com.gs.fw.common.mithra.attribute.Attribute;
import com.gs.fw.common.mithra.attribute.SingleColumnAttribute;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ColumnarInStream
{
    private InputStream in;

    public ColumnarInStream(InputStream dataIn)
    {
        this.in = dataIn;
    }

    public int read() throws IOException
    {
        return in.read();
    }

    public BitsInBytes decodeColumnarNull(SingleColumnAttribute attr, List data) throws IOException
    {
        int hasNulls = in.read();
        if (hasNulls == 0)
        {
            return null;
        }
        BitsInBytes result = BitsInBytes.readFromInputStream(in, data.size());
        Attribute nullableAttribute = (Attribute) attr;
        for(int i=0;i<data.size();i++)
        {
            if (result.get(i))
            {
                nullableAttribute.setValueNull(data.get(i));
            }
        }
        return result;
    }

    public boolean fullyRead(byte[] bytes) throws IOException
    {
        int read = 0;
        while (read < bytes.length)
        {
            int localRead = in.read(bytes, read, bytes.length - read);
            if (localRead == -1)
            {
                return false;
            }
            read += localRead;
        }
        return true;
    }

    public int readInt() throws IOException
    {
        int ch1 = readWithException();
        int ch2 = readWithException();
        int ch3 = readWithException();
        int ch4 = readWithException();
        return (ch1 << 24) | (ch2 << 16) | (ch3 << 8) | ch4;
    }

    public final long readLong() throws IOException
    {
        return (((long)readWithException() << 56) |
                ((long)(readWithException() & 0xFF) << 48) |
                ((long)(readWithException() & 0xFF) << 40) |
                ((long)(readWithException() & 0xFF) << 32) |
                ((long)(readWithException() & 0xFF) << 24) |
                ((long)(readWithException() & 0xFF) << 16) |
                ((long)(readWithException() & 0xFF) <<  8) |
                ((long)(readWithException() & 0xFF)));
    }

    public byte readWithExceptionAsByte() throws IOException
    {
        return (byte) (readWithException() & 0xFF);
    }
    public int readWithException() throws IOException
    {
        int result = in.read();
        if (result == -1)
        {
            throw new EOFException();
        }
        return result;
    }

    public InputStream getInputStream()
    {
        return in;
    }

    public void setTimezoneId(String timezoneId)
    {
        //ignore for now
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.usfirst.frc.team1736.robot;

import org.usfirst.frc.team1736.lib.Calibration.Calibration;

import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Spark;

public class GearPickup {
	private static GearPickup gearPickup = null;

	// Declare Motor Control
	Spark gearPickupMotor = new Spark(RobotConstants.INTAKE_MOTOR_PWM_PORT);

	// Declare Extender Control
	Solenoid intakeHPExtend = new Solenoid(RobotConstants.INTAKE_HP_EXTEND_SOLENOID_PORT);
	Solenoid intakeLPExtend = new Solenoid(RobotConstants.INTAKE_LP_EXTEND_SOLENOID_PORT);

	// Declaring Intake Calibration
	Calibration gearPickupSpeedCmd = new Calibration("Ground Pickup Gear Intake Motor Command", 1.0, 0.0, 1.0);

	// Intake Speed
	private final double pickupUp = 1.0;
	private static double pickupSpeedCommand = 0;

	OperatorController operatorControl;

	public static synchronized GearPickup getInstance() {
		if(gearPickup == null)
			gearPickup = new GearPickup();
		return gearPickup;
	}

	private GearPickup() {
		operatorControl = OperatorController.getInstance();

		// Init Motor to off
		gearPickupMotor.set(0.0);

		// Init position to up
	}

	public void update() {
		if(operatorControl.getPickupPosCmd() && operatorControl.getPickupSpeedCmd()) {
			// pickup gear - down and motors run fwd
			gearPickupMotor.set(gearPickupSpeedCmd.get());
			IntakeExtend();
		}
		else if(operatorControl.getPickupPosCmd() && !(operatorControl.getPickupSpeedCmd())) {
			// Gear placement - down and motor off
			gearPickupMotor.set(0.0);
			IntakeExtend();
		}
		else if(!(operatorControl.getPickupPosCmd()) && operatorControl.getPickupSpeedCmd()) {
			// eject gear - down and motor runs rev
			gearPickupMotor.set(-gearPickupSpeedCmd.get());
			IntakeExtend();
		}
		else {// !(operatorControl.getPickupPosCmd()) && !(operatorControl.getPickupSpeedCmd())
			// Not using - up and motor off
			gearPickupMotor.set(0.0);
			IntakeRetract();
		}
	}

	public void IntakeExtend() {
		intakeLPExtend.set(true);
	}

	public void IntakeRetract() {
		intakeLPExtend.set(false);
	}

	public boolean getPosCmd() {
		return operatorControl.getPickupPosCmd();
	}

	public boolean getSpeedCmd() {
		return operatorControl.getPickupSpeedCmd();
	}
}


text:
Simple reddit browser
======================

Minimal reddit redesign


text:
//
//  NetworkTools.m
//  NetNews
//
//  Created by Lukj on 2017/3/10.
//  Copyright © 2017年 lukj. All rights reserved.
//

#import "NetworkTools.h"

@implementation NetworkTools

+ (instancetype)sharedTools{

    static NetworkTools *tools;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tools = [[NetworkTools alloc] initWithBaseURL:[NSURL URLWithString:@"http://c.m.163.com/nc/article/list/"]];
    });

    return tools;
}

/**
 通用的请求方式

 @param requestType 请求的类型
 @param urlStr 请求的地址
 @param params 请求的参数
 @param successBlock 成功的回调
 @param failureBlock 失败的回调
 */
- (void)requestWithType:(RequestType)requestType andUrlStr:(NSString *)urlStr andParams:(id)params andSuccessBlock:(void(^)(id responseObject))successBlock andFailureBlock:(void(^)(id error))failureBlock{

    if (requestType == GET) {

        [self GET:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            successBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failureBlock(error);
        }];

    }else{

        [self POST:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            successBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error:%@",error);
            failureBlock(error);
        }];
    }

}

@end


text:
package standard

import (
	"github.com/labstack/gommon/log"
	"github.com/stretchr/testify/assert"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

func TestResponse_WriteHeader(t *testing.T) {
	recorder := httptest.NewRecorder()
	resp := NewResponse(recorder, log.New("echo"))

	resp.WriteHeader(http.StatusNotFound)
	assert.Equal(t, http.StatusNotFound, resp.Status())

	assert.True(t, resp.Committed())
}

func TestResponse_Write(t *testing.T) {
	recorder := httptest.NewRecorder()
	resp := NewResponse(recorder, log.New("echo"))
	resp.Write([]byte("Hello"))
	assert.Equal(t, int64(5), resp.Size())
	if body, err := ioutil.ReadAll(recorder.Body); assert.NoError(t, err) {
		assert.Equal(t, "Hello", string(body))
	}
	resp.Flush()
	assert.True(t, recorder.Flushed)
}

func TestResponse_SetCookie(t *testing.T) {
	recorder := httptest.NewRecorder()
	resp := NewResponse(recorder, log.New("echo"))

	resp.SetCookie(&Cookie{&http.Cookie{
		Name:     "session",
		Value:    "securetoken",
		Path:     "/",
		Domain:   "github.com",
		Expires:  time.Date(2016, time.January, 1, 0, 0, 0, 0, time.UTC),
		Secure:   true,
		HttpOnly: true,
	}})

	assert.Equal(t, "session=securetoken; Path=/; Domain=github.com; Expires=Fri, 01 Jan 2016 00:00:00 GMT; HttpOnly; Secure", recorder.Header().Get("Set-Cookie"))
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<meta-runner name="Publish TeamCity Artifacts">
  <description>Publishes artifacts to TeamCity</description>
  <settings>
    <parameters>
      <param name="system.artifact.paths" value="" spec="text description='Comma-separated paths to artifacts in TeamCity format' display='normal' label='Paths to artifacts:' validationMode='not_empty'" />
    </parameters>
    <build-runners>
      <runner name="" type="Ant">
        <parameters>
          <param name="build-file"><![CDATA[<project name="publish-artifacts">

<target name="publish">
<echo>##teamcity[publishArtifacts '${artifact.paths}']</echo>
</target>

</project>]]></param>
          <param name="build-file-path" value="build.xml" />
          <param name="target" value="publish" />
          <param name="teamcity.coverage.emma.include.source" value="true" />
          <param name="teamcity.coverage.emma.instr.parameters" value="-ix -*Test*" />
          <param name="teamcity.coverage.idea.includePatterns" value="*" />
          <param name="teamcity.step.mode" value="default" />
          <param name="use-custom-build-file" value="true" />
        </parameters>
      </runner>
    </build-runners>
    <requirements />
  </settings>
</meta-runner>


text:
title: It's Not Just Standing Up
disqus_identifier: 2006-08-its-not-just-standing-up
comments: true
---

Recently, I came across this gem from Martin Fowler's site called "[It's Not Just Standing Up: Patterns for Daily Stand-up Meetings][1]". If your stands up are starting to hit a rut, you will definitely want to read this article.

Some of my favorite parts of this article:

>Good stand-ups will feel **supportive**. When people are knocked down every time they raise a problem, they will tend to stop raising problems. Beyond preventing removal of obstacles, a non-supportive stand-up works against team dynamics. The stand-up instead becomes a ritual that team members dread.

>Regular interruption by observers is very disruptive to the delivery team by challenging the premise that the daily stand-up is primarily for the delivery team. Interruption also threatens *Fifteen Minutes or Less*. Enforce *Pigs and Chickens*.

I *love* this article. Absolutely recommended.

[1]:http://martinfowler.com/articles/itsNotJustStandingUp.html


text:
import time

import factory
import factory.django
import factory.fuzzy
import ldap
import volatildap
from django.conf import settings
from django.contrib.auth import hashers as auth_hashers
from django.contrib.auth import models as auth_models
from django.core import management
from django.db import connections
from django.db.models import Count, Q
from django.test import TestCase
from django.utils import timezone

from examples.models import (ConcreteGroup, FooGroup, LdapGroup,
                             LdapMultiPKRoom, LdapUser)
from ldapdb.backends.ldap.compiler import SQLCompiler, query_as_ldap

groups = ('ou=groups,dc=example,dc=org', {
    'objectClass': ['top', 'organizationalUnit'], 'ou': ['groups']})
people = ('ou=people,dc=example,dc=org', {
    'objectClass': ['top', 'organizationalUnit'], 'ou': ['groups']})
contacts = ('ou=contacts,ou=groups,dc=example,dc=org', {
    'objectClass': ['top', 'organizationalUnit'], 'ou': ['groups']})
users = ('ou=users,ou=people,dc=example,dc=org', {
    'objectClass': ['top', 'organizationalUnit'], 'ou': ['users']})
rooms = ('ou=rooms,dc=example,dc=org', {
    'objectClass': ['top', 'organizationalUnit'], 'ou': ['rooms']})
foogroup = ('cn=foogroup,ou=groups,dc=example,dc=org', {
    'objectClass': ['posixGroup'], 'memberUid': ['foouser', 'baruser'],
    'gidNumber': ['1000'], 'cn': ['foogroup']})
bargroup = ('cn=bargroup,ou=groups,dc=example,dc=org', {
    'objectClass': ['posixGroup'], 'memberUid': ['zoouser', 'baruser'],
    'gidNumber': ['1001'], 'cn': ['bargroup']})
wizgroup = ('cn=wizgroup,ou=groups,dc=example,dc=org', {
    'objectClass': ['posixGroup'], 'memberUid': ['wizuser', 'baruser'],
    'gidNumber': ['1002'], 'cn': ['wizgroup']})
foouser = ('uid=foouser,ou=people,dc=example,dc=org', {
    'cn': [b'F\xc3\xb4o Us\xc3\xa9r'],
    'objectClass': ['posixAccount', 'shadowAccount', 'inetOrgPerson'],
    'loginShell': ['/bin/bash'],
    'jpegPhoto': [
        b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff'
        b'\xfe\x00\x1cCreated with GIMP on a Mac\xff\xdb\x00C\x00\x05\x03\x04'
        b'\x04\x04\x03\x05\x04\x04\x04\x05\x05\x05\x06\x07\x0c\x08\x07\x07\x07'
        b'\x07\x0f\x0b\x0b\t\x0c\x11\x0f\x12\x12\x11\x0f\x11\x11\x13\x16\x1c'
        b'\x17\x13\x14\x1a\x15\x11\x11\x18!\x18\x1a\x1d\x1d\x1f\x1f\x1f\x13'
        b'\x17"$"\x1e$\x1c\x1e\x1f\x1e\xff\xdb\x00C\x01\x05\x05\x05\x07\x06\x07'
        b'\x0e\x08\x08\x0e\x1e\x14\x11\x14\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e'
        b'\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e'
        b'\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e'
        b'\x1e\x1e\x1e\x1e\x1e\x1e\x1e\xff\xc0\x00\x11\x08\x00\x08\x00\x08\x03'
        b'\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x15\x00\x01\x01\x00\x00'
        b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\xff\xc4\x00'
        b'\x19\x10\x00\x03\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        b'\x00\x00\x01\x02\x06\x11A\xff\xc4\x00\x14\x01\x01\x00\x00\x00\x00\x00'
        b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xc4\x00\x14\x11\x01'
        b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff'
        b'\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00\x9d\xf29wU5Q\xd6'
        b'\xfd\x00\x01\xff\xd9'],
    'uidNumber': ['2000'], 'gidNumber': ['1000'], 'sn': [b'Us\xc3\xa9r'],
    'homeDirectory': ['/home/foouser'], 'givenName': [b'F\xc3\xb4o'],
    'uid': ['foouser']})
baruser = ('uid=baruser,ou=users,ou=people,dc=example,dc=org', {
    'objectClass': ['posixAccount', 'shadowAccount', 'inetOrgPerson'],
    'cn': ['Bar Test'], 'givenName': ['Test'], 'sn': ['Bar'],
    'uid': ['baruser'], 'uidNumber': ['2001'], 'gidNumber': ['1000'],
    'homeDirectory': ['/home/baruser'], 'loginShell': ['/bin/bash'],
    'jpegPhoto': []})

class UserFactory(factory.django.DjangoModelFactory):
    username = factory.Faker('username')
    email = factory.Faker('email')
    is_active = True
    password = factory.LazyAttribute(lambda o: auth_hashers.make_password(o.cleartext_password))

    class Meta:
        model = auth_models.User

    class Params:
        cleartext_password = factory.fuzzy.FuzzyText(30)
        superuser = factory.Trait(
            is_staff=True,
            is_superuser=True,
        )

class BaseTestCase(TestCase):
    directory = {}

    databases = ['default', 'ldap']

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.ldap_server = volatildap.LdapServer(
            initial_data=cls.directory,
            schemas=['core.schema', 'cosine.schema', 'inetorgperson.schema', 'nis.schema'],
        )
        settings.DATABASES['ldap']['USER'] = cls.ldap_server.rootdn
        settings.DATABASES['ldap']['PASSWORD'] = cls.ldap_server.rootpw
        settings.DATABASES['ldap']['NAME'] = cls.ldap_server.uri

    @classmethod
    def tearDownClass(cls):
        cls.ldap_server.stop()
        super().tearDownClass()

    def setUp(self):
        super().setUp()
        self.ldap_server.start()

class ConnectionTestCase(BaseTestCase):
    directory = dict([people, foouser])

    def test_system_checks(self):
        management.call_command('check')

    def test_make_migrations(self):
        management.call_command('makemigrations', dry_run=True)

    def test_connection_options(self):
        LdapUser.objects.get(username='foouser')
        # self.assertEqual(self.ldapobj.get_option(ldap.OPT_X_TLS_DEMAND), True)

    def test_start_tls(self):
        # self.assertFalse(self.ldapobj.tls_enabled)
        LdapUser.objects.get(username='foouser')

    def test_bound_as_admin(self):
        LdapUser.objects.get(username='foouser')
        # self.assertEqual(self.ldapobj.bound_as, admin[0])

    def test_reconect(self):
        LdapUser.objects.get(username='foouser')
        self.ldap_server.stop()
        self.ldap_server.start()
        LdapUser.objects.get(username='foouser')

class GroupTestCase(BaseTestCase):
    directory = dict([groups, foogroup, bargroup, wizgroup, people, foouser])

    def test_count_none(self):
        qs = LdapGroup.objects.none()
        self.assertEqual(qs.count(), 0)

    def test_count_all(self):
        qs = LdapGroup.objects.all()
        self.assertEqual(qs.count(), 3)

    def test_aggregate_count(self):
        qs = LdapGroup.objects.all()
        result = qs.aggregate(num_groups=Count('name'))
        self.assertEqual(result['num_groups'], 3)

    def test_annotate_count(self):
        groups = LdapGroup.objects.order_by('name').annotate(num_usernames=Count('usernames'))
        self.assertEqual(len(groups), 3)
        self.assertEqual(groups[0].name, 'bargroup')
        self.assertEqual(groups[0].num_usernames, 2)
        self.assertEqual(groups[1].name, 'foogroup')
        self.assertEqual(groups[1].num_usernames, 2)
        self.assertEqual(groups[2].name, 'wizgroup')
        self.assertEqual(groups[2].num_usernames, 2)
        groups = LdapGroup.objects.filter(name='foogroup').annotate(num_usernames=Count('usernames'))
        self.assertEqual(len(groups), 1)
        self.assertEqual(groups[0].name, 'foogroup')
        self.assertEqual(groups[0].num_usernames, 2)
        groups = LdapGroup.objects.annotate(num_usernames=Count('usernames')).filter(name='foogroup')
        self.assertEqual(len(groups), 1)
        self.assertEqual(groups[0].name, 'foogroup')
        self.assertEqual(groups[0].num_usernames, 2)

    def test_length_all(self):
        qs = LdapGroup.objects.all()
        self.assertEqual(len(qs), 3)

    def test_length_none(self):
        qs = LdapGroup.objects.none()
        self.assertEqual(len(qs), 0)

    def test_ldap_filter(self):
        def get_filterstr(qs):
            connection = connections['ldap']
            compiler = SQLCompiler(
                query=qs.query,
                connection=connection,
                using=None,
            )
            return query_as_ldap(qs.query, compiler, connection).filterstr

        # single filter
        qs = LdapGroup.objects.filter(name='foogroup')
        self.assertEqual(get_filterstr(qs), '(&(objectClass=posixGroup)(cn=foogroup))')

        qs = LdapGroup.objects.filter(Q(name='foogroup'))
        self.assertEqual(get_filterstr(qs), '(&(objectClass=posixGroup)(cn=foogroup))')

        # AND filter
        qs = LdapGroup.objects.filter(gid=1000, name='foogroup')
        self.assertIn(get_filterstr(qs), [
            '(&(objectClass=posixGroup)(&(gidNumber=1000)(cn=foogroup)))',
            '(&(objectClass=posixGroup)(&(cn=foogroup)(gidNumber=1000)))',
        ])

        qs = LdapGroup.objects.filter(Q(gid=1000) & Q(name='foogroup'))
        self.assertIn(get_filterstr(qs), [
            '(&(objectClass=posixGroup)(&(gidNumber=1000)(cn=foogroup)))',
            '(&(objectClass=posixGroup)(&(cn=foogroup)(gidNumber=1000)))',
        ])

        # OR filter
        qs = LdapGroup.objects.filter(Q(gid=1000) | Q(name='foogroup'))
        self.assertIn(get_filterstr(qs), [
            '(&(objectClass=posixGroup)(|(gidNumber=1000)(cn=foogroup)))',
            '(&(objectClass=posixGroup)(|(cn=foogroup)(gidNumber=1000)))',
        ])

        # single exclusion
        qs = LdapGroup.objects.exclude(name='foogroup')
        self.assertEqual(get_filterstr(qs), '(&(objectClass=posixGroup)(!(cn=foogroup)))')

        qs = LdapGroup.objects.filter(~Q(name='foogroup'))
        self.assertEqual(get_filterstr(qs), '(&(objectClass=posixGroup)(!(cn=foogroup)))')

        # multiple exclusion
        qs = LdapGroup.objects.exclude(name='foogroup', gid=1000)
        self.assertIn(get_filterstr(qs), [
            '(&(objectClass=posixGroup)(!(&(gidNumber=1000)(cn=foogroup))))',
            '(&(objectClass=posixGroup)(!(&(cn=foogroup)(gidNumber=1000))))',
        ])

        qs = LdapGroup.objects.filter(name='foogroup').exclude(gid=1000)
        self.assertIn(get_filterstr(qs), [
            '(&(objectClass=posixGroup)(&(cn=foogroup)(!(gidNumber=1000))))',
            '(&(objectClass=posixGroup)(&(!(gidNumber=1000))(cn=foogroup)))',
        ])

    def test_filter(self):
        qs = LdapGroup.objects.filter(name='foogroup')
        self.assertEqual(qs.count(), 1)

        qs = LdapGroup.objects.filter(name='foogroup')
        self.assertEqual(len(qs), 1)

        g = qs[0]
        self.assertEqual(g.dn, 'cn=foogroup,%s' % LdapGroup.base_dn)
        self.assertEqual(g.name, 'foogroup')
        self.assertEqual(g.gid, 1000)
        self.assertCountEqual(g.usernames, ['foouser', 'baruser'])

        # try to filter non-existent entries
        qs = LdapGroup.objects.filter(name='does_not_exist')
        self.assertEqual(qs.count(), 0)

        qs = LdapGroup.objects.filter(name='does_not_exist')
        self.assertEqual(len(qs), 0)

    def test_get(self):
        g = LdapGroup.objects.get(name='foogroup')
        self.assertEqual(g.dn, 'cn=foogroup,%s' % LdapGroup.base_dn)
        self.assertEqual(g.name, 'foogroup')
        self.assertEqual(g.gid, 1000)
        self.assertCountEqual(g.usernames, ['foouser', 'baruser'])

        # try to get a non-existent entry
        self.assertRaises(LdapGroup.DoesNotExist, LdapGroup.objects.get,
                          name='does_not_exist')

    def test_exists(self):
        qs = LdapGroup.objects.filter(name='foogroup')
        self.assertTrue(qs.exists())

        qs2 = LdapGroup.objects.filter(name='missing')
        self.assertFalse(qs2.exists())

    def test_get_by_dn(self):
        g = LdapGroup.objects.get(dn='cn=foogroup,%s' % LdapGroup.base_dn)
        self.assertEqual(g.dn, 'cn=foogroup,%s' % LdapGroup.base_dn)
        self.assertEqual(g.name, 'foogroup')
        self.assertEqual(g.gid, 1000)
        self.assertCountEqual(g.usernames, ['foouser', 'baruser'])

    def test_gid_lookup(self):
        g = LdapGroup.objects.get(gid__in=[1000, 2000, 3000])
        self.assertEqual(g.dn, 'cn=foogroup,%s' % LdapGroup.base_dn)
        self.assertEqual(g.name, 'foogroup')
        self.assertEqual(g.gid, 1000)
        self.assertCountEqual(g.usernames, ['foouser', 'baruser'])

    def test_insert(self):
        g = LdapGroup()
        g.name = 'newgroup'
        g.gid = 1010
        g.usernames = ['someuser', 'foouser']
        g.save()

        # check group was created
        new = LdapGroup.objects.get(name='newgroup')
        self.assertEqual(new.name, 'newgroup')
        self.assertEqual(new.gid, 1010)
        self.assertCountEqual(new.usernames, ['someuser', 'foouser'])

    def test_create(self):
        LdapGroup.objects.create(
            name='newgroup',
            gid=1010,
            usernames=['someuser', 'foouser'],
        )

        # check group was created
        new = LdapGroup.objects.get(name='newgroup')
        self.assertEqual(new.name, 'newgroup')
        self.assertEqual(new.gid, 1010)
        self.assertCountEqual(new.usernames, ['someuser', 'foouser'])

    def test_order_by(self):
        # ascending name
        qs = LdapGroup.objects.order_by('name')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].name, 'bargroup')
        self.assertEqual(qs[1].name, 'foogroup')
        self.assertEqual(qs[2].name, 'wizgroup')

        # descending name
        qs = LdapGroup.objects.order_by('-name')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].name, 'wizgroup')
        self.assertEqual(qs[1].name, 'foogroup')
        self.assertEqual(qs[2].name, 'bargroup')

        # ascending gid
        qs = LdapGroup.objects.order_by('gid')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].gid, 1000)
        self.assertEqual(qs[1].gid, 1001)
        self.assertEqual(qs[2].gid, 1002)

        # descending gid
        qs = LdapGroup.objects.order_by('-gid')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].gid, 1002)
        self.assertEqual(qs[1].gid, 1001)
        self.assertEqual(qs[2].gid, 1000)

        # ascending pk
        qs = LdapGroup.objects.order_by('pk')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].name, 'bargroup')
        self.assertEqual(qs[1].name, 'foogroup')
        self.assertEqual(qs[2].name, 'wizgroup')

        # descending pk
        qs = LdapGroup.objects.order_by('-pk')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].name, 'wizgroup')
        self.assertEqual(qs[1].name, 'foogroup')
        self.assertEqual(qs[2].name, 'bargroup')

        # ascending dn
        qs = LdapGroup.objects.order_by('dn')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].name, 'bargroup')
        self.assertEqual(qs[1].name, 'foogroup')
        self.assertEqual(qs[2].name, 'wizgroup')

        # descending dn
        qs = LdapGroup.objects.order_by('-dn')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].name, 'wizgroup')
        self.assertEqual(qs[1].name, 'foogroup')
        self.assertEqual(qs[2].name, 'bargroup')

    def test_bulk_delete(self):
        LdapGroup.objects.all().delete()

        qs = LdapGroup.objects.all()
        self.assertEqual(len(qs), 0)

    def test_bulk_delete_none(self):
        LdapGroup.objects.none().delete()

        qs = LdapGroup.objects.all()
        self.assertEqual(len(qs), 3)

    def test_slice(self):
        qs = LdapGroup.objects.order_by('gid')
        objs = list(qs)
        self.assertEqual(len(objs), 3)
        self.assertEqual(objs[0].gid, 1000)
        self.assertEqual(objs[1].gid, 1001)
        self.assertEqual(objs[2].gid, 1002)

        # limit only
        qs = LdapGroup.objects.order_by('gid')
        objs = qs[:2]
        self.assertEqual(objs.count(), 2)

        objs = qs[:2]
        self.assertEqual(len(objs), 2)
        self.assertEqual(objs[0].gid, 1000)
        self.assertEqual(objs[1].gid, 1001)

        # offset only
        qs = LdapGroup.objects.order_by('gid')
        objs = qs[1:]
        self.assertEqual(objs.count(), 2)

        objs = qs[1:]
        self.assertEqual(len(objs), 2)
        self.assertEqual(objs[0].gid, 1001)
        self.assertEqual(objs[1].gid, 1002)

        # offset and limit
        qs = LdapGroup.objects.order_by('gid')
        objs = qs[1:2]
        self.assertEqual(objs.count(), 1)

        objs = qs[1:2]
        self.assertEqual(len(objs), 1)
        self.assertEqual(objs[0].gid, 1001)

    def test_update(self):
        g = LdapGroup.objects.get(name='foogroup')
        g.gid = 1002
        g.usernames = ['foouser2', u'baruseeer2']
        g.save()

        # check group was updated
        new = LdapGroup.objects.get(name='foogroup')
        self.assertEqual(new.name, 'foogroup')
        self.assertEqual(new.gid, 1002)
        self.assertCountEqual(new.usernames, ['foouser2', u'baruseeer2'])

    def test_update_change_dn(self):
        g = LdapGroup.objects.get(name='foogroup')
        g.name = 'foogroup2'
        g.save()
        self.assertEqual(g.dn, 'cn=foogroup2,%s' % LdapGroup.base_dn)

        # check group was updated
        new = LdapGroup.objects.get(name='foogroup2')
        self.assertEqual(new.name, 'foogroup2')
        self.assertEqual(new.gid, 1000)
        self.assertCountEqual(new.usernames, ['foouser', 'baruser'])

    def test_values(self):
        qs = sorted(LdapGroup.objects.values_list('name', flat=True))
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0], 'bargroup')
        self.assertEqual(qs[1], 'foogroup')
        self.assertEqual(qs[2], 'wizgroup')

    def test_search(self):
        qs = sorted(LdapGroup.objects.filter(name__contains='foo'))
        self.assertEqual(len(qs), 1)
        self.assertEqual(qs[0].name, 'foogroup')

    def test_values_list(self):
        qs = sorted(LdapGroup.objects.values_list('name'))
        self.assertEqual(len(qs), 3)
        self.assertEqual(list(qs[0]), ['bargroup'])
        self.assertEqual(list(qs[1]), ['foogroup'])
        self.assertEqual(list(qs[2]), ['wizgroup'])

    def test_delete(self):
        g = LdapGroup.objects.get(name='foogroup')
        g.delete()

        qs = LdapGroup.objects.all()
        self.assertEqual(len(qs), 2)

    def test_paginated_search(self):
        # This test will change the settings, assert we don't break things
        self.assertIsNone(settings.DATABASES['ldap'].get('CONNECTION_OPTIONS', {}).get('page_size'))

        # Test without BATCH_SIZE
        qs = LdapGroup.objects.filter(name__contains='group').order_by('name')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].name, 'bargroup')
        self.assertEqual(qs[1].name, 'foogroup')
        self.assertEqual(qs[2].name, 'wizgroup')

        # Set new page size
        settings.DATABASES['ldap']['CONNECTION_OPTIONS'] = settings.DATABASES['ldap'].get('CONNECTION_OPTIONS', {})
        settings.DATABASES['ldap']['CONNECTION_OPTIONS']['page_size'] = 1
        connections['ldap'].close()  # Force connection reload

        qs = LdapGroup.objects.filter(name__contains='group').order_by('name')
        self.assertEqual(len(qs), 3)
        self.assertEqual(qs[0].name, 'bargroup')
        self.assertEqual(qs[1].name, 'foogroup')
        self.assertEqual(qs[2].name, 'wizgroup')

        # Restore previous configuration
        del settings.DATABASES['ldap']['CONNECTION_OPTIONS']['page_size']

    def test_listfield(self):
        g = LdapGroup.objects.get(name='foogroup')
        self.assertCountEqual(['foouser', 'baruser'], g.usernames)

        # Try to filter on the list field, with and without contains
        qs = LdapGroup.objects.filter(usernames='foouser')
        self.assertEqual(qs.count(), 1)
        qs = LdapGroup.objects.filter(usernames__contains='foouser')
        self.assertEqual(qs.count(), 1)

        # Try to filter negatively on the list field, with and without contains
        qs = LdapGroup.objects.filter(~Q(usernames='foouser'))
        self.assertEqual(qs.count(), 2)
        qs = LdapGroup.objects.filter(~Q(usernames__contains='foouser'))
        self.assertEqual(qs.count(), 2)

        # Try to exclude on the list field, with and without contains
        qs = LdapGroup.objects.exclude(usernames='foouser')
        self.assertEqual(qs.count(), 2)
        qs = LdapGroup.objects.exclude(usernames__contains='foouser')
        self.assertEqual(qs.count(), 2)

    def test_listfield_manipulation(self):
        g = LdapGroup.objects.get(name='foogroup')
        self.assertCountEqual(['foouser', 'baruser'], g.usernames)

        # Replace values, with duplicated.
        g.usernames = ['john', 'jane', 'john']
        g.save()
        g = LdapGroup.objects.get(name='foogroup')
        self.assertCountEqual(['john', 'jane'], g.usernames)

        # Clear values
        g.usernames = []
        g.save()
        g = LdapGroup.objects.get(name='foogroup')
        self.assertEqual([], g.usernames)

class GroupSubclassingTestCase(BaseTestCase):
    directory = dict([groups, foogroup, bargroup, wizgroup, people, foouser])

    def test_concrete_group(self):
        g = ConcreteGroup.objects.get(name='foogroup')
        self.assertCountEqual(['foouser', 'baruser'], g.usernames)

        g.name = 'modified'
        g.save()

        g = ConcreteGroup.objects.get(name='modified')
        self.assertCountEqual(['foouser', 'baruser'], g.usernames)

class UserTestCase(BaseTestCase):
    directory = dict([groups, people, users, foouser, baruser])

    def test_verbose_name(self):
        self.assertEqual("Prime name", LdapUser._meta.get_field('first_name').verbose_name)
        self.assertEqual("Final name", LdapUser._meta.get_field('last_name').verbose_name)

    def test_get(self):
        u = LdapUser.objects.get(username='foouser')
        self.assertEqual(u.first_name, u'Fôo')
        self.assertEqual(u.last_name, u'Usér')
        self.assertEqual(u.full_name, u'Fôo Usér')

        self.assertEqual(u.group, 1000)
        self.assertEqual(u.home_directory, '/home/foouser')
        self.assertEqual(u.uid, 2000)
        self.assertEqual(u.username, 'foouser')
        self.assertEqual(
            u.photo,
            b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01'
            b'\x01\x00H\x00H\x00\x00\xff\xfe\x00\x1cCreated with '
            b'GIMP on a Mac\xff\xdb\x00C\x00\x05\x03\x04\x04\x04'
            b'\x03\x05\x04\x04\x04\x05\x05\x05\x06\x07\x0c\x08'
            b'\x07\x07\x07\x07\x0f\x0b\x0b\t\x0c\x11\x0f\x12\x12'
            b'\x11\x0f\x11\x11\x13\x16\x1c\x17\x13\x14\x1a\x15'
            b'\x11\x11\x18!\x18\x1a\x1d\x1d\x1f\x1f\x1f\x13\x17'
            b'"$"\x1e$\x1c\x1e\x1f\x1e\xff\xdb\x00C\x01\x05\x05'
            b'\x05\x07\x06\x07\x0e\x08\x08\x0e\x1e\x14\x11\x14'
            b'\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e'
            b'\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e'
            b'\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e'
            b'\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e'
            b'\x1e\x1e\xff\xc0\x00\x11\x08\x00\x08\x00\x08\x03'
            b'\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x15'
            b'\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00'
            b'\x00\x00\x00\x00\x00\x00\x08\xff\xc4\x00\x19\x10'
            b'\x00\x03\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00'
            b'\x00\x00\x00\x00\x00\x01\x02\x06\x11A\xff\xc4\x00'
            b'\x14\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00'
            b'\x00\x00\x00\x00\x00\x00\x00\xff\xc4\x00\x14\x11'
            b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
            b'\x00\x00\x00\x00\x00\xff\xda\x00\x0c\x03\x01\x00'
            b'\x02\x11\x03\x11\x00?\x00\x9d\xf29wU5Q\xd6\xfd\x00'
            b'\x01\xff\xd9',
        )

        self.assertRaises(LdapUser.DoesNotExist, LdapUser.objects.get,
                          username='does_not_exist')

    def test_update(self):
        # slapd removes microsecond details.
        before = timezone.now().replace(microsecond=0)

        u = LdapUser.objects.get(username='foouser')
        u.first_name = u'Fôo2'
        u.save()

        after = timezone.now().replace(microsecond=0)

        self.assertLessEqual(before, u.last_modified)
        self.assertLessEqual(u.last_modified, after)

        # make sure DN gets updated if we change the pk
        u.username = 'foouser2'
        u.save()
        self.assertEqual(u.dn, 'uid=foouser2,%s' % LdapUser.base_dn)

    def test_charfield_empty_values(self):
        """CharField should accept empty values."""
        u = LdapUser.objects.get(username='foouser')
        # Both '' and None are accepted
        u.phone = ''
        u.mobile_phone = None
        u.save()

        # '' and None are normalized to ''.
        u2 = LdapUser.objects.get(dn=u.dn)
        self.assertEqual('', u2.phone)
        self.assertEqual('', u2.mobile_phone)

    def test_intfield_empty_value(self):
        u = LdapUser.objects.get(username='foouser')
        # Set to 0
        u.uid = 0
        u.save()

        # Ensure we still fetch a '0', not an empty ID.
        u2 = LdapUser.objects.get(dn=u.dn)
        self.assertEqual(0, u2.uid)

    def test_datetime_lookup(self):

        # Due to slapd ignoring microsecond in last_modified,
        # wait for one second to ensure that all timestamps are on the proper
        # side of the 'before' boundary.
        time.sleep(1)
        before = timezone.now().replace(microsecond=0)

        qs = LdapUser.objects.filter(last_modified__gte=before)
        self.assertEqual([], list(qs))

        u = LdapUser.objects.get(username='foouser')
        u.first_name = u"Foo2"
        u.save()

        u = LdapUser.objects.get(username='foouser')
        self.assertLessEqual(before, u.last_modified)

        qs = LdapUser.objects.filter(last_modified__gte=before)
        self.assertEqual([u], list(qs))

        # Test __in lookup
        lm = u.last_modified
        u = LdapUser.objects.get(last_modified__in=[before, lm])
        self.assertEqual(u.username, 'foouser')

    def test_dn_consistency(self):
        u = LdapUser.objects.get(username='baruser')
        u.first_name = u"Barr"
        try:
            u.save()
        except ldap.LDAPError:
            self.fail("Cannot save object")
        # DN shouldn't be changed
        self.assertEqual(
            LdapUser.objects.get(username='baruser').dn,
            'uid=baruser,ou=users,ou=people,dc=example,dc=org')

class ScopedTestCase(BaseTestCase):
    directory = dict([groups, people, foogroup, contacts])

    def setUp(self):
        super().setUp()
        self.scoped_model = LdapGroup.scoped("ou=contacts,%s" %
                                             LdapGroup.base_dn)

    def test_scope(self):
        ScopedGroup = self.scoped_model

        qs = LdapGroup.objects.all()
        self.assertEqual(qs.count(), 1)

        qs = ScopedGroup.objects.all()
        self.assertEqual(qs.count(), 0)

        # create scoped group
        g2 = ScopedGroup()
        g2.name = "scopedgroup"
        g2.gid = 5000
        g2.save()

        qs = LdapGroup.objects.all()
        self.assertEqual(qs.count(), 2)

        qs = ScopedGroup.objects.all()
        self.assertEqual(qs.count(), 1)

        g2 = ScopedGroup.objects.get(name="scopedgroup")
        self.assertEqual(g2.name, u'scopedgroup')
        self.assertEqual(g2.gid, 5000)

class CompositePKTests(BaseTestCase):
    directory = dict([rooms])

    def test_create(self):
        room = LdapMultiPKRoom(
            name="Director office",
            number="42.01",
        )
        room.save()
        room = LdapMultiPKRoom.objects.get()
        self.assertEqual("cn=Director office+roomNumber=42.01,ou=rooms,dc=example,dc=org", room.dn)

    def test_fetch(self):
        room = LdapMultiPKRoom(
            name="Director office",
            number="42.01",
        )
        room.save()

        room2 = LdapMultiPKRoom.objects.get(number="42.01")
        self.assertEqual("Director office", room2.name)
        self.assertEqual("42.01", room2.number)

    def test_move(self):
        room = LdapMultiPKRoom.objects.create(
            name="Director office",
            number="42.01",
        )

        room.number = "42.02"
        room.save()

        qs = LdapMultiPKRoom.objects.all()
        self.assertEqual(1, len(qs))
        new_room = qs.get()
        self.assertEqual(room, new_room)
        self.assertEqual("42.02", new_room.number)
        self.assertEqual("cn=Director office+roomNumber=42.02,ou=rooms,dc=example,dc=org", new_room.dn)

    def test_update(self):
        room = LdapMultiPKRoom.objects.create(
            name="Director office",
            number="42.01",
            phone='+001234',
        )

        room.phone = '+004444'
        room.save()

        qs = LdapMultiPKRoom.objects.all()
        self.assertEqual(1, len(qs))
        new_room = qs.get()
        self.assertEqual(room, new_room)
        self.assertEqual("42.01", new_room.number)
        self.assertEqual('+004444', new_room.phone)
        self.assertEqual("cn=Director office+roomNumber=42.01,ou=rooms,dc=example,dc=org", new_room.dn)

    def test_update_ambiguous_pk(self):
        """Updating an object where two entries with close pks exist shouldn't fail.

        See #159.
        """
        room1 = LdapMultiPKRoom.objects.create(
            name="Director office",
            number="42.01",
            phone='+001234',
        )
        LdapMultiPKRoom.objects.create(
            name="Director office",
            number="42.01b",
            phone='+001111',
        )

        room1.phone = '+004444'
        room1.save()

        qs = LdapMultiPKRoom.objects.all()
        self.assertEqual(2, len(qs))
        new_room = qs.get(number="42.01")
        self.assertEqual("42.01", new_room.number)
        self.assertEqual('+004444', new_room.phone)
        self.assertEqual("cn=Director office+roomNumber=42.01,ou=rooms,dc=example,dc=org", new_room.dn)

class AdminTestCase(BaseTestCase):
    directory = dict([groups, people, foouser, foogroup, bargroup])

    def setUp(self):
        super().setUp()
        self._user = UserFactory(
            username='test_user',
            cleartext_password='password',
            superuser=True,
        )
        self.client.login(username="test_user", password="password")

    def test_index(self):
        response = self.client.get('/admin/examples/')
        self.assertContains(response, "Ldap groups")
        self.assertContains(response, "Ldap users")

    def test_group_list(self):
        response = self.client.get('/admin/examples/ldapgroup/')
        self.assertContains(response, "Ldap groups")
        self.assertContains(response, "foogroup")
        self.assertContains(response, "1000")

        # order by name
        response = self.client.get('/admin/examples/ldapgroup/?o=1')
        self.assertContains(response, "Ldap groups")
        self.assertContains(response, "foogroup")
        self.assertContains(response, "1000")

        # order by gid
        response = self.client.get('/admin/examples/ldapgroup/?o=2')
        self.assertContains(response, "Ldap groups")
        self.assertContains(response, "foogroup")
        self.assertContains(response, "1000")

    def test_group_detail(self):
        response = self.client.get('/admin/examples/ldapgroup/foogroup/', follow=True)
        self.assertContains(response, "foogroup")
        self.assertContains(response, "1000")

    def test_group_add(self):
        response = self.client.post('/admin/examples/ldapgroup/add/',
                                    {'gid': '1002', 'name': 'wizgroup'})
        self.assertRedirects(response, '/admin/examples/ldapgroup/')
        qs = LdapGroup.objects.all()
        self.assertEqual(qs.count(), 3)

    def test_group_delete(self):
        response = self.client.post(
            '/admin/examples/ldapgroup/foogroup/delete/', {'yes': 'post'})
        self.assertRedirects(response, '/admin/examples/ldapgroup/')
        qs = LdapGroup.objects.all()
        self.assertEqual(qs.count(), 1)

    def test_group_search(self):
        response = self.client.get('/admin/examples/ldapgroup/?q=foo')
        self.assertContains(response, "Ldap groups")
        self.assertContains(response, "foogroup")
        self.assertContains(response, "1000")

    def test_user_list(self):
        response = self.client.get('/admin/examples/ldapuser/')
        self.assertContains(response, "Ldap users")
        self.assertContains(response, "foouser")
        self.assertContains(response, "2000")

        # order by username
        response = self.client.get('/admin/examples/ldapuser/?o=1')
        self.assertContains(response, "Ldap users")
        self.assertContains(response, "foouser")
        self.assertContains(response, "2000")

        # order by uid
        response = self.client.get('/admin/examples/ldapuser/?o=2')
        self.assertContains(response, "Ldap users")
        self.assertContains(response, "foouser")
        self.assertContains(response, "2000")

    def test_user_detail(self):
        response = self.client.get('/admin/examples/ldapuser/foouser/', follow=True)
        self.assertContains(response, "foouser")
        self.assertContains(response, "2000")

    def test_user_delete(self):
        response = self.client.post('/admin/examples/ldapuser/foouser/delete/',
                                    {'yes': 'post'})
        self.assertRedirects(response, '/admin/examples/ldapuser/')

class FooGroupTestCase(BaseTestCase):
    directory = dict([groups, foogroup, bargroup, wizgroup, people, foouser])

    def as_ldap_query(self, qs):
        connection = connections['ldap']
        compiler = SQLCompiler(
            query=qs.query,
            connection=connection,
            using=None,
        )
        return query_as_ldap(qs.query, compiler, connection)

    def test_count_all(self):
        qs = FooGroup.objects.all()
        lq = self.as_ldap_query(qs)
        self.assertEqual(lq.base, groups[0])
        self.assertEqual(lq.filterstr, '(&(objectClass=posixGroup)(cn=foo*))')
        self.assertEqual(qs.count(), 1)

    def test_base_manager_dn(self):
        dn = foogroup[0]
        qs = FooGroup._base_manager.using(None).filter(dn=dn)
        lq = self.as_ldap_query(qs)
        self.assertEqual(lq.base, dn)
        self.assertEqual(lq.filterstr, '(&(objectClass=posixGroup))')
        self.assertEqual(qs.count(), 1)

    def test_update_group(self):
        g = FooGroup.objects.get(name='foogroup')
        g.gid = 1002
        g.usernames = ['foouser2', u'baruseeer2']
        g.save()

        # check group was updated
        new = FooGroup.objects.get(name='foogroup')
        self.assertEqual(new.name, 'foogroup')
        self.assertEqual(new.gid, 1002)
        self.assertCountEqual(new.usernames, ['foouser2', u'baruseeer2'])


text:
#include "Snp.h"

/**
  Call UNDI to stop the interface and changes the snp state.

  @param  Snp   Pointer to snp driver structure

  @retval EFI_SUCCESS            The network interface was stopped.
  @retval EFI_DEVICE_ERROR       SNP is not initialized.

**/
EFI_STATUS
PxeStop (
  SNP_DRIVER *Snp
  )
{
  Snp->Cdb.OpCode     = PXE_OPCODE_STOP;
  Snp->Cdb.OpFlags    = PXE_OPFLAGS_NOT_USED;
  Snp->Cdb.CPBsize    = PXE_CPBSIZE_NOT_USED;
  Snp->Cdb.DBsize     = PXE_DBSIZE_NOT_USED;
  Snp->Cdb.CPBaddr    = PXE_CPBADDR_NOT_USED;
  Snp->Cdb.DBaddr     = PXE_DBADDR_NOT_USED;
  Snp->Cdb.StatCode   = PXE_STATCODE_INITIALIZE;
  Snp->Cdb.StatFlags  = PXE_STATFLAGS_INITIALIZE;
  Snp->Cdb.IFnum      = Snp->IfNum;
  Snp->Cdb.Control    = PXE_CONTROL_LAST_CDB_IN_LIST;

  //
  // Issue UNDI command
  //
  DEBUG ((EFI_D_NET, "\nsnp->undi.stop()  "));

  (*Snp->IssueUndi32Command) ((UINT64)(UINTN) &Snp->Cdb);

  if (Snp->Cdb.StatCode != PXE_STATCODE_SUCCESS) {
    DEBUG (
      (EFI_D_WARN,
      "\nsnp->undi.stop()  %xh:%xh\n",
      Snp->Cdb.StatCode,
      Snp->Cdb.StatFlags)
      );

    return EFI_DEVICE_ERROR;
  }
  //
  // Set simple network state to Started and return success.
  //
  Snp->Mode.State = EfiSimpleNetworkStopped;
  return EFI_SUCCESS;
}

/**
  Changes the state of a network interface from "started" to "stopped."

  This function stops a network interface. This call is only valid if the network
  interface is in the started state. If the network interface was successfully
  stopped, then EFI_SUCCESS will be returned.

  @param  This                    A pointer to the EFI_SIMPLE_NETWORK_PROTOCOL
                                  instance.

  @retval EFI_SUCCESS             The network interface was stopped.
  @retval EFI_NOT_STARTED         The network interface has not been started.
  @retval EFI_INVALID_PARAMETER   This parameter was NULL or did not point to a
                                  valid EFI_SIMPLE_NETWORK_PROTOCOL structure.
  @retval EFI_DEVICE_ERROR        The command could not be sent to the network
                                  interface.
  @retval EFI_UNSUPPORTED         This function is not supported by the network
                                  interface.

**/
EFI_STATUS
EFIAPI
SnpUndi32Stop (
  IN EFI_SIMPLE_NETWORK_PROTOCOL *This
  )
{
  SNP_DRIVER  *Snp;
  EFI_TPL     OldTpl;
  EFI_STATUS  Status;

  if (This == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Snp = EFI_SIMPLE_NETWORK_DEV_FROM_THIS (This);

  OldTpl = gBS->RaiseTPL (TPL_CALLBACK);

  switch (Snp->Mode.State) {
  case EfiSimpleNetworkStarted:
    break;

  case EfiSimpleNetworkStopped:
    Status = EFI_NOT_STARTED;
    goto ON_EXIT;

  default:
    Status = EFI_DEVICE_ERROR;
    goto ON_EXIT;
  }

  Status = PxeStop (Snp);

ON_EXIT:
  gBS->RestoreTPL (OldTpl);

  return Status;
}


text:
package org.mule.tooling.lang.dw.parser.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface WeaveFunctionCallExpression extends WeaveExpression {

  @NotNull
  List<WeaveExpression> getExpressionList();

}


text:
/**
 *
 */
package com.github.nnest.sparrow.rest.command.document;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.github.nnest.sparrow.command.document.Get;
import com.github.nnest.sparrow.command.document.GetResultData;
import com.github.nnest.sparrow.command.document.MultiGetResultData;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;

/**
 * multiple get response
 *
 * @author brad.wu
 * @since 0.0.1
 * @version 0.0.1
 */
public class MultiGetResponse implements MultiGetResultData {
	@JsonProperty("docs")
	private List<InnerGetResultData> innerResponses = null;

	private int count = 0;
	private int successCount = 0;
	private int failCount = 0;

	/**
	 * (non-Javadoc)
	 *
	 * @see com.github.nnest.sparrow.ElasticCommandResultData#isSuccessful()
	 */
	@Override
	public boolean isSuccessful() {
		return this.count != 0 && this.count == this.successCount;
	}

	/**
	 * (non-Javadoc)
	 *
	 * @see com.github.nnest.sparrow.command.document.MultiGetResultData#isPartialSuccessful()
	 */
	@Override
	public boolean isPartialSuccessful() {
		return this.count != 0 && this.successCount != 0;
	}

	/**
	 * @return the count
	 */
	public int getInnerCommandCount() {
		return count;
	}

	/**
	 * @return the successCount
	 */
	public int getSuccessCount() {
		return successCount;
	}

	/**
	 * @return the failCount
	 */
	public int getFailCount() {
		return failCount;
	}

	/**
	 * @return the innerResponses
	 */
	public List<InnerGetResultData> getInnerResponses() {
		return this.innerResponses;
	}

	/**
	 * @param innerResponses
	 *            the innerResponses to set
	 */
	@JsonDeserialize(contentAs = InnerGetResponseReceiver.class)
	public void setInnerResponses(List<InnerGetResultData> innerResponses) {
		// reset counting
		count = 0;
		successCount = 0;
		failCount = 0;

		this.innerResponses = innerResponses;
		if (this.innerResponses != null && this.innerResponses.size() > 0) {
			Iterables.all(innerResponses, new Predicate<GetResultData>() {
				/**
				 * (non-Javadoc)
				 *
				 * @see com.google.common.base.Predicate#apply(java.lang.Object)
				 */
				@Override
				public boolean apply(GetResultData response) {
					count++;
					if (response.isSuccessful()) {
						successCount++;
					} else {
						failCount++;
					}
					return true;
				}
			});
		}
	}

	/**
	 * inner get response.
	 *
	 * @author brad.wu
	 * @since 0.0.1
	 * @version 0.0.1
	 */
	public static class InnerGetResponse extends GetResponse implements InnerGetResultData {
		private Get command = null;

		/**
		 * set command.
		 *
		 * @param command
		 *            command
		 */
		public void setCommand(Get command) {
			this.command = command;
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.command.document.MultiGetResultData.InnerGetResultData#getCommand()
		 */
		@Override
		public Get getCommand() {
			return command;
		}
	}

	/**
	 * inner get response receiver
	 *
	 * @author brad.wu
	 * @since 0.0.1
	 * @version 0.0.1
	 */
	public static class InnerGetResponseReceiver extends InnerGetResponse {
		private InnerGetResponse get = new InnerGetResponse();
		private JsonNode jsonNode = null;

		/**
		 * unwrap and get real {@linkplain GetResponse}
		 *
		 * @return real response
		 */
		public InnerGetResponse unwrap() {
			return this.get;
		}

		/**
		 * @return the jsonNode
		 */
		public JsonNode getJsonNode() {
			return jsonNode;
		}

		/**
		 * @param jsonNode
		 *            the jsonNode to set
		 */
		@JsonProperty("_source")
		public void setJsonNode(JsonNode jsonNode) {
			this.jsonNode = jsonNode;
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#getIndex()
		 */
		@Override
		public String getIndex() {
			return get.getIndex();
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#setIndex(java.lang.String)
		 */
		@Override
		@JsonProperty("_index")
		public void setIndex(String index) {
			get.setIndex(index);
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#getType()
		 */
		@Override
		public String getType() {
			return get.getType();
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#setType(java.lang.String)
		 */
		@Override
		@JsonProperty("_type")
		public void setType(String type) {
			get.setType(type);
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#getId()
		 */
		@Override
		public String getId() {
			return get.getId();
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#setId(java.lang.String)
		 */
		@Override
		@JsonProperty("_id")
		public void setId(String id) {
			get.setId(id);
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#getVersion()
		 */
		@Override
		public String getVersion() {
			return get.getVersion();
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#setVersion(java.lang.String)
		 */
		@Override
		@JsonProperty("_version")
		public void setVersion(String version) {
			get.setVersion(version);
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#isFound()
		 */
		@Override
		public boolean isFound() {
			return get.isFound();
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#setFound(boolean)
		 */
		@Override
		public void setFound(boolean found) {
			get.setFound(found);
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#isSuccessful()
		 */
		@Override
		public boolean isSuccessful() {
			return get.isSuccessful();
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#getDocument()
		 */
		@Override
		public <T> T getDocument() {
			return get.getDocument();
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.GetResponse#setDocument(java.lang.Object)
		 */
		@Override
		public void setDocument(Object document) {
			get.setDocument(document);
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.MultiGetResponse.InnerGetResponse#setCommand(com.github.nnest.sparrow.command.document.Get)
		 */
		@Override
		public void setCommand(Get command) {
			get.setCommand(command);
		}

		/**
		 * (non-Javadoc)
		 *
		 * @see com.github.nnest.sparrow.rest.command.document.MultiGetResponse.InnerGetResponse#getCommand()
		 */
		@Override
		public Get getCommand() {
			return get.getCommand();
		}

		/**
		 * transform document
		 *
		 * @param mapper
		 *            mapper
		 * @param documentType
		 *            document type
		 * @throws JsonProcessingException
		 *             exception
		 */
		public void transformDocument(ObjectMapper mapper, Class<?> documentType) throws JsonProcessingException {
			if (this.getJsonNode() != null) {
				this.setDocument(mapper.treeToValue(this.getJsonNode(), documentType));
			}
		}
	}
}


text:
require 'spec_helper'

module Checkout
  describe BestOfferCalculator do
    context "Discount Quantity on the Pricing Rule" do

      it "returns zero if there's no discount" do
        pricing_rule = {
          "B" => { unit_price: 15, offers: [] }
        }
        subject = BestOfferCalculator.new(pricing_rule)

        subject.discount("B", 2).should eq 0
      end

      it "calculates a discount price for a product if the basket quantity matches the rule discount quantity" do
        pricing_rule = {
          "B" => { unit_price: 15, offers: [ { discount: 0.4, quantity: 2 } ] }
        }
        subject = BestOfferCalculator.new(pricing_rule)

        subject.discount("B", 2).should eq 30*0.4
      end

      it "chooses the best discounts based on the remaining quantity of items" do
        pricing_rule = {
          "B" => { unit_price: 30, offers: [ { discount: 0.15, quantity: 2 }, { discount: 0.15, quantity: 3 } ] }
        }
        subject = BestOfferCalculator.new(pricing_rule)

        subject.discount("B", 5).should eq 60*0.15 + 90*0.15
      end

    end
  end
end


text:
CKEDITOR.plugins.setLang( 'flash', 'tr', {
	access: 'Kod


text:
package org.gradle.api.logging;

/**
 * The log levels supported by Gradle.
 */
public enum LogLevel {
    DEBUG,
    INFO,
    LIFECYCLE,
    WARN,
    QUIET,
    ERROR
}


text:
import { dirname, relative, resolve } from 'path';
import { Linter } from 'eslint';
import linterConfig from '../.eslintrc.json';

const ArchiveReader = App.ArchiveReader;
const Filesystem = Jymfony.Component.Filesystem.Filesystem;
const IOException = Jymfony.Component.Filesystem.Exception.IOException;
const JymfonyStyle = Jymfony.Component.Console.Style.JymfonyStyle;
const OpenFile = Jymfony.Component.Filesystem.OpenFile;
const Parser = App.Parser;
const SingleCommandApplication = Jymfony.Component.Console.SingleCommandApplication;
const VarExporter = Jymfony.Component.VarExporter.VarExporter;

export default class Application extends SingleCommandApplication {
    __construct(name = undefined) {
        super.__construct(name);

        /**
         * @type {ArchiveReader}
         *
         * @private
         */
        this._archive = undefined;

        /**
         * @type {App.Parser}
         *
         * @private
         */
        this._parser = new Parser();
    }

    /**
     * Executes the application.
     *
     * @param {Jymfony.Component.Console.Input.InputInterface} input
     * @param {Jymfony.Component.Console.Output.OutputInterface} output
     *
     * @returns {Promise<int>}
     */
    async execute(input, output) {
        const io = new JymfonyStyle(input, output);
        io.title('Tzdata updater');

        const file = await new OpenFile('https://data.iana.org/time-zones/releases/tzdata2022f.tar.gz', 'r');
        const buf = await file.fread(await file.getSize());

        this._archive = new ArchiveReader(buf);

        const files = [
            'africa',
            'antarctica',
            'asia',
            'australasia',
            'etcetera',
            'europe',
            'factory',
            'northamerica',
            'southamerica',
        ];

        io.text('Processing tzdata file...');
        io.progressStart(files.length);
        for (const file of files) {
            this._process(file);
            io.progressAdvance();
        }

        io.progressFinish();

        const baseDir = resolve(__dirname + '/../../data');

        const fs = new Filesystem();
        try {
            await fs.remove(baseDir);
        } catch (e) {
            if (! (e instanceof IOException)) {
                throw e;
            }
        }

        const mkdir = name => {
            try {
                __jymfony.mkdir(name);
            } catch (e) {
                // Do nothing
            }
        };

        mkdir(baseDir + '/timezones');
        mkdir(baseDir + '/abbrev');

        const eslintrc = await new OpenFile(baseDir + '/.eslintrc.json', 'w');
        await eslintrc.fwrite(Buffer.from(`{
  "rules": {
    "no-unused-vars": "off"
  }
}
`));
        await eslintrc.close();

        const linter = new Linter({ cwd: resolve(__dirname + '/..') });

        io.text('Exporting data...');
        io.progressStart(this._parser.zones.length + Object.keys(this._parser.aliases).length + Object.keys(this._parser.abbrevs).length);

        const zones = new Set();
        for (const zone of Object.values(this._parser.zones)) {
            const name = zone.name;
            zones.add(name);

            const utcRules = [];
            for (const rule of zone.rules) {
                if (isString(rule.rule)) {
                    utcRules.push({
                        until: rule.until,
                        ruleSet: this._parser.rules[rule.rule],
                        offset: rule.offset,
                        abbrev: rule.format,
                    });
                } else {
                    utcRules.push(rule);
                }
            }

            mkdir(baseDir + '/timezones/' + dirname(name));

            const zoneFile = await new OpenFile(baseDir + '/timezones/' + name + '.js', 'w');
            const source = 'export default ' + VarExporter.export(utcRules) + ';';
            const o = linter.verifyAndFix(source, linterConfig, {});

            await zoneFile.fwrite(Buffer.from(o.fixed ? o.output : source));
            await zoneFile.close();

            io.progressAdvance();
        }

        for (const [ name, main ] of __jymfony.getEntries(this._parser.aliases)) {
            const aliasFn = baseDir + '/timezones/' + name + '.js';
            const zoneFn = baseDir + '/timezones/' + main + '.js';
            mkdir(dirname(aliasFn));

            const zoneFile = await new OpenFile(aliasFn, 'w');
            const code = 'import tz from "' + relative(dirname(aliasFn), zoneFn) + '";\nexport default tz;';
            const o = linter.verifyAndFix(code, linterConfig, {});

            await zoneFile.fwrite(Buffer.from(o.fixed ? o.output : code));
            await zoneFile.close();

            io.progressAdvance();
        }

        for (const [ name, details ] of __jymfony.getEntries(this._parser.abbrevs)) {
            if (! name) {
                io.progressAdvance();
                continue;
            }

            mkdir(baseDir + '/timezones/' + dirname(name));

            const zoneFile = await new OpenFile(baseDir + '/abbrev/' + name + '.js', 'w');

            const code = 'export default ' + JSON.stringify(details) + ';';
            const o = linter.verifyAndFix(code, linterConfig, {});

            await zoneFile.fwrite(Buffer.from(o.fixed ? o.output : code));
            await zoneFile.close();

            io.progressAdvance();
        }

        const abbrevsJson = await new OpenFile(baseDir + '/abbrevs.json', 'w');
        await abbrevsJson.fwrite(Buffer.from(JSON.stringify(Object.keys(this._parser.abbrevs).filter(v => !!v).sort(), null, 4)));
        await abbrevsJson.close();

        const zonesJson = await new OpenFile(baseDir + '/zones.json', 'w');
        await zonesJson.fwrite(Buffer.from(JSON.stringify([ ...zones.values() ].sort(), null, 4)));
        await zonesJson.close();

        io.progressFinish();

        return 0;
    }

    _process(zone) {
        const file = this._archive.getFile(zone).toString();
        this._parser.parse(file);
    }
}


text:
@ECHO OFF
powershell .\build\build.ps1

IF ERRORLEVEL 1 (
	GOTO :error
) ELSE (
	GOTO :EOF
)

:error
ECHO.
ECHO Cannot run build\build.ps1.
ECHO If this is due to a SecurityError then please refer to BUILD.md for help!
ECHO.


text:
export interface IParticipant { id: number; first: string; last: string; }
export interface IEvent { id: number; selected?: boolean; etag: string; proficiency: string;
                        age: string; type: string; tag: string; dance: string; }
export interface IStyleEvents {id: number, style: string; events: Array<IEvent>; }
export interface ITeamMember {id: number; first: string; last: string; sex?: string; status: string; }
export interface ITeamEvents { id: number; members: Array<ITeamMember>;
                               qualifiers: Array<IStyleEvents>;
                               scholarships: Array<IStyleEvents>;
                               threshold?: number;
                               paid?: Array<number>; }

export class Event {
  selected = false;
  constructor(public _event: IEvent) {
    if (_event['selected']) {
      this.selected = true;
    }
  }
  get id(){
    return this._event['id'];
  }

  get etag(){
    return this._event['etag'];
  }

  get proficiency(){
    return this._event['proficiency'];
  }

  get age(){
    return this._event['age'];
  }

  get type(){
    return this._event['type'];
  }

  get tag(){
    return this._event['tag'];
  }

  get dance(){
    return this._event['dance'];
  }
}

export class StyleEvents {
  id: number;
  style: string;
  events: Array<IEvent>;

  constructor(public _style: IStyleEvents) {
    this.id = _style['id'];
    this.style = _style['style'];
    this.events = _style['events'].map(ievent => new Event(ievent));
  }

  get selected(){
    const events = this.events.filter(event => event.selected);
    return events.map(event => event.id);
  }
}

export class TeamEvents {
    qualifiers: Array<StyleEvents>;
    scholarships: Array<StyleEvents>;
    synced = true;
    threshold: number;
    index: number;
    count= 0;
    constructor(public iteam: ITeamEvents) {
      this.qualifiers = iteam.qualifiers.map(istyle => new StyleEvents(istyle));
      this.scholarships = iteam.scholarships.map(istyle => new StyleEvents(istyle));
      this.threshold = iteam.threshold ? iteam.threshold : 100;
      const qualifierCounts = this.qualifiers.length > 0 ? this.qualifiers.map(style => style.selected.length) : [];
      const scholarshipCounts = this.scholarships.length > 0 ? this.scholarships.map(style => style.selected.length) : [];
      const counts = qualifierCounts.concat(scholarshipCounts);
      if (counts.length > 0) {
        this.count = counts.reduce((a, b) => a + b);
      }else {
        this.count = 0;
      }
    }

    get id(){
      return this.iteam.id;
    }

    get members(){
      return this.iteam['members'];
    }

    get selected(){
      const _qualifiers = this.qualifiers.map(style => ({'style': style.id,
                                                        'events': style.selected}));
      const _scholarships = this.scholarships.map(style => ({'style': style.id,
                                                            'events': style.selected}));
      const result = {team: this.iteam.id,
                      entries: { qualifiers: _qualifiers.filter(rec => rec['events'].length > 0),
                                 scholarships: _scholarships.filter(rec => rec['events'].length > 0 )}
                     } ;

      return result;
    }

    toJSON() {
      return { 'id': this.iteam.id,
               'selected' : this.selected};
    }
}


text:
PPMusicImageShadow is a view that imitates in real time the shadow blurred effect of iOS Music App.

![alt tag](https://github.com/PierrePerrin/PPMusicImageShadow/blob/master/ExampleScreenShots/Simulator%20Screen%20Shot%206%20mars%202017%20à%2022.02.37.png)
![alt tag](https://github.com/PierrePerrin/PPMusicImageShadow/blob/master/ExampleScreenShots/Simulator%20Screen%20Shot%206%20mars%202017%20à%2022.04.20.png)
![alt tag](https://github.com/PierrePerrin/PPMusicImageShadow/blob/master/ExampleScreenShots/Simulator%20Screen%20Shot%206%20mars%202017%20à%2022.08.12.png)

## Installation

### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:

```bash
$ gem install cocoapods
```
To integrate PPMusicImageShadow into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

target '<Your Target Name>' do
pod 'PPMusicImageShadow'
end
```

### Manually

If you prefer  you can clone the project, release the framework or use the view swift file directly.

## Code Example

### Storyboard Example

Insert a normal UIView in your viewController.

![alt tag](https://github.com/PierrePerrin/PPMusicImageShadow/blob/master/ExampleScreenShots/Storyboard%20screens/1.jpg)
![alt tag](https://github.com/PierrePerrin/PPMusicImageShadow/blob/master/ExampleScreenShots/Storyboard%20screens/2.jpg)

Change it class with "PPMusicImageShadow". Now you can set an image like an imageView, a blur radius, and a corner radius.

### Programing Example

```swift
import PPMusicImageShadow

class ProgramingExampleViewController: UIViewController {

    var exampleView : PPMusicImageShadow!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.addEffectView()
        self.prepareExampleView()
        self.setImageToExampleView()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        self.exampleView.center = self.view.center
    }

    //MARK: Example
    func addEffectView(){

        self.exampleView = PPMusicImageShadow(frame: CGRect.init(x: 0, y: 0, width: 300, height: 300))
        self.view.addSubview(self.exampleView)
    }

    func setImageToExampleView(){

        let image = UIImage(named: "prairie-679016_1920.jpg")
        self.exampleView.image = image
    }

    func prepareExampleView(){

        self.exampleView.cornerRaduis = 10
        self.exampleView.blurRadius = 5
    }
}
```


text:
#ifndef GAMEPADROUTER_H
#define GAMEPADROUTER_H

#include <set>
#include <vector>
#include "ControllerEvent.h"
#include "ControllerFactory.h"
#include "InputRouter.h"
#include "JoystickAxisScheme.h"
#include "KeyScheme.h"
#include "TriggerAxisScheme.h"

/**
 * @ingroup GameInput
 * @brief Routes gamepad-related ControllerEvent%s according to inherent GamepadControllerFactory
 * specifications.
 */
class GamepadRouter : public InputRouter {
public:
    /**
     * @ingroup GameInput
     * @brief Factory for constructing VirtualController%s to represent gamepad devices as
     * controllers.
     */
    class GamepadControllerFactory : public ControllerFactory {
    public:
        /**
         * @brief Constructs a GamepadControllerFactory from input schemes.
         * @param keyScheme KeyScheme for constructed VirtualController%s
         * @param joystickAxisScheme JoystickAxisScheme for constructed VirtualController%s
         * @param triggerAxisScheme TriggerAxisScheme for constructed VirtualController%s
         */
        explicit GamepadControllerFactory(
                const KeyScheme& keyScheme,
                const JoystickAxisScheme& joystickAxisScheme,
                const TriggerAxisScheme& triggerAxisScheme
                );

        virtual VirtualController* createNewController(int deviceId) const override;

        virtual bool intersects(const ControllerFactory& otherFactory) const override;
        /**
         * @brief Returns whether or not this GamepadControllerFactory intersects (i.e. overlaps
         * input schemes) with the specified GamepadControllerFactory.
         * @note Two GamepadControllerFactory%s would be intersecting if both would return @c true
         * for handlesControllerEvent() when passed the same event.
         * @param otherFactory GamepadControllerFactory to test for intersection with this
         */
        bool intersects(const GamepadControllerFactory& otherFactory) const;

        virtual bool handlesControllerEvent(const ControllerEvent* event) const override;

        /**
         * @brief Set of KeyCode%s valid as input on a gamepad.
         */
        static std::set<KeyCode> sValidKeyCodes;
        /**
         * @brief Set of JoystickAxisCode%s valid as input on a gamepad.
         */
        static std::set<JoystickAxisCode> sValidJoystickAxisCodes;
        /**
         * @brief Set of TriggerAxisCode%s valid as input on a gamepad.
         */
        static std::set<TriggerAxisCode> sValidTriggerAxisCodes;

    private:
        KeyScheme mKeyScheme;
        JoystickAxisScheme mJoystickAxisScheme;
        TriggerAxisScheme mTriggerAxisScheme;
    };

    /**
     * @brief Adds the specified GamepadControllerFactory to the list of factories to route by.
     * @returns @c false if @p factory intersects with existing factories and cannot be added.
     */
    bool addGamepadControllerFactory(const GamepadControllerFactory& factory);

    /**
     * @brief Returns the singleton instance of GamepadRouter.
     */
    static GamepadRouter* getInstance();

private:
    /**
     * Private constructor for singleton class.
     */
    GamepadRouter();

    // List of GamepadControllerFactories to route by.
    std::vector<GamepadControllerFactory> mGamepadControllerFactories;

    // Singleton instance of the GamepadRouter.
    static GamepadRouter* sInstance;
};

#endif // GAMEPADROUTER_H


text:
@SomeAnnotation(Foo.<error descr="'Foo.Bar' has private access in 'Foo'">Bar</error>.class)
public class Foo{
  private static class Bar {
  }
}
@interface SomeAnnotation {
    Class value();
}


text:
package org.kaazing.gateway.service.messaging.buffer;

import java.io.Serializable;

import org.kaazing.gateway.service.messaging.MessagingMessage;

public class MessageBufferEntry implements Serializable {

    private static final long serialVersionUID = 1L;
    private final int id;
    private final MessagingMessage message;
    private final long expires;

    public MessageBufferEntry(int id, MessagingMessage message) {
        this.id = id;
        this.expires = 0;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public long getExpires() {
        return expires;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[id=")
          .append(id)
          .append(",expires=")
          .append(expires)
          .append(",message=")
          .append(message)
          .append(']');
        return sb.toString();
    }

    public MessagingMessage getMessage() {
        return message;
    }
}


text:
package com.pentaho.di.services;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *

 * Java class for ImportHandlerDto complex type.
 *
 *

 * The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ImportHandlerDto">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="MimeTypeDefinitions" type="{http://www.pentaho.com/schema/}MimeTypeDefinitionsDto"/>
 *       </sequence>
 *       <attribute name="class" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType( XmlAccessType.FIELD )
@XmlType( name = "ImportHandlerDto", propOrder = { "mimeTypeDefinitions" } )
public class ImportHandlerDto {

  @XmlElement( name = "MimeTypeDefinitions", required = true )
  protected MimeTypeDefinitionsDto mimeTypeDefinitions;
  @XmlAttribute( name = "class", required = true )
  protected String clazz;

  /**
   * Gets the value of the mimeTypeDefinitions property.
   *
   * @return possible object is {@link MimeTypeDefinitionsDto }
   *
   */
  public MimeTypeDefinitionsDto getMimeTypeDefinitions() {
    return mimeTypeDefinitions;
  }

  /**
   * Sets the value of the mimeTypeDefinitions property.
   *
   * @param value
   *          allowed object is {@link MimeTypeDefinitionsDto }
   *
   */
  public void setMimeTypeDefinitions( MimeTypeDefinitionsDto value ) {
    this.mimeTypeDefinitions = value;
  }

  /**
   * Gets the value of the clazz property.
   *
   * @return possible object is {@link String }
   *
   */
  public String getClazz() {
    return clazz;
  }

  /**
   * Sets the value of the clazz property.
   *
   * @param value
   *          allowed object is {@link String }
   *
   */
  public void setClazz( String value ) {
    this.clazz = value;
  }

}


text:
import { Component } from '@angular/core';

@Component({
  selector: 'my-component',
  templateUrl: './myfirst.component.html',
  styleUrls:['./myfirst.component.css']
})
export class FirstComponent{
 public user={};
public cart = [];
//for push data in array
  userData (value)
  {
  this.cart.push(value);
  console.log( this.cart);
   this.user={};
}
//for delete
deletekaro (val){

  var index=this.cart.indexOf(val);
  this.cart.splice(index, 1);
}
// for edit row data
public showEditableRow=null; // here i have to give null value because without giving null value this chunk of code is not working fine.
public current={};
editkaro (val){
  this.showEditableRow=true;
  this.current=val;

  alert("you want to edit");
}

savekaro(){
  this.showEditableRow=false;

}

}


text:
## Acesso
Para acessar esta opção, selecione o módulo **Cadastros**, opção **Tabelas**, opção **Classificações Tributárias**.

## Grade
Pela grade, podemos visualizar suas principais informações e fazer a manutenção de seus dados.
![classtributaria.grid](https://raw.githubusercontent.com/netforcews/docs-erp/master/cadastros/imagens/classtributaria.grid.png)

Campo | Descrição
--:|---
**Código** | Informa o código.
**Descrição** | Informa a descrição.
**Aut** | Informa se autorizado.

## Geral
![classtributaria.geral](https://raw.githubusercontent.com/netforcews/docs-erp/master/cadastros/imagens/classtributaria.geral.png)

Campo | Descrição
--:|---
**Código** | Informe o código. Por padrão, este campo é obrigatório.
**Autorizado** | Selecione se autorizado.
**Descrição** | Informe a descrição. Por padrão, este campo é obrigatório.

```TAB_CLASSIFICACAOTRIBUTARIA:CLASSTRIBUTARIA```


text:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?><x xmlns="http://www.schemaTest.org/xinclude-test" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.schemaTest.org/xinclude-test tests.xsd">
   <!-- including the same document, but as text -->
   <?xml version="1.0"?>
<x xmlns="http://www.schemaTest.org/xinclude-test"
   xmlns:xi="http://www.w3.org/2001/XInclude"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.schemaTest.org/xinclude-test tests.xsd">
   <!-- test that including the same document fails -->
   <!-- EXPECT FAILURE -->
   <xi:include parse="xml"
               href="test24.xml"/>
</x>

</x>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package id.ac.tazkia.dosen.dao;

import id.ac.tazkia.dosen.entity.KategoriBuktiKegiatan;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 *
 * @author razi
 */
public interface KategoriBuktiKegiatanDao extends PagingAndSortingRepository<KategoriBuktiKegiatan, String>{
    Page<KategoriBuktiKegiatan> findByNamaContainingIgnoreCase(String nama, Pageable p);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using SparkPost.Utilities;

namespace SparkPost.ValueMappers
{
    public class StringObjectDictionaryValueMapper : IValueMapper
    {
        private readonly IDataMapper dataMapper;

        public StringObjectDictionaryValueMapper(IDataMapper dataMapper)
        {
            this.dataMapper = dataMapper;
        }

        public bool CanMap(Type propertyType, object value)
        {
            return value is IDictionary<string, object>;
        }

        public object Map(Type propertyType, object value)
        {
            var original = (IDictionary<string, object>) value;
            var dictionary = new Dictionary<string, object>();
            foreach (var item in original.Where(i => i.Value != null))
            {
                var itemKey = SnakeCase.Convert(item.Key);
                var itemValue = item.Value;
                dictionary[itemKey] = dataMapper.GetTheValue(itemValue.GetType(), itemValue);
            }
            return dictionary.Count > 0 ? dictionary : null;
        }
    }
}


text:
package org.apache.velocity.exception;

/**
 * All Exceptions that can provide additional information about the place
 * where the error happened (template name, column and line number) can
 * implement this interface and the ParseErrorException will then be able
 * to deal with this information.
 *
 * @author Henning P. Schmiedehausen
 * @version $Id$
 * @since 1.5
 */
public interface ExtendedParseException
{
    /**
     * returns the Template name where this exception occurred.
     * @return The Template name where this exception occurred.
     */
    String getTemplateName();

    /**
     * returns the line number where this exception occurred.
     * @return The line number where this exception occurred.
     */
    int getLineNumber();

    /**
     * returns the column number where this exception occurred.
     * @return The column number where this exception occurred.
     */
    int getColumnNumber();
}


text:
trap '{ echo "Script interrupted. Cleaning up"; rm -rf ips.txt command.sh; exit 1; }' INT

cat data.txt |awk '{print $1}' > ips.txt

# for all ips in ips.txt file
count=1
for myip in `cat ips.txt`
do

command="export LD_LIBRARY_PATH=~/AT/AugmentedTimePython/AT-ZMQ/lib"
echo "$command" > command.sh

command="cd ~/AT/AugmentedTimePython/Socket/;git reset --hard;git pull;rm events.log nohup.out;make"
echo "$command" >> command.sh

command="nohup ./peer $count"
for i in `cat ips.txt`
do
    if [ $myip != $i ]
    then
        command="$command $i:12345"
    fi
done
echo "$command 1> nohup.out 2> nohup.out &" >> command.sh

command="exit"
echo "$command" >> command.sh

cert=`cat data.txt |grep "$myip "|awk '{print $2}'`
ssh -t -t -i cert/$cert ubuntu@$myip < command.sh
rm command.sh

count=$((count + 1))
done

rm ips.txt


text:
var assign = require('object-assign');
var delegate = require('dom-utils/lib/delegate');
var parseUrl = require('dom-utils/lib/parse-url');
var provide = require('../provide');
var usage = require('../usage');
var createFieldsObj = require('../utilities').createFieldsObj;
var getAttributeFields = require('../utilities').getAttributeFields;

/**
 * Registers outbound link tracking on a tracker object.
 * @constructor
 * @param {Object} tracker Passed internally by analytics.js
 * @param {?Object} opts Passed by the require command.
 */
function OutboundLinkTracker(tracker, opts) {

  usage.track(tracker, usage.plugins.OUTBOUND_LINK_TRACKER);

  // Feature detects to prevent errors in unsupporting browsers.
  if (!window.addEventListener) return;

  this.opts = assign({
    events: ['click'],
    linkSelector: 'a',
    shouldTrackOutboundLink: this.shouldTrackOutboundLink,
    fieldsObj: {},
    attributePrefix: 'ga-',
    hitFilter: null
  }, opts);

  this.tracker = tracker;

  // Binds methods.
  this.handleLinkInteractions = this.handleLinkInteractions.bind(this);

  // Creates a mapping of events to their delegates
  this.delegates = {};
  this.opts.events.forEach(function(event) {
    this.delegates[event] = delegate(document, event, this.opts.linkSelector,
        this.handleLinkInteractions, {composed: true, useCapture: true});
  }.bind(this));
}

/**
 * Handles all interactions on link elements. A link is considered an outbound
 * link if its hostname property does not match location.hostname. When the
 * beacon transport method is not available, the links target is set to
 * "_blank" to ensure the hit can be sent.
 * @param {Event} event The DOM click event.
 * @param {Element} link The delegated event target.
 */
OutboundLinkTracker.prototype.handleLinkInteractions = function(event, link) {

  if (this.opts.shouldTrackOutboundLink(link, parseUrl)) {
    // Opens outbound links in a new tab if the browser doesn't support
    // the beacon transport method.
    if (!navigator.sendBeacon) {
      link.target = '_blank';
    }

    var defaultFields = {
      transport: 'beacon',
      eventCategory: 'Outbound Link',
      eventAction: event.type,
      eventLabel: link.href
    };

    var userFields = assign({}, this.opts.fieldsObj,
        getAttributeFields(link, this.opts.attributePrefix));

    this.tracker.send('event', createFieldsObj(
        defaultFields, userFields, this.tracker, this.opts.hitFilter, link));
  }
};

/**
 * Determines whether or not the tracker should send a hit when a link is
 * clicked. By default links with a hostname property not equal to the current
 * hostname are tracked.
 * @param {Element} link The link that was clicked on.
 * @param {Function} parseUrl A cross-browser utility method for url parsing.
 * @return {boolean} Whether or not the link should be tracked.
 */
OutboundLinkTracker.prototype.shouldTrackOutboundLink =
    function(link, parseUrl) {

  var url = parseUrl(link.href);
  return url.hostname != location.hostname &&
      url.protocol.slice(0, 4) == 'http';
};

/**
 * Removes all event listeners and instance properties.
 */
OutboundLinkTracker.prototype.remove = function() {
  Object.keys(this.delegates).forEach(function(key) {
    this.delegates[key].destroy();
  }.bind(this));
};

provide('outboundLinkTracker', OutboundLinkTracker);


text:
class ConditionalTernary {
  public static void main(String[] args) {
    String s = false ? "no" : "yes";
    System.out.println(s);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 Copyright 2003 - 2015 The eFaps Team

 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.

-->

<ui-command xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>f3ead280-b429-402f-a239-5dbca138c7d9</uuid>
    <file-application>eFaps-Kernel</file-application>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Admin_Common_SystemConfigurationTree_Attributes_Menu_Action_Create</name>
        <target>
            <form>Admin_Common_SystemConfigurationAttributeForm</form>
            <execute program="org.efaps.esjp.admin.common.systemconfiguration.SystemConf" method="createAttribute" />
        </target>
        <property name="Target">modal</property>
        <property name="TargetCreateType">Admin_Common_SystemConfigurationAttribute</property>
        <property name="TargetConnectAttribute">Admin_Common_SystemConfigurationAttribute/Link</property>
        <property name="TargetMode">create</property>
        <property name="WindowWidth">800</property>
    </definition>
</ui-command>


text:
<?php

namespace JasonRoman\NbaApi\Request\Stats\Data\Synergy;

use JasonRoman\NbaApi\Request\Stats\Data\AbstractStatsDataRequest;

/**
 * This appears to only work with the 2015 season and the parameters cannot be changed.
 */
class TeamPlayTypeOffensiveReboundRequest extends AbstractStatsDataRequest
{
    const ENDPOINT = '/js/data/playtype/team_OffRebound.js';
}


text:
package main

import (
	"testing"
)

var f = charcount

func TestCharcout1(t *testing.T) {
	result := charcount('O')
	expected := []string{"Graphic", "Print", "Letter", "Upper"}
	if !equal(result, expected) {
		t.Errorf("%v %v", result, expected)
	}
}

func TestCharcout2(t *testing.T) {
	result := charcount('💏')
	expected := []string{"Graphic", "Print", "Symbol"}
	if !equal(result, expected) {
		t.Errorf("%v %v", result, expected)
	}
}

func TestCharcout3(t *testing.T) {
	result := charcount('1')
	expected := []string{"Graphic", "Print", "Digit", "Number"}
	if !equal(result, expected) {
		t.Errorf("%v %v", result, expected)
	}
}

func equal(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	emap := make(map[string]bool)
	for _, ea := range a {
		emap[ea] = true
	}
	for _, eb := range b {
		if emap[eb] == false {
			return false
		}
	}
	return true
}


text: Howardlinsanity.github.io


text:
package org.apache.samza.system.kafka

import java.util
import java.util.Properties

import kafka.admin.AdminClient
import kafka.utils.Logging
import org.apache.kafka.common.TopicPartition
import org.apache.samza.config.ApplicationConfig.ApplicationMode
import org.apache.samza.config.{ApplicationConfig, Config, KafkaConfig, StreamConfig}
import org.apache.samza.system.SystemStreamMetadata.SystemStreamPartitionMetadata
import org.apache.samza.system.{SystemStreamMetadata, SystemStreamPartition}

import scala.collection.JavaConverters._

/**
  * A helper class for KafkaSystemAdmin
  *
  * @param replicationFactor The number of replicas for the changelog stream
  * @param kafkaProps The kafka specific properties that need to be used for changelog stream creation
  */
case class ChangelogInfo(var replicationFactor: Int, var kafkaProps: Properties)

// TODO move to org.apache.kafka.clients.admin.AdminClien from the kafka.admin.AdminClient
object KafkaSystemAdminUtilsScala extends Logging {

  /**
    * A helper method that takes oldest, newest, and upcoming offsets for each
    * system stream partition, and creates a single map from stream name to
    * SystemStreamMetadata.
    */
  def assembleMetadata(oldestOffsets: Map[SystemStreamPartition, String], newestOffsets: Map[SystemStreamPartition, String], upcomingOffsets: Map[SystemStreamPartition, String]): Map[String, SystemStreamMetadata] = {
    val allMetadata = (oldestOffsets.keySet ++ newestOffsets.keySet ++ upcomingOffsets.keySet)
      .groupBy(_.getStream)
      .map {
        case (streamName, systemStreamPartitions) =>
          val streamPartitionMetadata = systemStreamPartitions
            .map(systemStreamPartition => {
              val partitionMetadata = new SystemStreamPartitionMetadata(
                // If the topic/partition is empty then oldest and newest will
                // be stripped of their offsets, so default to null.
                oldestOffsets.getOrElse(systemStreamPartition, null),
                newestOffsets.getOrElse(systemStreamPartition, null),
                upcomingOffsets(systemStreamPartition))
              (systemStreamPartition.getPartition, partitionMetadata)
            })
            .toMap
          val streamMetadata = new SystemStreamMetadata(streamName, streamPartitionMetadata.asJava)
          (streamName, streamMetadata)
      }
      .toMap

    // This is typically printed downstream and it can be spammy, so debug level here.
    debug("Got metadata: %s" format allMetadata)

    allMetadata
  }

  def getCoordinatorTopicProperties(config: KafkaConfig) = {
    val segmentBytes = config.getCoordinatorSegmentBytes
    (new Properties /: Map(
      "cleanup.policy" -> "compact",
      "segment.bytes" -> segmentBytes)) { case (props, (k, v)) => props.put(k, v); props }
  }

  def getIntermediateStreamProperties(config: Config): Map[String, Properties] = {
    val appConfig = new ApplicationConfig(config)
    if (appConfig.getAppMode == ApplicationMode.BATCH) {
      val streamConfig = new StreamConfig(config)
      streamConfig.getStreamIds().filter(streamConfig.getIsIntermediateStream(_)).map(streamId => {
        val properties = new Properties()
        properties.putAll(streamConfig.getStreamProperties(streamId))
        properties.putIfAbsent("retention.ms", String.valueOf(KafkaConfig.DEFAULT_RETENTION_MS_FOR_BATCH))
        (streamId, properties)
      }).toMap
    } else {
      Map()
    }
  }

  def deleteMessages(adminClient : AdminClient, offsets: util.Map[SystemStreamPartition, String]) = {
    val nextOffsets = offsets.asScala.toSeq.map { case (systemStreamPartition, offset) =>
      (new TopicPartition(systemStreamPartition.getStream, systemStreamPartition.getPartition.getPartitionId), offset.toLong + 1)
    }.toMap
    adminClient.deleteRecordsBefore(nextOffsets);
  }
}


text:
package de.galan.snake.client;

import java.util.Map;
import java.util.Set;

import de.galan.snake.core.SnakeModel;
import de.galan.snake.core.SourceListener;

/**
 * Static facade to access snake configuration properties within clients.
 *
 * @author galan
 */
public class Snake {

	private static SnakeModel model;

	public static void setModel(SnakeModel model) {
		Snake.model = model;
	}

	public static SnakeModel getModel() {
		return model;
	}

	public static String get(String name) {
		return getModel().get(name);
	}

	public static String get(String name, String fallback) {
		return getModel().get(name, fallback);
	}

	public static Map<String, String> getProperties() {
		return getModel().getProperties();
	}

	public static Set<String> getProperties(String prefix) {
		return getModel().getProperties(prefix);
	}

	public static boolean isSet(String name) {
		return getModel().isSet(name);
	}

	public static Integer getInt(String name) {
		return getModel().getInt(name);
	}

	public static Integer getInt(String name, Integer fallback) {
		return getModel().getInt(name, fallback);

	}

	public static Long getLong(String name) {
		return getModel().getLong(name);
	}

	public static Long getLong(String name, Long fallback) {
		return getModel().getLong(name, fallback);
	}

	public static Double getDouble(String name) {
		return getModel().getDouble(name);
	}

	public static Double getDouble(String name, Double fallback) {
		return getModel().getDouble(name, fallback);
	}

	public static boolean getBool(String name) {
		return getModel().getBool(name);
	}

	public static boolean getBool(String name, boolean fallback) {
		return getModel().getBool(name, fallback);
	}

	public static Long getTime(String name) {
		return getModel().getTime(name);
	}

	public static Long getTime(String name, String fallback) {
		return getModel().getTime(name, fallback);
	}

	public static String getInstance() {
		return getModel().getInstance();
	}

	public static String getDirectoryBase() {
		return getModel().getDirectoryBase();
	}

	public static String getDirectoryInstance() {
		return getModel().getDirectoryInstance();
	}

	public static String getDirectoryStorage() {
		return getModel().getDirectoryStorage();
	}

	public static String getDirectoryStorage(String subdirectory) {
		return getModel().getDirectoryStorage(subdirectory);
	}

	public static String getDirectoryLog() {
		return getModel().getDirectoryLog();
	}

	public static String getDirectoryConfiguration() {
		return getModel().getDirectoryConfiguration();
	}

	public static String getDirectoryTemp() {
		return getModel().getDirectoryTemp();
	}

	public static String getDirectoryScript() {
		return getModel().getDirectoryScript();
	}

	/** Logs an overview of the properties */
	public static void printProperties() {
		getModel().printProperties();
	}

	public static void addListener(SourceListener listener) {
		getModel().addListener(listener);
	}

	public static void removeListener(SourceListener listener) {
		getModel().removeListener(listener);
	}

	public static void overlay(String name, String value) {
		getModel().set(name, value);
	}

	public static void overlayInt(String name, Integer value) {
		getModel().setInt(name, value);
	}

	public static void overlayLong(String name, Long value) {
		getModel().setLong(name, value);
	}

	public static void overlayDouble(String name, Double value) {
		getModel().setDouble(name, value);
	}

	public static void overlayBool(String name, Boolean value) {
		getModel().setBool(name, value);
	}

	public static void overlayTime(String name, String value) {
		getModel().setTime(name, value);
	}

}