text:
var err = require('../util').err;
var should = require('../../');

module.exports['bool'] = {
  'test true': function(){
    true.should.be.true;
    false.should.not.be.true;
    (1).should.not.be.true;

    err(function(){
      'test'.should.be.true;
    }, "expected 'test' to be true")

    err(function(){
      true.should.not.be.true;
    }, "expected true not to be true")
  },

  'test false': function(){
    false.should.be.false;
    true.should.not.be.false;
    (0).should.not.be.false;

    err(function(){
      ''.should.be.false;
    }, "expected '' to be false")

    err(function(){
      false.should.not.be.false;
    }, "expected false not to be false")
  },

  'test ok': function(){
    true.should.be.ok;
    false.should.not.be.ok;
    (1).should.be.ok;
    (0).should.not.be.ok;

    err(function(){
      ''.should.be.ok;
    }, "expected '' to be truthy");

    err(function(){
      'test'.should.not.be.ok;
    }, "expected 'test' not to be truthy");
  },
}

redpajama_set_name: RedPajamaGithub


text:
import {Injectable, TemplateRef} from '@angular/core';
import {NavigationEnd, NavigationExtras, Router} from '@angular/router';
import {LoggerFactory} from '@elderbyte/ts-logger';
import {filter, map} from 'rxjs/operators';
import {ElderRouterOutletService} from './drawers/elder-router-outlet.service';
import {BehaviorSubject, Observable} from 'rxjs';
import {ShellContentSlot} from './shell-content-slot';
import {TemplateSlotManager} from '../../common/templates/template-slot-manager';

/**
 * This service manages the side content.
 * This is usually the left side which is a 'side nav' and the right side which shows detail information.
 */
@Injectable({
  providedIn: 'root'
})
export class ElderShellService {

  /***************************************************************************
   *                                                                         *
   * Fields                                                                  *
   *                                                                         *
   **************************************************************************/

  private readonly logger = LoggerFactory.getLogger('ElderShellService');

  private _navigationOpen = new BehaviorSubject<boolean>(false);
  private _clickOutsideToClose = true;

  private detailContentOutlet = 'side';

  private readonly slotManager: TemplateSlotManager<ShellContentSlot>;

  /***************************************************************************
   *                                                                         *
   * Constructor                                                             *
   *                                                                         *
   **************************************************************************/

  constructor(
    private router: Router,
    private routerOutletService: ElderRouterOutletService,
  ) {

    this.slotManager = new TemplateSlotManager(
      [
        ShellContentSlot.HEADER,
        ShellContentSlot.CENTER,
        ShellContentSlot.FOOTER
      ]
    );

    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map(event => event as NavigationEnd)
    )
      .subscribe(event => {
        this.closeSideNav();
      });
  }

  /***************************************************************************
   *                                                                         *
   * Properties                                                              *
   *                                                                         *
   **************************************************************************/

  /**
   * Checks if the navigation is isOpen
   */
  public get navigationOpen(): boolean {
    return this._navigationOpen.getValue();
  }

  public set navigationOpen(value: boolean) {
    this._navigationOpen.next(value);
  }

  public get navigationOpenChange(): Observable<boolean> {
    return this._navigationOpen.asObservable();
  }

  /**
   * Allow closing the side content by clicking outside of it.
   */
  public get clickOutsideToClose(): boolean {
    return this._clickOutsideToClose;
  }

  public set clickOutsideToClose(value: boolean) {
    this._clickOutsideToClose = value;
  }

  /***************************************************************************
   *                                                                         *
   * Shell Slot Template API                                                 *
   *                                                                         *
   **************************************************************************/

  /**
   * Returns an observable which emits the current active template for the given position
   * over time.
   */
  public activeSlotTemplate(slot: ShellContentSlot): Observable<TemplateRef<any>> {
    return this.slotManager.activeSlotTemplate(slot);
  }

  /**
   * Registers the given template as toolbar column at the given slot.
   *
   * @param slot at which template should be placed
   * @param template to set at slot
   * @param isDefault if the given template should be used as app default
   */
  public registerColumn(slot: ShellContentSlot, template: TemplateRef<any>, isDefault = false): void {
    this.slotManager.registerSlotTemplate(slot, template, isDefault);
  }

  /**
   * Deregister the given template from the toolbar.
   *
   * @param template to deregister
   * @param slot if set, the template will only be deregistered if it was registered at this slot (optional)
   */
  public deregisterColumn(template: TemplateRef<any>, slot?: ShellContentSlot) {
    this.slotManager.deregisterSlotTemplate(template, slot);
  }

  /***************************************************************************
   *                                                                         *
   * Public API                                                              *
   *                                                                         *
   **************************************************************************/

  /**
   * Toggles the side navigation
   */
  public toggleSidenav(): boolean {
    this.navigationOpen = !this.navigationOpen;
    return this.navigationOpen;
  }

  /**
   * Closes the side navigation
   */
  public closeSideNav(): void {
    this.navigationOpen = false;
  }

  /**
   * Closes the side detail content
   */
  public closeSideContent(): Promise<boolean> {
    return this.routerOutletService.deactivate(this.detailContentOutlet);
  }

  public isSideContentActive(): boolean {
    return this.routerOutletService.isActive(this.detailContentOutlet);
  }

  /**
   * Shows the side content
   * @param args The route arguments / path
   * @param clickOutsideToClose If enabled, the side content can be closed by clicking outside of it.
   * @param extras
   */
  public navigateSideContent(args: string[], clickOutsideToClose: boolean, extras?: NavigationExtras): Promise<boolean> {
    this.clickOutsideToClose = clickOutsideToClose;
    return this.routerOutletService.activate(this.detailContentOutlet, args, extras);
  }

}


text:
import angular from 'angular';
import _ from 'lodash';

angular.module('vorm')
	.factory('vormInvoke', [ '$injector', '$parse', function ( $injector, $parse ) {

		function invoke ( invokable, locals ) {
			let value;

			if(!invokable) {
				return invokable;
			}

			if((_.isArray(invokable) && typeof _.last(invokable) === 'function') || invokable.$inject !== undefined) {
				value = $injector.invoke(invokable, null, locals ? angular.copy(locals) : null);
			} else if(typeof invokable === 'function') {
				value = invokable();
			} else {
				value = invokable;
			}

			return value;
		}

		let invoker = function ( invokable, locals ) {
			return invoke(invokable, locals);
		};

		invoker.expr = function ( invokable, locals, scope ) {
			let value;
			if(typeof invokable === 'string') {
				value = $parse(invokable)(scope, locals);
			} else {
				value = invoke(invokable, locals);
			}
			return value;
		};

		return invoker;

	}]);


text:
GROB = **GR**EP **O**sm proto**B**uff file

Search the waypoints of an Openstreetmap Protobuf file for a string. Additionally the maximum distance to a waypoint can be specified.
Output is of the form: `lat,lon,tags`

# Build

1) Your `GOPATH` variable is assumed to be set to a sensible value.

2) Get the osmpdf library (used for digesting OSM protobuf files)

    $ go get github.com/qedus/osmpbf

3) Clone `grob`

    $ git clone https://github.com/wmo/grob

    $ cd grob

    $ go build grob

4) You are good to go now.

# Usage

Use case: you want to eat a pizza close to Checkpoint Charlie in Berlin.

1) Download the `Berlin.osm.pbf` file from [download.geofabrik.de/europe/germany.html](http://download.geofabrik.de/europe/germany.html) (in case the link is no longer valid, start from here: [wiki.openstreetmap.org/wiki/Planet.osm](http://wiki.openstreetmap.org/wiki/Planet.osm))

2) Locate checkpoint charlie

    grob berlin-latest.osm.pbf "checkpoint charlie"

    ..
    52.507546, 13.390361,  name:Checkpoint Charlie name:ko:체크포인트 찰리 ..
    ..

