text:
<?php

namespace Oro\Bundle\LocaleBundle\Serializer;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\PersistentCollection;

use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Serializer\SerializerInterface;

use Oro\Bundle\LocaleBundle\Entity\LocalizedFallbackValue;
use Oro\Bundle\LocaleBundle\Entity\Localization;

class LocalizationArraySerializer implements SerializerInterface
{
    /**
     * @var array
     */
    protected static $fieldsToSerializeInLocalization = [
        'id',
        'languageCode',
        'formattingCode',
        'name',
        'createdAt',
        'updatedAt',
        'updatedAtSet'
    ];

    /**
     * @var array
     */
    protected static $fieldsToSerializeInLocalizedFallbackValue = [
        'id',
        'fallback',
        'string',
        'text'
    ];

    /**
     * Used to deserialize relation properties
     * Format: [propertyName => [relationClassName, relationPropertyName]]
     *
     * @var array
     */
    protected static $relationClasses = [
        'parentLocalization' => [Localization::class, 'id']
    ];

    /**
     * @var string
     */
    protected static $titleKeyName = 'titles';

    /**
     * {@inheritdoc}
     * Available format: array
     * @throws \InvalidArgumentException
     *
     * @return array
     */
    public function serialize($data, $format = 'array', array $context = [])
    {
        if ($format !== 'array') {
            throw new \InvalidArgumentException("Only 'array' format is available.");
        }
        if (!is_object($data) || !$data instanceof Localization) {
            throw new \InvalidArgumentException(
                sprintf("First argument must be object of type '%s'", Localization::class)
            );
        }
        if ($data->getTitles() instanceof PersistentCollection) {
            $data->getTitles()->initialize();
        }

        $localizationArray = [];
        $reflectionLocalization = new \ReflectionObject($data);

        foreach (static::$fieldsToSerializeInLocalization as $propertyName) {
            $reflectionProperty = $reflectionLocalization->getProperty($propertyName);
            $reflectionProperty->setAccessible(true);
            $localizationArray[$reflectionProperty->getName()] = $reflectionProperty->getValue($data);
            $reflectionProperty->setAccessible(false);
        }

        $localizationArray = $this->serializeRelationProperties($data, $reflectionLocalization, $localizationArray);

        $titlesArray = $this->getSerializedTitles($data->getTitles());
        $localizationArray[static::$titleKeyName] = $titlesArray;

        return $localizationArray;
    }

    /**
     * {@inheritdoc}
     * Available type: Localization
     * Available format: array
     * @throws \InvalidArgumentException
     *
     * @return Localization
     */
    public function deserialize($data, $type = Localization::class, $format = 'array', array $context = [])
    {
        if ($format !== 'array' || !is_array($data)) {
            throw new \InvalidArgumentException("Only 'array' format is available.");
        }
        if ($type !== Localization::class) {
            throw new \InvalidArgumentException(
                sprintf("Only '%s' type is available", Localization::class)
            );
        }
        $localization = new Localization();
        $reflectionLocalization = new \ReflectionObject($localization);

        foreach (static::$fieldsToSerializeInLocalization as $propertyName) {
            $reflectionProperty = $reflectionLocalization->getProperty($propertyName);

            if (!array_key_exists($reflectionProperty->getName(), $data)) {
                continue;
            }

            $reflectionProperty->setAccessible(true);
            $reflectionProperty->setValue($localization, $data[$reflectionProperty->getName()]);
            $reflectionProperty->setAccessible(false);
        }

        $this->deserializeRelationProperties($data, $reflectionLocalization, $localization);
        $this->deserializeTitles($data, $localization);

        return $localization;
    }

    /**
     * @param Collection $titles
     * @return array
     */
    private function getSerializedTitles(Collection $titles)
    {
        $titlesArray = [];
        if (!empty($titles)) {
            foreach ($titles as $key => $title) {
                $reflectionTitle = new \ReflectionObject($title);
                foreach (static::$fieldsToSerializeInLocalizedFallbackValue as $propertyName) {
                    $reflectionProperty = $reflectionTitle->getProperty($propertyName);
                    $reflectionProperty->setAccessible(true);
                    $titlesArray[$key][$reflectionProperty->getName()] = $reflectionProperty->getValue($title);
                    $reflectionProperty->setAccessible(false);
                }
            }
        }

        return $titlesArray;
    }

    /**
     * @param array $titlesArray
     * @return ArrayCollection
     */
    private function getDeserializedTitles(array $titlesArray)
    {
        $titlesCollection = new ArrayCollection();
        if (!empty($titlesArray)) {
            foreach ($titlesArray as $titleArray) {
                $title = new LocalizedFallbackValue();
                $reflectionTitle = new \ReflectionObject($title);
                foreach (static::$fieldsToSerializeInLocalizedFallbackValue as $propertyName) {
                    $reflectionProperty = $reflectionTitle->getProperty($propertyName);
                    $reflectionProperty->setAccessible(true);
                    $reflectionProperty->setValue($title, $titleArray[$propertyName]);
                    $reflectionProperty->setAccessible(false);
                }
                $titlesCollection->add($title);
            }
        }

        return $titlesCollection;
    }

    /**
     * @param Localization      $localization
     * @param \ReflectionObject $reflectionLocalization
     * @param array             $localizationArray
     * @return array
     */
    protected function serializeRelationProperties(
        Localization $localization,
        \ReflectionObject $reflectionLocalization,
        array $localizationArray
    ) {
        foreach (static::$relationClasses as $propertyName => $classOptions) {
            $classPropertyName = $classOptions[1];

            $reflectionProperty = $reflectionLocalization->getProperty($propertyName);
            $reflectionProperty->setAccessible(true);

            if ($reflectionProperty->getValue($localization) === null) {
                $propertyValue = null;
            } else {
                try {
                    $propertyValue = (new PropertyAccessor())->getValue(
                        $reflectionProperty->getValue($localization),
                        $classPropertyName
                    );
                } catch (\Exception $exception) {
                    $propertyValue = null;
                }
            }
            $localizationArray[$reflectionProperty->getName()] = $propertyValue;
            $reflectionProperty->setAccessible(false);
        }

        return $localizationArray;
    }

    /**
     * @param array             $data
     * @param \ReflectionObject $reflectionLocalization
     * @param Localization      $localization
     */
    protected function deserializeRelationProperties(
        array $data,
        \ReflectionObject $reflectionLocalization,
        Localization $localization
    ) {
        foreach (static::$relationClasses as $propertyName => list($className, $classPropertyName)) {
            if (!array_key_exists($propertyName, $data) || $data[$propertyName] === null) {
                continue;
            }

            $reflectionProperty = $reflectionLocalization->getProperty($propertyName);

            $relationClass = new $className();
            $relationReflectionClass = new \ReflectionObject($relationClass);
            $relationReflectionProperty = $relationReflectionClass->getProperty($classPropertyName);
            $relationReflectionProperty->setAccessible(true);
            $relationReflectionProperty->setValue($relationClass, $data[$propertyName]);
            $relationReflectionProperty->setAccessible(false);

            $reflectionProperty->setAccessible(true);

            $reflectionProperty->setValue($localization, $relationClass);
            $reflectionProperty->setAccessible(false);
        }
    }

    /**
     * @param array        $data
     * @param Localization $localization
     */
    private function deserializeTitles($data, Localization $localization)
    {
        if (!array_key_exists(static::$titleKeyName, $data)) {
            return;
        }

        $titlesCollection = $this->getDeserializedTitles($data[static::$titleKeyName]);
        $reflectionLocalization = new \ReflectionObject($localization);
        $titlesProperty = $reflectionLocalization->getProperty(static::$titleKeyName);
        $titlesProperty->setAccessible(true);
        $titlesProperty->setValue($localization, $titlesCollection);
        $titlesProperty->setAccessible(false);
    }
}


text:
package oap.util.function;

import java.util.function.Function;

import static java.util.Objects.requireNonNull;

@FunctionalInterface
public interface TriFunction<T, U, S, R> {

    /**
     * Applies this function to the given arguments.
     *
     * @param t the first function argument
     * @param u the second function argument
     * @param s the third function argument
     * @return the function result
     */
    R apply( T t, U u, S s );

    default <V> TriFunction<T, U, S, V> andThen(
        Function<? super R, ? extends V> after ) {
        requireNonNull( after );
        return ( T t, U u, S s ) -> after.apply( apply( t, u, s ) );
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.nifi.wali;

import java.io.IOException;
import java.util.Collection;

public interface WriteAheadSnapshot<T> {
    SnapshotCapture<T> prepareSnapshot(long maxTransactionId);

    void writeSnapshot(SnapshotCapture<T> snapshot) throws IOException;

    SnapshotRecovery<T> recover() throws IOException;

    void update(Collection<T> records);

    int getRecordCount();
}


text:
require "adhearsion-asr"

module AdhearsionASR
  module Watson; end
end

require "adhearsion-asr-watson/version"
require "adhearsion-asr-watson/plugin"
require "adhearsion-asr-watson/controller_methods"


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Meliola speciosa Doidge

### Remarks
null


text:
package s3

func NewClient(bucket, region, prefix string) Client {
	basicClient := NewBasicClient(bucket, region, prefix)
	return NewClientFromBasic(basicClient)
}

func NewClientFromBasic(basicClient BasicClient) Client {
	return &client{
		BasicClient: basicClient,
	}
}

type client struct {
	BasicClient
}

func (s *client) Move(src, dst string) error {
	data, err := s.Get(src)
	if err != nil {
		return err
	}

	err = s.Put(dst, data)
	if err != nil {
		return err
	}

	return s.Delete(src)
}


text:
<?php
/**
 * Widget to display all the authors of the current blog. Requires members as authors
 * to be enabled.
 *
 * @author Mark Guinn <mark@adaircreative.com>
 * @package blogadmin
 * @subpackage widgets
 * @date 12/30/10
 */
class BlogAuthorsWidget extends Widget {

	static $title = 'Authors';
	static $cmsTitle = 'Blog Authors';
	static $description = 'Displays a list of blog authors.';

	/**
	 * @return DataObjectSet
	 */
	function Authors() {
		// TODO: if the context is a certain BlogHolder, should limit to authors with posts in that blog
		// TODO: post counts would be great
		return DataObject::get('Member',"\"BlogProfileURLSegment\" != ''");
	}

}


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


text:
from .mysql import MySQL
from .sqlite import SQLite

## ALL DECLARATION

__all__ = (
    'manager',
)

## DATABASE CHOICE

DATABASE_TYPE = 1

if DATABASE_TYPE == 1:
    manager = SQLite()
elif DATABASE_TYPE == 2:
    manager = MySQL()
else:
    # TODO : Add log message
    manager = SQLite()


text:
<?php

namespace App\Jobs;

use App\Models\FeedItem;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class MarkFeedItemAsRead implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * @var FeedItem
     */
    protected $feedItem;

    /**
     * Create a new job instance.
     *
     * @param FeedItem $feedItem
     * @return void
     */
    public function __construct(FeedItem $feedItem)
    {
        $this->feedItem = $feedItem;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->feedItem->read_at) {
            return;
        }

        $this->feedItem->read_at = now();

        $this->feedItem->save();
    }
}


