text:
weinre is WEb INspector REmote.
Pronounced like the word "winery".  Or maybe like the word "weiner".  Who knows,
really.

weinre is a debugger for web pages, like
FireBug (for FireFox)
and
Web Inspector (for WebKit-based browsers), except it's designed
to work remotely, and in particular, to allow you debug web pages
on a mobile device such as a phone.

Interesting places to visit:

videos at YouTube:
http://www.youtube.com/results?search_query=weinre

this documentation:
http://people.apache.org/~pmuellr/weinre/ [temporary]

unofficial binary packages:
http://people.apache.org/~pmuellr/weinre/ [temporary]

issues:
https://issues.apache.org/jira/gobble-de-gook/...

create a new issue:

bug
or
new feature

cloneable source at Apache:
https://git-wip-us.apache.org/repos/asf/cordova-weinre.git

Apache repo cloned at GitHub:
https://github.com/apache/cordova-weinre

mailing lists at Apache:
http://mail-archives.apache.org/mod_mbox/cordova-dev/ (for weinre development)

discussion at Google Group:
http://groups.google.com/group/weinre (for weinre usage)

More information on weinre's big brothers, Web Inspector / Google Chrome
Developer Tools, is available at
Google's Chrome Dev Tools pages
and
Apple's Web Inspector pages.

If you aren't familiar with FireBug or Web Inspector,
weinre isn't going to make too much sense to you.
weinre reuses the user interface code from the
Web Inspector project at WebKit,
so if you've used Safari's Web Inspector or Chrome's Developer Tools,
weinre will be very familiar.  If you're not
familiar with Web Inspector, the links above to Google's and Apple's documentation
will be useful.

Here's an example session using weinre:

Two screen captures are shown above.  On the left is the
weinre client application, displaying debug
information.
On the right is the target web page, running in Mobile Safari in the iOS Simulator.

In normal usage, you will be running the client application in a browser
on your desktop/laptop, and running a target web page on your mobile device.

In the session above, the debugger is display the Elements panel, with the
embedded console expanded in the bottom third of the window.  In the console
area, we've entered two statements:

document.body.style.backgroundColor
document.body.style.backgroundColor = "pink"

The result of running the first statement shows the value of the body's background style is not set.
The second statement sets the body's background to pink.  That horrifying pink
background is then rendered in the target's window.

In addition, an <tt>h1</tt> element is selected in the upper third of the
Elements panel, which causes the side panels on the right to be filled in with
relevant information.  In this case, the matched CSS rules for that <tt>h1</tt>
element are being shown.

If you are familiar with WebKit's Web Inspector,
a partial list of differences between it and weinre
are listed below:

weinre does not make use of any 'native' code
in the browser, it's all plain old boring JavaScript.

Because weinre doesn't use 'native' code,
it's functionality is limited.  For instance, source level debug of JavaScript
is not possible
easy.

Because weinre doesn't use 'native' code,
the debug target code will run on browsers
without specialized debug support.  For instance, a browser running on your phone.

weinre supports 'remote' interaction,
so you can run the debugger user interface on one
machine and can debug a web page running
on another machine.  For instance, debug a web page displayed on your phone from your
laptop.

Because weinre supports 'remote' interaction,
multiple debug clients can be debugging the same debug target at the same time.

One thing not different from Web Inspector is that the debug client
user interface only runs on WebKit-based browsers.

Supported Libraries and Platforms

Generally version numbers listed here are the earliest
versions of the relevant thing that have been tested.
Later versions of those things are also hopefully supported,
but let us know.

Libraries not supported

versions of Prototype.js before version 1.7 are not supported,
as they do not support the <tt>JSON.stringify()</tt> API correctly.  You
will get an <tt>alert()</tt> in the web page you are debugging if you
attempt to debug it with weinre and you are using an unsupported
version of Prototype.js.

Platforms supported - debug server

Any platform that supports node.js.

Platforms supported - debug client

The browser where the debugger user interface runs.

Google Chrome

Apple Safari

Other recent-ish WebKit-based browsers

Platforms supported - debug target

The browser with the page you are debugging.

Android Browser application

iOS Mobile Safari application

PhoneGap/Cordova

other

Platforms not supported - debug target

iOS 3.1.3 or earlier

webOS 1.45 or earlier


text:
package com.mongodb.memphis.config.adapters;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.mongodb.ReadPreference;

public class ReadPreferenceTypeAdapter extends TypeAdapter<ReadPreference> {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void write(JsonWriter out, ReadPreference value) throws IOException {
		if (value != null) {
			out.value(value.getName());
		}
		else {
			out.nullValue();
		}
	}

	@Override
	public ReadPreference read(JsonReader in) throws IOException {
		return ReadPreference.valueOf(in.nextString());
	}

}

redpajama_set_name: RedPajamaGithub


text:
Doghouse Location
=================

List your store locations in the frontend and manage them in the admin section. Again, continuing the trend of things that make no design-decisions for you, this module doesn't actually show anything in the frontend. It just comes with a nice backend interface.

## Features

- Really nice Adminhtml grid with day of the week sorting, store location - opening hour relations, image preview and everything
- Comes free with foreign keys and all that stuff
- It doesn't do anything on the front-end. That's up to you
- You can put stuff in it in the admin panel

## Screenshot

![Doghouse Location screenshot of admin panel](doghouse_location_screenshot.png?raw=true "Doghouse Location screenshot of admin panel")

## Installation

Install using **Composer** (preferred) or **Modman**. Don't just drag this into your project without being aware of the directory structure.

## Docs

Here's a list of things you can do with it.

Getting a collection of your store locations. Wow!

`Mage::getModel('dhlocation/location')->getCollection();`

Getting a collection of your opening hours by location `$id`, and sorting them by weekday.

	Mage::getModel('dhlocation/hour')->getCollection()
		->addFieldToFilter('location_id', $id)
		->sortByWeekDay();

Showing how nice your store with `$id` is.

	$store = Mage::getModel('dhlocation/location')->load($id);

	echo '<img src="' . $this->quoteEscape(Mage::helper('dhlocation')->getImage($store)) . '"/>'

That's it.

## About

