text:
package com.navercorp.pinpoint.plugin.thrift.interceptor.server;

import static com.navercorp.pinpoint.plugin.thrift.ThriftScope.THRIFT_SERVER_SCOPE;

import java.net.Socket;

import org.apache.thrift.TBaseProcessor;
import org.apache.thrift.protocol.TProtocol;

import com.navercorp.pinpoint.bootstrap.MetadataAccessor;
import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
import com.navercorp.pinpoint.bootstrap.context.SpanRecorder;
import com.navercorp.pinpoint.bootstrap.context.Trace;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.interceptor.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.interceptor.SimpleAroundInterceptor;
import com.navercorp.pinpoint.bootstrap.interceptor.group.ExecutionPolicy;
import com.navercorp.pinpoint.bootstrap.interceptor.group.InterceptorGroup;
import com.navercorp.pinpoint.bootstrap.interceptor.group.InterceptorGroupInvocation;
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.annotation.Group;
import com.navercorp.pinpoint.bootstrap.plugin.annotation.Name;
import com.navercorp.pinpoint.plugin.thrift.ThriftClientCallContext;
import com.navercorp.pinpoint.plugin.thrift.ThriftConstants;
import com.navercorp.pinpoint.plugin.thrift.ThriftUtils;

/**
 * Entry/exit point for tracing synchronous processors for Thrift services.
 *

 * Because trace objects cannot be created until the message is read, this interceptor merely sends
 * trace objects created by other interceptors in the tracing pipeline:
 *

 *

 {@link com.navercorp.pinpoint.plugin.thrift.interceptor.server.ProcessFunctionProcessInterceptor ProcessFunctionProcessInterceptor}
 *   marks the start of a trace, and sets up the environment for trace data to be injected.

 *
 *

 {@link com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadFieldBeginInterceptor TProtocolReadFieldBeginInterceptor},
 *   {@link com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadTTypeInterceptor TProtocolReadTTypeInterceptor}
 *   reads the header fields and injects the parent trace object (if any).

 *
 *

 {@link com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadMessageEndInterceptor TProtocolReadMessageEndInterceptor}
 *   creates the actual root trace object.

 *

 *

 * <tt>TBaseProcessorProcessInterceptor</tt> -> <tt>ProcessFunctionProcessInterceptor</tt> ->
 *    <tt>TProtocolReadFieldBeginInterceptor</tt> <-> <tt>TProtocolReadTTypeInterceptor</tt> -> <tt>TProtocolReadMessageEndInterceptor</tt>
 *

 * Based on Thrift 0.8.0+
 *
 * @author HyunGil Jeong
 *
 * @see com.navercorp.pinpoint.plugin.thrift.interceptor.server.ProcessFunctionProcessInterceptor ProcessFunctionProcessInterceptor
 * @see com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadFieldBeginInterceptor TProtocolReadFieldBeginInterceptor
 * @see com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadTTypeInterceptor TProtocolReadTTypeInterceptor
 * @see com.navercorp.pinpoint.plugin.thrift.interceptor.tprotocol.server.TProtocolReadMessageEndInterceptor TProtocolReadMessageEndInterceptor
 */
@Group(value=THRIFT_SERVER_SCOPE, executionPoint=ExecutionPolicy.BOUNDARY)
public class TBaseProcessorProcessInterceptor implements SimpleAroundInterceptor, ThriftConstants {

    private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
    private final boolean isDebug = logger.isDebugEnabled();

    private final TraceContext traceContext;
    private final MethodDescriptor descriptor;
    private final InterceptorGroup group;
    private final MetadataAccessor socketAccessor;

    public TBaseProcessorProcessInterceptor(
            TraceContext traceContext,
            MethodDescriptor descriptor,
            @Name(THRIFT_SERVER_SCOPE) InterceptorGroup group,
            @Name(METADATA_SOCKET) MetadataAccessor socketAccessor) {
        this.traceContext = traceContext;
        this.descriptor = descriptor;
        this.group = group;
        this.socketAccessor = socketAccessor;
    }

    @Override
    public void before(Object target, Object[] args) {
        // Do nothing
    }

    @Override
    public void after(Object target, Object[] args, Object result, Throwable throwable) {
        final Trace trace = this.traceContext.currentRawTraceObject();
        if (trace == null) {
            return;
        }
        // logging here as some Thrift servers depend on TTransportException being thrown for normal operations.
        // log only when current transaction is being traced.
        if (isDebug) {
            logger.afterInterceptor(target, args, result, throwable);
        }
        this.traceContext.removeTraceObject();
        if (trace.canSampled()) {
            try {
                processTraceObject(trace, target, args, throwable);
            } catch (Throwable t) {
                logger.warn("Error processing trace object. Cause:{}", t.getMessage(), t);
            } finally {
                trace.close();
            }
        }
    }

    private void processTraceObject(final Trace trace, Object target, Object[] args, Throwable throwable) {
        // end spanEvent
        try {
            SpanEventRecorder recorder = trace.currentSpanEventRecorder();
            // TODO Might need a way to collect and record method arguments
            // trace.recordAttribute(...);
            recorder.recordException(throwable);
            recorder.recordApi(this.descriptor);
        } catch (Throwable t) {
            logger.warn("Error processing trace object. Cause:{}", t.getMessage(), t);
        } finally {
            trace.traceBlockEnd();
        }

        // end root span
        SpanRecorder recorder = trace.getSpanRecorder();
        String methodUri = getMethodUri(target);
        recorder.recordRpcName(methodUri);
        // retrieve connection information
        String localIpPort = UNKNOWN_ADDRESS;
        String remoteAddress = UNKNOWN_ADDRESS;
        if (args.length == 2 && args[0] instanceof TProtocol) {
            TProtocol inputProtocol = (TProtocol)args[0];
            if (this.socketAccessor.isApplicable(inputProtocol.getTransport())) {
                Socket socket = this.socketAccessor.get(inputProtocol.getTransport());
                if (socket != null) {
                    localIpPort = ThriftUtils.getHostPort(socket.getLocalSocketAddress());
                    remoteAddress = ThriftUtils.getHost(socket.getRemoteSocketAddress());
                }
            }
        }
        if (localIpPort != UNKNOWN_ADDRESS) {
            recorder.recordEndPoint(localIpPort);
        }
        if (remoteAddress != UNKNOWN_ADDRESS) {
            recorder.recordRemoteAddress(remoteAddress);
        }
    }

    private String getMethodUri(Object target) {
        String methodUri = UNKNOWN_METHOD_URI;
        InterceptorGroupInvocation currentTransaction = this.group.getCurrentInvocation();
        Object attachment = currentTransaction.getAttachment();
        if (attachment instanceof ThriftClientCallContext && target instanceof TBaseProcessor) {
            ThriftClientCallContext clientCallContext = (ThriftClientCallContext)attachment;
            String methodName = clientCallContext.getMethodName();
            methodUri = ThriftUtils.getProcessorNameAsUri((TBaseProcessor<?>)target);
            StringBuilder sb = new StringBuilder(methodUri);
            if (!methodUri.endsWith("/")) {
                sb.append("/");
            }
            sb.append(methodName);
            methodUri = sb.toString();
        }
        return methodUri;
    }

}


text:
#ifndef HQ_SEMAPHORE_H
#define HQ_SEMAPHORE_H
#include "HQUtil.h"

class HQUTIL_API HQSemaphore
{
public:
	class ScopeLock
	{
	public:
		inline ScopeLock(HQSemaphore &sem) : m_sem(sem) {m_sem.Lock();}
		inline ~ScopeLock() {m_sem.Unlock();}
	private:
		HQSemaphore &m_sem;
	};

	///
	///if {initValue} < 1 , it's treated as one
	///
	HQSemaphore(hq_int32 initValue);
	~HQSemaphore();

	///decrease semaphore value by one and if it's negative, return false, and the calling thread does not own the semaphore, the semaphore's state is left unchanged as before calling this method
	bool TryLock();

	///decrease semaphore value by one and if it's negative, lock the calling thread
	void Lock();
	///increase semaphore value by one and if it's zero, one of waiting threads will be resumed
	void Unlock();
private:
	void *m_platformSpecific;
};

#endif

redpajama_set_name: RedPajamaGithub


text:
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
import datetime

def index(request):
    try:
        dt = datetime.datetime.now()
        context = {}
        context['dt'] = dt
        return render_to_response('index.html',context )
    except ValueError:
        raise Http404()

def test(request, idx):
    return render_to_response('bs/test%s.html'%idx )

def markdown(request):
    try:
        dt = datetime.datetime.now()
        context = {}
        context['dt'] = dt
        return render_to_response('markdown.html',context )
    except ValueError:
        raise Http404()


text:
Tested with CGX 2.19 / CCX 2.19

+ Axisymmetric model
+ Linear elasticity
+ Surface-to-surface Penalty contact
+ Force (pressure) control

File                   | Contents
:-------------         | :-------------
[pre.fbd](pre.fbd)     | Pre-processing script for CGX  (parametrized with `valu`)
[Hertz.inp](Hertz.inp) | CCX input, surface-to-surface penalty contact
[post.fbd](post.fbd)   | CGX post-processing script
[plots.fbd](plots.fbd) | CGX post-processing script (path plots)
[plots.gnu](plots.gnu) | Gnuplot script for path plots
[test.py](test.py)     | Python script to run the full simulation

## Preprocessing

The parameters can be changed in `pre.fbd`.

| Parameter | Value | Meaning |
| :------------- |  :------------- | :------------- |
| `radius` | 50 | radius of the hemisphere in mm |
| `height` | 60 | thickness of the cylindrical disk in mm |
| `width` | 120 | radius of the cylindrical disk in mm |
| `etyp` | qu8c | element type (in CGX terms) |

Two separate parts are generated and meshed with axisymmetric elements (by default CAX8).
The load is applied as pressure to the flat equatorial surface of the hemisphere (blue).
The lower surface of the flat disk (red) is constrained in axial (y) direction.
The nodes on the axis of symmetry (magenta) are constrained in radial (x) direction.
```
> cgx -b pre.fbd
```

## Solving
```
> ccx Hertz
> monitor.py Hertz
```
As you see, the force control is quite challenging for the solver.

## Postprocess