text:
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			actor.h
  \date			Apr 2013
  \author		TNick

  \brief		Contains the definition for Actor class

*//*

 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Please read COPYING and README files in root folder
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
#ifndef __ACTOR_INC__
#define __ACTOR_INC__
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include    <april/april.h>
#include    <april/logic/component.h>
#include    <april/logic/dna.h>

/*  INCLUDES    ============================================================ */
//
//
//
//
/*  DEFINITIONS    --------------------------------------------------------- */

namespace   april    {

class World;
class Sensor;
class Actuator;
class Brain;
class Actor;
class Reflex;
class Director;

/*  DEFINITIONS    ========================================================= */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */

/**
*	@brief	An active ocupier of the world
*
*	When an actor is first constructed it is not alive. This allows the
*	caller to initialise it, decode, DNA, ... Once the actor is made alive
*	using makeAlive() it will recieve time ticks from the World via
*	doSteps(). Because the world may be runned in a multi-thread
*	environment doSteps() also recieves the number of time units that passed
*	since the actor was last called.
*
*	doSteps() substracts the constant cost from the current energy and
*	if the energy is exhausted the actor dies (sends World::actorDies() to
*	parent world). Same happens if the actor reaches its \b death_ age.
*
*	doSteps() iterates components and sends them ActorComp::doSteps().
*	The order is following:
*	- sensors (may generate input for reflexes and brains)
*	- reflexes (may generate input for brains and actuators)
*	- brains (may generate input for actuators)
*	- actuators (may alter outside world)
*
*/
class
	APRILSHARED_EXPORT
	Actor		: public Component		{
	BBM_TRACK( Actor );

	//
	//
	//
	//
	/*  DEFINITIONS    ----------------------------------------------------- */

	friend class Director;
	friend class Sensor;
	friend class Actuator;
	friend class World;
	friend class Reflex;
	friend class Brain;
	friend class ActorFactory;

	/*  DEFINITIONS    ===================================================== */
	//
	//
	//
	//
	/*  DATA    ------------------------------------------------------------ */

private:

	//! the world where we belong
	World *					world_;

	//! header for the list of sensors
	List2Dh					sensors_;

	//! header for the list of actuators
	List2Dh					actuators_;

	//! header for the list of reflexes
	List2Dh					reflexes_;

	//! header for the list of brains
	List2Dh					brains_;

	//! the DNA of this actor
	DNA						dna_;

	//! the kind cached here (also present in DNA)
	ID						kind_;

	//! time of birth
	quint64					birth_;

	//! time of death
	quint64					death_;

	//! current age
	quint64					age_;

	//! current energy reserve
	quint64					energy_;

	//! running cost (energy substracted from energy_ on each time step)
	/**
	 * This value is cached here from DNA::cost().
	 */
	quint64					cost_;

	//! alive or dead
	bool					alive_;

	/*  DATA    ============================================================ */
	//
	//
	//
	//
	/*  FUNCTIONS    ------------------------------------------------------- */

public:

	/**
	*	@brief	constructor; creates an invalid actor that needs
	*	further initialisation
	*/
	Actor				( World * w );

	//! constructor method; creates and loads an actor from QSettings
	Q_REQUIRED_RESULT
	static Actor *		fromStg					( World * w, QSettings & s );

protected:

	/**
	*	@brief	destructor;
	*/
	virtual				~Actor					( void );

public:

	//! save to a QSettings object
	virtual bool		save					( QSettings & s ) const;

	//! load from a QSettings object
	virtual bool		load					( QSettings & s );

	//! associated ID, if any
	virtual ID			identificator			( void ) const
	{ return kind(); }

	//! associated factory, if any
	virtual Factory *	factory					( void ) const;

protected:

	//! kill the actor; both the actor and the world use this method
	/**
	 * The world is informed using World::actorDies(). Any remaining energy
	 * remaining inside is taken by the world.
	 */
	void				killMe					( void );

	/* OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO */
	/** @name Allow access to components
	 */
	///@{

public:

	//! first sensor in internal list
	Sensor *			firstSensor				( void ) const;

	//! first actuator in internal list
	Actuator *			firstActuator			( void ) const;

	//! first reflex in internal list
	Reflex *			firstReflex				( void ) const;

	//! first brain in internal list
	Brain *				firstBrain				( void ) const;

	///@}
	/* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo */

	/* OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO */
	/** @name find components based on their ID
	 */
	///@{

public:

	//! first sensor in internal list
	Sensor *			findSensor				( ID id ) const;

	//! first actuator in internal list
	Actuator *			findActuator			( ID id ) const;

	//! first reflex in internal list
	Reflex *			findReflex				( ID id ) const;

	//! first brain in internal list
	Brain *				findBrain				( ID id ) const;

	///@}
	/* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo */

	/* OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO */
	/** @name infromation about the actor
	 */
	///@{

public:

	//! the world where we belong
	inline World *		world					( void ) const
	{ return world_; }

	//! tell the kind
	inline ID			kind					( void ) const
	{ return kind_; }

	//! get the name of the kind (shortcut for UniqueId::name() )
	QString				kindName				( void ) const;

	//! the DNA of this actor
	const DNA &			dna						( void ) const
	{ return dna_; }

	//! tell the date of birth
	inline quint64		birth					( void ) const
	{ return birth_; }

	//! tell the date of death
	inline quint64		death					( void ) const
	{ return death_; }

	//! tell the age of this actor
	inline quint64		age						( void ) const
	{ return age_; }

	//! tell the life span of this actor
	inline quint64		toLive					( void ) const
	{ return death_-birth_; }

	//! own energy reserve
	quint64				energy					( void ) const
	{ return energy_; }

	//! total energy packed in this agent (the agent itself and the compoenets)
	quint64				totalEnergy				( void ) const;

	//! energy cost
	quint64				cost					( void ) const
	{ return cost_; }

	//! alive or dead
	bool				isAlive					( void ) const
	{ return alive_; }

	//! tell if this is the moment when the agent dies
	inline bool			dies					( void ) const
	{ return (birth_+age_ >= death_); }

	///@}
	/* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo */

	/* OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO */
	/** @name Changing the actor's internals
	 */
	///@{

protected:

	//! set the DNA to provided sequence (intended for ActorFactory)
	inline void			setDNA					( const DNA & src )
	{ dna_ = src; }

	//! load the components of the actor from the DNA
	bool				decodeDNA				( void );

	//! add an Actuator
	bool				addActuator				( Actuator * act );

	//! add a Sensor
	bool				addSensor				( Sensor * act );

	//! add a Reflex
	bool				addReflex				( Reflex * act );

	//! add a Brain
	bool				addBrain				( Brain * act );

	//! remove an Actuator
	bool				remActuator				( Actuator * act );

	//! remove a Sensor
	bool				remSensor				( Sensor * act );

	//! remove a Reflex
	bool				remReflex				( Reflex * act );

	//! remove a Brain
	bool				remBrain				( Brain * act );

	//! perform steps (called by the World)
	void				doSteps					( int steps  = 1 );

	//! make the actor alive
	void				makeAlive				( void );

	//! set total energy (used by the world to initialise and terminate actor)
	void				setEnergy				( quint64 new_val )
	{ energy_ = new_val; }

	///@}
	/* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo */

	/*  FUNCTIONS    ======================================================= */
	//
	//
	//
	//

};	/*	class Actor	*/

/*  CLASS    =============================================================== */
//
//
//
//

}   //  namespace   april

#endif // __ACTOR_INC__
/* ------------------------------------------------------------------------- */
/* ========================================================================= */


text:
This repository contains code examples and explanations that I'm using to teach absolute beginners.

The official documentation at MSDN (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/)
provides a much better overview of the language.

The code shown here is intended only for beginners, not advanced programmers.

If you already know how to program, you're much better off reading the official documentation and programming guide.


text: <video src="../../../media/content/test.mp4" onbeforeload="print('PASS', 'green'); if (window.layoutTestController) window.layoutTestController.notifyDone(); return false;" onload="print('FAIL', 'red'); if (window.layoutTestController) window.layoutTestController.notifyDone();"></video>


text:
package logger

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"strings"
)

func init() {
	showNumberLine, _ := beego.AppConfig.Bool("logger.numberLine")
	levelString := beego.AppConfig.String("logger.level")
	logModels := beego.AppConfig.Strings("logger.logger")
	for _, logModel := range logModels {
		if logModel == "console" {
			beego.SetLogger("console", "")
		}
		if logModel == "file" {
			filename := beego.AppConfig.String("logger.filename")
			config := fmt.Sprintf(`{"filename":"%s","maxdays":30}`, filename)
			beego.SetLogger("file", config)
		}
	}
	if showNumberLine {
		beego.SetLogFuncCall(showNumberLine)
	}
	level, _ := Levelify(levelString)
	beego.SetLevel(level)
}
func Levelify(levelString string) (int, error) {
	upperLevelString := strings.ToUpper(levelString)
	level, ok := levels[upperLevelString]
	if !ok {
		expected := strings.Join(levelKeys, ", ")
		return logs.LevelError, fmt.Errorf("Unknown LogLevel string '%s', expected one of [%s]", levelString, expected)
	}
	return level, nil
}

var levels = map[string]int{
	"DEBUG":    logs.LevelDebug,
	"INFO":     logs.LevelInformational,
	"WARN":     logs.LevelWarning,
	"ERROR":    logs.LevelError,
	"CRITICAL": logs.LevelCritical,
}

var levelKeys = []string{"DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"}


text:
package com.msopentech.odatajclient.engine.data.metadata.edm.v4;

public enum OnDeleteAction {

    Cascade,
    None,
    SetNull,
    SetDefault;

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.serviceusage.v1.model;

/**
 * Response message for the `DisableService` method. This response message is assigned to the
 * `response` field of the returned Operation when that operation is done.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Service Usage API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class DisableServiceResponse extends com.google.api.client.json.GenericJson {

  /**
   * The new state of the service after disabling.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleApiServiceusageV1Service service;

  /**
   * The new state of the service after disabling.
   * @return value or {@code null} for none
   */
  public GoogleApiServiceusageV1Service getService() {
    return service;
  }

  /**
   * The new state of the service after disabling.
   * @param service service or {@code null} for none
   */
  public DisableServiceResponse setService(GoogleApiServiceusageV1Service service) {
    this.service = service;
    return this;
  }

  @Override
  public DisableServiceResponse set(String fieldName, Object value) {
    return (DisableServiceResponse) super.set(fieldName, value);
  }

  @Override
  public DisableServiceResponse clone() {
    return (DisableServiceResponse) super.clone();
  }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Highlight plugin | Trumbowyg</title>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.13.0/themes/prism-tomorrow.css">
    <link rel="stylesheet" href="../../css/main.css">

Highlight plugin

Basic usage

                This plugin allow you to add an code highlighter in Trumbowyg.