Created by [Doghouse](http://doghouse.agency/) because we needed a user-friendly way of getting store locations in the database. It's bloat free, has plenty of events that you can listen to (if that's your thing), and can be used in any project because it doesn't output any HTML or make any design decisions for you.

## License

[MIT License](https://opensource.org/licenses/MIT)


text:
- Move to GitHub Actions and drop Python 2.7 support completely
- Added a Graph class in the module graph, which allows accessing vertices by names instead of indices
- Added alternative versions of union_rectangles
- Added an alternative version of bellman_ford which marks with distance -infinity the vertices reachable from the source by paths of arbitrary small weight
- Added an alternative version of subsetsum
- Added FenwickMin, a minimum variant of Fenwick Trees
- Added module fft for the Fast Fourier Transformation
- Added module karatsuba for multiplying polynomials
- Added module pareto for computing the Pareto set in 2 or 3 dimensions
- An alternative version of floyd_warshall added by Pascal Ortiz
- Changed the web host of the documentation
- Corrected the function building the Huffman tree
- Fenwick Trees indices now start at zero
- Removed erroneous PQ_trees
- Renamed module eratosthene into primes. Added the Gries-Misra sieve in this module
- Simplified interval_cover
- Simplified knuth_morris_pratt.maximum_border_length

## 1.3

- Added LazySegmentTree
- Added shortest_cycle
- Functions and classes are now provided also directly by tryalgo without the need to specify the module

## 1.2

- Added horn\_sat
- Added partition_refinement
- Added left\_right\_inversions


text:
package org.datavec.local.transforms.transform.rank;

import org.datavec.api.transform.ColumnType;
import org.datavec.api.transform.TransformProcess;
import org.datavec.api.transform.schema.Schema;
import org.datavec.api.writable.DoubleWritable;
import org.datavec.api.writable.Text;
import org.datavec.api.writable.Writable;
import org.datavec.api.writable.comparator.DoubleWritableComparator;
import org.datavec.local.transforms.LocalTransformExecutor;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.nd4j.common.tests.tags.TagNames;

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

import static org.junit.jupiter.api.Assertions.assertEquals;
@Tag(TagNames.FILE_IO)
@Tag(TagNames.JAVA_ONLY)
public class TestCalculateSortedRank  {

    @Test
    public void testCalculateSortedRank() {

        List<List<Writable>> data = new ArrayList<>();
        data.add(Arrays.asList((Writable) new Text("0"), new DoubleWritable(0.0)));
        data.add(Arrays.asList((Writable) new Text("3"), new DoubleWritable(0.3)));
        data.add(Arrays.asList((Writable) new Text("2"), new DoubleWritable(0.2)));
        data.add(Arrays.asList((Writable) new Text("1"), new DoubleWritable(0.1)));

        List<List<Writable>> rdd = (data);

        Schema schema = new Schema.Builder().addColumnsString("TextCol").addColumnDouble("DoubleCol").build();

        TransformProcess tp = new TransformProcess.Builder(schema)
                        .calculateSortedRank("rank", "DoubleCol", new DoubleWritableComparator()).build();

        Schema outSchema = tp.getFinalSchema();
        assertEquals(3, outSchema.numColumns());
        assertEquals(Arrays.asList("TextCol", "DoubleCol", "rank"), outSchema.getColumnNames());
        assertEquals(Arrays.asList(ColumnType.String, ColumnType.Double, ColumnType.Long), outSchema.getColumnTypes());

        List<List<Writable>> out = LocalTransformExecutor.execute(rdd, tp);

        List<List<Writable>> collected = out;
        assertEquals(4, collected.size());
        for (int i = 0; i < 4; i++)
            assertEquals(3, collected.get(i).size());

        for (List<Writable> example : collected) {
            int exampleNum = example.get(0).toInt();
            int rank = example.get(2).toInt();
            assertEquals(exampleNum, rank);
        }
    }

}


text:
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Perspex.Xaml.Base.UnitTest.SampleModel
{
    public abstract class PropertyChangeNotifier : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


text:
Rails gem to serialize attributes to string with as_json/to_json method.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'as_json_string_attributes', :git => 'https://github.com/alantseng7/as_json_string_attributes.git'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install as_json_string_attributes

## Usage

In your model class which you want to serilize it's attributes to json string with as\_json / to\_json. Include AsJsonStringAttributes in the class to use the module and use set\_json\_string\_attributes to set the attributes that you want to serilize.

```ruby
class Post < ActiveRecord::Base
	include AsJsonStringAttributes

	set_json_string_attributes :id, :user_id
end
```

In this example, the :id and :user will be serilized to json string with as\_json / to\_json. The following example was ran in rails console mode:

	$ post
 	=> #<Post id: 1095709597894710274, user_id: 1095708658118956033, content: "Testing!", created_at: "2015-10-14 16:06:24", updated_at: "2015-10-14 16:06:24">
 	$ post.to_json
 	=> "{\"id\":\"1095709597894710274\",\"user_id\":\"1095708658118956033\",\"content\":\"Testing!\",\"created_at\":\"2015-10-14T16:06:24.431Z\",\"updated_at\":\"2015-10-14T16:06:24.431Z\"}"

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/alantseng7/as_json_string_attributes.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
<TwilioResponse>
    <Account>
        <Sid>:mysid</Sid>
        <OwnerAccountSid>:mysid</OwnerAccountSid>
        <FriendlyName>my Account</FriendlyName>
        <Status>active</Status>
        <DateCreated>Tue, 20 May 2014 23:44:17 +0000</DateCreated>
        <DateUpdated>Wed, 28 May 2014 22:20:41 +0000</DateUpdated>
        <AuthToken>bd02cf790a08d9223d4044390b25b0f7</AuthToken>
        <Type>Trial</Type>
        <Uri>/2010-04-01/Accounts/:mysid</Uri>
        <SubresourceUris>
            <Applications>/2010-04-01/Accounts/mysid/Applications</Applications>
            <AuthorizedConnectApps>/2010-04-01/Accounts/:mysid/AuthorizedConnectApps
            </AuthorizedConnectApps>
            <AvailablePhoneNumbers>/2010-04-01/Accounts/:mysid/AvailablePhoneNumbers
            </AvailablePhoneNumbers>
            <Calls>/2010-04-01/Accounts/:mysid/Calls</Calls>
            <Conferences>/2010-04-01/Accounts/:mysid/Conferences</Conferences>
            <ConnectApps>/2010-04-01/Accounts/:mysid/ConnectApps</ConnectApps>
            <IncomingPhoneNumbers>/2010-04-01/Accounts/:mysid/IncomingPhoneNumbers
            </IncomingPhoneNumbers>
            <Media>/2010-04-01/Accounts/:mysid/Media</Media>
            <Messages>/2010-04-01/Accounts/:mysid/Messages</Messages>
            <Notifications>/2010-04-01/Accounts/:mysid/Notifications</Notifications>
            <OutgoingCallerIds>/2010-04-01/Accounts/:mysid/OutgoingCallerIds
            </OutgoingCallerIds>
            <Queues>/2010-04-01/Accounts/:mysid/Queues</Queues>
            <Recordings>/2010-04-01/Accounts/:mysid/Recordings</Recordings>
            <Sandbox>/2010-04-01/Accounts/:mysid/Sandbox</Sandbox>
            <SIP>/2010-04-01/Accounts/:mysid/SIP</SIP>
            <SMSMessages>/2010-04-01/Accounts/:mysid/SMS/Messages</SMSMessages>
            <Transcriptions>/2010-04-01/Accounts/:mysid/Transcriptions</Transcriptions>
            <Usage>/2010-04-01/Accounts/:mysid/Usage</Usage>
        </SubresourceUris>
    </Account>
</TwilioResponse>


text:
using System;
using System.Collections;
using TouchScript.Gestures;
using UnityEngine;

public class LongPress_Button : MonoBehaviour
{
    public GameObject Plane;

    private Transform button, thebase;
    private float timeToPress;
    private Vector3 startScale, targetScale;

    private void Awake()
    {
        button = transform.FindChild("Button");
        thebase = transform.FindChild("Base");
        startScale = button.localScale;
        targetScale = thebase.localScale;
    }

    private void OnEnable()
    {
        timeToPress = GetComponent<LongPressGesture>().TimeToPress;

        GetComponent<PressGesture>().Pressed += pressedHandler;
        GetComponent<ReleaseGesture>().Released += releasedHandler;
        GetComponent<LongPressGesture>().StateChanged += longPressStateChangedHandler;
    }

    private void OnDisable()
    {
        GetComponent<PressGesture>().Pressed -= pressedHandler;
        GetComponent<ReleaseGesture>().Released -= releasedHandler;
        GetComponent<LongPressGesture>().StateChanged -= longPressStateChangedHandler;
    }

    private void press()
    {
        button.transform.localPosition = new Vector3(0, -button.transform.localScale.y*.4f, 0);
    }

    private void release()
    {
        button.transform.localPosition = new Vector3(0, 0, 0);
    }

    private void reset()
    {
        button.transform.localScale = startScale;
        StopCoroutine("grow");
    }

    private void changeColor()
    {
        if (Plane == null) return;

        Plane.GetComponent<Renderer>().material.color = button.GetComponent<Renderer>().sharedMaterial.color;
    }

    private IEnumerator grow()
    {
        while (true)
        {
            button.transform.localScale += (targetScale.x - startScale.x)/timeToPress*Time.unscaledDeltaTime*new Vector3(1, 0, 1);
            yield return null;
        }
    }

    private void longPressStateChangedHandler(object sender, GestureStateChangeEventArgs e)
    {
        switch (e.State)
        {
            case Gesture.GestureState.Recognized:
            case Gesture.GestureState.Failed:
            case Gesture.GestureState.Cancelled:
                reset();
                break;
        }

        if (e.State == Gesture.GestureState.Recognized)
        {
            changeColor();
        }
    }

    private void pressedHandler(object sender, EventArgs e)
    {
        press();
        StartCoroutine("grow");
    }

    private void releasedHandler(object sender, EventArgs e)
    {
        release();
    }
}


text:
namespace lr
{

static const char* FILENAME = "level_cfg.json";

LevelCfg* LevelCfg::m_instance = NULL;

LevelCfg* LevelCfg::Instance()
{
	if (!m_instance) {
		m_instance = new LevelCfg();
	}
	return m_instance;
}

LevelCfg::LevelCfg()
{
	if (ee::FileHelper::IsFileExist(FILENAME)) {
		LoadFromFile(FILENAME);
	} else {
		wxStandardPathsBase& stdp = wxStandardPaths::Get();
		std::string exe_path = stdp.GetExecutablePath();
		std::string cfg_path = ee::FileHelper::GetFileDir(exe_path) + "\\" + FILENAME;
		if (ee::FileHelper::IsFileExist(cfg_path)) {
			LoadFromFile(cfg_path.c_str());
		}
	}
}

bool LevelCfg::QueryLayout(const std::string& type, int& col,
						   std::vector<ee::DynamicWidget*>& widgets)
{
	std::map<std::string, Dialog*>::iterator itr = m_dialogs.find(type);
	if (itr == m_dialogs.end()) {
		return false;
	}

	Dialog* d = itr->second;
	col = d->col;
	widgets = d->widgets;

	return true;
}

void LevelCfg::LoadFromFile(const char* filename)
{
	Json::Value val;

	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(filename);
	std::locale::global(std::locale("C"));
	reader.parse(fin, val);
	fin.close();

	int idx = 0;
	Json::Value d_val = val["dialog"][idx++];
	while (!d_val.isNull()) {
		InsertDialog(d_val);
		d_val = val["dialog"][idx++];
	}
}

void LevelCfg::InsertDialog(const Json::Value& val)
{
	Dialog* dlg = new Dialog;

	dlg->type = val["type"].asString();
	dlg->col = val["layout"]["col"].asInt();

	int idx = 0;
	Json::Value w_val = val["widget"][idx++];
	while (!w_val.isNull()) {
		dlg->widgets.push_back(ee::WidgetFactory::Instance()->Create(w_val));
		w_val = val["widget"][idx++];
	}

	m_dialogs.insert(std::make_pair(dlg->type, dlg));
}

}


text:
package com.siyeh.ig.classmetrics;

import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiTypeParameter;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.LibraryUtil;
import javax.annotation.Nonnull;

import java.util.HashSet;
import java.util.Set;

public class ClassInheritanceDepthInspection
  extends ClassMetricInspection {

  @Nonnull
  public String getID() {
    return "ClassTooDeepInInheritanceTree";
  }

  private static final int CLASS_INHERITANCE_LIMIT = 2;

  @Nonnull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("class.too.deep.display.name");
  }

  protected int getDefaultLimit() {
    return CLASS_INHERITANCE_LIMIT;
  }

  protected String getConfigurationLabel() {
    return InspectionGadgetsBundle.message(
      "class.too.deep.inheritance.depth.limit.option");
  }

  @Nonnull
  public String buildErrorString(Object... infos) {
    final Integer count = (Integer)infos[0];
    return InspectionGadgetsBundle.message(
      "class.too.deep.problem.descriptor", count);
  }

  public BaseInspectionVisitor buildVisitor() {
    return new ClassNestingLevel();
  }

  private class ClassNestingLevel extends BaseInspectionVisitor {

    @Override
    public void visitClass(@Nonnull PsiClass aClass) {
      // note: no call to super
      if (aClass.isEnum()) {
        return;
      }
      if (aClass instanceof PsiTypeParameter) {
        return;
      }
      final int inheritanceDepth =
        getInheritanceDepth(aClass, new HashSet<PsiClass>());
      if (inheritanceDepth <= getLimit()) {
        return;
      }
      registerClassError(aClass, Integer.valueOf(inheritanceDepth));
    }

    private int getInheritanceDepth(PsiClass aClass, Set<PsiClass> visited) {
      if (visited.contains(aClass)) {
        return 0;
      }
      visited.add(aClass);
      final PsiClass superClass = aClass.getSuperClass();
      if (superClass == null) {
        return 0;
      }
      if (LibraryUtil.classIsInLibrary(aClass) &&
          LibraryUtil.classIsInLibrary(superClass)) {
        return 0;
      }
      return getInheritanceDepth(superClass, visited) + 1;
    }
  }
}


text:
package com.thoughtworks.go.server.plugins;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.thoughtworks.go.domain.config.ConfigurationProperty;
import com.thoughtworks.go.domain.packagerepository.ConfigurationPropertyMother;
import com.thoughtworks.go.helper.MaterialsMother;
import com.thoughtworks.go.server.service.MaterialService;
import com.thoughtworks.go.plugin.infra.DefaultPluginManager;
import com.thoughtworks.go.plugin.infra.monitor.PluginFileDetails;
import com.thoughtworks.go.plugin.infra.monitor.PluginJarChangeListener;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:WEB-INF/applicationContext-global.xml",
        "classpath:WEB-INF/applicationContext-dataLocalAccess.xml",
        "classpath:WEB-INF/applicationContext-acegi-security.xml"
})
public class GenericPluginPerformanceIntegrationTest  {
    @Autowired private DefaultPluginManager defaultPluginManager;
    @Autowired private PluginJarChangeListener pluginJarChangeListener;
    @Autowired private MaterialService materialService;

