text:
package org.telegram.telegrambots.meta.api.methods.groupadministration;

import org.junit.jupiter.api.Test;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

/**
 * @author Ruben Bermudez
 * @version 6.0
 */
public class PromoteChatMemberTest {
    @Test
    public void testPromoteChatMemberWithAllSet() {
        PromoteChatMember promoteChatMember = PromoteChatMember
                .builder()
                .chatId(12345L)
                .userId(12345L)
                .build();
        assertEquals("promoteChatMember", promoteChatMember.getMethod());
        assertDoesNotThrow(promoteChatMember::validate);
    }

    @Test
    public void testPromoteChatMemberWithEmptyChatId() {
        PromoteChatMember promoteChatMember = PromoteChatMember
                .builder()
                .chatId("")
                .userId(12345L)
                .build();
        assertEquals("promoteChatMember", promoteChatMember.getMethod());
        Throwable thrown = assertThrows(TelegramApiValidationException.class, promoteChatMember::validate);
        assertEquals("ChatId can't be empty", thrown.getMessage());
    }

    @Test
    public void testPromoteChatMemberWithEmptyUserId() {
        PromoteChatMember promoteChatMember = PromoteChatMember
                .builder()
                .chatId("12345")
                .userId(0L)
                .build();
        assertEquals("promoteChatMember", promoteChatMember.getMethod());
        Throwable thrown = assertThrows(TelegramApiValidationException.class, promoteChatMember::validate);
        assertEquals("UserId can't be empty", thrown.getMessage());
    }

    @Test
    public void testPromoteChatMemberDeserializeValidResponse() {
        String responseText = "{\"ok\":true,\"result\": true}";

        PromoteChatMember promoteChatMember = PromoteChatMember
                .builder()
                .chatId("12345")
                .userId(123456L)
                .build();

        try {
            boolean result = promoteChatMember.deserializeResponse(responseText);
            assertTrue(result);
        } catch (TelegramApiRequestException e) {
            fail(e.getMessage());
        }
    }

    @Test
    public void testPromoteChatMemberDeserializeErrorResponse() {
        String responseText = "{\"ok\":false,\"error_code\": 404,\"description\": \"Error message\"}";

        PromoteChatMember promoteChatMember = PromoteChatMember
                .builder()
                .chatId("12345")
                .userId(123456L)
                .build();

        try {
            promoteChatMember.deserializeResponse(responseText);
            fail();
        } catch (TelegramApiRequestException e) {
            assertEquals(404, e.getErrorCode());
            assertEquals("Error message", e.getApiResponse());
        }
    }

    @Test
    public void testPromoteChatMemberDeserializeWithWrongObject() {
        String responseText = "{\"ok\":false\"error_code\": 404,\"description\": \"Error message\"}";

        PromoteChatMember promoteChatMember = PromoteChatMember
                .builder()
                .chatId("12345")
                .userId(123456L)
                .build();

        try {
            promoteChatMember.deserializeResponse(responseText);
            fail();
        } catch (TelegramApiRequestException e) {
            assertEquals("Unable to deserialize response", e.getMessage());
        }
    }
}


text:
require 'rails_helper'

RSpec.describe "pixel_pics/new", :type => :view do
  before(:each) do
    assign(:pixel_pic, PixelPic.new(
      :name => "MyString",
      :image_characters => "MyString"
    ))
  end

  it "renders new pixel_pic form" do
    render

    assert_select "form[action=?][method=?]", pixel_pics_path, "post" do

      assert_select "input#pixel_pic_name[name=?]", "pixel_pic[name]"

      assert_select "input#pixel_pic_image_characters[name=?]", "pixel_pic[image_characters]"
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#include <mitkTestingMacros.h>

#include <mitkNrrdTbssRoiImageReader.h>
#include "mitkDiffusionImagingObjectFactory.h"
#include "mitkCoreObjectFactory.h"

/**Documentation
 *  test for the class "mitkNrrdTbssImageReader".
 */
int mitkTbssRoiNrrdImageReaderTest(int argc , char* argv[])
{
  MITK_TEST_BEGIN("NrrdTbssRoiImageReaderTest");

  mitk::NrrdTbssRoiImageReader::Pointer roiReader = mitk::NrrdTbssRoiImageReader::New();

  MITK_TEST_CONDITION_REQUIRED(roiReader.GetPointer(), "Testing initialization of test object!");

  RegisterDiffusionImagingObjectFactory();

  roiReader->SetFileName(argv[1]);
  MITK_TEST_CONDITION_REQUIRED( roiReader->CanReadFile(argv[1], "", ""), "Testing CanReadFile() method with valid input file name!");
  roiReader->Update();

  mitk::TbssRoiImage* roiImg = roiReader->GetOutput();

  MITK_TEST_CONDITION_REQUIRED(roiImg != NULL, "Testing that roiImg is not null");

  mitk::TbssRoiImage::SizeType size = roiImg->GetLargestPossibleRegion().GetSize();

  MITK_TEST_CONDITION_REQUIRED(size[0]==182 && size[1]==218 && size[2]==182, "Test size of ROI image");

  // Test indices of the roi
  std::vector< itk::Index<3> > indices = roiImg->GetRoi();

  MITK_TEST_CONDITION(indices.size() == 24, "Test the number of indices belonging to the Roi");

  itk::Index<3> ix = indices.at(0);

  MITK_TEST_CONDITION(ix[0]==90 && ix[1]==132 && ix[2]==74, "Test whether first index is correct");

  ix = indices.at(23);

  MITK_TEST_CONDITION(ix[0]==90 && ix[1]==117 && ix[2]==88, "Test whether last index is correct");

  MITK_TEST_END();
}


text:
var gulp = require('gulp');

gulp.task('watch', function() {
  gulp.watch(['./public/css/*.css', './public/scripts/*.js', './public/*.html'], ['html']);
});


text:
@class BSDataInput;
@class BSDataOutput;
@class IOSByteArray;

@interface BCASN1BitString : BCASN1Primitive

#pragma mark Public

- (instancetype)initWithInt:(jint)paddingBit
              withByteArray:(IOSByteArray *)content;

- (IOSByteArray *)getContent;

- (jint)getPaddingBit;

+ (BCASN1BitString *)readBitStringWithBSDataInput:(BSDataInput *)dataInput;

- (void)serializeWithBSDataOutput:(BSDataOutput *)dataOutput;

@end

J2OBJC_EMPTY_STATIC_INIT(BCASN1BitString)

FOUNDATION_EXPORT BCASN1BitString *BCASN1BitString_readBitStringWithBSDataInput_(BSDataInput *dataInput);

FOUNDATION_EXPORT void BCASN1BitString_initWithInt_withByteArray_(BCASN1BitString *self, jint paddingBit, IOSByteArray *content);

FOUNDATION_EXPORT BCASN1BitString *new_BCASN1BitString_initWithInt_withByteArray_(jint paddingBit, IOSByteArray *content) NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(BCASN1BitString)

typedef BCASN1BitString ImActorModelCryptoAsn1ASN1BitString;

#endif // _BCASN1BitString_H_


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Reality Builder Demo: Instructions</title>
  <link rel="stylesheet" href="stylesheets/reset.css">
  <link rel="stylesheet" href="stylesheets/common.css">

Reality Builder Demo: Instructions

Steps

    Paths are relative to current directory.

      If necessary, set up a MongoDB
      server.

      Set MongoDB database connection in Reality Builder configuration.

      Start serving Reality Builder
      using Node.js:

node ../app.js

      Create the demo database realitybuilder. Example:

mongo realitybuilder scene/create_db.js

      Run the demo:
      <form action="demo.html">
        <fieldset>
          Widget's host (see step
          3):
          <input type="text" id="demoHostTextField" name="demoHost"
                 value="localhost:3000">

          <input type="checkbox" id="demoDevelModeCheckbox" value="on"
                 name="demoDevelMode">
          Enable development mode
          (uncompressed code)

          <input type="submit" value="Run"></input>
        </fieldset>
      </form>

Supported Browsers

    Tested with (in default configurations; versions current as of release of
    this Reality Builder version):

      Google Chrome

      Firefox

      Opera

      Internet Explorer 8: see below

      Internet Explorer 9

Internet Explorer 8 Support

    To make the demo work with Internet Explorer 8, the FlashCanvas Pro library
    is required. For reasons of license, this library is not included in the
    Reality Builder distribution. If desired, install FlashCanvas Pro as
    follows:

      Download FlashCanvas Pro 1.5 or
      compatible.

      Place FlashCanvas Pro into: ../separate/FlashCanvasPro


text:
package orbin.deskclock.actionbarmenu;

import android.app.Activity;

/**
 * Provider for a {@link MenuItemController} instances.
 */
public interface MenuItemProvider {

    /**
     * provides a {@link MenuItemController} that handles menu item.
     */
    MenuItemController provide(Activity activity);
}