            Read highlight plugin documentation

Just press plugin button and paste code there!

The code

$('#editor')
.trumbowyg({
    btns: [
        ['highlight']
    ]
});

Setup

In head tag

<!-- Import prismjs stylesheet -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.13.0/themes/prism.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/plugins/line-highlight/prism-line-highlight.min.css">

At the end of body

<!-- Import jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-3.3.1.min.js"><\/script>')</script>
<!-- Import prismjs -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js"></script>
<!-- Import prismjs line highlight plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/plugins/line-highlight/prism-line-highlight.min.js"></script>


text:
<?php

namespace app\modules\cms\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\cms\models\PostCategory;

/**
 * PostCategorySearch represents the model behind the search form about `app\modules\cms\models\PostCategory`.
 */
class PostCategorySearch extends PostCategory
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'pid', 'level', 'cover', 'sort', 'created_at', 'status'], 'integer'],
            [['code', 'name', 'body', 'seo_title', 'seo_keywords', 'seo_description'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = PostCategory::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'pid' => $this->pid,
            'level' => $this->level,
            'cover' => $this->cover,
            'sort' => $this->sort,
            'created_at' => $this->created_at,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'code', $this->code])
            ->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'body', $this->body])
            ->andFilterWhere(['like', 'seo_title', $this->seo_title])
            ->andFilterWhere(['like', 'seo_keywords', $this->seo_keywords])
            ->andFilterWhere(['like', 'seo_description', $this->seo_description]);

        return $dataProvider;
    }
}


text:
package hu.sztaki.ilab.longneck.process.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import hu.sztaki.ilab.longneck.Field;
import hu.sztaki.ilab.longneck.RecordImplForTest;
import hu.sztaki.ilab.longneck.TestCase;
import hu.sztaki.ilab.longneck.bootstrap.CompactProcess;
import hu.sztaki.ilab.longneck.bootstrap.Repository;
import hu.sztaki.ilab.longneck.process.FrameAddressResolver;
import hu.sztaki.ilab.longneck.process.LongneckProcess;
import hu.sztaki.ilab.longneck.process.block.Block;
import hu.sztaki.ilab.longneck.process.block.CloneRecord;
import hu.sztaki.ilab.longneck.process.block.SetNull;

import org.junit.*;

import static org.junit.Assert.*;

/**
 *
 * @author Geszler Döme <gdome@ilab.sztaki.hu>
 */

public class ProcessTesterTest {

    @Test
    public void testTesterBySetNullExample() {

        // Init process
        FrameAddressResolver frameAddressResolver = new FrameAddressResolver();
        Properties runtimeProperties = new Properties();
        Repository repository = new Repository();
        LongneckProcess process = new LongneckProcess();

        // Init blocks

        SetNull snBlock = new SetNull();
        List<String> fieldNames = new ArrayList<String>();
        fieldNames.add("id");
        snBlock.setApplyTo(fieldNames);
        List<Block> blocks = new ArrayList<Block>();
        blocks.add(snBlock);
        process.setBlocks(blocks);

        // Set test cases

        TestCase testCase = new TestCase();
        RecordImplForTest sourceRecord = new RecordImplForTest();
        sourceRecord.setRole("source");
        sourceRecord.add(new Field("id", "42"));
        testCase.addRecord(sourceRecord);
        RecordImplForTest targetRecord = new RecordImplForTest();
        targetRecord.setRole("target");
        targetRecord.add(new Field("id", null));
        testCase.addRecord(targetRecord);

        List<TestCase> testCases = new ArrayList<TestCase>();
        testCases.add(testCase);
        process.setTestCases(testCases);

        CompactProcess cProcess = new CompactProcess(process, repository,
            frameAddressResolver, runtimeProperties);

        ProcessTester tester = new ProcessTester(cProcess, true);

        assertTrue(tester.testAll());

        // Add a test that fails

        TestCase testCase2 = new TestCase();
        RecordImplForTest sourceRecord2 = new RecordImplForTest();
        sourceRecord2.setRole("source");
        sourceRecord2.add(new Field("id", "42"));
        testCase2.addRecord(sourceRecord2);
        RecordImplForTest targetRecord2 = new RecordImplForTest();
        targetRecord2.setRole("target");
        targetRecord2.add(new Field("id", "42"));
        testCase2.addRecord(targetRecord2);

        testCases.add(testCase2);

        assertFalse(tester.testAll());
    }

    @Test
    public void testTesterByClone() {

        // Init process
        FrameAddressResolver frameAddressResolver = new FrameAddressResolver();
        Properties runtimeProperties = new Properties();
        Repository repository = new Repository();
        LongneckProcess process = new LongneckProcess();

        // Init blocks

        CloneRecord clBlock = new CloneRecord();
        List<Block> blocks = new ArrayList<Block>();
        blocks.add(clBlock);
        process.setBlocks(blocks);

        // Set test cases

        TestCase testCase = new TestCase();
        RecordImplForTest sourceRecord = new RecordImplForTest();
        sourceRecord.setRole("source");
        sourceRecord.add(new Field("id", "42"));
        testCase.addRecord(sourceRecord);
        RecordImplForTest targetRecord = new RecordImplForTest();
        targetRecord.setRole("target");
        targetRecord.add(new Field("id", "42"));
        testCase.addRecord(targetRecord);
        RecordImplForTest targetRecord2 = new RecordImplForTest();
        targetRecord2.setRole("target");
        targetRecord2.add(new Field("id", "42"));
        testCase.addRecord(targetRecord2);

        List<TestCase> testCases = new ArrayList<TestCase>();
        testCases.add(testCase);
        process.setTestCases(testCases);

        CompactProcess cProcess = new CompactProcess(process, repository,
            frameAddressResolver, runtimeProperties);

        ProcessTester tester = new ProcessTester(cProcess, true);

        assertTrue(tester.testAll());

        // Add a test that fails

        TestCase testCase2 = new TestCase();
        testCase2.addRecord(sourceRecord);
        testCase2.addRecord(targetRecord);

        assertFalse(tester.testAll());
    }

    @Test
    public void testTesterByClone2() {

        // Init process
        FrameAddressResolver frameAddressResolver = new FrameAddressResolver();
        Properties runtimeProperties = new Properties();
        Repository repository = new Repository();
        LongneckProcess process = new LongneckProcess();

        // Init blocks

        CloneRecord clBlock = new CloneRecord();
        List<Block> blocks = new ArrayList<Block>();
        blocks.add(clBlock);
        process.setBlocks(blocks);

        // Set test cases

        TestCase testCase = new TestCase();
        RecordImplForTest sourceRecord = new RecordImplForTest();
        sourceRecord.setRole("source");
        sourceRecord.add(new Field("id", "42"));
        testCase.addRecord(sourceRecord);
        RecordImplForTest targetRecord = new RecordImplForTest();
        targetRecord.setRole("target");
        targetRecord.add(new Field("id", "42"));
        testCase.addRecord(targetRecord);
        RecordImplForTest targetRecord2 = new RecordImplForTest();
        targetRecord2.setRole("target");
        targetRecord2.add(new Field("id", "41"));
        testCase.addRecord(targetRecord2);

        List<TestCase> testCases = new ArrayList<TestCase>();
        testCases.add(testCase);
        process.setTestCases(testCases);

        CompactProcess cProcess = new CompactProcess(process, repository,
            frameAddressResolver, runtimeProperties);

        ProcessTester tester = new ProcessTester(cProcess, true);

        /* The process test fails, because there is no perfect
         * matching in the observed-expected target record graph.
         */

        assertFalse(tester.testAll());
    }
}


text:
NS_CC_EXT_BEGIN

extern CCPoint getAbsolutePosition(const CCPoint &pt, int nType, const CCSize &containerSize, const char *pPropName);

extern void setRelativeScale(CCNode *pNode, float fScaleX, float fScaleY, int nType, const char* pPropName);

NS_CC_EXT_END

#endif // __CCB_CCNODE_RELATIVEPOSITIONING_H__


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

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Apple Strudel (Apfelstrudel)</title>
      <categories>
        <cat>Penndutch</cat>
        <cat>Breads</cat>
        <cat>Fruits</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>2 1/2</qty>
          <unit>cups</unit></amt>
        <item>Flour</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>teaspoon</unit></amt>
        <item>Salt</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Shortening</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit/></amt>
        <item>Egg, slightly beaten</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Water, warm</item></ing>
      <ing>
        <amt>
          <qty>5</qty>
          <unit>cups</unit></amt>
        <item>Apple, sliced</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Brown sugar</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Raisins</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Nuts, chopped</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit>tablespoons</unit></amt>
        <item>Butter, melted</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>teaspoons</unit></amt>
        <item>Cinnamon</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Lemon, grated rind of</item></ing></ingredients>
    <directions>
      <step>  Sift the flour and salt together. Cut in the 2 Tbsp shortening and add the
  eggs and water. Knead well, then throw or beat dough against board until it
  blisters. Stand it in a warm place under a cloth for 20 minutes. Cover the
  kitchen table with a small white cloth and flour it. Put dough on it. Pull
  out with hands very carefully to thickness of tissue paper. Spread with
  mixture made of the sliced apples, melted butter, raisins, nuts, brown
  sugar, cinnamon and grated lemon rind. Fold in outer edges and roll about 4
  inches wide. Bake at 450-F for 10 minutes, reduce heat to 400-F and
  continue to bake about 20 minutes. Let cool. Cut in slices about 2 inches
  wide. Source: Pennsylvania Dutch Cook Book - Fine Old Recipes, Culinary
  Arts Press, 1936.

  From Gemini's MASSIVE MealMaster collection at www.synapse.com/~gemini

</step></directions></recipe></recipeml>


text:
package org.innovateuk.ifs.project.monitoringofficer.form;

import org.innovateuk.ifs.controller.BaseBindingResultTarget;

import javax.validation.constraints.NotNull;

public class MonitoringOfficerAssignProjectForm extends BaseBindingResultTarget {

    @NotNull(message = "{validation.monitoring-officer.assign.required}")
    private Long projectId;

    public Long getProjectId() {
        return projectId;
    }

    public void setProjectId(long projectId) {
        this.projectId = projectId;
    }
}


text:
import { Optional, Strings } from '@ephox/katamari';
import { SugarElement } from '@ephox/sugar';

import * as TextSearch from '../alien/TextSearch';
import DOMUtils from '../api/dom/DOMUtils';
import * as AutocompleteTag from './AutocompleteTag';
import { getText, isValidTextRange, isWhitespace } from './AutocompleteUtils';

export interface AutocompleteContext {
  range: Range;
  text: string;
  trigger: string;
}

const stripTrigger = (text: string, trigger: string) => text.substring(trigger.length);

const findTrigger = (text: string, index: number, trigger: string): Optional<number> => {
  // Identify the `char` in, and start the text from that point forward. If there is ever any whitespace, fail
  let i: number;
  const firstChar = trigger.charAt(0);

  for (i = index - 1; i >= 0; i--) {
    const char = text.charAt(i);
    if (isWhitespace(char)) {
      return Optional.none();
    }

    if (firstChar === char && Strings.contains(text, trigger, i, index)) {
      break;
    }
  }

  return Optional.some(i);
};