    @Ignore
    @Test
    public void testPluginCallsInParallel() throws Exception {
        String pathToPluginJar = "/home/godev/Downloads/yum-repo-exec-poller.jar";

        // Example: To hit 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3
        // Total number of requests: 15, concurrencyLevel = anything, numberOfDifferentIndexes = 3
        int totalNumberOfRequests = 100;
        int concurrencyLevel = 10;
        int numberOfDifferentIndexes = 20;

        defaultPluginManager.startInfrastructure();
        pluginJarChangeListener.pluginJarAdded(new PluginFileDetails(new File(pathToPluginJar), true));

        List<Callable<Object>> operations = new ArrayList<Callable<Object>>();
        for (int i = 0; i < totalNumberOfRequests; i++) {
            operations.add(operation(i % numberOfDifferentIndexes));
        }

        runInParallel(concurrencyLevel, operations);
    }

    private void runInParallel(int concurrencyLevel, List<Callable<Object>> operations) throws InterruptedException {
        long start = System.currentTimeMillis();

        ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel);
        List<Future<Object>> futures = executorService.invokeAll(operations);

        for (Future<Object> future : futures) {
            try {
                future.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        long end = System.currentTimeMillis();
        System.err.println((end - start) / 1000.0);
    }

    private Callable<Object> operation(final int index) {
        return new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                System.err.println("START " + index + " " + Thread.currentThread() + " " + System.currentTimeMillis());
                ConfigurationProperty repoUrl = ConfigurationPropertyMother.create("REPO_URL", false, "http://10.4.7.3:9090/yum/yum-repo-" + (index + 1));
                ConfigurationProperty packageSpec = ConfigurationPropertyMother.create("PACKAGE_SPEC", false, "perf*");

                materialService.latestModification(MaterialsMother.packageMaterial("repo-id", "repo-name", "pkg-id", "pkg-name", "yum", "1.0", Arrays.asList(repoUrl), Arrays.asList(packageSpec)),
                        new File("/tmp"), null);

                System.err.println("END " + index + " " + Thread.currentThread() + " " + System.currentTimeMillis());
                return null;
            }
        };
    }
}


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.mapreduce.lib.map (Apache Hadoop Main 2.5.1 API)
</TITLE>

<META NAME="date" CONTENT="2014-09-05">

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

org.apache.hadoop.mapreduce.lib.map

Classes

InverseMapper

MultithreadedMapper

RegexMapper

TokenCounterMapper

WrappedMapper


text:
var Logic = function (data) {
  this.name = data.name;
  this.check = data.check;
  this.command = data.command;
};

module.exports = Logic;


text:
var React = require('react');
var BigCalendar = require('react-big-calendar');
var moment = require('moment');
var events = require('../builder/event.js');
require('react-big-calendar/lib/css/react-big-calendar.css');

BigCalendar.momentLocalizer(moment);

var Agenda = React.createClass({

  getInitialState: function() {
       return { showAgenda: true };
  },

  onClick: function() {
    if (this.state.showAgenda === true) {
      this.setState({ showAgenda: false });
    } else {
      this.setState({ showAgenda: true });
    }
  },

  render: function(){

    return (

Today's Agenda

        { this.state.showAgenda ?

            <BigCalendar
              events={events}
              views={['day']}
              defaultView={'day'}
              defaultDate={new Date(2015, 3, 1)}
              style={{height: 400}}
            /> : null}

    );
  }
});

module.exports = Agenda;


text:
from tastypie.resources import ModelResource
from parker_demo.demo.models import ParkerDemo

class DemoResource(ModelResource):
    class Meta:
        queryset = ParkerDemo.objects.all()
        resource_name =  'demo'


text:
"""XML helper functions"""

from __future__ import absolute_import, division, print_function

from xml.dom.minidom import parseString #pylint: disable=E0611,F0401

__all__ = ['NotTextNodeError', 'xml_to_dict', 'node_to_dict', 'get_node_text']

#
# Converting XML to a Dictionary
# Author: Christoph Dietze
# URL   : http://code.activestate.com/recipes/116539/
#
class NotTextNodeError(Exception):
    pass

def xml_to_dict(xmlstring):
    """
    Converts an XML string to a Python dictionary

    .. Warning::
        This method does not support multiple inner nodes of the same name but
        with different values.  It always takes the last value.

    Examples
    --------
    ::

        <outer>
            <inner>one</inner>
            <inner>two</inner>
        </outer>

    gives you the dict::

       {u'outer': {u'inner': u'two'}}
    """
    return node_to_dict(parseString(xmlstring))

def node_to_dict(node):
    """
    node_to_dict() scans through the children of node and makes a dictionary
    from the content.

    Three cases are differentiated:

    1. If the node contains no other nodes, it is a text-node and
       {nodeName: text} is merged into the dictionary.
    2. If the node has the attribute "method" set to "true", then it's children
       will be appended to a list and this list is merged to the dictionary in
       the form: {nodeName:list}.
    3. Else, node_to_dict() will call itself recursively on the nodes children
       (merging {nodeName: node_to_dict()} to the dictionary).

    """
    dic = {}
    for n in node.childNodes:
        if n.nodeType != n.ELEMENT_NODE:
            continue
        if n.getAttribute("multiple") == "true":
            # node with multiple children: put them in a list
            l = []
            for c in n.childNodes:
                if c.nodeType != n.ELEMENT_NODE:
                    continue
                l.append(node_to_dict(c))
                dic.update({n.nodeName: l})
            continue

        try:
            text = get_node_text(n)
        except NotTextNodeError:
            # 'normal' node
            dic.update({n.nodeName: node_to_dict(n)})
            continue

        # text node
        dic.update({n.nodeName: text})
        continue
    return dic

def get_node_text(node):
    """
    scans through all children of node and gathers the text. if node has
    non-text child-nodes, then NotTextNodeError is raised.
    """
    t = ""
    for n in node.childNodes:
        if n.nodeType == n.TEXT_NODE:
            t += n.nodeValue
        else:
            raise NotTextNodeError
    return t


text:
package info.u_team.u_team_test.blockentity;

import info.u_team.u_team_core.blockentity.UBlockEntity;
import info.u_team.u_team_core.inventory.BlockEntityUFluidStackHandler;
import info.u_team.u_team_core.inventory.BlockEntityUItemStackHandler;
import info.u_team.u_team_core.inventory.UFluidStackHandler;
import info.u_team.u_team_core.inventory.UItemStackHandler;
import info.u_team.u_team_test.init.TestBlockEntityTypes;
import info.u_team.u_team_test.menu.BasicFluidInventoryMenu;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.util.LazyOptional;

public class BasicFluidInventoryBlockEntity extends UBlockEntity implements MenuProvider {

	protected final UItemStackHandler itemSlots;
	protected final LazyOptional<UItemStackHandler> itemSlotsOptional;

	protected final UFluidStackHandler fluidTanks;
	protected final LazyOptional<UFluidStackHandler> fluidTanksOptional;

	public BasicFluidInventoryBlockEntity(BlockPos pos, BlockState state) {
		super(TestBlockEntityTypes.BASIC_FLUID_INVENTORY.get(), pos, state);

		itemSlots = new BlockEntityUItemStackHandler(4, this);
		itemSlotsOptional = LazyOptional.of(() -> itemSlots);

		fluidTanks = new BlockEntityUFluidStackHandler(4, this);
		fluidTanksOptional = LazyOptional.of(() -> fluidTanks);
	}

	@Override
	public void saveNBT(CompoundTag compound) {
		super.saveNBT(compound);
		compound.put("items", itemSlots.serializeNBT());
		compound.put("fluids", fluidTanks.serializeNBT());
	}

	@Override
	public void loadNBT(CompoundTag compound) {
		super.loadNBT(compound);
		itemSlots.deserializeNBT(compound.getCompound("items"));
		fluidTanks.deserializeNBT(compound.getCompound("fluids"));
	}

	public UItemStackHandler getItemSlots() {
		return itemSlots;
	}

	public UFluidStackHandler getFluidTanks() {
		return fluidTanks;
	}

	// Capability

	@Override
	public <X> LazyOptional<X> getCapability(Capability<X> capability, Direction side) {
		if (capability == ForgeCapabilities.ITEM_HANDLER) {
			return itemSlotsOptional.cast();
		} else if (capability == ForgeCapabilities.FLUID_HANDLER) {
			return fluidTanksOptional.cast();
		} else {
			return super.getCapability(capability, side);
		}
	}

	@Override
	public void setRemoved() {
		super.setRemoved();
		itemSlotsOptional.invalidate();
		fluidTanksOptional.invalidate();
	}

	@Override
	public void onChunkUnloaded() {
		super.onChunkUnloaded();
		itemSlotsOptional.invalidate();
		fluidTanksOptional.invalidate();
	}

	// Container

	@Override
	public AbstractContainerMenu createMenu(int id, Inventory playerInventory, Player player) {
		return new BasicFluidInventoryMenu(id, playerInventory, this);
	}

	@Override
	public Component getDisplayName() {
		return Component.literal("Fluid Inventory");
	}
}


text:
Imports SistFoncreagro.BussinessEntities
Imports SistFoncreagro.DataAccess
Public Class HorarioAsignadoBL : Inherits MasterDataAccess : Implements IHorarioAsignadoBL
    Dim factoryrepository As IHorarioAsignadoRepository

    Public Sub New()
        factoryrepository = New HorarioAsignadoRepository
    End Sub

    Public Function GetHorarioAsignadoByIdPeriodoLaboral(ByVal IdPeriodoLaboral As Integer) As System.Collections.Generic.List(Of BussinessEntities.HorarioAsignado) Implements IHorarioAsignadoBL.GetHorarioAsignadoByIdPeriodoLaboral
        Return factoryrepository.GetHorarioAsignadoByIdPeriodoLaboral(IdPeriodoLaboral)
    End Function

    Public Function GetHorarioAsignadoByIdPeriodoLaboralAndByFecha(ByVal IdPeriodoLaboral As Integer, ByVal Fecha As Date) As BussinessEntities.HorarioAsignado Implements IHorarioAsignadoBL.GetHorarioAsignadoByIdPeriodoLaboralAndByFecha
        Return factoryrepository.GetHorarioAsignadoByIdPeriodoLaboralAndByFecha(IdPeriodoLaboral, Fecha)
    End Function

    Public Function SaveHORARIOASIGNADO(ByVal HorarioAsignado As BussinessEntities.HorarioAsignado) As Integer Implements IHorarioAsignadoBL.SaveHORARIOASIGNADO
        Return factoryrepository.SaveHORARIOASIGNADO(HorarioAsignado)
    End Function
End Class


text:
import React from "react";
import rewards from "rewards";
import { connect } from "react-redux";
import { doCloseModal } from "redux/actions/app";
import { makeSelectRewardByType } from "redux/selectors/rewards";
import ModalFirstReward from "./view";

