text:
package aQute.openapi.security.useradmin.util;

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.useradmin.Authorization;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;
import org.osgi.service.useradmin.User;
import org.osgi.service.useradmin.UserAdmin;

import aQute.lib.json.JSONCodec;
import aQute.lib.strings.Strings;
import aQute.openapi.security.useradmin.util.UserAdminDTO.RoleDTO;

@Component(service = UserAdminFacade.class)
public class UserAdminFacade {
	final static Pattern										ROLE_NAME_P	= Pattern
			.compile("\\p{javaJavaIdentifierStart}[\\p{javaJavaIdentifierPart}:*,\\-]*");
	final static ConcurrentHashMap<String, WildcardPermission>	permissions	= new ConcurrentHashMap<>();

	@Reference
	UserAdmin													userAdmin;

	public User getUser(String id) {
		if (id.equals("@"))
			id = Role.USER_ANYONE;

		Role role = userAdmin.getRole(id);
		if (role == null)
			return null;

		if (!(role instanceof User))
			throw new IllegalArgumentException("Not a user");

		return (User) role;
	}

	public CharSequence line(User r) throws InvalidSyntaxException {
		return basics(r);
	}

	private StringBuilder basics(Role r) throws InvalidSyntaxException {
		StringBuilder sb = new StringBuilder();
		if (r instanceof Group)
			sb.append("G:");
		else if (r instanceof User)
			sb.append("U:");
		else
			sb.append("#");

		sb.append(r.getName()).append(":");

		sb.append(Strings.join(getInGroups(r)));
		return sb;
	}

	public CharSequence line(Group r) throws InvalidSyntaxException {
		StringBuilder sb = basics(r);
		sb.append(":");
		sb.append(Strings.join(getMembers(r)));
		sb.append(":");
		sb.append(Strings.join(getRequiredMembers(r)));
		return sb;
	}

	public Set<Role> getMembers(Group r) {
		Role[] roles = r.getMembers();
		return toSet(roles);
	}

	public Set<Role> getRequiredMembers(Group r) {
		Role[] roles = r.getRequiredMembers();
		return toSet(roles);
	}

	public <T> Set<T> toSet(T[] roles) {
		if (roles == null)
			return Collections.emptySet();

		return new HashSet<T>(Arrays.asList(roles));
	}