3) Check within a radius of 0.5 km of waypoint 52.507546 13.390361 for pizza

    grob berlin-latest.osm.pbf -d 0.5 52.507546 13.390361 pizza

    52.505250, 13.393108,  name:Charlotte 1 amenity:restaurant cuisine:italian..
    52.506928, 13.392213,  name:Pizza amenity:fast_food #,0.14
    52.506916, 13.395269,  addr:housenumber:9 name:Pepe Pizza amenity:fast_foo..


text:
package org.mockito.internal.verification;

import org.mockito.internal.verification.api.VerificationData;
import org.mockito.verification.VerificationMode;

public class MockAwareVerificationMode implements VerificationMode {

    private final Object mock;
    private final VerificationMode mode;

    public MockAwareVerificationMode(Object mock, VerificationMode mode) {
        this.mock = mock;
        this.mode = mode;
    }

    public void verify(VerificationData data) {
        mode.verify(data);
    }

    public Object getMock() {
        return mock;
    }
}


text:
/**
 * The WMSLayer layer module.
 *
 * @return WMSLayerLayer class (extends CartoDBLayerClass)
 */
define(
  [
    'abstract/layer/CartoDBLayerClass',
    'text!map/cartocss/honduras_forest.cartocss'
  ],
  function(CartoDBLayerClass, honduras_forestCartoCSS) {
    'use strict';

    var WMSLayerLayer = CartoDBLayerClass.extend({
      options: {
        sql:
          "SELECT *, '{tableName}' AS layer, '{tableName}' AS name FROM {tableName}",
        cartocss: honduras_forestCartoCSS
      }
    });

    return WMSLayerLayer;
  }
);


text:
using namespace Managers;

std::map<std::string, GLuint> Shader_Manager::programs;

Shader_Manager::Shader_Manager()
{

}

Shader_Manager::~Shader_Manager()
{
	//for (std::map<std::string, GLuint>::iterator i = programs.begin(); i != programs.end(); i++)
	//{
	//	GLuint pr = i->second;
	//	glDeleteProgram(pr);
	//}

	//programs.clear();
}

std::string Shader_Manager::ReadShader(const std::string& filename)
{
	std::string shaderCode;
	std::ifstream file(filename, std::ios::in);

	if (!file.good()){
		std::cout << "Can't read file " << filename.c_str() << std::endl;
		std::terminate();
	}

	file.seekg(0, std::ios::end);
	shaderCode.resize((unsigned int)file.tellg());
	file.seekg(0, std::ios::beg);
	file.read(&shaderCode[0], shaderCode.size());
	file.close();

	return shaderCode;
}

GLuint Shader_Manager::CreateShader(GLenum shaderType,
									const std::string& source,
									const std::string& shaderName)
{
	int compile_result = 0;

	GLuint shader = glCreateShader(shaderType);
	const char *shader_code_ptr = source.c_str();
	const int   shader_code_size = source.size();

	glShaderSource(shader, 1, &shader_code_ptr, &shader_code_size);
	glCompileShader(shader);
	glGetShaderiv(shader, GL_COMPILE_STATUS, &compile_result);

	//daca exista erori output la consola
	if (compile_result == GL_FALSE){

		int info_log_length = 0;
		glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_log_length);
		std::vector<char> shader_log(info_log_length);
		glGetShaderInfoLog(shader, info_log_length, NULL, &shader_log[0]);
		std::cout << "ERROR compiling shader: " << shaderName.c_str() << std::endl << &shader_log[0] << std::endl;
	}

	return shader;
}

void Shader_Manager::CreateProgram(const std::string& shaderName,
								   const std::string& vertexShaderFilename,
								   const std::string& fragmentShaderFilename)
{
	//read the shader files and save the code
	std::string vertex_shader_code = ReadShader(vertexShaderFilename);
	std::string fragment_shader_code = ReadShader(fragmentShaderFilename);

	GLuint vertex_shader = CreateShader(GL_VERTEX_SHADER, vertex_shader_code, "vertex shader");
	GLuint fragment_shader = CreateShader(GL_FRAGMENT_SHADER, fragment_shader_code, "fragment shader");

	int  link_result = 0;
	//create the program handle, attatch the shaders and link it
	GLuint program = glCreateProgram();
	glAttachShader(program, vertex_shader);
	glAttachShader(program, fragment_shader);

	glLinkProgram(program);
	glGetProgramiv(program, GL_LINK_STATUS, &link_result);

	if (link_result == GL_FALSE){

		int info_log_length = 0;
		glGetProgramiv(program, GL_INFO_LOG_LENGTH, &info_log_length);
		std::vector<char> program_log(info_log_length);
		glGetProgramInfoLog(program, info_log_length, NULL, &program_log[0]);
		std::cout << "Shader Loader : LINK ERROR" << std::endl << &program_log[0] << std::endl;
		return;
	}
	programs[shaderName] = program;
}

const GLuint Shader_Manager::GetShader(const std::string& shaderName)
{
	return programs.at(shaderName);
}


text:
package com.example.rest;

import com.example.order.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/order")
public class OrderRestController {
    @Autowired
    private OrderService orderService;