const select = (state, props) => {
  const selectReward = makeSelectRewardByType();

  return {
    reward: selectReward(state, { reward_type: rewards.TYPE_NEW_USER }),
  };
};

const perform = dispatch => ({
  closeModal: () => dispatch(doCloseModal()),
});

export default connect(select, perform)(ModalFirstReward);


text:
/**
 * Created by DENIS on 29.04.2017.
 */
import {Component, OnInit} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {SpecialityModel} from "../../model/speciality.model";
import {SpecialityService} from "../../service/speciality/speciality.service";
import {EducationInstitutionService} from "../../service/education-institution/education-institution.service";
import {SearchService} from "../../service/search/search.service";
import {EducationInstitutionModel} from "../../model/education-institution.model";
import {FacultyModel} from "../../model/faculty.model";
import {FacultyService} from "../../service/faculty/faculty.service";
import {Comment} from "../../model/comment.model";

@Component({
  selector: 'app-speciality-detail',
  templateUrl: './speciality-detail.component.html',
  styleUrls: ['./speciality-detail.component.css']
})

export class SpecialityDetailComponent implements OnInit {

  speciality: SpecialityModel;
  institution: EducationInstitutionModel;
  faculty: FacultyModel;
  public comments: Comment[];
  public text: string;

  constructor(private route: ActivatedRoute, private specialityService: SpecialityService,
              private searchService: SearchService, private facultyService: FacultyService,
              private router: Router) {

  }

  ngOnInit(): void {
    this.initEntity();
  }

  initEntity() {
    this.comments = [];
    this.speciality = new SpecialityModel();
    this.institution = new EducationInstitutionModel();
    this.faculty = new FacultyModel();

    this.route
      .params
      .subscribe(param => {
        this.specialityService.getComments(+param["id"]).subscribe(res => {
          this.comments = res;
        });
        this.specialityService.getById(+param["id"]).subscribe(item => {
          this.speciality = item;
          this.searchService.getInsitutionBySpeciality(+param["id"]).subscribe(institution => {
            this.institution = institution;
          });
          this.facultyService.getFacultyBySpeciality(+param["id"]).subscribe(faculty => {
            this.faculty = faculty;
          });
        });
      });
  }

  goDetailInstitution(id: number) {
    this.router.navigate(['/institution/', id]);
  }

  goSpecialityInstitution(id: number) {
    this.router.navigate(['/institution/' + id + '/speciality']);
  }
/*
  addComment(id: number) {
    let comment: Comment;
    comment = new Comment();
    comment.specialityId = id;
    comment.date = date.getDay().toLocaleString() + "-" + date.getMonth().toLocaleString() + "-" + date.getFullYear().toLocaleString();
    if (this.text == "") {
    if(this.text == "") {
      this.text = "checking...";
    }
    comment.text = this.text;
    comment.username = "null";
    this.specialityService.addComment(comment).subscribe(res => {
    });
  }*/
}


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

namespace WInterop.Windows;

public enum GetAncestorOption : uint
{
    /// <summary>
    ///  Retrieves the parent window. This does not include the owner, as it does with the GetParent function.
    ///  [GA_PARENT]
    /// </summary>
    Parent = 1,

    /// <summary>
    ///  Retrieves the root window by walking the chain of parent windows.
    ///  []
    /// </summary>
    Root = 2,

    /// <summary>
    ///  Retrieves the owned root window by walking the chain of parent and owner windows returned by GetParent.
    ///  []
    /// </summary>
    RootOwner = 3
}


text:
"""
Stages under which nodes are categorized.  Listed in this
module to avoid typing the wrong string.
"""

INPUT = "input"
OUTPUT = "output"
FILTER_BINARY = "filter_binary"
FILTER_GRAY = "filter_gray"
BINARIZE = "binarize"
PAGE_SEGMENT = "page_segment"
RECOGNIZE = "recognize"
UTILS = "utils"
POST = "post_process"


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="title" content="Andrew Kravchuk" />
    <meta name="description" content="Andrew Kravchuk | Software Engineer | Freelancer">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:image" content="https://awkravchuk.ru/img/profile.png" />

    <title>Andrew Kravchuk</title>

    <link href="vendor/bootstrap/css/bootstrap.css" rel="stylesheet">

    <link href="css/freelancer.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CLato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Andrew Kravchuk

                        Portfolio

                        About

                        Contact

                        Andrew Kravchuk

                        Software Engineer - Freelancer

Portfolio

About

I am software engineer with Master's Degree in Computer Applications and 10+ years of work experience.

                    I'm also a free software contributor. Here are some projects I've contributed to:

docker-library/postgres

rabbitmq-c

django-uwsgi

libmodbus

I'm freelancer at the moment, available for hire right now.
                    You'll never hear "you can't do that" from me. Nothing is impossible.

                    Feel free to tell me what  you want to do and I'll respond within 12 hours.

Location

Dubna, Russia (UTC+3:00)

Around the Web

                        Copyright © Andrew Kravchuk 2016

baneks.site

The website located at baneks.site, made for russian anecdotes community. Made using Python, Django, Celery and Material Design Lite.

Date:
                                    December 2016

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Shade Sandbox interface

I've implemented graphical user interface of Shade Sandbox in early stages of its development.

Client:
                                    Cybergenic Corporation

Date:
                                    April 2011

Service:
                                    Desktop Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Free Download Manager 5

I've been working full-time on revival of famous application Free Download Manager, with particularly successful effort to create its Chrome extension.

Date:
                                    November 2014

Service:
                                    Desktop Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

ViBe

I've implemented background subtraction algorithm for video sequences called ViBe for my PhD thesis due to lack of freely available implementation. It was made in pure C and OpenCV.

 Source

Date:
                                    July 2013

Service:
                                    Research and Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Landscape

Show-off project featuring nice-looking landscape using Ogre3D engine.

 Source

Date:
                                    October 2011

Service:
                                    Game Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

WavPlot

A simple Qt audio analysis project made to clear up some things for myself.

 Source

Date:
                                    June 2010

Service:
                                    Desktop Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Particles

A simple space derbris demo using Ogre3D engine and Nvidia CUDA technology.

 Source

Date:
                                    May 2011

Service:
                                    Game Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

LogAnalyzer

A good friend of mine was running homebrew internet provider company back in the 2000s. He asked me to create billing application for it.

 Source

Date:
                                    July 2007

Service:
                                    Backend Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Botias

Client wanted to automate some of the accounting calculations required for pensions in Russia and Ukraine. Our team decided to create a cloud service to acheive this task. I've built all of its web backend and a bits of a calculation module. Unfortunately the project was cancelled.

 Source

Date:
                                    December 2012

Service:
                                    Backend Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
package org.carrot2.elasticsearch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.function.Supplier;
import org.carrot2.clustering.ClusteringAlgorithmProvider;
import org.carrot2.language.LanguageComponentsProvider;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.plugins.ExtensiblePlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.repositories.RepositoriesService;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestHandler;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.elasticsearch.xcontent.NamedXContentRegistry;

public class ClusteringPlugin extends Plugin implements ExtensiblePlugin, ActionPlugin {
  /** Master on/off switch property for the plugin (general settings). */
  public static final String DEFAULT_ENABLED_PROPERTY_NAME = "carrot2.enabled";

  /** Plugin name. */
  public static final String PLUGIN_NAME = "elasticsearch-carrot2";

  /** All algorithm providers. */
  private final LinkedHashMap<String, ClusteringAlgorithmProvider> algorithmProviders =
      new LinkedHashMap<>();

  /** All language component providers. */
  private final Map<String, List<LanguageComponentsProvider>> languageComponentProviders =
      new LinkedHashMap<>();

  private final boolean transportClient;
  private final boolean pluginEnabled;

  public ClusteringPlugin(Settings settings) {
    this.pluginEnabled = settings.getAsBoolean(DEFAULT_ENABLED_PROPERTY_NAME, true);
    this.transportClient =
        TransportClient.CLIENT_TYPE.equals(Client.CLIENT_TYPE_SETTING_S.get(settings));

    // load our own class loader's extensions.
    loadExtensions(getClass().getClassLoader());
  }

  @Override
  public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
    if (pluginEnabled) {
      return Arrays.asList(
          new ActionHandler<>(ClusteringAction.INSTANCE, ClusteringActionTransport.class),
          new ActionHandler<>(
              ListAlgorithmsAction.INSTANCE,
              ListAlgorithmsAction.TransportListAlgorithmsAction.class));
    }
    return Collections.emptyList();
  }

  @Override
  public List<RestHandler> getRestHandlers(
      Settings settings,
      RestController restController,
      ClusterSettings clusterSettings,
      IndexScopedSettings indexScopedSettings,
      SettingsFilter settingsFilter,
      IndexNameExpressionResolver indexNameExpressionResolver,
      Supplier<DiscoveryNodes> nodesInCluster) {
    return Arrays.asList(
        new ClusteringAction.RestClusteringAction(),
        new ListAlgorithmsAction.RestListAlgorithmsAction());
  }

  @Override
  public Collection<Object> createComponents(
      Client client,
      ClusterService clusterService,
      ThreadPool threadPool,
      ResourceWatcherService resourceWatcherService,
      ScriptService scriptService,
      NamedXContentRegistry xContentRegistry,
      Environment environment,
      NodeEnvironment nodeEnvironment,
      NamedWriteableRegistry namedWriteableRegistry,
      IndexNameExpressionResolver indexNameExpressionResolver,
      Supplier<RepositoriesService> repositoriesServiceSupplier) {
    List<Object> components = new ArrayList<>();
    if (pluginEnabled && !transportClient) {
      components.add(
          new ClusteringContext(
              environment,
              reorderAlgorithms(algorithmProviders),
              new LinkedHashMap<>(languageComponentProviders)));
    }
    return components;
  }

  /** This places Lingo3G in front of the algorithm list if it is available. */
  private LinkedHashMap<String, ClusteringAlgorithmProvider> reorderAlgorithms(
      LinkedHashMap<String, ClusteringAlgorithmProvider> providers) {
    String[] desiredOrder = {"Lingo3G", "Lingo", "STC", "Bisecting K-Means"};
    LinkedHashMap<String, ClusteringAlgorithmProvider> copy = new LinkedHashMap<>();
    for (String name : desiredOrder) {
      if (providers.containsKey(name)) {
        copy.put(name, providers.get(name));
      }
    }
    providers.forEach(
        (name, provider) -> {
          if (!copy.containsKey(name)) {
            copy.put(name, provider);
          }
        });
    return copy;
  }

  @Override
  public void loadExtensions(ExtensionLoader loader) {
    loadExtensions(
        loader.loadExtensions(ClusteringAlgorithmProvider.class),
        loader.loadExtensions(LanguageComponentsProvider.class));
  }

  private void loadExtensions(ClassLoader classLoader) {
    loadExtensions(
        ServiceLoader.load(ClusteringAlgorithmProvider.class, classLoader),
        ServiceLoader.load(LanguageComponentsProvider.class, classLoader));
  }

  private void loadExtensions(
      Iterable<ClusteringAlgorithmProvider> clusteringAlgorithmProviders,
      Iterable<LanguageComponentsProvider> languageComponentsProviders) {
    clusteringAlgorithmProviders.forEach(
        (provider) -> {
          String name = provider.name();
          if (algorithmProviders.containsKey(name)) {
            throw new RuntimeException("More than one provider for algorithm " + name + "?");
          }
          algorithmProviders.put(name, provider);
        });

    languageComponentsProviders.forEach(
        provider -> {
          for (String lang : provider.languages()) {
            languageComponentProviders
                .computeIfAbsent(lang, (k) -> new ArrayList<>())
                .add(provider);
          }
        });
  }
}


