text:
/* @flow */

export type DemoRoutes = Array<DemoRoute>;
export type DemoRoute = Array<Route> | Route;
type Route = {
  description: string,
  redirect?: string,
  slug: string,
  title: string
};

const demoRoutes: DemoRoutes = [
  {
    description:
      'Avatar provides a graphic representation of an identity. It can display an image, text, or an icon.',
    slug: 'avatar',
    title: 'Avatar'
  },
  {
    description:
      'Buttons trigger actions or state changes in your app. Choose a button color to match the intent of the action.',
    slug: 'button',
    title: 'Button'
  },
  {
    description:
      'ButtonGroup stylistically groups related buttons and provides the capability to select buttons like radios or checkboxes.',
    slug: 'button-group',
    title: 'ButtonGroup'
  },
  [
    {
      description:
        'Cards group related elements and actions. Use a Card to display content that doesn't fit neatly into a table row or grid cell.',
      slug: 'card',
      title: 'Card'
    },
    {
      description:
        'CardActions lays out actions like Buttons or Links in the body of the Card.',
      slug: 'card-actions',
      title: 'CardActions'
    },
    {
      description:
        'CardBlock lays out content that's not a title or an image in the body of the Card.',
      slug: 'card-block',
      title: 'CardBlock'
    },
    {
      description:
        'CardDivider visually seperates sections of content in Card.',
      slug: 'card-divider',
      title: 'CardDivider'
    },
    {
      description: 'CardFooter provides a stateful extension to Card.',
      slug: 'card-footer',
      title: 'CardFooter'
    },
    {
      description:
        'CardImages reinforce the intent of the Card. Images shouldn't be used alone in a Card, but should be paired with a call to action and/or a CardTitle.',
      slug: 'card-image',
      title: 'CardImage'
    },
    {
      description:
        "CardStatus provides a standard way of displaying a Card's current status.",
      slug: 'card-status',
      title: 'CardStatus'
    },
    {
      description:
        'CardTitles provide a consistently styled heading for your Card. Use a subtitle to provide supporting information for the data displayed in the Card.',
      slug: 'card-title',
      title: 'CardTitle'
    }
  ],
  [
    {
      description:
        'Checkboxes allows users to select one or more options from a list. Use Checkboxes to accept multiple choice input from a user.',
      slug: 'checkbox',
      title: 'Checkbox'
    },
    {
      description:
        'CheckboxGroup allows users to construct a group of Checkboxes and provides a simpler API than working with Checkbox directly',
      slug: 'checkbox-group',
      title: 'CheckboxGroup'
    }
  ],
  [
    {
      description:
        'Dialog displays content in a layer above the app and requires user interaction to dismiss it. It may appear contextually or as a modal.',
      slug: 'dialog',
      title: 'Dialog'
    },
    {
      description:
        'DialogActions renders primary and secondary actions inside Dialog.',
      slug: 'dialog-actions',
      title: 'DialogActions'
    },
    {
      description: 'DialogBody contains the main content of Dialog.',
      slug: 'dialog-body',
      title: 'DialogBody'
    },
    {
      description:
        'DialogFooter displays actionable content at the bottom of Dialog.',
      slug: 'dialog-footer',
      title: 'DialogFooter'
    },
    {
      description:
        'DialogHeader displays title content and an optional close button at the top of Dialog.',
      slug: 'dialog-header',
      title: 'DialogHeader'
    },
    {
      description: 'DialogTitle displays the title of Dialog.',
      slug: 'dialog-title',
      title: 'DialogTitle'
    }
  ],
  {
    description:
      'Dropdowns display a hidden Menu, available upon user interaction. Use Dropdowns for non-primary actions only.',
    slug: 'dropdown',
    title: 'Dropdown'
  },
  [
    {
      description:
        'FormFields wrap an input with a label and other features.  Wrap each input in your app with a FormField for appropriate accessibilty and styling.',
      slug: 'form-field',
      title: 'FormField'
    },
    {
      description:
        'FormFieldsets wrap related FormFields and provide a legend.  Wrap related FormFields in a FormFieldset with a useful legend to help communicate relationships.',
      slug: 'form-fieldset',
      title: 'FormFieldset'
    },
    {
      description:
        'FormFieldDividers separate FormFields.  FormFieldDividers are best used to call attention to a subtle difference between fields.',
      slug: 'form-field-divider',
      title: 'FormFieldDivider'
    }
  ],
  {
    description:
      'Icons symbolize actions and objects in your interface. Use icons in combination with labels to help users more quickly process your UI.',
    slug: 'icon',
    title: 'Icon'
  },
  [
    {
      description: 'Redirect layout to box',
      redirect: 'box',
      slug: 'layout',
      title: 'Layout'
    },
    {
      description:
        'Box component provides an easy way to apply standardized size & space to your layout.',
      slug: 'box',
      title: 'Box'
    },
    {
      description:
        'Flex component is used together with FlexItem to lay out other components in a flexible, and optionally responsive, manner.',
      slug: 'flex',
      title: 'Flex'
    },
    {
      description:
        'FlexItem is used within Flex to lay out other components in your app.',
      slug: 'flex-item',
      title: 'FlexItem'
    },
    {
      description:
        'Grid component is used together with GridItem to lay out other components in a columnar, and optionally responsive, manner.',
      slug: 'grid',
      title: 'Grid'
    },
    {
      description:
        'GridItem is used within Grid to lay out other components in your app.',
      slug: 'grid-item',
      title: 'GridItem'
    },
    {
      description:
        'StartEnd provides a simple way to align components to the start or end of a container.',
      slug: 'start-end',
      title: 'StartEnd'
    }
  ],
  {
    description:
      'Links change the users' browser location, and clearly express the intended destination.',
    slug: 'link',
    title: 'Link'
  },
  [
    {
      description:
        'Menus group related actions or links for your user. Use Menus to toggle features or to group navigation options.',
      slug: 'menu',
      title: 'Menu'
    },
    {
      description:
        'MenuDividers visually separate MenuGroups or individual MenuItems to increase usability in your Menu.',
      slug: 'menu-divider',
      title: 'MenuDivider'
    },
    {
      description: 'MenuGroups classify similar actions and provide labels.',
      slug: 'menu-group',
      title: 'MenuGroup'
    },
    {
      description:
        'MenuItems represent an option in a Menu. Use MenuItems to trigger actions or navigate to a new location.',
      slug: 'menu-item',
      title: 'MenuItem'
    }
  ],
  [
    {
      description: 'Redirect navigation to primary-nav',
      redirect: 'primary-nav',
      slug: 'navigation',
      title: 'Navigation'
    },
    {
      description:
        'NavItem, along with either PrimaryNav or SecondaryNav, provides navigation options for an app.',
      slug: 'nav-item',
      title: 'NavItem'
    },
    {
      description:
        'PrimaryNav provides the main, top-level navigation for an app, usually in the page header.',
      slug: 'primary-nav',
      title: 'PrimaryNav'
    },
    {
      description:
        'SecondaryNav serves additional navigation needs for your app.',
      slug: 'secondary-nav',
      title: 'SecondaryNav'
    }
  ],
  {
    description:
      'Pagination offers a means to control the space consumed by a collection of items by limiting the page size and providing navigation for access to all pages.',
    slug: 'pagination',
    title: 'Pagination'
  },
  {
    description:
      'Popovers display supporting content when your user interacts with an associated trigger. Use Popovers to implement other custom behaviors or widgets.',
    slug: 'popover',
    title: 'Popover'
  },
  [
    {
      description:
        'Radios allows users to select a single option from a list. Use Radios to accept limited choice input from a user.',
      slug: 'radio',
      title: 'Radio'
    },
    {
      description:
        'RadioGroup allows users to construct a group of Radios and provides a simpler API than working with Radio directly',
      slug: 'radio-group',
      title: 'RadioGroup'
    }
  ],
  {
    description: 'Select is a form control that provides a list of options.',
    slug: 'select',
    title: 'Select'
  },
  {
    description:
      'Table displays structured data with sortable columns and selectable rows.',
    slug: 'table',
    title: 'Table'
  },
  [
    {
      description:
        'Tabs provide easy management for viewing related content in the same layout region.',
      slug: 'tabs',
      title: 'Tabs'
    },
    {
      description:
        'Tab displays the tab title and associated panel content (when selected).',
      slug: 'tab',
      title: 'Tab'
    }
  ],
  {
    description:
      'The Text component provides styles and semantic meaning for text and headings in a manner consistent with other components.',
    slug: 'text',
    title: 'Text'
  },
  {
    description:
      'TextAreas accept data from the user.  Use a TextArea to accept potentially lengthy, free-form input from a user',
    slug: 'text-area',
    title: 'TextArea'
  },
  {
    description:
      'TextInputs accept data from the user.  Use a TextInput to accept brief, free-form input from a user',
    slug: 'text-input',
    title: 'TextInput'
  },
  {
    description:
      'ThemeProvider applies styles to a section of your app. Nesting enables multiple themes.',
    slug: 'theme-provider',
    title: 'ThemeProvider'
  },
  {
    description:
      'Tooltips display supporting content when your user interacts with an associated trigger. Use Tooltips to implement other custom behaviors or widgets.',
    slug: 'tooltip',
    title: 'Tooltip'
  }
];

export default demoRoutes;


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Sep.Git.Tfs.Util;
using Sep.Git.Tfs.Core;
using Xunit;

namespace Sep.Git.Tfs.Test.Util
{
    public class AuthorsFileUnitTest
    {
        [Fact]
        public void AuthorsFileEmptyFile()
        {
            MemoryStream ms = new MemoryStream();
            StreamReader sr = new StreamReader(ms);
            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(sr);
            Assert.NotNull(authFile.Authors);
            Assert.Equal<int>(0, authFile.Authors.Count);
        }