	@SuppressWarnings("unchecked")
	public CharSequence inspect(User r) throws InvalidSyntaxException {
		Authorization a = userAdmin.getAuthorization(r);
		return String.format(
				"User               %s\n"
						+ "In groups          %s\n"
						+ "Authorized         %s\n"
						+ "Properties         %s\n"
						+ "Credentials        %s\n",
				r.getName(), getInGroups(r), toSet(a.getRoles()), toMap(r.getProperties()),
				Collections.list(r.getCredentials().keys()));
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private Map<String, Object> toMap(Dictionary properties) {
		Map<String, Object> map = new HashMap<>();
		for (Object k : Collections.list(properties.keys())) {
			map.put((String) k, properties.get(k));
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	public CharSequence inspect(Group r) throws InvalidSyntaxException {
		return String.format(
				"Group              %s\n"
						+ "In groups          %s\n"
						+ "Basic Members      %s\n"
						+ "Requried Members   %s\n"
						+ "Properties         %s\n"
						+ "Credentials        %s\n",
				r.getName(), getInGroups(r), toSet(r.getMembers()), toSet(r.getRequiredMembers()),
				toMap(r.getProperties()), Collections.list(r.getCredentials().keys()));
	}

	public Set<Group> getInGroups(Role r) throws InvalidSyntaxException {

		return Stream
				.of(userAdmin.getRoles(null))
				.filter(r1 -> r1 instanceof Group)
				.map(r2 -> (Group) r2)
				.filter(g -> hasMember(g, r))
				.collect(Collectors.toSet());
	}

	public boolean hasMember(Group g, Role r) {
		Role[] members = g.getMembers();
		if (members == null)
			return false;

		for (Role m : members) {
			if (m.equals(r))
				return true;
		}
		return false;
	}

	public void validateName(String id) {
		if (!ROLE_NAME_P.matcher(id).matches())
			throw new IllegalArgumentException(
					"Not a valid user name " + id + " (must be a java identifier with '-' allowed)");
	}

	public Group getGroup(String groupName) {
		Role role = userAdmin.getRole(groupName);
		if (role == null)
			return null;

		if (!(role instanceof Group))
			throw new IllegalArgumentException("Not a group");

		return (Group) role;
	}

	public Role getRole(String id) {
		return userAdmin.getRole(id);
	}

	public User createUser(String id) {
		validateName(id);
		Role role = getRole(id);
		if (role != null)
			throw new IllegalArgumentException("A role with this name already exists " + id);

		return (User) userAdmin.createRole(id, Role.USER);
	}

	public Group createGroup(String id) {
		validateName(id);
		Role role = getRole(id);
		if (role != null)
			throw new IllegalArgumentException("A role with this name already exists " + id);

		Group g = (Group) userAdmin.createRole(id, Role.GROUP);
		return g;
	}

	public void modify(Role role, boolean noCreateGroups, boolean replace, Set<Role> becomeMemberOf)
			throws InvalidSyntaxException {

		Role[] roles = userAdmin.getRoles(null);

		if (replace) {
			for (Role r : roles) {
				if (r instanceof Group) {
					((Group) r).removeMember(role);
				}
			}
		}

		for (Role target : becomeMemberOf) {
			if (target instanceof Group) {
				((Group) target).addMember(role);
			}
		}

	}

	public boolean remove(Role g) {
		return userAdmin.removeRole(g.getName());
	}

	public Collection<Role> getRoles() throws InvalidSyntaxException {
		return getRoles(null);
	}

	public Collection<Role> getRoles(String filter) throws InvalidSyntaxException {
		Role[] roles = userAdmin.getRoles(filter);
		if (roles == null)
			return Collections.emptyList();

		return Arrays.asList(roles);
	}

	public Set<Role> toRoles(boolean noCreateGroups, String... members) throws InvalidSyntaxException {
		return toRoles(noCreateGroups, Arrays.asList(members));
	}

	public Set<Role> toRoles(boolean noCreateGroups, Collection<String> members) throws InvalidSyntaxException {
		if (members == null || members.isEmpty())
			return Collections.emptySet();

		Set<Role> result = new HashSet<>();
		Collection<Role> all = getRoles();
		for (String member : members) {
			if (isWildcard(member)) {
				result.addAll(filter(member, all));
			} else {
				Role role = getRole(member);
				if (role == null) {
					if (noCreateGroups)
						throw new IllegalArgumentException("No such role name " + member);
					role = userAdmin.createRole(member, Role.GROUP);
				}
				result.add(role);
			}
		}
		return result;
	}

	public Set<? extends Role> filter(String glob, Collection<? extends Role> all) {
		glob = toPattern(glob);

		return filter(Pattern.compile(glob), all);
	}

	private String toPattern(String glob) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < glob.length(); i++) {
			char c = glob.charAt(i);
			switch (c) {
			case '*':
			case '?':
			case '+':
			case '[':
			case '(':
			case '\\':
			case '^':
			case '$':
			case '.':
				sb.append('\\').append(c);
				break;

			case '@':
				sb.append(".*");
				break;
			default:
				sb.append(c);
				break;
			}
		}
		return sb.toString();
	}

	public Set<? extends Role> filter(Pattern glob, Collection<? extends Role> all) {
		Set<Role> result = new HashSet<>();
		for (Role r : all) {
			if (glob.matcher(r.getName()).matches())
				result.add(r);
		}
		return result;
	}

	private boolean isWildcard(String member) {
		return member.indexOf('@') >= 0;
	}

	public void addToGroup(Group g, Collection<? extends Role> roles) {
		for (Role r : roles) {
			g.addMember(r);
		}
	}

	public boolean remove(String id) {
		return userAdmin.removeRole(id);
	}

	public void clear(Group g) {
		Role[] roles = g.getMembers();
		if (roles == null)
			return;

		for (Role role : roles)
			g.removeMember(role);
	}

	public Set<Group> getGroups() throws InvalidSyntaxException {
		return toGroups(getRoles());
	}

	public Set<Group> toGroups(Collection<Role> roles) {
		return roles.stream()
				.filter(r -> r instanceof Group)
				.map(r -> (Group) r)
				.collect(Collectors.toSet());
	}

	public Set<User> toUsers(Collection<Role> roles) {
		return roles.stream()
				.filter(r -> r instanceof User)
				.map(r -> (User) r)
				.collect(Collectors.toSet());
	}

	public void remove(Set<? extends Role> roles) throws InvalidSyntaxException {
		for (Role r : roles) {
			for (Group g : getGroups()) {
				if (!roles.contains(g))
					g.removeMember(r);
			}
			userAdmin.removeRole(r.getName());
		}
	}

	public boolean exists(Role r) {
		return r.equals(userAdmin.getRole(r.getName()));
	}

	public Set<Role> imports(String in) throws Exception {
		UserAdminDTO result = new JSONCodec().dec().from(in).get(UserAdminDTO.class);
		Set<Role> roles = new TreeSet<>((a, b) -> a.getName().compareTo(b.getName()));

		for (RoleDTO rdto : result.roles) {

			Role role = mkRole(rdto);
			roles.add(role);
		}

		return roles;
	}

	private Role mkRole(RoleDTO r) throws InvalidSyntaxException {
		switch (r.type) {
		case Role.GROUP:
			return mkGroup(r);

		case Role.USER:
			return mkUser(r);

		default:
		case Role.ROLE:
			throw new IllegalArgumentException("Import cannot define Role types " + r);
		}
	}

	private Role mkUser(RoleDTO r) {
		User u = getUser(r.name);
		if (u == null)
			u = createUser(r.name);

		setProperties(u.getProperties(), r.properties);
		setProperties(u.getCredentials(), r.credentials);
		return u;
	}

	private Role mkGroup(RoleDTO r) throws InvalidSyntaxException {
		Group g = getGroup(r.name);
		if (g == null)
			g = createGroup(r.name);

		setProperties(g.getProperties(), r.properties);
		setProperties(g.getCredentials(), r.credentials);

		for (Role m : toRoles(false, r.basic))
			g.addMember(m);

		for (Role m : toRoles(false, r.required))
			g.addRequiredMember(m);
		return g;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void setProperties(Dictionary dictionary, Map<String, Object> properties) {
		if (properties == null)
			return;

		for (Map.Entry<String, Object> e : properties.entrySet()) {
			dictionary.put(e.getKey(), e.getValue());
		}
	}

	public String exports() throws Exception {
		UserAdminDTO uadto = new UserAdminDTO();
		uadto.date = System.currentTimeMillis();
		for (Role role : getRoles()) {
			if (role instanceof User) {
				if (Role.USER_ANYONE.equals(role.getName()))
					continue;

				RoleDTO roledto = new RoleDTO();
				roledto.name = role.getName();
				roledto.properties = toMap(role.getProperties());
				if (role instanceof User) {
					roledto.type = Role.USER;
					roledto.credentials = toMap(((User) role).getCredentials());
				}
				if (role instanceof Group) {
					roledto.type = Role.GROUP;
					Group g = (Group) role;
					roledto.basic = getMembers(g).stream().map(m -> m.getName()).collect(toList());
					roledto.required = getRequiredMembers(g).stream().map(m -> m.getName()).collect(toList());
				}
				uadto.roles.add(roledto);
			}
		}
		return new JSONCodec().enc().put(uadto).toString();
	}

	public Authorization getAuthorization(String userId) {
		User user = getUser(userId);
		if (user == null)
			return null;

		return userAdmin.getAuthorization(user);
	}

	public boolean implies(Role user, String action, String... arguments) {
		if (!(user instanceof User)) // user.anyone is role
			return false;

		Authorization authorization = userAdmin.getAuthorization((User) user);

		String[] roles = authorization.getRoles();
		if (roles == null || roles.length == 0) {
			return false;
		}

		String effective = effective(action, arguments);
		for (String role : roles) {
			if (role.equals(action) && arguments.length == 0)
				return true;

			WildcardPermission wp = permissions.computeIfAbsent(role, (r) -> WildcardPermission.caseSensitive(role));
			if (wp.implies(effective))
				return true;

		}
		return false;
	}

	public String effective(String permission, String[] arguments) {
		if (arguments.length == 0)
			return permission;

		StringBuilder sb = new StringBuilder();
		sb.append(permission);
		for (String arg : arguments) {
			sb.append(":");
			escape(sb, arg);
		}
		return sb.toString();
	}

	public void escape(StringBuilder sb, String arg) {
		for (int i = 0; i < arg.length(); i++) {
			char c = arg.charAt(i);
			if (c != '\\' && c != ':')
				sb.append(c);
			else {
				sb.append('\\');
				sb.append(c);
			}
		}
	}

	public User getUser(String key, String value) {
		return userAdmin.getUser(key, value);
	}

	public Set<User> getUsers() throws InvalidSyntaxException {
		return toUsers(getRoles());
	}

}


text:
from __future__ import absolute_import
from __future__ import unicode_literals

import codecs
import os
import re
import sys

from setuptools import find_packages
from setuptools import setup

def read(*parts):
    path = os.path.join(os.path.dirname(__file__), *parts)
    with codecs.open(path, encoding='utf-8') as fobj:
        return fobj.read()

def find_version(*file_paths):
    version_file = read(*file_paths)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

install_requires = [
    'requests',
    'docker'
]

setup(
    name='docker-parse',
    version=find_version("docker_parse", "__init__.py"),
    description='Parse docker-run options from a running Docker container',
    url='https://github.com/iamfat/docker-parse',
    author="Jia Huang",
    author_email="iamfat@gmail.com",
    license='MIT',
    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Topic :: Utilities',
        'License :: OSI Approved :: MIT License',
    ],
    keywords='docker parse run options',
    packages=find_packages(exclude=['tests.*', 'tests']),
    install_requires=install_requires,
    entry_points={
        'console_scripts': [
            'docker-parse=docker_parse:main',
        ],
    },
)

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0'?>
<!--

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

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

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

-->

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
  <id>runnable</id>
  <formats>
    <format>jar</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <containerDescriptorHandlers>
    <containerDescriptorHandler>
      <!--
          aggregate SPI's so that things like HDFS FileSystem works in uberjar
          http://docs.oracle.com/javase/tutorial/sound/SPI-intro.html
      -->
      <handlerName>metaInf-services</handlerName>
    </containerDescriptorHandler>
  </containerDescriptorHandlers>
  <dependencySets>
    <dependencySet>
      <unpack>true</unpack>
      <scope>runtime</scope>
      <outputDirectory>/</outputDirectory>
      <includes>
        <include>org.apache.phoenix:phoenix-server</include>
        <include>org.apache.phoenix:phoenix-server-client</include>
        <include>org.apache.calcite:*</include>
      </includes>
    </dependencySet>
  </dependencySets>
</assembly>


text:
/**
 ******************************************************************************
 * @file    usbh_MIDI.c
 * @author	Xavier Halgand
 * @version
 * @date
 * @brief   This file is the MIDI Layer Handlers for USB Host MIDI streaming class.
 *
 *
 ******************************************************************************
 */

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

/* Includes ------------------------------------------------------------------*/
#include "usbh_MIDI.h"

/*------------------------------------------------------------------------------------------------------------------------------*/

/** @defgroup USBH_MIDI_CORE_Private_FunctionPrototypes
 * @{
 */

static USBH_StatusTypeDef USBH_MIDI_InterfaceInit(USBH_HandleTypeDef *phost);

static USBH_StatusTypeDef USBH_MIDI_InterfaceDeInit(USBH_HandleTypeDef *phost);

static USBH_StatusTypeDef USBH_MIDI_Process(USBH_HandleTypeDef *phost);

static USBH_StatusTypeDef USBH_MIDI_SOFProcess(USBH_HandleTypeDef *phost);

static USBH_StatusTypeDef USBH_MIDI_ClassRequest(USBH_HandleTypeDef *phost);

static void MIDI_ProcessTransmission(USBH_HandleTypeDef *phost);

static void MIDI_ProcessReception(USBH_HandleTypeDef *phost);

/*-------------------------------------------------------------------------*/

USBH_ClassTypeDef MIDI_Class = {
    "MIDI", USB_AUDIO_CLASS, USBH_MIDI_InterfaceInit, USBH_MIDI_InterfaceDeInit,
    USBH_MIDI_ClassRequest,
    USBH_MIDI_Process,  // background process called in HOST_CLASS state (core state machine)
    USBH_MIDI_SOFProcess,
    NULL  // MIDI handle structure
};

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  USBH_MIDI_InterfaceInit
 *         The function init the MIDI class.
 * @param  phost: Host handle
 * @retval USBH Status
 */
static USBH_StatusTypeDef USBH_MIDI_InterfaceInit(USBH_HandleTypeDef *phost) {
  USBH_StatusTypeDef status = USBH_FAIL;
  uint8_t interface         = 0;
  MIDI_HandleTypeDef *MIDI_Handle;

  //USB_MIDI_ChangeConnectionState(0);

  interface = USBH_FindInterface(phost, USB_AUDIO_CLASS,
                                 USB_MIDISTREAMING_SubCLASS, 0xFF);

  if (interface == 0xFF) /* No Valid Interface */
  {
    USBH_DbgLog("Cannot Find the interface for MIDI Interface Class.",
                phost->pActiveClass->Name);
    status = USBH_FAIL;
  } else {
    USBH_SelectInterface(phost, interface);

    phost->pActiveClass->pData =
        (MIDI_HandleTypeDef *)USBH_malloc(sizeof(MIDI_HandleTypeDef));
    MIDI_Handle = phost->pActiveClass->pData;

    if (phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
            .Ep_Desc[0]
            .bEndpointAddress &
        0x80) {
      MIDI_Handle->InEp =
          (phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
               .Ep_Desc[0]
               .bEndpointAddress);
      MIDI_Handle->InEpSize =
          phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
              .Ep_Desc[0]
              .wMaxPacketSize;
    } else {
      MIDI_Handle->OutEp =
          (phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
               .Ep_Desc[0]
               .bEndpointAddress);
      MIDI_Handle->OutEpSize =
          phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
              .Ep_Desc[0]
              .wMaxPacketSize;
    }

    if (phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
            .Ep_Desc[1]
            .bEndpointAddress &
        0x80) {
      MIDI_Handle->InEp =
          (phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
               .Ep_Desc[1]
               .bEndpointAddress);
      MIDI_Handle->InEpSize =
          phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
              .Ep_Desc[1]
              .wMaxPacketSize;
    } else {
      MIDI_Handle->OutEp =
          (phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
               .Ep_Desc[1]
               .bEndpointAddress);
      MIDI_Handle->OutEpSize =
          phost->device.CfgDesc.Itf_Desc[phost->device.current_interface]
              .Ep_Desc[1]
              .wMaxPacketSize;
    }

    MIDI_Handle->OutPipe = USBH_AllocPipe(phost, MIDI_Handle->OutEp);
    MIDI_Handle->InPipe  = USBH_AllocPipe(phost, MIDI_Handle->InEp);

    /* Open the new channels */
    USBH_OpenPipe(phost, MIDI_Handle->OutPipe, MIDI_Handle->OutEp,
                  phost->device.address, phost->device.speed, USB_EP_TYPE_BULK,
                  MIDI_Handle->OutEpSize);

    USBH_OpenPipe(phost, MIDI_Handle->InPipe, MIDI_Handle->InEp,
                  phost->device.address, phost->device.speed, USB_EP_TYPE_BULK,
                  MIDI_Handle->InEpSize);

    //USB_MIDI_ChangeConnectionState(1);
    MIDI_Handle->state = MIDI_IDLE_STATE;

    USBH_LL_SetToggle(phost, MIDI_Handle->InPipe, 0);
    USBH_LL_SetToggle(phost, MIDI_Handle->OutPipe, 0);
    status = USBH_OK;
  }
  return status;
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  USBH_MIDI_InterfaceDeInit
 *         The function DeInit the Pipes used for the MIDI class.
 * @param  phost: Host handle
 * @retval USBH Status
 */
USBH_StatusTypeDef USBH_MIDI_InterfaceDeInit(USBH_HandleTypeDef *phost) {
  MIDI_HandleTypeDef *MIDI_Handle = phost->pActiveClass->pData;

  if (MIDI_Handle->OutPipe) {
    USBH_ClosePipe(phost, MIDI_Handle->OutPipe);
    USBH_FreePipe(phost, MIDI_Handle->OutPipe);
    MIDI_Handle->OutPipe = 0; /* Reset the Channel as Free */
  }

  if (MIDI_Handle->InPipe) {
    USBH_ClosePipe(phost, MIDI_Handle->InPipe);
    USBH_FreePipe(phost, MIDI_Handle->InPipe);
    MIDI_Handle->InPipe = 0; /* Reset the Channel as Free */
  }

  if (phost->pActiveClass->pData) {
    USBH_free(phost->pActiveClass->pData);
    phost->pActiveClass->pData = 0;
  }

  return USBH_OK;
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  USBH_MIDI_ClassRequest
 *         The function is responsible for handling Standard requests
 *         for MIDI class.
 * @param  phost: Host handle
 * @retval USBH Status
 */
static USBH_StatusTypeDef USBH_MIDI_ClassRequest(USBH_HandleTypeDef *phost) {
  phost->pUser(phost, HOST_USER_CLASS_ACTIVE);

  return USBH_OK;
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
  * @brief  USBH_MIDI_Stop
  *         Stop current MIDI Transmission
  * @param  phost: Host handle
  * @retval USBH Status
  */
USBH_StatusTypeDef USBH_MIDI_Stop(USBH_HandleTypeDef *phost) {
  MIDI_HandleTypeDef *MIDI_Handle = phost->pActiveClass->pData;

  if (phost->gState == HOST_CLASS) {
    MIDI_Handle->state = MIDI_IDLE_STATE;

    USBH_ClosePipe(phost, MIDI_Handle->InPipe);
    USBH_ClosePipe(phost, MIDI_Handle->OutPipe);
  }
  return USBH_OK;
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  USBH_MIDI_Process
 *         The function is for managing state machine for MIDI data transfers
 *         (background process)
 * @param  phost: Host handle
 * @retval USBH Status
 */
static USBH_StatusTypeDef USBH_MIDI_Process(USBH_HandleTypeDef *phost) {
  USBH_StatusTypeDef status       = USBH_BUSY;
  USBH_StatusTypeDef req_status   = USBH_OK;
  MIDI_HandleTypeDef *MIDI_Handle = phost->pActiveClass->pData;

  switch (MIDI_Handle->state) {
    case MIDI_IDLE_STATE:
      status = USBH_OK;
      break;

    case MIDI_TRANSFER_DATA:

      MIDI_ProcessTransmission(phost);
      MIDI_ProcessReception(phost);
      break;

    case MIDI_ERROR_STATE:
      req_status = USBH_ClrFeature(phost, 0x00);

      if (req_status == USBH_OK) {
        /*Change the state to waiting*/
        MIDI_Handle->state = MIDI_IDLE_STATE;
      }
      break;

    default:
      break;
  }

  return status;
}
/*------------------------------------------------------------------------------------------------------------------------------*/

/**
  * @brief  USBH_MIDI_SOFProcess
  *         The function is for managing SOF callback
  * @param  phost: Host handle
  * @retval USBH Status
  */
static USBH_StatusTypeDef USBH_MIDI_SOFProcess(USBH_HandleTypeDef *phost) {
  return USBH_OK;
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  This function return last recieved data size
 * @param  None
 * @retval None
 */
uint16_t USBH_MIDI_GetLastReceivedDataSize(USBH_HandleTypeDef *phost) {
  MIDI_HandleTypeDef *MIDI_Handle = phost->pActiveClass->pData;

  if (phost->gState == HOST_CLASS) {
    return USBH_LL_GetLastXferSize(phost, MIDI_Handle->InPipe);
  } else {
    return 0;
  }
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  This function prepares the state before issuing the class specific commands
 * @param  None
 * @retval None
 */
USBH_StatusTypeDef USBH_MIDI_Transmit(USBH_HandleTypeDef *phost,
                                      uint8_t *pbuff,
                                      uint16_t length) {
  USBH_StatusTypeDef Status       = USBH_BUSY;
  MIDI_HandleTypeDef *MIDI_Handle = phost->pActiveClass->pData;

  if ((MIDI_Handle->state == MIDI_IDLE_STATE) ||
      (MIDI_Handle->state == MIDI_TRANSFER_DATA)) {
    MIDI_Handle->pTxData       = pbuff;
    MIDI_Handle->TxDataLength  = length;
    MIDI_Handle->state         = MIDI_TRANSFER_DATA;
    MIDI_Handle->data_tx_state = MIDI_SEND_DATA;
    Status                     = USBH_OK;
#if (USBH_USE_OS == 1)
    osMessagePut(phost->os_event, USBH_CLASS_EVENT, 0);
#endif
  }
  return Status;
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  This function prepares the state before issuing the class specific commands
 * @param  None
 * @retval None
 */
USBH_StatusTypeDef USBH_MIDI_Receive(USBH_HandleTypeDef *phost,
                                     uint8_t *pbuff,
                                     uint16_t length) {
  USBH_StatusTypeDef Status       = USBH_BUSY;
  MIDI_HandleTypeDef *MIDI_Handle = phost->pActiveClass->pData;

  if ((MIDI_Handle->state == MIDI_IDLE_STATE) ||
      (MIDI_Handle->state == MIDI_TRANSFER_DATA)) {
    MIDI_Handle->pRxData       = pbuff;
    MIDI_Handle->RxDataLength  = length;
    MIDI_Handle->state         = MIDI_TRANSFER_DATA;
    MIDI_Handle->data_rx_state = MIDI_RECEIVE_DATA;
    Status                     = USBH_OK;
#if (USBH_USE_OS == 1)
    osMessagePut(phost->os_event, USBH_CLASS_EVENT, 0);
#endif
  }
  return Status;
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  The function is responsible for sending data to the device
 *  @param  pdev: Selected device
 * @retval None
 */
static void MIDI_ProcessTransmission(USBH_HandleTypeDef *phost) {
  MIDI_HandleTypeDef *MIDI_Handle = phost->pActiveClass->pData;
  USBH_URBStateTypeDef URB_Status = USBH_URB_IDLE;

  switch (MIDI_Handle->data_tx_state) {
    case MIDI_SEND_DATA:
      if (MIDI_Handle->TxDataLength > MIDI_Handle->OutEpSize) {
        USBH_BulkSendData(phost, MIDI_Handle->pTxData, MIDI_Handle->OutEpSize,
                          MIDI_Handle->OutPipe, 1);
      } else {
        USBH_BulkSendData(phost, MIDI_Handle->pTxData,
                          MIDI_Handle->TxDataLength, MIDI_Handle->OutPipe, 1);
      }

      MIDI_Handle->data_tx_state = MIDI_SEND_DATA_WAIT;

      break;

    case MIDI_SEND_DATA_WAIT:

      URB_Status = USBH_LL_GetURBState(phost, MIDI_Handle->OutPipe);

      /*Check the status done for transmission*/
      if (URB_Status == USBH_URB_DONE) {
        if (MIDI_Handle->TxDataLength > MIDI_Handle->OutEpSize) {
          MIDI_Handle->TxDataLength -= MIDI_Handle->OutEpSize;
          MIDI_Handle->pTxData += MIDI_Handle->OutEpSize;
        } else {
          MIDI_Handle->TxDataLength = 0;
        }

        if (MIDI_Handle->TxDataLength > 0) {
          MIDI_Handle->data_tx_state = MIDI_SEND_DATA;
        } else {
          MIDI_Handle->data_tx_state = MIDI_IDLE;
          USBH_MIDI_TransmitCallback(phost);
        }
#if (USBH_USE_OS == 1)
        osMessagePut(phost->os_event, USBH_CLASS_EVENT, 0);
#endif
      } else if (URB_Status == USBH_URB_NOTREADY) {
        MIDI_Handle->data_tx_state = MIDI_SEND_DATA;
#if (USBH_USE_OS == 1)
        osMessagePut(phost->os_event, USBH_CLASS_EVENT, 0);
#endif
      }
      break;
    default:
      break;
  }
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  This function responsible for reception of data from the device
 *  @param  pdev: Selected device
 * @retval None
 */

static void MIDI_ProcessReception(USBH_HandleTypeDef *phost) {
  MIDI_HandleTypeDef *MIDI_Handle = phost->pActiveClass->pData;
  USBH_URBStateTypeDef URB_Status = USBH_URB_IDLE;
  uint16_t length;

  switch (MIDI_Handle->data_rx_state) {
    case MIDI_RECEIVE_DATA:

      USBH_BulkReceiveData(phost, MIDI_Handle->pRxData, MIDI_Handle->InEpSize,
                           MIDI_Handle->InPipe);

      MIDI_Handle->data_rx_state = MIDI_RECEIVE_DATA_WAIT;
      //BSP_LED_On(LED_Red); //ok only here

      break;

    case MIDI_RECEIVE_DATA_WAIT:

      URB_Status = USBH_LL_GetURBState(phost, MIDI_Handle->InPipe);

      /*Check the status done for reception*/
      if (URB_Status == USBH_URB_DONE) {
        length = USBH_LL_GetLastXferSize(phost, MIDI_Handle->InPipe);

        if (((MIDI_Handle->RxDataLength - length) > 0) &&
            (length > MIDI_Handle->InEpSize)) {
          MIDI_Handle->RxDataLength -= length;
          MIDI_Handle->pRxData += length;
          MIDI_Handle->data_rx_state = MIDI_RECEIVE_DATA;
        } else {
          MIDI_Handle->data_rx_state = MIDI_IDLE;
          USBH_MIDI_ReceiveCallback(phost);
        }
#if (USBH_USE_OS == 1)
        osMessagePut(phost->os_event, USBH_CLASS_EVENT, 0);
#endif
      }
      break;

    default:
      break;
  }
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  The function informs user that data have been transmitted.
 *  @param  pdev: Selected device
 * @retval None
 */
__weak void USBH_MIDI_TransmitCallback(USBH_HandleTypeDef *phost) {
}

/*------------------------------------------------------------------------------------------------------------------------------*/

/**
 * @brief  The function informs user that data have been received.
 * @retval None
 */
__weak void USBH_MIDI_ReceiveCallback(USBH_HandleTypeDef *phost) {
}

/**************************END OF FILE*********************************************************/


text:
Yeoman Housestyles
==================

A Yeoman setup to generate a standards-compliant project from the command line with customisable features.
This project is based on the house styles repository by Tangent Snowball, which you can find [here](https://github.com/tangentsnowball/house-styles)

---

## Quick setup

The following needs to be completed before you can use this generator:

+ Install Node ([Direct download](http://nodejs.org/download/))
+ Install Yeoman `npm install -g yo` (this may require sudo)

Once these have been installed, clone the repository and `cd` into it. Then run:

`sudo npm link`

This will create a link between this code and Yeoman so it can be recognised as a generator.

You are all set up!

---

## Using the generator:

+ Create a directory and `cd` into it.
+ run `yo housestyles --force` (the force is to automate the overriding of the CSS files when they are customised)

You will be presented with a list of options:

+ Name of project (_Default:_ **_Empty_**) - This will be used for the `<title>` attribute and an `<h1>` on the home page
+ Responsive styles? (_Default:_ **_True_**) - Whether to include Tangent Snowball's default responsive styles
+ Features (_Default:_ **_True_**) - A checkbox that enables you to select/deselect features for the project. These include:
  * Icomoon (a third-party icon font used in Tangent Snowball's housestyles)
  * Modernizr (a third-party service used for feature detection)
+ LESS Features (Aspects of the standard house styles):
  * Alerts
  * Tabs
  * Icons
  * Popups

---

## Questions

If you find anything wrong with the plugin, have issues getting it working, or think of something cool it could do, feel free to submit an issue.


text:
package org.mongodb.morphia;

import com.mongodb.MapReduceCommand.OutputType;

/**
 * Defines how the output of the map reduce job is handled.
 * @deprecated use {@link OutputType} instead
 */
@Deprecated
public enum MapreduceType {
    REPLACE,
    MERGE,
    REDUCE,
    INLINE;

    /**
     * Finds the type represented by the value given
     *
     * @param value the value to look up
     * @return the type represented by the value given
     */
    public static MapreduceType fromString(final String value) {
        for (int i = 0; i < values().length; i++) {
            final MapreduceType fo = values()[i];
            if (fo.name().equals(value)) {
                return fo;
            }
        }
        return null;
    }

    OutputType toOutputType() {
        switch (this) {
            case REDUCE:
                return OutputType.REDUCE;
            case MERGE:
                return OutputType.MERGE;
            case INLINE:
                return OutputType.INLINE;
            default:
                return OutputType.REPLACE;
        }

    }
}


text:
const Task = require('../ember-cli/lib/models/task');
const stringUtils = require('ember-cli-string-utils');
import { CliConfig } from '../models/config';
import { getCollection, getSchematic } from '../utilities/schematics';

export interface SchematicGetOptions {
  collectionName: string;
  schematicName: string;
}

export interface SchematicAvailableOptions {
  name: string;
  description: string;
  aliases: string[];
  type: any;
}

export default Task.extend({
  run: function (options: SchematicGetOptions): Promise<SchematicAvailableOptions[]> {
    const collectionName = options.collectionName ||
      CliConfig.getValue('defaults.schematics.collection');

    const collection = getCollection(collectionName);

    const schematic = getSchematic(collection, options.schematicName);

    const properties = schematic.description.schemaJson.properties;
    const keys = Object.keys(properties);
    const availableOptions = keys
      .map(key => ({...properties[key], ...{name: stringUtils.dasherize(key)}}))
      .map(opt => {
        let type;
        switch (opt.type) {
          case 'string':
            type = String;
            break;
          case 'boolean':
            type = Boolean;
            break;
        }
        let aliases: string[] = [];
        if (opt.alias) {
          aliases = [...aliases, opt.alias];
        }
        if (opt.aliases) {
          aliases = [...aliases, ...opt.aliases];
        }

        return {
          ...opt,
          aliases,
          type,
          default: undefined // do not carry over schematics defaults
        };
      });

    return Promise.resolve(availableOptions);
  }
});


text:
package com.kotcrab.vis.runtime.util;

import com.artemis.utils.Bag;
import com.artemis.utils.ImmutableBag;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectSet;

/**
 * Various {@link Bag} related utils
 * @author Kotcrab
 */
public class VisBagUtils {
	public static <E> Array<E> toArray (ImmutableBag<E> bag) {
		Array<E> array = new Array<E>(bag.size());

		for (E element : bag)
			array.add(element);

		return array;
	}

	public static <E> ObjectSet<E> toSet (ImmutableBag<E> bag) {
		ObjectSet<E> array = new ObjectSet<E>(bag.size());

		for (E element : bag)
			array.add(element);

		return array;
	}

	public static <E> Bag<E> toBag (Array<E> array) {
		Bag<E> bag = new Bag<E>(array.size);

		for (E element : array)
			bag.add(element);

		return bag;
	}
}


text:
package org.apache.sis.internal.stream;

import java.util.function.DoublePredicate;
import java.util.function.DoubleUnaryOperator;
import java.util.stream.DoubleStream;
import java.util.stream.Stream;

/**
 * A stream on which {@code skip} and {@code limit} operations are delegated to a root stream.
 * This is useful when the root stream is capable of some optimizations, for example using SQL.
 * The redirection stops as soon as an operation may change the elements order or filtering.
 *
 * @author  Alexis Manin (Geomatys)
 * @author  Martin Desruisseaux (Geomatys)
 * @version 1.1
 * @since   1.1
 * @module
 */
public final class PaginedDoubleStream extends DoubleStreamWrapper {
    /**
     * The root stream on which to delegate {@code skip} and {@code limit} operations.
     */
    private Stream<?> root;

    /**
     * Creates a new mapped stream.
     *
     * @param  source  the stream to wrap.
     * @param  root    the stream on which to delegate {@code skip} and {@code limit} operations.
     */
    public PaginedDoubleStream(final DoubleStream source, final Stream<?> root) {
        super(source);
        this.root = root;
    }

    /**
     * Discards the specified number of elements.
     * This method delegates the operation to the root stream.
     *
     * @param  n  number of elements to skip.
     * @return {@code this}.
     */
    @Override
    public DoubleStream skip(final long n) {
        root = root.skip(n);
        return this;
    }

    /**
     * Truncates this stream to the given number of elements.
     * This method delegates the operation to the root stream.
     *
     * @param  maxSize  number of elements to keep.
     * @return {@code this}.
     */
    @Override
    public DoubleStream limit(final long maxSize) {
        root = root.limit(maxSize);
        return this;
    }

    /**
     * Returns the number of elements in this stream.
     * This method delegates the operation to the root stream.
     *
     * @return number of elements in this stream.
     */
    @Override
    public long count() {
        return root.count();
    }

    @Override
    public DoubleStream map(DoubleUnaryOperator mapper) {
        return new PaginedDoubleStream(super.map(mapper), root);
    }

    /*
     * All intermediate methods that may change elements order or count must be listed below.
     */
    @Override public DoubleStream distinct()                        {return delegate().distinct();}
    @Override public DoubleStream unordered()                       {return delegate().unordered();}
    @Override public DoubleStream sorted()                          {return delegate().sorted();}
    @Override public DoubleStream filter(DoublePredicate predicate) {return delegate().filter(predicate);}
}


text:
import Test.HUnit
import Q22

test1 = TestCase (assertEqual "rangeTest 1 0 should be Right y < x is not supported." (Right "y < x is not supported") (rangeTest 1 0))
test2 = TestCase (assertEqual "rangeTest 0 0 should be Left [0]                    ." (Left [0]                      ) (rangeTest 0 0))
test3 = TestCase (assertEqual "rangeTest 0 1 should be Left [0,1]                  ." (Left [0,1]                    ) (rangeTest 0 1))
test4 = TestCase (assertEqual "rangeTest 0 2 should be Left [0,1,2]                ." (Left [0,1,2]                  ) (rangeTest 0 2))
test5 = TestCase (assertEqual "rangeTest 1 2 should be Left [1,2]                  ." (Left [1,2]                    ) (rangeTest 1 2))

main = runTestTT $ TestList [test1,test2,test3,test4,test5]


text:
package androidx.appcompat.app;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import android.os.Build;
import android.os.SystemClock;
import android.support.test.filters.SmallTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.KeyEvent;

import androidx.appcompat.test.R;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * Test shortcut trigger in case of MenuItems with non-default modifiers.
 */
@SmallTest
@RunWith(AndroidJUnit4.class)
public class AppCompatMenuItemShortcutsTest {

    private AppCompatMenuItemShortcutsTestActivity mActivity;

    @Rule
    public ActivityTestRule<AppCompatMenuItemShortcutsTestActivity> mActivityTestRule =
            new ActivityTestRule<>(AppCompatMenuItemShortcutsTestActivity.class);

    @Before
    public void setup() {
        mActivity = mActivityTestRule.getActivity();
    }

    @Test
    public void testPerformShortcut() {
        // The support library is only needed for API 25 or lower.
        if (Build.VERSION.SDK_INT < 26) {
            final long downTime = SystemClock.uptimeMillis();
            int keyCodeToSend, metaState;
            KeyEvent keyEventToSend;

            // Test shortcut trigger in case of non-default single modifier
            keyCodeToSend = KeyEvent.KEYCODE_C;
            metaState = KeyEvent.META_SHIFT_ON;
            keyEventToSend = new KeyEvent(downTime, downTime, KeyEvent.ACTION_DOWN,
                    keyCodeToSend, 0, metaState);
            assertTrue(mActivity.onKeyDown(keyCodeToSend, keyEventToSend));
            assertEquals(mActivity.getMenuItemIdTracker(), R.id.single_modifier);

            // Test shortcut trigger in case of multiple non-default modifiers
            keyCodeToSend = KeyEvent.KEYCODE_D;
            metaState = KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON;
            keyEventToSend = new KeyEvent(downTime, downTime, KeyEvent.ACTION_DOWN,
                    keyCodeToSend, 0, metaState);
            assertTrue(mActivity.onKeyDown(keyCodeToSend, keyEventToSend));
            assertEquals(mActivity.getMenuItemIdTracker(), R.id.multiple_modifiers);

            // Test no shortcut trigger in case of incorrect modifier
            keyCodeToSend = KeyEvent.KEYCODE_E;
            metaState = KeyEvent.META_CTRL_ON;
            keyEventToSend = new KeyEvent(downTime, downTime, KeyEvent.ACTION_DOWN,
                    keyCodeToSend, 0, metaState);
            assertFalse(mActivity.onKeyDown(keyCodeToSend, keyEventToSend));
        }
    }
}


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// tile.cpp
//
// Identification: src/backend/storage/tile.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <cassert>
#include <cstdio>
#include <sstream>

#include "backend/catalog/schema.h"
#include "backend/common/exception.h"
#include "backend/common/pool.h"
#include "backend/common/serializer.h"
#include "backend/common/types.h"
#include "backend/storage/tuple_iterator.h"
#include "backend/storage/tuple.h"
#include "backend/storage/storage_manager.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group_header.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "backend/concurrency/optimistic_rb_txn_manager.h"

namespace peloton {
namespace storage {

Tile::Tile(BackendType backend_type, TileGroupHeader *tile_header,
           const catalog::Schema &tuple_schema, TileGroup *tile_group,
           int tuple_count)
    : database_id(INVALID_OID),
      table_id(INVALID_OID),
      tile_group_id(INVALID_OID),
      tile_id(INVALID_OID),
      backend_type(backend_type),
      schema(tuple_schema),
      data(NULL),
      tile_group(tile_group),
      pool(NULL),
      num_tuple_slots(tuple_count),
      column_count(tuple_schema.GetColumnCount()),
      tuple_length(tuple_schema.GetLength()),
      uninlined_data_size(0),
      column_header(NULL),
      column_header_size(INVALID_OID),
      tile_group_header(tile_header) {
  assert(tuple_count > 0);

  tile_size = tuple_count * tuple_length;

  // allocate tuple storage space for inlined data
  auto &storage_manager = storage::StorageManager::GetInstance();
  data = reinterpret_cast<char *>(
      storage_manager.Allocate(backend_type, tile_size));
  assert(data != NULL);

  // zero out the data
  std::memset(data, 0, tile_size);

  // allocate pool for blob storage if schema not inlined
  if (schema.IsInlined() == false) pool = new VarlenPool(backend_type);
}

Tile::~Tile() {
  // reclaim the tile memory (INLINED data)
  auto &storage_manager = storage::StorageManager::GetInstance();
  storage_manager.Release(backend_type, data);
  data = NULL;

  // reclaim the tile memory (UNINLINED data)
  if (schema.IsInlined() == false) delete pool;
  pool = NULL;

  // clear any cached column headers
  if (column_header) delete column_header;
  column_header = NULL;
}

//===--------------------------------------------------------------------===//
// Tuples
//===--------------------------------------------------------------------===//

/**
 * Insert tuple at slot
 * NOTE : No checks, must be at valid slot.
 */
void Tile::InsertTuple(const oid_t tuple_offset, Tuple *tuple) {
  assert(tuple_offset < GetAllocatedTupleCount());

  // Find slot location
  char *location = tuple_offset * tuple_length + data;

  // Copy over the tuple data into the tuple slot in the tile
  std::memcpy(location, tuple->tuple_data, tuple_length);
}

/**
 * Returns value present at slot
 */
// column id is a 0-based column number
Value Tile::GetValue(const oid_t tuple_offset, const oid_t column_id) {
  assert(tuple_offset < GetAllocatedTupleCount());
  assert(column_id < schema.GetColumnCount());

  const ValueType column_type = schema.GetType(column_id);

  const char *tuple_location = GetTupleLocation(tuple_offset);
  const char *field_location = tuple_location + schema.GetOffset(column_id);
  const bool is_inlined = schema.IsInlined(column_id);

  // ROLLBACK SEGMENT
  if (concurrency::TransactionManagerFactory::GetProtocol() == peloton::CONCURRENCY_TYPE_OCC_RB) {
    auto txn_manager = static_cast<concurrency::OptimisticRbTxnManager *>(&concurrency::TransactionManagerFactory::GetInstance());
    cid_t read_ts = txn_manager->GetLatestReadTimestamp();
    auto tile_group_header = tile_group->GetHeader();

    // The ininitial value of this column is in the master copy
    Value value = Value::InitFromTupleStorage(field_location, column_type, is_inlined);

    // If self is owner, just return the master version
    if (txn_manager->IsOwner(tile_group_header, tuple_offset))
      return value;

    RBSegType rb_seg = txn_manager->GetRbSeg(tile_group_header, tuple_offset);

    // Traverse the RB chain, stop when invisible
    while (txn_manager->IsRBVisible(rb_seg, read_ts) == true) {
      auto rb_col_count = storage::RollbackSegmentPool::GetColCount(rb_seg);
      for (size_t col_idx = 0; col_idx < rb_col_count; col_idx++) {
        auto col_id = storage::RollbackSegmentPool::GetIdOffsetPair(rb_seg, col_idx)->col_id;
        // We have found the column in one of the rollback segment
        if (col_id == column_id) {
          value = storage::RollbackSegmentPool::GetValue(rb_seg, &schema, col_idx);
        }
      }

      rb_seg = storage::RollbackSegmentPool::GetNextPtr(rb_seg);
    }

    return value;
  }
  // ROLLBACK SEGMENT

  return Value::InitFromTupleStorage(field_location, column_type, is_inlined);
}

/*
 * Faster way to get value
 * By amortizing schema lookups
 */
// column offset is the actual offset of the column within the tuple slot
Value Tile::GetValueFast(const oid_t tuple_offset, const size_t column_offset,
                         const ValueType column_type, const bool is_inlined) {
  assert(tuple_offset < GetAllocatedTupleCount());
  assert(column_offset < schema.GetLength());

  const char *tuple_location = GetTupleLocation(tuple_offset);
  const char *field_location = tuple_location + column_offset;

  return Value::InitFromTupleStorage(field_location, column_type, is_inlined);
}

/**
 * Sets value at tuple slot.
 */
// column id is a 0-based column number
void Tile::SetValue(const Value &value, const oid_t tuple_offset,
                    const oid_t column_id) {
  assert(tuple_offset < num_tuple_slots);
  assert(column_id < schema.GetColumnCount());

  char *tuple_location = GetTupleLocation(tuple_offset);
  char *field_location = tuple_location + schema.GetOffset(column_id);
  const bool is_inlined = schema.IsInlined(column_id);
  size_t column_length = schema.GetAppropriateLength(column_id);

  const bool is_in_bytes = false;
  value.SerializeToTupleStorageAllocateForObjects(
      field_location, is_inlined, column_length, is_in_bytes, pool);
}

/*
 * Faster way to set value
 * By amortizing schema lookups
 */
// column offset is the actual offset of the column within the tuple slot
void Tile::SetValueFast(const Value &value, const oid_t tuple_offset,
                        const size_t column_offset, const bool is_inlined,
                        const size_t column_length) {
  assert(tuple_offset < num_tuple_slots);
  assert(column_offset < schema.GetLength());

  char *tuple_location = GetTupleLocation(tuple_offset);
  char *field_location = tuple_location + column_offset;

  const bool is_in_bytes = false;
  value.SerializeToTupleStorageAllocateForObjects(
      field_location, is_inlined, column_length, is_in_bytes, pool);
}

Tile *Tile::CopyTile(BackendType backend_type) {
  auto schema = GetSchema();
  bool tile_columns_inlined = schema->IsInlined();
  auto allocated_tuple_count = GetAllocatedTupleCount();

  // Create a shallow copy of the old tile
  TileGroupHeader *new_header = GetHeader();
  Tile *new_tile = TileFactory::GetTile(
      backend_type, INVALID_OID, INVALID_OID, INVALID_OID, INVALID_OID,
      new_header, *schema, tile_group, allocated_tuple_count);

  ::memcpy(static_cast<void *>(new_tile->data), static_cast<void *>(data),
           tile_size);

  // Do a deep copy if some column is uninlined, so that
  // the values in that column point to the new pool
  if (!tile_columns_inlined) {
    auto uninlined_col_cnt = schema->GetUninlinedColumnCount();

    // Go over each uninlined column, making a deep copy
    for (oid_t col_itr = 0; col_itr < uninlined_col_cnt; col_itr++) {
      auto uninlined_col_offset = schema->GetUninlinedColumn(col_itr);

      // Copy the column over to the new tile group
      for (oid_t tuple_itr = 0; tuple_itr < allocated_tuple_count;
           tuple_itr++) {
        auto val = new_tile->GetValue(tuple_itr, uninlined_col_offset);
        new_tile->SetValue(val, tuple_itr, uninlined_col_offset);
      }
    }
  }

  return new_tile;
}

//===--------------------------------------------------------------------===//
// Utilities
//===--------------------------------------------------------------------===//

const std::string Tile::GetInfo() const {
  std::ostringstream os;

  os << "\t-----------------------------------------------------------\n";

  os << "\tTILE\n";
  os << "\tCatalog ::"
     << " DB: " << database_id << " Table: " << table_id
     << " Tile Group:  " << tile_group_id << " Tile:  " << tile_id << "\n";

  // Tuples
  os << "\t-----------------------------------------------------------\n";
  os << "\tDATA\n";

  TupleIterator tile_itr(this);
  Tuple tuple(&schema);

  std::string last_tuple = "";

  while (tile_itr.Next(tuple)) {
    os << "\t" << tuple;
  }

  os << "\t-----------------------------------------------------------\n";

  tuple.SetNull();

  return os.str();
}

//===--------------------------------------------------------------------===//
// Serialization/Deserialization
//===--------------------------------------------------------------------===//

bool Tile::SerializeTo(SerializeOutput &output, oid_t num_tuples) {
  /**
   * The table is serialized as:
   *
   * [(int) total size]
   * [(int) header size] [num columns] [column types] [column names]
   * [(int) num tuples] [tuple data]
   *
   */

  // A placeholder for the total table size written at the end
  std::size_t pos = output.Position();
  output.WriteInt(-1);

  // Serialize the header
  if (!SerializeHeaderTo(output)) return false;

  // Active tuple count
  output.WriteInt(static_cast<int>(num_tuples));

  oid_t written_count = 0;
  TupleIterator tile_itr(this);
  Tuple tuple(&schema);

  while (tile_itr.Next(tuple) && written_count < num_tuples) {
    tuple.SerializeTo(output);
    ++written_count;
  }

  tuple.SetNull();

  assert(written_count == num_tuples);

  // Length prefix is non-inclusive
  int32_t sz = static_cast<int32_t>(output.Position() - pos - sizeof(int32_t));
  assert(sz > 0);
  output.WriteIntAt(pos, sz);

  return true;
}

bool Tile::SerializeHeaderTo(SerializeOutput &output) {
  std::size_t start;

  // Use the cache if possible
  if (column_header != NULL) {
    assert(column_header_size != INVALID_OID);
    output.WriteBytes(column_header, column_header_size);
    return true;
  }

  assert(column_header_size == INVALID_OID);

  // Skip header position
  start = output.Position();
  output.WriteInt(-1);

  // Status code
  output.WriteByte(-128);

  // Column counts as a short
  output.WriteShort(static_cast<int16_t>(column_count));

  // Write an array of column types as bytes
  for (oid_t column_itr = 0; column_itr < column_count; ++column_itr) {
    ValueType type = schema.GetType(column_itr);
    output.WriteByte(static_cast<int8_t>(type));
  }

  // Write the array of column names as strings
  // NOTE: strings are ASCII only in metadata (UTF-8 in table storage)
  for (oid_t column_itr = 0; column_itr < column_count; ++column_itr) {
    // Column name: Write (offset, length) for column definition, and string to
    // string table
    const std::string &name = GetColumnName(column_itr);

    // Column names can't be null, so length must be >= 0
    int32_t length = static_cast<int32_t>(name.size());
    assert(length >= 0);

    // this is standard string serialization for voltdb
    output.WriteInt(length);
    output.WriteBytes(name.data(), length);
  }

  // Write the header size which is a non-inclusive int
  size_t Position = output.Position();
  column_header_size = static_cast<int32_t>(Position - start);

  int32_t non_inclusive_header_size =
      static_cast<int32_t>(column_header_size - sizeof(int32_t));
  output.WriteIntAt(start, non_inclusive_header_size);

  // Cache the column header
  column_header = new char[column_header_size];
  memcpy(column_header, static_cast<const char *>(output.Data()) + start,
         column_header_size);

  return true;
}

//  Serialized only the tuples specified, along with header.
bool Tile::SerializeTuplesTo(SerializeOutput &output, Tuple *tuples,
                             int num_tuples) {
  std::size_t pos = output.Position();
  output.WriteInt(-1);

  assert(!tuples[0].IsNull());

  // Serialize the header
  if (!SerializeHeaderTo(output)) return false;

  output.WriteInt(static_cast<int32_t>(num_tuples));
  for (int tuple_itr = 0; tuple_itr < num_tuples; tuple_itr++) {
    tuples[tuple_itr].SerializeTo(output);
  }

  // Length prefix is non-inclusive
  output.WriteIntAt(
      pos, static_cast<int32_t>(output.Position() - pos - sizeof(int32_t)));

  return true;
}

/**
 * Loads only tuple data, not schema, from the serialized tile.
 * Used for initial data loading.
 * @param allow_export if false, export enabled is overriden for this load.
 */
void Tile::DeserializeTuplesFrom(SerializeInputBE &input, VarlenPool *pool) {
  /*
   * Directly receives a Tile buffer.
   * [00 01]   [02 03]   [04 .. 0x]
   * rowstart  colcount  colcount * 1 byte (column types)
   *
   * [0x+1 .. 0y]
   * colcount * strings (column names)
   *
   * [0y+1 0y+2 0y+3 0y+4]
   * rowcount
   *
   * [0y+5 .. end]
   * rowdata
   */

  input.ReadInt();  // rowstart
  input.ReadByte();

  oid_t column_count = input.ReadShort();
  assert(column_count > 0);

  // Store the following information so that we can provide them to the user on
  // failure
  ValueType types[column_count];
  std::vector<std::string> names;

  // Skip the column types
  for (oid_t column_itr = 0; column_itr < column_count; ++column_itr) {
    types[column_itr] = (ValueType) input.ReadEnumInSingleByte();
  }

  // Skip the column names
  for (oid_t column_itr = 0; column_itr < column_count; ++column_itr) {
    names.push_back(input.ReadTextString());
  }

  // Check if the column count matches what the temp table is expecting
  if (column_count != schema.GetColumnCount()) {
    std::stringstream message(std::stringstream::in | std::stringstream::out);

    message << "Column count mismatch. Expecting " << schema.GetColumnCount()
            << ", but " << column_count << " given" << std::endl;
    message << "Expecting the following columns:" << std::endl;
    message << schema.GetColumnCount() << std::endl;
    message << "The following columns are given:" << std::endl;

    for (oid_t column_itr = 0; column_itr < column_count; column_itr++) {
      message << "column " << column_itr << ": " << names[column_itr]
              << ", type = " << ValueTypeToString(types[column_itr])
              << std::endl;
    }

    throw SerializationException(message.str());
  }

  // Use the deserialization routine skipping header
  DeserializeTuplesFromWithoutHeader(input, pool);
}

/**
 * Loads only tuple data and assumes there is no schema present.
 * Used for recovery where the schema is not sent.
 * @param allow_export if false, export enabled is overriden for this load.
 */
void Tile::DeserializeTuplesFromWithoutHeader(SerializeInputBE &input,
                                              VarlenPool *pool) {
  oid_t tuple_count = input.ReadInt();
  assert(tuple_count > 0);

  // First, check if we have required space
  assert(tuple_count <= num_tuple_slots);
  storage::Tuple *temp_tuple = new storage::Tuple(&schema, true);

  for (oid_t tuple_itr = 0; tuple_itr < tuple_count; ++tuple_itr) {
    temp_tuple->Move(GetTupleLocation(tuple_itr));
    temp_tuple->DeserializeFrom(input, pool);
    // TRACE("Loaded new tuple #%02d\n%s", tuple_itr,
    // temp_target1.debug(Name()).c_str());
  }
}

// active tuple slots
oid_t Tile::GetActiveTupleCount() const {
  // For normal tiles
  if (tile_group_header != nullptr) {
    return tile_group_header->GetCurrentNextTupleSlot();
  }
      // For temp tiles
      else {
    return num_tuple_slots;
  }
}

void Tile::Sync() {
  // Sync the tile data
  auto &storage_manager = storage::StorageManager::GetInstance();
  storage_manager.Sync(backend_type, data, tile_size);
}

//===--------------------------------------------------------------------===//
// Utilities
//===--------------------------------------------------------------------===//

// Compare two tiles (expensive !)
bool Tile::operator==(const Tile &other) const {
  if (!(GetColumnCount() == other.GetColumnCount())) return false;

  if (!(database_id == other.database_id)) return false;

  catalog::Schema other_schema = other.schema;
  if (schema != other_schema) return false;

  TupleIterator tile_itr(this);
  TupleIterator other_tile_itr(&other);

  Tuple tuple(&schema);
  Tuple other_tuple(&other_schema);

  while (tile_itr.Next(tuple)) {
    if (!(other_tile_itr.Next(other_tuple))) return false;

    if (!(tuple == other_tuple)) return false;
  }

  tuple.SetNull();
  other_tuple.SetNull();

  return true;
}

bool Tile::operator!=(const Tile &other) const { return !(*this == other); }

TupleIterator Tile::GetIterator() { return TupleIterator(this); }

// TileStats* Tile::GetTileStats() {
//	return NULL;
//}

}  // End storage namespace
}  // End peloton namespace


text:
FROM tianon/centos:6.5
MAINTAINER Hiroaki Nakamura <hnakamur@gmail.com>

# install epel (for GeoIP-devel)
RUN yum install -y http://ftp.iij.ad.jp/pub/linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm && \
    rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

# update RPMs
RUN yum update -y

# build ruby
RUN yum install -y tar gcc && \
    cd /usr/local/src && \
    curl -O http://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.1.tar.gz && \
    tar xf ruby-2.1.1.tar.gz && \
    cd /usr/local/src/ruby-2.1.1 && \
    ./configure --prefix /usr/local/ruby && \
    make && \
    make install && \
    rm -rf /usr/local/src/ruby-2.1.1 ruby-2.1.1.tar.gz

# build redis
RUN yum install -y curl tar make gcc && \
    cd /usr/local/src && \
    curl -O http://download.redis.io/releases/redis-2.8.8.tar.gz && \
    tar xf redis-2.8.8.tar.gz && \
    cd redis-2.8.8 && \
    make && \
    make install

# build hiredis
RUN yum install -y git && \
    cd /usr/local/src && \
    git clone https://github.com/redis/hiredis && \
    cd hiredis && \
    make && \
    make install INSTALL_LIBRARY_PATH=/usr/local/lib64 && \
    echo /usr/local/lib64 > /etc/ld.so.conf.d/hiredis.conf && \
    ldconfig

# build pcre
RUN yum install -y gcc-c++ && \
    cd /usr/local/src && \
    curl -L -o pcre-8.35.tar.gz http://sourceforge.net/projects/pcre/files/pcre/8.35/pcre-8.35.tar.gz/download && \
    tar xf pcre-8.35.tar.gz && \
    cd pcre-8.35 && \
    ./configure --prefix=/usr/local --libdir=/usr/local/lib64 \
      --enable-jit --enable-utf && \
    make && \
    make install && \
    echo /usr/local/lib64 > /etc/ld.so.conf.d/pcre-8.35.x86_64.conf && \
    ldconfig

# build ngx_mruby
RUN yum install -y bison git wget openssl-devel && \
    cd /usr/local/src && \
    git clone git://github.com/matsumoto-r/ngx_mruby.git && \
    cd ngx_mruby && \
    git submodule init && \
    git submodule update && \
    cd /usr/local/src/ngx_mruby && \
    sed -i.orig "s|conf.gem :git => 'git://github.com/matsumoto-r/mruby-memcached.git'|#&|;/^  conf.gem :git => 'git:\/\/github.com\/mattn\/mruby-onig-regexp.git'/a\
\  conf.gem :git => 'git://github.com/iij/mruby-env.git'" \
      build_config.rb && \
    cd /usr/local/src && \
    curl -O http://nginx.org/download/nginx-1.4.7.tar.gz && \
    tar xf nginx-1.4.7.tar.gz && \
    cd /usr/local/src/ngx_mruby && \
    PATH=/usr/local/ruby/bin:$PATH \
      NGINX_CONFIG_OPT_ENV='--prefix=/usr/local/nginx' \
      NGINX_SRC_ENV='/usr/local/src/nginx-1.4.7' \
      sh build.sh

# build nginx with mruby
#
# Configuration summary
#   + using PCRE library: /usr/local/src/pcre-8.35
#   + using system OpenSSL library
#   + md5: using OpenSSL library
#   + sha1: using OpenSSL library
#   + using system zlib library
#
#   nginx path prefix: "/usr/local/nginx"
#   nginx binary file: "/usr/local/nginx/sbin/nginx"
#   nginx configuration prefix: "/usr/local/nginx/conf"
#   nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
#   nginx pid file: "/usr/local/nginx/logs/nginx.pid"
#   nginx error log file: "/usr/local/nginx/logs/error.log"
#   nginx http access log file: "/usr/local/nginx/logs/access.log"
#   nginx http client request body temporary files: "client_body_temp"
#   nginx http proxy temporary files: "proxy_temp"
#   nginx http fastcgi temporary files: "fastcgi_temp"
#   nginx http uwsgi temporary files: "uwsgi_temp"
#   nginx http scgi temporary files: "scgi_temp"
#
RUN yum install -y openssl-devel zlib-devel libxslt-devel gd-devel \
      GeoIP-devel httpd-tools && \
    cd /usr/local/src/nginx-1.4.7 && \
    ./configure --prefix=/usr/local/nginx \
      --user=nginx \
      --group=nginx \
      --with-file-aio \
      --with-ipv6 \
      --with-http_ssl_module \
      --with-http_realip_module \
      --with-http_addition_module \
      --with-http_xslt_module \
      --with-http_image_filter_module \
      --with-http_geoip_module \
      --with-http_sub_module \
      --with-http_dav_module \
      --with-http_flv_module \
      --with-http_mp4_module \
      --with-http_gzip_static_module \
      --with-http_random_index_module \
      --with-http_secure_link_module \
      --with-http_degradation_module \
      --with-http_stub_status_module \
      --with-md5-asm \
      --with-sha1-asm \
      --with-pcre-jit --with-pcre=/usr/local/src/pcre-8.35 \
      --with-cc-opt='-O2 -g' \
      --add-module=/usr/local/src/ngx_mruby \
      --add-module=/usr/local/src/ngx_mruby/dependence/ngx_devel_kit && \
    make && \
    useradd -r -d /usr/local/nginx -s /sbin/nologin \
      -c 'nginx web server with mruby' nginx && \
    make install

ADD conf/ /usr/local/nginx/conf/
ADD html/ /usr/local/nginx/html/
EXPOSE 80
CMD ["/usr/local/nginx/sbin/nginx"]


text:
/**
 * @file Tabs
 */

export default from './Tabs';


text:
require 'thread'

module Aws
  module S3
    class BucketRegionCache

      def initialize
        @regions = {}
        @listeners = []
        @mutex = Mutex.new
      end

      # Registers a block as a callback. This listener is called when a
      # new bucket/region pair is added to the cache.
      #
      #     S3::BUCKET_REGIONS.bucket_added do |bucket_name, region_name|
      #       # ...
      #     end
      #
      # This happens when a request is made against the classic endpoint,
      # "s3.amazonaws.com" and an error is returned requiring the request
      # to be resent with Signature Version 4. At this point, multiple
      # requests are made to discover the bucket region so that a v4
      # signature can be generated.
      #
      # An application can register listeners here to avoid these extra
      # requests in the future. By constructing an {S3::Client} with
      # the proper region, a proper signature can be generated and redirects
      # avoided.
      # @return [void]
      def bucket_added(&block)
        if block
          @mutex.synchronize { @listeners << block }
        else
          raise ArgumentError, 'missing required block'
        end
      end

      # @param [String] bucket_name
      # @return [String,nil] Returns the cached region for the named bucket.
      #   Returns `nil` if the bucket is not in the cache.
      # @api private
      def [](bucket_name)
        @mutex.synchronize { @regions[bucket_name] }
      end

      # Caches a bucket's region. Calling this method will trigger each
      # of the {#bucket_added} listener callbacks.
      # @param [String] bucket_name
      # @param [String] region_name
      # @return [void]
      # @api private
      def []=(bucket_name, region_name)
        @mutex.synchronize do
          @regions[bucket_name] = region_name
          @listeners.each { |block| block.call(bucket_name, region_name) }
        end
      end

      # @api private
      def clear
        @mutex.synchronize { @regions = {} }
      end

      # @return [Hash] Returns a hash of cached bucket names and region names.
      def to_hash
        @mutex.synchronize do
          @regions.dup
        end
      end
      alias to_h to_hash

    end

    # @api private
    BUCKET_REGIONS = BucketRegionCache.new

  end
end


text:
var redis = require("redis"); // npm install redis
var fail = require("../common").fail;

var pubsub = require("./pubsub");

console.log("loaded module: profile"); // TODO - __filename

// profiles -> GET /profiles?[username|userid=] -> <profiles>
//             Only returns profiles with matching prefix if username specified
// curl -X GET http://127.0.0.1:8000/profiles
exports.GET = function(request, response) { // TODO - move rest.* to request object
  var client = request.redis();
  if (request.query.userid) {                                         // userid
    return client.multi()
        .get("userid:" + request.query.userid + ":profile")
        .smembers("userid:" + request.query.userid + ":followers")
        .smembers("userid:" + request.query.userid + ":following")
        .exec(function(err, reply) {
          var profile = JSON.parse(reply[0]);
          if (!profile) return response.fin(404, "Not found");
          read_profiles(reply[1], function(error, profiles) {
            if (error) return response.fin(500, error);
            profile.followers = profiles.map(function(profile) { return JSON.parse(profile) });
            read_profiles(reply[2], function(error, profiles) {
              if (error) return response.fin(500, error);
              profile.following = profiles.map(function(profile) { return JSON.parse(profile) });
              return response.fin(200, profile);
            });
          });
        });
    function read_profiles(userids, continuation) {
      var multi = client.multi();
      for (var i in userids) {
        multi.get("userid:" + userids[i] + ":profile");
      }
      multi.exec(continuation);
    }
  }
  return client.zrange("usernames:userid", 0, -1, function(error, userids) {// everyone
    if (error) return response.fin(500, error);
    var multi = client.multi();
    for (var i in userids) {
      multi.get("userid:" + userids[i] + ":profile")
          .smembers("userid:" + userids[i] + ":followers")
          .smembers("userid:" + userids[i] + ":following");
    }
    multi.exec(function(error, reply) {
      if (error) return response.fin(500, error);
      var profiles = [];
      for (var i = 0; i < reply.length;) {
        var profile = JSON.parse(reply[i++]);
        profile.followers = reply[i++];
        profile.following = reply[i++];
        profiles.push(profile);
      }
      return response.fin(200, profiles);
    });
  });
};

// profiles -> PUT /profiles {}
//             Update the profile of the currently logged in user
// ccurl -X PUT -d '{"userid":1,"username":"antoine@7degrees.co.za","longitude":0.0,"latitude":0.0}' "http://127.0.0.1:8000/profiles"
exports.PUT = function(request, response) {
  if (!request.session.data.authorized) return response.fin(401, "not logged in");
  if (!request.data.userid || !request.data.username ||
      request.session.data.userid   != request.data.userid ||
      request.session.data.username != request.data.username) return response.fin(400, "invalid request");
  var client = request.redis();
  client.set("userid:" + request.session.data.userid + ":profile",
             JSON.stringify(request.data), function(error, userid) {
    if (error) return response.fin(500, error);
    return response.fin(200, request.data);
  });
};

// following -> POST /profiles/following { username|userid : <username|userid> }
//              follow username or userid
// following -> DELETE /profiles/following?[username|userid=]
//              unfollow username or userid
// ccurl -X POST -d '{"username":"antoine@7degrees.co.za"}' "http://127.0.0.1:8000/profiles/following"
// ccurl -X DELETE "http://127.0.0.1:8000/profiles/following?username=antoine@7degrees.co.za"
exports.following = {
  POST : function(request, response) {
    if (!request.session.data.authorized) return response.fin(401, "not logged in");
    if (!request.data.username && !request.data.userid) return response.fin(400, "specify username or userid");
    var client = request.redis();
    if (request.data.username) { // if username specified, need to look up uid
      return client.get("username:" + request.data.username + ":userid", function(error, userid) {
        if (error) return response.fin(500, error);
        if (!userid) return response.fin(404, "no username:" + request.data.username);
        follow(userid);
      });
    }
    follow(request.data.userid);
    function follow(userid) {
      client.multi()
          .get ("userid:" + userid + ":username")
          .sadd("userid:" + request.session.data.userid + ":following", userid)
          .sadd("userid:" + userid + ":followers", request.session.data.userid)
          .exec(function(error, reply) {
            if (error) return response.fin(500, error);
            if (!reply[0]) return response.fin(404, "no username found for userid:" + userid);
            request.data.channel = reply[0];
            return pubsub.subscribers.POST(request, response);
          });
    }
  },

  DELETE : function(request, response) {
    if (!request.session.data.authorized)           return response.fin(401, "not logged in");
    if (!request.query.username && !request.query.userid) return response.fin(400, "specify username or userid");
    var client = request.redis();
    if (request.query.username) { // if username specified, need to look up uid
      return client.get("username:" + request.query.username + ":userid", function(error, userid) {
        if (error) return response.fin(500, error);
        unfollow(userid);
      });
    }
    unfollow(request.query.userid);
    function unfollow(userid) {
      client.multi()
          .get ("userid:" + userid + ":channelid")
          .srem("userid:" + request.session.data.userid + ":following", userid)
          .srem("userid:" + userid + ":followers", request.session.data.userid)
          .exec(function(error, reply) {
            if (error) return response.fin(500, error);
            if (!reply[0]) return response.fin(500, "no channelid found for userid:" + userid);
            request.query.channelid = reply[0];
            return pubsub.subscribers.DELETE(request, response);
          });
    }
  }
};


text:
'use strict';

function platformsValid(platforms) {
  var availablePlatforms = ['windows', 'windows10', 'ios', 'android', 'chrome', 'web', 'firefox'];

  for (var i = 0; i < platforms.length; i++) {
    if (availablePlatforms.indexOf(platforms[i].toLowerCase()) < 0) {
      return false;
    }
  }

  return true;
}

function platformToRunValid(platform) {
  var platfrormsToRun = ['windows', 'android'];

  if (!platform || platfrormsToRun.indexOf(platform.toLowerCase()) < 0) {
    return false;
  }

  return true;
}

function logLevelValid(level) {
  var availableLevels = ['debug', 'info', 'warn', 'error'];
  return availableLevels.indexOf(level.toLowerCase()) >= 0;
}

module.exports = {
  platformsValid: platformsValid,
  platformToRunValid: platformToRunValid,
  logLevelValid: logLevelValid
};


text: selenium nodes with installed flash in docker container


text:
<!DOCTYPE html>

    <title>HBStepperTableCell Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

Cephei 1.17 Docs

View on GitHub

Install in Dash

          <form role="search" action="../search.json">
            <input type="text" placeholder="Search documentation" data-typeahead>
          </form>

        Cephei Reference

        HBStepperTableCell Class Reference

            Cephei — General

                defaults

                HBOutputForShellCommand

                HBOutputForShellCommandWithReturnCode

                HBPreferences

                HBRespringController

                NSDictionary(HBAdditions)

                NSString(HBAdditions)

            CepheiUI — General

                NSLayoutConstraint(CompactConstraint)

                UIColor(HBAdditions)

                UIView(CompactConstraint)

            Cephei — Types and Constants

                HBPreferencesDidChangeNotification

                HBPreferencesNotMobileException

                HBPreferencesChangeCallback

                HBPreferencesValueChangeCallback

            CepheiPrefs — General

                CepheiPrefs Annoying Warning

                HBAppearanceSettings

                HBAppearanceSettingsLargeTitleStyle

                HBSupportController

            CepheiPrefs — List Controllers

                HBAboutListController

                HBListController

                HBRootListController

                PSListController(HBTintAdditions)

            CepheiPrefs — Cells

                HBDiscreteSliderTableCell

                HBImageTableCell

                HBLinkTableCell

                HBPackageTableCell

                HBPackageNameHeaderCell

                HBSpinnerTableCell

                HBStepperTableCell

                HBTintedTableCell

                HBTwitterCell

            CepheiPrefs — Deprecated

                HBListItemsController

                HBInitialsLinkTableCell

HBStepperTableCell

Objective-C

@interface HBStepperTableCell : PSControlTableCell

Swift

class HBStepperTableCell : PSControlTableCell

The HBStepperTableCell class in CepheiPrefs allows setting a value using a stepper control
(“minus” and “plus” buttons).

Requires iOS 6.0 or later.

Specifier Parameters

label	 Required. The label displayed when the value is plural. Use %i
to denote where the number should be displayed.

max	 Required. The highest possible numeric value for the stepper.

min	 Required. The lowest possible numeric value for the stepper.

singularLabel	 Required. The label displayed when the value is singular.

Example Usage

<dict>
    <key>cellClass</key>
    <string>HBStepperTableCell</string>
    <key>default</key>
    <real>5</real>
    <key>defaults</key>
    <string>ws.hbang.common.demo</string>
    <key>key</key>
    <string>Stepper</string>
    <key>label</key>
    <string>%i Things</string>
    <key>max</key>
    <real>15</real>
    <key>min</key>
    <real>1</real>
    <key>singularLabel</key>
    <string>1 Thing</string>
</dict>

                    control

The stepper control.

Declaration

Objective-C

@property (nonatomic, retain) UIStepper *control;

Swift

var control: UIStepper! { get set }

© 2021 HASHBANG Productions. All rights reserved. (Last updated: 2021-09-29)

Generated by jazzy ♪♫ v0.13.6, a Realm project.


text:
package a

var global, global2 *int

type T struct {
	Pointer *int
}

func dontinline() {}

func Store(t *T) {
	global = t.Pointer
	dontinline()
}

func Store2(t *T) {
	global2 = t.Pointer
	dontinline()
}

func Get() *int {
	return global
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<title>Regression Tester - Help</title>

	<link rel="icon" type="image/x-icon" href="logo.ico" />

Regression Tester Help

Command Line Arguments

/multipleinstances - Allows multiple instances of the Regression Tester to run.

/targetdb=mydatabase - Allows you to override the stored database name in the preferences.

/rundb - Runs all tests in the working copy against the target db.

/scenariogroupguid=someguid = Tells the Regression Tester to jump to the given scenario group's guid.

/? - Displays help about the command line arguments.

Exposed RT Variables

			p_ScenarioGUID$

				Holds the guid of the current scenario being run. Available only in the Scenario Startup, Post-Param Assignment, Pre-UDC's, UDC's, and Scenario Teardown hooks.

			v_arrDefaulted (boolean array)

				Array of booleans, whose index is the case-sensitive parameter name that you want to know whether or not was passed in this scenario. Available in the Post-Param Assignment, Pre-UDC's, UDC's, and Scenario Teardown hooks.

			:<library_item_name>

				Library items are used to store large amounts of text outside of your UDCs and are usually used to store expected result text. These
				library items are then compared against actual result text. You can create a library item and then reference it by its name as a bind variable with your hooks.

				For example, to make sure a function getReport() returns your exact report text, you can create a library item named
				Expected_Report_Text that holds the expected report text, and then test the function's return value against the
				bind variable ":Expected_Report_Text" using a comparison type of exp (expression).

Order of Execution

Test DECLARE section

Scenario Group DECLARE section

Scenario Group Startup Hook

		Savepoint PostScenarioGroupStartup

		For every scenario:

Scenario Startup Hook

Parameter values assigned to variables

Post-Param Assignment Hook

Unit Called

Pre-UDCs Hook

UDCs Called

Scenario Teardown Hook

ROLLBACK to PostScenarioGroupStartup (Optional)

Scenario Group Teardown Hook

ROLLBACK

How To...

Compare Two Sys Ref Cursors Manually

		Using a PL/SQL Block UDC, you can call compareCursors$ yourself:

PROCEDURE compareCursors$(p_ExpectedResults IN OUT NOCOPY SYS_REFCURSOR, p_ActualResults IN OUT NOCOPY SYS_REFCURSOR, p_CSVExcludedColumns VARCHAR2 := NULL);

		Strongly-typed parameter cursors can also be tested using the comparison type of "nested".

To compare the results of a SELECT vs. another SELECT, see the Cursor vs. Cursor UDC.

Test a Pipelined Result Function

Right-click on the pipelined result function to test in the schema tree, and choose New -> Test. Your new test and a default scenario group will be added.

If the regression tester can't determine the function's return type, it'll prompt you to type in the function's return value type in the test's Parameters field as "schema.package.type".

Check the "Pipelined Function" checkbox, which is also on the Test Info tab, to let the tester know the function is pipelined.

When putting in the scenarios on the Scenarios tab, if you expect a scenario to raise an exception, set the return value type to "don't test".

		You have a few options for checking the results:

"some rows" - require the pipelined result set to not be empty.

"no rows" - require the pipelined result set be empty.

"matrix" - allows you to specify the expected data back in tabular form, by choosing the matrix option, saving the test, and then double clicking in the return value cell to edit the matrix.

"nested" - a pipelined result set returns an array (TABLE) of PL/SQL RECORDs

"select" - if you're working with a small returned result set, you might build an expected result set that consists of SELECT's FROM DUAL, like below, and put that in the return value column:

SELECT 1 AS customerID, 'Jane' AS firstname, 'Doe' AS lastname FROM dual
UNION ALL
SELECT 2 AS customerID, 'John' AS firstname, 'Doe' AS lastname FROM dual;

				If you're working with large expected result set, then you might create a table that has your expected results in it:

SELECT *
  FROM test1234_expected_result_set
 ORDER BY customer_id;

			Hint: Remember that you might create such an expected result set table in the first place by doing a CTAS (CREATE TABLE .. AS SELECT), like the following:

CREATE TABLE test1234_expected_result_set AS
  SELECT *
    FROM TABLE(joeprogrammer.mypkg.myFunction);

			You can use the "don't test" option to not test the results at all, and optionally test it yourself with a User-Defined Check (UDC).

Save when you're done by hitting Ctrl+S or by hitting the Save button in the menu bar.

Test a Function Returning a User-Defined Type (UDT)

		Choose a comparison type of "nested", and you can double-click in the cell to set your expected values for the out side of IN/OUT parameters,
		OUT parameters, and RETURN parameters. For more robust testing, you can use a PL/SQL Block UDC.

Testing TABLE Types

		You can test TABLE parameters with the "nested" comparison type, then setting your expected values by clicking in the parameter cell.
		Note that PL/SQL TABLEs (INDEX BY VARCHAR2, etc.) are not yet supported.

Test a Function

Right-click on the function to test in the schema tree, and choose New -> Test. Your new test and a default scenario group will be added.

You'll be on the Scenarios tab, and you can begin adding various scenarios of input parameters and their expected return values/exceptions.

Save when you're done by hitting Ctrl+S or by hitting the Save button in the toolbar.

Test an IN/OUT or OUT Parameter

Right-click on the function to test in the schema tree and choose New -> Test. Your new test and a default scenario group will be added.

You'll be on the Scenarios tab, and you can begin adding various scenarios of input parameters and their expected return values/exceptions.

For IN/OUT parameters there are two value columns, one for the value to pass in, and one for the value expected back.

For OUT parameters, your expected OUT value goes in the parameter field.

Save when you're done by hitting Ctrl+S or by hitting the Save button in the toolbar.

User-Defined Checks (UDCs)

Cursor vs. Matrix

		This UDC allows you to compare an OUT, RETURN, or pipelined result set cursor against
		a hard-coded table (matrix). To compare against an unknown set or a larger set, use a
		Cursor vs. Cursor UDC.

Cursor vs. Cursor

		This UDC allows you to compare the results of one SELECT statement against the results
		of another SELECT statement. This is usually used when comparing a large data set of
		actual results against a large set of expected results stored in a test table. It can
		also be used when the expected results are not known till run time.

		Make sure both SELECT statements have their columns and rows in the same order.


text:
<?php

namespace Liuggio\Concurrent\Consumer;

use Liuggio\Concurrent\Event\EventsName;
use Liuggio\Concurrent\Event\ProcessStartedEvent;
use Liuggio\Concurrent\Event\ChannelIsWaitingEvent;
use Liuggio\Concurrent\Process\ProcessFactoryInterface;
use Liuggio\Concurrent\Queue\QueueInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class ConsumerListener
{
    /** @var int */
    private $processCounter;
    /** @var QueueInterface */
    private $queue;
    /** @var EventDispatcherInterface */
    private $eventDispatcher;
    /** @var ProcessFactoryInterface */
    private $processFactory;
    /** @var string */
    private $cwd;
    /** @var string */
    private $template;

    public function __construct(
        QueueInterface $queue,
        EventDispatcherInterface $eventDispatcher,
        ProcessFactoryInterface $processFactory,
        $template = null,
        $cwd = null)
    {
        $this->processCounter = 0;
        $this->queue = $queue;
        $this->eventDispatcher = $eventDispatcher;
        $this->processFactory = $processFactory;
        $this->cwd = $cwd;
        $this->template = $template;
    }

    public function onChannelIsWaiting(ChannelIsWaitingEvent $event)
    {
        $channel = $event->getChannel();
        $event->stopPropagation();

        $value = null;
        $isEmpty = true;
        while ($isEmpty) {
            try {
                $value = $this->queue->dequeue();
                $isEmpty = false;
            } catch (\RuntimeException $e) {
                $isEmpty = true;
            }
            if ($isEmpty && $this->queue->isFrozen()) {
                return;
            }
            if ($isEmpty) {
                usleep(200);
            }
        }
        ++$this->processCounter;

        $process = $this->processFactory->create(
            $channel,
            $value,
            $this->processCounter,
            $this->template,
            $this->cwd
        );
        $process->start();

        $this->eventDispatcher->dispatch(EventsName::PROCESS_STARTED, new ProcessStartedEvent($process));
    }
}


text:
- Bug causing primary typeface in body font stack to be dropped in both builds.

## v0.2.5
- Compiled Calcite variables files into a single _variables.scss file.
- Added Calcite-Web loading animation
- added opensans font files
- added build process for *-open.css files
- renamed `calcite-custom.scss` to `components.scss` because that's what it is.

## v0.2.4
- updated the very old grunt-sass which was using a very old node-sass which could not handle @at-root and thus passed it thru into the css... breaking the glyphicons.

## v0.2.3
- bumped version to address bizzaro caching @ github or proxies or whatever.

## v0.2.2
### Changed
- added build-*.scss files that include bootstrap
- removed the bootstrap include from the .scss files that ship in dist.
- made `bootstrap-sass@3.3.5` a dependancy of this project so it will be auto-installed
- added missing bootstrap vars into calcite files
- distibutions will have the combined & minified bootstrap javascript
- added docs describing this
- added a better example page and the example page markup to the static section so people can copy-paste and be working with calcite-bootstrap.
- added missing /dist/sass/calcite folder to the build process

## v0.2.1
### Changed
- swapped acetate for assemble
- converted minimal docs to acetate
- added deploy.js which builds the json files needed for the Patterns site

## v0.2.0

### Changed
- project structure so we have `./bin`, `./docs` and `./lib`. Source js and sass live in lib, the docs are in doc and bin has a script for releasing.

### Added
- `grunt build:sass` to build the css and package the sass files in `./dist` in prep of a release


text:
package weixin.popular.bean.menu.selfmenu;

import java.util.List;

public class Button {

    private String name;

    private String type;    //click|view|news_info|img|text|voice|video
    private String key;
    private String url;
    private String value;
    private NewsInfo news_info;

    private List<Button> list;

    private Button sub_button;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public List<Button> getList() {
        return list;
    }

    public void setList(List<Button> list) {
        this.list = list;
    }

    public Button getSub_button() {
        return sub_button;
    }

    public void setSub_button(Button sub_button) {
        this.sub_button = sub_button;
    }

    public NewsInfo getNews_info() {
        return news_info;
    }

    public void setNews_info(NewsInfo news_info) {
        this.news_info = news_info;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/errldisplay/errldisplay.H $                   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2013,2015                        */
/* [+] Google Inc.                                                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef ERRLDISPLAY_H
#define ERRLDISPLAY_H
/**
 *  @file src/include/usr/errldisplay/errldisplay.H
 *
 *  @brief  Error Log display for Host Boot environment
 *
 */

/*****************************************************************************/
// I n c l u d e s
/*****************************************************************************/
#include <config.h>
#include <errl/errlentry.H>

namespace ERRORLOGDISPLAY
{

/*****************************************************************************/
// Forward class declarations
/*****************************************************************************/

class ErrLogDisplay;

/**
 *  @brief Returns a reference to the error log display singleton
 *
 *  @return Reference to the error log display
 */
ErrLogDisplay& errLogDisplay();

/**
 *  @brief  Error log display module
 *  This class provides a log dump function for host boot.
 */
class ErrLogDisplay
{

public:

    /**
     * @struct errLogInfo
     *
     * Structure that holds human-readable strings describing errors
     */
    struct errLogInfo
    {
        uint8_t moduleId;
        uint16_t reasonCode;
        const char * descriptString;
        const char * moduleName;
        const char * reasonString;
        const char * userData1String;
        const char * userData2String;
    };

    /**
     * @struct compTableInfo
     *
     * Structure that holds human readable strings for component IDs.
     */
    struct compTableInfo
    {
        const compId_t value;
        const char * name;
    };

    // Sort function to compare errLogInfo structs
    static bool errorLogInfoCompare(const errLogInfo e1, const errLogInfo e2)
    {
        if (e1.moduleId == e2.moduleId)
        {
            return (e1.reasonCode < e2.reasonCode);
        }
        return (e1.moduleId < e2.moduleId);
    }

    // Sort function to compare compTableInfo structs
    static bool compTableCompare(const compTableInfo c1, const compTableInfo c2)
    {
        return (c1.value < c2.value);
    }

    /**
     *  @brief Display a human-readable error log entry.
     *
     *  @param[in] i_err                Error log handle to be displayed
     *  @param[in] i_committerComp      The id of the component that is
     *                                  committing this error log entry
     *
     *  @return None
     */
    static void msgDisplay (const errlHndl_t &i_err, compId_t i_committerComp);

    /**
     *  @brief Initialization for the error log display function.
     *  This registers with the core error logging to provide human-readable
     *  output for errors.
     */
    errlHndl_t init();

private:

    // Auto-generated data tables that hold error information.
    static errLogInfo errorInfo [];
    static uint16_t errorInfoTableSize;
    static compTableInfo compTable [];
    static uint16_t compTableSize;

    /**
     * @brief Find the error log info struture that corresponds to the given
     * module ID & reason code.
     *
     * @param[in] moduleId    The id of the module which errored.
     * @param[in] reasonCode  The reason of the error.
     *
     * @return the error log info structure that matches the module/reason code.
     * or NULL, if there is no structure found.
     */
    static const errLogInfo* findErrLogInfo (uint8_t i_moduleId,
                                             uint16_t i_reasonCode);

    /**
     * @brief Find the component name that corresponds to the given ID.
     *
     * @param[in] compId     The id of the component to be identified.
     *
     * @return a string with the name of the component, or "unknown" if the
     * module name is not found.
     */
    static const char * findComponentName (compId_t i_compId);

    /**
     * @brief Displays a "callout" type error log component
     */
    static void displayCallout (void *data, size_t size);

    /**
     * @brief Displays a "target" type error log component
     */
    static void displayTarget (void *data, size_t size);
};

} // End namespace

#endif //ERRLDISPLAY_H


text:
package client

import (
	"context"
	"github.com/cloudfoundry-community/go-cfclient/v3/resource"
	"github.com/cloudfoundry-community/go-cfclient/v3/testutil"
	"net/http"
	"testing"
)

func TestEnvVarGroups(t *testing.T) {
	g := testutil.NewObjectJSONGenerator(852)
	envVarGroup := g.EnvVarGroup().JSON

	tests := []RouteTest{
		{
			Description: "Get running env var group",
			Route: testutil.MockRoute{
				Method:   "GET",
				Endpoint: "/v3/environment_variable_groups/running",
				Output:   g.Single(envVarGroup),
				Status:   http.StatusOK},
			Expected: envVarGroup,
			Action: func(c *Client, t *testing.T) (any, error) {
				return c.EnvVarGroups.GetRunning(context.Background())
			},
		},
		{
			Description: "Update buildpack",
			Route: testutil.MockRoute{
				Method:   "PATCH",
				Endpoint: "/v3/environment_variable_groups/staging",
				Output:   g.Single(envVarGroup),
				Status:   http.StatusOK,
				PostForm: `{ "var": { "DEBUG": "false" }}`,
			},
			Expected: envVarGroup,
			Action: func(c *Client, t *testing.T) (any, error) {
				r := &resource.EnvVarGroupUpdate{
					Var: map[string]string{
						"DEBUG": "false",
					},
				}
				return c.EnvVarGroups.UpdateStaging(context.Background(), r)
			},
		},
	}
	ExecuteTests(tests, t)
}