text:
module Models where

import Control.Exception          (catch, displayException, SomeException)
import Database.PostgreSQL.Simple (Connection, execute_)
import GHC.Int

import qualified Models.Media as M
import qualified Models.Projects as P

data ModelType = Authors
               | Series
               | Posts
               | Media
               | Projects
               deriving (Eq, Show)

execHandler :: SomeException -> IO ()
execHandler e =  do
  print "It Blew up!\n"
  putStrLn $ displayException e

makeMigrations :: Connection -> IO ()
makeMigrations conn = do
  catch (execute_ conn P.createProjectsTable >> print "creating projects table") execHandler
  catch (execute_ conn M.createMediaTable >> print "creating media table") execHandler
  catch (execute_ conn M.createPostMediaTable >> print "creating post-media relationship table") execHandler
  pure ()


text:
/**
 * Example Plugin 1.0
 *
 * There are  files included in this package but this is the only file required. The other files
 * only offer additional information and prospective of the scope of tools you can use to further develop.
 *
 */

/**
 * This plugin is for demonstration purpose only.
 * Do see the comments in the code for some samples of API and methods available.
 *
 */
function ExamplePlugin(arg1, arg2)
{

	//alerts data set in the contructors $ajax->ExamplePlugin();
	//alert(arg1.test1);
	//alert(arg1.test2);

	//see plugins's api documentation to see all the available functions and variables available.

	/**
	 * The following statement shows several things:
	 * How to request ajax  to the plugin itself, usage or parameters
	 *
	 * the ":json" part of the url tells ajax to return  a json object.
	 *
	 *
	 */
	this.call(this.ajaxFile+'?ExamplePlugin:json/docs', function(response) {

		//alert(response.test1);
		//alert(response.test2);
	});

	//You may access the parameters the  same order they were sent.
	//arg1.test1;

	//arg1.test2

	//arg2

	/**
	 * this.prevent()
	 *
	 * You can intercept other ajax APIs executed after the plugin was called.
	 * Using  the method this.prevent();
	 *
	 * this.prevent() will stop other APIs, and returns them into one function which you may
	 * use at your own pase.
	 *
	 * Example:
	 *
	 * Lets say in your controller you use
	 *
	 * $ajax->Exec('button', $ajax->form('url','form_id'));
	 *
	 * The above Api will submit a form attached to a button,
	 *
	 * but lets say you want to do something else before the form is submitted through ajax,
	 * this is a case where you can use this method.
	 *
	 * if  you  use prevent(), that Api will be intercepted and not executed.
	 * Then it gives you the controll of execution of that API, in the returned value.
	 * Which you may execute.
	 *
	 * var Api = this.prevent();
	 *
	 * setTimeout(function() {
	 * 		Api();
	 * },5000);
	 * you may prevent more than one APIs by passing a number in this
	 * function  this.prevent(3); - will prevent 3 APIs and they all are returned back to you.
	 *
	 *
	 */
	//this.prevent()

	//sample of importing javascript into the scope
	this.import('http://cjax.googlecode.com/svn/trunk/_extra/test_unit/plugins/js/test.js', function() {
		console.log('File was imported.');
	});
	//sample of importing css to the page
	this.import('http://cjax.googlecode.com/svn/trunk/_extra/test_unit/plugins/css/test.css');

	//sample of preventing the next  API $ajax->info()

	//CJAX.preventDefault();

	//setTimeout('func2()',20000);

	//console.log('File base:', this.base);
	//console.log('This file:', this.file);
	//console.log('Paramters Passed:', a, b ,c);
}


text:
using System;
using NUnit.Framework;
using NSubstitute;

namespace GeneticSharp.Domain.UnitTests.Terminations
{
    [TestFixture()]
    [Category("Terminations")]
    public class TimeEvolvingTerminationTest
    {
        [Test()]
        public void HasReached_TimeLowerThanMaxTime_False()
        {
            var ga = Substitute.For<IGeneticAlgorithm>();

            ga.TimeEvolving.Returns(TimeSpan.FromSeconds(0.1),
                                    TimeSpan.FromSeconds(00.9));

            var target = new TimeEvolvingTermination(TimeSpan.FromSeconds(1));
            Assert.IsFalse(target.HasReached(ga));
            Assert.IsFalse(target.HasReached(ga));
        }

        [Test()]
        public void HasReached_TimeGreaterOrEqualMaxTime_True()
        {
            var ga = Substitute.For<IGeneticAlgorithm>();

            ga.TimeEvolving.Returns(TimeSpan.FromSeconds(0.1),
                                    TimeSpan.FromSeconds(0.9),
                                    TimeSpan.FromSeconds(1),
                                    TimeSpan.FromSeconds(1.1));

            var target = new TimeEvolvingTermination(TimeSpan.FromSeconds(1));

            Assert.IsFalse(target.HasReached(ga));
            Assert.IsFalse(target.HasReached(ga));
            Assert.IsTrue(target.HasReached(ga));
            Assert.IsTrue(target.HasReached(ga));
        }
    }
}


text:
<?php

namespace Grid\Mail\Model\Template;

use Locale;
use Zend\Db\Sql\Expression;
use Zork\Model\LocaleAwareTrait;
use Zork\Model\LocaleAwareInterface;
use Zork\Model\Mapper\DbAware\ReadWriteMapperAbstract;

/**
 * Mapper
 *
 * @author David Pozsar <david.pozsar@megaweb.hu>
 */
class Mapper extends ReadWriteMapperAbstract
          implements LocaleAwareInterface
{

    use LocaleAwareTrait;

    /**
     * @var string
     */
    const FALLBACK_LOCALE = 'en';

    /**
     * Table name used in all queries
     *
     * @var string
     */
    protected static $tableName = 'mail_template';

    /**
     * Default column-conversion functions as types;
     * used in selected(), deselect()
     *
     * @var array
     */
    protected static $columns = array(
        'id'            => self::INT,
        'name'          => self::STR,
        'locale'        => self::STR,
        'fromAddress'   => self::STR,
        'fromName'      => self::STR,
        'subject'       => self::STR,
        'bodyHtml'      => self::STR,
        'bodyText'      => self::STR,
    );

    /**
     * Contructor
     *
     * @param \Mail\Model\Template\Structure $mailTemplateStructurePrototype
     * @param string $locale
     */
    public function __construct( Structure $mailTemplateStructurePrototype = null,
                                 $locale = null )
    {
        parent::__construct( $mailTemplateStructurePrototype ?: new Structure );
        $this->setLocale( $locale );
    }

    /**
     * Find a structure by name (and a locale)
     *
     * @param string $name
     * @param string|null $locale
     * @return \Mail\Model\Template\Structure
     */
    public function findByName( $name, $locale = null )
    {
        $locale = $locale ?: $this->getLocale();
        $lang   = Locale::getPrimaryLanguage( $locale );

        return $this->findOne( array(
            'name' => $name,
        ), array(
            new Expression(
                'CASE ? ' .
                    'WHEN ? THEN 1 ' .
                    'WHEN ? THEN 2 ' .
                    'WHEN ? THEN 3 ' .
                    'ELSE 4 ' .
                'END ASC',
                array(
                    'locale',
                    $locale,
                    $lang,
                    static::FALLBACK_LOCALE
                ),
                array(
                    Expression::TYPE_IDENTIFIER,
                    Expression::TYPE_VALUE,
                    Expression::TYPE_VALUE,
                    Expression::TYPE_VALUE,
                )
            ),
        ) );
    }

}


text:
import praw
import math
import os # This is used only to get the local directory of a file, nothing malicious.
import time
import random

subreddits = ["test"] # PUT SUBREDDITS IN HERE!!!

username = "USERNAME"
password = "PASSWORD"

cwd = os.getcwd()
try:
    words = open(cwd + r'\responses.txt', 'r')
except:
    print("Error loading responses file.")
lines = words.readlines()
words.close()
del words
try:
    words2 = open(cwd + r'\subject_list.txt', 'r')
except:
    print("Error loading subject list.")
subject_list = words2.readlines()
words2.close()
for x, line in enumerate(subject_list):
    line.replace('-', ' ')
    line.replace('_', ' ')
    line.replace('.', ' ')
    subject_list[x] = line
del words2
comment_total = 10
comment_skip = 37
if (comment_skip > 1):
    comment_skip = random.randint(comment_skip - 1, comment_skip + 1) # Gives a bit of randomness to skip so that repeated runnings with same skip will not place the same comment
largest_subject = len(max(subject_list, key=len))

def binary_search(search_item): # This is used to check through the subject_list document to help get the subject of a comment
    start_point = 0
    end_point = len(subject_list) - 1
    for y in range(0, int(round(math.log(len(subject_list), 2))) + 1): # This calculates the maximum possible iterations it would take to find a word, if it gets past that the search has failed.
        midpoint = (start_point + end_point)//2 # Calculates the midpoint as an integer
        current_subject = subject_list[midpoint].strip('\n')
        for x in range(0, min(len(search_item), len(current_subject))): # Moves through each character in word comparing to search term, many words will have similar matching characters at the beggining
            if (current_subject[x] != search_item[x]): # Checks if word has been found at current midpoint
                if(ord(search_item[x]) < ord(current_subject[x])):
                    end_point = midpoint - 1
                else:
                    start_point = midpoint + 1
                break # Stops the current search at this word as a match has not been found and there's no point continuing
            elif (x == min(len(search_item), len(current_subject)) - 1): # If the search gets to the end of the word then we know it has found the right term
                if (len(current_subject) > len(search_item)): # If the midpoint is on a word longer than the search_item it will move the end point below because that's the solution to the problem
                    end_point = midpoint - 1
                elif (len(current_subject) < len(search_item)):
                    start_point = midpoint + 1
                else:
                    return True
    return False