        [Fact]
        public void AuthorsFileSimpleRecord()
        {
            string author = @"Domain\Test.User = Test User <TestUser@example.com>";
            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(author))));
            Assert.NotNull(authFile.Authors);
            Assert.Equal<int>(1, authFile.Authors.Count);
            Assert.True(authFile.Authors.ContainsKey(@"Domain\Test.User"));
            Author auth = authFile.Authors[@"Domain\Test.User"];
            Assert.Equal<string>("Test User", auth.Name);
            Assert.Equal<string>("TestUser@example.com", auth.Email);
        }

        [Fact]
        public void AuthorsFileCaseInsensitiveRecord()
        {
            string author = @"DOMAIN\Test.User = Test User <TestUser@example.com>";
            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(author))));
            Assert.NotNull(authFile.Authors);
            Assert.Equal<int>(1, authFile.Authors.Count);
            Assert.True(authFile.Authors.ContainsKey(@"domain\Test.User"));
            Author auth = authFile.Authors[@"domain\Test.User"];
            Assert.Equal<string>("Test User", auth.Name);
            Assert.Equal<string>("TestUser@example.com", auth.Email);
        }

        [Fact]
        public void AuthorsFileMultiLineRecord()
        {
            string author =
@"Domain\Test.User = Test User <TestUser@example.com>
Domain\Different.User = Three Name User < TestUser@example.com >";
            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(author))));
            Assert.NotNull(authFile.Authors);
            Assert.Equal<int>(2, authFile.Authors.Count);

            Assert.True(authFile.Authors.ContainsKey(@"Domain\Test.User"));
            Author auth = authFile.Authors[@"Domain\Test.User"];
            Assert.Equal<string>("Test User", auth.Name);
            Assert.Equal<string>("TestUser@example.com", auth.Email);

            Assert.True(authFile.Authors.ContainsKey(@"Domain\Different.User"));
            auth = authFile.Authors[@"Domain\Different.User"];
            Assert.Equal<string>("Three Name User", auth.Name);
            Assert.Equal<string>(" TestUser@example.com ", auth.Email);
        }

        [Fact]
        public void AuthorsFileMultiLineRecordWithBlankLine()
        {
            string author =
@"Domain\Test.User = Test User <TestUser@example.com>

Domain\Different.User = Three Name User < TestUser@example.com >";
            AuthorsFile authFile = new AuthorsFile();
            Assert.Throws<GitTfsException>(() => authFile.Parse(new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(author)))));
        }

        [Fact]
        public void AuthorsFileTestBadRecord()
        {
            string author =
@"Domain\Test.User = Test User";
            AuthorsFile authFile = new AuthorsFile();
            Assert.Throws<GitTfsException>(() => authFile.Parse(new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(author)))));
        }

        [Fact]
        public void AuthorsFileCommentCharacterStartOfLine()
        {
            string author =
@"Domain\Test.User = Test User <TestUser@example.com>
#Domain\Different.User = Three Name User < TestUser@example.com >";
            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(author))));
            Assert.NotNull(authFile.Authors);
            Assert.Equal<int>(1, authFile.Authors.Count);

            Assert.True(authFile.Authors.ContainsKey(@"Domain\Test.User"));
            Assert.False(authFile.Authors.ContainsKey(@"Domain\Different.User"));
        }

        [Fact]
        public void AuthorsFileCommentCharacterMiddleOfLine()
        {
            string author =
@"Domain\Test.User = Test User <TestUser@example.com>
D#omain\Different.User = Three Name User < TestUser@example.com >";
            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(author))));
            Assert.NotNull(authFile.Authors);
            Assert.Equal<int>(2, authFile.Authors.Count);

            Assert.True(authFile.Authors.ContainsKey(@"Domain\Test.User"));
            Assert.True(authFile.Authors.ContainsKey(@"D#omain\Different.User"));
        }

        [Fact]
        public void AuthorsFileInternationalCharacters()
        {
            string author = @"DOMAIN\Blåbærsyltetøy = ÆØÅ User <ÆØÅ@example.com>";
            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(author))));
            Assert.NotNull(authFile.Authors);
            Assert.Equal<int>(1, authFile.Authors.Count);
            Assert.True(authFile.Authors.ContainsKey(@"domain\Blåbærsyltetøy"));
            Author auth = authFile.Authors[@"domain\Blåbærsyltetøy"];
            Assert.Equal<string>("ÆØÅ User", auth.Name);
            Assert.Equal<string>("ÆØÅ@example.com", auth.Email);
        }

        [Fact]
        public void AuthorsFileInternationalCharactersMultiLine()
        {
            string author = @"DOMAIN\Blåbærsyltetøy = ÆØÅ User <ÆØÅ@example.com>
differentDomain\Blåbærsyltetøy = ÆØÅ User <ÆØÅ@example.com>";
            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(author))));
            Assert.NotNull(authFile.Authors);
            Assert.Equal<int>(2, authFile.Authors.Count);
            Assert.True(authFile.Authors.ContainsKey(@"domain\Blåbærsyltetøy"));
            Author auth = authFile.Authors[@"domain\Blåbærsyltetøy"];
            Assert.Equal<string>("ÆØÅ User", auth.Name);
            Assert.Equal<string>("ÆØÅ@example.com", auth.Email);

            Assert.True(authFile.Authors.ContainsKey(@"differentDomain\Blåbærsyltetøy"));
            auth = authFile.Authors[@"differentDomain\Blåbærsyltetøy"];
            Assert.Equal<string>("ÆØÅ User", auth.Name);
            Assert.Equal<string>("ÆØÅ@example.com", auth.Email);
        }

        [Fact]
        public void AuthorsFileInternationalCharactersCommented()
        {
            string author = @"DOMAIN\Blåbærsyltetøy = ÆØÅ User <ÆØÅ@example.com>
#DifferentDomain\Blåbærsyltetøy = ÆØÅ User <ÆØÅ@example.com>";
            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(author))));
            Assert.NotNull(authFile.Authors);
            Assert.Equal<int>(1, authFile.Authors.Count);
            Assert.True(authFile.Authors.ContainsKey(@"domain\Blåbærsyltetøy"));
        }

        private string _MergeAuthorsIntoString(string[] authors)
        {
            string result = @"";

            for (int i = 0; i < authors.Length; ++i)
            {
                if (i != 0)
                    result += Environment.NewLine;

                result += authors[i];
            }
            return result;
        }

        private AuthorsFile _SetupAuthorsFile(string[] authors)
        {
            string author = _MergeAuthorsIntoString(authors);

            AuthorsFile authFile = new AuthorsFile();
            authFile.Parse(new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(author))));
            return authFile;
        }

        [Fact]
        public void AuthorsFileMultipleUsers()
        {
            string[] authors = {
                @"Domain\Test.User = Test User <TestUser@example.com>",
                @"Domain\Different.User = Three Name User < DiffUser@example.com >",
                @"Domain\Yet.Another.User = Mr. 3 <yau@example.com>"
            };

            AuthorsFile authFile = _SetupAuthorsFile(authors);

            Assert.Equal<int>(authors.Length, authFile.Authors.Count);
            Assert.Equal<int>(authors.Length, authFile.AuthorsByGitUserId.Count);

            // contains all tfs users
            Assert.True(authFile.Authors.ContainsKey(@"Domain\Test.User"));
            Assert.True(authFile.Authors.ContainsKey(@"Domain\Different.User"));
            Assert.True(authFile.Authors.ContainsKey(@"Domain\Yet.Another.User"));

            // contains all git users
            Assert.True(authFile.AuthorsByGitUserId.ContainsKey(Author.BuildGitUserId("TestUser@example.com")));
            Assert.True(authFile.AuthorsByGitUserId.ContainsKey(Author.BuildGitUserId("DiffUser@example.com")));
            Assert.True(authFile.AuthorsByGitUserId.ContainsKey(Author.BuildGitUserId("YAU@example.com")));
        }

        [Fact]
        public void AuthorsFileDifferentIdsForUsersWithSameEmail()
        {
            string[] authors = {
                @"Domain\Test.User = Test User <TestUser@example.com>",
                @"Domain\Different.User = Three Name User < TestUser@example.com >",
                @"Domain\Yet.Another.User = Mr. 3 <testuser@example.com>"
            };

            AuthorsFile authFile = _SetupAuthorsFile(authors);

            Assert.NotNull(authFile.AuthorsByGitUserId);

            // multiple users with the same email -> 3 tfs users, 1 git user
            Assert.Equal<int>(authors.Length, authFile.Authors.Count);
            Assert.Equal<int>(1, authFile.AuthorsByGitUserId.Count);

            // contains all tfs users
            Assert.True(authFile.Authors.ContainsKey(@"Domain\Test.User"));
            Assert.True(authFile.Authors.ContainsKey(@"Domain\Different.User"));
            Assert.True(authFile.Authors.ContainsKey(@"Domain\Yet.Another.User"));

            // contains all git users
            Assert.True(authFile.AuthorsByGitUserId.ContainsKey(Author.BuildGitUserId("TestUser@example.com")));

            // return the first tfs user id in the authors file when multiple
            // match to the same git id.
            Tuple<string, string> git_author = new Tuple<string, string>("Test User", "TestUser@example.com");
            Author a = authFile.FindAuthor(git_author);
            Assert.NotNull(a);
            Assert.Equal(a.TfsUserId, @"Domain\Test.User");

        }

        [Fact]
        public void AuthorsFileFindAuthors()
        {
            string[] authors = {
                @"Domain\Test.User = Test User <TestUser@example.com>",
                @"Domain\Different.User = Three Name User < TestUser@example.com >",
                @"Domain\Yet.Another.User = Mr. 3 <testuser@example.com>"
            };

            AuthorsFile authFile = _SetupAuthorsFile(authors);

            // find existing author
            Tuple<string, string> gitAuthor = new Tuple<string, string>("Test User", "TestUser@example.com");
            Author existingAuthor = authFile.FindAuthor(gitAuthor);
            Assert.NotNull(existingAuthor);

            // try to find unknown author
            Tuple<string, string> gitUnknownAuthor = new Tuple<string, string>("Test User", "TestFailUser@example.com");
            Author unknownAuthor = authFile.FindAuthor(gitUnknownAuthor);
            Assert.Null(unknownAuthor);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!--
@SCRIPT:
  button.accessibilityAttributeValue(AXSelected)
  div.accessibilityAttributeNames.has(AXSelectedChildren)
  div.accessibilityAttributeValue(AXSelectedChildren)
-->
<!--
  This is a regression test for bug: 1276763
  before the fix (3359801), when focus is on the button, the result was:
  div.accessibilityAttributeValue(AXSelectedChildren)=[:3]
-->
<!DOCTYPE html>
<div id="div">
  <button autofocus id="button"></button>
</div>


text:
(function() {

    'use strict';

    angular.module('menu.service').factory(
            'leftMenuService',
            ['$http', '$q', '$rootScope',
            function($http, $q, $rootScope) {

        function LeftMenuService() {
            var self = this;
        }

        LeftMenuService.prototype.upload = function(form) {
            var defer = $q.defer();
            var formData = new FormData();
            formData.append('file', form.file);
            $http.post($rootScope.hostname + '/module/upload/file', formData, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            })
            .success(function(data) {
                defer.resolve(data);
            })
            .error(function(data) {
                defer.reject(data);
            });
            return defer.promise;
        };

        LeftMenuService.prototype.uploadAndIndexing = function(form) {
            var defer = $q.defer();
            var formData = new FormData();
            formData.append('file', form.file);
            formData.append('tags', form.tags);
            $http.post($rootScope.hostname + '/module/upload-and-index/file', formData, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            })
            .success(function(data) {
                defer.resolve(data);
            })
            .error(function(data) {
                defer.reject(data);
            });
            return defer.promise;
        };

        return new LeftMenuService();

    }]);

})();


text:
angular.module('app').service('Tools', function(moment, Profile) {
	this.eachLift = function(iterFn) {
		angular.forEach(Profile.lifts, iterFn);
	};
});


text:
package com.ctrip.hermes.kafka;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.message.MessageAndMetadata;
import kafka.serializer.StringDecoder;

import org.I0Itec.zkclient.ZkClient;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.Assert;
import org.junit.Test;

import com.ctrip.hermes.kafka.admin.ZKStringSerializer;

public class NativeKafkaWithStringDecoderTest {