const findStart = (dom: DOMUtils, initRange: Range, trigger: string, minChars: number = 0): Optional<AutocompleteContext> => {
  if (!isValidTextRange(initRange)) {
    return Optional.none();
  }

  const buffer = { text: '', offset: 0 };

  const findTriggerIndex = (element: Text, offset: number, text: string) => {
    buffer.text = text + buffer.text;
    buffer.offset += offset;
    // Stop searching by just returning the current offset if whitespace was found (eg Optional.none())
    // and we'll handle the final checks below instead
    return findTrigger(buffer.text, buffer.offset, trigger).getOr(offset);
  };

  const root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  return TextSearch.repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerIndex, root).bind((spot) => {
    const range = initRange.cloneRange();
    range.setStart(spot.container, spot.offset);
    range.setEnd(initRange.endContainer, initRange.endOffset);

    // If the range is collapsed then we didn't find a match so abort
    if (range.collapsed) {
      return Optional.none();
    }

    const text = getText(range);
    const triggerIndex = text.lastIndexOf(trigger);

    // If the match doesn't start with the trigger (eg whitespace found) or the match is less than the minimum number of chars then abort
    if (triggerIndex !== 0 || stripTrigger(text, trigger).length < minChars ) {
      return Optional.none();
    } else {
      return Optional.some({ text: stripTrigger(text, trigger), range, trigger });
    }
  });
};

const getContext = (dom: DOMUtils, initRange: Range, trigger: string, minChars: number = 0): Optional<AutocompleteContext> =>
  AutocompleteTag.detect(SugarElement.fromDom(initRange.startContainer)).fold(
    () => findStart(dom, initRange, trigger, minChars),
    (elm) => {
      const range = dom.createRng();
      range.selectNode(elm.dom);
      const text = getText(range);
      return Optional.some({ range, text: stripTrigger(text, trigger), trigger });
    }
  );

export {
  findTrigger, // Exposed for testing.
  getContext
};


text:
package org.apache.mxnet.io

import org.apache.mxnet._
import org.slf4j.LoggerFactory
import java.util.concurrent.Semaphore

import org.apache.mxnet.DType.DType

import scala.collection.immutable.ListMap

/**
 * Base class for prefetching iterators. Takes one or more DataIters
 * and combine them with prefetching.
 *
 * @param iters list of DataIters
 * @param dataNames
 * @param labelNames
 */
class PrefetchingIter(
    iters: IndexedSeq[DataIter],
    dataNames: IndexedSeq[Map[String, String]] = null,
    labelNames: IndexedSeq[Map[String, String]] = null) extends DataIter {

  private val logger = LoggerFactory.getLogger(classOf[PrefetchingIter])

  require(iters.nonEmpty, "Iters length must be greater than 0")

  @deprecated("Please use provideDataDesc instead", "1.3.0")
  override def provideData: ListMap[String, Shape] = {
    if (dataNames == null) {
      iters.map(_.provideData).reduce(_ ++ _)
    } else {
      iters.map(_.provideData).zip(dataNames).map { case (providedData, names) =>
        providedData.map { case (oldName, shape) => names(oldName) -> shape }
      }.reduceLeft(_ ++ _)
    }
  }

  @deprecated("Please use provideDataDesc instead", "1.3.0")
  override def provideLabel: ListMap[String, Shape] = {
    if (labelNames == null) {
      iters.map(_.provideLabel).reduce(_ ++ _)
    } else {
      iters.map(_.provideLabel).zip(labelNames).map { case (providedLabel, names) =>
        providedLabel.map { case (oldName, shape) => names(oldName) -> shape }
      }.reduceLeft(_ ++ _)
    }
  }

  override def provideDataDesc: IndexedSeq[DataDesc] = {
    if (dataNames == null) {
      iters.flatMap(_.provideDataDesc)
    } else {
      iters.map(_.provideDataDesc).zip(dataNames).flatMap { case (providedDataDesc, names) =>
          providedDataDesc.map(desc =>
            new DataDesc(names(desc.name), desc.shape, desc.dtype, desc.layout))
      }
    }
  }

  override def provideLabelDesc: IndexedSeq[DataDesc] = {
    if (labelNames == null) {
      iters.flatMap(_.provideLabelDesc)
    } else {
      iters.map(_.provideLabelDesc).zip(labelNames).flatMap { case (providedLabelDesc, names) =>
        providedLabelDesc.map(desc =>
          new DataDesc(names(desc.name), desc.shape, desc.dtype, desc.layout))
      }
    }
  }

  private val _batchSize: Int = this.provideDataDesc.head.shape(0)
  private val dataReady: IndexedSeq[Semaphore] =
                                        (0 until iters.length).map(i => new Semaphore(0))
  private val dataTaken: IndexedSeq[Semaphore] =
                                        (0 until iters.length).map(i => new Semaphore(1))

  @volatile private var started: Boolean = true
  private var currentBatch: DataBatch = null
  private val nextBatch: Array[DataBatch] = (0 until iters.length).map { i =>
    new DataBatch(null, null, null, 0)
  }.toArray

  // thread entry
  def prefetchFunc(i: Int): Runnable = new Runnable {
    override def run(): Unit = {
      while (started) {
        dataTaken(i).acquire()
        if (started) {
          try {
            nextBatch(i) = iters(i).next()
          } catch {
            case ex: NoSuchElementException => nextBatch(i) = null
          }
        }
        dataReady(i).release()
      }
    }
  }

  private val prefetchThreads =
    for (i <- 0 until iters.length) yield new Thread(prefetchFunc(i))
  prefetchThreads.foreach(_.start())

  override def next(): DataBatch = currentBatch

  /**
   * reset the iterator
   */
  override def reset(): Unit = {
    for (e <- dataReady) e.acquire()
    for (i <- iters) i.reset()
    for (e <- dataTaken) e.release()
  }

  override def batchSize: Int = this._batchSize

  /**
   * get data of current batch
   * @return the data of current batch
   */
  override def getData(): IndexedSeq[NDArray] = currentBatch.data

  /**
   * Get label of current batch
   * @return the label of current batch
   */
  override def getLabel(): IndexedSeq[NDArray] = currentBatch.label

  /**
   * the index of current batch
   * @return
   */
  override def getIndex(): IndexedSeq[Long] = currentBatch.index

  /**
    * get the number of padding examples
    * in current batch
    * @return number of padding examples in current batch
    */
  override def getPad(): Int = this.currentBatch.pad

  override def hasNext: Boolean = {
    for (e <- dataReady) e.acquire()
    if (nextBatch(0) == null) {
      for (i <- nextBatch) {
        assert(i == null, "Number of entry mismatches between iterators")
      }
      for (e <- dataReady) e.release()
      false
    } else {
      for (batch <- nextBatch) {
        assert(batch.pad == nextBatch(0).pad,
            "Number of entry mismatches between iterators")
      }
      val datas = for (batch <- nextBatch) yield batch.data
      val labels = for (batch <- nextBatch) yield batch.label
      currentBatch = new DataBatch(datas.toIndexedSeq.flatten,
        labels.toIndexedSeq.flatten,
        nextBatch(0).index,
        nextBatch(0).pad)
      for (e <- dataTaken) e.release()
      true
    }
  }

  /**
   * Stop all its internal prefetching threads.
   * The object shall never be used after it is disposed.
   */
  def dispose(): Unit = {
    started = false
    for (e <- dataTaken) e.release()
    for (t <- prefetchThreads) t.join()
  }
}


text:
import Logger from './Logger';
import config from '../config';

export default class Console implements Logger {
  protected levels = [ 'ALL', 'DEBUG', 'VERBOSE', 'INFO', 'WARNING', 'ERROR', 'NONE' ];

  public debug(message: string): void {
    if (this.levels.indexOf(config.logger.level) > 1) {
      return;
    }
    console.log(message);
  }

  public verbose(message: string): void {
    if (this.levels.indexOf(config.logger.level) > 2) {
      return;
    }
    console.log(message);
  }

  public info(message: string): void {
    if (this.levels.indexOf(config.logger.level) > 3) {
      return;
    }
    console.log(message);
  }

  public warning(message: string): void {
    if (this.levels.indexOf(config.logger.level) > 4) {
      return;
    }
    console.warn(message);
  }

  public error(message: string): void {
    if (this.levels.indexOf(config.logger.level) > 5) {
      return;
    }
    console.error(message);
  }

  /**
   * What a terrible failure
   * @param message
   */
  public wtf(message: string): void {
    console.error(message);
  }
}


text:
package fredboat.audio.player;

import fredboat.commandmeta.abs.CommandContext;
import fredboat.shared.constant.BotConstants;
import net.dv8tion.jda.core.entities.Guild;

public class PlayerLimitManager {

    // A negative limit means unlimited
    private static int limit = -1;

    public static boolean checkLimit(Guild guild) {
        GuildPlayer guildPlayer = PlayerRegistry.getExisting(guild);
        //noinspection SimplifiableIfStatement
        if (guildPlayer != null && guildPlayer.getTrackCount() > 0)
            return true;

        return limit < 0
                || PlayerRegistry.getPlayingPlayers().size() < limit;

    }

    public static boolean checkLimitResponsive(CommandContext context) {
        boolean b = checkLimit(context.guild);

        if (!b) {
            String patronUrl = "<" + BotConstants.DOCS_DONATE_URL + ">";
            String msg = context.i18nFormat("playersLimited", limit, patronUrl);
            context.reply(msg);
        }

        return b;
    }

    public static int getLimit() {
        return limit;
    }

    public static void setLimit(int limit) {
        PlayerLimitManager.limit = limit;
    }
}


text:
namespace Microsoft.Azure.Management.DataLake.Store
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.DataLake;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using Newtonsoft.Json;

    /// <summary>
    /// Creates an Azure Data Lake Store filesystem client.
    /// </summary>
    public partial interface IDataLakeStoreFileSystemManagementClient : System.IDisposable
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        JsonSerializerSettings SerializationSettings { get; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        JsonSerializerSettings DeserializationSettings { get; }

        /// <summary>
        /// Credentials needed for the client to connect to Azure.
        /// </summary>
        ServiceClientCredentials Credentials { get; }

        /// <summary>
        /// Client Api Version.
        /// </summary>
        string ApiVersion { get; }

        /// <summary>
        /// Gets the URI used as the base for all cloud service requests.
        /// </summary>
        string AdlsFileSystemDnsSuffix { get; set; }

        /// <summary>
        /// Gets or sets the preferred language for the response.
        /// </summary>
        string AcceptLanguage { get; set; }

        /// <summary>
        /// Gets or sets the retry timeout in seconds for Long Running
        /// Operations. Default value is 30.
        /// </summary>
        int? LongRunningOperationRetryTimeout { get; set; }

        /// <summary>
        /// When set to true a unique x-ms-client-request-id value is generated
        /// and included in each request. Default is true.
        /// </summary>
        bool? GenerateClientRequestId { get; set; }

        /// <summary>
        /// Gets the IFileSystemOperations.
        /// </summary>
        IFileSystemOperations FileSystem { get; }

    }
}