```
> cgx -b post.fbd
```
The solution shows the expected feature of Hertz contact with the maximum of the equivalent stress somewhat below the contact surface. However, there is evidence of contact finding problems near the axis of symmetry. With CAX8R elements (reduced integration, specify `qu8cr` in `pre.fbd`) this problem is even more pronounced.

```
> cgx -b plots.fbd
```
Stress plot along the axis of symmetry (x=0) at the contact location:

Contact pressure distribution along the meridian of the sphere:


text:
package com.imap.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * Абстрактный класс для доступа к БД.
 *
 * @author Boris Finkelshtein <finke.ba@gmail.com>
 */
public abstract class AbstractDao {

	private JdbcTemplate jdbcTemplate;

	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

}


text:
<?php

namespace OPNsense\DynDNS\Api;

use OPNsense\Base\ApiMutableModelControllerBase;

class AccountsController extends ApiMutableModelControllerBase
{
    protected static $internalModelName = 'account';
    protected static $internalModelClass = 'OPNsense\DynDNS\DynDNS';

    public function searchItemAction()
    {
        $result = $this->searchBase(
            "accounts.account",
            [
              'enabled', 'service', 'description', 'username', 'hostnames', 'use_interface',
              'interface', 'protocol', 'current_ip', 'current_mtime'
            ],
            "description"
        );
        foreach ($result['rows'] as &$row) {
            if ($row['service'] == 'Custom') {
                $row['service'] = 'Custom (' . $row['protocol'] . ')';
            }
            unset($row['protocol']);
        }
        return $result;
    }

    public function setItemAction($uuid)
    {
        return $this->setBase("account", "accounts.account", $uuid);
    }

    public function addItemAction()
    {
        return $this->addBase("account", "accounts.account");
    }

    public function getItemAction($uuid = null)
    {
        return $this->getBase("account", "accounts.account", $uuid);
    }

    public function delItemAction($uuid)
    {
        return $this->delBase("accounts.account", $uuid);
    }

    public function toggleItemAction($uuid, $enabled = null)
    {
        return $this->toggleBase("accounts.account", $uuid, $enabled);
    }
}


text:
from decimal import Decimal as D

from oscar.test import factories
from oscar.apps.partner import strategy

def add_product(basket, price=None, quantity=1, product=None):
    """
    Helper to add a product to the basket.
    """
    has_strategy = False
    try:
        has_strategy = hasattr(basket, 'strategy')
    except RuntimeError:
        pass
    if not has_strategy:
        basket.strategy = strategy.Default()
    if price is None:
        price = D('1')
    if product and product.has_stockrecords:
        record = product.stockrecords.all()[0]
    else:
        record = factories.create_stockrecord(
            product=product, price_excl_tax=price,
            num_in_stock=quantity + 1)
    basket.add_product(record.product, quantity)

def add_products(basket, args):
    """
    Helper to add a series of products to the passed basket
    """
    for price, quantity in args:
        add_product(basket, price, quantity)


text:
DebugStyle::DebugStyle(std::string _name, GLenum _drawMode) : Style(_name, _drawMode) {

    constructVertexLayout();
    constructShaderProgram();

}

void DebugStyle::constructVertexLayout() {

    m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({
        {"a_position", 3, GL_FLOAT, false, 0},
        {"a_color", 4, GL_UNSIGNED_BYTE, true, 0}
    }));

}

void DebugStyle::constructShaderProgram() {

    std::string vertShaderSrcStr = stringFromResource("debug.vs");
    std::string fragShaderSrcStr = stringFromResource("debug.fs");

    m_shaderProgram = std::make_shared<ShaderProgram>();
    m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr);

}

void DebugStyle::addData(TileData &_data, MapTile &_tile, const MapProjection &_mapProjection) const {

    if (Tangram::getDebugFlag(Tangram::DebugFlags::TILE_BOUNDS)) {

        Mesh* mesh = new Mesh(m_vertexLayout, m_drawMode);

        // Add four vertices to draw the outline of the tile in red

        std::vector<PosColVertex> vertices;

        GLuint abgr = 0xff0000ff;

        vertices.reserve(4);
        vertices.push_back({ -1.f, -1.f, 0.f, abgr });
        vertices.push_back({  1.f, -1.f, 0.f, abgr });
        vertices.push_back({  1.f,  1.f, 0.f, abgr });
        vertices.push_back({ -1.f,  1.f, 0.f, abgr });

        mesh->addVertices(std::move(vertices), { 0, 1, 2, 3, 0 });
        mesh->compileVertexBuffer();

        _tile.addGeometry(*this, std::unique_ptr<VboMesh>(mesh));

    }

}

void DebugStyle::buildPoint(Point &_point, StyleParams& _params, Properties &_props, VboMesh &_mesh) const {

    // No-op

}

void DebugStyle::buildLine(Line &_line, StyleParams& _params, Properties &_props, VboMesh &_mesh) const {

    // No-op

}

void DebugStyle::buildPolygon(Polygon &_polygon, StyleParams& _params, Properties &_props, VboMesh &_mesh) const {

    // No-op

}


text:
/*
 * D. Palindrome Degree
 * time limit per test1 second
 * memory limit per test256 megabytes
 * inputstandard input
 * outputstandard output
 * String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length  are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.
 *
 * Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.
 *
 * You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
 *
 * Input
 * The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive.
 *
 * Output
 * Output the only number — the sum of the polindrome degrees of all the string's prefixes.
 *
 * Examples
 * input
 * a2A
 * output
 * 1
 * input
 * abacaba
 * output
 * 6
 * */
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

#define N 10000000
char A[N];
int n;

int p[N], Res[N];
int ans, right_bound, left_bound;

void Manachar() {
    right_bound = 1, left_bound = 1;
    for (int i = 1; i <= n; i++) {
        p[i] = max(1, min(p[2*left_bound-i], right_bound-i));
        while (i - p[i] >= 1 && i + p[i] <= n && A[i+p[i]] == A[i-p[i]]) p[i]++;
        if (i+p[i]-1 > right_bound) {
            right_bound = i+p[i]-1;
            left_bound = i;
        }
        if (i-p[i]+1 == 1) {
            if (i%2 == 0) {
                Res[i+p[i]] = Res[i]+1;
            } else {
                Res[i+p[i]] = Res[i-1]+1;
            }
            ans += Res[i+p[i]];
        }
    }
}

int main() {
    string s;
    cin >> s;

    for (int i = 0; i < s.size(); i++) {
        A[++n] = s[i];
        A[++n] = '#';
    }
    n--;
    Manachar();
    printf("%d", ans);

    return 0;
}


text:
/*
	Given an object, executes the index functions and collects the keys
	into an object.
*/

module.exports = function (obj, indexes) {
	var ix, ino = [], done = false, self = this,
		pre, post, flds = this.db.flds, hdrs = this.db.hdrs;

	if(indexes) {
		/* link data index */
		pre = ''; post='';
	} else {
		/* normal object index */
		pre = this.type + hdrs;
		post = flds + obj.id;
		indexes = this.opt.indexes;
//		ino.push(this.type + flds + obj.id);
	}

	for(ix in indexes) {
		indexes[ix](obj, push);
	}
	done = true;

	function push() {
		if(done) throw Error('ERR_INDEX_ASYNC_FUNCTION ' + self.type);
		ino.push(pre + ix + self.db.key(arguments) + post);
	}

	return ino;
};


text:
package main

import (
	"fmt"

	glfw "github.com/go-gl/glfw/v3.1/glfw"
	mgl "github.com/go-gl/mathgl/mgl32"

	fizzle "github.com/tbogdala/fizzle"
	graphics "github.com/tbogdala/fizzle/graphicsprovider"
	opengl "github.com/tbogdala/fizzle/graphicsprovider/opengl"
	forward "github.com/tbogdala/fizzle/renderer/forward"
	"github.com/tbogdala/fizzle/scene"
)

const (
	renderSystemPriority = 100.0
	renderSystemName     = "RenderSystem"
)

// RenderSystem implements fizzle/scene/System interface and handles the rendering
// of entities in the scene.
type RenderSystem struct {
	Renderer   *forward.ForwardRenderer
	MainWindow *glfw.Window
	Camera     fizzle.Camera

	gfx graphics.GraphicsProvider

	visibleEntities []scene.Entity
}

// NewRenderSystem allocates a new RenderSystem object.
func NewRenderSystem() *RenderSystem {
	rs := new(RenderSystem)
	rs.visibleEntities = []scene.Entity{}
	return rs
}

// Initialize will create the main window using glfw and then create the underyling
// renderer.
func (rs *RenderSystem) Initialize(windowName string, w int, h int) error {
	// create the window and iniitialize opengl
	err := rs.initGraphics(windowName, w, h)
	if err != nil {
		return err
	}

	// setup the forward renderer
	rs.Renderer = forward.NewForwardRenderer(rs.gfx)
	rs.Renderer.ChangeResolution(int32(w), int32(h))

	// set some OpenGL flags
	rs.gfx.Enable(graphics.CULL_FACE)
	rs.gfx.Enable(graphics.DEPTH_TEST)

	return nil
}

// initGraphics creates an OpenGL window and initializes the required graphics libraries.
// It will either succeed or panic.
func (rs *RenderSystem) initGraphics(title string, w int, h int) error {
	// GLFW must be initialized before it's called
	err := glfw.Init()
	if err != nil {
		return fmt.Errorf("Failed to initialize GLFW. %v", err)
	}

	// request a OpenGL 3.3 core context
	glfw.WindowHint(glfw.Samples, 0)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)

	// do the actual window creation
	rs.MainWindow, err = glfw.CreateWindow(w, h, title, nil, nil)
	if err != nil {
		return fmt.Errorf("Failed to create the main window. %v", err)
	}

	// set a function to update the renderer on window resize
	rs.MainWindow.SetSizeCallback(func(w *glfw.Window, width int, height int) {
		rs.Renderer.ChangeResolution(int32(width), int32(height))
	})

	rs.MainWindow.MakeContextCurrent()

	// disable v-sync for max draw rate
	glfw.SwapInterval(0)

	// initialize OpenGL
	rs.gfx, err = opengl.InitOpenGL()
	if err != nil {
		return fmt.Errorf("Failed to initialize OpenGL. %v", err)
	}
	fizzle.SetGraphics(rs.gfx)

	return nil
}