def check_for_nouns(words):
    # Goes throug every word and checks from back of list, this confuses me i don't know how i made it and somehow it works
    # ¯\_(ツ)_/¯
    matches = []
    for x, word in enumerate(words): # Goes through every word
        word_ranges = []
        current_word_range = word
        word_ranges.append(current_word_range)
        i = 1
        while (x + i < len(words)) and (len(current_word_range + words[x + i]) + 1 <= largest_subject):
            current_word_range = ' ' + words[x + i]
            word_ranges.append(current_word_range)
            i += 1

        for word_range in reversed(word_ranges):
            if (binary_search(word_range) == True):
                matches.append(word_range)
                break

    if (len(matches) > 0):
        return max(matches, key=len)
    else:
        return "that"

def replace_character(output_text, comment, format_point, subject): # Replaces formatting tags with their correct replacement
    first_half = output_text[:(format_point - 1)]
    second_half = output_text[(format_point + 2):]
    replacement = ""
    if (output_text[format_point] == 'u'):
        temp_word = comment.author.name.lower()
        for i, char in enumerate(temp_word): # Makes it so when a user name is stated no symbols are included and it is all lower case to make it seem more natural, the name is also cut of where a second part is included.
            if (96 < ord(char) < 123): # Only adds word if it is a letter in the alphabet
                replacement += char
            elif (replacement != ""):
                if (i < len(temp_word) - 1) and (ord(temp_word[i + 1]) > 96) and (ord(temp_word[i + 1]) < 123): # Checks if there is a letter in the next character, these avoid cutting of names with letters replaced with numbers and letters with underscores
                    replacement += char
                else:
                    break
    elif (output_text[format_point] == 's'):
        replacement = subject
    else:
        replacement = "ERROR WITH FORMATTING TAG REPLACEMENT - UNRECOGNISED TAG [" + output_text[format_point] + "]."
    output_text = first_half + replacement + second_half
    return output_text

def split_words(text): # Splits up words
    text.strip('\n')
    words = []
    start_writing = False
    current_word = ""
    for char in text:
        if (start_writing == False): # Starts writing once there are characters
            if (97 <= ord(char) <= 122) or (48 <= ord(char) <= 57):
                start_writing = True
                current_word += char
        else: # Stops writing once the end of a word is reached and that word is added to the list
            if (97 <= ord(char) <= 122) or (48 <= ord(char) <= 57) or (char == '\'') or (char == '/'):
                current_word += char
            else:
                start_writing = False
                words.append(current_word)
                current_word = ""
    if (current_word != ""): # Adds the current_word if not already done
        words.append(current_word)
    return words

def matching_keywords(keywords, words, comment_body):
    for keyword in keywords:
        if (' ' in keyword): # If the keyword is longer than one word it just checks if that phrase is in the word
            if (keyword not in comment_body):
                return False
        else:
            for word in words:
                if (word != keyword):
                    return False
    return True

def generate_response(comment, is_reply): # Generates a response based on context
    global random
    question_trigger_words = ["how", "why", "what", "when"] # Words to look for in parent comment that will make it a question
    personal_trigger_words = ["i", "im", "i'm", "feel", "am"]
    directed_trigger_words = ["you", "are", "you're", "youre", "your"]
    phrases = []
    words = split_words(comment.body.lower()) # generates a list of individual words that is used for various things, all lower case
    is_question = False
    is_personal = False
    is_directed = False
    for word in words: # Checks if comment is a question, personal or directed
        for parameter in personal_trigger_words:
            if (word == parameter):
                is_personal = True
                break
        for parameter in directed_trigger_words:
            if (word == parameter):
                is_directed = True
                break
        for parameter in question_trigger_words:
            if (word == parameter):
                is_question = True
                break
    subject = check_for_nouns(words) # Gets the subject of the sentence
    for line in lines: # Generates a list of phrases that can be used and selected from given the context
        if (line[0] == '%'): # Stop if % sign found
            break
        if (line[0] != '~'): # Ignore line if ~ sign found
            parameters_raw = ""
            parameter_sets = []
            phrase = ""
            main_text = False
            parameters = ""
            for char in line: # This splits the parameters from the phrase and puts the invidual parameter sets (for OR logic)into a list called parameter_sets
                if (main_text == False):
                    if (char == '|'):
                        main_text = True
                        parameter_sets.append(parameters)
                        del parameters
                        del parameters_raw
                    elif (char == '/'):
                        parameter_sets.append(parameters)
                        parameters = ""
                    else:
                        parameters += char
                else:
                    phrase += char
            del main_text
            keywords = []
            got_keyword = False
            keyword = ""
            start_x = 0

            skip = True # This has to be used as a line needs to be skipped, but the point at which this is decided is inside another for loop, so a boolean must be used to store the outcome
            for parameters in parameter_sets:
                for x, char in enumerate(parameters): # Gets keywords and removes them from parameters
                    if (got_keyword == False):
                        if (char == '\"'):
                            start_x = x
                            got_keyword = True
                    else:
                        if (char == '\"'):
                            got_keyword = False
                            parameters = parameters[:start_x] + parameters[(x + 1):]
                            keywords.append(keyword.lower())
                            keyword = ""
                        else:
                            keyword += char
                del got_keyword
                del start_x
                del keyword
                if (is_reply) != ('.' in parameters): # Goes through parameters and skips iteration if they don't match, preventing the line from being added, somehow it works
                    continue
                elif (is_question) != ('?' in parameters):
                    continue
                elif (is_personal) != ('p' in parameters):
                    continue
                elif (is_directed) != ('d' in parameters):
                    continue
                elif (subject == "that") and ('s' in parameters): # The s parameter works differently to the others, any phrase with s will only be used if a subject exists in the parent
                    continue
                elif (len(keywords) > 0) and (matching_keywords(keywords, words, comment.body) == False): # Like with s, keywords are not exlucsive and other phrases without keywords can be used
                    continue
                skip = False
                break
            if (skip == False):
                phrases.append(phrase)
            else:
                continue
    if (len(phrases) > 0):
        output_text = random.choice(phrases) # Selects phrase to use randomely out of phrases
    else:
        return ""
    x = 0
    while x < len(output_text): # Replaces characters and chooses random phrases
        if (output_text[x] == '{'):
            choices = []
            choice = "" # This is used for two reasons, temporary and other temporary thing
            for i in range(x + 1, len(output_text)):
                char2 = output_text[i]
                if (char2 == '}'):
                    choices.append(choice)
                    choice = random.choice(choices)
                    output_text = output_text[:x] + choice + output_text[i + 1:]
                    break
                elif (char2 == '/'):
                    choices.append(choice)
                    choice = ""
                else:
                    choice += char2
        elif (output_text[x] == '[') and (x < len(output_text) - 2) and (output_text[x + 2] == ']'): # This is what checks if there are actually characters present without checking the middle char.
            output_text = replace_character(output_text, comment, x + 1, subject)
        x += 1
    del x
    output_text = output_text.rstrip() # Removes whitespace to the right which just seem to be added on for i don't know why
    return output_text

def attempt_comments(comments):
    actual_coms = 0
    for coms, comment in enumerate(comments, 1): # Move through each comment in subreddit
        for x in reversed(range(0, coms + 1)):
            if (int(coms) % int(comment_skip) == 0) and comment.author.name != username:
                reply = generate_response(comment, False)
                if(reply != ""):
                    print("        Attempting Comment...")
                    try:
                        comment.reply(reply)
                    except praw.errors.RateLimitExceeded:
                        print("This account has exceeded its maximum amount of comments in a time on /r/" + subreddit_name + ", terminating commenting on this sub.")
                        return actual_coms
                    else:
                        print("        Commented.")
                        actual_coms += 1
                        break
    return actual_coms

def run_program():
    global subreddits
    r = praw.Reddit(user_agent = "Hola, mi llamo es señor Cielos Azules")
    print("Connecting to Reddit...")
    while True:
        try:
            r.login(username, password, disable_warning=True)
        except praw.errors.InvalidUserPass:
            print("Error trying to login, check Username and Password.")
        except:
            print("Error trying to connect to Reddit")
        else:
            print("Connected.")
            break
        print("Trying again...")
        time.sleep(1)
    if (comment_total > 0):
        for subreddit_name in subreddits: # Moves through subreddits to comment on
            print("Getting /r/" + subreddit_name + " information...")
            subreddit = r.get_subreddit(subreddit_name)

            print("Getting comment information...")
            comments = subreddit.get_comments(limit=(comment_total*comment_skip))

            print("Starting automated commenting system...")

            print("    Repying to thread comments...")

            actual_comments = attempt_comments(comments) # This is where the comments are actually made

            print("    " + str(actual_coms) + " comments have been made in /r/" + subreddit_name + ".")
            print(" ")
    else:
        print("Skipping commenting.")
    actual_coms = 0
    print("")
    print("Getting inbox information...")
    inbox = r.get_unread()
    print("    Looking at inbox...")
    replied = False
    for coms, comment in enumerate(inbox): # Replies to comments
        reply = generate_response(comment, True)
        if (reply == ""):
            continue
        else:
            try:
                comment.reply(reply)
                replied = True # This keeps track of unread messages that have attempted to be replied to so that it can be stated if there are not any to reply to.
            except praw.errors.RateLimitExceeded:
                print("        Tried to reply to a comment but cannot in this subreddit as the maximum number of comments has been exceeded.")
            else:
                print("        Replied to inbox comment.")
                comment.mark_as_read()
                actual_coms += 1
        print("")
    if (replied == False):
        print("    There are no unread messages in the inbox.")
    print("Completed Program...")

# By Dom Newman
run_program()


text:
from xml.dom import minidom
import py, sys, os

def runandparse(testdir, *args):
    resultpath = testdir.tmpdir.join("junit.xml")
    result = testdir.runpytest("--junitxml=%s" % resultpath, *args)
    xmldoc = minidom.parse(str(resultpath))
    return result, xmldoc

def assert_attr(node, **kwargs):
    __tracebackhide__ = True
    for name, expected in kwargs.items():
        anode = node.getAttributeNode(name)
        assert anode, "node %r has no attribute %r" %(node, name)
        val = anode.value
        if val != str(expected):
            py.test.fail("%r != %r" %(str(val), str(expected)))