text:
package org.elasticsearch.xpack.security.authc.support;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.discovery.DiscoveryModule;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.xpack.core.XPackSettings;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;

public class HttpTlsRuntimeCheck {

    private static final Logger logger = LogManager.getLogger(HttpTlsRuntimeCheck.class);

    private final AtomicBoolean initialized = new AtomicBoolean(false);
    private final Boolean httpTlsEnabled;
    private final SetOnce<Transport> transportReference;
    private final Boolean securityEnabled;
    private final boolean singleNodeDiscovery;
    private boolean enforce;

    public HttpTlsRuntimeCheck(Settings settings, SetOnce<Transport> transportReference) {
        this.transportReference = transportReference;
        this.securityEnabled = XPackSettings.SECURITY_ENABLED.get(settings);
        this.httpTlsEnabled = XPackSettings.HTTP_SSL_ENABLED.get(settings);
        this.singleNodeDiscovery = "single-node".equals(DiscoveryModule.DISCOVERY_TYPE_SETTING.get(settings));
    }

    public void checkTlsThenExecute(Consumer<Exception> exceptionConsumer, String featureName, Runnable andThen) {
        // If security is enabled, but TLS is not enabled for the HTTP interface
        if (securityEnabled && false == httpTlsEnabled) {
            if (false == initialized.get()) {
                final Transport transport = transportReference.get();
                if (transport == null) {
                    exceptionConsumer.accept(new ElasticsearchException("transport cannot be null"));
                    return;
                }
                final boolean boundToLocal = Arrays.stream(transport.boundAddress().boundAddresses())
                    .allMatch(b -> b.address().getAddress().isLoopbackAddress())
                    && transport.boundAddress().publishAddress().address().getAddress().isLoopbackAddress();
                this.enforce = false == boundToLocal && false == singleNodeDiscovery;
                initialized.set(true);
            }
            if (enforce) {
                final ParameterizedMessage message = new ParameterizedMessage(
                    "[{}] requires TLS for the HTTP interface", featureName);
                logger.debug(message);
                exceptionConsumer.accept(new ElasticsearchException(message.getFormattedMessage()));
                return;
            }
        }
        andThen.run();
    }
}


text:
package com.sdk.blendle.models.generated.api;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@Generated("org.jsonschema2pojo")
public class UserEmail {

    @SerializedName("pattern")
    @Expose
    private String pattern;
    @SerializedName("max_length")
    @Expose
    private Integer maxLength;

    /**
     *
     * @return
     *     The pattern
     */
    public String getPattern() {
        return pattern;
    }

    /**
     *
     * @param pattern
     *     The pattern
     */
    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    /**
     *
     * @return
     *     The maxLength
     */
    public Integer getMaxLength() {
        return maxLength;
    }

    /**
     *
     * @param maxLength
     *     The max_length
     */
    public void setMaxLength(Integer maxLength) {
        this.maxLength = maxLength;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(pattern).append(maxLength).toHashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }
        if ((other instanceof UserEmail) == false) {
            return false;
        }
        UserEmail rhs = ((UserEmail) other);
        return new EqualsBuilder().append(pattern, rhs.pattern).append(maxLength, rhs.maxLength).isEquals();
    }

}


text:
package net.ripe.db.whois.update.handler.validator.sets;

import net.ripe.db.whois.common.rpsl.ObjectType;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.update.domain.Action;
import net.ripe.db.whois.update.domain.PreparedUpdate;
import net.ripe.db.whois.update.domain.UpdateContext;
import net.ripe.db.whois.update.domain.UpdateMessages;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class PeeringSetAttributeMustBePresentTest {
    @Mock PreparedUpdate update;
    @Mock UpdateContext updateContext;

    private PeeringSetAttributeMustBePresent subject;

    @Before
    public void setup() {
        subject = new PeeringSetAttributeMustBePresent();

    }

    @Test
    public void testGetActions() {
        assertThat(subject.getActions(), containsInAnyOrder(Action.CREATE, Action.MODIFY));
    }

    @Test
    public void testGetTypes() {
        assertThat(subject.getTypes(), Matchers.contains(ObjectType.PEERING_SET, ObjectType.FILTER_SET));
    }

    @Test
    public void mpPeering_and_peering_present() {
        when(update.getType()).thenReturn(ObjectType.PEERING_SET);
        when(update.getUpdatedObject()).thenReturn(RpslObject.parse("peering-set: prng-ripe\ndescr: description\npeering: AS6845 at 194.102.255.254\nmp-peering: AS702:PRNG-AT-CUSTOMER"));

        subject.validate(update, updateContext);

        verify(updateContext).addMessage(update, UpdateMessages.eitherSimpleOrComplex(ObjectType.PEERING_SET, "peering", "mp-peering"));
    }

    @Test
    public void mpPeering_nor_peering_present() {
        when(update.getType()).thenReturn(ObjectType.PEERING_SET);
        when(update.getUpdatedObject()).thenReturn(RpslObject.parse("peering-set: prng-ripe\ndescr: description"));

        subject.validate(update, updateContext);

        verify(updateContext).addMessage(update, UpdateMessages.neitherSimpleOrComplex(ObjectType.PEERING_SET, "peering", "mp-peering"));
    }

    @Test
    public void only_mpPeering_present() {
        when(update.getType()).thenReturn(ObjectType.PEERING_SET);
        when(update.getUpdatedObject()).thenReturn(RpslObject.parse("peering-set: prng-ripe\ndescr: description\nmp-peering: AS702:PRNG-AT-CUSTOMER"));

        subject.validate(update, updateContext);

        verify(updateContext, never()).addMessage(update, UpdateMessages.eitherSimpleOrComplex(ObjectType.PEERING_SET, "peering", "mp-peering"));
        verify(updateContext, never()).addMessage(update, UpdateMessages.neitherSimpleOrComplex(ObjectType.PEERING_SET, "peering", "mp-peering"));
    }

    @Test
    public void only_peering_present() {
        when(update.getType()).thenReturn(ObjectType.PEERING_SET);
        when(update.getUpdatedObject()).thenReturn(RpslObject.parse("peering-set: prng-ripe\ndescr: description\npeering: AS6845 at 194.102.255.254"));

        subject.validate(update, updateContext);

        verify(updateContext, never()).addMessage(update, UpdateMessages.eitherSimpleOrComplex(ObjectType.PEERING_SET, "peering", "mp-peering"));
        verify(updateContext, never()).addMessage(update, UpdateMessages.neitherSimpleOrComplex(ObjectType.PEERING_SET, "peering", "mp-peering"));
    }

    @Test
    public void filter_and_mpFilter_present() {
        when(update.getType()).thenReturn(ObjectType.FILTER_SET);
        when(update.getUpdatedObject()).thenReturn(RpslObject.parse("filter-set: prng-ripe\ndescr: description\nfilter: AS6845 at 194.102.255.254\nmp-filter: AS702:PRNG-AT-CUSTOMER"));

        subject.validate(update, updateContext);

        verify(updateContext).addMessage(update, UpdateMessages.eitherSimpleOrComplex(ObjectType.FILTER_SET, "filter", "mp-filter"));
    }

    @Test
    public void mpFilter_nor_filter_present() {
        when(update.getType()).thenReturn(ObjectType.FILTER_SET);
        when(update.getUpdatedObject()).thenReturn(RpslObject.parse("filter-set: prng-ripe\ndescr: description"));

        subject.validate(update, updateContext);

        verify(updateContext).addMessage(update, UpdateMessages.neitherSimpleOrComplex(ObjectType.FILTER_SET, "filter", "mp-filter"));
    }

    @Test
    public void only_mpFilter_present() {
        when(update.getType()).thenReturn(ObjectType.FILTER_SET);
        when(update.getUpdatedObject()).thenReturn(RpslObject.parse("filter-set: prng-ripe\ndescr: description\nmp-filter: AS702:PRNG-AT-CUSTOMER"));

        subject.validate(update, updateContext);

        verify(updateContext, never()).addMessage(update, UpdateMessages.eitherSimpleOrComplex(ObjectType.FILTER_SET, "filter", "mp-filter"));
        verify(updateContext, never()).addMessage(update, UpdateMessages.neitherSimpleOrComplex(ObjectType.FILTER_SET, "filter", "mp-filter"));
    }

    @Test
    public void only_filter_present() {
        when(update.getType()).thenReturn(ObjectType.FILTER_SET);
        when(update.getUpdatedObject()).thenReturn(RpslObject.parse("filter-set: prng-ripe\ndescr: description\nfilter: AS6845 at 194.102.255.254"));

        subject.validate(update, updateContext);

        verify(updateContext, never()).addMessage(update, UpdateMessages.eitherSimpleOrComplex(ObjectType.FILTER_SET, "filter", "mp-filter"));
        verify(updateContext, never()).addMessage(update, UpdateMessages.neitherSimpleOrComplex(ObjectType.FILTER_SET, "filter", "mp-filter"));
    }
}


text:
local map = vim.keymap.set
local default_options = {noremap = true, silent = true}

map('n', '<leader>f', '<Plug>(easymotion-s)', default_options)
map('n', '<leader>F', '<Plug>(easymotion-s)', default_options)
map('n', '<leader>w', '<Plug>(easymotion-bd-w)', default_options)
map('n', '<leader>W', '<Plug>(easymotion-bd-W)', default_options)
map('n', '<leader>e', '<Plug>(easymotion-bd-e)', default_options)
map('n', '<leader>E', '<Plug>(easymotion-bd-E)', default_options)

vim.g.EasyMotion_keys = 'asdklöqwertzuiopyxcvbnm,.-fghj'


text:
namespace BcmMigrationTool
{
    using System;
    using System.Collections.Generic;