// SetLight puts a light in the specified slot for the renderer.
func (rs *RenderSystem) SetLight(i int, l *forward.Light) {
	rs.Renderer.ActiveLights[i] = l
}

// GetRequestedPriority returns the requested priority level for the System
// which may be of significance to a Manager if they want to order Update() calls.
func (rs *RenderSystem) GetRequestedPriority() float32 {
	return renderSystemPriority
}

// GetName returns the name of the system that can be used to identify
// the System within Manager.
func (rs *RenderSystem) GetName() string {
	return renderSystemName
}

// OnAddEntity should get called by the scene Manager each time a new entity
// has been added to the scene.
func (rs *RenderSystem) OnAddEntity(newEntity scene.Entity) {
	_, okay := newEntity.(RenderableEntity)
	if okay {
		rs.visibleEntities = append(rs.visibleEntities, newEntity)
	}
}

// OnRemoveEntity should get called by the scene Manager each time an entity
// has been removed from the scene.
func (rs *RenderSystem) OnRemoveEntity(oldEntity scene.Entity) {
	surviving := rs.visibleEntities[:0]
	for _, e := range rs.visibleEntities {
		if e.GetID() != oldEntity.GetID() {
			surviving = append(surviving, e)
		}
	}
	rs.visibleEntities = surviving
}

// Update renderers the known entities.
func (rs *RenderSystem) Update(frameDelta float32) {
	// clear the screen
	width, height := rs.Renderer.GetResolution()
	rs.gfx.Viewport(0, 0, int32(width), int32(height))
	rs.gfx.ClearColor(0.25, 0.25, 0.25, 1.0)
	rs.gfx.Clear(graphics.COLOR_BUFFER_BIT | graphics.DEPTH_BUFFER_BIT)

	// make the projection and view matrixes
	projection := mgl.Perspective(mgl.DegToRad(60.0), float32(width)/float32(height), 1.0, 100.0)
	var view mgl.Mat4
	if rs.Camera != nil {
		view = rs.Camera.GetViewMatrix()
	} else {
		view = mgl.Ident4()
	}

	// draw stuff the visible entities
	for _, e := range rs.visibleEntities {
		visibleEntity, okay := e.(RenderableEntity)
		if okay {
			r := visibleEntity.GetRenderable()
			rs.Renderer.DrawRenderable(r, nil, projection, view, rs.Camera)
		}
	}

	// draw the screen
	rs.MainWindow.SwapBuffers()
}


text:
package org.onosproject.lisp.ctl;

import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.ChannelProgressivePromise;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.EventLoop;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.net.SocketAddress;

/**
 * Adapter for testing against a netty channel.
 */
public class ChannelAdapter implements Channel {
    @Override
    public EventLoop eventLoop() {
        return null;
    }

    @Override
    public Channel parent() {
        return null;
    }

    @Override
    public ChannelConfig config() {
        return null;
    }

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

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

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

    @Override
    public ChannelMetadata metadata() {
        return null;
    }

    @Override
    public SocketAddress localAddress() {
        return null;
    }

    @Override
    public SocketAddress remoteAddress() {
        return null;
    }

    @Override
    public ChannelFuture closeFuture() {
        return null;
    }

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

    @Override
    public Unsafe unsafe() {
        return null;
    }

    @Override
    public ChannelPipeline pipeline() {
        return null;
    }

    @Override
    public ByteBufAllocator alloc() {
        return null;
    }

    @Override
    public ChannelPromise newPromise() {
        return null;
    }

    @Override
    public ChannelProgressivePromise newProgressivePromise() {
        return null;
    }

    @Override
    public ChannelFuture newSucceededFuture() {
        return null;
    }

    @Override
    public ChannelFuture newFailedFuture(Throwable cause) {
        return null;
    }

    @Override
    public ChannelPromise voidPromise() {
        return null;
    }

    @Override
    public ChannelFuture bind(SocketAddress localAddress) {
        return null;
    }

    @Override
    public ChannelFuture connect(SocketAddress remoteAddress) {
        return null;
    }

    @Override
    public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
        return null;
    }

    @Override
    public ChannelFuture disconnect() {
        return null;
    }

    @Override
    public ChannelFuture close() {
        return null;
    }

    @Override
    public ChannelFuture deregister() {
        return null;
    }

    @Override
    public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
        return null;
    }

    @Override
    public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {
        return null;
    }

    @Override
    public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
        return null;
    }

    @Override
    public ChannelFuture disconnect(ChannelPromise promise) {
        return null;
    }

    @Override
    public ChannelFuture close(ChannelPromise promise) {
        return null;
    }

    @Override
    public ChannelFuture deregister(ChannelPromise promise) {
        return null;
    }

    @Override
    public Channel read() {
        return null;
    }

    @Override
    public ChannelFuture write(Object msg) {
        return null;
    }

    @Override
    public ChannelFuture write(Object msg, ChannelPromise promise) {
        return null;
    }

    @Override
    public Channel flush() {
        return null;
    }

    @Override
    public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
        return null;
    }

    @Override
    public ChannelFuture writeAndFlush(Object msg) {
        return null;
    }

    @Override
    public <T> Attribute<T> attr(AttributeKey<T> attributeKey) {
        return null;
    }

    @Override
    public int compareTo(Channel o) {
        return 0;
    }
}


text:
#region

using System;
using System.Collections.Specialized;
using System.IO;
using Firebase.Platform.Default;

#endregion

namespace Firebase.Platform {
  /// <summary>
  /// This is how consumers get access to concrete implementations of platform
  /// services such as unity versions of AuthTokenProvider and FirebaseHttpRequest.
  /// This is primarily to allow testing with mono (non-unity) versions of these
  /// services. Unity specifics are centralized within Firebase.App which allow
  /// firebase components themselves to remain dependent only on Mono.
  /// This allows us to more easily run unit tests in Mono, and do adhoc testing
  /// using mono command line apps.
  /// </summary>
  internal static class Services {

    static Services() {
      // Platform neutral versions until unity versions get installed.
      AppConfig = AppConfigExtensions.Instance;
      Clock = SystemClock.Instance;
      Logging = DebugLogger.Instance;
    }

    // This service stores additional config properties that are either
    // platform specific (writeable app path) or user specified, but not
    // part of the common API.
    public static IAppConfigExtensions AppConfig { get; internal set; }

    // Having the clock as a platform service allows test infrastructure to fast
    // forward time artificially which is useful for retry tests.
    public static IClockService Clock { get; internal set; }

    // This allows us to replace calls to unityengine.debug with regular
    // c# logging and capturing the logs for test purposes.
    public static ILoggingService Logging { get; internal set; }

  }
}


text:
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="@string/title_activity_settings">

    <PreferenceCategory android:title="@string/pref_title_general">

        <SwitchPreference
            android:defaultValue="false"
            android:key="key_usecelsius"
            android:summaryOff="@string/pref_summary_fahrenheit"
            android:summaryOn="@string/pref_summary_celsius"
            android:title="@string/pref_title_units" />

        <SwitchPreference
            android:defaultValue="false"
            android:key="key_followgps"
            android:summary="@string/pref_summary_currentlocation"
            android:title="@string/label_currentlocation" />

    </PreferenceCategory>

    <PreferenceCategory
        android:title="@string/pref_title_api"
        android:key="category_api">

        <ListPreference
            android:key="API"
            android:summary="%s"
            android:title="@string/api_label" />

        <SwitchPreference
            android:defaultValue="false"
            android:key="key_usepersonalkey"
            android:summary="@string/pref_summary_personalkey"
            android:title="@string/pref_title_personalkey" />

        <Preference
            android:key="key_apiregister"
            android:summary="@string/pref_summary_apiregister"
            android:title="@string/pref_title_apiregister" />

        <SimpleWeather.Droid.Wear.SettingsActivity.KeyEntryPreference
            android:key="API_KEY"
            android:singleLine="true"
            android:summary="@string/pref_summary_apikey"
            android:title="@string/key_hint" />

    </PreferenceCategory>

    <PreferenceCategory
        android:title="Sync"
        android:key="category_sync">

        <ListPreference
            android:key="key_datasync"
            android:defaultValue="0"
            android:entries="@array/datasync_entries"
            android:entryValues="@array/datasync_values"
            android:title="Data Synchronization" />

        <Preference
            android:key="key_connectionstatus"
            android:title="Connection Status"
            android:summary="" />

    </PreferenceCategory>

    <PreferenceCategory android:title="@string/pref_title_about">

        <Preference
            android:key="key_aboutapp"
            android:title="@string/pref_title_about_app" />

    </PreferenceCategory>

</PreferenceScreen>


text:
12-bit data from accelrometer on an embedded device.

### Details
* Program should take the following arguments from commandline
	* name of a binary input file
	* a text output file.

* Input file will contain 12-bit unsigned values.
* Output file should contain the 32 largest values from the input file.
* Other than the IO portion, consider your code is running on a memory and speed limited device (embedded)

### Installtion
* Download the code
* A make file is provided for building the project. Run 'make' command from the extracted folder
* 'make' will generate an executable named 'accelerator'.
* This executable takes 4 commandline arguments 	```./accelerator -i in_file -o out_file``` Where
	* ```in_file``` - is the input binary file for testing
	* ```out_file``` - is the text output file generated by the program

### Summary

Problem listed two requirements:
1. Output file contains the 32 largest values from the input file.
2. Output file should also contain the last 32 values read from the input file.

Design considerations
---------------------
1. 	For requirement 1, I have used a minheap (priority queue).
	Minheap provides compact and fast implementation for storing a small subset
	of ordered data. Minheap requires only one comparison for each element. If
	Minheap is full, one comparison with top of the heap is needed to decide
	if we need to add the element to minheap. This speeds up the implementation
	considerably for  data sets. Minheap also allows efficient way
	to sort the list as per the requirements. Also, insertion and removal of
	data from heap is very fast (through sink/swim operations). Minheap also has
	an advantage on space as it does not require additional data structures for
	maintaining state (as opposed to BST which requires left and right pointers).