    @RequestMapping(value = "/{name}/{price}", method = RequestMethod.POST)
    @ResponseBody
    public String addBookToOrder(@PathVariable("name") String name, @PathVariable("price") String price) {
        return orderService.addBookToOrder(new BookDTO(name, price)).getId();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void removeBookFromOrder(@PathVariable("id") String id) {
        orderService.deleteBookFromOrder(id);
    }

    @RequestMapping(value = "/calculate", method = RequestMethod.GET)
    @ResponseBody
    public String removeBookFromOrder() {
        return orderService.calculatePriceAfterAddingTax().getValue().toString();
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public String previewOrder() {
        return orderService.previewOrder().toString();
    }
}


text:
"""
Created on Feb 28, 2018

@author: Tyranic-Moron
"""

from twisted.plugin import IPlugin
from pymoronbot.moduleinterface import IModule, BotModule
from zope.interface import implementer

@implementer(IPlugin, IModule)
class CommandHandler(BotModule):
    def actions(self):
        return super(CommandHandler, self).actions() + [('message-channel', 1, self.handleCommand),
                                                        ('message-user', 1, self.handleCommand)]

    def handleCommand(self, message):
        if message.Command:
            return self.bot.moduleHandler.runGatheringAction('botmessage', message)

commandhandler = CommandHandler()


text:
package org.bean.jandan.model;

import java.util.ArrayList;

/**
 * Created by liuyulong@yixin.im on 2015/5/6.
 */
public abstract class CommentsResult<E, R extends Comment> extends PageResult<R> {

    private ArrayList<E> comments;

    public ArrayList<E> getComments() {
        return comments;
    }

    public void setComments(ArrayList<E> comments) {
        this.comments = comments;
    }

    @Override
    public String toString() {
        return "CommentsResult{" +
                "comments=" + comments +
                "} " + super.toString();
    }
}


text:
package im.actor.model.api.updates;
/*
 *  Generated by the Actor API Scheme generator.  DO NOT EDIT!
 */

import im.actor.model.droidkit.bser.Bser;
import im.actor.model.droidkit.bser.BserParser;
import im.actor.model.droidkit.bser.BserObject;
import im.actor.model.droidkit.bser.BserValues;
import im.actor.model.droidkit.bser.BserWriter;
import im.actor.model.droidkit.bser.DataInput;
import im.actor.model.droidkit.bser.DataOutput;
import im.actor.model.droidkit.bser.util.SparseArray;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import com.google.j2objc.annotations.ObjectiveCName;
import static im.actor.model.droidkit.bser.Utils.*;
import java.io.IOException;
import im.actor.model.network.parser.*;
import java.util.List;
import java.util.ArrayList;
import im.actor.model.api.*;

public class UpdateGroupOnline extends Update {

    public static final int HEADER = 0x21;
    public static UpdateGroupOnline fromBytes(byte[] data) throws IOException {
        return Bser.parse(new UpdateGroupOnline(), data);
    }

    private int groupId;
    private int count;

    public UpdateGroupOnline(int groupId, int count) {
        this.groupId = groupId;
        this.count = count;
    }

    public UpdateGroupOnline() {

    }

    public int getGroupId() {
        return this.groupId;
    }

    public int getCount() {
        return this.count;
    }

    @Override
    public void parse(BserValues values) throws IOException {
        this.groupId = values.getInt(1);
        this.count = values.getInt(2);
    }

    @Override
    public void serialize(BserWriter writer) throws IOException {
        writer.writeInt(1, this.groupId);
        writer.writeInt(2, this.count);
    }

    @Override
    public String toString() {
        String res = "update GroupOnline{";
        res += "groupId=" + this.groupId;
        res += ", count=" + this.count;
        res += "}";
        return res;
    }

    @Override
    public int getHeaderKey() {
        return HEADER;
    }
}


text:
function TFM = createRotationAboutPoint3d(ROT, point)
%CREATEROTATIONABOUTPOINT3D Rotate about a point using a rotation matrix.
%
%   TFM = createRotationAboutPoint3d(ROT, POINT) Returns the transformation
%   matrix corresponding to a translation(-POINT), rotation with ROT and
%   translation(POINT). Ignores a possible translation in ROT(1:3,4).
%
%   See also:
%   transforms3d, transformPoint3d, createRotationOx, createRotationOy,
%   createRotationOz, createRotation3dLineAngle, createRotationVector3d,
%   createRotationVectorPoint3d
%
% ---------
% Author: oqilipo
% Created: 2021-01-31
% Copyright 2021

% Extract only the rotation
ROT = [ROT(1:3,1:3), [0 0 0]'; [0 0 0 1]];

TFM = createTranslation3d(point) * ROT * createTranslation3d(-point);

end


text:
<!DOCTYPE html>

 <title>First homework</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <link href="css/bootstrap.min.css" rel="stylesheet" media="orange">

My first app

 wont be the last
>

 </video>


text:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 128
#define NONE -1
#define EOS '\0'
#define NUM 257
#define KEYWORD 258
#define ID 259
#define DONE 260
#define MAX 999
char lexemes[MAX];
char buffer[SIZE];
int lastchar=-1;
int lastentry=0;
int tokenval=DONE;
int lineno=1;
int lookahead;
struct entry
{
char *lexptr;
int token;
}
symtable[100];
struct entry
keywords[]={"if",KEYWORD,"else",KEYWORD,"for",KEYWORD,"int",KEYWORD,"float",KEYWORD,"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"return",KEYWORD,0,0};
void Error_Message(char *m)

{
fprintf(stderr,"line %d, %s \n",lineno,m);
exit(1);
}
int look_up(char s[ ])
{
int k;
for(k=lastentry;k>0;k--)
if(strcmp(symtable[k].lexptr,s)==0)
return k;
return 0;
}
int insert(char s[ ],int tok)
{
int len;
len=strlen(s);
if(lastentry+1>=MAX)
Error_Message("Symbpl table is full");
if(lastchar+len+1>=MAX)
Error_Message("Lexemes array is full");
lastentry=lastentry+1;
symtable[lastentry].token=tok;
symtable[lastentry].lexptr=&lexemes[lastchar+1];
lastchar=lastchar+len+1;
strcpy(symtable[lastentry].lexptr,s);
return lastentry;
}
/*void Initialize()
{
struct entry *ptr;
for(ptr=keywords;ptr->token;ptr+1)
insert(ptr->lexptr,ptr->token);
}*/
int lexer()
{
int t;
int val,i=0;
while(1)
{
t=getchar();
if(t==' '||t=='\t');
else
if(t=='\n')
lineno=lineno+1;
else
if(isdigit(t))
{
ungetc(t,stdin);
scanf("%d",&tokenval);
return NUM;

}
else
if(isalpha(t))
{
while(isalnum(t))
{
buffer[i]=t;
t=getchar();
i=i+1;
if(i>=SIZE)
Error_Message("Compiler error");
}
buffer[i]=EOS;
if(t!=EOF)
ungetc(t,stdin);
val=look_up(buffer);
if(val==0)
val=insert(buffer,ID);
tokenval=val;
return symtable[val].token;
}
else
if(t==EOF)
return DONE;
else
{
tokenval=NONE;
return t;
}
}
}
void Match(int t)
{
if(lookahead==t)
lookahead=lexer();
else
Error_Message("Syntax error");
}
void display(int t,int tval)
{
if(t=='+'||t=='-'||t=='*'||t=='/')
printf("\nArithmetic Operator: %c",t);
else if(t==NUM)
printf("\n Number: %d",tval);
 else if(t==ID)
printf("\n Identifier: %s",symtable[tval].lexptr);
else
printf("\n Token %d tokenval %d",t,tokenval);
}
void F()

{
void E();
switch(lookahead)
{
case '(' : Match('(');
E();
Match(')');
break;
case NUM : display(NUM,tokenval);
Match(NUM);
break;
case ID : display(ID,tokenval);
Match(ID);
break;
default : Error_Message("Syntax error");
}
}
void T()
{
int t;
F();
while(1)
{
 switch(lookahead)
{
case '*' : t=lookahead;
 Match(lookahead);
 F();
 display(t,NONE);
 continue;
case '/' : t=lookahead;
 Match(lookahead);
 display(t,NONE);
 continue;
 default : return;
}
}
}
void E()
{
int t;
T();
while(1)
{
switch(lookahead)
{
case '+' : t=lookahead;
Match(lookahead);
T();
display(t,NONE);

continue;
case '-' : t=lookahead;
Match(lookahead);
T();
display(t,NONE);
continue;
default : return;
}
}
}
void parser()
{
lookahead=lexer();
while(lookahead!=DONE)
{
E();
Match(';');
}
}
int main()
{
char ans[10];
printf("\n Enter the expression ");
printf("And place ; at the end\n");
printf("Press Ctrl-Z to terminate\n");
parser();
return 0;
}


text:
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
Einbeiniger::Application.initialize!


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace ContosoUniversity.Models
{
    public class Course
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }

        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}


text:
require 'google/apis/language_v1beta2/service.rb'
require 'google/apis/language_v1beta2/classes.rb'
require 'google/apis/language_v1beta2/representations.rb'

module Google
  module Apis
    # Google Cloud Natural Language API
    #
    # Provides natural language understanding technologies to developers. Examples
    # include sentiment analysis, entity recognition, entity sentiment analysis, and
    # text annotations.
    #
    # @see https://cloud.google.com/natural-language/
    module LanguageV1beta2
      VERSION = 'V1beta2'
      REVISION = '20170809'

      # Apply machine learning models to reveal the structure and meaning of text
      AUTH_CLOUD_LANGUAGE = 'https://www.googleapis.com/auth/cloud-language'

      # View and manage your data across Google Cloud Platform services
      AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
    end
  end
end


text:
My CMS written in PHP (2015-2017, RUS)

## Screenshots

## Third-patry solutions
* jQuery (https://github.com/jquery/jquery)
* ACE (https://github.com/ajaxorg/ace)
* Font Awesome (https://github.com/FortAwesome/Font-Awesome)
* Wysiwyg.js (https://github.com/wysiwygjs/wysiwyg.js)


text:
Middleware to authenticate user through given key. (Required)

```python
MIDDLEWARE_CLASSES = (
    ...
    'keyauth.middleware.KeyAuthenticationMiddleware',
)
```

This middlware adds two attributes to the `request` object:

- `request.user`: `User` instance of the authenticated client.
- `request.key`: `Key` instance of the given token.

## KeyRequiredMiddleware

Add this middleware to protect all views with key authetication.

```python
MIDDLEWARE_CLASSES = (
    ...
    'keyauth.middleware.KeyRequiredMiddleware',
)
```

## SuitableKeyMiddleware

Add this middleware to check if given key is suitable according to its type and request's user agent.

```python
MIDDLEWARE_CLASSES = (
    ...
    'keyauth.middleware.KeyRequiredMiddleware',
    'keyauth.middleware.SuitableKeyMiddleware',
)
```


text:
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/linuxkit/linuxkit/src/cmd/linuxkit/util"
	"github.com/linuxkit/linuxkit/src/cmd/linuxkit/version"

	log "github.com/sirupsen/logrus"
	"gopkg.in/yaml.v2"
)

// GlobalConfig is the global tool configuration
type GlobalConfig struct {
	Pkg PkgConfig `yaml:"pkg"`
}

// PkgConfig is the config specific to the `pkg` subcommand
type PkgConfig struct {
}

var (
	defaultLogFormatter = &log.TextFormatter{}

	// Config is the global tool configuration
	Config = GlobalConfig{}
)

// infoFormatter overrides the default format for Info() log events to
// provide an easier to read output
type infoFormatter struct {
}

func (f *infoFormatter) Format(entry *log.Entry) ([]byte, error) {
	if entry.Level == log.InfoLevel {
		return append([]byte(entry.Message), '\n'), nil
	}
	return defaultLogFormatter.Format(entry)
}

func printVersion() {
	fmt.Printf("%s version %s\n", filepath.Base(os.Args[0]), version.Version)
	if version.GitCommit != "" {
		fmt.Printf("commit: %s\n", version.GitCommit)
	}
	os.Exit(0)
}

func readConfig() {
	cfgPath := filepath.Join(os.Getenv("HOME"), ".moby", "linuxkit", "config.yml")
	cfgBytes, err := ioutil.ReadFile(cfgPath)
	if err != nil {
		if os.IsNotExist(err) {
			return
		}
		fmt.Printf("Failed to read %q\n", cfgPath)
		os.Exit(1)
	}
	if err := yaml.Unmarshal(cfgBytes, &Config); err != nil {
		fmt.Printf("Failed to parse %q\n", cfgPath)
		os.Exit(1)
	}
}

func main() {
	flag.Usage = func() {
		fmt.Printf("USAGE: %s [options] COMMAND\n\n", filepath.Base(os.Args[0]))
		fmt.Printf("Commands:\n")
		fmt.Printf("  build       Build an image from a YAML file\n")
		fmt.Printf("  cache       Manage the local cache\n")
		fmt.Printf("  metadata    Metadata utilities\n")
		fmt.Printf("  pkg         Package building\n")
		fmt.Printf("  push        Push a VM image to a cloud or image store\n")
		fmt.Printf("  run         Run a VM image on a local hypervisor or remote cloud\n")
		fmt.Printf("  serve       Run a local http server (for iPXE booting)\n")
		fmt.Printf("  version     Print version information\n")
		fmt.Printf("  help        Print this message\n")
		fmt.Printf("\n")
		fmt.Printf("Run '%s COMMAND --help' for more information on the command\n", filepath.Base(os.Args[0]))
		fmt.Printf("\n")
		fmt.Printf("Options:\n")
		flag.PrintDefaults()
	}

	readConfig()

	// Set up logging
	util.AddLoggingFlags(nil)
	flag.Parse()
	util.SetupLogging()

	args := flag.Args()
	if len(args) < 1 {
		fmt.Printf("Please specify a command.\n\n")
		flag.Usage()
		os.Exit(1)
	}

	switch args[0] {
	case "build":
		build(args[1:])
	case "cache":
		cache(args[1:])
	case "metadata":
		metadata(args[1:])
	case "pkg":
		pkg(args[1:])
	case "push":
		push(args[1:])
	case "run":
		run(args[1:])
	case "serve":
		serve(args[1:])
	case "version":
		printVersion()
	case "help":
		flag.Usage()
	default:
		fmt.Printf("%q is not valid command.\n\n", args[0])
		flag.Usage()
		os.Exit(1)
	}
}


text:
package com.twitter.bijection.json

import com.twitter.bijection.InversionFailure
import org.codehaus.jackson.JsonNode
import org.codehaus.jackson.node.JsonNodeFactory

import scala.collection.Factory
import scala.jdk.CollectionConverters._
import scala.util.{Success, Try}

trait CollectionJson {
  // This causes diverging implicits
  def collectionJson[T, C <: Iterable[T]](implicit
      fact: Factory[T, C],
      jbij: JsonNodeInjection[T]
  ): JsonNodeInjection[C] =
    new AbstractJsonNodeInjection[C] {
      def apply(l: C) = {
        val ary = JsonNodeFactory.instance.arrayNode
        l foreach { t =>
          ary.add(jbij(t))
        }
        ary
      }
      override def invert(n: JsonNode): Try[C] = {
        val builder = fact.newBuilder
        var inCount = 0
        n.getElements.asScala.foreach { jn =>
          inCount += 1
          val thisC = jbij.invert(jn)
          if (thisC.isFailure) {
            return InversionFailure.failedAttempt(n)
          }
          builder += thisC.get
        }
        val res = builder.result
        if (res.size == inCount) Success(res) else InversionFailure.failedAttempt(n)
      }
    }
}


text:
export default function hello() {
  return "Hello";
}


text:
<?php

namespace Sabre\DAV\Exception;

use Sabre\DAV;

class ConflictingLock extends Locked {

    /**
     * This method allows the exception to include additional information into the WebDAV error response
     *
     * @param DAV\Server $server
     * @param \DOMElement $errorNode
     * @return void
     */
    public function serialize(DAV\Server $server, \DOMElement $errorNode) {

        if ($this->lock) {
            $error = $errorNode->ownerDocument->createElementNS('DAV:','d:no-conflicting-lock');
            $errorNode->appendChild($error);
            if (!is_object($this->lock)) var_dump($this->lock);
            $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri));
        }

    }

}


text:
"""
ssh and rsync code
"""
from __future__ import print_function
import logging
import subprocess
import os
import stat
import shutil
import tempfile
import socket

from boto.exception import S3ResponseError

from .disco_creds import DiscoS3Bucket, SSH_PRIVATE_KEY_BUCKET_PREFIX
from .exceptions import CommandError

logger = logging.getLogger(__name__)

SSH_DEFAULT_OPTIONS = ["-oBatchMode=yes", "-oStrictHostKeyChecking=no", '-oUserKnownHostsFile=/dev/null']

class DiscoRemoteExec(object):
    """
    Wrapper class for ssh and rsync.  Adds ssh keys to the user's ssh-agent on
    initialization.
    """

    def __init__(self, credential_buckets):
        DiscoRemoteExec.add_ssh_keys(credential_buckets)

    @staticmethod
    def add_ssh_keys_in_bucket(tempdir, bucket_name):
        """
        Grabs all the private ssh keys we have access to in the named bucket and
        adds them to our ssh keychain.
        """
        try:
            s3_bucket = DiscoS3Bucket(bucket_name)
        except S3ResponseError:
            # It is ok if the keys don't exist, but log something to debug
            logger.info("Found no ssh keys at %s", SSH_PRIVATE_KEY_BUCKET_PREFIX)
            return

        for key in s3_bucket.listkeys(SSH_PRIVATE_KEY_BUCKET_PREFIX):
            keyfile = tempdir + '/' + key
            # write the ssh key to a temporary file
            try:
                s3_bucket.get_contents_to_file(key, keyfile)
                os.chmod(keyfile, os.stat(keyfile).st_mode & (stat.S_IREAD | stat.S_IWRITE))
                if os.system("ssh-add {0} 2> /dev/null".format(keyfile)) != 0:
                    raise CommandError("Failed to add {0} key".format(keyfile))
                logger.debug("Added ssh key %s", key)
            except S3ResponseError:
                logger.info("Failed to add ssh key %s", key)

    @staticmethod
    def add_ssh_keys(credential_buckets):
        """
        Grabs private ssh keys from each of our credential buckets and adds
        them to our ssh keychain.
        """
        try:
            # Create temporary directory for the ssh key files
            tempdir = tempfile.mkdtemp()
            full_temp_path = tempdir + '/' + SSH_PRIVATE_KEY_BUCKET_PREFIX
            if not os.path.exists(full_temp_path):
                os.makedirs(full_temp_path)

            # Add keys from each of our credential buckets
            for bucket_name in credential_buckets:
                logger.debug("Adding keys from %s", bucket_name)
                DiscoRemoteExec.add_ssh_keys_in_bucket(tempdir, bucket_name)

        finally:
            # Remove the temporary directory
            shutil.rmtree(tempdir)

    # R0914 Allow more than 15 local variables so we can pass a lot of options to ssh
    # pylint: disable=R0914
    @staticmethod
    def remotecmd(address, remote_command, user, stdin=None,
                  nothrow=False, jump_address=None, log_on_error=None,
                  ssh_options=(), forward_agent=None):
        """
        Runs the passed in command on a remote host, via a jump host if a jump_address
        is provided and if the address is not reachable without a jump host.

        Returns a tuple containing the return code and the standard output from the command.
        """
        is_reachable = DiscoRemoteExec._is_reachable(address)

        if not is_reachable and not jump_address and not nothrow:
            raise CommandError('Unable to run command {0}. {1} host is not reachable'
                               .format(remote_command, address))

        use_jump_address = jump_address and not is_reachable
        command = DiscoRemoteExec._get_remote_exec_command(address, remote_command, user,
                                                           jump_address if use_jump_address else None,
                                                           ssh_options, forward_agent)
        logger.debug("command: %s", command)

        # output subprocess into a file to bypass pipe buffer size limitation,
        # which might cause subprocess hanging, see
        # https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/
        with tempfile.TemporaryFile() as output:
            process = subprocess.Popen(command,
                                       stdin=subprocess.PIPE,
                                       stdout=output,
                                       stderr=subprocess.STDOUT)
            process.communicate(stdin)
            output.seek(0)
            stdout = output.read()
            logger.debug(stdout)
            if (not nothrow) and (process.returncode != 0):
                if log_on_error:
                    logger.error(stdout)
                raise CommandError("command: {0} returned {1}".format(
                    " ".join(command), process.returncode))
            return (process.returncode, stdout)

    @staticmethod
    def _get_remote_exec_command(address, remote_command, user, jump_address, ssh_options, forward_agent):
        """
        Get the SSH command to use to run a remote command
        Args:
            address (str): Address of the remote host
            remote_command (List[str]): The command and arguments to run
                                        or an empty list if commands will be taken from stdin
            user (str): The user to run command as
            jump_address (str): Address of the jump box to use if unable to connect directly to the host
            ssh_options (List[str]): List of extra ssh options
            forward_agent (bool): Enable forwarding agent

        Returns List[str]: The ssh command and its arguments in a list
        """
        common_flags = ["-oConnectTimeout=10"]
        common_flags.extend(SSH_DEFAULT_OPTIONS)
        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            common_flags.append("-v")

        # Build up command to get from tunnel to final dest
        final_hop = ["ssh"]
        final_hop.extend(common_flags)
        if forward_agent:
            final_hop.extend(["-A"])
        final_hop.append("-l{0}".format(user))
        final_hop.append(address)
        final_hop.extend(ssh_options)

        if jump_address:
            final_hop.append("'{0}'".format(" ".join(remote_command)))
        elif remote_command:
            final_hop.extend(remote_command)

        if jump_address:
            # Build up command to get to tunnel host
            proxy_hop = ["ssh", "-A", "-t", "{0}@{1}".format(user, jump_address)]
            proxy_hop.extend(common_flags)

            command = []
            command.extend(proxy_hop)
            command.append(" ".join(final_hop))
        else:
            command = final_hop

        return command

    @staticmethod
    def rsync(address, source, destination, user, nothrow=False):
        """Efficiently copies data from a source to a destination as a specific user"""
        local_command = ["rsync", "-a", "-v", "-z", "--delete"]

        # config ssh call
        ssh_options = "ssh {0} -oConnectTimeout=10".format(" ".join(SSH_DEFAULT_OPTIONS))
        local_command.append("-e")
        local_command.append(ssh_options)

        user_string = "{0}@".format(user) if user else ""
        full_destination = "{0}{1}:{2}".format(user_string, address, destination)

        local_command.append(source)
        local_command.append(full_destination)
        logger.debug("command: %s", local_command)

        # Try syncing with filter flag if we get syntax error assume its not
        # supported, then try without it.
        rsync_exit_code = DiscoRemoteExec._call_rsync(local_command + ["--filter=:e /.nosync"])
        if rsync_exit_code == 1:
            logger.debug("rsync failed due to 'Syntax or usage error.' Attempting without filter.")
            rsync_exit_code = DiscoRemoteExec._call_rsync(local_command)
        if (not nothrow) and (rsync_exit_code != 0):
            raise CommandError("command: rsync of {0} to {1} on {2} failed with exit code {3}".format(
                source, destination, address, rsync_exit_code))
        return rsync_exit_code

    @staticmethod
    def _call_rsync(command):
        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            with tempfile.TemporaryFile() as output:
                process = subprocess.Popen(
                    command,
                    stdout=output,
                    stderr=subprocess.STDOUT
                )
                process.communicate()
                output.seek(0)
                stdout = output.read()
                logger.debug(stdout)
                return process.returncode
        else:
            with open("/dev/null", "w") as devnull:
                return subprocess.call(command, stdout=devnull, stderr=devnull)

    @staticmethod
    def _is_reachable(ip_address):
        """Returns True if we can connect to port 22 at the given ip address"""
        if not ip_address:
            return False
        logger.info("Probing %s", ip_address)
        try:
            sock = socket.create_connection((ip_address, 22), timeout=2)
            sock.close()
            return True
        except (socket.timeout, socket.error):
            return False

    if __name__ == "__main__":
        print("This is a library. Nothing to run.")
        import sys
        sys.exit(1)


text:
package me.tabak.cakeday.ui.fragments;

import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import butterknife.ButterKnife;
import butterknife.InjectView;
import me.tabak.cakeday.MainActivity;
import me.tabak.cakeday.MyApplication;
import me.tabak.cakeday.R;
import me.tabak.cakeday.data.reddit.RedditService;
import me.tabak.cakeday.data.reddit.model.RedditLink;
import me.tabak.cakeday.data.reddit.model.RedditObject;
import me.tabak.cakeday.rx.EndlessObserver;
import me.tabak.cakeday.ui.recycler.anim.MyItemAnimator;
import me.tabak.cakeday.ui.viewholder.RedditLinkViewHolder;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import timber.log.Timber;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

public class RedditLinkListFragment extends Fragment {
  public static final int LIMIT = 25;
  @Inject RedditService mRedditService;
  @InjectView(R.id.list_recyclerview) RecyclerView mRecyclerView;
  @InjectView(R.id.swipe_refresh_layout) SwipeRefreshLayout mSwipeRefreshLayout;
  private List<RedditLink> mLinks = new ArrayList<>();
  private RedditLinkAdapter mAdapter;
  private MainActivity mActivity;
  private LinearLayoutManager mLayoutManager;
  private String mSort = "hot";
  private LinksRefreshListener mRefreshListener;
  private String mAfterId;
  private String mBeforeId;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MyApplication.get(getActivity()).inject(this);
    mAdapter = new RedditLinkAdapter();
    mActivity = (MainActivity) getActivity();
    setHasOptionsMenu(true);
    mActivity.setTitle(getString(R.string.app_name) + " - " + getString(R.string.listing_hot));
    if (savedInstanceState == null) {
      createRequest(true).subscribe(new LinksObserver());
    }
  }

  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                           @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_list, container, false);
    ButterKnife.inject(this, view);
    return view;
  }

  @Override
  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mRefreshListener = new LinksRefreshListener();
    mSwipeRefreshLayout.setOnRefreshListener(mRefreshListener);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(mAdapter);
    if (Build.VERSION.SDK_INT >= 11) {
      mRecyclerView.setItemAnimator(new MyItemAnimator(mLayoutManager));
    }
    mRecyclerView.setOnScrollListener(new LinkListScrollListener());
    if (mAdapter.getItemCount() == 0) {
      mSwipeRefreshLayout.post(() -> mSwipeRefreshLayout.setRefreshing(true));
    }
    mSwipeRefreshLayout.setColorSchemeColors(
        getResources().getColor(R.color.orange_bright),
        getResources().getColor(R.color.orange_dark),
        getResources().getColor(R.color.orange_light),
        getResources().getColor(R.color.orange_pale)
    );
  }