    public partial class ActivityParentsView
    {
        public int ID { get; set; }
        public int ActivityID { get; set; }
        public System.Guid LinkGUID { get; set; }
        public bool IsDeletedLocally { get; set; }
        public int ContactServiceID { get; set; }
        public System.Guid ParentEntryGUID { get; set; }
        public Nullable<System.Guid> GrandParentEntryGUID { get; set; }
        public Nullable<System.Guid> GreatGrandParentEntryGUID { get; set; }
        public Nullable<System.Guid> ReferredEntryId { get; set; }
        public System.Guid ActivityGUID { get; set; }
        public int ActivityType { get; set; }
        public string ActivityTypeName { get; set; }
        public bool ActivityIsDeletedLocally { get; set; }
        public string Subject { get; set; }
        public Nullable<System.DateTime> ActivityDate { get; set; }
        public Nullable<System.Guid> OwnerID { get; set; }
        public Nullable<System.DateTime> CreatedOn { get; set; }
        public string CreatedBy { get; set; }
        public Nullable<System.DateTime> ModifiedOn { get; set; }
        public Nullable<System.DateTime> ModifiedOnUTC { get; set; }
        public string ModifiedBy { get; set; }
        public Nullable<System.DateTime> ActivityStartTime { get; set; }
        public Nullable<int> ActivityDuration { get; set; }
        public Nullable<System.DateTime> ActivityEndTime { get; set; }
        public string PhoneNumCalled { get; set; }
        public string FromName { get; set; }
        public string ToNames { get; set; }
        public string CCNames { get; set; }
        public Nullable<System.DateTime> ActivitySentTime { get; set; }
        public string ActivityStatus { get; set; }
        public string ActivityPriority { get; set; }
        public Nullable<byte> ActivityPercentComplete { get; set; }
        public string ActivityLocation { get; set; }
        public string LinkToOriginal { get; set; }
        public Nullable<short> LinkToOriginalType { get; set; }
        public string CallType { get; set; }
        public Nullable<long> Version { get; set; }
        public long ContentVersion { get; set; }
        public Nullable<long> HistoryVersion { get; set; }
        public Nullable<long> LinkContentVersion { get; set; }
        public string ActivityNote { get; set; }
        public byte[] CompressedRichText { get; set; }
        public Nullable<int> IconIndex { get; set; }
        public Nullable<System.DateTime> MessageDeliveryTime { get; set; }
        public Nullable<int> GrandParentContactServiceID { get; set; }
        public Nullable<int> GreatGrandParentContactServiceID { get; set; }
        public int ParentType { get; set; }
        public Nullable<int> GrandParentType { get; set; }
        public Nullable<int> GreatGrandParentType { get; set; }
        public Nullable<bool> IsBillable { get; set; }
        public Nullable<int> AttachmentCount { get; set; }
    }
}