class TestPython:
    def test_summing_simple(self, testdir):
        testdir.makepyfile("""
            import pytest
            def test_pass():
                pass
            def test_fail():
                assert 0
            def test_skip():
                pytest.skip("")
            @pytest.mark.xfail
            def test_xfail():
                assert 0
            @pytest.mark.xfail
            def test_xpass():
                assert 1
        """)
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, errors=0, failures=1, skips=3, tests=2)

    def test_timing_function(self, testdir):
        testdir.makepyfile("""
            import time, pytest
            def test_sleep():
                time.sleep(0.01)
        """)
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testsuite")[0]
        tnode = node.getElementsByTagName("testcase")[0]
        val = tnode.getAttributeNode("time").value
        assert float(val) >= 0.001

    def test_setup_error(self, testdir):
        testdir.makepyfile("""
            def pytest_funcarg__arg(request):
                raise ValueError()
            def test_function(arg):
                pass
        """)
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, errors=1, tests=0)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            classname="test_setup_error",
            name="test_function")
        fnode = tnode.getElementsByTagName("error")[0]
        assert_attr(fnode, message="test setup failure")
        assert "ValueError" in fnode.toxml()

    def test_skip_contains_name_reason(self, testdir):
        testdir.makepyfile("""
            import pytest
            def test_skip():
                pytest.skip("hello23")
        """)
        result, dom = runandparse(testdir)
        assert result.ret == 0
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, skips=1)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            classname="test_skip_contains_name_reason",
            name="test_skip")
        snode = tnode.getElementsByTagName("skipped")[0]
        assert_attr(snode,
            type="pytest.skip",
            message="hello23",
            )

    def test_classname_instance(self, testdir):
        testdir.makepyfile("""
            class TestClass:
                def test_method(self):
                    assert 0
        """)
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, failures=1)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            classname="test_classname_instance.TestClass",
            name="test_method")

    def test_classname_nested_dir(self, testdir):
        p = testdir.tmpdir.ensure("sub", "test_hello.py")
        p.write("def test_func(): 0/0")
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, failures=1)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            classname="sub.test_hello",
            name="test_func")

    def test_internal_error(self, testdir):
        testdir.makeconftest("def pytest_runtest_protocol(): 0 / 0")
        testdir.makepyfile("def test_function(): pass")
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, errors=1, tests=0)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode, classname="pytest", name="internal")
        fnode = tnode.getElementsByTagName("error")[0]
        assert_attr(fnode, message="internal error")
        assert "Division" in fnode.toxml()

    def test_failure_function(self, testdir):
        testdir.makepyfile("""
            import sys
            def test_fail():
                print ("hello-stdout")
                sys.stderr.write("hello-stderr\\n")
                raise ValueError(42)
        """)

        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, failures=1, tests=1)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            classname="test_failure_function",
            name="test_fail")
        fnode = tnode.getElementsByTagName("failure")[0]
        assert_attr(fnode, message="test failure")
        assert "ValueError" in fnode.toxml()
        systemout = fnode.nextSibling
        assert systemout.tagName == "system-out"
        assert "hello-stdout" in systemout.toxml()
        systemerr = systemout.nextSibling
        assert systemerr.tagName == "system-err"
        assert "hello-stderr" in systemerr.toxml()

    def test_failure_escape(self, testdir):
        testdir.makepyfile("""
            def pytest_generate_tests(metafunc):
                metafunc.addcall(id="<", funcargs=dict(arg1=42))
                metafunc.addcall(id="&", funcargs=dict(arg1=44))
            def test_func(arg1):
                assert 0
        """)
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, failures=2, tests=2)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            classname="test_failure_escape",
            name="test_func[<]")
        tnode = node.getElementsByTagName("testcase")[1]
        assert_attr(tnode,
            classname="test_failure_escape",
            name="test_func[&]")

    def test_junit_prefixing(self, testdir):
        testdir.makepyfile("""
            def test_func():
                assert 0
            class TestHello:
                def test_hello(self):
                    pass
        """)
        result, dom = runandparse(testdir, "--junitprefix=xyz")
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, failures=1, tests=2)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            classname="xyz.test_junit_prefixing",
            name="test_func")
        tnode = node.getElementsByTagName("testcase")[1]
        assert_attr(tnode,
            classname="xyz.test_junit_prefixing."
                      "TestHello",
            name="test_hello")

    def test_xfailure_function(self, testdir):
        testdir.makepyfile("""
            import pytest
            def test_xfail():
                pytest.xfail("42")
        """)
        result, dom = runandparse(testdir)
        assert not result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, skips=1, tests=0)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            classname="test_xfailure_function",
            name="test_xfail")
        fnode = tnode.getElementsByTagName("skipped")[0]
        assert_attr(fnode, message="expected test failure")
        #assert "ValueError" in fnode.toxml()

    def test_xfailure_xpass(self, testdir):
        testdir.makepyfile("""
            import pytest
            @pytest.mark.xfail
            def test_xpass():
                pass
        """)
        result, dom = runandparse(testdir)
        #assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, skips=1, tests=0)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            classname="test_xfailure_xpass",
            name="test_xpass")
        fnode = tnode.getElementsByTagName("skipped")[0]
        assert_attr(fnode, message="xfail-marked test passes unexpectedly")
        #assert "ValueError" in fnode.toxml()

    def test_collect_error(self, testdir):
        testdir.makepyfile("syntax error")
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, errors=1, tests=0)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            #classname="test_collect_error",
            name="test_collect_error")
        fnode = tnode.getElementsByTagName("failure")[0]
        assert_attr(fnode, message="collection failure")
        assert "SyntaxError" in fnode.toxml()

    def test_collect_skipped(self, testdir):
        testdir.makepyfile("import pytest; pytest.skip('xyz')")
        result, dom = runandparse(testdir)
        assert not result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, skips=1, tests=0)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            #classname="test_collect_error",
            name="test_collect_skipped")
        fnode = tnode.getElementsByTagName("skipped")[0]
        assert_attr(fnode, message="collection skipped")

    def test_unicode(self, testdir):
        value = 'hx\xc4\x85\xc4\x87\n'
        testdir.makepyfile("""
            # coding: utf-8
            def test_hello():
                print (%r)
                assert 0
        """ % value)
        result, dom = runandparse(testdir)
        assert result.ret == 1
        tnode = dom.getElementsByTagName("testcase")[0]
        fnode = tnode.getElementsByTagName("failure")[0]
        if not sys.platform.startswith("java"):
            assert "hx" in fnode.toxml()

def test_mangle_testnames():
    from _pytest.junitxml import mangle_testnames
    names = ["a/pything.py", "Class", "()", "method"]
    newnames = mangle_testnames(names)
    assert newnames == ["a.pything", "Class", "method"]

class TestNonPython:
    def test_summing_simple(self, testdir):
        testdir.makeconftest("""
            import pytest
            def pytest_collect_file(path, parent):
                if path.ext == ".xyz":
                    return MyItem(path, parent)
            class MyItem(pytest.Item):
                def __init__(self, path, parent):
                    super(MyItem, self).__init__(path.basename, parent)
                    self.fspath = path
                def runtest(self):
                    raise ValueError(42)
                def repr_failure(self, excinfo):
                    return "custom item runtest failed"
        """)
        testdir.tmpdir.join("myfile.xyz").write("hello")
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.getElementsByTagName("testsuite")[0]
        assert_attr(node, errors=0, failures=1, skips=0, tests=1)
        tnode = node.getElementsByTagName("testcase")[0]
        assert_attr(tnode,
            #classname="test_collect_error",
            name="myfile.xyz")
        fnode = tnode.getElementsByTagName("failure")[0]
        assert_attr(fnode, message="test failure")
        assert "custom item runtest failed" in fnode.toxml()

def test_nullbyte(testdir):
    # A null byte can not occur in XML (see section 2.2 of the spec)
    testdir.makepyfile("""
        import sys
        def test_print_nullbyte():
            sys.stdout.write('Here the null -->' + chr(0) + '<--')
            sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')
            assert False
    """)
    xmlf = testdir.tmpdir.join('junit.xml')
    result = testdir.runpytest('--junitxml=%s' % xmlf)
    text = xmlf.read()
    assert '\x00' not in text
    assert '#x00' in text

def test_nullbyte_replace(testdir):
    # Check if the null byte gets replaced
    testdir.makepyfile("""
        import sys
        def test_print_nullbyte():
            sys.stdout.write('Here the null -->' + chr(0) + '<--')
            sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')
            assert False
    """)
    xmlf = testdir.tmpdir.join('junit.xml')
    result = testdir.runpytest('--junitxml=%s' % xmlf)
    text = xmlf.read()
    assert '#x0' in text

def test_invalid_xml_escape():
    # Test some more invalid xml chars, the full range should be
    # tested really but let's just thest the edges of the ranges
    # intead.
    # XXX This only tests low unicode character points for now as
    #     there are some issues with the testing infrastructure for
    #     the higher ones.
    # XXX Testing 0xD (\r) is tricky as it overwrites the just written
    #     line in the output, so we skip it too.
    global unichr
    try:
        unichr(65)
    except NameError:
        unichr = chr
    u = py.builtin._totext
    invalid = (0x00, 0x1, 0xB, 0xC, 0xE, 0x19,
                27, # issue #126
               0xD800, 0xDFFF, 0xFFFE, 0x0FFFF) #, 0x110000)
    valid = (0x9, 0xA, 0x20,) # 0xD, 0xD7FF, 0xE000, 0xFFFD, 0x10000, 0x10FFFF)

    from _pytest.junitxml import bin_xml_escape

    for i in invalid:
        got = bin_xml_escape(unichr(i))
        if i <= 0xFF:
            expected = '#x%02X' % i
        else:
            expected = '#x%04X' % i
        assert got == expected
    for i in valid:
        assert chr(i) == bin_xml_escape(unichr(i))

def test_logxml_path_expansion():
    from _pytest.junitxml import LogXML

    home_tilde = os.path.normpath(os.path.expanduser('~/test.xml'))
    # this is here for when $HOME is not set correct
    home_var = os.path.normpath(os.path.expandvars('$HOME/test.xml'))

    xml_tilde = LogXML('~/test.xml', None)
    assert xml_tilde.logfile == home_tilde

    xml_var = LogXML('$HOME/test.xml', None)
    assert xml_var.logfile == home_var


text:
package copr