  @Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_link_list, menu);
    menu.findItem(R.id.menu_clear_all).setOnMenuItemClickListener(item -> {
      if (!mSwipeRefreshLayout.isRefreshing()) {
        mRefreshListener.onRefresh();
      }
      return true;
    });

    // Set up click listeners for the sorting menu
    SubMenu sortMenu = menu.findItem(R.id.menu_sort).getSubMenu();
    for (int i = 0; i < sortMenu.size(); i++) {
      sortMenu.getItem(i).setOnMenuItemClickListener(item -> {
        // Reset before and after ID when changing listings.
        mBeforeId = null;
        mAfterId = null;

        mActivity.setTitle(getString(R.string.app_name) + " - " + item.getTitle());
        mSort = item.getTitle().toString().toLowerCase();
        mRefreshListener.onRefresh();
        return true;
      });
    }
  }

  private Observable<List<RedditObject>> createRequest(boolean after) {
    // Null out the field we're not interested in.
    if (after) {
      mBeforeId = null;
    } else {
      mAfterId = null;
    }
    return mRedditService.getLinks(mSort, LIMIT, mAfterId, mBeforeId)
        .map(response -> response.getData().getChildren())
        .observeOn(AndroidSchedulers.mainThread());
  }

  private class RedditLinkAdapter extends RecyclerView.Adapter<RedditLinkViewHolder> {

    @Override
    public RedditLinkViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
      CardView cardView = new CardView(getActivity());
      cardView.setLayoutParams(new RecyclerView.LayoutParams(
          ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
      getLayoutInflater(null).inflate(R.layout.view_reddit_link, cardView, true);
      return new RedditLinkViewHolder(cardView);
    }

    @Override
    public void onBindViewHolder(RedditLinkViewHolder holder, int position) {
      holder.bindView(mLinks.get(position), false);
      holder.itemView.setOnClickListener(v -> mActivity.showDetailFragment(mLinks.get(position)));
    }

    @Override
    public int getItemCount() {
      // Always add one extra slot at the end for the 'loading more items' view.
      return mLinks.size();
    }
  }

  private class LinksObserver extends EndlessObserver<List<RedditObject>> {
    private final boolean mAfter;

    /**
     * Constructor that always adds items to the end.
     */
    public LinksObserver() {
      mAfter = true;
    }

    /**
     * Constructor that allows you to specify whether links should be added to the beginning or the end.
     * @param after
     */
    public LinksObserver(boolean after) {
      mAfter = after;
    }

    @Override
    public void onError(Throwable e) {
      mSwipeRefreshLayout.setRefreshing(false);
      Timber.e(e, "Failed to load links from Reddit.");
      new AlertDialog.Builder(getActivity())
          .setMessage("You failed at browsing reddit.")
          .setPositiveButton("Retry", (dialog, which) -> createRequest(mAfter).subscribe(new LinksObserver()))
          .setNegativeButton("Cancel", null)
          .show();
    }

    @Override @SuppressWarnings("unchecked")
    public void onNext(List<RedditObject> items) {
      mSwipeRefreshLayout.setRefreshing(false);
      addItems(items);
    }

    private void addItems(List<RedditObject> items) {
      if (mLinks.size() > 2 * LIMIT) {
        // our list will hold 3 * LIMIT items.  If the list already has more than 2 * LIMIT items
        // we need to remove any extras.
        if (mAfter) {
          mLinks = new ArrayList<>(mLinks.subList(LIMIT, mLinks.size()));
          mAdapter.notifyItemRangeRemoved(0, LIMIT);
        } else {
          mLinks = new ArrayList<>(mLinks.subList(0, LIMIT * 2));
          mAdapter.notifyItemRangeRemoved(2 * LIMIT, LIMIT);
        }
      }

      List<RedditLink> links = (List) items;
      int startPos = mAfter ? mLinks.size() : 0;
      mLinks.addAll(startPos, links);

      // Store the first and last IDs so we can get more later
      if (mLinks.size() > 0) {
        mAfterId = mLinks.get(mLinks.size() - 1).getName();
        mBeforeId = mLinks.get(0).getName();
      }

      mAdapter.notifyItemRangeInserted(startPos, links.size());
    }
  }

  private class LinksRefreshListener implements SwipeRefreshLayout.OnRefreshListener {
    @Override
    public void onRefresh() {
      mAdapter.notifyItemRangeRemoved(0, mLinks.size());
      mLinks.clear();
      createRequest(true).subscribe(new LinksObserver());
    }
  }

  private class LinkListScrollListener extends RecyclerView.OnScrollListener {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
      super.onScrolled(recyclerView, dx, dy);

      // Load more items when there are LIMIT/2 items left before the end.
      if (!mSwipeRefreshLayout.isRefreshing()) {
        if (mLayoutManager.findLastVisibleItemPosition() > mLinks.size() - LIMIT * .5) {
          mSwipeRefreshLayout.setRefreshing(true);
          createRequest(true).subscribe(new LinksObserver(true));
        } else if (mLayoutManager.findFirstVisibleItemPosition() < LIMIT * .5 && mLinks.size() > 2 * LIMIT) {
          mSwipeRefreshLayout.setRefreshing(true);
          createRequest(false).subscribe(new LinksObserver(false));
        }
      }
    }
  }
}