	@Test
	public void testNative() throws IOException, InterruptedException, ExecutionException {
		String topic = "kafka.SimpleTextTopic";
		ZkClient zkClient = new ZkClient("10.3.6.90:2181,10.3.8.62:2181,10.3.8.63:2181");
		zkClient.setZkSerializer(new ZKStringSerializer());
		int msgNum = 100000;
		final CountDownLatch countDown = new CountDownLatch(msgNum);

		Properties producerProps = new Properties();
		// Producer
		producerProps.put("metadata.broker.list", "10.3.6.237:9092,10.3.6.239:9092,10.3.6.24:9092");
		producerProps.put("bootstrap.servers", "10.3.6.90:2181,10.3.8.62:2181,10.3.8.63:2181");
		producerProps.put("value.serializer", StringSerializer.class.getCanonicalName());
		producerProps.put("key.serializer", StringSerializer.class.getCanonicalName());
		// Consumer
		Properties consumerProps = new Properties();
		consumerProps.put("zookeeper.connect", "10.3.6.90:2181,10.3.8.62:2181,10.3.8.63:2181");
		consumerProps.put("group.id", "GROUP_" + topic);

		final List<String> actualResult = new ArrayList<String>();
		final List<String> expectedResult = new ArrayList<String>();

		ConsumerConnector consumerConnector = Consumer.createJavaConsumerConnector(new ConsumerConfig(consumerProps));
		Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
		topicCountMap.put(topic, 1);
		final List<KafkaStream<String, String>> streams = consumerConnector.createMessageStreams(topicCountMap,
		      new StringDecoder(null), new StringDecoder(null)).get(topic);
		for (final KafkaStream<String, String> stream : streams) {
			new Thread() {
				public void run() {
					for (MessageAndMetadata<String, String> msgAndMetadata : stream) {
						try {
							System.out.println("received: " + msgAndMetadata.message());
							actualResult.add(msgAndMetadata.message());
							countDown.countDown();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}.start();
		}

		KafkaProducer<String, String> producer = new KafkaProducer<String, String>(producerProps);
		int i = 0;
		while (i < msgNum) {
			ProducerRecord<String, String> data = new ProducerRecord<String, String>(topic, "test-message" + i++);
			Future<RecordMetadata> send = producer.send(data);
			send.get();
			if (send.isDone()) {
				System.out.println("sending: " + data.value());
				expectedResult.add(data.value());
			}
		}

		countDown.await();

		Assert.assertArrayEquals(expectedResult.toArray(), actualResult.toArray());

		consumerConnector.shutdown();
		producer.close();
	}
}


text:
<!doctype html>
<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->
<!--[if lt IE 7]>
<html class="no-js lt-ie9 lt-ie8 lt-ie7 ui-mobile-rendering" lang="en"> <![endif]-->
<!--[if IE 7]>
<html class="no-js lt-ie9 lt-ie8 ui-mobile-rendering" lang="en"> <![endif]-->
<!--[if IE 8]>
<html class="no-js lt-ie9 ui-mobile-rendering" lang="en"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js ui-mobile-rendering" lang="en"> <!--<![endif]-->
<head>
    <meta charset="utf-8">
    <title>Santropol Bike DB</title>
    <meta name="description" content="Lightweight Marionette and Require.js Boilerplate Project">

    <!-- Mobile viewport optimized: h5bp.com/viewport -->
    <meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width">

    <!--Change to app.min.css for production -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap3.min.css"/>
    <!-- xeditable -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap-editable.css"/>
    <!-- Jquery UI -->
    <link rel="stylesheet" type="text/css" href="css/jquery-ui.css"/>

    <!--Change to Init.min.js below for production-->

    <script type="text/javascript" src="js/libs/require.js" data-main="js/app/config/Init"></script>
    <!--<script type="text/javascript" src="js/build/main.min.js"></script>-->

</head>
<body>
    <div class="container-fluid" id="index-container">
    </div>
</body>
</html>


text:
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "progress.h"

#define PROGRESS_WINDOW 10

typedef struct
{
    time_t when;
    int completed;

} TIMESTAMP;

struct _PROGRESS
{
    int total;
    int stampcount;
    TIMESTAMP stamps[PROGRESS_WINDOW];
};

#define LAST_STAMP(p) ((p)->stamps[(p)->stampcount - 1])
#define FIRST_STAMP(p) ((p)->stamps[0])

PROGRESS*
progress_start(int total)
{
    PROGRESS* p = malloc(sizeof(PROGRESS));
    p->total = total;
    p->stampcount = 0;
    progress_update(p, 0);
    return p;
}

static double
progress_estimate(PROGRESS* progress)
{
    int count;
    int left;
    double elapsed;
    double rate;

    if (progress->stampcount < 2) {
	return 0.0;
    }

    count = LAST_STAMP(progress).completed - FIRST_STAMP(progress).completed;
    left = progress->total - LAST_STAMP(progress).completed;
    elapsed = (double)(LAST_STAMP(progress).when - FIRST_STAMP(progress).when);
    if (elapsed <= 0.1) {
	elapsed = 0.1;
    }
    rate = count / elapsed;
    return left / rate;
}

double
progress_update(PROGRESS* progress, int completed)
{
    time_t now;

    time(&now);

    /* only return progress every 10 seconds */
    if (progress->stampcount > 0
	&& difftime(now, LAST_STAMP(progress).when) < 10.0) {
	return 0.0;
    }

    if (progress->stampcount == PROGRESS_WINDOW)
    {
	memmove(progress->stamps, progress->stamps + 1,
		sizeof(progress->stamps[0]) * (PROGRESS_WINDOW - 1));
	--progress->stampcount;
    }
    ++progress->stampcount;
    LAST_STAMP(progress).completed = completed;
    LAST_STAMP(progress).when = now;

    return progress_estimate(progress);
}


text:
package foodtruck.server.resources.json;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

import com.google.common.html.HtmlEscapers;
import com.google.common.io.ByteStreams;
import com.google.inject.Inject;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;

import foodtruck.dao.TruckDAO;
import foodtruck.geolocation.GeoLocator;
import foodtruck.geolocation.GeolocationGranularity;
import foodtruck.model.Location;
import foodtruck.model.StopOrigin;
import foodtruck.model.Truck;
import foodtruck.model.TruckStop;
import foodtruck.server.resources.BadRequestException;
import foodtruck.time.HtmlDateFormatter;

/**
 * @author aviolette@gmail.com
 * @since 10/11/12
 */
@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class TruckStopReader implements MessageBodyReader<TruckStop> {
  private final TruckDAO truckDAO;
  private final DateTimeFormatter format;
  private final GeoLocator geolocator;
  private final LocationReader locationReader;

  @Inject
  public TruckStopReader(TruckDAO trucks, GeoLocator geolocator, LocationReader locationReader,
      @HtmlDateFormatter DateTimeFormatter formatter) {
    this.truckDAO = trucks;
    this.format = formatter;
    this.geolocator = geolocator;
    this.locationReader = locationReader;
  }

  @Override
  public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    return type.equals(TruckStop.class);
  }

  @Override
  public TruckStop readFrom(Class<TruckStop> type, Type genericType, Annotation[] annotations, MediaType mediaType,
      MultivaluedMap<String, String> httpHeaders,
      InputStream entityStream) throws IOException, WebApplicationException {
    final String json = new String(ByteStreams.toByteArray(entityStream));
    try {
      JSONObject obj = new JSONObject(json);
      Truck truck = truckDAO.findByIdOpt(obj.getString("truckId"))
          .orElseThrow(() -> new BadRequestException("No truck specified"));
      DateTime startTime, endTime;
      try {
        startTime = format.parseDateTime(obj.getString("startTime").toUpperCase());
      } catch (IllegalArgumentException iae) {
        throw new BadRequestException("Start time incorrect or unspecified");
      }
      try {
        endTime = format.parseDateTime(obj.getString("endTime").toUpperCase());
      } catch (IllegalArgumentException iae) {
        throw new BadRequestException("Could not parse end time");
      }
      if (startTime.isAfter(endTime)) {
        throw new BadRequestException("End time is before start time");
      }
      final JSONObject loc = obj.optJSONObject("location");
      final String origin = obj.optString("origin", StopOrigin.MANUAL.toString());
      Location location;
      if (loc == null) {
        location = geolocator.locate(obj.getString("locationName"), GeolocationGranularity.NARROW);
      } else {
        location = locationReader.toLocation(loc);
      }
      if (location == null) {
        throw new BadRequestException("Location couldn't be resolved");
      }
      if (!location.isResolved()) {
        throw new BadRequestException("Location is not resolved", String.valueOf(location.getKey()));
      }
      long key = obj.optLong("id", 0);
      boolean locked = obj.optBoolean("locked", false);
      return TruckStop.builder()
          .origin(StopOrigin.valueOf(origin))
          .truck(truck)
          .description(HtmlEscapers.htmlEscaper()
              .escape(obj.optString("description")))
          .startTime(startTime)
          .imageUrl(HtmlEscapers.htmlEscaper()
              .escape(obj.optString("imageUrl")))
          .endTime(endTime)
          .location(location)
          .key((key > 0) ? key : null)
          .locked(locked)
          .build();
    } catch (JSONException e) {
      throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
    }
  }
}


text:
package main

import (
	"testing"
)

func TestShouldDirect(t *testing.T) {
	directList := newDirectList()

	directList.Domain["com.cn"] = domainTypeDirect
	directList.Domain["edu.cn"] = domainTypeDirect
	directList.Domain["baidu.com"] = domainTypeDirect

	g, _ := ParseRequestURI("gtemp.com")
	if directList.shouldDirect(g) {
		t.Error("never visited site should be considered using proxy")
	}

	directDomains := []string{
		"baidu.com",
		"www.baidu.com",
		"www.ahut.edu.cn",
	}
	for _, domain := range directDomains {
		url, _ := ParseRequestURI(domain)
		if !directList.shouldDirect(url) {
			t.Errorf("domain %s in direct list should be considered using direct, host: %s", domain, url.Host)
		}
	}

}


text:
/**
 * Created by hanwencheng on 1/22/16.
 */

import DB from '../lib/db-interface.js';

export default function check(req) {

  /**
   * req.body
   * {
   *  email: email
   *  username : name,
   *  password: password
   *  passwordRepeat : passwordRepeat
   * }
   */
  return new Promise((resolve, reject)=>{
     return resolve("i am fine")
  });
}


text:
/*
    SDL_android_main.c, placed in the public domain by Sam Lantinga  3/13/14
*/
#include "SDL_internal.h"

#ifdef __ANDROID__

/* Include the SDL main definition header */
#include "SDL_main.h"

/*******************************************************************************
                 Functions called by JNI
*******************************************************************************/
#include <jni.h>

/* Called before SDL_main() to initialize JNI bindings in SDL library */
extern void SDL_Android_Init(JNIEnv* env, jclass cls);

/* Start up the SDL app */
JNIEXPORT int JNICALL Java_org_libsdl_app_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobject array)
{
    int i;
    int argc;
    int status;

    /* This interface could expand with ABI negotiation, callbacks, etc. */
    SDL_Android_Init(env, cls);

    SDL_SetMainReady();

    /* Prepare the arguments. */

    int len = (*env)->GetArrayLength(env, array);
    char* argv[1 + len + 1];
    argc = 0;
    /* Use the name "app_process" so PHYSFS_platformCalcBaseDir() works.
       https://bitbucket.org/MartinFelis/love-android-sdl2/issue/23/release-build-crash-on-start
     */
    argv[argc++] = SDL_strdup("app_process");
    for (i = 0; i < len; ++i) {
        const char* utf;
        char* arg = NULL;
        jstring string = (*env)->GetObjectArrayElement(env, array, i);
        if (string) {
            utf = (*env)->GetStringUTFChars(env, string, 0);
            if (utf) {
                arg = SDL_strdup(utf);
                (*env)->ReleaseStringUTFChars(env, string, utf);
            }
            (*env)->DeleteLocalRef(env, string);
        }
        if (!arg) {
            arg = SDL_strdup("");
        }
        argv[argc++] = arg;
    }
    argv[argc] = NULL;

    /* Run the application. */

    status = SDL_main(argc, argv);

    /* Release the arguments. */

    for (i = 0; i < argc; ++i) {
        SDL_free(argv[i]);
    }

    /* Do not issue an exit or the whole application will terminate instead of just the SDL thread */
    /* exit(status); */

    return status;
}

#endif /* __ANDROID__ */

/* vi: set ts=4 sw=4 expandtab: */


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace PEReader
{
    internal static class ExtensionMethods
    {
        /// <summary>
        /// Reads a marshal-able type fro ma stream.
        /// </summary>
        /// <typeparam name="T">
        ///   The type to read. Must be capable of being read using
        ///   <see cref="Marshal.PtrToStructure(IntPtr, Type)"/>.
        /// </typeparam>
        /// <param name="stream">[this] The stream to read from.</param>
        /// <returns>The value read from the stream.</returns>
        public static T Read<T>(this Stream stream)
        {
            int len = Marshal.SizeOf(typeof(T));

            var bytes = new byte[len];
            if (stream.Read(bytes, 0, len) != len)
            {
                throw new IOException("Not enough data in the stream");
            }

            var hBytes = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            try
            {
                return (T)Marshal.PtrToStructure(hBytes.AddrOfPinnedObject(), typeof(T));
            }
            finally
            {
                hBytes.Free();
            }
        }

        /// <summary>
        /// Reads an ASCII-encoded, NUL-terminated string from a stream.
        /// </summary>
        /// <param name="stream">[this] The stream to read from.</param>
        /// <returns>The string read from the stream.</returns>
        public static string ReadAsciiZeroTerminated(this Stream stream)
        {
            var builder = new StringBuilder();

            for (int ch = stream.ReadByte();
                 ch > 0;
                 ch = stream.ReadByte())
            {
                builder.Append((char)(ch & 0xFF));
            }

            return builder.ToString();
        }

        /// <summary>
        /// Reads a UTF8-encoded, NUL-terminated string from a stream.
        /// </summary>
        /// <param name="stream">[this] The stream to read from.</param>
        /// <returns>The string read from the stream.</returns>
        public static string ReadUtf8ZeroTerminated(this Stream stream)
        {
            var bytes = new List<byte>();

            for (int ch = stream.ReadByte();
                 ch > 0;
                 ch = stream.ReadByte())
            {
                bytes.Add((byte)(ch & 0xFF));
            }

            return Encoding.UTF8.GetString(bytes.ToArray());
        }

        /// <summary>
        /// Reads a UTF8-encoded string of known length from a stream.
        /// </summary>
        /// <param name="stream">[this] The stream to read from.</param>
        /// <param name="length">The length of the string.</param>
        /// <returns>The string read from the stream.</returns>
        public static string ReadUtf8(this Stream stream, int length)
        {
            var bytes = new byte[length];

            for (int i = 0; i < length; i++)
            {
                int ch = stream.ReadByte();
                bytes[i] = (byte)(ch & 0xFF);
            }

            return Encoding.UTF8.GetString(bytes).TrimEnd('\0');
        }

        /// <summary>
        /// Aligns a stream to the next multiple of <paramref name="count"/> bytes.
        /// If the stream is already aligned, this does not advance the stream.
        /// </summary>
        /// <param name="stream">[this] The stream to align.</param>
        /// <param name="count">The number of bytes to align to.</param>
        public static void AlignToBytes(this Stream stream, int count)
        {
            while ((stream.Position % count) != 0)
            {
                stream.ReadByte();
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/aaa"
        android:title="aaaaa" />

    <item
        android:id="@+id/bbbb"
        android:title="aaaaa" />

</menu>


text:
#ifndef PHONON_MMF_DEFS_H
#define PHONON_MMF_DEFS_H

#include <QtGlobal>

QT_BEGIN_NAMESPACE

namespace Phonon
{
namespace MMF
{
static const qint32 DefaultTickInterval = 10;
static const qreal  InitialVolume = 0.5;

enum MediaType {
    MediaTypeUnknown,
    MediaTypeAudio,
    MediaTypeVideo
};

enum VideoParameter {
    WindowHandle        = 0x1,
    WindowScreenRect    = 0x2,
    ScaleFactors        = 0x4
};
Q_DECLARE_FLAGS(VideoParameters, VideoParameter)
Q_DECLARE_OPERATORS_FOR_FLAGS(VideoParameters)

}
}

QT_END_NAMESPACE

#endif // PHONON_MMF_DEFS_H


text:
<?php

/**
 * DOM HTML Base font element class
 *
 * @category    	PAHDI
 * @package     	PAHDI-DOM
 * @property		int			$size		Element's font size
 * @property		string		$face		Element's font
 * @property		string		$color		Element's font color
 */
class HTMLBaseFontElement extends HTMLElement
{
	/**
	 * Provides a way to access some properties
	 *
	 * @param	string	$name	Property name
	 * @return	mixed	Property value
	 * @ignore
	 */
	function __get ($name)
	{
		switch ($name) {
			case "face":
				return $this->_getProperty($name);
			break;
			case "color":
				return $this->_getProperty($name, "color");
			break;
			case "size":
				return (int) $this->_getProperty($name, "int", - 1);
			break;
			default:
				return parent::__get($name);
			break;
		}
	}

	/**
	 * Provides a way to set some properties
	 *
	 * @param	string	$name	Property name
	 * @param	mixed	$value	Property value
	 * @return	void
	 * @ignore
	 */
	function __set ($name, $value)
	{
		switch ($name) {
			case "face":
				$this->_setProperty($name, $value);
			break;
			case "color":
				$this->_setProperty($name, $value, "color");
			break;
			case "size":
				$this->_setProperty($name, (int) $value, "int", 0);
			break;
			default:
				parent::__set($name, $value);
			break;
		}
	}
}


text:
package org.apache.spark.sql.execution.command

import org.apache.spark.sql.catalyst.analysis.{AnalysisTest, UnresolvedPartitionSpec, UnresolvedTable}
import org.apache.spark.sql.catalyst.parser.CatalystSqlParser.parsePlan
import org.apache.spark.sql.catalyst.plans.logical.DropPartitions
import org.apache.spark.sql.test.SharedSparkSession

class AlterTableDropPartitionParserSuite extends AnalysisTest with SharedSparkSession {

  test("drop partition") {
    val sql = """
      |ALTER TABLE table_name DROP PARTITION
      |(dt='2008-08-08', country='us'), PARTITION (dt='2009-09-09', country='uk')
      """.stripMargin
    val expected = DropPartitions(
      UnresolvedTable(
        Seq("table_name"),
        "ALTER TABLE ... DROP PARTITION ...",
        Some("Please use ALTER VIEW instead.")),
      Seq(
        UnresolvedPartitionSpec(Map("dt" -> "2008-08-08", "country" -> "us")),
        UnresolvedPartitionSpec(Map("dt" -> "2009-09-09", "country" -> "uk"))),
      ifExists = false,
      purge = false)

    comparePlans(parsePlan(sql), expected)
  }

  test("drop partition if exists") {
    val sql = """
      |ALTER TABLE table_name DROP IF EXISTS
      |PARTITION (dt='2008-08-08', country='us'),
      |PARTITION (dt='2009-09-09', country='uk')
      """.stripMargin
    val expected = DropPartitions(
      UnresolvedTable(
        Seq("table_name"),
        "ALTER TABLE ... DROP PARTITION ...",
        Some("Please use ALTER VIEW instead.")),
      Seq(
        UnresolvedPartitionSpec(Map("dt" -> "2008-08-08", "country" -> "us")),
        UnresolvedPartitionSpec(Map("dt" -> "2009-09-09", "country" -> "uk"))),
      ifExists = true,
      purge = false)
    comparePlans(parsePlan(sql), expected)
  }

  test("drop partition in a table with multi-part identifier") {
    val sql = "ALTER TABLE a.b.c DROP IF EXISTS PARTITION (ds='2017-06-10')"
    val expected = DropPartitions(
      UnresolvedTable(
        Seq("a", "b", "c"),
        "ALTER TABLE ... DROP PARTITION ...",
        Some("Please use ALTER VIEW instead.")),
      Seq(UnresolvedPartitionSpec(Map("ds" -> "2017-06-10"))),
      ifExists = true,
      purge = false)

    comparePlans(parsePlan(sql), expected)
  }

  test("drop partition with PURGE") {
    val sql = "ALTER TABLE table_name DROP PARTITION (p=1) PURGE"
    val expected = DropPartitions(
      UnresolvedTable(
        Seq("table_name"),
        "ALTER TABLE ... DROP PARTITION ...",
        Some("Please use ALTER VIEW instead.")),
      Seq(UnresolvedPartitionSpec(Map("p" -> "1"))),
      ifExists = false,
      purge = true)

    comparePlans(parsePlan(sql), expected)
  }

  test("drop partition from view") {
    val sql = "ALTER VIEW table_name DROP PARTITION (p=1)"
    checkError(
      exception = parseException(parsePlan)(sql),
      errorClass = "_LEGACY_ERROR_TEMP_0035",
      parameters = Map("message" -> "ALTER VIEW ... DROP PARTITION"),
      context = ExpectedContext(
        fragment = sql,
        start = 0,
        stop = 41))
  }
}


text:
import os

from oslo_config import cfg
from oslo_log import log as logging

from osc_lib.i18n import _
from osc_lib import utils

from tripleoclient.exceptions import OvercloudUpdateNotConfirmed

from tripleoclient import command
from tripleoclient import constants
from tripleoclient import utils as oooutils
from tripleoclient.workflows import deployment

CONF = cfg.CONF

class ExternalUpdateRun(command.Command):
    """Run external minor update Ansible playbook

       This will run the external minor update Ansible playbook,
       executing tasks from the undercloud. The update playbooks are
       made available after completion of the 'overcloud update
       prepare' command.

    """

    log = logging.getLogger(__name__ + ".ExternalUpdateRun")

    def get_parser(self, prog_name):
        parser = super(ExternalUpdateRun, self).get_parser(prog_name)
        parser.add_argument('--static-inventory',
                            dest='static_inventory',
                            action="store",
                            default=None,
                            help=_('DEPRECATED: tripleo-ansible-inventory.yaml'
                                   ' in working dir will be used.')
                            )
        parser.add_argument("--ssh-user",
                            dest="ssh_user",
                            action="store",
                            default="tripleo-admin",
                            help=_("DEPRECATED: Only tripleo-admin should be "
                                   "used as ssh user.")
                            )
        parser.add_argument('--tags',
                            dest='tags',
                            action="store",
                            default="",
                            help=_('A string specifying the tag or comma '
                                   'separated list of tags to be passed '
                                   'as --tags to ansible-playbook. ')
                            )
        parser.add_argument('--skip-tags',
                            dest='skip_tags',
                            action="store",
                            default="",
                            help=_('A string specifying the tag or comma '
                                   'separated list of tags to be passed '
                                   'as --skip-tags to ansible-playbook. ')
                            )
        parser.add_argument('--stack', dest='stack',
                            help=_('Name or ID of heat stack '
                                   '(default=Env: OVERCLOUD_STACK_NAME)'),
                            default=utils.env('OVERCLOUD_STACK_NAME',
                                              default='overcloud'))
        parser.add_argument('-e', '--extra-vars', dest='extra_vars',
                            action='append',
                            help=('Set additional variables as key=value or '
                                  'yaml/json'),
                            default=[])
        parser.add_argument('-y', '--yes', default=False,
                            action='store_true',
                            help=_("Use -y or --yes to skip the confirmation "
                                   "required before any upgrade "
                                   "operation. Use this with caution! "),
                            )
        parser.add_argument(
            '--limit',
            action='store',
            default=None,
            help=_("A string that identifies a single node or comma-separated"
                   "list of nodes the config-download Ansible playbook "
                   "execution will be limited to. For example: --limit"
                   " \"compute-0,compute-1,compute-5\".")
        )
        parser.add_argument(
            '--ansible-forks',
            action='store',
            default=None,
            type=int,
            help=_('The number of Ansible forks to use for the'
                   ' config-download ansible-playbook command.')
        )
        parser.add_argument(
            '--refresh',
            action='store_true',
            help=_('DEPRECATED: Refresh the config-download playbooks.'
                   'Use `overcloud update prepare` instead to refresh '
                   'playbooks.')
        )

        return parser

    def take_action(self, parsed_args):
        logging.register_options(CONF)
        logging.setup(CONF, '')
        self.log.debug("take_action(%s)" % parsed_args)
        oooutils.ensure_run_as_normal_user()

        if (not parsed_args.yes
                and not oooutils.prompt_user_for_confirmation(
                    constants.UPDATE_PROMPT, self.log)):
            raise OvercloudUpdateNotConfirmed(constants.UPDATE_NO)

        working_dir = oooutils.get_default_working_dir(parsed_args.stack)
        config_download_dir = os.path.join(working_dir, 'config-download')
        ansible_dir = os.path.join(config_download_dir, parsed_args.stack)
        inventory_path = os.path.join(ansible_dir,
                                      'tripleo-ansible-inventory.yaml')
        key = oooutils.get_key(parsed_args.stack)
        playbooks = [os.path.join(ansible_dir, p)
                     for p in constants.EXTERNAL_UPDATE_PLAYBOOKS]
        oooutils.run_ansible_playbook(
            playbook=playbooks,
            inventory=inventory_path,
            workdir=config_download_dir,
            tags=parsed_args.tags,
            extra_vars=parsed_args.extra_vars,
            skip_tags=parsed_args.skip_tags,
            limit_hosts=oooutils.playbook_limit_parse(
                limit_nodes=parsed_args.limit
            ),
            forks=parsed_args.ansible_forks,
            key=key,
            reproduce_command=True
        )

        deployment.snapshot_dir(ansible_dir)
        self.log.info("Completed Overcloud External Update Run.")


text:
@implementation PKCaseInsensitiveLiteral

- (BOOL)qualifies:(id)obj {
    return NSOrderedSame == [literal.stringValue caseInsensitiveCompare:[obj stringValue]];
//    return [literal isEqualIgnoringCase:obj];
}

@end


text:
import asyncio
import aiohttp
from aiohttp.helpers import BasicAuth
from urllib.parse import urljoin
from settings import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_REGION
import tqdm

class BnetClient:
    def __init__(self):
        self.access_token = None
        self.session = aiohttp.ClientSession()
        self.bliz_url = 'https://{}.battle.net/'.format(OAUTH_REGION)
        self.api_url = 'https://{}.api.blizzard.com/'

    async def __aenter__(self):
        await self.session.__aenter__()
        await self.login()
        return self

    async def __aexit__(self, exc_type, exc_value, tb):
        await self.session.__aexit__(exc_type, exc_value, tb)

    async def get_access_token(self):
        r = await self.session.post(self.bliz_url + 'oauth/token',
                                    auth=BasicAuth(OAUTH_CLIENT_ID,
                                                   OAUTH_CLIENT_SECRET),
                                    data={'grant_type': 'client_credentials'})
        return (await r.json())['access_token']

    async def login(self):
        if self.access_token is None:
            self.access_token = await self.get_access_token()

    async def query(self, path, region='us', **kwargs):
        url = urljoin(self.api_url, path).format(region)
        headers = {
            'Authorization': 'Bearer ' + self.access_token,
            'Battlenet-Namespace': 'static-us',
        }
        for i in range(5):  # retry 5 times if too many requests
            r = await self.session.get(url, headers=headers, **kwargs)
            if r.status == 429:
                await asyncio.sleep(2)
            else:
                break
        else:
            raise RuntimeError("Doing requests too fast")

        res = await r.json(content_type=None)
        if 'status' in res and res['status'] == 'nok':
            raise RuntimeError("Request failed: " + res['reason']
                               + "\nURL: " + url)
        return res

    async def achievement_category(self, cat_id=None):
        category = 'index' if cat_id is None else str(cat_id)
        return (await self.query(
            'data/wow/achievement-category/{}'.format(category),
            params={'locale': 'en_US'},
        ))

    async def achievement(self, ach_id):
        return (await self.query(
            'data/wow/achievement/{}'.format(ach_id),
            params={'locale': 'en_US'},
        ))

    async def achievement_media(self, ach_id):
        return (await self.query(
            'data/wow/media/achievement/{}'.format(ach_id),
            params={'locale': 'en_US'},
        ))

    async def mounts(self):
        return (await self.query('wow/mount/'))

    async def pets(self):
        return (await self.query('wow/pet/'))

    async def realms(self, region):
        params = {'namespace': 'dynamic-' + region,
                  'locale': 'en_US'}
        return (await self.query('data/wow/realm/', region=region,
                                 params=params))

    async def pets_species(self, species_id):
        return (await self.query('wow/pet/species/{}'.format(species_id)))

    async def item(self, item_id):
        return (await self.query(
            'data/wow/item/{}'.format(item_id),
            params={'locale': 'en_US'}
        ))

    async def item_media(self, ach_id):
        return (await self.query(
            'data/wow/media/item/{}'.format(ach_id),
            params={'locale': 'en_US'},
        ))

    async def pet_source(self, species_id):
        species = await self.pets_species(species_id)
        return species['source'].split(':')[0].strip()

def get_master_list(name, *args, **kwargs):
    assert name in ('mounts', 'pets', 'realms')

    async def get():
        async with BnetClient() as client:
            return (await getattr(client, name)(*args, **kwargs))
    return asyncio.run(get())

def media_to_icon(media):
    bnet_icon = media['assets'][0]['value']
    bnet_icon = bnet_icon[:-len('.jpg')]
    bnet_icon = bnet_icon.split('/')[-1]
    return bnet_icon

async def build_achievement_master_list():
    """
    This builds an old API-style achievement master list which can then be
    processed by the achievement fixer.
    """
    res = {}
    semaphore = asyncio.Semaphore(30)  # concurrent reqs

    async def enrich_achievement(ach):
        async with semaphore:
            data = await client.achievement(ach['id'])
            media = await client.achievement_media(ach['id'])
            ach.update(data)
            ach.update(media)

    async def enrich_achievement_list(achs):
        tasks = [enrich_achievement(ach) for ach in achs]
        for f in tqdm.asyncio.tqdm_asyncio.as_completed(
            tasks,
            position=2,
            leave=False
        ):
            await f

    async with BnetClient() as client:
        index = await client.achievement_category()
        res['achievements'] = index['root_categories']
        res['achievements'] = [
            i for i in res['achievements'] if i['name'] != 'Guild'
        ]
        for supercat in tqdm.tqdm(res['achievements'], position=0):
            supercat_data = await client.achievement_category(supercat['id'])
            supercat['display_order'] = supercat_data['display_order']
            if 'achievements' in supercat_data:
                supercat['achievements'] = supercat_data['achievements']
                await enrich_achievement_list(supercat['achievements'])
                supercat['achievements'].sort(
                    key=lambda x: x.get('display_order', 0)
                )
            if 'subcategories' in supercat_data:
                supercat['categories'] = supercat_data['subcategories']
                for cat in tqdm.tqdm(
                    supercat['categories'],
                    position=1,
                    leave=False
                ):
                    cat_data = await client.achievement_category(cat['id'])
                    cat['display_order'] = cat_data['display_order']
                    cat['achievements'] = cat_data['achievements']
                    await enrich_achievement_list(cat['achievements'])
                    cat['achievements'].sort(
                        key=lambda x: x.get('display_order', 0)
                    )
                supercat['categories'].sort(
                    key=lambda x: x.get('display_order', 0)
                )
        res['achievements'].sort(key=lambda x: x.get('display_order', 0))

    return res


text:
<?php

/**
 *
 * @license See LICENSE in source root
 * @version 1.0
 * @since   1.0
 */

namespace Cspray\Labrador\Test\Stub;

use Amp\Promise;
use Amp\Success;
use Cspray\Labrador\Plugin\BootablePlugin;

class BootCalledPlugin implements BootablePlugin {

    private $bootCalled = false;

    public function wasCalled() {
        return $this->bootCalled;
    }

    public function boot() : Promise {
        $this->bootCalled = true;
        return new Success();
    }
}


text:
namespace ash {

SystemTrayItem::SystemTrayItem(SystemTray* system_tray)
    : system_tray_(system_tray),
      restore_focus_(false) {
}

SystemTrayItem::~SystemTrayItem() {
}

views::View* SystemTrayItem::CreateTrayView(user::LoginStatus status) {
  return NULL;
}

views::View* SystemTrayItem::CreateDefaultView(user::LoginStatus status) {
  return NULL;
}

views::View* SystemTrayItem::CreateDetailedView(user::LoginStatus status) {
  return NULL;
}

views::View* SystemTrayItem::CreateNotificationView(user::LoginStatus status) {
  return NULL;
}

void SystemTrayItem::DestroyTrayView() {
}

void SystemTrayItem::DestroyDefaultView() {
}

void SystemTrayItem::DestroyDetailedView() {
}

void SystemTrayItem::DestroyNotificationView() {
}

void SystemTrayItem::TransitionDetailedView() {
  system_tray()->ShowDetailedView(this, 0, true, BUBBLE_USE_EXISTING);
}

void SystemTrayItem::UpdateAfterLoginStatusChange(user::LoginStatus status) {
}

void SystemTrayItem::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) {
}

void SystemTrayItem::PopupDetailedView(int for_seconds, bool activate) {
  // Never show a detailed view during OOBE, e.g. from a notification.
  if (!Shell::GetInstance()->system_tray_delegate()->IsOobeCompleted())
    return;
  system_tray()->ShowDetailedView(
      this, for_seconds, activate, BUBBLE_CREATE_NEW);
}

void SystemTrayItem::SetDetailedViewCloseDelay(int for_seconds) {
  system_tray()->SetDetailedViewCloseDelay(for_seconds);
}

void SystemTrayItem::HideDetailedView() {
  system_tray()->HideDetailedView(this);
}

void SystemTrayItem::ShowNotificationView() {
  system_tray()->ShowNotificationView(this);
}

void SystemTrayItem::HideNotificationView() {
  system_tray()->HideNotificationView(this);
}

bool SystemTrayItem::ShouldHideArrow() const {
  return false;
}

bool SystemTrayItem::ShouldShowShelf() const {
  return true;
}

}  // namespace ash


text:
package com.datasift.connector.writer;

import org.junit.Test;
import static org.junit.Assert.*;

public class TestSleeper {

    @Test
    public void should_sleep() throws InterruptedException {
        long before = System.currentTimeMillis();
        new Sleeper().sleep(1000);
        long after = System.currentTimeMillis();
        long diff = after - before;
        assertTrue(diff >= 1000);
    }
}


text:
var loader = require('./lib/loader');
var path = require('path');

module.exports = function(app, options) {
    //is a winston instance is passed as the second argument it will be used for autoroute logging
    //otherwise it will use a 'clean' winston instance
    if (!options.logger || (!(options.logger.debug && typeof options.logger.debug == 'function'))) {
        options.logger = require('winston');
        options.logger.debug('using custom logger');
    }
    else {
        options.logger.debug('using specified logger')
    }

    if (!options.routesDir) {
        options.routesDir = path.join(process.cwd(), "routes");
    }

    options.logger.debug("Loading routes directory", {
        dir: options.routesDir
    });

    loader.loadDirectory(options.routesDir, "", app, options);
};


text:
package com.jiangren.javaee.repositories;

import com.jiangren.javaee.models.Course;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Created by seabookchen on 2/09/2017.
 */
public class CourseDao {

    @PersistenceContext
    private EntityManager em;

    public void createCourse(Course course) {
        em.persist(course);
    }

    public Course findCourse(Long id) {
        return em.find(Course.class, id);
    }
}


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

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Closes a PostgreSQL connection</title>

pg_client_encoding

pg_connect

PostgreSQL Functions

PHP Manual

pg_close

(PHP 4, PHP 5)

pg_close — Closes a PostgreSQL connection

Description

   bool pg_close
    ([ resource $connection
  ] )

   pg_close() closes the non-persistent
   connection to a PostgreSQL database associated with the given
   connection resource.

Note:

    Using pg_close() is not usually necessary, as
    non-persistent open connections are automatically closed at the end
    of the script.

   If there is open large object resource on the connection, do not
   close the connection before closing all large object resources.

Parameters

connection

       PostgreSQL database connection resource.  When
       connection is not present, the default connection
       is used. The default connection is the last connection made by
       pg_connect() or pg_pconnect().

Return Values

   Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_close() example

<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
   or die("Could not connect");
echo "Connected successfully";
pg_close($dbconn);
?>

The above example will output:

Connected successfully

See Also

pg_connect() - Open a PostgreSQL connection

pg_client_encoding

pg_connect

PostgreSQL Functions

PHP Manual


text:
module Paysto
  require 'csv'
  require 'net/http'

  mattr_accessor  :id,
                  :secret,
                  :description,
                  :urls,
                  :ips,
                  :tax,
                  :min_tax,
                  :expiration,
                  :payment_class_name,
                  :invoice_class_name,
                  :invoice_notification_class_name

  RXP = Regexp.new('[^a-zA-Z0-9$&%;:?!\.,\s}(\[){\]"\'`\\/|^_~*+=<>@-]+')

  class << self

    # Configuring module.
    def setup
      yield self
    end

    # Payment class.
    def payment_class
      @@payment_class_name.constantize
    end

    # Invoice class.
    def invoice_class
      @@invoice_class_name.constantize
    end

    # InvoiceNotification class.
    def invoice_notification_class
      @@invoice_notification_class_name.constantize
    end

    # List of available pay methods according to your tariff plan.
    def currencies
      https_request_to @@urls[:currencies], base_params
    end

    # Your current balance in Paysto.
    def balance
      https_request_to @@urls[:balance], base_params
    end

    # Returns array of payments with details between dates.
    # +from+  –  from date.
    # +to+    –  to date.
    def get_payments(from, to)
      p = { 'PAYSTO_SHOP_ID' => @@id,
            'FROM'           => from.strftime('%Y%m%d%H%M'),
            'TO'             => to.strftime('%Y%m%d%H%M') }
      p.merge!('PAYSTO_MD5'  => generate_md5(p))

      res = https_request_to(@@urls[:payments_list], p)
      CSV.parse(res)
    end

    # Returns payment type or 'common' by default.
    # +invoice_id+  –  invoice ID of payment.
    # +time+        –  estimated payment execution time.
    def get_payment_type(invoice_id, time = Time.zone.now)
      _payments = get_payments(time.utc - 30.minutes, time.utc + 5.minutes)
      if _payments.present?
        p = _payments.select{ |_p| _p[2].eql?(invoice_id.to_s) }.first
        _type = p[7] if p
      end
      _type || 'common'
    end

    # Check whether the invoice is valid.
    def invoice_valid?(invoice)
      invoice && invoice.send("#{@@payment_class_name.underscore}_id").blank? && invoice.paid_at.blank?
    end

    # Check whether the IP is permitted.
    def ip_valid?(ip)
      @@ips.include?(ip)
    end

    # Check whether the MD5 sign is valid.
    def md5_valid?(p)
      hash = p.except('action', 'controller', 'PAYSTO_MD5')
      generate_md5(hash) == p['PAYSTO_MD5']
    end

    # Timestamp string in Paysto format for payments expiration.
    def pay_till
      (Time.zone.now + @@expiration).utc.strftime('%Y%m%d%H%M')
    end

    # Real income value without Paysto tax for any amount which you want to calculate.
    # +str+  –  amount string or numeric, does not matter.
    def real_amount(str)
      amount = str.to_f
      _tax = amount * @@tax
      _tax = @@min_tax if _tax < @@min_tax
      amount - _tax
    end

    private

    # Generating MD5 sign according with received params.
    def generate_md5(p = {}, upcase = true)
      md5 = Digest::MD5.hexdigest(md5_string(p))
      upcase ? md5.upcase : md5
    end

    # Final data string to gererane MD5.
    def md5_string(p = {})
      str = p.to_a.sort_by{ |pair| pair.first.downcase }.map{ |pair| pair.join('=') }.join('&')
      str_with_secret = [str, @@secret].join('&')
      str_with_secret.gsub(RXP, '')
    end

    # Base set of params for requests.
    def base_params
      p = { 'PAYSTO_SHOP_ID' => @@id }
      p.merge!('PAYSTO_MD5'  => generate_md5(p))
    end

    # Performing an HTTPS request.
    def https_request_to(url, params)
      uri = URI.parse(url)
      req = Net::HTTP::Post.new(uri.path)
      req.set_form_data(params)
      session = Net::HTTP.new(uri.hostname, 443)
      session.use_ssl = true
      res = session.start do |http|
        http.request(req)
      end
      res.body.force_encoding('UTF-8')
    end

  end
end


text:
package podtask

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/gogo/protobuf/proto"
	"github.com/pborman/uuid"
	"k8s.io/kubernetes/contrib/mesos/pkg/offers"
	mesosmeta "k8s.io/kubernetes/contrib/mesos/pkg/scheduler/meta"
	"k8s.io/kubernetes/contrib/mesos/pkg/scheduler/metrics"
	"k8s.io/kubernetes/pkg/api"

	log "github.com/golang/glog"
	mesos "github.com/mesos/mesos-go/mesosproto"
	mutil "github.com/mesos/mesos-go/mesosutil"
)

type StateType int

const (
	StatePending StateType = iota
	StateRunning
	StateFinished
	StateUnknown
)

type FlagType string

const (
	Launched = FlagType("launched")
	Bound    = FlagType("bound")
	Deleted  = FlagType("deleted")
)

var starRole = []string{"*"}

// A struct that describes a pod task.
type T struct {
	ID  string
	Pod api.Pod

	// Stores the final procurement result, once set read-only.
	// Meant to be set by algorith.SchedulerAlgorithm only.
	Spec *Spec

	Offer       offers.Perishable // thread-safe
	State       StateType
	Flags       map[FlagType]struct{}
	CreateTime  time.Time
	UpdatedTime time.Time // time of the most recent StatusUpdate we've seen from the mesos master

	podStatus       api.PodStatus
	prototype       *mesos.ExecutorInfo // readonly
	frameworkRoles  []string            // Mesos framework roles, pods are allowed to be launched with those
	defaultPodRoles []string            // roles under which pods are scheduled if none are specified in labels
	podKey          string
	launchTime      time.Time
	bindTime        time.Time
	mapper          HostPortMapper
}

type Port struct {
	Port uint64
	Role string
}

type Spec struct {
	SlaveID       string
	AssignedSlave string
	Resources     []*mesos.Resource
	PortMap       []HostPortMapping
	Data          []byte
	Executor      *mesos.ExecutorInfo
}

// mostly-clone this pod task. the clone will actually share the some fields:
//   - executor    // OK because it's read only
//   - Offer       // OK because it's guarantees safe concurrent access
func (t *T) Clone() *T {
	if t == nil {
		return nil
	}

	// shallow-copy
	clone := *t

	// deep copy
	clone.Flags = map[FlagType]struct{}{}
	for k := range t.Flags {
		clone.Flags[k] = struct{}{}
	}
	return &clone
}

func (t *T) HasAcceptedOffer() bool {
	return t.Spec != nil
}

func (t *T) GetOfferId() string {
	if t.Offer == nil {
		return ""
	}
	return t.Offer.Details().Id.GetValue()
}

func generateTaskName(pod *api.Pod) string {
	ns := pod.Namespace
	if ns == "" {
		ns = api.NamespaceDefault
	}
	return fmt.Sprintf("%s.%s.pod", pod.Name, ns)
}

// GenerateTaskDiscoveryEnabled turns on/off the generation of DiscoveryInfo for TaskInfo records
var GenerateTaskDiscoveryEnabled = false

func generateTaskDiscovery(pod *api.Pod) *mesos.DiscoveryInfo {
	di := &mesos.DiscoveryInfo{
		Visibility: mesos.DiscoveryInfo_CLUSTER.Enum(),
	}
	switch visibility := pod.Annotations[mesosmeta.Namespace+"/discovery-visibility"]; visibility {
	case "framework":
		di.Visibility = mesos.DiscoveryInfo_FRAMEWORK.Enum()
	case "external":
		di.Visibility = mesos.DiscoveryInfo_EXTERNAL.Enum()
	case "", "cluster":
		// noop, pick the default we already set
	default:
		// default to CLUSTER, just warn the user
		log.Warningf("unsupported discovery-visibility annotation: %q", visibility)
	}
	// name should be {{label|annotation}:name}.{pod:namespace}.pod
	nameDecorator := func(n string) *string {
		ns := pod.Namespace
		if ns == "" {
			ns = api.NamespaceDefault
		}
		x := n + "." + ns + "." + "pod"
		return &x
	}
	for _, tt := range []struct {
		fieldName string
		dest      **string
		decorator func(string) *string
	}{
		{"name", &di.Name, nameDecorator},
		{"environment", &di.Environment, nil},
		{"location", &di.Location, nil},
		{"version", &di.Version, nil},
	} {
		d := tt.decorator
		if d == nil {
			d = func(s string) *string { return &s }
		}
		if v, ok := pod.Labels[tt.fieldName]; ok && v != "" {
			*tt.dest = d(v)
		}
		if v, ok := pod.Annotations[mesosmeta.Namespace+"/discovery-"+tt.fieldName]; ok && v != "" {
			*tt.dest = d(v)
		}
	}
	return di
}

func (t *T) BuildTaskInfo() (*mesos.TaskInfo, error) {
	if t.Spec == nil {
		return nil, errors.New("no podtask.T.Spec given, cannot build task info")
	}

	info := &mesos.TaskInfo{
		Name:      proto.String(generateTaskName(&t.Pod)),
		TaskId:    mutil.NewTaskID(t.ID),
		Executor:  t.Spec.Executor,
		Data:      t.Spec.Data,
		Resources: t.Spec.Resources,
		SlaveId:   mutil.NewSlaveID(t.Spec.SlaveID),
	}

	if GenerateTaskDiscoveryEnabled {
		info.Discovery = generateTaskDiscovery(&t.Pod)
	}

	return info, nil
}

// Clear offer-related details from the task, should be called if/when an offer
// has already been assigned to a task but for some reason is no longer valid.
func (t *T) Reset() {
	log.V(3).Infof("Clearing offer(s) from pod %v", t.Pod.Name)
	t.Offer = nil
	t.Spec = nil
}

func (t *T) Set(f FlagType) {
	t.Flags[f] = struct{}{}
	if Launched == f {
		t.launchTime = time.Now()
		queueWaitTime := t.launchTime.Sub(t.CreateTime)
		metrics.QueueWaitTime.Observe(metrics.InMicroseconds(queueWaitTime))
	}
}

func (t *T) Has(f FlagType) (exists bool) {
	_, exists = t.Flags[f]
	return
}

// Roles returns the valid roles under which this pod task can be scheduled.
// If the pod has roles annotations defined they are being used
// else default pod roles are being returned.
func (t *T) Roles() (result []string) {
	if r, ok := t.Pod.ObjectMeta.Annotations[mesosmeta.RolesKey]; ok {
		roles := strings.Split(r, ",")

		for i, r := range roles {
			roles[i] = strings.TrimSpace(r)
		}

		return filterRoles(
			roles,
			not(emptyRole), not(seenRole()), inRoles(t.frameworkRoles...),
		)
	}

	// no roles label defined, return defaults
	return t.defaultPodRoles
}

func New(ctx api.Context, id string, pod *api.Pod, prototype *mesos.ExecutorInfo, frameworkRoles, defaultPodRoles []string) (*T, error) {
	if prototype == nil {
		return nil, fmt.Errorf("illegal argument: executor is nil")
	}

	if len(frameworkRoles) == 0 {
		frameworkRoles = starRole
	}

	if len(defaultPodRoles) == 0 {
		defaultPodRoles = starRole
	}

	key, err := MakePodKey(ctx, pod.Name)
	if err != nil {
		return nil, err
	}

	if id == "" {
		id = "pod." + uuid.NewUUID().String()
	}

	task := &T{
		ID:              id,
		Pod:             *pod,
		State:           StatePending,
		podKey:          key,
		mapper:          NewHostPortMapper(pod),
		Flags:           make(map[FlagType]struct{}),
		prototype:       prototype,
		frameworkRoles:  frameworkRoles,
		defaultPodRoles: defaultPodRoles,
	}
	task.CreateTime = time.Now()

	return task, nil
}

func (t *T) SaveRecoveryInfo(dict map[string]string) {
	dict[mesosmeta.TaskIdKey] = t.ID
	dict[mesosmeta.SlaveIdKey] = t.Spec.SlaveID
	dict[mesosmeta.OfferIdKey] = t.Offer.Details().Id.GetValue()
	dict[mesosmeta.ExecutorIdKey] = t.Spec.Executor.ExecutorId.GetValue()
}

// reconstruct a task from metadata stashed in a pod entry. there are limited pod states that
// support reconstruction. if we expect to be able to reconstruct state but encounter errors
// in the process then those errors are returned. if the pod is in a seemingly valid state but
// otherwise does not support task reconstruction return false. if we're able to reconstruct
// state then return a reconstructed task and true.
//
// at this time task reconstruction is only supported for pods that have been annotated with
// binding metadata, which implies that they've previously been associated with a task and
// that mesos knows about it.
//
// assumes that the pod data comes from the k8s registry and reflects the desired state.
//
func RecoverFrom(pod api.Pod) (*T, bool, error) {
	// we only expect annotations if pod has been bound, which implies that it has already
	// been scheduled and launched
	if pod.Spec.NodeName == "" && len(pod.Annotations) == 0 {
		log.V(1).Infof("skipping recovery for unbound pod %v/%v", pod.Namespace, pod.Name)
		return nil, false, nil
	}

	// only process pods that are not in a terminal state
	switch pod.Status.Phase {
	case api.PodPending, api.PodRunning, api.PodUnknown: // continue
	default:
		log.V(1).Infof("skipping recovery for terminal pod %v/%v", pod.Namespace, pod.Name)
		return nil, false, nil
	}

	ctx := api.WithNamespace(api.NewDefaultContext(), pod.Namespace)
	key, err := MakePodKey(ctx, pod.Name)
	if err != nil {
		return nil, false, err
	}

	//TODO(jdef) recover ports (and other resource requirements?) from the pod spec as well

	now := time.Now()
	t := &T{
		Pod:        pod,
		CreateTime: now,
		podKey:     key,
		State:      StatePending, // possibly running? mesos will tell us during reconciliation
		Flags:      make(map[FlagType]struct{}),
		mapper:     NewHostPortMapper(&pod),
		launchTime: now,
		bindTime:   now,
		Spec:       &Spec{},
	}
	var (
		offerId string
	)
	for _, k := range []string{
		mesosmeta.BindingHostKey,
		mesosmeta.TaskIdKey,
		mesosmeta.SlaveIdKey,
		mesosmeta.OfferIdKey,
	} {
		v, found := pod.Annotations[k]
		if !found {
			return nil, false, fmt.Errorf("incomplete metadata: missing value for pod annotation: %v", k)
		}
		switch k {
		case mesosmeta.BindingHostKey:
			t.Spec.AssignedSlave = v
		case mesosmeta.SlaveIdKey:
			t.Spec.SlaveID = v
		case mesosmeta.OfferIdKey:
			offerId = v
		case mesosmeta.TaskIdKey:
			t.ID = v
		case mesosmeta.ExecutorIdKey:
			// this is nowhere near sufficient to re-launch a task, but we really just
			// want this for tracking
			t.Spec.Executor = &mesos.ExecutorInfo{ExecutorId: mutil.NewExecutorID(v)}
		}
	}
	t.Offer = offers.Expired(offerId, t.Spec.AssignedSlave, 0)
	t.Flags[Launched] = struct{}{}
	t.Flags[Bound] = struct{}{}
	return t, true, nil
}


text:
"""
    Authors: Gabriel Grill, Anton Ovchinnikov
"""

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from cassandra.cluster import Cluster
import logging
import time
import json
import io
import sys
import csv
import os
from datetime import date, datetime
import threading
import re
from time import sleep

log = logging.getLogger()
log.setLevel('INFO')

DEFAULT_TIMEOUT = 300.0

#extracts features from tweet text
def extract_features(t, col_str, val_str):
    tweet_text_lower = tweet['text'].lower()
    tweet_text_clean = ' '.join(tweet_text_lower for e in string if e.isalnum())
    tweet_text_tokens = tweet_text_clean.split()
    category_count = {}

    for token in tweet_text_tokens:
        cat = getCategory(token)
        if cat != "":
            if cat in category_count:
                category_count[cat] += 1
            else:
                category_count[cat] = 0

    for cat, count in category_count.iteritems():
           col_str.append(cat)
           val_str.append(count)

# loads a csv file of form "city,region" into Map and returns it
def load_location_dict(fname):
    #path = os.path.split(os.getcwd())[0]
    #path = os.getcwd()
    #fname = path+"/cassandra_db/"+str(fname)
    print fname
    with open(fname, 'r') as ifile:
        reader = csv.reader(ifile)
        print reader
        next(reader, None) #ignore header
        return {rows[0].lower():rows[1].lower() for rows in reader}

#extracts location from token
def extract_location(loc, locs):
    text = re.sub('[^a-zA-Z0-9-]', ' ', loc.encode("ascii","ignore")).lower()
    loc_tokens = filter(lambda a: a != '', text.strip().split())

    if loc_tokens is not None:
        for token in locs:
            if token in loc_tokens:
                return token
    return ""

#prepares values of type 'text' for the db
def prep(x):
    #return "'" + x + "'"
    text = re.sub('[^a-zA-Z0-9:-]', ' ', re.sub("-+", "-", x.encode("ascii","ignore")))
    return "'" + text + "'"
    #return "'" + x.encode("ascii","ignore").replace("'", "") + "'"

#tweet contains field with content
def has(t, val):
    return val in t and t[val] is not None

#reads tweets from a text file
def open_tweets(fname):
    with open(fname) as f:
        try:
            for line in f.readlines():
                yield json.loads(line.decode('utf8'))
        except Exception as e:
            print("Failed on {0}: {1}".format(fname, e))

#checks if a word is part of the tokenized tweet text
def contains_words(to_check, tweet_tokens):
    for word in tweet_tokens:
        if word in to_check:
            return True
    return False

class SimpleClient:
    #the CQL standard can be found here: https://github.com/pcmanus/cassandra/blob/3779/doc/cql3/CQL.textile
    #the api to this cassandra lib can be found here: http://www.datastax.com/documentation/developer/python-driver/1.0/share/doctips/docTips.html
    session = None

    cols = ["id", "time", "user_id", "region", "city", "content",
            "lat", "long", "rt_count", "fav_count", "lang"]

    tweet_cols = [("id", "id", False), ("content", "text", True),
                  ("rt_count", "retweet_count", False),
                  ("fav_count", "favorite_count", False), ("lang", "lang", True)]
    city_region_dict = load_location_dict('regions.csv')
    regions = set(city_region_dict.values())
    cities = city_region_dict.keys()

    def __init__(self):
        self.createInsLock = threading.RLock()
        self.sendBatchLock= threading.RLock()

    #takes as input a list of insert statements and sends them as a batch
    #very fast, but batch construction and sending should be best done in a
    #seperate thread for max. performance
    def send_batch(self, inserts):
        log.info("invoking batch execution insert")
        self.session.execute("BEGIN BATCH\n" + "\n".join(inserts) + "\nAPPLY BATCH;")
        log.info("batch of tweets loaded into db")

    def create_insert(self, t, t_tokens, food_word_dict, cat_counts=None):
        insert_strs = []
        for food_category in food_word_dict:
            category_words = food_word_dict[food_category]
            for product in category_words:
                if contains_words([product], t_tokens):
                    insert_string = self.create_insert_for_category(t, food_category, cat_counts)
                    insert_strs.append(insert_string)
        return insert_strs

    #returns a string representing an insert for a tweet
    def create_insert_for_category(self, t, food_category, cat_counts=None):
       log.info("creating insert")
       col_str = []
       val_str = []
       city = ""
       region = ""

       for col, val, shouldPrep in self.tweet_cols:
           if has(t,val):
               col_str.append(col)
               if(shouldPrep):
                   val = prep(t[val])
               else:
                   val = str(t[val])
               val_str.append(val.strip())

       if has(t,'user'):
           if has(t['user'], 'id'):
               col_str.append('user_id')
               val_str.append(prep(str(t['user']['id'])))
           if has(t['user'],'location'):
               city = extract_location(t['user']['location'], self.cities)
               if city != "":
                  region = self.city_region_dict[city.lower()]
               else:
                  region = extract_location(t['user']['location'], self.regions)

       if has(t,'place') and has(t['place'],'name'):
           col_str.append("place")
           val_str.append(prep(t['place']['name']))

       if(region != ""):
           col_str.append("region")
           val_str.append(prep(region))
       if(city != ""):
           col_str.append("city")
           val_str.append(prep(city))

       if has(t,'coordinates') and has(t['coordinates'],'coordinates'):
            col_str.append("long")
            val_str.append(str(t['coordinates']['coordinates'][0]))
            col_str.append("lat")
            val_str.append(str(t['coordinates']['coordinates'][1]))
       if has(t,"created_at"):
            col_str.append("time")
            time_obj = datetime.strptime(t['created_at'], '%a %b %d %H:%M:%S +0000 %Y')
            val_str.append(prep(time_obj.strftime('%Y-%m-%d %H:%M:%S')))
            col_str.append('day')
            val_str.append(str(time_obj.day))
            col_str.append('month')
            val_str.append(str(time_obj.month))
            col_str.append('year')
            val_str.append(str(time_obj.year))

       #extract_features(t, col_str, val_str)
       if cat_counts is not None:
        for cat, count in cat_counts.iteritems():
            col_str.append(cat)
            val_str.append(str(count))

       table_name = 'tweets_' + food_category
       return "INSERT INTO " + table_name + "(" + ",".join(col_str) + ") VALUES (" + ",".join(val_str) + ");"

    #inserts a tweet into the db
    def send_tweet(self, t):
        s = self.create_insert(t)
        self.session.execute(s)
        log.info("tweet loaded into db")

    #connect to cluster
    def connect(self, nodes):
        cluster = Cluster(nodes)
        metadata = cluster.metadata
        self.session = cluster.connect()
        self.session.default_timeout = DEFAULT_TIMEOUT
        log.info("Connected to cluster: " + metadata.cluster_name)
        for host in metadata.all_hosts():
            log.info("Datacenter: %s; Host: %s; Rack: %s",
                host.datacenter, host.address, host.rack)

    #close connection to cluster
    def close(self):
        self.session.cluster.shutdown()
        self.session.shutdown()
        log.info("Connection closed.")

    #use keyspace (called before cmds are executed in keyspace)
    def use_keyspace(self, keyspace):
        self.session.execute("use "+str(keyspace)+";")
        log.info("Using keyspace "+str(keyspace))

    #creates db schema in cassandra
    def extended_schema(self, food_categories, pred_categories):
        self.session.execute("""
            CREATE KEYSPACE tweet_collector WITH replication =
            {'class':'SimpleStrategy', 'replication_factor':1};""")
        log.info('Created keyspace tweet_collector')

        sleep(3)
        self.session.execute("use tweet_collector;")

        create_table_strs = []
        for f_category in food_categories:
            table_name = 'tweets_' + f_category
            te = """
                 CREATE TABLE %s (
    	         id bigint,
                 time timestamp,
                 day int,
                 month int,
                 year int,
    	         user_id text,
    	         region text,
    	         city text,
                 content text,
                 lat float,
                 long float,
                 place text,
       	         rt_count int,
                 fav_count int,
                 cnts int,
                 lang text,\n""" %(table_name) + \
                 ',\n'.join(map((lambda coln: str(coln) + " int"), pred_categories)) + ',\n' + \
                 "PRIMARY KEY (id) );"
            print("Map: " + te)
            self.session.execute(te)
            create_table_strs.append(te)
            log.info("> Table " + table_name + " created.")
            sleep(1)
        log.info(">>> Schema created.")

        # Save 'create table' queries
        with open('shark_create_table.sql', 'wb') as f:
            for s in create_table_strs:
                s = re.sub(r'\btext\b', 'string', s)
                s = re.sub(r'CREATE TABLE', 'CREATE EXTERNAL TABLE', s)
                s = re.sub(r',\nPRIMARY KEY.*$', ")\n", s)
                s += "STORED BY 'org.apache.hadoop.hive.cassandra.cql.CqlStorageHandler' WITH SERDEPROPERTIES ('cassandra.host'='100.88.224.12', 'cassandra.port'='9160');"
                f.write(s + "\n")

    #drops schema
    def drop_schema(self, keyspace):
        self.session.execute("DROP KEYSPACE IF EXISTS tweet_collector;")
        print "Schema (keyspace) dropped."

    #create index for rows, which are used for selection
    def create_index(self, food_categories):
        for category in food_categories:
            table_name = 'tweets_' + category
            for column in ['region', 'city', 'time', 'long', 'lat']:
                index_name = table_name + '_' + column
                create_str = """
                    CREATE INDEX %s
                    ON %s (%s);""" % (index_name, table_name, column)
                print create_str
                self.session.execute(create_str)
                sleep(3)
                log.info("> Index %s on table %s created." % (index_name, table_name) )

        log.info(">>> Index created.")

    #prints all saved tweets
    def print_rows(self):
        results = self.session.execute("SELECT * FROM tweets;")
        print("Tweet table:")
        print("---------------------------------------------------------------")
        for row in results:
            print(row)
        log.info("Rows printed.")

def usage():
    print("""python %s <input file | -d> [node]
              -d     drop schema

    Defaults: node = 127.0.0.1
    stores tweets read from input file into a local cassandra db"""
    % sys.argv[0])

def main():
    if len(sys.argv) < 2:
        usage()
        sys.exit(-1)

    node = "127.0.0.1"
    if len(sys.argv) > 2:
        node = sys.argv[2]

    logging.basicConfig()
    client = SimpleClient()
    client.connect([node])

    if sys.argv[1] == "-d":
        client.drop_schema()
        exit(0)

    #client.create_schema([])
    #client.create_index()

    for t in open_tweets(sys.argv[1]):
        client.send_tweet(t)

    client.print_rows()
    client.close()

if __name__ == '__main__':
    main()


text:
<?php
/**
 * CountriesApiTest
 * PHP version 5
 *
 * @category Class
 * @package  Kinow\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * Server API
 *
 * Reference for Server API (REST/Json)
 *
 * OpenAPI spec version: 1.4.39
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Please update the test case below to test the endpoint.
 */

namespace Kinow\Client;

use \Kinow\Client\Configuration;
use \Kinow\Client\ApiClient;
use \Kinow\Client\ApiException;
use \Kinow\Client\ObjectSerializer;

/**
 * CountriesApiTest Class Doc Comment
 *
 * @category Class
 * @package  Kinow\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class CountriesApiTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Setup before running any test cases
     */
    public static function setUpBeforeClass()
    {

    }

    /**
     * Setup before running each test case
     */
    public function setUp()
    {

    }

    /**
     * Clean up after running each test case
     */
    public function tearDown()
    {

    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass()
    {

    }

    /**
     * Test case for getCountries
     *
     * .
     *
     */
    public function testGetCountries()
    {

    }

}


text:
package com.jayway.restassured.module.mockmvc;

import com.jayway.restassured.module.mockmvc.http.HeaderController;
import com.jayway.restassured.response.Header;
import org.apache.commons.lang3.mutable.MutableObject;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;

import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

// @formatter:off
public class ResultHandlerTest {

    @BeforeClass
    public static void configureMockMvcInstance() {
        RestAssuredMockMvc.standaloneSetup(new HeaderController());
    }

    @AfterClass
    public static void restRestAssured() {
        RestAssuredMockMvc.reset();
    }

    @Test public void
    supports_using_result_handlers_using_the_dsl() {
        MutableObject<Boolean> mutableObject = new MutableObject<Boolean>(false);

        given().
                resultHandlers(print(), customResultHandler(mutableObject)).
                header(new Header("headerName", "John Doe")).
        when().
                get("/header").
        then().
                statusCode(200).
                body("headerName", equalTo("John Doe"));

        assertThat(mutableObject.getValue(), is(true));
    }

    @Test public void
    merges_result_handlers_using_the_dsl() {
        MutableObject<Boolean> mutableObject1 = new MutableObject<Boolean>(false);
        MutableObject<Boolean> mutableObject2 = new MutableObject<Boolean>(false);

        given().
                resultHandlers(customResultHandler(mutableObject1)).
                resultHandlers(customResultHandler(mutableObject2)).
                header(new Header("headerName", "John Doe")).
        when().
                get("/header").
        then().
                statusCode(200).
                body("headerName", equalTo("John Doe"));

        assertThat(mutableObject1.getValue(), is(true));
        assertThat(mutableObject2.getValue(), is(true));
    }

    @Test public void
    supports_defining_result_handlers_statically() {
        MutableObject<Boolean> mutableObject1 = new MutableObject<Boolean>(false);
        MutableObject<Boolean> mutableObject2 = new MutableObject<Boolean>(false);
        RestAssuredMockMvc.resultHandlers(customResultHandler(mutableObject1), customResultHandler(mutableObject2));

        given().
                header(new Header("headerName", "John Doe")).
        when().
                get("/header").
        then().
                statusCode(200).
                body("headerName", equalTo("John Doe"));

        assertThat(mutableObject1.getValue(), is(true));
        assertThat(mutableObject2.getValue(), is(true));
    }

    @Test public void
    merges_statically_defined_result_handlers_with_dsl_defined() {
        MutableObject<Boolean> mutableObject1 = new MutableObject<Boolean>(false);
        MutableObject<Boolean> mutableObject2 = new MutableObject<Boolean>(false);
        RestAssuredMockMvc.resultHandlers(customResultHandler(mutableObject1));

        given().
                resultHandlers(customResultHandler(mutableObject2)).
                header(new Header("headerName", "John Doe")).
        when().
                get("/header").
        then().
                statusCode(200).
                body("headerName", equalTo("John Doe"));

        assertThat(mutableObject1.getValue(), is(true));
        assertThat(mutableObject2.getValue(), is(true));
    }

// @formatter:on

    private ResultHandler customResultHandler(final MutableObject<Boolean> mutableObject) {
        return new ResultHandler() {
            public void handle(MvcResult result) throws Exception {
                mutableObject.setValue(true);
            }
        };
    }
}


text:
require 'rubimc'

def main(argv)

	# some console print example
	print_comment "This is clear C code, it can be compiled with 'gcc' utility"
	printf "========Run Program========\n"
	printf "Hello! I`m code generated by RubimC and compiled by gcc\n"
	printf "I have %d arguments: ", argv.count
	argv.count.times do |i|
		printf "%s ", argv[i]
	end
	printf "\n"

	# some arithmetic operation example
	integer :b
	boolean :c
	double :u1
	b = 1;
	c = false
	u1 = b*b + (2*b) + (b + 3)

	# some conditions example
	if b > 0
		if u1 == c
			b = 27 & c
			u1 = 33 if b!= c
		end
	end

	# some loop example
	u1.times do |i|
		next if i==2
		printf("now 'i' value is %d\n", i)
	end

	# connect external library
	ExternLibs.add("test_lib.h")
	printf "External function return: %d\n", ExternLibs.eval("test_lib()")
end


text:
module("contacts test", {
	setup: function(){
		S.open("//contacts.html");
	}
});

test("Filtering", function(){
	S(".contact").visible();
	S(".count").text("1000", function(){
		ok(true, "initially 1000 contacts")
	})
	S(".category:first").visible().click();
	S(".count").text("143", function(){
		ok(true, "143 contacts after filtering")
	})
});

test("Creating a Category", function(){
	S(".category").visible(function(){
		equals(S(".category").size(), 7, "7 categories")
	})
	S("#category .createbutton").exists().click();
	S("#category input").visible().click().type("\b\b\b\bBasketball\r");
	S(".category").size(8, function(){
		ok(true, "there are 8 categories")
	})
});

test("Creating a Contact", function(){
	S(".contact").visible(function(){
		equals(S(".contact").size(), 100, "50 contacts")
	})
	S("#contacts .createbutton").exists().click();
	S("#contacts input:eq(0)").visible().click().type("\b\b\b\b\bBrian");
	S("#contacts input:eq(1)").visible().click().type("\b\b\b\bMoschel\r");
	S(".contact").size(101, function(){
		ok(true, "there are 51 contacts")
	})
});


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

<resources>
    <dimen name="activity_vertical_padding">16dp</dimen>
    <dimen name="activity_horizontal_padding">16dp</dimen>
</resources>