import (
	"context"
	"time"

	"github.com/pingcap/errors"
	"github.com/pingcap/kvproto/pkg/coprocessor"
	"github.com/pingcap/kvproto/pkg/metapb"
	tikverr "github.com/tikv/client-go/v2/error"
	"github.com/tikv/client-go/v2/tikv"
	"github.com/tikv/client-go/v2/tikvrpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// RegionInfo contains region related information for batchCopTask
type RegionInfo struct {
	Region         tikv.RegionVerID
	Meta           *metapb.Region
	Ranges         *KeyRanges
	AllStores      []uint64
	PartitionIndex int64 // used by PartitionTableScan, indicates the n-th partition of the partition table
}

func (ri *RegionInfo) toCoprocessorRegionInfo() *coprocessor.RegionInfo {
	return &coprocessor.RegionInfo{
		RegionId: ri.Region.GetID(),
		RegionEpoch: &metapb.RegionEpoch{
			ConfVer: ri.Region.GetConfVer(),
			Version: ri.Region.GetVer(),
		},
		Ranges: ri.Ranges.ToPBRanges(),
	}
}

// RegionBatchRequestSender sends BatchCop requests to TiFlash server by stream way.
type RegionBatchRequestSender struct {
	*tikv.RegionRequestSender
	enableCollectExecutionInfo bool
}

// NewRegionBatchRequestSender creates a RegionBatchRequestSender object.
func NewRegionBatchRequestSender(cache *RegionCache, client tikv.Client, enableCollectExecutionInfo bool) *RegionBatchRequestSender {
	return &RegionBatchRequestSender{
		RegionRequestSender:        tikv.NewRegionRequestSender(cache.RegionCache, client),
		enableCollectExecutionInfo: enableCollectExecutionInfo,
	}
}

// SendReqToAddr send batch cop request
func (ss *RegionBatchRequestSender) SendReqToAddr(bo *Backoffer, rpcCtx *tikv.RPCContext, regionInfos []RegionInfo, req *tikvrpc.Request, timout time.Duration) (resp *tikvrpc.Response, retry bool, cancel func(), err error) {
	cancel = func() {}
	if e := tikvrpc.SetContext(req, rpcCtx.Meta, rpcCtx.Peer); e != nil {
		return nil, false, cancel, errors.Trace(e)
	}
	ctx := bo.GetCtx()
	if rawHook := ctx.Value(tikv.RPCCancellerCtxKey{}); rawHook != nil {
		ctx, cancel = rawHook.(*tikv.RPCCanceller).WithCancel(ctx)
	}
	start := time.Now()
	resp, err = ss.GetClient().SendRequest(ctx, rpcCtx.Addr, req, timout)
	if ss.Stats != nil && ss.enableCollectExecutionInfo {
		tikv.RecordRegionRequestRuntimeStats(ss.Stats, req.Type, time.Since(start))
	}
	if err != nil {
		cancel()
		ss.SetRPCError(err)
		e := ss.onSendFailForBatchRegions(bo, rpcCtx, regionInfos, err)
		if e != nil {
			return nil, false, func() {}, errors.Trace(e)
		}
		return nil, true, func() {}, nil
	}
	// We don't need to process region error or lock error. Because TiFlash will retry by itself.
	return
}

func (ss *RegionBatchRequestSender) onSendFailForBatchRegions(bo *Backoffer, ctx *tikv.RPCContext, regionInfos []RegionInfo, err error) error {
	// If it failed because the context is cancelled by ourself, don't retry.
	if errors.Cause(err) == context.Canceled || status.Code(errors.Cause(err)) == codes.Canceled {
		return errors.Trace(err)
	} else if tikv.LoadShuttingDown() > 0 {
		return tikverr.ErrTiDBShuttingDown
	}

	// The reload region param is always true. Because that every time we try, we must
	// re-build the range then re-create the batch sender. As a result, the len of "failStores"
	// will change. If tiflash's replica is more than two, the "reload region" will always be false.
	// Now that the batch cop and mpp has a relative low qps, it's reasonable to reload every time
	// when meeting io error.
	rc := RegionCache{ss.GetRegionCache()}
	rc.OnSendFailForBatchRegions(bo, ctx.Store, regionInfos, true, err)

	// Retry on send request failure when it's not canceled.
	// When a store is not available, the leader of related region should be elected quickly.
	// TODO: the number of retry time should be limited:since region may be unavailable
	// when some unrecoverable disaster happened.
	err = bo.Backoff(tikv.BoTiFlashRPC(), errors.Errorf("send request error: %v, ctx: %v, regionInfos: %v", err, ctx, regionInfos))
	return errors.Trace(err)
}


text:
Spree::Admin::OrdersController.class_eval do
  after_filter :set_admin , :only => [:update]

  def set_admin
    @order.admin = current_user
    @order.save
  end
end


text:
<?php

namespace Isometriks\Bundle\RedditBotBundle\Model;

class Feed implements FeedInterface
{
    protected $url;
    protected $subreddit;
    protected $flair = array();
    protected $options = array();

    public function __construct($url, $subreddit, array $flair, array $options)
    {
        $this->url = $url;
        $this->subreddit = $subreddit;
        $this->flair = $flair;
        $this->options = $options;
    }

    public function getUrl()
    {
        return $this->url;
    }

    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }

    public function getSubreddit()
    {
        return $this->subreddit;
    }

    public function setSubreddit($subreddit)
    {
        $this->subreddit = $subreddit;

        return $this;
    }

    public function getFlair()
    {
        return $this->flair;
    }

    public function setFlair(array $flair)
    {
        $this->flair = $flair;

        return $this;
    }

    public function getOptions()
    {
        return $this->options;
    }

    public function setOptions(array $options)
    {
        $this->options = $options;
    }

    public function getOption($option)
    {
        if (!array_key_exists($option, $this->options)) {
            throw new \InvalidArgumentException(sprintf('Option "%s" does not exist', $option));
        }

        return $this->options[$option];
    }

    public function setOption($option, $value)
    {
        $this->options[$option] = $value;
    }
}


text:
using System;
using Microsoft.Extensions.Logging;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace SkiaSharpSample
{
	/// <summary>
	/// Provides application-specific behavior to supplement the default Application class.
	/// </summary>
	public sealed partial class App : Application
	{
		/// <summary>
		/// Initializes the singleton application object.  This is the first line of authored code
		/// executed, and as such is the logical equivalent of main() or WinMain().
		/// </summary>
		public App()
		{
			ConfigureFilters(Uno.Extensions.LogExtensionPoint.AmbientLoggerFactory);

			InitializeComponent();
			Suspending += OnSuspending;
		}

		/// <summary>
		/// Invoked when the application is launched normally by the end user.  Other entry points
		/// will be used such as when the application is launched to open a specific file.
		/// </summary>
		/// <param name="e">Details about the launch request and process.</param>
		protected override void OnLaunched(LaunchActivatedEventArgs e)
		{
			Frame rootFrame = Windows.UI.Xaml.Window.Current.Content as Frame;

			// Do not repeat app initialization when the Window already has content,
			// just ensure that the window is active
			if (rootFrame == null)
			{
				// Create a Frame to act as the navigation context and navigate to the first page
				rootFrame = new Frame();

				rootFrame.NavigationFailed += OnNavigationFailed;

				if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
				{
					//TODO: Load state from previously suspended application
				}

				// Place the frame in the current Window
				Windows.UI.Xaml.Window.Current.Content = rootFrame;
			}

			if (e.PrelaunchActivated == false)
			{
				if (rootFrame.Content == null)
				{
					// When the navigation stack isn't restored navigate to the first page,
					// configuring the new page by passing required information as a navigation
					// parameter
					rootFrame.Navigate(typeof(MainPage), e.Arguments);
				}
				// Ensure the current window is active
				Windows.UI.Xaml.Window.Current.Activate();
			}
		}

		/// <summary>
		/// Invoked when Navigation to a certain page fails
		/// </summary>
		/// <param name="sender">The Frame which failed navigation</param>
		/// <param name="e">Details about the navigation failure</param>
		private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
		{
			throw new Exception($"Failed to load {e.SourcePageType.FullName}: {e.Exception}");
		}

		/// <summary>
		/// Invoked when application execution is being suspended.  Application state is saved
		/// without knowing whether the application will be terminated or resumed with the contents
		/// of memory still intact.
		/// </summary>
		/// <param name="sender">The source of the suspend request.</param>
		/// <param name="e">Details about the suspend request.</param>
		private void OnSuspending(object sender, SuspendingEventArgs e)
		{
			var deferral = e.SuspendingOperation.GetDeferral();
			//TODO: Save application state and stop any background activity
			deferral.Complete();
		}

		/// <summary>
		/// Configures global logging
		/// </summary>
		/// <param name="factory"></param>
		private static void ConfigureFilters(ILoggerFactory factory)
		{
			factory
				.WithFilter(new FilterLoggerSettings
					{
						{ "Uno", LogLevel.Warning },
						{ "Windows", LogLevel.Warning },

						// Debug JS interop
						// { "Uno.Foundation.WebAssemblyRuntime", LogLevel.Debug },

						// Generic Xaml events
						// { "Windows.UI.Xaml", LogLevel.Debug },
						// { "Windows.UI.Xaml.VisualStateGroup", LogLevel.Debug },
						// { "Windows.UI.Xaml.StateTriggerBase", LogLevel.Debug },
						// { "Windows.UI.Xaml.UIElement", LogLevel.Debug },

						// Layouter specific messages
						// { "Windows.UI.Xaml.Controls", LogLevel.Debug },
						// { "Windows.UI.Xaml.Controls.Layouter", LogLevel.Debug },
						// { "Windows.UI.Xaml.Controls.Panel", LogLevel.Debug },
						// { "Windows.Storage", LogLevel.Debug },

						// Binding related messages
						// { "Windows.UI.Xaml.Data", LogLevel.Debug },

						// DependencyObject memory references tracking
						// { "ReferenceHolder", LogLevel.Debug },

						// ListView-related messages
						// { "Windows.UI.Xaml.Controls.ListViewBase", LogLevel.Debug },
						// { "Windows.UI.Xaml.Controls.ListView", LogLevel.Debug },
						// { "Windows.UI.Xaml.Controls.GridView", LogLevel.Debug },
						// { "Windows.UI.Xaml.Controls.VirtualizingPanelLayout", LogLevel.Debug },
						// { "Windows.UI.Xaml.Controls.NativeListViewBase", LogLevel.Debug },
						// { "Windows.UI.Xaml.Controls.ListViewBaseSource", LogLevel.Debug }, //iOS
						// { "Windows.UI.Xaml.Controls.ListViewBaseInternalContainer", LogLevel.Debug }, //iOS
						// { "Windows.UI.Xaml.Controls.NativeListViewBaseAdapter", LogLevel.Debug }, //Android
						// { "Windows.UI.Xaml.Controls.BufferViewCache", LogLevel.Debug }, //Android
						// { "Windows.UI.Xaml.Controls.VirtualizingPanelGenerator", LogLevel.Debug }, //WASM
					}
				)
#if DEBUG
				.AddConsole(LogLevel.Debug);
#else
				.AddConsole(LogLevel.Information);
#endif
#if !WINDOWS_UWP
			Uno.UI.Adapter.Microsoft.Extensions.Logging.LoggingAdapter.Initialize();
#endif
		}
	}
}


text:
import Ember from 'ember';

export default Ember.Component.extend({
  model: function (params) {
		return this.store.find('vendor', params.vendor_id);
	}
});