text:
P class

## Mom
DOM

## Parameters
No parameters.

## Static Members
No static members.

## Public Members
No public members.


text:
import logging
from math import floor
import time
import traceback

from celery.contrib.abortable import AbortableTask
from django.conf import settings
from django.utils import simplejson as json
from livesettings import config_value

from panda import solr, utils
from panda.utils.notifications import notify
from panda.utils.typecoercion import DataTyper

SOLR_READ_BUFFER_SIZE = 500
SOLR_ADD_BUFFER_SIZE = 500

class ReindexTask(AbortableTask):
    """
    Task to import all data for a dataset from a CSV.
    """
    name = 'panda.tasks.reindex'

    def run(self, dataset_slug, *args, **kwargs):
        """
        Execute reindex.
        """
        from panda.models import Dataset

        log = logging.getLogger(self.name)
        log.info('Beginning reindex, dataset_slug: %s' % dataset_slug)

        try:
            dataset = Dataset.objects.get(slug=dataset_slug)
        except Dataset.DoesNotExist:
            log.warning('Reindexing failed due to Dataset being deleted, dataset_slug: %s' % dataset_slug)

            return

        task_status = dataset.current_task
        task_status.begin('Preparing to reindex')

        if self.is_aborted():
            task_status.abort('Aborted during preparation')

            log.warning('Reindex aborted, dataset_slug: %s' % dataset_slug)

            return

        read_buffer = []
        add_buffer = []
        data_typer = DataTyper(dataset.column_schema)
        throttle = config_value('PERF', 'TASK_THROTTLE')

        i = 0

        while i < dataset.row_count:
            if not read_buffer:
                query = 'dataset_slug: %s' % (dataset.slug)
                response = solr.query(settings.SOLR_DATA_CORE, query, limit=SOLR_READ_BUFFER_SIZE, offset=i)
                read_buffer = response['response']['docs']

            data = read_buffer.pop(0)
            row = json.loads(data['data'])

            new_data = utils.solr.make_data_row(dataset, row)
            new_data['id'] = data['id']
            new_data['data_upload_id'] = data['data_upload_id']
            new_data = data_typer(new_data, row)

            add_buffer.append(new_data)

            if i % SOLR_ADD_BUFFER_SIZE == 0:
                solr.add(settings.SOLR_DATA_CORE, add_buffer)

                add_buffer = []

                task_status.update('%.0f%% complete' % floor(float(i) / float(dataset.row_count) * 100))

                if self.is_aborted():
                    task_status.abort('Aborted after reindexing %.0f%%' % floor(float(i) / float(dataset.row_count) * 100))

                    log.warning('Reindex aborted, dataset_slug: %s' % dataset_slug)

                    return

                time.sleep(throttle)

            i += 1

        if add_buffer:
            solr.add(settings.SOLR_DATA_CORE, add_buffer)
            add_buffer = []

        solr.commit(settings.SOLR_DATA_CORE)

        task_status.update('100% complete')

        # Refresh dataset
        try:
            dataset = Dataset.objects.get(slug=dataset_slug)
        except Dataset.DoesNotExist:
            log.warning('Reindexing could not be completed due to Dataset being deleted, dataset_slug: %s' % dataset_slug)

            return

        dataset.column_schema = data_typer.schema
        dataset.save()

        log.info('Finished reindex, dataset_slug: %s' % dataset_slug)

        return data_typer

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        """
        Save final status, results, etc.
        """
        from panda.models import Dataset

        log = logging.getLogger(self.name)

        try:
            dataset = Dataset.objects.get(slug=args[0])
        except Dataset.DoesNotExist:
            log.warning('Can not send reindexing notifications due to Dataset being deleted, dataset_slug: %s' % args[0])

            return

        try:
            try:
                self.send_notifications(dataset, retval, einfo)
            finally:
                # If reindex failed, clear any data that might be staged
                if dataset.current_task.status == 'FAILURE':
                    solr.delete(settings.SOLR_DATA_CORE, 'dataset_slug:%s' % args[0], commit=True)
        finally:
            dataset.unlock()

    def send_notifications(self, dataset, retval, einfo):
        """
        Send user notifications this task has finished.
        """
        task_status = dataset.current_task

        extra_context = {
            'related_dataset': dataset
        }

        if einfo:
            if hasattr(einfo, 'traceback'):
                tb = einfo.traceback
            else:
                tb = ''.join(traceback.format_tb(einfo[2]))

            task_status.exception(
                'Reindex failed',
                u'%s\n\nTraceback:\n%s' % (unicode(retval), tb)
            )

            template_prefix = 'reindex_failed'
            notification_type = 'Error'
        elif self.is_aborted():
            template_prefix = 'reindex_aborted'
            notification_type = 'Info'
        else:
            task_status.complete('Import complete')

            template_prefix = 'reindex_complete'
            extra_context['type_summary'] = retval.summarize()
            notification_type = 'Info'

        if task_status.creator:
            notify(
                task_status.creator,
                template_prefix,
                notification_type,
                url='#dataset/%s' % dataset.slug,
                extra_context=extra_context
            )