2. 	For requirement 2, I have used a circular buffer to store the last 32 values read from
	the input file. I have also provided a compact version of the circular buffer that
	packs the data. However, compact version is little bit complicated as it need to
	pack and unpack data of 12-bits. A suitable data structure can be used depending
	on the memory/performance tradeoff. Compact version can be turned on by setting
	USE_COMPRESSED_CIRC_BUF to 1 in config.h

3. I have directly used array of 32 elements for both minheap and circular buffer
   implementations. This design can be easily extended once we know more about the
   system requirements. For example, minheap and circular buffer can hold up to 2^16
   elements. Also data for these data structures can be provided by the users.
   Please note that, this will have additional impact on memory size.

 4.	For memory allocation, I have used global variables for this problem.
	This is because on some systems local memory will be available for storing
	relatively small amount of data. For example, compiler can statically
	allocate global variable in device's local memory. Please note that depending
	on the embedded system capabilities you can use several methods to
	allocate/deallocate memory.

	Overall the current design/implementation takes 135 bytes of memory
	(for non-compressed circular buffer) and 119 bytes of memory (for compressed
	circular buffer).

Files
-----
* ```main.c``` starting program, handles IO and commandline arguments. Please note that this file will not be part of the embedded code.

* ```acceldata.h/c``` Main logic is here for handling the accelerometer data. It allocates memory and uses other data structures to store data.

* ```circbuf.h/c```  Circular buffer implementation for 16-bit data

* ```circbuf_12bit.h/c``` Circular buffer implemenation for 12-bit data (compact)

* ```pq.h/c```  Minheap (priority queue) implementation.

* ```config.h``` configuration details


text:
require 'forwardable'
require 'addressable/uri'
require 'mimemagic'
require 'nokogiri'
require 'yaml'
require 'zip'

require_relative 'mangdown/error'

require_relative 'mangdown/support/logging'
require_relative 'mangdown/support/equality'
require_relative 'mangdown/support/tools'
require_relative 'mangdown/support/cbz'
require_relative 'mangdown/page'
require_relative 'mangdown/chapter'
require_relative 'mangdown/manga'

require_relative 'mangdown/adapter/no_adapter_error'
require_relative 'mangdown/adapter/not_implemented_error'
require_relative 'mangdown/adapter/mangareader'
require_relative 'mangdown/adapter/manga_bat'

# Find, download and package manga from the web
module Mangdown
  class <<self
    include Logging
  end

  DOWNLOAD_DIR ||= Dir.home + '/manga'

  def self.register_adapter(name, adapter)
    adapters[name] = adapter
  end

  def self.adapters
    @adapters ||= {}
  end

  def self.manga(uri_or_instance)
    with_adapter(uri_or_instance, :manga) do |instance|
      Mangdown::Manga.new(instance)
    end
  end

  def self.chapter(uri_or_instance)
    with_adapter(uri_or_instance, :chapter) do |instance|
      Mangdown::Chapter.new(instance)
    end
  end

  def self.page(uri_or_instance)
    with_adapter(uri_or_instance, :page) do |instance|
      Mangdown::Page.new(instance)
    end
  end

  # rubocop:disable Metrics/AbcSize
  # rubocop:disable Metrics/MethodLength
  def self.with_adapter(instance, instance_constructor)
    if instance.is_a?(String)
      adapter = adapter(instance)
      instance = adapter.public_send(instance_constructor, instance)
    else
      adapter = adapter(instance.url)
      klass = adapter.class.const_get(instance_constructor.to_s.capitalize)
      instance = klass.new(instance.attributes)
    end
    yield(instance)
  rescue Adapter::NoAdapterError
    raise
  rescue StandardError => error
    logger.error(debug_error(error, adapter, instance))
    raise Mangdown::Error, "Adapter failed: #{error.message}"
  end
  private_class_method :with_adapter
  # rubocop:enable Metrics/AbcSize
  # rubocop:enable Metrics/MethodLength

  def self.adapter(uri)
    adapter = adapters.values.find { |a| a.for?(uri) }

    raise Adapter::NoAdapterError, uri unless adapter

    adapter
  end
  private_class_method :adapter

  def self.debug_error(error, adapter, instance)
    {
      msg: 'Adapter method failed',
      adapter: adapter.class,
      instance: instance,
      error: error,
      error_msg: error.message,
      backtrace: error.backtrace
    }.to_s
  end
  private_class_method :debug_error

  register_adapter :mangareader, Mangdown::Mangareader.new
  register_adapter :manga_bat, Mangdown::MangaBat.new
end