text:
package com.bbxyard.mp.xenum;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.bbxyard.mp.xenum.mapper")
public class XEnumApplication {
    public static void main(String[] args) {
        SpringApplication.run(XEnumApplication.class, args);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Main!</string>
    <string name="app_name">Web1</string>
</resources>


text:
Python script to email people when they join your Terraria server. Good for a private server with not a lot of users. I use it for my friends and I on the server we use privately. We're busy people so sometimes it's good to take a break and hop in the server when someone else happens to hop in.

**Features**
* Will only send an email every 30 minutes (prevents emails spamming out as people join/leave/join/leave/join
* Configured for TLS security on SMTP because my host required it
* Random string appended to email subject to prevent threading on gmail - makes it confusing what happened.
* Very, very, flexible - you can have this do anything in response to a console logged event on a terraria server. i.e. you could trigger an event every time the server saves, or something. Maybe have it update a web page with what is going on on the server or something.

You'll need to tee the output of your terraria server executable to a text file. I'm using wtee.exe from:

https://github.com/WinLAFS/wintee

How To Setup (Windows)

* Get Python 2.7 (wherever)
* get wtee.exe (https://github.com/WinLAFS/wintee)
* get logscanner.py (this repo)
* put in your smtp for logscanner.py and your email addresses (to and from)

example .bat script to launch terrariaserver.exe:

`cmd.exe /K "cd C:\tshock\ & TerrariaServer.exe -maxplayers 4 -world "C:\Users\Username\Documents\My Games\Terraria\Worlds\myworld.wld" --stats-optout" | c:\wtee.exe C:\tshock\logs\tlivelog.txt`

example shortcut to logscanner.py

`C:\Python27\python.exe c:\tshock\logscanner.py`


text:
@implementation SPIMSendMessageShareClubModel

- (instancetype)init {
    self = [super init];
    if (self) {
        _clubId = @"";
        _imageUrl = @"";
        _shareTitle = @"";
        _content = @"";
    }
    return self;
}

@end


text:
using System.Collections.Generic;

namespace MonoGame.Extended.Tiled
{
    public class TiledMapProperties : Dictionary<string, string>
    {
    }
}


text:
<?php

/**
 * Parser output
 *
 * @package Less
 * @subpackage output
 */
class Less_Output {

	/**
	 * Output holder
	 *
	 * @var string
	 */
	protected $strs = array();

	/**
	 * Adds a chunk to the stack
	 *
	 * @param string $chunk The chunk to output
	 * @param Less_FileInfo $fileInfo The file information
	 * @param integer $index The index
	 * @param mixed $mapLines
	 */
	public function add( $chunk, $fileInfo = null, $index = 0, $mapLines = null ) {
		$this->strs[] = $chunk;
	}

	/**
	 * Is the output empty?
	 *
	 * @return boolean
	 */
	public function isEmpty() {
		return count( $this->strs ) === 0;
	}

	/**
	 * Converts the output to string
	 *
	 * @return string
	 */
	public function toString() {
		return implode( '', $this->strs );
	}

}


text:
<!--
  Generated template for the History page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar color = "grape" text-center>
    <ion-title>History</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>
  <ion-list >
    <ion-item *ngFor = "let test of tests; let $index = index;" (click)="goToResult(test)">
      Test {{$index + 1 }}
     <ion-note style="float: right;">
       {{test.createDate | date:'dd-MMM-yyyy hh:mm a'}}
      </ion-note>

    </ion-item>
  </ion-list>
</ion-content>


text:
<?php

namespace JsonRPC;

use BadFunctionCallException;
use Closure;
use InvalidArgumentException;
use ReflectionFunction;
use ReflectionMethod;

/**
 * Class ProcedureHandler
 *
 * @package JsonRPC
 * @author  Frederic Guillot
 */
class ProcedureHandler
{
    /**
     * List of procedures
     *
     * @access protected
     * @var array
     */
    protected $callbacks = array();

    /**
     * List of classes
     *
     * @access protected
     * @var array
     */
    protected $classes = array();

    /**
     * List of instances
     *
     * @access protected
     * @var array
     */
    protected $instances = array();

    /**
     * Before method name to call
     *
     * @access protected
     * @var string
     */
    protected $beforeMethodName = '';

    /**
     * Register a new procedure
     *
     * @access public
     * @param  string   $procedure       Procedure name
     * @param  closure  $callback        Callback
     * @return $this
     */
    public function withCallback($procedure, Closure $callback)
    {
        $this->callbacks[$procedure] = $callback;
        return $this;
    }

    /**
     * Bind a procedure to a class
     *
     * @access public
     * @param  string   $procedure    Procedure name
     * @param  mixed    $class        Class name or instance
     * @param  string   $method       Procedure name
     * @return $this
     */
    public function withClassAndMethod($procedure, $class, $method = '')
    {
        if ($method === '') {
            $method = $procedure;
        }

        $this->classes[$procedure] = array($class, $method);
        return $this;
    }

    /**
     * Bind a class instance
     *
     * @access public
     * @param  mixed   $instance
     * @return $this
     */
    public function withObject($instance)
    {
        $this->instances[] = $instance;
        return $this;
    }

    /**
     * Set a before method to call
     *
     * @access public
     * @param  string $methodName
     * @return $this
     */
    public function withBeforeMethod($methodName)
    {
        $this->beforeMethodName = $methodName;
        return $this;
    }

    /**
     * Register multiple procedures from array
     *
     * @access public
     * @param  array  $callbacks Array with procedure names (array keys) and callbacks (array values)
     * @return $this
     */
    public function withCallbackArray($callbacks)
    {
        foreach ($callbacks as $procedure => $callback) {
            $this->withCallback($procedure, $callback);
        }

        return $this;
    }

    /**
     * Bind multiple procedures to classes from array
     *
     * @access public
     * @param  array  $callbacks Array with procedure names (array keys) and class and method names (array values)
     * @return $this
     */
    public function withClassAndMethodArray($callbacks)
    {
        foreach ($callbacks as $procedure => $callback) {
            $this->withClassAndMethod($procedure, $callback[0], $callback[1]);
        }

        return $this;
    }

    /**
     * Execute the procedure
     *
     * @access public
     * @param  string   $procedure    Procedure name
     * @param  array    $params       Procedure params
     * @return mixed
     */
    public function executeProcedure($procedure, array $params = array())
    {
        if (isset($this->callbacks[$procedure])) {
            return $this->executeCallback($this->callbacks[$procedure], $params);
        } elseif (isset($this->classes[$procedure]) && method_exists($this->classes[$procedure][0], $this->classes[$procedure][1])) {
            return $this->executeMethod($this->classes[$procedure][0], $this->classes[$procedure][1], $params);
        }

        foreach ($this->instances as $instance) {
            if (method_exists($instance, $procedure)) {
                return $this->executeMethod($instance, $procedure, $params);
            }
        }

        throw new BadFunctionCallException('Unable to find the procedure');
    }

    /**
     * Execute a callback
     *
     * @access public
     * @param  Closure   $callback     Callback
     * @param  array     $params       Procedure params
     * @return mixed
     */
    public function executeCallback(Closure $callback, $params)
    {
        $reflection = new ReflectionFunction($callback);

        $arguments = $this->getArguments(
            $params,
            $reflection->getParameters(),
            $reflection->getNumberOfRequiredParameters(),
            $reflection->getNumberOfParameters()
        );

        return $reflection->invokeArgs($arguments);
    }

    /**
     * Execute a method
     *
     * @access public
     * @param  mixed     $class        Class name or instance
     * @param  string    $method       Method name
     * @param  array     $params       Procedure params
     * @return mixed
     */
    public function executeMethod($class, $method, $params)
    {
        $instance = is_string($class) ? new $class : $class;
        $reflection = new ReflectionMethod($class, $method);

        $this->executeBeforeMethod($instance, $method);

        $arguments = $this->getArguments(
            $params,
            $reflection->getParameters(),
            $reflection->getNumberOfRequiredParameters(),
            $reflection->getNumberOfParameters()
        );

        return $reflection->invokeArgs($instance, $arguments);
    }

    /**
     * Execute before method if defined
     *
     * @access public
     * @param  mixed  $object
     * @param  string $method
     */
    public function executeBeforeMethod($object, $method)
    {
        if ($this->beforeMethodName !== '' && method_exists($object, $this->beforeMethodName)) {
            call_user_func_array(array($object, $this->beforeMethodName), array($method));
        }
    }

    /**
     * Get procedure arguments
     *
     * @access public
     * @param  array   $requestParams    Incoming arguments
     * @param  array   $methodParams     Procedure arguments
     * @param  integer $nbRequiredParams Number of required parameters
     * @param  integer $nbMaxParams      Maximum number of parameters
     * @return array
     */
    public function getArguments(array $requestParams, array $methodParams, $nbRequiredParams, $nbMaxParams)
    {
        $nbParams = count($requestParams);

        if ($nbParams < $nbRequiredParams) {
            throw new InvalidArgumentException('Wrong number of arguments');
        }

        if ($nbParams > $nbMaxParams) {
            throw new InvalidArgumentException('Too many arguments');
        }

        if ($this->isPositionalArguments($requestParams)) {
            return $requestParams;
        }

        return $this->getNamedArguments($requestParams, $methodParams);
    }

    /**
     * Return true if we have positional parameters
     *
     * @access public
     * @param  array    $request_params      Incoming arguments
     * @return bool
     */
    public function isPositionalArguments(array $request_params)
    {
        return array_keys($request_params) === range(0, count($request_params) - 1);
    }

    /**
     * Get named arguments
     *
     * @access public
     * @param  array $requestParams Incoming arguments
     * @param  array $methodParams  Procedure arguments
     * @return array
     */
    public function getNamedArguments(array $requestParams, array $methodParams)
    {
        $params = array();

        foreach ($methodParams as $p) {
            $name = $p->getName();

            if (array_key_exists($name, $requestParams)) {
                $params[$name] = $requestParams[$name];
            } elseif ($p->isDefaultValueAvailable()) {
                $params[$name] = $p->getDefaultValue();
            } else {
                throw new InvalidArgumentException('Missing argument: '.$name);
            }
        }

        return $params;
    }
}


text:
<?xml version="1.0"?>
<config>
  <acl>
    <resources>
      <all>
        <title>Allow Everything</title>
      </all>
      <admin>
        <children>
          <system>
            <children>
              <config>
                <children>
                  <customcatalog translate="title">
                    <title>Customcatalog Section</title>
                    <sort_order>1</sort_order>
                  </customcatalog>
                </children>
              </config>
            </children>
          </system>
        </children>
      </admin>
    </resources>
  </acl>
</config>


text:
package org.springframework.scripting.groovy;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.lang.Nullable;

public class LogUserAdvice implements MethodBeforeAdvice, ThrowsAdvice {

	private int countBefore = 0;

	private int countThrows = 0;

	@Override
	public void before(Method method, Object[] objects, @Nullable Object o) throws Throwable {
		countBefore++;
		// System.out.println("Method:" + method.getName());
	}

	public void afterThrowing(Exception e) throws Throwable {
		countThrows++;
		// System.out.println("***********************************************************************************");
		// System.out.println("Exception caught:");
		// System.out.println("***********************************************************************************");
		// e.printStackTrace();
		throw e;
	}

	public int getCountBefore() {
		return countBefore;
	}

	public int getCountThrows() {
		return countThrows;
	}

	public void reset() {
		countThrows = 0;
		countBefore = 0;
	}

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<parent>
		<artifactId>url-shortener-parent</artifactId>
		<groupId>com.google.developers</groupId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<modelVersion>4.0.0</modelVersion>

	<artifactId>url-shortener-shared</artifactId>

	<name>url-shortener-shared</name>

	<url>http://developers.dushu.hu/</url>

	<prerequisites>
		<maven>2.2.1</maven>
	</prerequisites>

	<build>
		<defaultGoal>compile exec:java</defaultGoal>
		<plugins>

			<!-- phase: prepare-package -->

			<!-- inherited -->
			<plugin>
				<artifactId>maven-help-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>versions-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>buildnumber-maven-plugin</artifactId>
			</plugin>

			<!-- phase: n/a - manual -->

		</plugins>
	</build>

	<dependencies>

		<dependency>
			<groupId>com.google.gdata</groupId>
			<artifactId>core</artifactId>
		</dependency>

		<dependency>
			<groupId>com.google.apis</groupId>
			<artifactId>google-api-services-urlshortener</artifactId>
		</dependency>

		<dependency>
			<groupId>com.google.api-client</groupId>
			<artifactId>google-api-client-appengine</artifactId>
		</dependency>

		<dependency>
			<groupId>com.google.appengine</groupId>
			<artifactId>appengine-api-labs</artifactId>
		</dependency>
		<dependency>
			<groupId>com.google.appengine</groupId>
			<artifactId>appengine-endpoints</artifactId>
		</dependency>
		<dependency>
			<groupId>com.google.appengine</groupId>
			<artifactId>appengine-jsr107cache</artifactId>
		</dependency>
		<dependency>
			<groupId>net.sf.jsr107cache</groupId>
			<artifactId>jsr107cache</artifactId>
		</dependency>

		<dependency>
			<groupId>com.google.inject.extensions</groupId>
			<artifactId>guice-servlet</artifactId>
		</dependency>

		<!-- logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-jdk14</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
		</dependency>

		<!-- testing -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>com.google.appengine</groupId>
			<artifactId>appengine-testing</artifactId>
		</dependency>
		<dependency>
			<groupId>com.google.appengine</groupId>
			<artifactId>appengine-api-stubs</artifactId>
		</dependency>

	</dependencies>

</project>


text:
screpl-save-images
==================

Screpl plugin for saving all images from a url to disk.


text:
"""ThreatConnect TI Generic Mappings Object"""
# standard library
from typing import TYPE_CHECKING

# first-party
from tcex.api.tc.v2.threat_intelligence.tcex_ti_tc_request import TiTcRequest

if TYPE_CHECKING:
    # first-party
    from tcex.api.tc.v2.threat_intelligence.threat_intelligence import ThreatIntelligence

class Owner:
    """Common API calls for for Indicators/SecurityLabels/Groups and Victims"""

    def __init__(self, ti: 'ThreatIntelligence'):
        """Initialize Class properties."""
        self._data = {}

        self._type = 'Owner'
        self._api_type = 'owners'
        self._api_entity = 'owner'

        self._tc_requests = TiTcRequest(ti.session_tc)

    @property
    def type(self):
        """Return main type."""
        return self._type

    @property
    def tc_requests(self):
        """Return tc request object."""
        return self._tc_requests

    @property
    def api_type(self):
        """Return api type."""
        return self._api_type

    @property
    def api_entity(self):
        """Return api entity."""
        return self._api_entity

    @api_entity.setter
    def api_entity(self, api_entity):
        """Set the Api Entity."""
        self._api_entity = api_entity

    @api_type.setter
    def api_type(self, api_type):
        """Set the Api Type."""
        self._api_type = api_type

    @tc_requests.setter
    def tc_requests(self, tc_requests):
        """Set the Tc Request Object."""
        self._tc_requests = tc_requests

    def single(self, unique_id):
        """Return main type."""
        return self.tc_requests.single(
            self.api_type,
            None,
            unique_id,
        )

    def many(self):
        """Get all of the owners available."""
        yield from self.tc_requests.many(self.api_type, None, self.api_entity)

    def mine(self):
        """Get all of my owners available."""
        return self.tc_requests.mine()

    def members(self):
        """Get all members for my owners."""
        yield from self.tc_requests.many(self.api_type, 'mine/members', 'user')

    def metrics(self):
        """Get all the metrics for owners."""
        yield from self.tc_requests.many(self.api_type, 'metrics', 'ownerMetric')


text:
@implementation GLGOpenGLController

#pragma Lifecycle methods
- (id) initWithWindow: (NSWindow *) theWindow {
    if (self = [super init]) {
        [GLGNameProperty initialize];

        window = theWindow;
        [window setDelegate:self];

        CGFloat width = [[NSScreen mainScreen] frame].size.width;
        CGFloat height = [[NSScreen mainScreen] frame].size.height;
        CGFloat rectWidth = 1280;
        CGFloat rectHeight = 800;
        CGFloat sceneWidth = rectWidth;
        CGFloat sceneHeight = rectHeight;

        NSRect windowRect = NSMakeRect(0, 0, rectWidth, rectHeight);
        NSRect viewRect = NSMakeRect(0, 0, sceneWidth, sceneHeight);
        NSPoint point = NSMakePoint((width - rectWidth) / 2, (height - rectHeight) / 2);
        [window setFrame:windowRect display:YES];
        [window setFrameOrigin:point];

        scene = [[GLGOpenGLView alloc] initWithFrame: viewRect];
        [scene setWantsBestResolutionOpenGLSurface:YES];
        [scene setDelegate: self];
        [window makeFirstResponder:scene];
        [[window contentView] addSubview:scene];

        GLint swapInt = 1;
        [[scene openGLContext] makeCurrentContext];
        [[scene openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];

        glEnable(GL_CULL_FACE);
        glEnable(GL_DEPTH_TEST);

        [[window contentView] setWantsLayer:YES];
        GLGMainMenuActor *actor = [[GLGMainMenuActor alloc] initWithWindow:window andDelegate:self];
        [actor positionSubviewsRelativeToView:scene];
        [actor setScene:scene];
        gameSceneActor = (id)actor;

        [window setMinSize:NSMakeSize(800, 600)];
        [window setAspectRatio:NSMakeSize(rectWidth, rectHeight)];
      }

    return self;
}

#pragma mark - Scene Transition methods
- (void) switchToMainMenuView {
    id actor = (GLGGalaxyPickerActor *) gameSceneActor;
    [actor release];

    [scene setFrame: [[window contentView] frame]];

    GLGMainMenuActor *newActor = [[GLGMainMenuActor alloc] initWithWindow:window andDelegate:self];
    [newActor positionSubviewsRelativeToView:scene];
    [newActor setScene:scene];
    gameSceneActor = newActor;
}

- (void) switchToGalaxyView {
    id actor = (NSObject *) gameSceneActor;
    [actor release];

    NSRect frame = [[window contentView] frame];
    [scene setFrame:NSMakeRect(frame.origin.x, frame.origin.y, frame.size.width - sidebarWidth, frame.size.height - 25)];
    GLGGalaxyPickerActor *newActor = [[GLGGalaxyPickerActor alloc] initWithWindow:window];
    [newActor setDelegate:self];
    [newActor setScene:scene];

    gameSceneActor = newActor;
}

- (void) switchToPlanetView {
    GLGGalaxyPickerActor *actor = (GLGGalaxyPickerActor *) gameSceneActor;
    GLGPlanetoid *planet = [actor selectedPlanet];
    assert( planet != nil );

    [actor release];
    GLGPlanetActor *newActor = [[GLGPlanetActor alloc] initWithPlanet:planet delegate:self];
    [newActor setScene:scene];

    CGFloat width = window.frame.size.width;
    CGFloat height = window.frame.size.height;
    [[scene animator] setFrame:NSMakeRect(0, 0, width, height)];

    gameSceneActor = newActor;
}

- (GLGOpenGLView *) openGLView {
    return scene;
}

#pragma mark - NSWindow delegate methods
- (void) windowDidResize:(NSNotification *) notification {
    [gameSceneActor resizeWithWindow:[notification object]];
}

#pragma mark - openGL update methods
- (void) updateFramerate {
    [gameSceneActor updateFramerate];
}

- (void) update {
    [gameSceneActor updateWithView:scene];
    [scene display];
}

- (void) prepareOpenGL {
    [self becomeFirstResponder];

    return;
}

#pragma mark - view delegate methods
- (void) GLGOpenGLViewDidReshape:(NSOpenGLView *) view {
    const GLfloat width = [view bounds].size.width;
    const GLfloat height = [view bounds].size.height;

    NSParameterAssert(0 < height);

    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();
    glViewport(0, 0, width, height);
    glOrtho(0, width, 0, height, -1, 1);

    [[view openGLContext] update];
}

- (void) GLGOpenGLView:(GLGOpenGLView *) view drawInRect:(NSRect) rect {
    [gameSceneActor incrementFrameNumber];
    [gameSceneActor updateWithView:view];
}

- (void) didPanByVector:(CGPoint) vector {
    [gameSceneActor didPanByVector:vector];
}

- (void) didZoom:(CGFloat) amount {
    [gameSceneActor didZoom:amount];
}

- (void) handleMouseDown:(NSPoint) point {
    [gameSceneActor handleMouseDown:point];
}

- (void) handleMouseUp {
    [gameSceneActor handleMouseUp];
}

#pragma mark - UI control methods
- (void) keyWasPressed:(NSEvent *) event {
    [gameSceneActor keyWasPressed:[event keyCode]];
}

@end


text:
class Api::V1::MobileController < ApplicationController
  skip_before_filter :authenticated
  before_filter :mobile_request?

  respond_to :json

  def show
    if params[:class]
      model = params[:class].classify.constantize
      respond_with model.find(params[:id]).to_json
    end
  end

  def index
    if params[:class]
      model = params[:class].classify.constantize
      respond_with model.all.to_json
    else
      respond_with nil.to_json
    end
  end

  private

  def mobile_request?
    if session[:mobile_param]
      session[:mobile_param] == "1"
    else
      request.user_agent =~ /ios|android/i
    end
  end
end


text:
module Cryptoexchange::Exchanges
  module StocksExchange
    module Services
      class Market < Cryptoexchange::Services::Market
        class << self
          def supports_individual_ticker_query?
            false
          end
        end

        def fetch
          output = super(self.ticker_url)
          adapt_all(output)
        end

        def ticker_url
          "#{Cryptoexchange::Exchanges::StocksExchange::Market::API_URL}/ticker"
        end

        def adapt_all(output)
          output['data'].map do |pair|
            base, target = pair['market_name'].split('_')
            market_pair = Cryptoexchange::Models::MarketPair.new(
                            base: pair['currency_code'],
                            target: pair['market_code'],
                            market: Cryptoexchange::Exchanges::StocksExchange::Market::NAME
                          )
            adapt(pair, market_pair)
          end.compact
        end

        def adapt(output, market_pair)
          ticker           = Cryptoexchange::Models::Ticker.new
          ticker.base      = market_pair.base
          ticker.target    = market_pair.target
          ticker.market    = StocksExchange::Market::NAME
          ticker.last      = NumericHelper.to_d(output['last'])
          ticker.bid       = NumericHelper.to_d(output['bid'])
          ticker.ask       = NumericHelper.to_d(output['ask'])
          ticker.volume    = NumericHelper.to_d(output['volumeQuote'])
          ticker.payload   = output
          ticker
        end
      end
    end
  end
end


text:
@import "./vars.css";

@component-namespace el {
  @b year-table {
    font-size: 12px;
    margin: -1px;

    .el-icon {
      color: var(--datepicker-icon-color);
    }

    td {
      text-align: center;
      padding: 20px 3px;
      cursor: pointer;

      .cell {
        width: 48px;
        height: 32px;
        display: block;
        line-height: 32px;
        color: var(--datepicker-color);
      }

      &.available .cell:hover {
        background-color: var(--datepicker-cell-hover-color);
      }

      &.current .cell {
        background-color: var(--datepicker-active-color) !important;
        color: #fff;
      }
    }
  }
}


text:
package models.analytics.individual

// external
import akka.actor.ActorLogging
import akka.contrib.pattern.ReceivePipeline
import akka.contrib.pattern.ReceivePipeline.Inner
import models.market.MarketStructures.BollingerBandPoint
import utils.Misc

import scala.collection.mutable.ListBuffer

// internal
import models.market.MarketEMACollection
import models.market.MarketStructures.{Candles, ClosePrice, MarketMessage}

/**
  * Implements bollinger bands
  */
trait Bollinger extends ActorLogging {

  this: ReceivePipeline => pipelineInner {
    case msg: MarketMessage =>
      val cp = ClosePrice(msg.time, msg.last)
      updateBands(cp)
      Inner(msg)

    /**
      * Assumes that the candles are orderd by latest time first!
      */
    case mc: Candles =>
      val cp = mc.candles.map( c => ClosePrice(c.time, c.close))
      computeBands(cp)
      Inner(mc)
  }

  private val zeBands = ListBuffer[BollingerBandPoint]()

  // these are the system defaults but can be overridden
  val periodInAverage = 20
  val closePrices = ListBuffer[ClosePrice]()
  val periodMinutes = 5
  val percent: BigDecimal = 0.04
  // to be defined
  val marketName: String

  def reset() = {
    zeBands.clear()
    closePrices.clear()
  }

  /**
    * Sets all averages for each period as a collection of simple moving averages.
    *
    * @param prices assumes the close prices are sorted with most recent
    *                    close period first and that all close prices have the same periodMinutes
    *                    as this object. Example, close prices for every 5 minute
    *                    period for the last 24 hour window.
    * @return
    */
  def computeBands(prices: List[ClosePrice]) = {
    closePrices ++= prices
    // create a new collection for specific periods
    val periodPrices = closePrices.sliding(periodInAverage).toList

    for (prices <- periodPrices) {
      val mean = prices.map(_.price).sum / periodInAverage
      val sum = prices.map( p => (p.price - mean) * (p.price - mean)).sum
      val mean2 = sum / prices.length
      val std = Math.sqrt(mean2.toDouble)

      val upper = mean + 2 * std
      val lower = mean - 2 * std
      val time = prices.head.time

      zeBands.append(BollingerBandPoint(time, mean, upper, lower))
    }
  }

  private def updateBands(price: ClosePrice) = {
    if (closePrices.length > 0) {
      val normalTime = Misc.roundDateToMinute(price.time, periodMinutes)

      val isUpdate = if (closePrices.head.time.equals(normalTime)) {
        closePrices.update(0, price.copy(time = normalTime))
        true
      } else {
        closePrices.insert(0, price.copy(time = normalTime))
        false
      }

      val prices = closePrices.take(periodInAverage)
      val mean = prices.map(_.price).sum / periodInAverage
      val sumSqr = prices.map( p => (p.price - mean) * (p.price - mean)).sum
      val mean2 = sumSqr / prices.length
      val std = Math.sqrt(mean2.toDouble)

      val upper = mean + 2 * std
      val lower = mean - 2 * std
      val time = prices.head.time
      val band = BollingerBandPoint(time, mean, upper, lower)

      if (isUpdate) {
        zeBands.update(0, band)
      } else {
        zeBands.insert(0, band)
      }
    }
  }

  /**
    * Returns the latest ema for each period.
    *
    * @return map of period to ema for that period
    */
  def getLatestPoints(): Option[BollingerBandPoint] = {
    zeBands.headOption
  }

  /**    val bollingers = getAllPoints()
    * Returns the moving averages for this market.
    *
    * @return a map of period to exponential moving averages for that period
    *         list of ExponentialMovingAverages are ordered with most recent first
    */
  def getAllPoints(): List[BollingerBandPoint] = {
    zeBands.toList
  }
}


text:
module.exports = ConsoleWyrmhole;

const makeDfd = require('../../../dist/dfd').makeDfd;

function ConsoleWyrmhole() {
    var msgIdCnt = 0;
    var dfds = {};

    this.sendMessage = function(msg, data) {
        var msgObj = {
            message: msg,
            messageId: ++msgIdCnt,
            data: data
        };
        console.log('sendMessage: ', msgObj);
        var dfd = makeDfd();
        dfds[msgIdCnt] = dfd;
        return dfd.promise;
    };
}


text:
It displays different crypto currency tickers on MacBook's Pro Touch Bar using Electron.

![Ticker preview](https://raw.githubusercontent.com/geoffrey/osx-touchbar-crypto-ticker/master/osx-touchbar-crypto-ticker-preview.png)

`npm install` to install all dependencies

`npm start` to run Crypto Ticker on MacBook's Pro fancy Touch Bar and serve its true purpose

`npm test` to test it

### Inspired by:

 - [osx-touchbar-party-parrot](https://github.com/mjaniszew/osx-touchbar-party-parrot)


text:
using namespace sequence::details;

namespace sequence {

FolderContent parse(const Configuration &config,
                    GetNextEntryFunction getNextEntry) {
  FolderContent result;
  Items &directories = result.directories;
  Items &files = result.files;
  // Scanning and bucketing files.
  FileBucketizer bucketizer;
  FilesystemEntry entry;
  while (getNextEntry(entry)) {
    if (entry.isDirectory) {
      directories.emplace_back(entry.filename);
    } else {
      bucketizer.ingest(entry.filename);
    }
  }
  // Splitting recursively to retain a single location.
  auto buckets = splitAllAndSort(config.getPivotIndex, bucketizer.transfer());
  // Merging padding if necessary.
  if (config.mergePadding && buckets.size() >= 2) {
    mergeCompatiblePadding(buckets);
  }
  // Packing indices if needed.
  if (config.pack) {
    for (auto &bucket : buckets) {
      bucket.pack();
    }
  }
  // Output items.
  for (auto &bucket : buckets) {
    bucket.output(config.bakeSingleton,
                  [&files](Item item) { files.push_back(std::move(item)); });
  }
  // Sorting if needed.
  if (config.sort) {
    sortIfNeeded(directories);
    sortIfNeeded(buckets);
  }
  return result;
}

////////////////////////////////////////////////////////////////////////////////
#if defined(_WIN64) || defined(_WIN32)
struct Lister {
private:
  WIN32_FIND_DATA fdFile;
  HANDLE hFind;
  std::string tmp;
  bool noMoreFile;

public:
  Lister(const char *pFilename) {
    tmp = pFilename;
    tmp += "\\*";
    hFind = FindFirstFile(tmp.c_str(), &fdFile);
    noMoreFile = hFind == INVALID_HANDLE_VALUE;
  }

  GetNextEntryFunction getNextEntryFunction() {
    return [&](sequence::FilesystemEntry &entry) -> bool {
      if (noMoreFile)
        return false;
      tmp = fdFile.cFileName;
      entry.filename = tmp;
      entry.isDirectory = fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
      noMoreFile = !FindNextFile(hFind, &fdFile);
      return true;
    };
  }

  ~Lister() {
    if (hFind != INVALID_HANDLE_VALUE)
      FindClose(hFind);
  }
};
////////////////////////////////////////////////////////////////////////////////
#elif defined(__APPLE__) || defined(__linux)
////////////////////////////////////////////////////////////////////////////////
struct Lister {
private:
  const char *const pDirectory;
  DIR *pDir;
  struct dirent *direntry;
  std::string symlink_buffer;

public:
  Lister(const char *pFilename)
      : pDirectory(pFilename), pDir(opendir(pFilename)), direntry(nullptr) {}

  int resolveLinkMode(const struct dirent *const direntry) {
    symlink_buffer.clear();
    symlink_buffer += pDirectory;
    symlink_buffer += '/';
    symlink_buffer += direntry->d_name;
    struct stat stats;
    if (stat(symlink_buffer.c_str(), &stats) == 0) {
      if (S_ISREG(stats.st_mode))
        return DT_REG;
      if (S_ISDIR(stats.st_mode))
        return DT_DIR;
    }
    return DT_UNKNOWN;
  }

  GetNextEntryFunction getNextEntryFunction() {
    return [&](sequence::FilesystemEntry &entry) -> bool {
      if (!pDir) {
        return false;
      }
      for (;;) {
        direntry = readdir(pDir);
        if (!direntry) {
          return false;
        }
        const int st_mode = direntry->d_type == DT_LNK
                                ? resolveLinkMode(direntry)
                                : direntry->d_type;
        if (st_mode == DT_DIR) {
          entry.isDirectory = true;
        } else if (st_mode == DT_REG) {
          entry.isDirectory = false;
        } else {
          continue;
        }
        entry.filename = direntry->d_name;
        return true;
      }
    };
  }

  ~Lister() {
    if (pDir)
      closedir(pDir);
  }
};
////////////////////////////////////////////////////////////////////////////////
#else
#error "Unsupported platform"
#endif

FolderContent parseDir(const Configuration &configuration,
                       CStringView foldername) {
  Lister lister(foldername.ptr());
  auto content = parse(configuration, lister.getNextEntryFunction());
  content.name = foldername.toString();
  return content;
}

} // namespace sequence


text:
import { LetterJj32 } from "../../";

export = LetterJj32;


text:
<?php

namespace Archive\StorageBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ArchiveStorageBundle extends Bundle
{
}


text:
package org.basex.gui;

import static org.basex.gui.layout.BaseXKeys.*;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.plaf.basic.*;

import org.basex.core.*;
import org.basex.core.parse.*;
import org.basex.data.*;
import org.basex.gui.layout.*;
import org.basex.query.*;
import org.basex.util.*;
import org.basex.util.list.*;

/**
 * This class offers a text field for keyword and XQuery input.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class GUIInput extends BaseXCombo {
  /** Reference to the main window. */
  private final GUI gui;
  /** Input completions. */
  private final BaseXCombo completions;
  /** BasicComboPopup Menu. */
  private GUIInputPopup popup;

  /** String for temporary input. */
  private String prefix = "";

  /**
   * Default constructor.
   * @param main main window reference
   */
  GUIInput(final GUI main) {
    super(main, true);
    gui = main;

    BaseXLayout.resizeFont(this, 1.3f);

    completions = new BaseXCombo(main);
    completions.addActionListener(e -> completeInput());
    popup = new GUIInputPopup(completions);

    addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(final KeyEvent e) {
        if(ESCAPE.is(e)) {
          popup.setVisible(false);
        } else if(ENTER.is(e)) {
          if(popup.isVisible()) {
            completeInput();
            popup.setVisible(false);
          } else {
            updateHistory();
            // evaluate the input
            if(e.getModifiersEx() == 0) gui.execute();
          }
        }

        final int count = completions.getItemCount();
        if(count == 0) return;

        int bi = completions.getSelectedIndex();
        if(NEXTLINE.is(e)) {
          if(popup.isVisible()) {
            if(++bi == count) bi = 0;
          } else {
            popupMenu();
          }
        } else if(PREVLINE.is(e)) {
          if(popup.isVisible()) {
            if(--bi < 0) bi = count - 1;
          } else {
            popupMenu();
          }
        }
        if(bi != completions.getSelectedIndex()) completions.setSelectedIndex(bi);
      }

      @Override
      public void keyReleased(final KeyEvent e) {
        if(!NEXTLINE.is(e) && !PREVLINE.is(e)) {
          if(modifier(e) || control(e)) return;
          popupMenu();
          if(gui.gopts.get(GUIOptions.EXECRT) && !cmdMode()) main.execute();
        }
      }
    });
  }

  @Override
  public void setText(final String txt) {
    super.setText(txt);
    completions.removeAllItems();
    popup.setVisible(false);
  }

  /**
   * Sets the input mode.
   * @param mode mode
   */
  void mode(final String mode) {
    hint(mode + Text.DOTS).setText("");

    final Data data = gui.context.data();
    final int i = data == null ? 2 : gui.gopts.get(GUIOptions.SEARCHMODE);
    history(i == 0 ? GUIOptions.SEARCH : i == 1 ?
        GUIOptions.XQUERY : GUIOptions.COMMANDS, gui.gopts);
  }

  /**
   * Checks if the input is a command.
   * @return result of check
   */
  private boolean cmdMode() {
    final int mode = gui.gopts.get(GUIOptions.SEARCHMODE);
    return mode == 2 || gui.context.data() == null;
  }

  /**
   * Checks if the input is a query.
   * @return result of check
   */
  private boolean queryMode() {
    final int mode = gui.gopts.get(GUIOptions.SEARCHMODE);
    return mode == 1 || mode == 0 && Strings.startsWith(getText(), '/');
  }

  /**
   * Completes the input with the current combobox choice.
   */
  private void completeInput() {
    final String suffix = completions.getSelectedItem();
    if(suffix.isEmpty()) return;
    final int pl = prefix.length(), ll = pl > 0 ? prefix.charAt(pl - 1) : ' ';
    if(Character.isLetter(ll) && Character.isLetter(suffix.charAt(0))) prefix += " ";
    setText(prefix + suffix);
    popupMenu();
    if(gui.gopts.get(GUIOptions.EXECRT) && !cmdMode()) gui.execute();
  }

  /**
   * Shows or hides a popup menu with input completions.
   */
  private void popupMenu() {
    final String query = getText();

    StringList list = null;
    if(textField().getCaretPosition() == query.length()) {
      final Data data = gui.context.data();
      if(queryMode() && data != null) {
        try(QueryContext qc = new QueryContext(gui.context)) {
          list = qc.suggest(query, data);
        }
      } else if(cmdMode()) {
        list = CommandParser.get(query, gui.context).suggest();
      }
    }

    if(list != null) {
      prefix = list.pop();
      createCombo(list);
    } else {
      popup.setVisible(false);
    }
  }

  /**
   * Creates and shows the combo box.
   * @param sl strings to be added
   */
  private void createCombo(final StringList sl) {
    if(sl == null || sl.isEmpty()) {
      popup.setVisible(false);
      return;
    }
    if(completionsChanged(sl)) {
      completions.setItems(sl.toArray());
      completions.setSelectedIndex(-1);
      popup = new GUIInputPopup(completions);
    }

    final int w = getFontMetrics(getFont()).stringWidth(prefix);
    popup.show(this, Math.min(getWidth(), w), getHeight());
  }

  /**
   * Tests if the combo box entries have changed.
   * @param list strings to be compared
   * @return result of check
   */
  private boolean completionsChanged(final StringList list) {
    final int ls = list.size();
    if(ls != completions.getItemCount()) return true;
    for(int l = 0; l < ls; ++l) {
      if(!list.get(l).equals(completions.getItemAt(l))) return true;
    }
    return false;
  }

  /** Combo popup menu class, overriding the default constructor. */
  private static final class GUIInputPopup extends BasicComboPopup {
    /**
     * Constructor.
     * @param combo combobox reference
     */
    GUIInputPopup(final JComboBox<Object> combo) {
      super(combo);
      final int h = combo.getMaximumRowCount();
      setPreferredSize(new Dimension(getPreferredSize().width, getPopupHeightForRowCount(h) + 2));
    }
  }
}


text:
import { css, cx } from '@emotion/css';
import { sortBy } from 'lodash';
import React, { ChangeEvent } from 'react';
import { FixedSizeList } from 'react-window';

import { CoreApp, GrafanaTheme2 } from '@grafana/data';
import { reportInteraction } from '@grafana/runtime';
import {
  Button,
  HighlightPart,
  HorizontalGroup,
  Input,
  Label,
  LoadingPlaceholder,
  withTheme2,
  BrowserLabel as LokiLabel,
  fuzzyMatch,
} from '@grafana/ui';

import PromQlLanguageProvider from '../../prometheus/language_provider';
import LokiLanguageProvider from '../language_provider';
import { escapeLabelValueInExactSelector, escapeLabelValueInRegexSelector } from '../language_utils';

// Hard limit on labels to render
const MAX_LABEL_COUNT = 1000;
const MAX_VALUE_COUNT = 10000;
const MAX_AUTO_SELECT = 4;
const EMPTY_SELECTOR = '{}';

export interface BrowserProps {
  // TODO #33976: Is it possible to use a common interface here? For example: LabelsLanguageProvider
  languageProvider: LokiLanguageProvider | PromQlLanguageProvider;
  onChange: (selector: string) => void;
  theme: GrafanaTheme2;
  app?: CoreApp;
  autoSelect?: number;
  hide?: () => void;
  lastUsedLabels: string[];
  storeLastUsedLabels: (labels: string[]) => void;
  deleteLastUsedLabels: () => void;
}

interface BrowserState {
  labels: SelectableLabel[];
  searchTerm: string;
  status: string;
  error: string;
  validationStatus: string;
}

interface FacettableValue {
  name: string;
  selected?: boolean;
  highlightParts?: HighlightPart[];
  order?: number;
}

export interface SelectableLabel {
  name: string;
  selected?: boolean;
  loading?: boolean;
  values?: FacettableValue[];
  hidden?: boolean;
  facets?: number;
}

export function buildSelector(labels: SelectableLabel[]): string {
  const selectedLabels = [];
  for (const label of labels) {
    if (label.selected && label.values && label.values.length > 0) {
      const selectedValues = label.values.filter((value) => value.selected).map((value) => value.name);
      if (selectedValues.length > 1) {
        selectedLabels.push(`${label.name}=~"${selectedValues.map(escapeLabelValueInRegexSelector).join('|')}"`);
      } else if (selectedValues.length === 1) {
        selectedLabels.push(`${label.name}="${escapeLabelValueInExactSelector(selectedValues[0])}"`);
      }
    }
  }
  return ['{', selectedLabels.join(','), '}'].join('');
}

export function facetLabels(
  labels: SelectableLabel[],
  possibleLabels: Record<string, string[]>,
  lastFacetted?: string
): SelectableLabel[] {
  return labels.map((label) => {
    const possibleValues = possibleLabels[label.name];
    if (possibleValues) {
      let existingValues: FacettableValue[];
      if (label.name === lastFacetted && label.values) {
        // Facetting this label, show all values
        existingValues = label.values;
      } else {
        // Keep selection in other facets
        const selectedValues: Set<string> = new Set(
          label.values?.filter((value) => value.selected).map((value) => value.name) || []
        );
        // Values for this label have not been requested yet, let's use the facetted ones as the initial values
        existingValues = possibleValues.map((value) => ({ name: value, selected: selectedValues.has(value) }));
      }
      return { ...label, loading: false, values: existingValues, facets: existingValues.length };
    }

    // Label is facetted out, hide all values
    return { ...label, loading: false, hidden: !possibleValues, values: undefined, facets: 0 };
  });
}

const getStyles = (theme: GrafanaTheme2) => ({
  wrapper: css`
    background-color: ${theme.colors.background.secondary};
    padding: ${theme.spacing(2)};
    width: 100%;
  `,
  list: css`
    margin-top: ${theme.spacing(1)};
    display: flex;
    flex-wrap: wrap;
    max-height: 200px;
    overflow: auto;
  `,
  section: css`
    & + & {
      margin: ${theme.spacing(2, 0)};
    }
    position: relative;
  `,
  selector: css`
    font-family: ${theme.typography.fontFamilyMonospace};
    margin-bottom: ${theme.spacing(1)};
  `,
  status: css`
    padding: ${theme.spacing(0.5)};
    color: ${theme.colors.text.secondary};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    /* using absolute positioning because flex interferes with ellipsis */
    position: absolute;
    width: 50%;
    right: 0;
    text-align: right;
    transition: opacity 100ms linear;
    opacity: 0;
  `,
  statusShowing: css`
    opacity: 1;
  `,
  error: css`
    color: ${theme.colors.error.main};
  `,
  valueList: css`
    margin-right: ${theme.spacing(1)};
  `,
  valueListWrapper: css`
    border-left: 1px solid ${theme.colors.border.medium};
    margin: ${theme.spacing(1, 0)};
    padding: ${theme.spacing(1, 0, 1, 1)};
  `,
  valueListArea: css`
    display: flex;
    flex-wrap: wrap;
    margin-top: ${theme.spacing(1)};
  `,
  valueTitle: css`
    margin-left: -${theme.spacing(0.5)};
    margin-bottom: ${theme.spacing(1)};
  `,
  validationStatus: css`
    padding: ${theme.spacing(0.5)};
    margin-bottom: ${theme.spacing(1)};
    color: ${theme.colors.text.maxContrast};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  `,
});

export class UnthemedLokiLabelBrowser extends React.Component<BrowserProps, BrowserState> {
  state: BrowserState = {
    labels: [] as SelectableLabel[],
    searchTerm: '',
    status: 'Ready',
    error: '',
    validationStatus: '',
  };

  onChangeSearch = (event: ChangeEvent<HTMLInputElement>) => {
    this.setState({ searchTerm: event.target.value });
  };

  onClickRunLogsQuery = () => {
    reportInteraction('grafana_loki_log_browser_closed', {
      app: this.props.app,
      closeType: 'showLogsButton',
    });
    const selector = buildSelector(this.state.labels);
    this.props.onChange(selector);
  };

  onClickRunMetricsQuery = () => {
    reportInteraction('grafana_loki_log_browser_closed', {
      app: this.props.app,
      closeType: 'showLogsRateButton',
    });
    const selector = buildSelector(this.state.labels);
    const query = `rate(${selector}[$__interval])`;
    this.props.onChange(query);
  };

  onClickClear = () => {
    reportInteraction('grafana_loki_log_browser_closed', {
      app: this.props.app,
      closeType: 'clearButton',
    });
    this.setState((state) => {
      const labels: SelectableLabel[] = state.labels.map((label) => ({
        ...label,
        values: undefined,
        selected: false,
        loading: false,
        hidden: false,
        facets: undefined,
      }));
      return { labels, searchTerm: '', status: '', error: '', validationStatus: '' };
    });
    this.props.deleteLastUsedLabels();
  };

  onClickLabel = (name: string, value: string | undefined, event: React.MouseEvent<HTMLElement>) => {
    const label = this.state.labels.find((l) => l.name === name);
    if (!label) {
      return;
    }
    // Toggle selected state
    const selected = !label.selected;
    let nextValue: Partial<SelectableLabel> = { selected };
    if (label.values && !selected) {
      // Deselect all values if label was deselected
      const values = label.values.map((value) => ({ ...value, selected: false }));
      nextValue = { ...nextValue, facets: 0, values };
    }
    // Resetting search to prevent empty results
    this.setState({ searchTerm: '' });
    this.updateLabelState(name, nextValue, '', () => this.doFacettingForLabel(name));
  };

  onClickValue = (name: string, value: string | undefined, event: React.MouseEvent<HTMLElement>) => {
    const label = this.state.labels.find((l) => l.name === name);
    if (!label || !label.values) {
      return;
    }
    // Resetting search to prevent empty results
    this.setState({ searchTerm: '' });
    // Toggling value for selected label, leaving other values intact
    const values = label.values.map((v) => ({ ...v, selected: v.name === value ? !v.selected : v.selected }));
    this.updateLabelState(name, { values }, '', () => this.doFacetting(name));
  };

  onClickValidate = () => {
    const selector = buildSelector(this.state.labels);
    this.validateSelector(selector);
  };

  updateLabelState(name: string, updatedFields: Partial<SelectableLabel>, status = '', cb?: () => void) {
    this.setState((state) => {
      const labels: SelectableLabel[] = state.labels.map((label) => {
        if (label.name === name) {
          return { ...label, ...updatedFields };
        }
        return label;
      });
      // New status overrides errors
      const error = status ? '' : state.error;
      return { labels, status, error, validationStatus: '' };
    }, cb);
  }

  componentDidMount() {
    const { languageProvider, autoSelect = MAX_AUTO_SELECT, lastUsedLabels } = this.props;
    if (languageProvider) {
      const selectedLabels: string[] = lastUsedLabels;
      languageProvider.start().then(() => {
        let rawLabels: string[] = languageProvider.getLabelKeys();
        if (rawLabels.length > MAX_LABEL_COUNT) {
          const error = `Too many labels found (showing only ${MAX_LABEL_COUNT} of ${rawLabels.length})`;
          rawLabels = rawLabels.slice(0, MAX_LABEL_COUNT);
          this.setState({ error });
        }
        // Auto-select all labels if label list is small enough
        const labels: SelectableLabel[] = rawLabels.map((label, i, arr) => ({
          name: label,
          selected: (arr.length <= autoSelect && selectedLabels.length === 0) || selectedLabels.includes(label),
          loading: false,
        }));
        // Pre-fetch values for selected labels
        this.setState({ labels }, () => {
          this.state.labels.forEach((label) => {
            if (label.selected) {
              this.fetchValues(label.name, EMPTY_SELECTOR);
            }
          });
        });
      });
    }
  }

  doFacettingForLabel(name: string) {
    const label = this.state.labels.find((l) => l.name === name);
    if (!label) {
      return;
    }
    const selectedLabels = this.state.labels.filter((label) => label.selected).map((label) => label.name);
    this.props.storeLastUsedLabels(selectedLabels);
    if (label.selected) {
      // Refetch values for newly selected label...
      if (!label.values) {
        this.fetchValues(name, buildSelector(this.state.labels));
      }
    } else {
      // Only need to facet when deselecting labels
      this.doFacetting();
    }
  }

  doFacetting = (lastFacetted?: string) => {
    const selector = buildSelector(this.state.labels);
    if (selector === EMPTY_SELECTOR) {
      // Clear up facetting
      const labels: SelectableLabel[] = this.state.labels.map((label) => {
        return { ...label, facets: 0, values: undefined, hidden: false };
      });
      this.setState({ labels }, () => {
        // Get fresh set of values
        this.state.labels.forEach((label) => label.selected && this.fetchValues(label.name, selector));
      });
    } else {
      // Do facetting
      this.fetchSeries(selector, lastFacetted);
    }
  };

  async fetchValues(name: string, selector: string) {
    const { languageProvider } = this.props;
    this.updateLabelState(name, { loading: true }, `Fetching values for ${name}`);
    try {
      let rawValues = await languageProvider.getLabelValues(name);
      // If selector changed, clear loading state and discard result by returning early
      if (selector !== buildSelector(this.state.labels)) {
        this.updateLabelState(name, { loading: false }, '');
        return;
      }
      if (rawValues.length > MAX_VALUE_COUNT) {
        const error = `Too many values for ${name} (showing only ${MAX_VALUE_COUNT} of ${rawValues.length})`;
        rawValues = rawValues.slice(0, MAX_VALUE_COUNT);
        this.setState({ error });
      }
      const values: FacettableValue[] = rawValues.map((value) => ({ name: value }));
      this.updateLabelState(name, { values, loading: false });
    } catch (error) {
      console.error(error);
    }
  }

  async fetchSeries(selector: string, lastFacetted?: string) {
    const { languageProvider } = this.props;
    if (lastFacetted) {
      this.updateLabelState(lastFacetted, { loading: true }, `Facetting labels for ${selector}`);
    }
    try {
      const possibleLabels = await languageProvider.fetchSeriesLabels(selector, true);
      // If selector changed, clear loading state and discard result by returning early
      if (selector !== buildSelector(this.state.labels)) {
        if (lastFacetted) {
          this.updateLabelState(lastFacetted, { loading: false });
        }
        return;
      }
      if (Object.keys(possibleLabels).length === 0) {
        this.setState({ error: `Empty results, no matching label for ${selector}` });
        return;
      }
      const labels: SelectableLabel[] = facetLabels(this.state.labels, possibleLabels, lastFacetted);
      this.setState({ labels, error: '' });
      if (lastFacetted) {
        this.updateLabelState(lastFacetted, { loading: false });
      }
    } catch (error) {
      console.error(error);
    }
  }

  async validateSelector(selector: string) {
    const { languageProvider } = this.props;
    this.setState({ validationStatus: `Validating selector ${selector}`, error: '' });
    const streams = await languageProvider.fetchSeries(selector);
    this.setState({ validationStatus: `Selector is valid (${streams.length} streams found)` });
  }

  render() {
    const { theme } = this.props;
    const { labels, searchTerm, status, error, validationStatus } = this.state;
    if (labels.length === 0) {
      return <LoadingPlaceholder text="Loading labels..." />;
    }
    const styles = getStyles(theme);
    const selector = buildSelector(this.state.labels);
    const empty = selector === EMPTY_SELECTOR;

    let selectedLabels = labels.filter((label) => label.selected && label.values);
    if (searchTerm) {
      selectedLabels = selectedLabels.map((label) => {
        const searchResults = label.values!.filter((value) => {
          // Always return selected values
          if (value.selected) {
            value.highlightParts = undefined;
            return true;
          }
          const fuzzyMatchResult = fuzzyMatch(value.name.toLowerCase(), searchTerm.toLowerCase());
          if (fuzzyMatchResult.found) {
            value.highlightParts = fuzzyMatchResult.ranges;
            value.order = fuzzyMatchResult.distance;
            return true;
          } else {
            return false;
          }
        });
        return {
          ...label,
          values: sortBy(searchResults, (value) => (value.selected ? -Infinity : value.order)),
        };
      });
    } else {
      // Clear highlight parts when searchTerm is cleared
      selectedLabels = this.state.labels
        .filter((label) => label.selected && label.values)
        .map((label) => ({
          ...label,
          values: label?.values ? label.values.map((value) => ({ ...value, highlightParts: undefined })) : [],
        }));
    }

    return (

            1. Select labels to search in

            {labels.map((label) => (
              <LokiLabel
                key={label.name}
                name={label.name}
                loading={label.loading}
                active={label.selected}
                hidden={label.hidden}
                facets={label.facets}
                onClick={this.onClickLabel}
              />
            ))}

            2. Find values for the selected labels

            <Input onChange={this.onChangeSearch} aria-label="Filter expression for values" value={searchTerm} />

            {selectedLabels.map((label) => (

                <div className={styles.valueTitle} aria-label={`Values for ${label.name}`}>
                  <LokiLabel
                    name={label.name}
                    loading={label.loading}
                    active={label.selected}
                    hidden={label.hidden}
                    //If no facets, we want to show number of all label values
                    facets={label.facets || label.values?.length}
                    onClick={this.onClickLabel}
                  />

                <FixedSizeList
                  height={200}
                  itemCount={label.values?.length || 0}
                  itemSize={28}
                  itemKey={(i) => (label.values as FacettableValue[])[i].name}
                  width={200}
                  className={styles.valueList}
                >
                  {({ index, style }) => {
                    const value = label.values?.[index];
                    if (!value) {
                      return null;
                    }
                    return (

                        <LokiLabel
                          name={label.name}
                          value={value?.name}
                          active={value?.selected}
                          highlightParts={value?.highlightParts}
                          onClick={this.onClickValue}
                          searchTerm={searchTerm}
                        />

                    );
                  }}
                </FixedSizeList>

            ))}

          3. Resulting selector

            {selector}

          {validationStatus &&
{validationStatus}
}
          <HorizontalGroup>
            <Button aria-label="Use selector as logs button" disabled={empty} onClick={this.onClickRunLogsQuery}>
              Show logs
            </Button>
            <Button
              aria-label="Use selector as metrics button"
              variant="secondary"
              disabled={empty}
              onClick={this.onClickRunMetricsQuery}
            >
              Show logs rate
            </Button>
            <Button
              aria-label="Validate submit button"
              variant="secondary"
              disabled={empty}
              onClick={this.onClickValidate}
            >
              Validate selector
            </Button>
            <Button aria-label="Selector clear button" variant="secondary" onClick={this.onClickClear}>
              Clear
            </Button>

              {error || status}

          </HorizontalGroup>

    );
  }
}

export const LokiLabelBrowser = withTheme2(UnthemedLokiLabelBrowser);


text:
import {from} from 'rxjs';
import {asyncTest} from '../test-util';

describe('Observable.fromPromise', () => {
  let log: any[];
  let observable1: any;

  beforeEach(() => { log = []; });

  it('fromPromise func callback should run in the correct zone', asyncTest((done: any) => {
       const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
       const promiseZone1: Zone = Zone.current.fork({name: 'Promise Zone1'});
       const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
       let res: any;
       let promise: any =
           promiseZone1.run(() => { return new Promise((resolve, reject) => { res = resolve; }); });
       observable1 = constructorZone1.run(() => { return from(promise); });

       subscriptionZone.run(() => {
         observable1.subscribe(
             (result: any) => {
               expect(Zone.current.name).toEqual(subscriptionZone.name);
               log.push(result);
               expect(log).toEqual([1]);
               done();
             },
             () => { fail('should not call error'); }, () => {});
       });
       res(1);

       expect(log).toEqual([]);
     }, Zone.root));
});


text:
A personal academic website theme for [Hugo](https://gohugo.io).

[![Screenshot](https://raw.githubusercontent.com/gcushen/hugo-academic/master/images/screenshot.png)](https://github.com/gcushen/hugo-academic/)

Key features:

- Designed for academic staff, students, or general personal use
- Includes Biography, Publications, Projects, News/Blog, Teaching, and Contact sections
- Write in [Markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) for easy formatting and code highlighting, with [LaTeX](https://en.wikibooks.org/wiki/LaTeX/Mathematics) for mathematical expressions
- Academic linking (Scholar etc.), Google Analytics, and Disqus comments
- Responsive and mobile friendly
- Simple and refreshing one page design
- Easy to customize

Latest demo: [gcushen.github.io/hugo-academic-demo/](http://gcushen.github.io/hugo-academic-demo/)

## Installation

1. Install [Hugo](https://gohugo.io/overview/installing/) and create a new website:

        hugo new site my_website
        cd my_website

2. Install Academic theme with [git](https://help.github.com/articles/set-up-git/):

        git clone https://github.com/gcushen/hugo-academic.git themes/academic

    Or alternatively, [download Academic](https://github.com/gcushen/hugo-academic/archive/master.zip) and extract it into a `themes/academic` folder within your Hugo website.

3. If you are creating a new website, copy the contents of the `exampleSite` folder to your website root folder, overwriting existing files if necessary. The `exampleSite` folder contains an example config file and content to help you get started.

        cp -av themes/academic/exampleSite/* .

4. Start the Hugo server from your website root folder:

        hugo server --watch

    Now you can go to [localhost:1313](http://localhost:1313) and your new Academic themed website should appear.

5. Customize your website (see next section), build it by running `hugo`, and deploy it by copying the `public/` directory (by FTP, Rsync, git push, etc.) to your production web server.

## Getting Started

Refer to the [documentation](http://gcushen.github.io/hugo-academic-demo/#posts) under the *Posts* section of the latest Academic theme demo.

## Upgrading

Feel free to *star* the project on [Github](https://github.com/gcushen/hugo-academic/) and monitor the commits for updates.

Before upgrading the theme, it is recommended to make a backup of your entire website directory, or at least your `themes/academic` directory. You can also read about the [most recent milestones](https://github.com/gcushen/hugo-academic/releases) (but this doesn't necessarily reflect the latest *master* release).

Before upgrading for the first time, the remote *origin* repository should be renamed to *upstream*:

    $ cd themes/academic
    $ git remote rename origin upstream

To list available updates:

    $ cd themes/academic
    $ git fetch upstream
    $ git log --pretty=oneline --abbrev-commit --decorate HEAD..upstream/master

Upgrade by running:

    $ cd themes/academic
    $ git pull upstream

If you have modified files in `themes/academic`, git will attempt to auto-merge changes. If conflicts are reported, you will need to manually edit the files with conflicts and add them back (`git add <filename>`).

If there are any issues after upgrading, you may wish to compare your site with the latest [example site](https://github.com/gcushen/hugo-academic/tree/master/exampleSite) to check if any settings changed.

## Contributing

Please use the [issue tracker](https://github.com/gcushen/hugo-academic/issues) to let me know about any bugs or feature requests, or alternatively make a pull request.

## License

Copyright 2016 [George Cushen](https://georgecushen.com).

Released under the [MIT](https://github.com/gcushen/hugo-academic/blob/master/LICENSE.md) license.


text:
namespace Dhgms.TplHelper.CodeGeneration.Model
{
    using Dhgms.Nucleotide.PropertyInfo;

    public class SingleResultBoolean : SingleResultBase
    {
        public override string ClassName => "SingleResultBoolean";

        public override PropertyInfoBase[] Properties => new PropertyInfoBase[]
                                                             {
                                                                 new Dhgms.Nucleotide.PropertyInfo.ClrBooleanPropertyInfo(
                                                                     Dhgms.Nucleotide.Model.CollectionType.None,
                                                                     "Result",
                                                                     "The result for the task",
                                                                     true,
                                                                     false, null)
                                                             };

        public override string ClassRemarks => "Represents a task that returns a single integer 32 result";
    }
}


text:
import sqlite3

__author__ = 'Acer.Yang <yangacer@gmail.com>'
__version__ = '0.1.6'

def get_token(text):
    out = ''
    for c in text:
        if c.isalnum() or ord(c) >= 128:
            out += c
        elif len(out):
            yield out
            out = ''
    if len(out):
        yield out
    pass

class __CONSTS__(object):

    SQL_COL_INFO = 'PRAGMA table_info({});'
    SQL_PURGE_TBL = 'DELETE FROM {};'
    SQL_STATS = '''
    SELECT term, documents, occurrences FROM {}_terms WHERE col=0;
    '''
    pass

class ns(object):

    dbfile = 'simpletag.db'
    table = None
    conn = None
    using_parenthesis_query = False

    def resolve_supported_level(self):
        sql = 'PRAGMA compile_options;'
        csr = self.conn.cursor()
        opts = [row[0] for row in csr.execute(sql)]
        if 'ENABLE_FTS3' not in opts:
            raise RuntimeError('SQLite''s FTS is not enabled')
        if 'ENABLE_FTS3_PARENTHESIS' in opts:
            self.using_parenthesis_query = True
        pass

    def get_existing_tbl_type(self, name):
        sql = 'select name from sqlite_master where type = "table";'
        csr = self.conn.cursor()
        return [row[0] for row in csr.execute(sql)]

    def __init__(self):
        raise NotImplementedError()

    def __priv_init__(self):
        conn = sqlite3.connect(self.dbfile)
        conn.row_factory = sqlite3.Row
        self.conn = conn
        self.resolve_supported_level()
        pass

    def open_table_(self, name):
        csr = self.conn.cursor()
        sql = self.__sql__['SQL_CREATE_TBL'].format(name)
        csr.executescript(sql)
        self.conn.commit()
        for k, v in self.__sql__.iteritems():
            self.__sql__[k] = v.format(name)
        self.table = name
        pass

    def purge(self):
        csr = self.conn.cursor()
        csr.execute(__CONSTS__.SQL_PURGE_TBL.format(self.table))
        self.conn.commit()
        pass

    def query_ids(self, query_str):
        sql = self.__sql__['SQL_QUERY_IDS']
        csr = self.conn.cursor()
        for row in csr.execute(sql, (query_str,)):
            yield row[0]

    def query_by_tags(self, query_str, tokenize=True):
        sql = self.__sql__['SQL_QUERY_BY_TAGS']
        csr = self.conn.cursor()
        for row in csr.execute(sql, (query_str, )):
            if tokenize is True:
                yield row[0], [tok for tok in get_token(row[1])]
            else:
                yield row[0], row[1]

    def query_tags(self, docid):
        sql = self.__sql__['SQL_QUERY_TAGS']
        csr = self.conn.cursor()
        for row in csr.execute(sql, (docid,)):
            for tok in get_token(row[0]):
                yield tok

    def stats(self):
        csr = self.conn.cursor()
        for row in csr.execute(__CONSTS__.SQL_STATS.format(self.table)):
            yield dict(((key, row[key]) for key in row.keys()))

    pass

class TextNS(ns):
    """
    >>> import simpletag

    >>> ns = simpletag.TextNS('myTextTagSpace')

    >>> doc_1 = '/a/b'
    >>> tags_1 = ['tag']

    >>> doc_2 = '/b/a'
    >>> tags_2 = 'tag simple!'

    >>> ns.update(doc_1, tags_1)
    >>> ns.update(doc_2, tags_2)

    >>> print [ doc for doc in ns.query_ids('tag') ]
    [u'/a/b', u'/b/a']

    >>> print [ tag for tag in ns.query_tags(doc_1) ]
    [u'tag']

    >>> print [ st for st in ns.stats() ] # doctest: +NORMALIZE_WHITESPACE
    [{'term': u'simple', 'documents': 1, 'occurrences': 1},
            {'term': u'tag', 'documents': 2, 'occurrences': 2}]

    >>> ns.purge()
    """

    def __init__(self, name):

        super(TextNS, self).__priv_init__()
        tbls = self.get_existing_tbl_type(name)
        if name in tbls and (name + '_text_id') not in tbls:
            raise TypeError(name)

        self.__sql__ = dict(
            SQL_CREATE_TBL='''
            PRAGMA recursive_triggers='ON';
            CREATE VIRTUAL TABLE IF NOT EXISTS {0} USING FTS4(tags);
            CREATE TABLE IF NOT EXISTS {0}_text_id (
                textid TEXT UNIQUE PRIMARY KEY NOT NULL);
            CREATE VIRTUAL TABLE IF NOT EXISTS {0}_terms USING fts4aux({0});
            CREATE TRIGGER IF NOT EXISTS {0}_del_text_id
                AFTER DELETE ON {0}_text_id
                BEGIN
                    DELETE FROM {0} WHERE docid=OLD.rowid;
                END;
            ''',
            SQL_INSERT='INSERT OR REPLACE INTO {}_text_id VALUES(?);',
            SQL_UPDATE_1='DELETE FROM {} WHERE docid=?;',
            SQL_UPDATE_2='INSERT INTO {} (docid, tags) VALUES (?, ?);',
            SQL_PURGE_TBL='DELETE FROM {0}; DELETE FROM {0}_text_id;',
            SQL_DEL='''
            DELETE FROM {0} WHERE docid=(
                SELECT rowid FROM {0}_text_id WHERE textid=?);
            ''',
            SQL_QUERY_IDS='''
            SELECT * FROM {0}_text_id AS lhs
                JOIN (SELECT docid FROM {0} WHERE tags MATCH ?) AS rhs
                ON (lhs.rowid=rhs.docid);
            ''',
            SQL_QUERY_BY_TAGS='''
            SELECT * FROM {0}_text_id, {0} WHERE {0}.tags MATCH ? AND
                {0}_text_id.rowid = {0}.docid;
            ''',
            SQL_QUERY_TAGS='''
            SELECT tags FROM {0} WHERE docid=(
                SELECT rowid FROM {0}_text_id WHERE textid=?);
            ''',
            SQL_STATS='''
            SELECT term, documents, occurrences FROM {}_terms WHERE col=0;
            '''
        )

        self.open_table_(name)
        pass

    def update(self, ident, tags):
        if not isinstance(ident, str) and not isinstance(ident, unicode):
            raise TypeError('Invalid ident type')

        if not isinstance(tags, str) and not isinstance(tags, unicode):
            tags = ' '.join(tags)

        csr = self.conn.cursor()
        sql = self.__sql__['SQL_INSERT']
        csr.execute(sql, (ident, ))

        rowid = csr.lastrowid
        sql = self.__sql__['SQL_UPDATE_1']
        csr.execute(sql, (rowid, ))

        sql = self.__sql__['SQL_UPDATE_2']
        csr.execute(sql, (rowid, tags))
        self.conn.commit()
        pass

    pass

class IntNS(ns):
    """
    >>> import simpletag

    >>> ns = simpletag.IntNS('myIntTagSpace')

    >>> doc_1 = 1
    >>> tags_1 = ['tag']

    >>> doc_2 = 2
    >>> tags_2 = 'tag simple!'

    >>> ns.update(doc_1, tags_1)
    >>> ns.update(doc_2, tags_2)

    >>> print [ doc for doc in ns.query_ids('tag') ]
    [1, 2]

    >>> print [ tag for tag in ns.query_tags(doc_1) ]
    [u'tag']

    >>> print [ st for st in ns.stats() ] # doctest: +NORMALIZE_WHITESPACE
    [{'term': u'simple', 'documents': 1, 'occurrences': 1},
            {'term': u'tag', 'documents': 2, 'occurrences': 2}]

    >>> ns.purge()
    """

    def __init__(self, name, conn=None):

        super(IntNS, self).__priv_init__()
        tbls = self.get_existing_tbl_type(name)
        if name in tbls and (name + '_text_id') in tbls:
            raise TypeError(name)

        self.__sql__ = dict(
            SQL_CREATE_TBL='''
            CREATE VIRTUAL TABLE IF NOT EXISTS {0} USING FTS4(tags);
            CREATE VIRTUAL TABLE IF NOT EXISTS {0}_terms USING fts4aux({0});
            ''',
            SQL_UPDATE_1='DELETE FROM {} WHERE docid=?;',
            SQL_UPDATE_2='INSERT INTO {} (docid, tags) VALUES (?, ?);',
            SQL_PURGE_TBL='DELETE FROM {0};',
            SQL_DEL='DELETE FROM {} WHERE docid=?;',
            SQL_QUERY_IDS='SELECT docid FROM {0} WHERE tags MATCH ?;',
            SQL_QUERY_BY_TAGS='''
            SELECT docid, tags FROM {0} WHERE tags MATCH ?;
            ''',
            SQL_QUERY_TAGS='SELECT tags FROM {} WHERE docid=?;',
            SQL_STATS='''
            SELECT term, documents, occurrences FROM {}_terms WHERE col=0;
            ''',
        )

        self.open_table_(name)
        pass

    def update(self, ident, tags):
        if not isinstance(ident, int):
            raise TypeError('Invalid ident type')

        if not isinstance(tags, str) and not isinstance(tags, unicode):
            tags = ' '.join(tags)

        csr = self.conn.cursor()

        sql = self.__sql__['SQL_UPDATE_1']
        csr.execute(sql, (ident, ))

        sql = self.__sql__['SQL_UPDATE_2']
        csr.execute(sql, (ident, tags))
        self.conn.commit()
        pass

    pass


text:
using namespace cocos2d;

namespace cocosbuilder {

#define PROPERTY_COLOR "color"
#define PROPERTY_OPACITY "opacity"
#define PROPERTY_BLENDFUNC "blendFunc"

void LayerColorLoader::onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, const Color3B& pColor3B, CCBReader * ccbReader) {
    if(strcmp(pPropertyName, PROPERTY_COLOR) == 0) {
        ((LayerColor *)pNode)->setColor(pColor3B);
    } else {
        LayerLoader::onHandlePropTypeColor3(pNode, pParent, pPropertyName, pColor3B, ccbReader);
    }
}

void LayerColorLoader::onHandlePropTypeByte(Node * pNode, Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader) {
    if(strcmp(pPropertyName, PROPERTY_OPACITY) == 0) {
        ((LayerColor *)pNode)->setOpacity(pByte);
    } else {
        LayerLoader::onHandlePropTypeByte(pNode, pParent, pPropertyName, pByte, ccbReader);
    }
}

void LayerColorLoader::onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, const BlendFunc& pBlendFunc, CCBReader * ccbReader) {
    if(strcmp(pPropertyName, PROPERTY_BLENDFUNC) == 0) {
        ((LayerColor *)pNode)->setBlendFunc(pBlendFunc);
    } else {
        LayerLoader::onHandlePropTypeBlendFunc(pNode, pParent, pPropertyName, pBlendFunc, ccbReader);
    }
}

}


text:
{-# LANGUAGE OverloadedStrings #-}

module System.Giraffe.TrackerBenchmark (trackerBenchmark) where

import           Criterion.Main
import           Data.Text              (Text, pack)
import           System.Giraffe.Tracker
import           System.Giraffe.Types
import           System.Random

invalidRequest :: InvalidRequest
invalidRequest = InvalidRequest "invalid request"

emptyScrapeRequest :: ScrapeRequest
emptyScrapeRequest = ScrapeRequest { scrapeRequestInfoHashes = [] }

fullScrapeRequest :: StdGen -> ScrapeRequest
fullScrapeRequest gen = ScrapeRequest
    { scrapeRequestInfoHashes = replicate 128 $ randomText 32 gen
    }

randomText :: Int -> StdGen -> Text
randomText size = pack . take size . randomRs ('a', 'z')

trackerBenchmark :: IO [Benchmark]
trackerBenchmark = do
    gen <- newStdGen
    tr <- createEmptyTracker

    return
        [ bgroup "Tracker/init"
            [ bench "createEmptyTracker" createEmptyTracker
            ]
        , bgroup "EmptyTracker/announce"
            []
        , bgroup "EmptyTracker/scrape"
            [ bench "emptyScrapeRequest" $ handleInMemoryScrape tr emptyScrapeRequest
            , bench "fullScrapeRequest" $ handleInMemoryScrape tr $ fullScrapeRequest gen
            ]
        , bgroup "EmptyTracker/invalid"
            [ bench "invalidRequest" $ handleInMemoryInvalid tr invalidRequest
            ]
        ]


text:
<?php

namespace EnriseUserAdLdap\Entity;

use ZfcUser\Entity\User as ZfcUserEntity;

class User extends ZfcUserEntity {

}


text:
require_dependency 'carto/controller_helper'

class Carto::Api::SearchPreviewController < ::Api::ApplicationController
  ssl_required

  before_filter :login_required
  before_filter :load_parameters

  rescue_from StandardError, with: :rescue_from_standard_error
  rescue_from Carto::ParamCombinationInvalidError, with: :rescue_from_carto_error

  DEFAULT_LIMIT = 4
  DEFAULT_TYPES = "derived,table,remote,tag".freeze
  VALID_TYPES = Carto::Visualization::VALID_TYPES + ["tag"]

  def index
    searcher_params = { user: current_viewer, pattern: @pattern, types: @types, limit: @limit }
    searcher = Carto::DashboardPreviewSearcher.new(searcher_params)
    result = searcher.search

    presenter_params = { dashboard_search_result: result, limit: @limit, current_viewer: current_viewer, context: self }
    presentation = Carto::Api::SearchPreviewPresenter.new(presenter_params).to_poro

    render json: presentation
  end

  private

  def load_parameters
    @limit = params.fetch(:limit, DEFAULT_LIMIT).to_i
    @pattern = params[:q]

    @types = params.fetch(:types, DEFAULT_TYPES).split(',')
    if (@types - VALID_TYPES).present?
      raise Carto::ParamCombinationInvalidError.new(:types, VALID_TYPES)
    end
  end

end


text:
package it.mapeto2my.java_aop.factories.models.json;

import java.lang.reflect.Method;

public class Flow {

	private Flowable[] flowables;
	private int flowStep;
	private int flowCount;

	public Flow(int flowableNumber) {

		this.flowables = new Flowable[flowableNumber];
	}

	public Object flow(Object target,Method targetMethod) throws Exception{

		Object returnedObj = null;

		if(flowStep == flowCount)
			returnedObj= targetMethod.invoke(target);
		else
			returnedObj = flowables[flowStep++].intercept(this,target,targetMethod);

		return returnedObj;
	}

	public void addFlowable(Flowable flowable){
		flowables[flowCount++] = flowable;
	}

	public Flowable[] getFlowables() {
		return flowables;
	}

	public void setFlowables(Flowable[] flowables) {
		this.flowables = flowables;
	}
}


text:
using System.Collections.Generic;
using TokenFilterFactory = Lucene.Net.Analysis.Util.TokenFilterFactory;

namespace org.apache.lucene.analysis.miscellaneous
{

	using TokenFilterFactory = TokenFilterFactory;

	///
	/// Factory for <seealso cref="org.apache.lucene.analysis.miscellaneous.ScandinavianNormalizationFilter"/>.
	///

	/// <fieldType name="text_scandnorm" class="solr.TextField" positionIncrementGap="100">
	///   <analyzer>
	///     <tokenizer class="solr.WhitespaceTokenizerFactory"/>
	///     <filter class="solr.ScandinavianNormalizationFilterFactory"/>
	///   </analyzer>
	/// </fieldType>

	///
	public class ScandinavianNormalizationFilterFactory : TokenFilterFactory
	{

	  public ScandinavianNormalizationFilterFactory(IDictionary<string, string> args) : base(args)
	  {
		if (args.Count > 0)
		{
		  throw new System.ArgumentException("Unknown parameters: " + args);
		}
	  }

	  public override ScandinavianNormalizationFilter create(TokenStream input)
	  {
		return new ScandinavianNormalizationFilter(input);
	  }
	}

}


text:
[Quantum Espresso](http://www.quantum-espresso.org/) is a suite of software
for performing calculations on electronic structures and for materials
modeling.

The build process uses
[XCONFIGURE](https://xconfigure.readthedocs.io/en/latest/) to configure Quantum
Espresso and its dependency, [ELPA](https://elpa.mpcdf.mpg.de/). Test inputs
are made available by some benchmarking data sets available
[on GitHub](https://github.com/electronic-structure/benchmarks).


text:
Please attach complete source files that exhibit the issue in addition
to quoting from them here.

# Steps to Reproduce

# Expected Behavior

# Observed Behavior


text:
su - zookeeper -c "/usr/hdp/current/zookeeper-server/bin/zkServer.sh start"

tail -f /var/lib/zookeeper/zookeeper.out `find /var/log -name *.log -or -name *.out`


text:
<?xml version="1.0" encoding="UTF-8" ?>
<phpdoc>
	<title>bee4/transport</title>
	<parser>
		<target>doc/phpdoc</target>
		<extensions>
			<extension>php</extension>
		</extensions>
		<visibility></visibility>
		<markers>
			<item>TODO</item>
			<item>FIXME</item>
			<item>IDEA</item>
		</markers>
	</parser>
	<transformer>
		<target>doc/phpdoc</target>
	</transformer>
	<transformations>
		<template name="clean" />
	</transformations>
	<files>
		<directory>src</directory>
	</files>
	<logging>
		<level>crit</level>
		<paths>
			<default>doc/phpdoc/default.log</default>
			<errors>doc/phpdoc/errors.log</errors>
		</paths>
	</logging>
</phpdoc>


text:
package com.conveyal.analysis.util;

import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.FromStringDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.bson.types.ObjectId;

/**
 * This provides JSON serialization and deserialization of BSON IDs.
 */
public class BsonObjectIdModule extends SimpleModule {

    public BsonObjectIdModule () {
        super("BsonObjectId", new Version(1, 0, 0, null, "com.conveyal", "analysis"));
        this.addSerializer(ObjectId.class, new ToStringSerializer());
        this.addDeserializer(ObjectId.class, new FromStringDeserializer<>(ObjectId.class) {
            @Override
            protected ObjectId _deserialize(String s, DeserializationContext deserializationContext)  {
                return new ObjectId(s);
            }
        });

    }

}


text:
package com.sequenceiq.cloudbreak.controller.validation;

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

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintTarget;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.validation.metadata.ConstraintDescriptor;

import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.junit.Before;
import org.junit.Test;

import com.sequenceiq.cloudbreak.api.model.InstanceGroupAdjustmentJson;
import com.sequenceiq.cloudbreak.api.model.StatusRequest;
import com.sequenceiq.cloudbreak.api.model.UpdateStackJson;
import com.sequenceiq.cloudbreak.validation.UpdateStackRequestValidator;

public class UpdateStackRequestValidatorTest {

    private UpdateStackRequestValidator underTest;

    private ConstraintValidatorContext constraintValidatorContext;

    @Before
    public void setUp() {
        underTest = new UpdateStackRequestValidator();
        constraintValidatorContext = new ConstraintValidatorContextImpl(
                new ArrayList<>(), null,
                PathImpl.createRootPath(),
                new DummyConstraintDescriptor()
        );
    }

    @Test
    public void testIsValidShouldReturnTrueWhenStatusIsUpdated() {
        UpdateStackJson updateStackJson = new UpdateStackJson();
        updateStackJson.setInstanceGroupAdjustment(null);
        updateStackJson.setStatus(StatusRequest.STARTED);
        boolean valid = underTest.isValid(updateStackJson, constraintValidatorContext);
        assertTrue(valid);
    }

    @Test
    public void testIsValidShouldReturnTrueWhenNodeCountIsUpdated() {
        UpdateStackJson updateStackJson = new UpdateStackJson();
        InstanceGroupAdjustmentJson instanceGroupAdjustmentJson = new InstanceGroupAdjustmentJson();
        instanceGroupAdjustmentJson.setScalingAdjustment(12);
        instanceGroupAdjustmentJson.setInstanceGroup("slave_1");
        updateStackJson.setInstanceGroupAdjustment(instanceGroupAdjustmentJson);
        updateStackJson.setStatus(null);
        boolean valid = underTest.isValid(updateStackJson, constraintValidatorContext);
        assertTrue(valid);
    }

    @Test
    public void testInValidShouldReturnTrueWhenNodeCountIsLowerThanOneUpdatedAndWithClusterEvent() {
        UpdateStackJson updateStackJson = new UpdateStackJson();
        InstanceGroupAdjustmentJson instanceGroupAdjustmentJson = new InstanceGroupAdjustmentJson();
        instanceGroupAdjustmentJson.setScalingAdjustment(-1);
        instanceGroupAdjustmentJson.setWithClusterEvent(true);
        instanceGroupAdjustmentJson.setInstanceGroup("slave_1");
        updateStackJson.setInstanceGroupAdjustment(instanceGroupAdjustmentJson);
        updateStackJson.setStatus(null);
        boolean valid = underTest.isValid(updateStackJson, constraintValidatorContext);
        assertFalse(valid);
    }

    @Test
    public void testIsValidShouldReturnFalseWhenRequestContainsNodeCountAndStatus() {
        UpdateStackJson updateStackJson = new UpdateStackJson();
        InstanceGroupAdjustmentJson instanceGroupAdjustmentJson = new InstanceGroupAdjustmentJson();
        instanceGroupAdjustmentJson.setScalingAdjustment(4);
        instanceGroupAdjustmentJson.setInstanceGroup("slave_1");
        updateStackJson.setStatus(StatusRequest.STARTED);
        updateStackJson.setInstanceGroupAdjustment(instanceGroupAdjustmentJson);
        boolean valid = underTest.isValid(updateStackJson, constraintValidatorContext);
        assertFalse(valid);
    }

    @Test
    public void testIsValidShouldReturnFalseWhenRequestContainsOnlyNulls() {

        UpdateStackJson updateStackJson = new UpdateStackJson();
        updateStackJson.setInstanceGroupAdjustment(null);
        updateStackJson.setStatus(null);
        boolean valid = underTest.isValid(updateStackJson, constraintValidatorContext);
        assertFalse(valid);
    }

    private class DummyAnnotation implements Annotation {

        @Override
        public boolean equals(Object obj) {
            return false;
        }

        @Override
        public int hashCode() {
            return 0;
        }

        @Override
        public String toString() {
            return "dummy";
        }

        @Override
        public Class<? extends Annotation> annotationType() {
            return getClass();
        }
    }

    private class DummyConstraintDescriptor implements ConstraintDescriptor<DummyAnnotation>, Serializable {

        @Override
        public DummyAnnotation getAnnotation() {
            return null;
        }

        @Override
        public String getMessageTemplate() {
            return "";
        }

        @Override
        public Set<Class<?>> getGroups() {
            return new HashSet<>();
        }

        @Override
        public Set<Class<? extends Payload>> getPayload() {
            return new HashSet<>();
        }

        @Override
        public ConstraintTarget getValidationAppliesTo() {
            return ConstraintTarget.PARAMETERS;
        }

        @Override
        public List<Class<? extends ConstraintValidator<DummyAnnotation, ?>>> getConstraintValidatorClasses() {
            return new ArrayList<>();
        }

        @Override
        public Map<String, Object> getAttributes() {
            return new HashMap<>();
        }

        @Override
        public Set<ConstraintDescriptor<?>> getComposingConstraints() {
            return new HashSet<>();
        }

        @Override
        public boolean isReportAsSingleViolation() {
            return false;
        }
    }
}


text: An Atom package to manage the project requirements


text:
var express = require('express');
var router = express.Router();
var Setting = require('../models/setting');
var auth = require('../etc/authentication.js');

router.get('/', function(req, res) {
    Setting.find({}).exec(function(err, settings) {
        if (err) {
            res.status(500).send('Could not get settings. Error: ' + err);
        } else {
            res.json(settings);
        }
    });
});

router.post('/', auth, function(req, res) {
    var key = req.body.key;
    var value = req.body.value;

    Setting.update({ key: key }, { key: key, value: value }, { upsert: true }, function(err, setting) {
        if (err) {
            res.status(500).send('Could not create settings. Error: ' + err);
        } else {
            res.json(setting);
        }
    });
});

module.exports = router;


text:
package com.azavea.maml.util

trait Neighborhood
case class Square(extent: Int) extends Neighborhood
case class Circle(radius: Double) extends Neighborhood
case class Nesw(extent: Int) extends Neighborhood
case class Wedge(radius: Double, startAngle: Double, endAngle: Double) extends Neighborhood
case class Annulus(innerRadius: Double, outerRadius: Double) extends Neighborhood