text:
using System;

class P21_FindSubArrayEqualingSum
{
    static bool foundSum = false;

    static void calculatePossibilities(int[] array, int index, int start, int sizeOfInput, int sumToLookFor, int[] inputArray)
    {
        int length = array.Length;

        if (index >= length)
        {
            int subSum = 0;
            for (int i = 0; i < array.Length; i++)
            {
                subSum += inputArray[array[i]];
            }

            if (subSum == sumToLookFor)
            {
                foreach (var item in array)
                {
                    Console.Write(inputArray[item] + " ");
                    foundSum = true;
                }
                Console.WriteLine();
            }
            return;
        }

        for (int i = start; i < sizeOfInput; i++)
        {
            array[index] = i;
            calculatePossibilities(array, index + 1, i + 1, sizeOfInput, sumToLookFor, inputArray);
        }

    }

    static void Main()
    {
        int[] array = { 2, -3, 4, 1, -2, 6, 8, 9, 5, 10, 6, -10 };
        int sumToLookFor = -15;
        int numberOfElements = 2;

        int[] subArray = new int[numberOfElements];
        calculatePossibilities(subArray, 0, 0, array.Length, sumToLookFor, array);

        if (!foundSum)
        {
            Console.WriteLine("no such sum");
        }

    }
}


text:
package ru.job4j.ioservice.networkManager;