text:
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace Tailviewer.Archiver.Repository
{
	/// <summary>
	///     This exception is thrown when the given user token is invalid.
	/// </summary>
	[Serializable]
	public class InvalidUserTokenException
		: Exception
	{
		public InvalidUserTokenException()
			: base("The given user token is invalid")
		{
		}

		public InvalidUserTokenException(string message)
			: base(message)
		{
		}

		public InvalidUserTokenException(string message, Exception inner)
			: base(message, inner)
		{
		}

		[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
		protected InvalidUserTokenException(SerializationInfo info, StreamingContext context) : base(info, context)
		{
		}

		[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			base.GetObjectData(info, context);
		}
	}
}


text:
define(
    ({
        "widgets": {
            "ShareDialog": {
                "title": "Compartir",
                "heading": "Compartir este mapa",
                "url": "Enlace del mapa",
                "embed": "Integrar mapa",
                "extent": "Compartir la extensión del mapa actual",
                "size": "Tamaño (ancho/alto):",
                "facebookTooltip": "Facebook",
                "twitterTooltip": "Twitter",
                "gplusTooltip": "Google Plus",
                "emailTooltip": "Correo electrónico"
            }
        }
    })

);


text:
from __future__ import absolute_import
from __future__ import division
from builtins import range
from past.utils import old_div
import time
import numpy as np
from pomdpy.util import console
from pomdpy.action_selection import ucb_action
from .belief_tree_solver import BeliefTreeSolver

module = "pomcp"

class POMCP(BeliefTreeSolver):
    """
    Monte-Carlo Tree Search implementation, from POMCP
    """

    # Dimensions for the fast-UCB table
    UCB_N = 10000
    UCB_n = 100

    def __init__(self, agent):
        """
        Initialize an instance of the POMCP solver
        :param agent:
        :param model:
        :return:
        """
        super(POMCP, self).__init__(agent)

        # Pre-calculate UCB values for a speed-up
        self.fast_UCB = [[None for _ in range(POMCP.UCB_n)] for _ in range(POMCP.UCB_N)]

        for N in range(POMCP.UCB_N):
            for n in range(POMCP.UCB_n):
                if n is 0:
                    self.fast_UCB[N][n] = np.inf
                else:
                    self.fast_UCB[N][n] = agent.model.ucb_coefficient * np.sqrt(old_div(np.log(N + 1), n))

    @staticmethod
    def reset(agent):
        """
        Generate a new POMCP solver

        :param agent:
        Implementation of abstract method
        """
        return POMCP(agent)

    def find_fast_ucb(self, total_visit_count, action_map_entry_visit_count, log_n):
        """
        Look up and return the value in the UCB table corresponding to the params
        :param total_visit_count:
        :param action_map_entry_visit_count:
        :param log_n:
        :return:
        """
        assert self.fast_UCB is not None
        if total_visit_count < POMCP.UCB_N and action_map_entry_visit_count < POMCP.UCB_n:
            return self.fast_UCB[int(total_visit_count)][int(action_map_entry_visit_count)]

        if action_map_entry_visit_count == 0:
            return np.inf
        else:
            return self.model.ucb_coefficient * np.sqrt(old_div(log_n, action_map_entry_visit_count))

    def select_eps_greedy_action(self, eps, start_time):
        """
        Starts off the Monte-Carlo Tree Search and returns the selected action. If the belief tree
                data structure is disabled, random rollout is used.
        """
        if self.disable_tree:
            self.rollout_search(self.belief_tree_index)
        else:
            self.monte_carlo_approx(eps, start_time)
        return ucb_action(self, self.belief_tree_index, True)

    def simulate(self, belief_node, eps, start_time):
        """
        :param belief_node:
        :return:
        """
        return self.traverse(belief_node, 0, start_time)

    def traverse(self, belief_node, tree_depth, start_time):
        delayed_reward = 0

        state = belief_node.sample_particle()

        # Time expired
        if time.time() - start_time > self.model.action_selection_timeout:
            console(4, module, "action selection timeout")
            return 0

        action = ucb_action(self, belief_node, False)

        # Search horizon reached
        if tree_depth >= self.model.max_depth:
            console(4, module, "Search horizon reached")
            return 0

        step_result, is_legal = self.model.generate_step(state, action)

        child_belief_node = belief_node.child(action, step_result.observation)
        if child_belief_node is None and not step_result.is_terminal and belief_node.action_map.total_visit_count > 0:
            child_belief_node, added = belief_node.create_or_get_child(action, step_result.observation)

        if not step_result.is_terminal or not is_legal:
            tree_depth += 1
            if child_belief_node is not None:
                # Add S' to the new belief node
                # Add a state particle with the new state
                if child_belief_node.state_particles.__len__() < self.model.max_particle_count:
                    child_belief_node.state_particles.append(step_result.next_state)
                delayed_reward = self.traverse(child_belief_node, tree_depth, start_time)
            else:
                delayed_reward = self.rollout(belief_node)
            tree_depth -= 1
        else:
            console(4, module, "Reached terminal state.")

        # delayed_reward is "Q maximal"
        # current_q_value is the Q value of the current belief-action pair
        action_mapping_entry = belief_node.action_map.get_entry(action.bin_number)

        q_value = action_mapping_entry.mean_q_value

        # off-policy Q learning update rule
        q_value += (step_result.reward + (self.model.discount * delayed_reward) - q_value)

        action_mapping_entry.update_visit_count(1)
        action_mapping_entry.update_q_value(q_value)

        # Add RAVE ?
        return q_value


text:
<?php

namespace Modules\Auth\Controller {

	use Modules\Auth, Modules\Entitizer, Utils\Validate, Session, Str;

	class Login {

		private $user = null;

		/**
		 * Constructor
		 */

		public function __construct() {

			$this->user = Entitizer::get(TABLE_USERS);
		}

		/**
		 * Invoker
		 *
		 * @return true|string|array : true on success, otherwise an error code, or an array of type [$param_name, $error_code],
		 *         where $param_name is a name of param that has triggered the error,
		 *         and $error_code is a language phrase related to the error
		 */

		public function __invoke(array $post) {

			# Declare variables

			$name_email = ''; $password = '';

			# Extract post array

			extract($post);

			# Validate values

			if ((false === ($name = Validate::userName($name_email))) &&

				(false === ($email = Validate::userEmail($name_email)))) return ['name_email', 'USER_ERROR_NAME_INVALID'];

			if (false === ($password = Validate::userPassword($password))) return ['password', 'USER_ERROR_PASSWORD_INVALID'];

			# Init user

			$init_by = ((false !== $name) ? 'name' : 'email');

			if ((!$this->user->init($$init_by, $init_by)) || (Auth::isAdmin() && ($this->user->rank < RANK_ADMINISTRATOR))) {

				return ['name_email', ('USER_ERROR_' . strtoupper($init_by) .'_INCORRECT')];
			}

			# Check password

			$password = Str::encode($this->user->auth_key, $password);

			if (0 !== strcmp($this->user->password, $password)) return ['password', 'USER_ERROR_PASSWORD_INCORRECT'];

			# Check access

			if (!Auth::isAdmin() && ($this->user->rank === RANK_GUEST)) return 'USER_ERROR_ACCESS';

			# Create session

			$session = Entitizer::get(TABLE_USERS_SESSIONS, $this->user->id); $session->remove();

			$code = Str::random(40); $ip = REQUEST_CLIENT_IP; $time = REQUEST_TIME;

			$data = ['id' => $this->user->id, 'code' => $code, 'ip' => $ip, 'time' => $time];

			if (!$session->create($data)) return 'USER_ERROR_AUTH_LOGIN';

			# Set session variable

			Session::set('code', $code);

			# ------------------------

			return true;
		}
	}
}


text:
  Nadaillac est
       un village
       géographiquement positionné dans le département de Dordogne en Aquitaine. Elle totalisait 339 habitants en 2008.

Si vous pensez venir habiter à Nadaillac, vous pourrez aisément trouver une maison à acheter.

Le nombre d'habitations, à Nadaillac, se décomposait en 2011 en trois appartements et 229 maisons soit
 un marché relativement équilibré.

La commune compte de nombreux  aménagements, elle dispose, entre autres, de un bassin de natation, deux terrains de tennis, un centre d'équitation et un terrain de sport.

À proximité de Nadaillac sont situées les communes de
Archignac à 7 km, 324 habitants,
Estivals localisée à 5 km, 128 habitants,
Chavagnac à 5 km, 319 habitants,
Chartrier-Ferrière localisée à 5 km, 329 habitants,
Gignac à 6 km, 609 habitants,
La Dornac à 5 km, 365 habitants,
 entre autres. De plus, Nadaillac est située à seulement 17 km de Brive-la-Gaillarde.


text:
<?php
namespace Application\Controller;

use Zend\View\Model\ViewModel;
use Core\Controller\ActionController;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\DbSelect as PaginatorDbSelectAdapter;

class IndexController extends ActionController
{
	/**
	 * @return void
	 */
    public function indexAction()
    {
        $post = $this->getTable('Application\Model\Post');
        $sql = $post->getSql();
        $select = $sql->select();

        $paginatorAdapter = new PaginatorDbSelectAdapter($select, $sql);
        $paginator = new Paginator($paginatorAdapter);
        $cache = $this->getServiceLocator()->get('Cache');
        $paginator->setCache($cache);
        $paginator->setCurrentPageNumber($this->params()->fromRoute('page'));

        $view = new ViewModel(array(
        	'posts' => $paginator
		));
        return $view;
    }

	/**
	 * @return Zend\Http\Response
	 */
	public function commentsAction() {
		$id = (int) $this->params()->fromRoute('id',0);
		$where = array('post_id' => $id);
		$comments = $this->getTable('Application\Model\Comment')
			->fetchAll(null,$where)
			->toArray();

		$response = $this->getResponse();
		$response->setStatusCode(200);
		$response->setContent(json_encode($comments));
		$response->getHeaders()->addHeaderLine('Content-Type','application/json');
		return $response;
	}
}


text:
<?php

namespace AppBundle\Security;

use Fury473\Bundle\AtarashiiBundle\Service\UserService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;

class Guard extends AbstractGuardAuthenticator
{

    /**
     * @var UserService
     */
    private $userService;

    /**
     * @param UserService $userService
     */
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    /**
     * Called on every request. Return whatever credentials you want,
     * or null to stop authentication.
     */
    public function getCredentials(Request $request)
    {
        if (!$request->getUser() || !$request->getPassword()) {
            return null;
        }

        // What you return here will be passed to getUser() as $credentials
        return array(
            'username' => $request->getUser(),
            'password' => $request->getPassword()
        );
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        // if null, authentication will fail
        // if a User object, checkCredentials() is called
        return new User($credentials['username'], $credentials['password'], ['ROLE_USER']);
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        $validation = $this->userService->verifyCredentials();
        if ($validation !== true) {
            throw new CustomUserMessageAuthenticationException($validation);
        }

        // return true to cause authentication success
        return true;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        // on success, let the request continue
        return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        return $this->createResponse($request, $exception);
    }

    /**
     * Called when authentication is needed, but it's not sent
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        return $this->createResponse($request, $authException);
    }

    public function supportsRememberMe()
    {
        return false;
    }

    private function createResponse(Request $request, AuthenticationException $authException)
    {
        $response = new JsonResponse(strtr($authException->getMessageKey(), $authException->getMessageData()));
        $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $request->getHost()));
        $response->setStatusCode(Response::HTTP_UNAUTHORIZED);

        return $response;
    }
}


text:
package cmd

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"

	"github.com/ghodss/yaml"
	"github.com/spf13/cobra"

	apimachineryversion "k8s.io/apimachinery/pkg/version"
	"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/util/i18n"
	"k8s.io/kubernetes/pkg/version"
)

type Version struct {
	ClientVersion *apimachineryversion.Info `json:"clientVersion,omitempty" yaml:"clientVersion,omitempty"`
	ServerVersion *apimachineryversion.Info `json:"serverVersion,omitempty" yaml:"serverVersion,omitempty"`
}

var (
	versionExample = templates.Examples(i18n.T(`
		# Print the client and server versions for the current context
		kubectl version`))
)

func NewCmdVersion(f cmdutil.Factory, out io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "version",
		Short:   i18n.T("Print the client and server version information"),
		Long:    "Print the client and server version information for the current context",
		Example: versionExample,
		Run: func(cmd *cobra.Command, args []string) {
			err := RunVersion(f, out, cmd)
			cmdutil.CheckErr(err)
		},
	}
	cmd.Flags().BoolP("client", "c", false, "Client version only (no server required).")
	cmd.Flags().BoolP("short", "", false, "Print just the version number.")
	cmd.Flags().String("output", "", "output format, options available are yaml and json")
	cmd.Flags().MarkShorthandDeprecated("client", "please use --client instead.")
	return cmd
}

func RunVersion(f cmdutil.Factory, out io.Writer, cmd *cobra.Command) error {
	var serverVersion *apimachineryversion.Info = nil
	var serverErr error = nil
	vo := Version{nil, nil}

	clientVersion := version.Get()
	vo.ClientVersion = &clientVersion

	if !cmdutil.GetFlagBool(cmd, "client") {
		serverVersion, serverErr = retrieveServerVersion(f)
		vo.ServerVersion = serverVersion
	}

	switch of := cmdutil.GetFlagString(cmd, "output"); of {
	case "":
		if cmdutil.GetFlagBool(cmd, "short") {
			fmt.Fprintf(out, "Client Version: %s\n", clientVersion.GitVersion)

			if serverVersion != nil {
				fmt.Fprintf(out, "Server Version: %s\n", serverVersion.GitVersion)
			}
		} else {
			fmt.Fprintf(out, "Client Version: %s\n", fmt.Sprintf("%#v", clientVersion))

			if serverVersion != nil {
				fmt.Fprintf(out, "Server Version: %s\n", fmt.Sprintf("%#v", *serverVersion))
			}
		}
	case "yaml":
		y, err := yaml.Marshal(&vo)
		if err != nil {
			return err
		}

		fmt.Fprintln(out, string(y))
	case "json":
		y, err := json.Marshal(&vo)
		if err != nil {
			return err
		}
		fmt.Fprintln(out, string(y))
	default:
		return errors.New("invalid output format: " + of)

	}

	return serverErr
}

func retrieveServerVersion(f cmdutil.Factory) (*apimachineryversion.Info, error) {
	discoveryClient, err := f.DiscoveryClient()
	if err != nil {
		return nil, err
	}

	// Always request fresh data from the server
	discoveryClient.Invalidate()
	return discoveryClient.ServerVersion()
}


text:
package com.google.wave.api;

import junit.framework.TestCase;

/**
 * Gadget unit tests.
 *
 * @author scovitz@google.com (Seth Covitz)
 */
public class GadgetTest extends TestCase {

  private static final String EMPTY_STRING = "";
  private static final String URL = "url";

  public void testDefaultConstructor() {
    Gadget gadget = new Gadget();
    assertEquals(ElementType.GADGET, gadget.getType());
    assertEquals(EMPTY_STRING, gadget.getProperty(URL));
    assertEquals(EMPTY_STRING, gadget.getUrl());
  }

  public void testUrlConstructor() {
    Gadget gadget = new Gadget(URL);
    assertEquals(ElementType.GADGET, gadget.getType());
    assertEquals(URL, gadget.getProperty(URL));
    assertEquals(URL, gadget.getUrl());
  }
}


text:
package com.palantir.atlasdb.keyvalue.impl;

import static org.assertj.core.api.Assertions.assertThat;

import com.palantir.tracing.Tracer;
import com.palantir.tracing.api.Span;
import com.palantir.tracing.api.SpanObserver;
import com.palantir.tracing.api.SpanType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.ClassRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TracingKvsTest extends AbstractKeyValueServiceTest {
    @ClassRule
    public static final TestResourceManager TRM =
            new TestResourceManager(() -> TracingKeyValueService.create(new InMemoryKeyValueService(false)));

    private static final Logger log = LoggerFactory.getLogger(TracingKvsTest.class);
    private static final String TEST_OBSERVER_NAME = TracingKvsTest.class.getName();

    public TracingKvsTest() {
        super(TRM);
    }

    @Override
    public void setUp() throws Exception {
        Tracer.initTrace(Optional.of(true), getClass().getSimpleName() + "." + Math.random());
        Tracer.subscribe(TEST_OBSERVER_NAME, new TestSpanObserver());
        Tracer.startSpan("test", SpanType.LOCAL);
        super.setUp();
    }

    @Override
    public void tearDown() throws Exception {
        try {
            Optional<Span> finishedSpan = Tracer.completeSpan();
            SpanObserver observer = Tracer.unsubscribe(TEST_OBSERVER_NAME);
            assertThat(observer).isInstanceOf(TestSpanObserver.class);
            List<Span> spans = ((TestSpanObserver) observer).spans();
            log.warn(
                    "{} spans: {}",
                    spans.size(),
                    spans.stream().map(Span::getOperation).collect(Collectors.toList()));
            if (Tracer.isTraceObservable()) {
                assertThat(finishedSpan.isPresent()).isTrue();
                assertThat(finishedSpan.get().getOperation()).isEqualTo("test");
                String traceId = finishedSpan.get().getTraceId();
                assertThat(traceId).isNotNull();
                assertThat(traceId).isNotEmpty();
                assertThat(spans).isNotEmpty();
                assertThat(spans.size())
                        .describedAs("Should include root test span and additional KVS method spans %s", spans)
                        .isGreaterThanOrEqualTo(1);
                assertThat(spans.stream()
                                .filter(span -> !Objects.equals(traceId, span.getTraceId()))
                                .map(Span::getTraceId)
                                .collect(Collectors.toSet()))
                        .describedAs("All spans should have same trace ID %s, spans %s", traceId, spans)
                        .isEmpty();
            }
        } finally {
            super.tearDown();
        }
    }

    private static final class TestSpanObserver implements SpanObserver {
        private final List<Span> spans = new ArrayList<>();

        @Override
        public void consume(Span span) {
            log.warn("{}", span);
            spans.add(span);
        }

        List<Span> spans() {
            return Collections.unmodifiableList(spans);
        }
    }
}


text:
typedef struct collision_system_t CollisionSystem;
typedef struct aspect_system_t AspectSystem;
typedef struct prefab_t Prefab;

typedef struct entity_queue_t {
    Entity entities[MAX_ENTITIES];
    u32 length;
    u32 head;
    u32 tail;
} EntityQueue;

void entity_queue_init(EntityQueue* self);
void entity_queue_push(EntityQueue* self, Entity entity);
Entity entity_queue_pop(EntityQueue* self);

typedef struct entity_id_list_t {
    Entity* list;
    u32 size;
    u32 capacity;
} EntityList;

void entity_list_init(EntityList* self, u32 capacity);
void entity_list_resize(EntityList* self, u32 capacity);
void entity_list_free(EntityList* self);

#define ENTITY_MANAGER_MESSAGE_QUEUE_CAPACITY 128

POOL_REGISTER(Entity);

typedef struct entity_manager_t {
    POOL(Entity) entities;
    AspectSystem* systems[COMPONENT_LAST];
    ComponentList componentsMap[COMPONENT_LAST];
    i32 lowestEId;
    EntityQueue removeQueue;
    MessageEventQueue eventQueue;
} EntityManager;

EntityManager* entity_manager_new();
void entity_manager_free(EntityManager* self);
void entity_manager_register_system(EntityManager* self, AspectSystem* system, u32 capacity);
void entity_manager_set_system_compare_function(EntityManager* self, AspectSystem* system, component_compare_f compareFunc);
i32 entities_gen_entity_id(EntityManager* self);
Entity entities_create_entity(EntityManager* self);
Entity entities_instantiate_prefab(EntityManager* self, Prefab* prefab, Vec2 position, f32 rotation);
void entities_add_component(EntityManager* self, Component* component);
Component* entities_get_component(EntityManager* self, ComponentType type, Entity entity);
ComponentList* entities_get_all_components(EntityManager* self, ComponentType type);
bool entities_has_component(EntityManager* self, ComponentType type, Entity entity);
void entities_remove_entity(EntityManager* self, Entity entity);
void entities_remove_all_entities(EntityManager* self);
//void entities_get_all_of(EntityManager* self, ComponentType type, EntityList* dest);
void entities_send_message(EntityManager* self, Entity entity, Message message);
void entities_send_message_deferred(EntityManager* self, Entity entity, Message message);

// Should be called AFTER update AND render calls have been made!
void entities_update(EntityManager* self);

#define REGISTER_SYSTEM(self, system, capacity) \
    entity_manager_register_system(self, (AspectSystem*)system, capacity)

#define SET_SYSTEM_COMPARISON(entitymanager, system, compare) \
    entity_manager_set_system_compare_function(entitymanager, (AspectSystem*)system, compare)

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <item
        android:id="@+id/action_decorate_views"
        android:title="@string/mf_action_decorate_views"
        app:showAsAction="never"
        />
</menu>


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

<title>android.support.v7.appcompat Class Hierarchy</title>
<meta name="date" content="2014-08-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package android.support.v7.appcompat

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

android.support.v7.appcompat.BuildConfig

android.support.v7.appcompat.R

android.support.v7.appcompat.R.anim

android.support.v7.appcompat.R.attr

android.support.v7.appcompat.R.bool

android.support.v7.appcompat.R.color

android.support.v7.appcompat.R.dimen

android.support.v7.appcompat.R.drawable

android.support.v7.appcompat.R.id

android.support.v7.appcompat.R.integer

android.support.v7.appcompat.R.layout

android.support.v7.appcompat.R.string

android.support.v7.appcompat.R.style

android.support.v7.appcompat.R.styleable

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
__author__ = 'Tony Beltramelli www.tonybeltramelli.com - 16/09/2015'

from ..utils.UMath import *
from ..View import *

import collections

class RelevanceAssessment:
    def __init__(self, labels):
        self.labels = labels
        self.view = View(False, True)

        self.positives = []
        self.negatives = []
        self.reliabilities = []

        self.errors = []

        self.all_f1_score = []
        self.all_precision = []
        self.all_recall = []
        self.all_reliability = []

        self.confusion_matrix = self.build_confusion_matrix(labels)

    def update_training(self, error):
        self.errors.append(error)

    def update_evaluation(self, predicted_label, expected_label, predictions):
        self.confusion_matrix[expected_label][predicted_label] += 1

        if predicted_label == expected_label:
            self.positives.append(expected_label)
        else:
            self.negatives.append(expected_label)

        self.reliabilities.append(UMath.reliability([x / sum(predictions) for x in predictions]))

        print "predict: {}, expect: {} {}".format(predicted_label, expected_label, "OK" if predicted_label == expected_label else "")

    def compute(self, collection_size):
        true_positives = float(len(self.positives))
        false_negatives = self.get_false_positives(self.negatives, self.positives)

        precision = true_positives / collection_size
        recall = true_positives / UMath.get_denominator(true_positives + false_negatives)
        f1_score = 2 * (precision * recall) / UMath.get_denominator(precision + recall)
        reliability = np.mean(self.reliabilities)

        print "f1_score: {} (precision: {}, recall: {}), reliability: {}".format(f1_score, precision, recall, reliability)

        self.all_f1_score.append(f1_score)
        self.all_precision.append(precision)
        self.all_recall.append(recall)
        self.all_reliability.append(reliability)

        self.positives = []
        self.negatives = []
        self.reliabilities = []

    def get_statistics(self, data):
        amin = np.amin(data)
        mean = np.mean(data)
        amax = np.amax(data)
        stddev = np.std(data)

        return "min: {}, mean: {}, max: {}, stddev: {}".format(amin, mean, amax, stddev)

    def get_false_positives(self, negatives, true_positives):
        unique_false_negatives = set(true_positives) & set(negatives)
        false_negatives = 0

        for x in unique_false_negatives:
            for y in negatives:
                if x == y:
                    false_negatives += 1

        return float(false_negatives)

    def get_confusion_matrix(self):
        matrix = self.convert_to_matrix(self.confusion_matrix)
        return UMath.normalize_array(matrix)

    def build_confusion_matrix(self, label_set):
        expected_labels = collections.OrderedDict()

        for expected_label in label_set:
            expected_labels[expected_label] = collections.OrderedDict()

            for predicted_label in label_set:
                expected_labels[expected_label][predicted_label] = 0.0

        return expected_labels

    def convert_to_matrix(self, dictionary):
        length = len(dictionary)
        confusion_matrix = np.zeros((length, length))

        i = 0
        for row in dictionary:
            j = 0
            for column in dictionary:
                confusion_matrix[i][j] = dictionary[row][column]
                j += 1
            i += 1

        return confusion_matrix

    def output_compared_plot(self, path):
        length = len(self.all_f1_score)
        elength = len(self.errors)

        if elength > length:
            ratio = elength / length
            self.all_f1_score = UMath.interpolate(self.all_f1_score, length * ratio)
            self.all_precision = UMath.interpolate(self.all_precision, length * ratio)
            self.all_recall = UMath.interpolate(self.all_recall, length * ratio)
            self.all_reliability = UMath.interpolate(self.all_reliability, length * ratio)

        data = [self.errors, self.all_f1_score, self.all_precision, self.all_recall, self.all_reliability]
        colors = ['m', 'c', 'g', 'b', 'r']
        labels = ["Mean square error", "F1 score", "Precision", "Recall", "Reliability"]

        self.view.plot_data("K-fold cross-validation", data, "Epoch", "Amplitude", colors, labels)
        self.view.show()
        self.view.save(path)

    def output_statistics(self, path, run_name):
        output_file = open(path, 'a')
        output_file.write("#Statistics {}\n".format(run_name))

        output_file.write("* F1 score: {}\n".format(self.get_statistics(self.all_f1_score)))
        output_file.write("* Precision: {}\n".format(self.get_statistics(self.all_precision)))
        output_file.write("* Recall: {}\n".format(self.get_statistics(self.all_recall)))
        output_file.write("* Reliability: {}\n".format(self.get_statistics(self.all_reliability)))
        if len(self.errors) > 0:
            output_file.write("* Mean square error: {}\n".format(self.get_statistics(self.errors)))

        output_file.write("\n")
        output_file.close()

    def output_mean_square_mean_error(self, path, k=1):
        if k > 1:
            step = len(self.errors) / k
            errors = np.zeros(step)

            for i in xrange(0, len(self.errors), step):
                error_run = []

                for j in range(i, i + step):
                    error_run.append(self.errors[j])

                errors = [sum(x) for x in zip(errors, error_run)]

            errors = [x / k for x in errors]
        else:
            errors = self.errors

        self.view.plot_data("Training", [errors], "Epoch", "Mean square error")
        self.view.show()
        self.view.save(path)

    def output_confusion_matrix(self, path):
        matrix = self.get_confusion_matrix()

        self.view.plot_confusion_matrix(matrix, self.labels)
        self.view.show()
        self.view.save(path)


text:
<?php
//
// After including cdash_test_case.php, subsequent require_once calls are
// relative to the top of the CDash source tree
//
require_once(dirname(__FILE__).'/cdash_test_case.php');

class BuildOverviewTestCase extends KWWebTestCase
{
  function __construct()
    {
    parent::__construct();
    }

  function testBuildOverview()
    {
    $this->login();
    $this->get($this->url."/buildOverview.php");
    if(strpos($this->getBrowser()->getContentAsText(), "project not specified") === false)
      {
      $this->fail("'project not specified' not found when expected");
      return 1;
      }
    $this->get($this->url."/buildOverview.php?project=InsightExample");
    if(strpos($this->getBrowser()->getContentAsText(), "Build summary") === false)
      {
      $this->fail("'Build summary' not found when expected");
      return 1;
      }
    $this->pass("Passed");
    }
}

?>


text:
<?php

namespace Concrete\Core\Url\Resolver;

use League\Url\UrlImmutable;
use Concrete\Core\Page\Page;
use Concrete\Core\Entity\Site\SkeletonTree;

class PageUrlResolver implements UrlResolverInterface
{
    /**
     * @var \Concrete\Core\Url\Resolver\PathUrlResolver
     */
    protected $pathUrlResolver;

    public function __construct(PathUrlResolver $path_url_resolver)
    {
        $this->pathUrlResolver = $path_url_resolver;
    }

    protected function resolveWithPageId(Page $page, array $arguments)
    {
        return $this->resolveWithResolver('/?cID=' . $page->getCollectionID(), $arguments);
    }

    /**
     * {@inheritdoc}
     *
     * @see \Concrete\Core\Url\Resolver\UrlResolverInterface::resolve()
     */
    public function resolve(array $arguments, $resolved = null)
    {
        if ($resolved) {
            // We don't need to do any post processing on urls.
            return $resolved;
        }

        $page = $arguments ? head($arguments) : null;

        if (isset($page) && $page instanceof Page) {

            if ($externalUrl = $page->getCollectionPointerExternalLink()) {
                return $this->resolveWithResolver($externalUrl, []);
            }

            $tree = $page->getSiteTreeObject();
            if (is_object($tree) && $tree instanceof SkeletonTree) {
                return $this->resolveWithPageId($page, $arguments);
            }

            if ($path = $page->getCollectionPath()) {
                return $this->resolveWithResolver($path, $arguments);
            }

            // if there's no path but it's the home page
            if ($page->isHomePage()) {
                return $this->resolveWithResolver('/', $arguments);
            }

            // otherwise, it's a page object with no path yet, which happens when pages aren't yet approved
            return $this->resolveWithPageId($page, $arguments);
        }

        return null;
    }

    /**
     * @param string $path
     * @param array $arguments
     *
     * @return \League\URL\URLInterface
     */
    protected function resolveWithResolver($path, $arguments)
    {
        array_unshift($arguments, $path);

        return $this->pathUrlResolver->resolve($arguments);
    }
}


text:
import scrapy

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import HtmlXPathSelector
from competitor_prices.items import Product
from scrapy.contrib.linkextractors import LinkExtractor
import random

# For testing
from scrapy.shell import inspect_response
from scrapy.utils.response import open_in_browser
from ipdb import set_trace
# http://doc.scrapy.org/en/latest/topics/contracts.html
from scrapy.contracts import Contract
from scrapy.exceptions import ContractFail

class EvoSpider(CrawlSpider):
  name = 'evo'

  def __init__(self, *args, **kwargs):
    super(EvoSpider, self).__init__(*args, **kwargs)
    #self.allowed_domains = ['http://www.evo.com/', 'www.evo.com/']
    self.name = 'evo'
    self.base_url = 'http://www.evo.com'
    self.start_urls = ['http://www.evo.com/brands.aspx']

  def parse_start_url(self, response):
    # Parse out the brand pages and return a new response object
    brands = response.xpath("//span[@class='col3']/a/@href").extract()

    for brand in brands:
      brand_url = str(self.base_url + brand)
      yield scrapy.Request(url = brand_url,
                           callback = self.parse_brand_landing_pages)
      self.log("Queued up: %s" % brand_url)

  def parse_brand_landing_pages(self, response):
    product_links = response.xpath("//div[@class='product']/a/@href").extract()

    for product in product_links:
      product_url = str(self.base_url + product)
      self.log("Here comes product: %s" % product_url)

      yield scrapy.Request(url = product_url,
                           callback = self.parse_item)

    # Paginate!
    next_page = response.xpath("//div[@class='paging']/a[@class='inline-block next']/@href").extract()

    if next_page:
      self.log("Found next page: %s" % next_page[0])
      link_butt = next_page[0].split('/')[-1]
      next_page_url = str(response.url.split('.aspx')[0] + "/" + link_butt)

      yield scrapy.Request(url = next_page_url,
                      callback = self.parse_brand_landing_pages)

  def parse_product_pages(self, response):
    product_page_pattern = "//a[contains(@class, 'qa-product-link')]/@href"
    product_pages = response.xpath(product_page_pattern).extract()

    for product in product_pages:
      product_url = str(self.base_url + product)
      self.log("Hitting product page: %s" % product_url)

      yield scrapy.Request(url = product_url,
                           callback = self.parse_item)

  def parse_item(self, response):

    item = Product()
    dirty_data = {}

    dirty_data['source'] = [self.name]
    dirty_data['product_id'] = response.xpath("//span[@class='sku identifier']/span[@class='value']/text()").extract()
    dirty_data['review_count'] = response.xpath("//span[@class='review r0']/span[@class='rating']/span[@class='value-title']/@title").extract()
    dirty_data['review_score'] = response.xpath('//*[@id="pnlRightInformation"]/div[1]/span[1]/a/span[1]/span/@title').extract()
    dirty_data['brand'] = response.xpath("//h1[@class='fn']/strong[@class='brand']/text()").extract()
    dirty_data['description_short'] = response.xpath("//div[@id='detailsTab']/h2/text()").extract()
    dirty_data['description_long'] = [''.join(response.xpath("//div[@class='description']/text()").extract()).strip().replace('  ', ' ')]
    dirty_data['price'] = response.xpath("//div[@id='priceContainer']//span[@class='price']/text()").extract()
    dirty_data['product_url'] = [response.url]
    dirty_data['image'] = response.xpath('//*[@id="ctl00_Body_mainImagePanel"]//img[@class="mainImage"]/@src').extract()
    dirty_data['condition'] = response.xpath('//*[@id="pnlRightInformation"]/div[1]/span[5]/text()').extract()

    for variable in dirty_data.keys():
      if dirty_data[variable]:
        if variable == 'inventory':
          item[variable] = dirty_data[variable][0]
        elif variable in ['price', 'price_high', 'price_low', 'review_score']:
          item[variable] = float(dirty_data[variable][0].strip().replace('$', '').replace(',', ''))
        elif variable in ['review_count']:
          item[variable] = int(dirty_data[variable][0].strip())
        elif variable == 'condition':
          item[variable] = dirty_data[variable][0].strip().replace('Condition: ', '')
        else:
          item[variable] = dirty_data[variable][0].strip()
    yield item


text:
    {{i18n.account.leave_account_title}}

{{i18n.account.leave_account_question}}

    <button class="btn btn-primary btn-default" ng-click="leaveAccount()" id="confirmLeaving">{{i18n.button.ok}}</button>
    <button class="btn btn-warning" ng-click="cancel()" id="cancelLeaving">{{i18n.button.cancel}}</button>


text:
import sys

if len(sys.argv) != 2:
    print "%s TABLECOUNT" % sys.argv[0]
    sys.exit(0)
NON_PART_TABLE_COUNT = int(sys.argv[1])

for i in range(NON_PART_TABLE_COUNT):
    tname = "heap_table_%s" % (i+1)
    print "create table %s (id int, description varchar(256)) with (appendonly=false) distributed by (id);" % tname
    print "insert into %s select * from reference;" % tname


text:
<component name="libraryTable">
  <library name="support-media-compat-25.0.1">
    <ANNOTATIONS>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-media-compat/25.0.1/annotations.zip!/" />
    </ANNOTATIONS>
    <CLASSES>
      <root url="jar://$USER_HOME$/.android/build-cache/2f064da2210b13714300bf184c6c2b11eed4fbfe/output/jars/libs/internal_impl-25.0.1.jar!/" />
      <root url="file://$USER_HOME$/.android/build-cache/2f064da2210b13714300bf184c6c2b11eed4fbfe/output/res" />
      <root url="jar://$USER_HOME$/.android/build-cache/2f064da2210b13714300bf184c6c2b11eed4fbfe/output/jars/classes.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/support-media-compat/25.0.1/support-media-compat-25.0.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
layout: press
title: "Cyber-activist Bassel Khartabil, believed executed in Syria, remembered as 'one of the great ones'"
source: "CBC Radio"
link: http://www.cbc.ca/radio/asithappens/as-it-happens-thursday-edition-1.4233735/cyber-activist-bassel-khartabil-believed-executed-in-syria-remembered-as-one-of-the-great-ones-1.4233762
categories: [ press ]
tags: [ ]
---


text:
[![npm version](https://img.shields.io/npm/v/postcss-filter-declarations.svg)](https://www.npmjs.com/package/postcss-filter-declarations)
[![Build Status](https://travis-ci.com/shinnn/postcss-filter-declarations.svg?branch=master)](https://travis-ci.com/shinnn/postcss-filter-declarations)
[![Coverage Status](https://img.shields.io/coveralls/shinnn/postcss-filter-declarations.svg)](https://coveralls.io/github/shinnn/postcss-filter-declarations)

A [PostCSS](https://github.com/postcss/postcss) plugin to filter declarations by property names

```javascript
var fs = require('fs');

var postcss = require('postcss');
var filterDeclarations = require('postcss-filter-declarations');

postcss()
  .use(filterDeclarations({props: ['display', 'color']}))
  .process(fs.readFileSync('path/to/css/file'))
  .css;
```

```css
.menubar {
  display: block;
  position: fixed;
  color: gray;
}

@media print {
  h1 {
    font-size: 16px;
  }

  a {
    color: blue;
  }
}
```

↓

```css
.menubar {
  display: block;
  color: gray;
}
@media print {
  h1 {
  }

  a {
    color: blue;
  }
}
```

## Installation

[Use](https://docs.npmjs.com/cli/install) [npm](https://docs.npmjs.com/about-npm/).

```
npm install postcss-filter-declarations
```

## API

```javascript
var filterDeclarations = require('postcss-filter-declarations');
```

### filterDeclarations([options])

*options*: `Object`
Return: `Function`

#### options.properties

(alias: **options.props**)

Type: `Stirng` or `Array` of `String`
Default: `[]`

Removes all [CSS declarations](https://github.com/postcss/postcss/blob/master/API.md#declaration-node) except for the proerties specified by this option.

```javascript
postcss()
  .use(filterDeclarations({
    props: 'color'
  }))
  .process('a {color: red;} b {background: blue;}')
  .css; //=> 'a {color: red;} b {}'
```

#### options.exclude

Type: `Boolean`
Defult: `false`

`true` inverts the filtering result.

```javascript
postcss()
  .use(filterDeclarations({
    props: 'color',
    exclude: true
  }))
  .process('a {color: red;} b {background: blue;}')
  .css; //=> 'a {} b {background: blue;}'
```

## License

Copyright (c) 2014 - 2019 [Shinnosuke Watanabe](https://github.com/shinnn)

Licensed under [the MIT License](./LICENSE).


text:
from twext.python.log import Logger
from txweb2 import responsecode, server, http
from txdav.xml import element as davxml
from txweb2.http import HTTPError, StatusResponse
from txweb2.resource import WrapperResource

from twisted.internet.defer import inlineCallbacks, returnValue, maybeDeferred

from twistedcaldav.config import config

__all__ = [
    "LinkResource",
]

# FIXME: copied from resource.py to avoid circular dependency
class CalDAVComplianceMixIn(object):
    def davComplianceClasses(self):
        return (
            tuple(super(CalDAVComplianceMixIn, self).davComplianceClasses())
            + config.CalDAVComplianceClasses
        )

"""
A resource that is a soft-link to another.
"""

class LinkResource(CalDAVComplianceMixIn, WrapperResource):
    """
    This is similar to a WrapperResource except that we locate our resource dynamically. We need to deal with the
    case of a missing underlying resource (broken link) as indicated by self._linkedResource being None.
    """
    log = Logger()

    def __init__(self, parent, link_url):
        self.parent = parent
        self.linkURL = link_url
        self.loopDetect = set()
        super(LinkResource, self).__init__(self.parent.principalCollections())

    @inlineCallbacks
    def linkedResource(self, request):

        if not hasattr(self, "_linkedResource"):
            if self.linkURL in self.loopDetect:
                raise HTTPError(StatusResponse(responsecode.LOOP_DETECTED, "Recursive link target: %s" % (self.linkURL,)))
            else:
                self.loopDetect.add(self.linkURL)
            self._linkedResource = (yield request.locateResource(self.linkURL))
            self.loopDetect.remove(self.linkURL)

        if self._linkedResource is None:
            raise HTTPError(StatusResponse(responsecode.NOT_FOUND, "Missing link target: %s" % (self.linkURL,)))

        returnValue(self._linkedResource)

    def isCollection(self):
        return True if hasattr(self, "_linkedResource") else False

    def resourceType(self):
        return self._linkedResource.resourceType() if hasattr(self, "_linkedResource") else davxml.ResourceType.link

    def locateChild(self, request, segments):

        def _defer(result):
            if result is None:
                return (self, server.StopTraversal)
            else:
                return (result, segments)
        d = self.linkedResource(request)
        d.addCallback(_defer)
        return d

    @inlineCallbacks
    def renderHTTP(self, request):
        linked_to = (yield self.linkedResource(request))
        if linked_to:
            returnValue(linked_to)
        else:
            returnValue(http.StatusResponse(responsecode.OK, "Link resource with missing target: %s" % (self.linkURL,)))

    def getChild(self, name):
        return self._linkedResource.getChild(name) if hasattr(self, "_linkedResource") else None

    @inlineCallbacks
    def hasProperty(self, property, request):
        hosted = (yield self.linkedResource(request))
        result = (yield hosted.hasProperty(property, request)) if hosted else False
        returnValue(result)

    @inlineCallbacks
    def readProperty(self, property, request):
        hosted = (yield self.linkedResource(request))
        result = (yield hosted.readProperty(property, request)) if hosted else None
        returnValue(result)

    @inlineCallbacks
    def writeProperty(self, property, request):
        hosted = (yield self.linkedResource(request))
        result = (yield hosted.writeProperty(property, request)) if hosted else None
        returnValue(result)

class LinkFollowerMixIn(object):

    @inlineCallbacks
    def locateChild(self, req, segments):

        self._inside_locateChild = True
        resource, path = (yield maybeDeferred(super(LinkFollowerMixIn, self).locateChild, req, segments))
        while isinstance(resource, LinkResource):
            linked_to = (yield resource.linkedResource(req))
            if linked_to is None:
                break
            resource = linked_to

        returnValue((resource, path))


text:
require 'net/http'
require 'net/https'
require "rack-proxy"
require "rack/reverse_proxy_matcher"
require "rack/exception"

module Rack
  class ReverseProxy
    include NewRelic::Agent::Instrumentation::ControllerInstrumentation if defined? NewRelic

    def initialize(app = nil, &b)
      @app = app || lambda {|env| [404, [], []] }
      @matchers = []
      @global_options = {:preserve_host => true, :x_forwarded_host => true, :matching => :all, :replace_response_host => false}
      instance_eval &b if block_given?
    end

    def call(env)
      rackreq = Rack::Request.new(env)
      matcher = get_matcher(rackreq.fullpath, extract_http_request_headers(rackreq.env), rackreq)
      return @app.call(env) if matcher.nil?

      if @global_options[:newrelic_instrumentation]
        action_name = "#{rackreq.path.gsub(/\/\d+/,'/:id').gsub(/^\//,'')}/#{rackreq.request_method}" # Rack::ReverseProxy/foo/bar#GET
        perform_action_with_newrelic_trace(:name => action_name, :request => rackreq) do
          proxy(env, rackreq, matcher)
        end
      else
        proxy(env, rackreq, matcher)
      end
    end

    private

    def proxy(env, source_request, matcher)
      uri = matcher.get_uri(source_request.fullpath,env)
      if uri.nil?
        return @app.call(env)
      end
      options = @global_options.dup.merge(matcher.options)

      # Initialize request
      target_request = Net::HTTP.const_get(source_request.request_method.capitalize).new(uri.request_uri)

      # Setup headers
      target_request_headers = extract_http_request_headers(source_request.env)

      if options[:preserve_host]
        target_request_headers['HOST'] = "#{uri.host}:#{uri.port}"
      end

      if options[:x_forwarded_host]
        target_request_headers['X-Forwarded-Host'] = source_request.host
        target_request_headers['X-Forwarded-Port'] = "#{source_request.port}"
      end

      target_request.initialize_http_header(target_request_headers)

      # Basic auth
      target_request.basic_auth options[:username], options[:password] if options[:username] and options[:password]

      # Setup body
      if target_request.request_body_permitted? && source_request.body
        source_request.body.rewind
        target_request.body_stream    = source_request.body
      end

      target_request.content_length = source_request.content_length || 0
      target_request.content_type   = source_request.content_type if source_request.content_type

      # Create a streaming response (the actual network communication is deferred, a.k.a. streamed)
      target_response = HttpStreamingResponse.new(target_request, uri.host, uri.port)

      target_response.use_ssl = "https" == uri.scheme

      # Let rack set the transfer-encoding header
      response_headers = target_response.headers
      response_headers.delete('transfer-encoding')

      # Replace the location header with the proxy domain
      if response_headers['location'] && options[:replace_response_host]
        response_location = URI(response_headers['location'][0])
        response_location.host = source_request.host
        response_headers['location'] = response_location.to_s
      end

      [target_response.status, response_headers, target_response.body]
    end

    def extract_http_request_headers(env)
      headers = env.reject do |k, v|
        !(/^HTTP_[A-Z_]+$/ === k) || v.nil?
      end.map do |k, v|
        [reconstruct_header_name(k), v]
      end.inject(Utils::HeaderHash.new) do |hash, k_v|
        k, v = k_v
        hash[k] = v
        hash
      end

      x_forwarded_for = (headers["X-Forwarded-For"].to_s.split(/, +/) << env["REMOTE_ADDR"]).join(", ")

      headers.merge!("X-Forwarded-For" =>  x_forwarded_for)
    end

    def reconstruct_header_name(name)
      name.sub(/^HTTP_/, "").gsub("_", "-")
    end

    def get_matcher(path, headers, rackreq)
      matches = @matchers.select do |matcher|
        matcher.match?(path, headers, rackreq)
      end

      if matches.length < 1
        nil
      elsif matches.length > 1 && @global_options[:matching] != :first
        raise AmbiguousProxyMatch.new(path, matches)
      else
        matches.first
      end
    end

    def reverse_proxy_options(options)
      @global_options=options
    end

    def reverse_proxy(matcher, url=nil, opts={})
      raise GenericProxyURI.new(url) if matcher.is_a?(String) && url.is_a?(String) && URI(url).class == URI::Generic
      @matchers << ReverseProxyMatcher.new(matcher,url,opts)
    end
  end
end