text:
package com.dianping.cat.build;

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

import org.unidal.lookup.configuration.AbstractResourceConfigurator;
import org.unidal.lookup.configuration.Component;

import com.dianping.cat.alarm.spi.config.AlertConfigManager;
import com.dianping.cat.report.alert.AlarmManager;
import com.dianping.cat.report.alert.config.BaseRuleHelper;
import com.dianping.cat.report.alert.spi.config.UserDefinedRuleManager;

public class HomeAlarmComponentConfigurator extends AbstractResourceConfigurator {
	@Override
	public List<Component> defineComponents() {

		List<Component> all = new ArrayList<Component>();

		all.add(A(AlarmManager.class));
		all.add(A(AlertConfigManager.class));
		all.add(A(BaseRuleHelper.class));
		all.add(A(UserDefinedRuleManager.class));
		return all;
	}
}

redpajama_set_name: RedPajamaGithub


text:
set -e

export GOOGLE_APPLICATION_CREDENTIALS=../../application_credentials.json
bundle exec rspec


text:
namespace aria2 {

class FeatureConfigTest:public CppUnit::TestFixture {

  CPPUNIT_TEST_SUITE(FeatureConfigTest);
  CPPUNIT_TEST(testGetDefaultPort);
  CPPUNIT_TEST(testStrSupportedFeature);
  CPPUNIT_TEST(testFeatureSummary);
  CPPUNIT_TEST_SUITE_END();
public:
  void testGetDefaultPort();
  void testStrSupportedFeature();
  void testFeatureSummary();
};

CPPUNIT_TEST_SUITE_REGISTRATION(FeatureConfigTest);

void FeatureConfigTest::testGetDefaultPort() {
  CPPUNIT_ASSERT_EQUAL((uint16_t)80, getDefaultPort("http"));
  CPPUNIT_ASSERT_EQUAL((uint16_t)443, getDefaultPort("https"));
  CPPUNIT_ASSERT_EQUAL((uint16_t)21, getDefaultPort("ftp"));
}

void FeatureConfigTest::testStrSupportedFeature() {
  const char* https = strSupportedFeature(FEATURE_HTTPS);
#ifdef ENABLE_SSL
  CPPUNIT_ASSERT(https);
#else
  CPPUNIT_ASSERT(!https);
#endif // ENABLE_SSL
  CPPUNIT_ASSERT(!strSupportedFeature(MAX_FEATURE));
}

void FeatureConfigTest::testFeatureSummary() {
  const std::string features[] = {

#ifdef ENABLE_ASYNC_DNS
    "Async DNS",
#endif // ENABLE_ASYNC_DNS

#ifdef ENABLE_BITTORRENT
    "BitTorrent",
#endif // ENABLE_BITTORRENT

#ifdef HAVE_SQLITE3
    "Firefox3 Cookie",
#endif // HAVE_SQLITE3

#ifdef HAVE_ZLIB
    "GZip",
#endif // HAVE_ZLIB

#ifdef ENABLE_SSL
    "HTTPS",
#endif // ENABLE_SSL

#ifdef ENABLE_MESSAGE_DIGEST
    "Message Digest",
#endif // ENABLE_MESSAGE_DIGEST

#ifdef ENABLE_METALINK
    "Metalink",
#endif // ENABLE_METALINK

#ifdef ENABLE_XML_RPC
    "XML-RPC",
#endif // ENABLE_XML_RPC

  };

  std::string featuresString = strjoin(std::begin(features),
                                       std::end(features), ", ");
  CPPUNIT_ASSERT_EQUAL(featuresString, featureSummary());
}

} // namespace aria2


text:
using System;

namespace CSF.Screenplay.Stopwatch
{
  /// <summary>
  /// Formats a <c>System.TimeSpan</c> as a human-readable string.
  /// </summary>
  public interface IFormatsDurations
  {
    /// <summary>
    /// Gets the human-readable representation of the given timespan.
    /// </summary>
    /// <returns>The duration.</returns>
    /// <param name="timespan">Timespan.</param>
    string GetDuration(TimeSpan timespan);
  }
}


text:
package org.elasticsearch.discovery.ec2;

import com.amazonaws.util.DateUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URLEncodedUtils;
import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.test.fixture.AbstractHttpFixture;

import javax.xml.XMLConstants;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * {@link AmazonEC2Fixture} is a fixture that emulates an AWS EC2 service.
 */
public class AmazonEC2Fixture extends AbstractHttpFixture {

    private final Path nodes;
    private final boolean instanceProfile;
    private final boolean containerCredentials;

    private AmazonEC2Fixture(final String workingDir, final String nodesUriPath, boolean instanceProfile, boolean containerCredentials) {
        super(workingDir);
        this.nodes = toPath(Objects.requireNonNull(nodesUriPath));
        this.instanceProfile = instanceProfile;
        this.containerCredentials = containerCredentials;
    }

    public static void main(String[] args) throws Exception {
        if (args == null || args.length != 2) {
            throw new IllegalArgumentException("AmazonEC2Fixture <working directory> <nodes transport uri file>");
        }

        boolean instanceProfile = Booleans.parseBoolean(System.getenv("ACTIVATE_INSTANCE_PROFILE"), false);
        boolean containerCredentials = Booleans.parseBoolean(System.getenv("ACTIVATE_CONTAINER_CREDENTIALS"), false);

        final AmazonEC2Fixture fixture = new AmazonEC2Fixture(args[0], args[1], instanceProfile, containerCredentials);
        fixture.listen();
    }

    @Override
    protected Response handle(final Request request) throws IOException {
        if ("/".equals(request.getPath()) && (HttpPost.METHOD_NAME.equals(request.getMethod()))) {
            final String userAgent = request.getHeader("User-Agent");
            if (userAgent != null && userAgent.startsWith("aws-sdk-java")) {

                final String auth = request.getHeader("Authorization");
                if (auth == null || auth.contains("ec2_integration_test_access_key") == false) {
                    throw new IllegalArgumentException("wrong access key: " + auth);
                }

                // Simulate an EC2 DescribeInstancesResponse
                byte[] responseBody = EMPTY_BYTE;
                for (NameValuePair parse : URLEncodedUtils.parse(new String(request.getBody(), UTF_8), UTF_8)) {
                    if ("Action".equals(parse.getName())) {
                        responseBody = generateDescribeInstancesResponse();
                        break;
                    }
                }
                return new Response(RestStatus.OK.getStatus(), contentType("text/xml; charset=UTF-8"), responseBody);
            }
        }
        if ("/latest/meta-data/local-ipv4".equals(request.getPath()) && (HttpGet.METHOD_NAME.equals(request.getMethod()))) {
            return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, "127.0.0.1".getBytes(UTF_8));
        }

        if (instanceProfile &&
            "/latest/meta-data/iam/security-credentials/".equals(request.getPath()) &&
            HttpGet.METHOD_NAME.equals(request.getMethod())) {
            final Map<String, String> headers = new HashMap<>(contentType("text/plain"));
            return new Response(RestStatus.OK.getStatus(), headers, "my_iam_profile".getBytes(UTF_8));
        }