import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Created by pacman on 27.06.17.
 * Tests the class NetworkClient.
 */
public class NetworkClientTest {

    /**
     * Tests startClient(String pathToRoot).
     * @throws IOException IOException.
     */
    @Test
    public void whenGetsFromServerMessageShouldDisplayThem() throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outputStream));

        String usersInputFromConsole = "exit\n";
        ByteArrayInputStream streamFromConsole = new ByteArrayInputStream(usersInputFromConsole.getBytes());
        System.setIn(streamFromConsole);
        String inputFromServer = "Hello\n";
        ByteArrayInputStream inputStream = new ByteArrayInputStream(inputFromServer.getBytes());

        ByteArrayOutputStream outputToServer = new ByteArrayOutputStream();
        Socket socket = mock(Socket.class);
        when(socket.getInputStream()).thenReturn(inputStream);
        when(socket.getOutputStream()).thenReturn(outputToServer);
        new NetworkClient(socket).startClient("/home/pacman/Development");
        assertThat(outputStream.toString(), is(inputFromServer));
    }
}


text:
using namespace v8::internal;

static const int kBufferSize = 100;

// Removes trailing '0' digits.
static void TrimRepresentation(Vector<char> representation) {
  int len = StrLength(representation.start());
  int i;
  for (i = len - 1; i >= 0; --i) {
    if (representation[i] != '0') break;
  }
  representation[i + 1] = '\0';
}