text:
- [[Issue #13]] Added support for Linux newlines on Windows and vice versa
- [[Issue #27]] All tools now return a non-zero error code if there are errors
- [[Issue #30]] guard2once can now convert `#if !defined(INCLUDE_GUARD)`
- [[Issue #31]] Added support for all ASCII-compatible file encodings

## [v2.3.0] | 2018-02-05
- Added `*.hxx` to list of header extensions for --recursive
- [[Issue #25]] Added --stdout option

## [v2.2.2] | 2017-10-11
- [[Issue #24]] Fixed once2guard --help

## [v2.2.1] | 2017-10-10
- [[Issue #20]] Fixed --endif-style for UTF-8 files with Python 2
- [[Issue #21]] Fixed handling UTF-8 files on Windows in Python 3
- [[Issue #22]] Improved error reporting for UTF-16 and UTF-32 on Python 3
- [[Issue #23]] Fixed first line of file being ignored for UTF-8 with BOM

## [v2.2.0] | 2017-10-04
- Added support for negative values to 'path' command
- Added 'parents' command to pattern language
- Added option to print guard to checkguard
- [[Issue #16]] Added options to specify #endif style
- [[Issue #19]] The 'path' command's argument is now optional

## [v2.1.0] | 2017-02-14
- Improved heuristics for guessing include guard symbols
- Added 'remove' command to pattern language
- [[Issue #10]] Added option to strip trailing whitespace when removing guards
- [[Issue #14]] Comments immediately following #endif are now accepted
- [[Issue #15]] Include guards with the value 1 are now recognized

## [v2.0.0] | 2016-12-01
- Any include guard pattern is now accepted by default
- Packaged for PyPI
- [[Issue #12]] Added support for Python 3.5
- [[Issue #9]] checkguard no longer warns about files using pragma once
- [[Issue #3]] Added flag to specify the desired include guard convention

## [v1.0.0] | 2016-07-22
- Ex post facto acknowledgement that this project was stable.

[v2.4.0]: https://github.com/cgmb/guardonce/compare/v2.3.0...v2.4.0
[v2.3.0]: https://github.com/cgmb/guardonce/compare/v2.2.2...v2.3.0
[v2.2.2]: https://github.com/cgmb/guardonce/compare/v2.2.1...v2.2.2
[v2.2.1]: https://github.com/cgmb/guardonce/compare/v2.2.0...v2.2.1
[v2.2.0]: https://github.com/cgmb/guardonce/compare/v2.1.0...v2.2.0
[v2.1.0]: https://github.com/cgmb/guardonce/compare/v2.0.0...v2.1.0
[v2.0.0]: https://github.com/cgmb/guardonce/compare/v1.0.0...v2.0.0
[v1.0.0]: https://github.com/cgmb/guardonce/commits/v1.0.0
[Issue #3]: https://github.com/cgmb/guardonce/issues/3
[Issue #9]: https://github.com/cgmb/guardonce/issues/9
[Issue #10]: https://github.com/cgmb/guardonce/issues/10
[Issue #12]: https://github.com/cgmb/guardonce/issues/12
[Issue #13]: https://github.com/cgmb/guardonce/issues/13
[Issue #14]: https://github.com/cgmb/guardonce/issues/14
[Issue #15]: https://github.com/cgmb/guardonce/issues/15
[Issue #16]: https://github.com/cgmb/guardonce/issues/16
[Issue #19]: https://github.com/cgmb/guardonce/issues/19
[Issue #20]: https://github.com/cgmb/guardonce/issues/20
[Issue #21]: https://github.com/cgmb/guardonce/issues/21
[Issue #22]: https://github.com/cgmb/guardonce/issues/22
[Issue #23]: https://github.com/cgmb/guardonce/issues/23
[Issue #24]: https://github.com/cgmb/guardonce/issues/24
[Issue #25]: https://github.com/cgmb/guardonce/issues/25
[Issue #27]: https://github.com/cgmb/guardonce/issues/27
[Issue #30]: https://github.com/cgmb/guardonce/issues/30
[Issue #31]: https://github.com/cgmb/guardonce/issues/31


text:
#include <stdlib.h>
#include <iostream>

#include "gtest/gtest.h"
#include "geopm_error.h"
#include "Exception.hpp"
#include "DeciderFactory.hpp"

class DeciderFactoryTest: public :: testing :: Test
{
    protected:
        void SetUp();
};

void DeciderFactoryTest::SetUp()
{
    setenv("GEOPM_PLUGIN_PATH", ".libs/", 1);
}

TEST_F(DeciderFactoryTest, decider_register)
{
    geopm::DeciderFactory factory;
    std::string dname("power_governing");
    geopm::Decider *d = factory.decider(dname);
    ASSERT_FALSE(d == NULL);

    std::string ans = d->name();
    ASSERT_FALSE(ans.empty());
    EXPECT_EQ(0, ans.compare(dname));

    delete d;
}

TEST_F(DeciderFactoryTest, no_supported_decider)
{
    geopm::DeciderFactory factory;
    geopm::Decider* d = NULL;
    int thrown = 0;
    try {
        d = factory.decider("doesntexist");
    }
    catch (geopm::Exception e) {
        thrown = e.err_value();
    }
    ASSERT_EQ(NULL, d);
    EXPECT_EQ(GEOPM_ERROR_DECIDER_UNSUPPORTED, thrown);
}


text:
package algorithm.leet_91_105;

import algorithm.TreeNode;

/**
 * Created by songheng on 5/6/16.
 */
public class ConstructBinaryTreefromPreorderandInorderTraversal_105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 1) {
            return new TreeNode(preorder[0]);
        }
        return helper(preorder,0,preorder.length-1,inorder,0,inorder.length-1);

    }

    private TreeNode helper(int[] preorder, int pStart, int pEnd, int[] inoder, int nStart, int nEnd) {

        if (pStart == pEnd) {
            return new TreeNode(preorder[pStart]);
        }
        if(pStart > pEnd ){
            return null;
        }
        int root = preorder[pStart];
        TreeNode nNode = new TreeNode(root);
        int pos = nStart;
        for (; pos <= nEnd; pos++) {
            if (inoder[pos] == root) {
                break;
            }
        }
        nNode.left = helper(preorder, pStart + 1, pStart+pos-nStart, inoder, nStart, pos - 1);
        nNode.right = helper(preorder,pStart+pos-nStart+1, pEnd, inoder, pos + 1, nEnd);
        return nNode;
    }

}


text:
package org.omg.MessageRouting;

//
// IDL:omg.org/MessageRouting/UnlimitedPing:1.0
//
final public class UnlimitedPingHolder implements org.omg.CORBA.portable.Streamable
{
    public UnlimitedPing value;

    public
    UnlimitedPingHolder()
    {
    }

    public
    UnlimitedPingHolder(UnlimitedPing initial)
    {
        value = initial;
    }

    public void
    _read(org.omg.CORBA.portable.InputStream in)
    {
        value = UnlimitedPingHelper.read(in);
    }

    public void
    _write(org.omg.CORBA.portable.OutputStream out)
    {
        UnlimitedPingHelper.write(out, value);
    }

    public org.omg.CORBA.TypeCode
    _type()
    {
        return UnlimitedPingHelper.type();
    }
}


text:
h4{
	display:block;
	width:100%;
	clear:both;
	margin:0px;
	padding:10px 0px;
}
.messages{
	display:block;
	clear:both;
	color:#999;
}

a img{
	border:none;
}
a.zoomIt{
	display:block;
	position:relative;
	float:left;
}

/*
ZoomIt customizations

The 3 CSS classes below can be changed to any other CSS class you desire. Just make sure
to fill the parameters with the new classes when starting jqZoomIt().

Default values in script:

- zoomClass			: 'zoomIt_zoomed', // additional styling on zoom container
- zoomLoadingClass	: 'zoomIt_loading', // css class to apply before the big image is fully loaded
- zoomAreaClass		: 'zoomIt_area', // additional styling on zoomed area
*/

/* big image container */
.zoomIt_zoomed{
	border:2px #CCC solid;
	-moz-box-shadow: 10px 10px 5px #888;
	-webkit-box-shadow: 10px 10px 5px #888;
	box-shadow: 10px 10px 5px #888;
}
/* big image loading class */
.zoomIt_loading{
	background:url(../../Resources/public/css/images/loading.gif) center center no-repeat;
}
/* small image zoomed area overlay */
.zoomIt_area{
	border:none;
}


text:
import numpy as np
import time
import logging
import math

# Dimensions of the playing field
WORLD_X = 3000
WORLD_Y = 2000
BEAC_R = 40
BORDER = 15

BEACONS = np.array([[WORLD_X+BEAC_R+BORDER, WORLD_Y / 2.],
                [-BEAC_R-BORDER, WORLD_Y + BEAC_R+BORDER],
                [- BEAC_R-BORDER, - BEAC_R - BORDER]])

# parametres of lidar
MAX_ITENS = 3500  # MAX_ITENS 2600
MAX_DIST = 3700
BEAC_DIST_THRES = 200

class ParticleFilter:
    def __init__(self, particles=500, sense_noise=50, distance_noise=30, angle_noise=0.02, in_x=150, in_y=150, in_angle=0.0, input_queue=None, out_queue=None,color='blue'):
        global BEACONS
        if(color =='blue'):
            BEACONS = np.array([[-BEAC_R-BORDER, WORLD_Y / 2.], [(WORLD_X + BEAC_R+BORDER), (WORLD_Y + BEAC_R+BORDER)], [(WORLD_X + BEAC_R+BORDER), (- BEAC_R - BORDER)]])

        stamp = time.time()
        self.input_queue = input_queue
        self.out_queue = out_queue
        self.particles_num = particles
        self.sense_noise = sense_noise
        self.distance_noise = distance_noise
        self.angle_noise = angle_noise
        self.warning = False
        self.last = (in_x,in_y,in_angle)
        x = np.random.normal(in_x, distance_noise, particles)
        y = np.random.normal(in_y, distance_noise, particles)
        orient = np.random.normal(in_angle, angle_noise, particles) % (2 * np.pi)
        self.particles = np.array([x, y, orient]).T  # instead of np.vstack((x,y,orient)).T
        logging.info('initialize time: '+str(time.time()-stamp))
        # Added Andrei for debug
        self.debug_info = []
        self.start_time = time.time()

    def gaus(self, x, mu=0, sigma=1):
        """calculates the probability of x for 1-dim Gaussian with mean mu and var. sigma"""
        return np.exp(- ((x-mu) ** 2) / (sigma ** 2) / 2.0) / np.sqrt(2.0 * np.pi * (sigma ** 2))

    def move_particles(self, delta, mode="npy"): # delta = [dx,dy,d_rot]
        stamp = time.time()
        x_noise = np.random.normal(0, self.distance_noise, self.particles_num)
        y_noise = np.random.normal(0, self.distance_noise, self.particles_num)
        angle_noise = np.random.normal(0, self.angle_noise, self.particles_num)
        self.particles[:, 0] = self.particles[:, 0] + delta[0] + x_noise
        self.particles[:, 1] = self.particles[:, 1] + delta[1] + y_noise
        self.particles[:, 2] = (self.particles[:, 2] + delta[2] + angle_noise) % (2 * math.pi)
        # START instead of
        # NOT FASTER! NOT RIGHT((
        # # self.particles + noise + delta:
        # # noise - Nx3 : N - num particles, (x_noise, y_noise, angle_noise)
        # self.particles += (np.random.multivariate_normal(mean=np.array([0, 0, 0]),
        #                                     cov=np.diag(np.array([self.distance_noise,
        #                                                    self.distance_noise,
        #                                                    self.angle_noise])),
        #                                     size=(self.particles_num))
        #                    + np.array([delta]))
        # self.particles[:, 2] %= 2 * np.pi
        # END instead of
        #logging.info('Particle Move time: ' + str(time.time() - stamp))

    def resample(self, weights):
        # OLD START
        # n = self.particles_num
        # indices = []
        # C = [0.] + [sum(weights[:i + 1]) for i in range(n)]
        # u0, j = np.random.rand(), 0
        # for u in [(u0 + i) / n for i in range(n)]:
        # START instead of
        n = self.particles_num
        weigths = np.array(weights)
        indices = []
        C = np.append([0.], np.cumsum(weigths))# [0.] + [sum(weights[:i + 1]) for i in range(n)]
        j = 0
        u0 = (np.random.rand() + np.arange(n))/n
        for u in u0: #[(u0 + i) / n for i in range(n)
        # END intsead of
            while j < len(C) and u > C[j]:
                j += 1
            indices += [j - 1]
        return indices

    def calculate_main(self):
        stamp = time.time()
        x = np.mean(self.particles[:, 0])
        y = np.mean(self.particles[:, 1])
        zero_elem = self.particles[0, 2]
        temporary = ((self.particles[:, 2]-zero_elem+np.pi) % (2.0 * np.pi))+zero_elem-np.pi
        orient = np.mean(temporary)
        answer = (x, y, orient)
        #logging.info('main_calculation time' + str(time.time() - stamp))
        #logging.info("Particle Filter coordinates: "+str(answer))
        return answer

    def particle_sense(self, scan):
        stamp = time.time()
        angle, distance = get_landmarks(scan)
        x_coords, y_coords = p_trans(angle,distance)
        weights = self.weights(x_coords,y_coords)
        if self.warning:
            return
            x = np.random.normal(self.last[0], 150, self.particles_num)
            y = np.random.normal(self.last[1], 150, self.particles_num)
            orient = np.random.normal(self.last[2], np.pi, self.particles_num) % (2 * np.pi)
            self.particles = np.array([x, y, orient]).T  # instead of np.vstack((x,y,orient)).T
            self.warning = False
            logging.info('particle_sense time :' + str(time.time() - stamp) + " points: " + str(len(x_coords)))
            return self.particles
        self.particles = self.particles[self.resample(weights), :]
        logging.info('particle_sense time :' + str(time.time() - stamp)+" points: "+str(len(x_coords)))
        return self.particles

    def weights(self, x_beac, y_beac):
        """Calculate particle weight based on its pose and lidar data"""
        # TODO check ICP implementation
        # BEACONS: from global BEACONS to particles local: (X, Y) - Nx3x2 matrices
        res = BEACONS[np.newaxis, :, :] - self.particles[:, np.newaxis, :2]
        X = ( res[:,:,0]*np.cos(self.particles[:,2])[:, np.newaxis]
              + res[:,:,1]*np.sin(self.particles[:,2])[:, np.newaxis])
        Y = ( -res[:, :, 0] * np.sin(self.particles[:, 2])[:, np.newaxis]
              + res[:, :, 1] * np.cos(self.particles[:, 2])[:, np.newaxis])
        beacon = np.concatenate((X[:, :, np.newaxis], Y[:, :, np.newaxis]), axis=2)

        # beacon = beacons are in local coordinates of particles.
        # distance from theoretical beacons to detected beacons from scan (x_beac, y_beac)
        # ln1, ln2, ln3: NxM (M - number of detected beacons from scan)
        ln1 = np.abs(np.sqrt((beacon[:, np.newaxis, 0, 0] - x_beac[np.newaxis, :])**2
                             + (beacon[:, np.newaxis, 0, 1] - y_beac[np.newaxis, :])**2) - BEAC_R)
        ln2 = np.abs(np.sqrt((beacon[:, np.newaxis, 1, 0] - x_beac[np.newaxis, :])**2
                             + (beacon[:, np.newaxis, 1, 1] - y_beac[np.newaxis, :])**2) - BEAC_R)
        ln3 = np.abs(np.sqrt((beacon[:, np.newaxis, 2, 0] - x_beac[np.newaxis, :])**2
                             + (beacon[:, np.newaxis, 2, 1] - y_beac[np.newaxis, :])**2) - BEAC_R)

        # lns are differences in theoretical and detected beacon data from lidar
        # ln1,ln2,ln3 are correct computed OK)

        # get minimal distance for each particle, its detected beacons to theoretical beacons
        errors = np.minimum(ln1, np.minimum(ln2, ln3))
        # too far real beacons go away: non valid
        limit_err = errors > BEAC_DIST_THRES

        # find map from detected beacon to closest real (valid distance neede)
        error_l1 = np.logical_and(np.equal(errors, ln1), ~limit_err)
        error_l2 = np.logical_and(np.equal(errors, ln2), ~limit_err)
        error_l3 = np.logical_and(np.equal(errors, ln3), ~limit_err)
        # bool error_li: sum to get number of particles for each of 3 beacons
        err_l1 = np.sum(error_l1, axis=-1)
        err_l2 = np.sum(error_l2, axis=-1)
        err_l3 = np.sum(error_l3, axis=-1)

        # find sum of errors near 3 beacons for each particle: beacon_error_sum Nx3
        beacon_error_sum = np.ones([self.particles_num, 3], dtype=np.float)*1000
        ind = np.where(err_l1)[0]
        if ind.size:
            beacon_error_sum[ind, 0] = np.sum(np.where(error_l1, errors, 0), axis=-1)[ind] / err_l1[ind]
        ind = np.where(err_l2)[0]
        if ind.size:
            beacon_error_sum[ind, 1] = np.sum(np.where(error_l2, errors, 0), axis=-1)[ind] / err_l2[ind]
        ind = np.where(err_l3)[0]
        if ind.size:
            beacon_error_sum[ind, 2] = np.sum(np.where(error_l3, errors, 0), axis=-1)[ind] / err_l3[ind]
        # weights of particles are estimated via errors got from scan of beacons and theoretical beacons location
        # median version
        #weights = self.gaus(np.median(beacon_error_sum, axis=1),mu=0, sigma=self.sense_noise)
        # mean version
        weights = self.gaus(np.mean(beacon_error_sum, axis=1),mu=0, sigma=self.sense_noise)
        # check weights
        if np.sum(weights)<self.gaus(self.sense_noise*5.0,mu =0,sigma= self.sense_noise)*self.particles_num:
            logging.info("Dangerous Situation")
            #self.warning = True

        if np.sum(weights) > 0:
            weights /= np.sum(weights)
        else:
            weights = np.ones(self.particles_num, dtype=np.float)/self.particles_num
        return weights
        # TODO try use median instead mean
        # TODO if odometry works very bad and weights are small use only lidar

    def send_command(self,name,params=None):
        self.input_queue.put({'source':'loc','cmd':name,'params':params})
        return self.out_queue.get()

    def localisation(self, localisation,shared_coords,get_raw):
        time.sleep(0.5)
        #time.sleep(50)
        while True:
            if localisation.value:
                tmstmp = time.time() - self.start_time
                coords = self.send_command('getCurrentCoordinates')['data']
                if coords and type(coords[0]) is not type(100.):
                    logging.critical("Incorrect coordinates format")
                    continue
                coords[0] = coords[0]*1000
                coords[1] = coords[1]*1000
                self.move_particles(
                    [coords[0] - shared_coords[0], coords[1] - shared_coords[1], coords[2] - shared_coords[2]])
                # add aproximation
                lidar_data = get_raw()
                self.particle_sense(lidar_data)
                if self.warning:
                    x = np.random.normal(self.last[0], 200, self.particles_num)
                    y = np.random.normal(self.last[1], 200, self.particles_num)
                    orient = np.random.normal(self.last[2], np.pi, self.particles_num) % (2 * np.pi)
                    self.particles = np.array([x, y, orient]).T  # instead of np.vstack((x,y,orient)).T
                    self.warning = False
                    self.particle_sense(lidar_data)
                    self.move_particles([0, 0, 0])
                    self.particle_sense(lidar_data)
                    self.move_particles([0, 0, 0])
                main_robot = self.calculate_main()
                self.last = main_robot
                shared_coords[0] = main_robot[0]
                shared_coords[1] = main_robot[1]
                shared_coords[2] = main_robot[2]
                #logging.info(self.send_command('setCoordinates',[shared_coords[0] / 1000., shared_coords[1] / 1000., shared_coords[2]]))
            time.sleep(0.1)

                #logging.info("Odometry        coords: " + str(list(coords[:2]
                                #+ [np.rad2deg(coords[2])])))
                #logging.info("Particel Filter coords: " + str(shared_coords[:2]
                                #+ [np.rad2deg(shared_coords[2])]))
# help functions

def get_landmarks(scan):
    """Returns filtrated lidar data"""
    stamp = time.time()
    ind = np.where(np.logical_and(scan[:, 1] > MAX_ITENS, scan[:, 0] < MAX_DIST))[0]
    angles = np.pi / 4 / 180 * ind
    distances = scan[ind, 0]
    #logging.info('scan preproccesing time: ' + str(time.time() - stamp))
    return (angles + np.pi / 4) % (2 * np.pi), distances  # delete +np.pi for our robot ANDREW you NEED return (angles + np.pi / 4 + np.pi) % (2 * np.pi), distances

def p_trans(agl, pit):
    x_beac = pit*np.cos(agl) # multiply by minus in our robot
    y_beac = pit*np.sin(agl)
    return x_beac,y_beac


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syn. Fung. Amer. bor. no. 2037 (1832)

#### Original name
Rhytisma vitis Schwein.

### Remarks
null


text:
![Swift 3.0](https://img.shields.io/badge/Swift-3.0-orange.svg)
[![Version](https://img.shields.io/cocoapods/v/SelectionDialog.svg?style=flat)](http://cocoapods.org/pods/selectiondialog)
[![License](https://img.shields.io/cocoapods/l/SelectionDialog.svg?style=flat)](http://cocoapods.org/pods/selectiondialog)
[![Platform](https://img.shields.io/cocoapods/p/SelectionDialog.svg?style=flat)](http://cocoapods.org/pods/selectiondialog)
[![Build Status](https://travis-ci.org/kciter/SelectionDialog.svg?branch=master)](https://travis-ci.org/kciter/SelectionDialog)

Simple selection dialog inspired from [ios-custom-alertview](https://github.com/wimagguc/ios-custom-alertview)

# Preview
<img src="https://github.com/kciter/SelectionDialog/raw/master/Images/preview.png" width='375px' alt="Preview Image">

## Requirements
* iOS 8.0+
* Swift 3
* Xcode 8.0

## Installation
### CocoaPods
```ruby
use_frameworks!
pod "SelectionDialog"
```
### Manually
To install manually the KCSelectionDialog in an app, just drag the `SelectionDialog/*.swift` file into your project.

## Usage
### Swift
```swift
let dialog = SelectionDialog(title: "Dialog", closeButtonTitle: "Close")
dialog.addItem(item: "I have icon :)", icon: UIImage(named: "Icon1")!)
dialog.addItem(item: "I have icon and handler :D", icon: UIImage(named: "Icon2")!, didTapHandler: { () in
    print("Item didTap!")
})
dialog.addItem(item: "I have nothing :(")
dialog.show()
```

If you want to launch the dialog at the starting point of the app, make sure you put the code inside DispatchQueue.main.async. Otherwise it will not work
```swift
override func viewDidLoad() {
    DispatchQueue.main.async {
        let dialog = SelectionDialog(title: "Dialog", closeButtonTitle: "Close")
        dialog.addItem(item: "I have icon :)", icon: UIImage(named: "Icon1")!)
        dialog.addItem(item: "I have icon and handler :D", icon: UIImage(named: "Icon2")!, didTapHandler: { () in
            print("Item didTap!")
        })
        dialog.addItem(item: "I have nothing :(")
        dialog.show()
    }
}
```


text:
> Pwn - 600pts

Connect to the machine at and try to exploit my joyful echo server: `207.154.215.146:1337`

Are you able to pwn it?

PS: connect using `nc <ip> <port>`

File: [shellcode](./shellcode)

[Writeup](./writeup.md)


text:
"use strict";

var fs    = require('fs');
var _     = require('lodash');
var walk  = require('./build/walk');

function getScriptTag(path) { return '<script src="' + path + '"></script>'; }
function getLinkTag(path)   { return '<link rel="stylesheet" href="' + path + '"/>'; }

module.exports = function(grunt) {
  grunt.initConfig({ pkg: grunt.file.readJSON('package.json') });

  grunt.registerTask(
      'compile',
      function (templateFile) {
          var sourceFiles = walk('src');

          var scriptTags = sourceFiles
            .filter(function(filename){
              return filename.match(/\.js/g);
            })
            .reverse()
            .reduce(function(prev, curr){
              return prev + '\n' + getScriptTag(curr);
            }, '');

          var linkTags = sourceFiles
            .filter(function(filename){
              return filename.match(/\.css/g);
            })
            .reduce(function(prev, curr){
              return prev + '\n' + getLinkTag(curr);
            }, '');

          var data = {
              js: scriptTags,
              css: linkTags
          };

          var template = fs.readFileSync(templateFile);
          fs.writeFileSync(templateFile.replace('.template', ''), _.template(template, data));
      }
  );

  grunt.registerTask('default', 'compile:index.html.template');

};


text:
package com.mysema.examples;

public abstract class Person {

    private int age = 0;

    public abstract String firstName();

    public final String lastName() {
        return "Spiewak";
    }

    public synchronized void incrementAge() {
        age += 1;
    }

    //public native String hardDriveAge();

}


text:
<?php

namespace Magento\Bundle\Model\Resource;

/**
 * Bundle Selection Resource Model
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Selection extends \Magento\Framework\Model\Resource\Db\AbstractDb
{
    /**
     * Define main table and id field
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('catalog_product_bundle_selection', 'selection_id');
    }

    /**
     * Retrieve Required children ids
     * Return grouped array, ex array(
     *   group => array(ids)
     * )
     *
     * @param int $parentId
     * @param bool $required
     * @return array
     */
    public function getChildrenIds($parentId, $required = true)
    {
        $childrenIds = [];
        $notRequired = [];
        $adapter = $this->_getReadAdapter();
        $select = $adapter->select()->from(
            ['tbl_selection' => $this->getMainTable()],
            ['product_id', 'parent_product_id', 'option_id']
        )->join(
            ['e' => $this->getTable('catalog_product_entity')],
            'e.entity_id = tbl_selection.product_id AND e.required_options=0',
            []
        )->join(
            ['tbl_option' => $this->getTable('catalog_product_bundle_option')],
            'tbl_option.option_id = tbl_selection.option_id',
            ['required']
        )->where(
            'tbl_selection.parent_product_id = :parent_id'
        );
        foreach ($adapter->fetchAll($select, ['parent_id' => $parentId]) as $row) {
            if ($row['required']) {
                $childrenIds[$row['option_id']][$row['product_id']] = $row['product_id'];
            } else {
                $notRequired[$row['option_id']][$row['product_id']] = $row['product_id'];
            }
        }

        if (!$required) {
            $childrenIds = array_merge($childrenIds, $notRequired);
        } else {
            if (!$childrenIds) {
                foreach ($notRequired as $groupedChildrenIds) {
                    foreach ($groupedChildrenIds as $childId) {
                        $childrenIds[0][$childId] = $childId;
                    }
                }
            }
            if (!$childrenIds) {
                $childrenIds = [[]];
            }
        }

        return $childrenIds;
    }

    /**
     * Retrieve array of related bundle product ids by selection product id(s)
     *
     * @param int|array $childId
     * @return array
     */
    public function getParentIdsByChild($childId)
    {
        $adapter = $this->_getReadAdapter();
        $select = $adapter->select()->distinct(
            true
        )->from(
            $this->getMainTable(),
            'parent_product_id'
        )->where(
            'product_id IN(?)',
            $childId
        );

        return $adapter->fetchCol($select);
    }

    /**
     * Save bundle item price per website
     *
     * @param \Magento\Bundle\Model\Selection $item
     * @return void
     */
    public function saveSelectionPrice($item)
    {
        $write = $this->_getWriteAdapter();
        if ($item->getDefaultPriceScope()) {
            $write->delete(
                $this->getTable('catalog_product_bundle_selection_price'),
                ['selection_id = ?' => $item->getSelectionId(), 'website_id = ?' => $item->getWebsiteId()]
            );
        } else {
            $values = [
                'selection_id' => $item->getSelectionId(),
                'website_id' => $item->getWebsiteId(),
                'selection_price_type' => $item->getSelectionPriceType(),
                'selection_price_value' => $item->getSelectionPriceValue(),
            ];
            $write->insertOnDuplicate(
                $this->getTable('catalog_product_bundle_selection_price'),
                $values,
                ['selection_price_type', 'selection_price_value']
            );
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Dimerium scabrosum Syd. {?}

### Remarks
null


text:
using FlagData;
using Xamarin.Forms;
using System;
using Xamarin.Essentials;

namespace FlagFacts
{
    public partial class FlagDetailsPage : ContentPage
    {
        private readonly FlagDetailsViewModel vm;

        public FlagDetailsPage()
        {
            vm = DependencyService.Get<FlagDetailsViewModel>();

            InitializeComponent();
            BindingContext = vm;
        }

        private async void OnShow(object sender, EventArgs e)
        {
            vm.CurrentFlag.DateAdopted = vm.CurrentFlag.DateAdopted.AddYears(1);
            await DisplayAlert(vm.CurrentFlag.Country,
                $"{vm.CurrentFlag.DateAdopted:D} - {vm.CurrentFlag.IncludesShield}: {vm.CurrentFlag.MoreInformationUrl}",
                "OK");
        }

        private void OnMoreInformation(object sender, EventArgs e)
        {
            Launcher.OpenAsync(((FlagDetailsViewModel)BindingContext).CurrentFlag.MoreInformationUrl);
        }

        private void OnPrevious(object sender, EventArgs e)
        {
            vm.MoveToPreviousFlag();
        }

        private void OnNext(object sender, EventArgs e)
        {
            vm.MoveToNextFlag();
        }
    }
}


text:
package squidpony.squidgrid.mapping.locks.generators;

import squidpony.squidgrid.mapping.locks.IRoomLayout;

/**
 * Interface for classes that provide methods to procedurally generate new
 * {@link IRoomLayout}s.
 */
public interface ILayoutGenerator {

    /**
     * Generates a new {@link IRoomLayout}.
     */
    void generate();

    /**
     * Gets the most recently generated {@link IRoomLayout}.
     *
     * @return the most recently generated IRoomLayout
     */
    IRoomLayout getRoomLayout();

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <label>Número de la seguridad social</label>
    <name>SSN__c</name>
</CustomFieldTranslation>


text:
package jaegertracing

import (
	"bytes"
	"io"
	"net/http"

	"github.com/labstack/echo/v4"
)

type responseDumper struct {
	http.ResponseWriter

	mw  io.Writer
	buf *bytes.Buffer
}

func newResponseDumper(resp *echo.Response) *responseDumper {
	buf := new(bytes.Buffer)
	return &responseDumper{
		ResponseWriter: resp.Writer,

		mw:  io.MultiWriter(resp.Writer, buf),
		buf: buf,
	}
}

func (d *responseDumper) Write(b []byte) (int, error) {
	return d.mw.Write(b)
}

func (d *responseDumper) GetResponse() string {
	return d.buf.String()
}