        if (instanceProfile && "/latest/api/token".equals(request.getPath())
            && HttpPut.METHOD_NAME.equals(request.getMethod())) {
            // TODO: Implement IMDSv2 behavior here. For now this just returns a 403 which makes the SDK fall back to IMDSv1
            //       which is implemented in this fixture
            return new Response(RestStatus.FORBIDDEN.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
        }

        if ((containerCredentials &&
            "/ecs_credentials_endpoint".equals(request.getPath()) &&
            HttpGet.METHOD_NAME.equals(request.getMethod())) ||
            ("/latest/meta-data/iam/security-credentials/my_iam_profile".equals(request.getPath()) &&
            HttpGet.METHOD_NAME.equals(request.getMethod()))) {
            final Date expiration = new Date(new Date().getTime() + TimeUnit.DAYS.toMillis(1));
            final String response = "{"
                + "\"AccessKeyId\": \"" + "ec2_integration_test_access_key" + "\","
                + "\"Expiration\": \"" + DateUtils.formatISO8601Date(expiration) + "\","
                + "\"RoleArn\": \"" + "test" + "\","
                + "\"SecretAccessKey\": \"" + "ec2_integration_test_secret_key" + "\","
                + "\"Token\": \"" + "test" + "\""
                + "}";

            final Map<String, String> headers = new HashMap<>(contentType("application/json"));
            return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8));
        }

        return null;
    }

    /**
     * Generates a XML response that describe the EC2 instances
     */
    private byte[] generateDescribeInstancesResponse() {
        final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

        final StringWriter out = new StringWriter();
        XMLStreamWriter sw;
        try {
            sw = xmlOutputFactory.createXMLStreamWriter(out);
            sw.writeStartDocument();

            String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
            {
                sw.writeStartElement("requestId");
                sw.writeCharacters(UUID.randomUUID().toString());
                sw.writeEndElement();

                sw.writeStartElement("reservationSet");
                {
                    if (Files.exists(nodes)) {
                        for (String address : Files.readAllLines(nodes)) {

                            sw.writeStartElement("item");
                            {
                                sw.writeStartElement("reservationId");
                                sw.writeCharacters(UUID.randomUUID().toString());
                                sw.writeEndElement();

                                sw.writeStartElement("instancesSet");
                                {
                                    sw.writeStartElement("item");
                                    {
                                        sw.writeStartElement("instanceId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("imageId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceState");
                                        {
                                            sw.writeStartElement("code");
                                            sw.writeCharacters("16");
                                            sw.writeEndElement();

                                            sw.writeStartElement("name");
                                            sw.writeCharacters("running");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateDnsName");
                                        sw.writeCharacters(address);
                                        sw.writeEndElement();

                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(address);
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceType");
                                        sw.writeCharacters("m1.medium");
                                        sw.writeEndElement();

                                        sw.writeStartElement("placement");
                                        {
                                            sw.writeStartElement("availabilityZone");
                                            sw.writeCharacters("use-east-1e");
                                            sw.writeEndElement();

                                            sw.writeEmptyElement("groupName");

                                            sw.writeStartElement("tenancy");
                                            sw.writeCharacters("default");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateIpAddress");
                                        sw.writeCharacters(address);
                                        sw.writeEndElement();

                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(address);
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                    sw.writeEndElement();
                }
                sw.writeEndElement();

                sw.writeEndDocument();
                sw.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return out.toString().getBytes(UTF_8);
    }

    @SuppressForbidden(reason = "Paths#get is fine - we don't have environment here")
    private static Path toPath(final String dir) {
        return Paths.get(dir);
    }
}


text:
function gaussRand(samples = 6) {
  let rand = 0;
  for (let i = 0; i < samples; i += 1) rand += Math.random();
  return rand / samples;
}

function randrange(low, high, floor = true, gauss = false, gaussSamples = 6) {
  const randFunc = gauss ? gaussRand : Math.random;
  const out = randFunc(gaussSamples) * (high - low) + low;
  return floor ? Math.floor(out) : out;
}

class Particle {
  constructor(anim) {
    this.anim = anim;
    // Position and movement

    this.progress = Math.random() * (Math.PI * 2);
    this.speed = randrange(5, 25, false);
    this.frequency = 1;
    // Amplitude is anywhere from 10% of screen width to 25%
    this.amplitude = randrange(-0.10, 0.25, false, true, 10);
    this.verticalShift = randrange(-0.25, 0.25, false, true, 20);
    // Appearance

    this.radius = randrange(1, 7);
    this.opacity = randrange(0.25, 0.75, false);
  }

  // x and y are decimals where (0, something) is the top left of the canvas and (2pi, something).
  // I say "something" because it's complicated and I'm not sure
  get x() {return this.progress;}
  get y() {return this.amplitude * Math.sin(this.frequency * this.x) + this.verticalShift;}

  step() {
    this.progress += this.speed / this.anim.canvas.width;
    this.progress %= Math.PI * 2;
  }}

// Animation class

class SineParticles {
  constructor(canvas, count = 2500) {
    this.canvas = canvas;
    this.ctx = canvas.getContext('2d');
    this.particles = [];
    this.fps = 30;
    this.trailLength = 1;

    this.resize();
    window.addEventListener('resize', () => this.resize());

    // Create particles
    for (let i = 0; i < count; i += 1) this.particles.push(new Particle(this));

    this.start();
  }

  resize() {
    this.canvas.width = this.canvas.offsetWidth;
    this.canvas.height = this.canvas.offsetHeight;
    if (window.devicePixelRatio === 2) {
      this.canvas.width = this.canvas.offsetWidth * 2;
      this.canvas.height = this.canvas.offsetHeight * 2;
    }
    this.draw();
  }

  draw() {
    this.ctx.fillStyle = `rgba(0, 0, 0, ${1 / Math.max(this.trailLength, 1)})`;
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    this.particles.forEach(p => {
      const x = p.x / (2 * Math.PI) * this.canvas.width;
      const y = p.y * this.canvas.width + this.canvas.height / 2;
      // Draw circle
      this.ctx.fillStyle = `rgba(255, 255, 255, ${p.opacity})`;
      this.ctx.beginPath();
      this.ctx.arc(x, y, p.radius, 0, 2 * Math.PI, false);
      this.ctx.fill();
    });
  }

  step() {this.particles.forEach(p => p.step());}

  renderLoop() {
    this.draw();
    setTimeout(() => this.renderLoop(), 1000 / 60);
  }

  stepLoop() {
    this.step();
    setTimeout(() => this.stepLoop(), 1000 / 60);
  }

  start() {
    this.stepLoop();
    this.renderLoop();
  }}

window.SineParticles = SineParticles;

const anim = new SineParticles(document.querySelector('canvas'));

// const range = document.querySelector('input[type="range"]');
// const label = document.getElementById('out');

// function oninput() {
//   const v = (range.value ** 2) / 2;
//   anim.trailLength = v;
//   label.textContent = v.toFixed(2);
// }
// oninput();
// range.addEventListener('input', oninput);


text:
<resources>
    <string name="app_name">Prismoji</string>
</resources>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>


text:
SCRIPT_DIR=$(dirname $(readlink -f $0))

echo  "[*] Build and Run of vulnerable phpzag file upload example."
docker build -t vuln ${SCRIPT_DIR}

echo "[*] Running docker"
docker run -p 8000:80 -d vuln

echo "[*] Test now the following:"
echo "./phpzag_upload.sh localhost:8000/"


text:
from setuptools import setup

VERSION = '0.0.0'

setup(
    name='django-cerebral-forms',
    version=VERSION,
    packages=['cerebral'],
    install_requires=[],

    description='Progressive forms for intelligent websites',
    author='Jeremy Swinarton',
    author_email='jeremy@swinarton.com',
    license='MIT',
)


text:
module ReusableContainers
  module ApplicationHelper
    def dark_side?
      Rails.logger.debug request.fullpath
      request.fullpath =~ /\/admin/
    end

    def meta
      @meta ||= Meta.instance
      unless @meta.title?
        @meta.title= "#{self.action_name} | #{self.controller_name}"
      end
      @meta
    end

    def current_entry
      @entry ||= Entry.find(params[:current_entry_id], :include => :container)
    end

    def current_container
      @current_container ||= current_entry.container
    end

    def public_path_to_entry(entry)
      public_entry_url(:ancestry_slug => entry.ancestry_slug, :slug => entry.slug)
    end

    def public_link_to_entry(entry)
      if entry != current_entry && entry.active?
        if entry.direct?
          link_to entry.text, entry.destination_string, :title => entry.title, :class => "entry_links"
        elsif entry.is_root?
          link_to entry.text, public_root_path, :title => entry.title, :class => "entry_links"
        else
          link_to entry.text, public_path_to_entry(entry), :title => entry.title, :class => "entry_links"
        end
      else
        content_tag :span, entry.text, :class => "entry_links", :title => entry.title
      end
    end
  end

end


text:
#ifndef APX_CLIENT_SOCKET_CONNECTION_H
#define APX_CLIENT_SOCKET_CONNECTION_H

//////////////////////////////////////////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////////////////////////////////////////
#include "adt_bytearray.h"
#include "apx/client_connection.h"

//////////////////////////////////////////////////////////////////////////////
// PUBLIC CONSTANTS AND DATA TYPES
//////////////////////////////////////////////////////////////////////////////
#ifdef UNIT_TEST
#define SOCKET_TYPE struct testsocket_tag
#else
#define SOCKET_TYPE struct msocket_t
#endif
SOCKET_TYPE; //this is a forward declaration of the declared type just above

typedef struct apx_clientSocketConnection_tag
{
   apx_clientConnection_t base;
   adt_bytearray_t send_buffer;
   apx_size_t default_buffer_size;
   apx_size_t pending_bytes;
   SOCKET_TYPE *socket_object;
   MUTEX_T lock;
}apx_clientSocketConnection_t;

//////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTION PROTOTYPES
//////////////////////////////////////////////////////////////////////////////
apx_error_t apx_clientSocketConnection_create(apx_clientSocketConnection_t *self, SOCKET_TYPE * socket_object);
void apx_clientSocketConnection_destroy(apx_clientSocketConnection_t *self);
void apx_clientSocketConnection_vdestroy(void *arg);
apx_clientSocketConnection_t *apx_clientSocketConnection_new(SOCKET_TYPE * socket_object);

#ifndef UNIT_TEST
apx_error_t apx_clientConnection_tcp_connect(apx_clientSocketConnection_t *self, const char *address, uint16_t port);
# ifndef _WIN32
apx_error_t apx_clientConnection_unix_connect(apx_clientSocketConnection_t *self, const char *socket_path);
# endif
#endif

// ConnectionInterface API
int32_t apx_clientSocketConnection_vtransmit_max_bytes_avaiable(void* arg);
int32_t apx_clientSocketConnection_vtransmit_current_bytes_avaiable(void* arg);
void apx_clientSocketConnection_vtransmit_begin(void* arg);
void apx_clientSocketConnection_vtransmit_end(void* arg);
apx_error_t apx_clientSocketConnection_vtransmit_data_message(void* arg, uint32_t write_address, bool more_bit, uint8_t const* msg_data, int32_t msg_size, int32_t* bytes_available);
apx_error_t apx_clientSocketConnection_vtransmit_direct_message(void* arg, uint8_t const* msg_data, int32_t msg_size, int32_t* bytes_available);
#ifdef UNIT_TEST
void apx_clientSocketConnection_attach_node_manager(apx_clientSocketConnection_t* self, apx_nodeManager_t* node_manager);
apx_error_t apx_clientSocketConnection_build_node(apx_clientSocketConnection_t* self, char const* definition_text);
void apx_clientSocketConnection_run(apx_clientSocketConnection_t* self);
#endif

#undef SOCKET_TYPE
#endif //APX_CLIENT_SOCKET_CONNECTION_H


text:
package com.taglog.twitter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

import com.taglog.test.Settings;

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class TwitterDataCollectorTest {
	private String consumerKey = Settings.consumerKey;
	private String consumerSecret = Settings.consumerSecret;
	private String accessToken = Settings.accessToken;
	private String accessTokenSecret = Settings.accessTokenSecret;

	@Test
	public void getFavAndRT() {
		String sepa = "\t";
		String fileName = "tweetId.txt";
		ClassLoader loader = TwitterDataCollectorTest.class.getClassLoader();
		URL filePath = loader.getResource("com/taglog/test/" + fileName);
		System.out.println(filePath.getPath());

		FileReader fr = null;
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		try {
			fr = new FileReader(filePath.getPath());
			br = new BufferedReader(fr);

			String line;

			while ((line = br.readLine()) != null) {
				TwitterDataCollector dataCollector = new TwitterDataCollector(consumerKey, consumerSecret, accessToken, accessTokenSecret);
				long tweetId = Long.parseLong(line);
				int fav = dataCollector.getFavoriteCountByTweetId(tweetId);
				int rt = dataCollector.getRetweetCountByTweetId(tweetId);

				sb.append(Integer.toString(fav) + sepa + Integer.toString(rt) + "\n");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(sb.toString());
		}

		System.out.println(sb.toString());

	}

}


text:
/**
 *
 */
package svenz.remote.swing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import javax.swing.JComboBox;
import svenz.remote.device.DeviceGroupRegistry;

/**
 * @author Sven Zethelius
 *
 */
public class DeviceActionListener implements ActionListener
{
	private static final String PREFIX = "Frame.selectors.";
	private static final String DEFAULT = DeviceGroupRegistry.INVALID_SELECTION;
	private DeviceGroupRegistry m_registry;
	private JComboBox<String> m_location;
	private JComboBox<String> m_activity;

	public void setRegistry(DeviceGroupRegistry registry)
	{
		m_registry = registry;
	}

	public void setLocation(JComboBox<String> location)
	{
		m_location = location;
		m_location.addActionListener(this);
	}

	public void setActivity(JComboBox<String> activity)
	{
		m_activity = activity;
		m_activity.addActionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		String location =
				((String) m_location.getSelectedItem()).replace(PREFIX + "location.", "").replace("/name", "");
		String activity =
				((String) m_activity.getSelectedItem()).replace(PREFIX + "activity.", "").replace("/name", "");
		if (m_location == e.getSource())
		{
			Collection<String> activities = m_registry.getActivitiesForLocation(location);
			if (!DEFAULT.equals(location) && !activities.contains(activity))
			{
				activity = DEFAULT;
				m_activity.setSelectedItem(PREFIX + "activity." + DEFAULT + "/name");
			}
		}
		else if (m_activity == e.getSource())
		{
			Collection<String> locations = m_registry.getLocationsForActivity(activity);
			if (!DEFAULT.equals(activity) && !locations.contains(location))
			{
				location = DEFAULT;
				m_location.setSelectedItem(PREFIX + "location." + DEFAULT + "/name");
			}
		}
		else
			throw new IllegalArgumentException("Unable to match source");

		m_registry.setActiveDeviceGroup(location, activity);
	}
}


text:
layout: post
title: "Using DMS in your Sitecore 7 Search"
date: 2014-01-29 21:19
author: admin
comments: true
categories: [Sitecore]
tags: [DMS, Personalisation, Search, Sitecore 7]
---
Sitecore's Digital Marketing  System  (DMS) is a great suite of tools  that can enable profile matching and  personalisation within your Sitecore website. When used effectively you can really know what your website visitors are up to and act accordingly with a call-to-action or three!

If you're not already familiar with it's features I'd encourage you to read up on what's involved to get it working.  To start with, you'll need some website personas and a strategy. Once you have this, the rest is relatively straight forward.

DMS allows content editors to setup categories to describe and score data on each Sitecore item. With this in place, content can be personalised using the Rules Engine. All well and good, but what if I wanted to surface a range of personalised content and allow searching of content based on DMS categories? I've solved this particular issue recently by using Sitecore 7 Search with DMS and stored DMS data in the search index.

Since the evolution of Sitecore to version 7 there is now  an easier way to do this via Computed Index Fields. Computed Index fields allow you to run code at the time of indexing, enabling dynamic computed values for your fields.

So, I've put together some rough-and- ready sample code  below using computed index fields, that checks an item has DMS tracking and has profile keys assigned, and adds a list of strings representing categories to the search index.

``` csharp

    using Sitecore.Analytics.Configuration;
    using Sitecore.Analytics.Data;
    using Sitecore.ContentSearch;
    using Sitecore.ContentSearch.ComputedFields;
    using Sitecore.Data.Fields;
    using Sitecore.Data.Items;
    using System.Collections.Generic;
    using System.Linq;

    namespace Coreblimey.Business.Search.ComputedFields
    {
        public class DMSComputedField : IComputedIndexField
        {
            public string FieldName
            {
                get;
                set;
            }

            public string ReturnType
            {
                get;
                set;
            }

            public DMSComputedField()
            {
            }

            public object ComputeFieldValue(IIndexable indexable)
            {
                Item item = indexable as SitecoreIndexableItem;
                // Check analytics setup
                if (AnalyticsSettings.Enabled)
                {
                    Field field = item.Fields[Constants.DMSFields.Tracking];
                    if (field != null)
                    {
                        List<string> strs = new List<string>();
                        ContentProfile[] profiles = (new TrackingField(field)).Profiles;
                        if (profiles != null)
                        {
                            foreach (var profile in profiles)
                            {
                                // Get Profile Keys assigned
                                var listKeys = GetKeys((new TrackingField(field)), profile, 1);
                                if (listKeys.Count() > 0)
                                {
                                    strs.AddRange((from l in listKeys
                                                   select l.InnerItem["name"]).ToList());

                                }
                            }

                            return strs;
                        }
                    }
                }
                return new List<string>();
            }

            public static IEnumerable<ContentProfileKeyData> GetKeys(TrackingField trackingField, ContentProfile profile, int minimumScore)
            {
                var matchedKeys = new List<ContentProfileKeyData>();

                foreach (ContentProfileKeyData profileKey in profile.Keys)
                {
                    if (profileKey.Value >= minimumScore)
                    {
                        matchedKeys.Add(profileKey);
                    }
                }
                return matchedKeys;
            }

        }
    }

```

To get this to run, all you have to do is find the Computed Index Fields section in the indexes.config file, specify the  assembly and type of the ComputedIndex field code and jobs a good'un.  Then when you push an item into your search index, the computed field code will run and create a special field with your DMS categories.

``` xml
 <field fieldName="dmscategories" returnType="stringCollection">Coreblimey.Business.Search.ComputedFields.DMSComputedField,Coreblimey.Business</field>
```

With the content in the index, you can now unleash the power of Sitecore 7 search to allow searching  by DMS category and use current real time DMS data in tandem with indexed data to produce personalised, relevant content to your website users.

Hope there was something useful here. Until next time...

Ian


text:
package org.jetbrains.plugins.scala.lang.autoImport
package generated

class AutoImportFixingImportTest extends AutoImportTestBase {
  //This class was generated by build script, please don't change this
  override def folderPath: String = super.folderPath + "fixingImport/"

  def testFixImport(): Unit = doTest()

  def testImmutable(): Unit = doTest()
}


text:
jQuery(document).ready(function($){

    // navbar
    $(".button-collapse").sideNav();

    // select
    $('select').material_select();

});


text:
package cc.ccoder.model.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cc.ccoder.model.dao.ICategoryDao;
import cc.ccoder.model.entity.Category;
import cc.ccoder.model.service.ICategoryService;

@Service("iCategoryService")
public class CategoryServiceImpl implements ICategoryService {

	@Autowired
	private ICategoryDao iCategoryDao;

	@Override
	public Category selectById(Integer id) {
		return iCategoryDao.selectById(id);
	}

	@Override
	public List<Category> selectCategoryChildrenByParentId(Integer parentId) {
		return iCategoryDao.selectCategoryChildrenByParentId(parentId);
	}

	@Override
	public Map<Category, List<Category>> getCategories(Integer parentId) {
		//当前parentId下面的子分类信息
		List<Category> categories = selectCategoryChildrenByParentId(parentId);
		System.out.println("parentId分类 : "+categories);
		Map<Category, List<Category>> categoryMap = new HashMap<Category, List<Category>>();
		for(Category categoryItem : categories){
			categoryMap.put(categoryItem,selectCategoryChildrenByParentId(categoryItem.getId()));
		}
		return categoryMap;
	}

}


text:
var log = require('logmagic').local('web.middleware.logger');

module.exports = function() {
  return function logger(req, res, next) {
    req._startTime = new Date();

    // mount safety
    if (req._logging) {
      return next();
    }

    // flag as logging
    req._logging = true;

    // proxy end to output loggging
    var end = res.end;

    res.on('error', function(err) {
      log.error('Error has been emitted on the request object: ' + err.toString());
    });

    res.end = function(chunk, encoding) {
      // Make sure the end function actually executes
      res.end = end;
      res.end(chunk, encoding);

      // Build our logging information
      var obj = {};
      obj['response-time'] = new Date() - req._startTime;
      obj['remote-addr'] = req.socket &&
          (req.socket.remoteAddress ||
          (req.socket.socket && req.socket.socket.remoteAddress));
      obj.method = req.method;
      obj['http-version'] = req.httpVersionMajor + '.' + req.httpVersionMinor;
      obj.status = res.statusCode;
      obj['content-length'] = res._headers['content-length'];
      obj.referrer = req.headers.referer;
      obj['user-agent'] = req.headers['user-agent'];
      obj.txnId = req.txnId;

      // Log using logmagic our access info
      log.info(req.originalUrl, obj);
    };
    next();
  };
};


text:
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';

@inject(HttpClient)
export class Users {
  heading = 'Github Users';
  users = [];

  constructor(http) {
    this.http = http;
  }

  activate() {
    this.http.configure(config => {
      config
        .useStandardConfiguration()
        .withBaseUrl('https://api.github.com/');
    });

    return this.http.fetch('users')
      .then(response => response.json())
      .then(users => this.users = users);
  }
}


text:
namespace Screener.Log
{
    public class Logger
    {
        private static Logger _currentInstance;

        public static Logger Instance => _currentInstance ?? (_currentInstance = new Logger());

        public void Log(string text)
        {
            System.Console.WriteLine(text);
        }

        public void LogWarning(string text)
        {
            System.Console.WriteLine("[WARN]" + text);
        }
    }
}


text:
require 'spec_helper'
require 'omnibus-ctl'

RSpec.describe 'gitlab-ctl replicate-geo-database' do
  subject { Omnibus::Ctl.new('testing-ctl') }

  let(:required_arguments) do
    %w(--host=gitlab-primary.geo
       --slot-name=gitlab_primary_geo)
  end

  before do
    allow_any_instance_of(Omnibus::Ctl).to receive(:require).and_call_original
    allow_any_instance_of(Omnibus::Ctl).to receive(:require).with(
      '/opt/testing-ctl/embedded/service/omnibus-ctl-ee/lib/geo/replication'
    ) do
      require_relative('../../../files/gitlab-ctl-commands-ee/lib/geo/replication')
    end

    subject.load_file('files/gitlab-ctl-commands-ee/replicate_geo_database.rb')
  end

  it 'appends a geo replication command' do
    expect(subject.get_all_commands_hash).to include('replicate-geo-database')
  end

  describe "#replicate_geo_database" do
    it 'executes the geo replication command' do
      stub_command_arguments(required_arguments)

      expect(Geo::Replication).to receive(:new).and_call_original
        .with(subject, hash_including(host: 'gitlab-primary.geo',
                                      slot_name: 'gitlab_primary_geo'))

      expect_any_instance_of(Geo::Replication).to receive(:execute)

      replicate_geo_database
    end

    it 'applies defaults to optional arguments' do
      stub_command_arguments(required_arguments)

      expect(Geo::Replication).to receive(:new).and_call_original
        .with(subject, hash_including(host: 'gitlab-primary.geo',
                                      slot_name: 'gitlab_primary_geo',
                                      user: 'gitlab_replicator',
                                      port: 5432,
                                      password: nil,
                                      now: false,
                                      force: false,
                                      skip_backup: false,
                                      skip_replication_slot: false,
                                      backup_timeout: 1800,
                                      sslmode: 'verify-full',
                                      sslcompression: 0,
                                      recovery_target_timeline: 'latest',
                                      db_name: 'gitlabhq_production'))

      expect_any_instance_of(Geo::Replication).to receive(:execute)

      replicate_geo_database
    end

    it 'requires the host argument' do
      stub_command_arguments(%w(--slot-name=gitlab_primary_geo))

      expect(Geo::Replication).not_to receive(:new)

      # Important to catch this SystemExit or else RSpec exits
      expect { subject.replicate_geo_database }.to raise_error(SystemExit).and(
        output(/missing argument: host/).to_stdout
      )
    end

    it 'requires the slot-name argument' do
      stub_command_arguments(%w(--host=gitlab-primary.geo))

      expect(Geo::Replication).not_to receive(:new)

      # Important to catch this SystemExit or else RSpec exits
      expect { subject.replicate_geo_database }.to raise_error(SystemExit).and(
        output(/missing argument: --slot-name/).to_stdout
      )
    end

    context 'with SSL compression enabled' do
      it 'enables SSL compression' do
        stub_command_arguments(
          required_arguments +
            %w(--sslmode=disable
               --sslcompression=1
               --no-wait))

        expect(Geo::Replication).to receive(:new).and_call_original
          .with(subject, hash_including(host: 'gitlab-primary.geo',
                                        slot_name: 'gitlab_primary_geo',
                                        sslmode: 'disable',
                                        sslcompression: 1,
                                        now: true))

        expect_any_instance_of(Geo::Replication).to receive(:execute)

        replicate_geo_database
      end
    end

    context 'with db_name specified' do
      it 'sets the db_name option' do
        stub_command_arguments(
          required_arguments +
            %w(--db-name=custom_db_name))

        expect(Geo::Replication).to receive(:new).and_call_original
          .with(subject, hash_including(host: 'gitlab-primary.geo',
                                        slot_name: 'gitlab_primary_geo',
                                        db_name: 'custom_db_name'))

        expect_any_instance_of(Geo::Replication).to receive(:execute)

        replicate_geo_database
      end
    end
  end

  def stub_command_arguments(arguments)
    expect_any_instance_of(Omnibus::Ctl::GeoReplicationCommand)
      .to receive(:arguments).and_return(arguments)
  end

  def replicate_geo_database
    # GeoReplicationCommand is designed to `exit 1` when there is a problem
    # during option parsing. Tests that trigger this exit will also silently
    # exit RSpec immediately, *and* they will *not* fail.
    #
    # So if a test expects a successful call, we *must* catch at least
    # SystemExit for the test to be valid. And since other errors are always
    # possible, and should also fail the test, we don't need to specify
    # SystemExit here.
    #
    # In short, this is necessary for a failable test.
    expect { subject.replicate_geo_database }.not_to raise_error
  end
end


text:
var fs = require('fs')
var glob = require('glob');
var mkdirp = require('mkdirp');
var optimist = require('optimist');
var path = require('path');
var argv = optimist.argv;

function splitHeader(content) {
  var lines = content.split('\n');
  for (var i = 1; i < lines.length - 1; ++i) {
    if (lines[i] === '---') {
      break;
    }
  }
  return {
    header: lines.slice(1, i + 1).join('\n'),
    content: lines.slice(i + 1).join('\n')
  };
}

function backtickify(str) {
  var escaped = '`' + str.replace(/\\/g, '\\\\').replace(/`/g, '\\`') + '`';
  // Replace require( with require\( so node-haste doesn't replace example
  // require calls in the docs
  return escaped.replace(/require\(/g, 'require\\(');
}

function execute() {
  var MD_DIR = '../docs/';

  glob('src/flux/docs/*.*', function(er, files) {
    files.forEach(function(file) {
      try {
        fs.unlinkSync(file);
      } catch(e) {
        /* seriously, unlink throws when the file doesn't exist :( */
      }
    });
  });

  var metadatas = {
    files: [],
  };

  glob(MD_DIR + '**/*.*', function (er, files) {
    files.forEach(function(file) {
      var extension = path.extname(file);
      if (extension === '.md' || extension === '.markdown') {
        var content = fs.readFileSync(file, {encoding: 'utf8'});
        var metadata = {};

        // Extract markdown metadata header
        var both = splitHeader(content);
        var lines = both.header.split('\n');
        for (var i = 0; i < lines.length - 1; ++i) {
          var keyvalue = lines[i].split(':');
          var key = keyvalue[0].trim();
          var value = keyvalue.slice(1).join(':').trim();
          // Handle the case where you have "Community #10"
          try { value = JSON.parse(value); } catch(e) { }
          metadata[key] = value;
        }
        metadatas.files.push(metadata);

        if (metadata.permalink.match(/^https?:/)) {
          return;
        }

        // Create a dummy .js version that just calls the associated layout
        var layout = metadata.layout[0].toUpperCase() + metadata.layout.substr(1) + 'Layout';

        var content = (
          '/**\n' +
          ' * @generated\n' +
          ' * @jsx React.DOM\n' +
          ' */\n' +
          'var React = require("React");\n' +
          'var layout = require("' + layout + '");\n' +
          'var content = ' + backtickify(both.content) + '\n' +
          'var Post = React.createClass({\n' +
          '  render: function() {\n' +
          '    return layout({metadata: ' + JSON.stringify(metadata) + '}, content);\n' +
          '  }\n' +
          '});\n' +
          // TODO: Use React statics after upgrading React
          'Post.content = content;\n' +
          'module.exports = Post;\n'
        );

        var targetFile = 'src/flux/' + metadata.permalink.replace(/\.html$/, '.js');
        mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'), ''));
        fs.writeFileSync(targetFile, content);
      }

      if (extension === '.json') {
        var content = fs.readFileSync(file, {encoding: 'utf8'});
        metadatas[path.basename(file, '.json')] = JSON.parse(content);
      }
    });

    fs.writeFileSync(
      'core/metadata.js',
      '/**\n' +
      ' * @generated\n' +
      ' * @providesModule Metadata\n' +
      ' */\n' +
      'module.exports = ' + JSON.stringify(metadatas, null, 2) + ';'
    );
  });
}

if (argv.convert) {
  console.log('convert!')
  execute();
}

module.exports = execute;


text:
package com.timgroup.eventsubscription;

import com.codahale.metrics.Counter;
import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.dsl.Disruptor;
import com.timgroup.eventstore.api.Position;
import com.timgroup.eventstore.api.ResolvedEvent;
import com.timgroup.eventsubscription.lifecycleevents.CaughtUp;
import com.timgroup.eventsubscription.lifecycleevents.InitialCatchupCompleted;

import java.time.Clock;
import java.util.Optional;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;

import static java.util.Objects.requireNonNull;

public class EventStoreChaser implements Runnable {
    private final Function<Position, Stream<ResolvedEvent>> eventSource;
    private final Disruptor<EventContainer> disruptor;
    private final ChaserListener listener;
    private final EventContainer.Translator translator = new EventContainer.Translator();
    private final Supplier<Boolean> isRunning;

    private Position lastPosition;
    private final Clock clock;
    private final Optional<Counter> counter;
    private boolean initialCatchupCompleted;

    public EventStoreChaser(
            Function<Position, Stream<ResolvedEvent>> eventSource,
            Position startingPosition,
            Disruptor<EventContainer> disruptor,
            ChaserListener listener,
            Clock clock,
            Optional<Counter> counter,
            Supplier<Boolean> isRunning) {
        this.eventSource = requireNonNull(eventSource);
        this.disruptor = disruptor;
        this.listener = requireNonNull(listener);
        this.lastPosition = requireNonNull(startingPosition);
        this.clock = clock;
        this.counter = counter;
        this.isRunning = isRunning;
    }

    @Override
    public void run() {
        try {
            try (Stream<ResolvedEvent> stream = eventSource.apply(lastPosition)) {
                stream.forEachOrdered(nextEvent -> {
                    checkForShutdown();
                    listener.chaserReceived(nextEvent.position());
                    lastPosition = nextEvent.position();
                    publish(translator.setting(nextEvent));
                });
            }

            if (initialCatchupCompleted) {
                publish((event, sequence) -> {
                    event.deserializedEvent = new CaughtUp(lastPosition, clock.instant());
                    event.position = lastPosition;
                });
            } else {
                initialCatchupCompleted = true;
                publish((event, sequence) -> {
                    event.deserializedEvent = new InitialCatchupCompleted(lastPosition, clock.instant());
                    event.position = lastPosition;
                });
            }
            listener.chaserUpToDate(lastPosition);
            counter.ifPresent(Counter::inc);
        } catch (ShutdownException e) {
            // Ignore
        } catch (Exception e) {
            listener.transientFailure(e);
        }
    }

    private void checkForShutdown() throws ShutdownException {
        if (!isRunning.get()) {
            throw new ShutdownException();
        }
    }

    private void publish(EventTranslator<EventContainer> eventTranslator) throws ShutdownException {
        while (!disruptor.getRingBuffer().tryPublishEvent(eventTranslator)) {
            checkForShutdown();
            LockSupport.parkNanos(1);
        }
    }

    private static class ShutdownException extends RuntimeException {
    }
}


text:
using BuildIt.Forms.Sample.Core.ViewModels;
using System;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace BuildIt.Forms.Sample
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CustomControl : ContentView
    {
        public CustomViewModel ViewModel => BindingContext as CustomViewModel;

        public CustomControl()
        {
            InitializeComponent();

            BindingContext = new CustomViewModel();
        }

        public void ShowClicked(object sender, EventArgs e)
        {
            ViewModel.SwitchStates(true);
            // VisualStateManager.GoToState(this, "Show");
        }

        public void HideClicked(object sender, EventArgs e)
        {
            ViewModel.SwitchStates(false);
            // VisualStateManager.GoToState(this, "Hide");
        }

        public async Task BindVisualStates()
        {
            await VisualStateManager.Bind(this, ViewModel.StateManager);
        }
    }
}


text:
@extends('layout.default')

@section('title', $__t('Batteries overview'))
@section('activeNav', 'batteriesoverview')
@section('viewJsName', 'batteriesoverview')

@push('pageStyles')
<link href="{{ $U('/node_modules/animate.css/animate.min.css?v=', true) }}{{ $version }}"
	rel="stylesheet">
@endpush

@section('content')

@yield('title')

			<button class="btn btn-outline-dark d-md-none mt-2 float-right order-1 order-md-3"
				type="button"
				data-toggle="collapse"
				data-target="#related-links">

			</button>

					{{ $__t('Journal') }}

					{{ $__t('Clear filter') }}

			<input type="text"
				id="search"
				class="form-control"
				placeholder="{{ $__t('Search') }}">

				 {{ $__t('Status') }}

			<select class="custom-control custom-select"
				id="status-filter">
				<option value="all">{{ $__t('All') }}</option>
				<option value="duesoon">{{ $__t('Due soon') }}</option>
				<option value="overdue">{{ $__t('Overdue') }}</option>
			</select>

					{{ $__t('Battery') }}
					{{ $__t('Used in') }}
					{{ $__t('Last charged') }}
					{{ $__t('Next planned charge cycle') }}
					Hidden status

					@include('components.userfields_thead', array(
					'userfields' => $userfields
					))

				@foreach($current as $currentBatteryEntry)

battery_id }}-row"
					class="@if(FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->charge_interval_days > 0 && $currentBatteryEntry->next_estimated_charge_time < date('Y-m-d H:i:s')) table-danger @elseif(FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->charge_interval_days > 0 && $currentBatteryEntry->next_estimated_charge_time < date('Y-m-d H:i:s', strtotime('+' . $nextXDays . ' days')))
					table-warning
					@endif">

						battery_id }}"
							data-battery-name="{{ FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->name }}">

							<button class="btn btn-sm btn-light text-secondary"
								type="button"
								data-toggle="dropdown">

							</button>

								battery_id }}"
									type="button"
									href="#">
									{{ $__t('Battery overview') }}

								battery_id }}">
									{{ $__t('Battery journal') }}

								battery_id }}?embedded">
									{{ $__t('Edit battery') }}

								battery_id . '/grocycode?download=true') }}">
									{!! str_replace('grocycode', 'grocycode', $__t('Download %s grocycode', $__t('Battery'))) !!}

								@if(GROCY_FEATURE_FLAG_LABEL_PRINTER)
								battery_id }}"
									type="button"
									href="#">
									{!! str_replace('grocycode', 'grocycode', $__t('Print %s grocycode on label printer', $__t('Battery'))) !!}

								@endif

					battery_id }}">
						{{ FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->name }}

						{{ FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->used_in }}

						battery_id }}-last-tracked-time">{{ $currentBatteryEntry->last_tracked_time }}
						<time id="battery-{{ $currentBatteryEntry->battery_id }}-last-tracked-time-timeago"
							class="timeago timeago-contextual"
							datetime="{{ $currentBatteryEntry->last_tracked_time }}"></time>

						@if(FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->charge_interval_days > 0)
						battery_id }}-next-charge-time">{{ $currentBatteryEntry->next_estimated_charge_time }}
						<time id="battery-{{ $currentBatteryEntry->battery_id }}-next-charge-time-timeago"
							class="timeago timeago-contextual"
							datetime="{{ $currentBatteryEntry->next_estimated_charge_time }}"></time>
						@else
						...
						@endif

						"@if(FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->charge_interval_days > 0 && $currentBatteryEntry->next_estimated_charge_time < date('Y-m-d
							H:i:s'))
							overdue
							@elseif(FindObjectInArrayByPropertyValue($batteries, 'id'
							,
							$currentBatteryEntry->battery_id)->charge_interval_days > 0 && $currentBatteryEntry->next_estimated_charge_time < date('Y-m-d
								H:i:s',
								strtotime('+'
								.
								$nextXDays
								. ' days'
								)))
								duesoon
								@endif

								@include('components.userfields_tbody',
								array( 'userfields'=> $userfields,
								'userfieldValues' => FindAllObjectsInArrayByPropertyValue($userfieldValues, 'object_id', $currentBatteryEntry->battery_id)
								))

				@endforeach

				@include('components.batterycard')

				<button type="button"
					class="btn btn-secondary"
					data-dismiss="modal">{{ $__t('Close') }}</button>

@stop


text:
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Maps_red\TicketingBundle\Entity\TicketKeyword as BaseTicketKeyword;

/**
 * @ORM\Entity(repositoryClass="App\Repository\TicketKeywordRepository")
 */
class TicketKeyword extends BaseTicketKeyword
{
}


text:
from sakia.data.entities import Identity
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsSceneContextMenuEvent

class BaseScene(QGraphicsScene):
    # This defines signals taking string arguments
    node_context_menu_requested = pyqtSignal(Identity)
    node_hovered = pyqtSignal(str)
    node_clicked = pyqtSignal(str, dict)

    def __init__(self, parent=None):
        super().__init__(parent)


text:
/*
 *   dewarptest2.c
 *
 *   This runs the basic functions for a single page.  It can be used
 *   to debug the disparity model-building.
 *
 *     dewarptest2 method [image pageno]
 *
 *     where: method = 1 (use single page dewarp function)
 *                     2 (break down into multiple steps)
 *
 *   Default image is cat.035.jpg.
 *   Others are 1555.007.jpg, shearer.148.tif, etc.
 */

#include "allheaders.h"

#define  NORMALIZE     1

l_int32 main(int    argc,
             char **argv)
{
l_int32      method, pageno;
L_DEWARP    *dew1;
L_DEWARPA   *dewa;
PIX         *pixs, *pixn, *pixg, *pixb, *pixd;
static char  mainName[] = "dewarptest2";

    if (argc != 2 && argc != 4)
        return ERROR_INT("Syntax: dewarptest2 method [image pageno]",
                         mainName, 1);

    if (argc == 2) {
        pixs = pixRead("cat.035.jpg");
        pageno = 35;
    }
    else {
        pixs = pixRead(argv[2]);
        pageno = atoi(argv[3]);
    }
    if (!pixs)
        return ERROR_INT("image not read", mainName, 1);
    method = atoi(argv[1]);
    lept_mkdir("lept/dewarp");

    if (method == 1) {  /* Use single page dewarp function */
        dewarpSinglePage(pixs, 0, 1, 1, 0, &pixd, NULL, 1);
        pixDisplay(pixd, 100, 100);
    } else {  /* Break down into multiple steps; require min of only 8 lines */
        dewa = dewarpaCreate(40, 30, 1, 8, 50);
        dewarpaUseBothArrays(dewa, 1);
        dewarpaSetCheckColumns(dewa, 0);

#if NORMALIZE
            /* Normalize for varying background and binarize */
        pixn = pixBackgroundNormSimple(pixs, NULL, NULL);
        pixg = pixConvertRGBToGray(pixn, 0.5, 0.3, 0.2);
        pixb = pixThresholdToBinary(pixg, 130);
        pixDestroy(&pixn);
#else
            /* Don't normalize; just threshold and clean edges */
        pixg = pixConvertTo8(pixs, 0);
        pixb = pixThresholdToBinary(pixg, 100);
        pixSetOrClearBorder(pixb, 30, 30, 40, 40, PIX_CLR);
#endif

            /* Run the basic functions */
        dew1 = dewarpCreate(pixb, pageno);
        dewarpaInsertDewarp(dewa, dew1);
        dewarpBuildPageModel(dew1, "/tmp/lept/dewarp/test2_model.pdf");
        dewarpaApplyDisparity(dewa, pageno, pixg, -1, 0, 0, &pixd,
                              "/tmp/lept/dewarp/test2_apply.pdf");

        dewarpaInfo(stderr, dewa);
        dewarpaDestroy(&dewa);
        pixDestroy(&pixg);
        pixDestroy(&pixb);
    }

    pixDestroy(&pixs);
    pixDestroy(&pixd);
    return 0;
}


text:
package com.yokmama.learn10.chapter07.lesson33;

import android.content.Context;
import android.os.Build;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * RecyclerViewのアイテムのクリックを取得するイベントリスナー
 *
 * Created by yokmama on 15/05/07.
 */
public abstract class ItemClickListener implements RecyclerView.OnItemTouchListener{
    private final GestureDetectorCompat mGestureDetector;

    public ItemClickListener(RecyclerView recyclerView){
        //RecyclerViewに対するジェスチャーを検出するためGestureDetectorを生成
        mGestureDetector = new ItemClickGestureDetector(recyclerView.getContext(),
                new ItemClickGestureListener(recyclerView));
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        if (!isAttachedToWindow(rv) || !hasAdapter(rv)) {
            return false;
        }

        //RecyclerViewに対するタッチイベントをGestureDetectorにて処理する
        mGestureDetector.onTouchEvent(e);
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean b) {
        //子のViewのうち、OnTouchをインターセプトする必要が発生した場合に呼ばれる。
    }

    /***
     * クリック時に呼ばれる
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     * @return
     */
    abstract boolean performItemClick(RecyclerView parent, View view, int position, long id);

    /***
     * ロングクリック時に呼ばれる
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     * @return
     */
    abstract boolean performItemLongClick(RecyclerView parent, View view, int position, long id);

    /***
     * RecyclerViewが画面にアタッチされているかどうか判断
     *
     * @param hostView
     * @return
     */
    private boolean isAttachedToWindow(RecyclerView hostView) {
        if (Build.VERSION.SDK_INT >= 19) {
            return hostView.isAttachedToWindow();
        } else {
            return (hostView.getHandler() != null);
        }
    }

    /***
     * RecyclerViewにAdapterが設定されているかどうか判断
     *
     * @param hostView
     * @return
     */
    private boolean hasAdapter(RecyclerView hostView) {
        return (hostView.getAdapter() != null);
    }

    /***
     * クリック処理のみ検出するGestureDetector
     *
     */
    private class ItemClickGestureDetector extends GestureDetectorCompat {
        private final ItemClickGestureListener mGestureListener;

        public ItemClickGestureDetector(Context context, ItemClickGestureListener listener) {
            super(context, listener);
            mGestureListener = listener;
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            final boolean handled = super.onTouchEvent(event);

            final int action = event.getAction() & MotionEventCompat.ACTION_MASK;
            if (action == MotionEvent.ACTION_UP) {
                mGestureListener.dispatchSingleTapUpIfNeeded(event);
            }

            return handled;
        }
    }

    /***
     * クリック処理に応じて、シングルクリックかロングクリックか判定し、
     * それぞれ設定されたリスナーメソッドをコールする
     *
     */
    private class ItemClickGestureListener extends GestureDetector.SimpleOnGestureListener {
        private final RecyclerView mRecyclerView;
        private View mTargetChild;
        public ItemClickGestureListener(RecyclerView recyclerView) {
            mRecyclerView = recyclerView;
        }

        public void dispatchSingleTapUpIfNeeded(MotionEvent event) {
            if (mTargetChild != null) {
                onSingleTapUp(event);
            }
        }

        @Override
        public boolean onDown(MotionEvent event) {
            final int x = (int) event.getX();
            final int y = (int) event.getY();

            mTargetChild = mRecyclerView.findChildViewUnder(x, y);
            return (mTargetChild != null);
        }

        @Override
        public void onShowPress(MotionEvent event) {
            if (mTargetChild != null) {
                mTargetChild.setPressed(true);
            }
        }

        @Override
        public boolean onSingleTapUp(MotionEvent event) {
            boolean handled = false;

            if (mTargetChild != null) {
                mTargetChild.setPressed(false);

                final int position = mRecyclerView.getChildPosition(mTargetChild);
                final long id = mRecyclerView.getAdapter().getItemId(position);
                handled = performItemClick(mRecyclerView, mTargetChild, position, id);

                mTargetChild = null;
            }

            return handled;
        }

        @Override
        public boolean onScroll(MotionEvent event, MotionEvent event2, float v, float v2) {
            if (mTargetChild != null) {
                mTargetChild.setPressed(false);
                mTargetChild = null;

                return true;
            }

            return false;
        }

        @Override
        public void onLongPress(MotionEvent event) {
            if (mTargetChild == null) {
                return;
            }

            final int position = mRecyclerView.getChildPosition(mTargetChild);
            final long id = mRecyclerView.getAdapter().getItemId(position);
            final boolean handled = performItemLongClick(mRecyclerView, mTargetChild, position, id);

            if (handled) {
                mTargetChild.setPressed(false);
                mTargetChild = null;
            }
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>search.js - RDoc Documentation</title>

<link href="../../fonts.css" rel="stylesheet">
<link href="../../rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Pages

Gemfile

Gemfile.lock

MIT-LICENSE

README

Rakefile

autofactura.gemspec

ActiveSupport.html

ApplicationController.html

ApplicationHelper.html

Autofactura.html

Articulo.html

Autofactura.html

Comprobante.html

Concepto.html

Domicilio.html

Impuesto.html

Nota.html

Receptor.html

Remision.html

Serie.html

AutofacturaTest.html

Dummy.html

Application.html

Gemfile.html

Gemfile_lock.html

MIT-LICENSE.html

Object.html

README_rdoc.html

Rakefile.html

autofactura_gemspec.html

fonts.css

index.html

darkfish.js

jquery.js

navigation.js

search.js

search_index.js

searcher.js

autofactura_tasks_rake.html

rdoc.css

Autofactura_html.html

Serie_html.html

Autofactura_html.html

README_rdoc_html.html

index_html.html

darkfish_js.html

jquery_js.html

navigation_js.html

search_index_js.html

search_js.html

searcher_js.html

rdoc_css.html

table_of_contents_html.html

table_of_contents.html

README_rdoc.html

Rakefile.html

application_js.html

application_css.html

config_ru.html

test_log.html

404_html.html

422_html.html

500_html.html

favicon_ico.html

autofactura_tasks.rake

Autofactura.html

Autofactura.html

Serie.html

README_rdoc.html

index.html

darkfish.js

jquery.js

navigation.js

search.js

search_index.js

searcher.js

rdoc.css

table_of_contents.html

README

Rakefile

application.js

application.css

config.ru

test.log

404.html

422.html

500.html

favicon.ico

Search = function(data, input, result) {

this.data = data;
this.$input = $(input);
this.$result = $(result);

this.$current = null;
this.$view = this.$result.parent();
this.searcher = new Searcher(data.index);
this.init();

}

Search.prototype = $.extend({}, Navigation, new function() {

var suid = 1;

this.init = function() {
  var _this = this;
  var observer = function() {
    _this.search(_this.$input[0].value);
  };
  this.$input.keyup(observer);
  this.$input.click(observer); // mac's clear field

  this.searcher.ready(function(results, isLast) {
    _this.addResults(results, isLast);
  })

  this.initNavigation();
  this.setNavigationActive(false);
}

this.search = function(value, selectFirstMatch) {
  value = jQuery.trim(value).toLowerCase();
  if (value) {
    this.setNavigationActive(true);
  } else {
    this.setNavigationActive(false);
  }

  if (value == '') {
    this.lastQuery = value;
    this.$result.empty();
    this.setNavigationActive(false);
  } else if (value != this.lastQuery) {
    this.lastQuery = value;
    this.firstRun = true;
    this.searcher.find(value);
  }
}

this.addResults = function(results, isLast) {
  var target = this.$result.get(0);
  if (this.firstRun && (results.length > 0 || isLast)) {
    this.$current = null;
    this.$result.empty();
  }

  for (var i=0, l = results.length; i < l; i++) {
    target.appendChild(this.renderItem.call(this, results[i]));
  };

  if (this.firstRun && results.length > 0) {
    this.firstRun = false;
    this.$current = $(target.firstChild);
    this.$current.addClass('current');
  }
  if (jQuery.browser.msie) this.$element[0].className += '';
}

this.move = function(isDown) {
  if (!this.$current) return;
  var $next = this.$current[isDown ? 'next' : 'prev']();
  if ($next.length) {
    this.$current.removeClass('current');
    $next.addClass('current');
    this.scrollIntoView($next[0], this.$view[0]);
    this.$current = $next;
  }
  return true;
}

this.hlt = function(html) {
  return this.escapeHTML(html).
    replace(/\u0001/g, '<em>').
    replace(/\u0002/g, '</em>');
}

this.escapeHTML = function(html) {
  return html.replace(/[&<>]/g, function(c) {
    return '&#' + c.charCodeAt(0) + ';';
  });
}

});

Validate

Generated by RDoc 4.1.1.

Based on Darkfish by Michael Granger.


text:
'use strict';

/**
 * The result of a request to list container registry operations.
 */
class OperationListResult extends Array {
  /**
   * Create a OperationListResult.
   * @property {string} [nextLink] The URI that can be used to request the next
   * list of container registry operations.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of OperationListResult
   *
   * @returns {object} metadata of OperationListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'OperationListResult',
      type: {
        name: 'Composite',
        className: 'OperationListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'OperationDefinitionElementType',
                  type: {
                    name: 'Composite',
                    className: 'OperationDefinition'
                  }
              }
            }
          },
          nextLink: {
            required: false,
            serializedName: 'nextLink',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = OperationListResult;


text:
run_stat() {
	file=$1
	extra=$2
	if [ x$(uname -s) = xDarwin ]; then
		stat -f "%N: size=%z bytes $extra" $file
	else
		stat -c "%n: size=%s bytes $extra" $file
	fi
}

TIMES=1000000
AA=./atomic_append
FILES="f1 f2"

# delete files if already present
rm -f $FILES

# run with append
echo "Running with append $TIMES times"
$AA f1 $TIMES & $AA f1 $TIMES &
wait

# run without append
echo "Running without append $TIMES times"
$AA f2 $TIMES x & $AA f2 $TIMES x &
wait

# print file sizes
run_stat f1 "(with append)"
run_stat f2 "(without append)"

# clean up
rm -f $FILES


text:
package org.thingsboard.server.common.data.sync.ie;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class EntityExportSettings {
    private boolean exportRelations;
    private boolean exportAttributes;
    private boolean exportCredentials;
}


text:
require_relative 'meta_getter'

module GoodData
  module Mixin
    module MetaPropertyWriter
      def metadata_property_writer(*props)
        props.each do |prop|
          define_method "#{prop}=", proc { |val| meta[prop.to_s] = val }
        end
      end
    end
  end
end