TEST(FastDtoaShortestVariousDoubles) {
  char buffer_container[kBufferSize];
  Vector<char> buffer(buffer_container, kBufferSize);
  int length;
  int point;
  int status;

  double min_double = 5e-324;
  status = FastDtoa(min_double, FAST_DTOA_SHORTEST, 0,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("5", buffer.start());
  CHECK_EQ(-323, point);

  double max_double = 1.7976931348623157e308;
  status = FastDtoa(max_double, FAST_DTOA_SHORTEST, 0,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("17976931348623157", buffer.start());
  CHECK_EQ(309, point);

  status = FastDtoa(4294967272.0, FAST_DTOA_SHORTEST, 0,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("4294967272", buffer.start());
  CHECK_EQ(10, point);

  status = FastDtoa(4.1855804968213567e298, FAST_DTOA_SHORTEST, 0,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("4185580496821357", buffer.start());
  CHECK_EQ(299, point);

  status = FastDtoa(5.5626846462680035e-309, FAST_DTOA_SHORTEST, 0,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("5562684646268003", buffer.start());
  CHECK_EQ(-308, point);

  status = FastDtoa(2147483648.0, FAST_DTOA_SHORTEST, 0,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("2147483648", buffer.start());
  CHECK_EQ(10, point);

  status = FastDtoa(3.5844466002796428e+298, FAST_DTOA_SHORTEST, 0,
                    buffer, &length, &point);
  if (status) {  // Not all FastDtoa variants manage to compute this number.
    CHECK_EQ("35844466002796428", buffer.start());
    CHECK_EQ(299, point);
  }

  uint64_t smallest_normal64 = V8_2PART_UINT64_C(0x00100000, 00000000);
  double v = Double(smallest_normal64).value();
  status = FastDtoa(v, FAST_DTOA_SHORTEST, 0, buffer, &length, &point);
  if (status) {
    CHECK_EQ("22250738585072014", buffer.start());
    CHECK_EQ(-307, point);
  }

  uint64_t largest_denormal64 = V8_2PART_UINT64_C(0x000FFFFF, FFFFFFFF);
  v = Double(largest_denormal64).value();
  status = FastDtoa(v, FAST_DTOA_SHORTEST, 0, buffer, &length, &point);
  if (status) {
    CHECK_EQ("2225073858507201", buffer.start());
    CHECK_EQ(-307, point);
  }
}

TEST(FastDtoaPrecisionVariousDoubles) {
  char buffer_container[kBufferSize];
  Vector<char> buffer(buffer_container, kBufferSize);
  int length;
  int point;
  int status;

  status = FastDtoa(1.0, FAST_DTOA_PRECISION, 3, buffer, &length, &point);
  CHECK(status);
  CHECK_GE(3, length);
  TrimRepresentation(buffer);
  CHECK_EQ("1", buffer.start());
  CHECK_EQ(1, point);

  status = FastDtoa(1.5, FAST_DTOA_PRECISION, 10, buffer, &length, &point);
  if (status) {
    CHECK_GE(10, length);
    TrimRepresentation(buffer);
    CHECK_EQ("15", buffer.start());
    CHECK_EQ(1, point);
  }

  double min_double = 5e-324;
  status = FastDtoa(min_double, FAST_DTOA_PRECISION, 5,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("49407", buffer.start());
  CHECK_EQ(-323, point);

  double max_double = 1.7976931348623157e308;
  status = FastDtoa(max_double, FAST_DTOA_PRECISION, 7,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("1797693", buffer.start());
  CHECK_EQ(309, point);

  status = FastDtoa(4294967272.0, FAST_DTOA_PRECISION, 14,
                    buffer, &length, &point);
  if (status) {
    CHECK_GE(14, length);
    TrimRepresentation(buffer);
    CHECK_EQ("4294967272", buffer.start());
    CHECK_EQ(10, point);
  }

  status = FastDtoa(4.1855804968213567e298, FAST_DTOA_PRECISION, 17,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("41855804968213567", buffer.start());
  CHECK_EQ(299, point);

  status = FastDtoa(5.5626846462680035e-309, FAST_DTOA_PRECISION, 1,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("6", buffer.start());
  CHECK_EQ(-308, point);

  status = FastDtoa(2147483648.0, FAST_DTOA_PRECISION, 5,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("21475", buffer.start());
  CHECK_EQ(10, point);

  status = FastDtoa(3.5844466002796428e+298, FAST_DTOA_PRECISION, 10,
                    buffer, &length, &point);
  CHECK(status);
  CHECK_GE(10, length);
  TrimRepresentation(buffer);
  CHECK_EQ("35844466", buffer.start());
  CHECK_EQ(299, point);

  uint64_t smallest_normal64 = V8_2PART_UINT64_C(0x00100000, 00000000);
  double v = Double(smallest_normal64).value();
  status = FastDtoa(v, FAST_DTOA_PRECISION, 17, buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("22250738585072014", buffer.start());
  CHECK_EQ(-307, point);

  uint64_t largest_denormal64 = V8_2PART_UINT64_C(0x000FFFFF, FFFFFFFF);
  v = Double(largest_denormal64).value();
  status = FastDtoa(v, FAST_DTOA_PRECISION, 17, buffer, &length, &point);
  CHECK(status);
  CHECK_GE(20, length);
  TrimRepresentation(buffer);
  CHECK_EQ("22250738585072009", buffer.start());
  CHECK_EQ(-307, point);

  v = 3.3161339052167390562200598e-237;
  status = FastDtoa(v, FAST_DTOA_PRECISION, 18, buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("331613390521673906", buffer.start());
  CHECK_EQ(-236, point);

  v = 7.9885183916008099497815232e+191;
  status = FastDtoa(v, FAST_DTOA_PRECISION, 4, buffer, &length, &point);
  CHECK(status);
  CHECK_EQ("7989", buffer.start());
  CHECK_EQ(192, point);
}

TEST(FastDtoaGayShortest) {
  char buffer_container[kBufferSize];
  Vector<char> buffer(buffer_container, kBufferSize);
  bool status;
  int length;
  int point;
  int succeeded = 0;
  int total = 0;
  bool needed_max_length = false;

  Vector<const PrecomputedShortest> precomputed =
      PrecomputedShortestRepresentations();
  for (int i = 0; i < precomputed.length(); ++i) {
    const PrecomputedShortest current_test = precomputed[i];
    total++;
    double v = current_test.v;
    status = FastDtoa(v, FAST_DTOA_SHORTEST, 0, buffer, &length, &point);
    CHECK_GE(kFastDtoaMaximalLength, length);
    if (!status) continue;
    if (length == kFastDtoaMaximalLength) needed_max_length = true;
    succeeded++;
    CHECK_EQ(current_test.decimal_point, point);
    CHECK_EQ(current_test.representation, buffer.start());
  }
  CHECK_GT(succeeded*1.0/total, 0.99);
  CHECK(needed_max_length);
}

TEST(FastDtoaGayPrecision) {
  char buffer_container[kBufferSize];
  Vector<char> buffer(buffer_container, kBufferSize);
  bool status;
  int length;
  int point;
  int succeeded = 0;
  int total = 0;
  // Count separately for entries with less than 15 requested digits.
  int succeeded_15 = 0;
  int total_15 = 0;

  Vector<const PrecomputedPrecision> precomputed =
      PrecomputedPrecisionRepresentations();
  for (int i = 0; i < precomputed.length(); ++i) {
    const PrecomputedPrecision current_test = precomputed[i];
    double v = current_test.v;
    int number_digits = current_test.number_digits;
    total++;
    if (number_digits <= 15) total_15++;
    status = FastDtoa(v, FAST_DTOA_PRECISION, number_digits,
                      buffer, &length, &point);
    CHECK_GE(number_digits, length);
    if (!status) continue;
    succeeded++;
    if (number_digits <= 15) succeeded_15++;
    TrimRepresentation(buffer);
    CHECK_EQ(current_test.decimal_point, point);
    CHECK_EQ(current_test.representation, buffer.start());
  }
  // The precomputed numbers contain many entries with many requested
  // digits. These have a high failure rate and we therefore expect a lower
  // success rate than for the shortest representation.
  CHECK_GT(succeeded*1.0/total, 0.85);
  // However with less than 15 digits almost the algorithm should almost always
  // succeed.
  CHECK_GT(succeeded_15*1.0/total_15, 0.9999);
}