text:
[commerce.js](../README.md) › [Globals](../globals.md) › ["Product"](../modules/_product_.md) › [Product](_product_.product.md)

# Class: Product

Product is something that goes in a cart, we sync these from the server but
only keep the fields we care about

## Hierarchy

* **Product**

  ↳ [LineItem](_lineitem_.lineitem.md)

## Implements

* [IProduct](../interfaces/_types_.iproduct.md)

## Index

### Constructors

* [constructor](_product_.product.md#constructor)

### Properties

* [bootstrapPromise](_product_.product.md#bootstrappromise)
* [client](_product_.product.md#client)
* [description](_product_.product.md#description)
* [id](_product_.product.md#id)
* [listPrice](_product_.product.md#listprice)
* [name](_product_.product.md#name)
* [price](_product_.product.md#price)
* [productId](_product_.product.md#productid)
* [productName](_product_.product.md#productname)
* [productSlug](_product_.product.md#productslug)
* [slug](_product_.product.md#slug)

## Constructors

###  constructor

\+ **new Product**(`raw`: any, `client`: [IProductClient](../interfaces/_types_.iproductclient.md)): *[Product](_product_.product.md)*

*Defined in [Product.ts:50](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L50)*

**Parameters:**

Name | Type |
------ | ------ |
`raw` | any |
`client` | [IProductClient](../interfaces/_types_.iproductclient.md) |

**Returns:** *[Product](_product_.product.md)*

## Properties

###  bootstrapPromise

• **bootstrapPromise**: *Promise‹[IProduct](../interfaces/_types_.iproduct.md) | void›*

*Defined in [Product.ts:47](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L47)*

___

###  client

• **client**: *[IProductClient](../interfaces/_types_.iproductclient.md)*

*Defined in [Product.ts:50](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L50)*

___

###  description

• **description**: *string*

*Implementation of [IProduct](../interfaces/_types_.iproduct.md).[description](../interfaces/_types_.iproduct.md#description)*

*Defined in [Product.ts:44](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L44)*

___

###  id

• **id**: *string*

*Implementation of [IProduct](../interfaces/_types_.iproduct.md).[id](../interfaces/_types_.iproduct.md#id)*

*Defined in [Product.ts:20](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L20)*

___

###  listPrice

• **listPrice**: *number*

*Implementation of [IProduct](../interfaces/_types_.iproduct.md).[listPrice](../interfaces/_types_.iproduct.md#listprice)*

*Defined in [Product.ts:41](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L41)*

___

###  name

• **name**: *string*

*Implementation of [IProduct](../interfaces/_types_.iproduct.md).[name](../interfaces/_types_.iproduct.md#name)*

*Defined in [Product.ts:32](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L32)*

___

###  price

• **price**: *number*

*Implementation of [IProduct](../interfaces/_types_.iproduct.md).[price](../interfaces/_types_.iproduct.md#price)*

*Defined in [Product.ts:38](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L38)*

___

###  productId

• **productId**: *string*

*Implementation of [IProduct](../interfaces/_types_.iproduct.md).[productId](../interfaces/_types_.iproduct.md#productid)*

*Defined in [Product.ts:23](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L23)*

___

###  productName

• **productName**: *string*

*Implementation of [IProduct](../interfaces/_types_.iproduct.md).[productName](../interfaces/_types_.iproduct.md#productname)*

*Defined in [Product.ts:35](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L35)*

___

###  productSlug

• **productSlug**: *string*

*Implementation of [IProduct](../interfaces/_types_.iproduct.md).[productSlug](../interfaces/_types_.iproduct.md#productslug)*

*Defined in [Product.ts:29](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L29)*

___

###  slug

• **slug**: *string*

*Implementation of [IProduct](../interfaces/_types_.iproduct.md).[slug](../interfaces/_types_.iproduct.md#slug)*

*Defined in [Product.ts:26](https://github.com/shopjs/commerce.js/blob/c368654/src/Product.ts#L26)*


text:
<?php

namespace Asfour\ActionBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Asfour\ActionBundle\Entity\Action;
use Asfour\ActionBundle\Form\ActionType;

/**
 * Action controller.
 *
 */
class ActionController extends Controller
{

    /**
     * Lists all Action entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AsfourActionBundle:Action')->findAll();

        return $this->render('AsfourActionBundle:Action:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Action entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Action();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('action_show', array('id' => $entity->getId())));
        }

        return $this->render('AsfourActionBundle:Action:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Action entity.
     *
     * @param Action $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Action $entity)
    {
        $form = $this->createForm(new ActionType(), $entity, array(
            'action' => $this->generateUrl('action_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Action entity.
     *
     */
    public function newAction()
    {
        $entity = new Action();
        $form   = $this->createCreateForm($entity);

        return $this->render('AsfourActionBundle:Action:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Action entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AsfourActionBundle:Action')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Action entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('AsfourActionBundle:Action:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Action entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AsfourActionBundle:Action')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Action entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('AsfourActionBundle:Action:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Action entity.
    *
    * @param Action $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Action $entity)
    {
        $form = $this->createForm(new ActionType(), $entity, array(
            'action' => $this->generateUrl('action_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Action entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AsfourActionBundle:Action')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Action entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('action_edit', array('id' => $id)));
        }

        return $this->render('AsfourActionBundle:Action:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Action entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AsfourActionBundle:Action')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Action entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('action'));
    }

    /**
     * Creates a form to delete a Action entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('action_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface TypesetKit ()

@property (nonatomic, strong) NSMutableArray *attributeRanges;

@property (nonatomic, assign) NSInteger attributeFrom;
@property (nonatomic, assign) NSInteger attributeTo;

@property (nonatomic, assign) NSInteger attributeLocation;
@property (nonatomic, assign) NSInteger attributeLength;

@property (nonatomic, strong) NSMutableParagraphStyle *paragraphStyle;

@end

@implementation TypesetKit (Match)

- (void)removeAllAttributeRanges {
    [self.attributeRanges removeAllObjects];
    self.paragraphStyle = nil;
}

#pragma mark - Range Construct

- (TypesetUIntegerBlock)from {
    return ^(NSUInteger from) {
        if (self.attributeTo != -1) {
            [self removeAllAttributeRanges];
            [self.attributeRanges addObject:[NSValue valueWithLocation:from length:self.attributeTo - from]];
        }
        self.attributeFrom = from;
        return self;
    };
}

- (TypesetUIntegerBlock)to {
    return ^(NSUInteger to) {
        if (self.attributeFrom != -1) {
            [self removeAllAttributeRanges];
            [self.attributeRanges addObject:[NSValue valueWithLocation:self.attributeFrom length:to - self.attributeFrom]];
        }
        self.attributeTo = to;
        return self;
    };
}

- (TypesetUIntegerBlock)location {
    return ^(NSUInteger location) {
        if (self.attributeLength != -1) {
            [self removeAllAttributeRanges];
            [self.attributeRanges addObject:[NSValue valueWithLocation:location length:self.attributeLength]];
        }
        self.attributeLocation = location;
        return self;
    };
}

- (TypesetUIntegerBlock)length {
    return ^(NSUInteger length) {
        if (self.attributeLocation != -1) {
            [self removeAllAttributeRanges];
            [self.attributeRanges addObject:[NSValue valueWithLocation:self.attributeLocation length:length]];
        }
        self.attributeLength = length;
        return self;
    };
}

- (TypesetRangeBlock)range {
    return ^(NSRange range) {
        [self removeAllAttributeRanges];
        [self.attributeRanges addObject:[NSValue valueWithRange:range]];
        return self;
    };
}

#pragma mark - Match String

- (TypesetStringBlock)matchAll {
    return ^(NSString *substring) {
        return self.matchAllWithOptions(substring, 0);
    };
}

- (TypesetMatchBlock)matchAllWithOptions {
    return ^(NSString *substring, NSStringCompareOptions options) {
        NSRange range = [self.string.string rangeOfString:substring options:options];
        [self removeAllAttributeRanges];
        [self.attributeRanges addObject:[NSValue valueWithRange:range]];
        while (range.length != 0) {
            NSInteger location = range.location + range.length;
            NSInteger length = self.string.length - location;
            range = [self.string.string rangeOfString:substring options:options range:NSMakeRange(location, length)];
            [self.attributeRanges addObject:[NSValue valueWithRange:range]];
        }
        return self;
    };
}

- (TypesetStringBlock)match {
    return ^(NSString *substring) {
        return self.matchWithOptions(substring, 0);
    };
}

- (TypesetStringBlock)matchLast {
    return ^(NSString *substring) {
        return self.matchWithOptions(substring, NSBackwardsSearch);
    };
}

- (TypesetMatchBlock)matchWithOptions {
    return ^(NSString *substring, NSStringCompareOptions options) {
        NSRange range = [self.string.string rangeOfString:substring options:options];
        [self removeAllAttributeRanges];
        [self.attributeRanges addObject:[NSValue valueWithRange:range]];
        return self;
    };
}

- (TypesetKit *)all {
    [self removeAllAttributeRanges];
    [self.attributeRanges addObject:[NSValue valueWithLocation:0 length:self.string.length]];
    return self;
}

#pragma mark - MatchWithPattern

- (TypesetBlock(NSString *, NSRegularExpressionOptions))matchAllWithPatternAndOptions {
    return ^(NSString *pattern, NSRegularExpressionOptions options) {
        return [self matchAllWithPattern:pattern options:options];
    };
}

- (TypesetStringBlock)matchAllWithPattern {
    return ^(NSString *pattern) {
        return [self matchAllWithPattern:pattern options:0];
    };
}

- (TypesetKit *)matchNumbers {
    return [self matchAllWithPattern:@"\\d+" options:0];
}

- (TypesetKit *)matchLetters {
    return [self matchAllWithPattern:@"[a-zA-Z]+" options:0];
}

- (TypesetStringBlock)matchLanguage {
    return ^(NSString *language) {
        return [self matchAllWithPattern:[NSString stringWithFormat:@"\\p{script=%@}", language] options:0];
    };
}

- (TypesetKit *)matchChinese {
    return self.matchLanguage(@"Han");
}

#pragma mark - Helper

- (TypesetKit *)matchWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options {
    NSError *regError;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                           options:options
                                                                             error:&regError];
    if (regError) NSLog(@"%@",regError.localizedDescription);

    [self removeAllAttributeRanges];
    NSRange range = NSMakeRange(0, self.string.string.length);
    NSRange resultRange = [regex rangeOfFirstMatchInString:self.string.string
                                                   options:0 range:range];
    [self.attributeRanges addObject:[NSValue valueWithRange:resultRange]];
    return self;
}

- (TypesetKit *)matchAllWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options {
    NSError *regError;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                           options:options
                                                                             error:&regError];
    if (regError) NSLog(@"%@",regError.localizedDescription);

    [self removeAllAttributeRanges];
    NSRange range = NSMakeRange(0, self.string.string.length);
    [regex enumerateMatchesInString:self.string.string
                            options:0 range:range
                         usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
                             [self.attributeRanges addObject:[NSValue valueWithRange:result.range]];
                         }];
    return self;
}

@end


text:
Custom CollegeCode badge to link your repo to this organization [![College Code](https://img.shields.io/badge/CollegeCode-Repo-red.svg)](https://github.com/CollegeCODE/badges/)

Note: This badge is optional and just a way to show that your repo is part of collegecode and the author is part of the team.

## General Instructions

### Get Badge from this URL -> https://img.shields.io/badge/CollegeCode-Repo-red.svg

Add the following code in your readme.md

```
![College Code](https://img.shields.io/badge/CollegeCode-Repo-red.svg)](REPLACE_THIS_WITH_COLLEGECODE_REPO OR JUST_LINK_TO_ORGANIZATION_PAGE)
```


text:
package no.kantega.publishing.spring;

import no.kantega.publishing.api.plugin.OpenAksessPlugin;
import org.apache.commons.io.IOUtils;
import org.kantega.jexmec.PluginManager;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 */
public class PluginStaticContentController extends AbstractController {
    private PluginManager<OpenAksessPlugin> pluginManager;
    private String prefix;
    private final File[] baseDirectories;

    public PluginStaticContentController() {
        final String resourceBases = System.getProperty("resourceBases");

        // For easy development reload of plugin resources

        List<File> baseDirectories = new ArrayList<File>();

        if(resourceBases != null) {
            for(String base : resourceBases.split(File.pathSeparator)) {
                File baseFile = new File(base);
                if(baseFile.exists() && baseFile.isDirectory()) {
                    baseDirectories.add(baseFile);
                }
            }
        }

        this.baseDirectories = baseDirectories.toArray(new File[baseDirectories.size()]);

    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

        final String pathInfo = request.getPathInfo();
        String path = pathInfo.substring("/static/".length());

        String resourcePath = prefix + path;

        URL resource = getResourceFromDevelopmentPaths(resourcePath);
        if(resource == null) {
            resource = getResourceFromPlugins(resourcePath);
        }
        if(resource != null) {
            String mimeType = getServletContext().getMimeType(pathInfo.substring(pathInfo.lastIndexOf("/") +1));
            response.setContentType(mimeType);
            IOUtils.copy(resource.openStream(), response.getOutputStream());
            return null;
        } else {

            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }
    }

    private URL getResourceFromDevelopmentPaths(String resourcePath) {
        for(File base : baseDirectories) {
            final File file = new File(base, resourcePath);
            if(file.exists()) {
                try {
                    return file.toURI().toURL();
                } catch (MalformedURLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return null;
    }

    private URL getResourceFromPlugins(String resourcePath) {
        for(OpenAksessPlugin plugin : pluginManager.getPlugins()) {
            ClassLoader classLoader = pluginManager.getClassLoader(plugin);

            if(classLoader != null) {
                URL resource = classLoader.getResource(resourcePath);
                if(resource != null) {
                    return resource;
                }
            }
        }
        return null;
    }

    public void setPluginManager(PluginManager<OpenAksessPlugin> pluginManager) {
        this.pluginManager = pluginManager;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
}


text:
- Adds `VaingloryAPI::Region` object
- Validates `VaingloryAPI::Client` region at instantiation
- Moves Gem date to `VaingloryAPI::RELEASE_DATE`
- Adds shared RSpec example group for all lib specs
- Changes default RSpec format to "documentation"
- Updates README

## 0.0.4
- Fixes bug where where some match data was missing (see: [Issue #7](https://github.com/cbortz/vainglory-api-ruby/issues/7))
- Adds a `CHANGELOG.md` to the repository
- Adds Rubocop configurations
- Adds YARD documentation
- Removes and ignores `Gemfile.lock`
- Refreshes stored VCR cassettes
- Splits `VaingloryAPI` and `VaingloryAPI::Client` specs

## 0.0.3
- Ruby version >= 2.0 is required
- Adds Gem version badge

## 0.0.2 [yanked]
...nothing substantial happened here

## 0.0.1 [yanked]
- Integrates with TravisCI
- Integrates with CodeClimate
- Implements basic OStruct responses for API endpoints


text:
package com.github.btrekkie.reductions.planar.test;

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

import com.github.btrekkie.reductions.planar.IPlanarGadget;
import com.github.btrekkie.reductions.planar.Point;

/** A test gadget for I3SatPlanarGadgetFactory.createCrossover().  See the comments for that method. */
class TestCrossoverGadget implements IPlanarGadget {
    /**
     * The index of one of the entry ports - corresponding to EXIT_PORT1 and immediately counterclockwise from
     * ENTRY_PORT2 - as in I3SatPlanarGadgetFactory.firstCrossoverEntryPort or
     * I3SatPlanarGadgetFactory.secondCrossoverEntryPort.
     */
    public static final int ENTRY_PORT1 = 0;

    /**
     * The index of one of the exit ports - corresponding to ENTRY_PORT1 and immediately counterclockwise from
     * EXIT_PORT2 - as in I3SatPlanarGadgetFactory.firstCrossoverExitPort or
     * I3SatPlanarGadgetFactory.secondCrossoverExitPort.
     */
    public static final int EXIT_PORT1 = 2;

    /**
     * The index of one of the entry ports - corresponding to EXIT_PORT2 and immediately clockwise from ENTRY_PORT1 - as
     * in I3SatPlanarGadgetFactory.firstCrossoverEntryPort or I3SatPlanarGadgetFactory.secondCrossoverEntryPort.
     */
    public static final int ENTRY_PORT2 = 1;

    /**
     * The index of one of the exit ports - corresponding to ENTRY_PORT2 and immediately clockwise from EXIT_PORT1 - as
     * in I3SatPlanarGadgetFactory.firstCrossoverExitPort or I3SatPlanarGadgetFactory.secondCrossoverExitPort.
     */
    public static final int EXIT_PORT2 = 3;

    @Override
    public int width() {
        return 20;
    }

    @Override
    public int height() {
        return 20;
    }

    @Override
    public List<Point> ports() {
        return Arrays.asList(new Point(0, 10), new Point(10, 0), new Point(20, 10), new Point(10, 20));
    }
}


text:
package com.datamountaineer.streamreactor.connect.source

import javax.naming.NameNotFoundException

import javax.jms.Session

import com.datamountaineer.streamreactor.connect.TestBase
import com.datamountaineer.streamreactor.connect.jms.JMSSessionProvider
import com.datamountaineer.streamreactor.connect.jms.config.{DestinationSelector, JMSConfig, JMSSettings}
import org.apache.activemq.ActiveMQConnection
import org.scalatest.BeforeAndAfterAll
import org.scalatest.concurrent.Eventually

import scala.util.Try

class JMSSessionProviderTest extends TestBase with BeforeAndAfterAll with Eventually {

  val forAJmsConsumer = false
  val forAJmsProducer = true

  "should only create JMS Queue Consumer when reading from JMS Queue" in testWithBrokerOnPort { (conn, brokerUrl) =>
    val props = getProps1Queue(brokerUrl)
    val config = JMSConfig(props)
    val settings = JMSSettings(config, forAJmsConsumer)
    val provider = JMSSessionProvider(settings, forAJmsConsumer)

    provider.queueConsumers.size shouldBe 1
    provider.queueProducers.size shouldBe 0
    provider.topicsConsumers.size shouldBe 0
    provider.topicProducers.size shouldBe 0
  }

  "should only create JMS Topic Consumer when reading from JMS Topic" in testWithBrokerOnPort { (conn, brokerUrl) =>
    val props = getProps1Topic(brokerUrl)
    val config = JMSConfig(props)
    val settings = JMSSettings(config, forAJmsConsumer)
    val provider = JMSSessionProvider(settings, forAJmsConsumer)

    provider.queueConsumers.size shouldBe 0
    provider.queueProducers.size shouldBe 0
    provider.topicsConsumers.size shouldBe 1
    provider.topicProducers.size shouldBe 0
  }

  "should only create JMS Queue Producer when writing to JMS Queue" in testWithBrokerOnPort { (conn, brokerUrl) =>
    val props = getProps1Queue(brokerUrl)
    val config = JMSConfig(props)
    val settings = JMSSettings(config, forAJmsProducer)
    val provider = JMSSessionProvider(settings, forAJmsProducer)

    provider.queueConsumers.size shouldBe 0
    provider.queueProducers.size shouldBe 1
    provider.topicsConsumers.size shouldBe 0
    provider.topicProducers.size shouldBe 0
  }

  "should only create JMS Topic Producer when writing to JMS Topic" in testWithBrokerOnPort { (conn, brokerUrl) =>
    val props = getProps1Topic(brokerUrl)
    val config = JMSConfig(props)
    val settings = JMSSettings(config, forAJmsProducer)
    val provider = JMSSessionProvider(settings, forAJmsProducer)

    provider.queueConsumers.size shouldBe 0
    provider.queueProducers.size shouldBe 0
    provider.topicsConsumers.size shouldBe 0
    provider.topicProducers.size shouldBe 1
  }

  "should close the connection when the task is stopped" in testWithBrokerOnPort { (conn, brokerUrl) =>
    val props = getProps1Topic(brokerUrl)
    val config = JMSConfig(props)
    val settings = JMSSettings(config, forAJmsProducer)
    val provider = JMSSessionProvider(settings, forAJmsProducer)

    provider.close().isSuccess shouldBe true
    Try(provider.connection.createSession(false, Session.CLIENT_ACKNOWLEDGE)).isFailure shouldBe true
  }

  "should close connection and free resources on exception when configuring session provider" in
    testWithBroker(clientID = Some("static-client-id")) { brokerUrl =>
      val props = getProps1Topic(brokerUrl)
      val config = JMSConfig(props)
      val validSettings = JMSSettings(config, forAJmsConsumer)
      val invalidSettings = validSettings.copy(destinationSelector = DestinationSelector.JNDI)

      assertThrows[NameNotFoundException] {
        JMSSessionProvider(invalidSettings, forAJmsConsumer)
      }
      val provider = JMSSessionProvider(validSettings, forAJmsConsumer)
      provider.connection.asInstanceOf[ActiveMQConnection].isClosed shouldBe false
      provider.connection.close()
    }
}


text:
==============================================================================
libbkmeans: A Library for clustering with K-means on binary data
==============================================================================
Manuel J. Marin-Jimenez

This software implements a kmeans clustering method for binary data.
This can be used to cluster binary features as ORB, FREAK, etc.
--------------------------------------------------------------------------------

   Source-Code:   https://github.com/mjmarin/libbkmeans

--------------------------------------------------------------------------------
Contents of the package:
--------------------------------------------------------------------------------
- bin - the executable file will be created here
- data - some test images
- doc - folder where the documentation will be generated
- include - contains all the software header files
- libs - folder where the library will be generated
- obj - folder where the object files will be generated during the compilation
- src - contains all the software source files
- tests - contains some programs to test the library

--------------------------------------------------------------------------------
Requirements:
--------------------------------------------------------------------------------
This software has been tested on MS Windows with MS Visual C++ 2010 Express and OpenCV 2.4.4

--------------------------------------------------------------------------------
Quick start:
--------------------------------------------------------------------------------
1. Compile with CMake
2. Run test program:
   clustercv data\plant.jpg 100

--------------------------------------------------------------------------------
Citation:
--------------------------------------------------------------------------------
If you use this library for your publications, please cite it as:
@misc{libbkmeans,
 author = {Marin-Jimenez, Manuel J.},
 title = {{LibBKmeans}: A Library for clustering with K-means on binary data},
 year = {2013},
 note =   {Software available at \url{https://github.com/mjmarin/libbkmeans}}
}

--------------------------------------------------------------------------------
Version history:
--------------------------------------------------------------------------------
 - v0.0.1: first release


text:
package boofcv.alg.filter.derivative;

import boofcv.alg.filter.derivative.impl.GradientSobel_Naive;
import boofcv.alg.filter.derivative.impl.GradientSobel_Outer;
import boofcv.alg.filter.derivative.impl.GradientSobel_UnrolledOuter;
import boofcv.misc.PerformerBase;
import boofcv.misc.ProfileOperation;

/**
 * Benchmarks related to computing image derivatives
 *
 * @author Peter Abeles
 */
public class BenchmarkSobel extends BenchmarkDerivativeBase{

	public static class Sobel_I8 extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel.process(imgInt8,derivX_I16,derivY_I16,borderI32);
		}
	}

	public static class Sobel_F32 extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel.process(imgFloat32,derivX_F32,derivY_F32,borderF32);
		}
	}

	public static class SobelNaive_I8 extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel_Naive.process(imgInt8,derivX_I16,derivY_I16);
		}
	}

	public static class SobelNaive_F32 extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel_Naive.process(imgFloat32,derivX_F32,derivY_F32);
		}
	}

	public static class SobelOuter_I8 extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel_Outer.process_I8(imgInt8,derivX_I16,derivY_I16);
		}
	}

	public static class SobelOuter_I8_Sub extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel_Outer.process_I8_sub(imgInt8,derivX_I16,derivY_I16);
		}
	}

	public static class SobelOuter_F32 extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel_Outer.process_F32(imgFloat32,derivX_F32,derivY_F32);
		}
	}

	public static class SobelUnrolledOuter_I8 extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel_UnrolledOuter.process_I8(imgInt8,derivX_I16,derivY_I16);
		}
	}

	public static class SobelUnrolledOuter_F32 extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel_UnrolledOuter.process_F32(imgFloat32,derivX_F32,derivY_F32);
		}
	}

	public static class SobelUnrolledOuter_F32_Sub extends PerformerBase
	{
		@Override
		public void process() {
			GradientSobel_UnrolledOuter.process_F32_sub(imgFloat32,derivX_F32,derivY_F32);
		}
	}

	@Override
	public void profile_I8() {
		ProfileOperation.printOpsPerSec(new Sobel_I8(),TEST_TIME);
		ProfileOperation.printOpsPerSec(new SobelNaive_I8(),TEST_TIME);
		ProfileOperation.printOpsPerSec(new SobelOuter_I8(),TEST_TIME);
		ProfileOperation.printOpsPerSec(new SobelOuter_I8_Sub(),TEST_TIME);
		ProfileOperation.printOpsPerSec(new SobelUnrolledOuter_I8(),TEST_TIME);
	}

	@Override
	public void profile_F32() {
		ProfileOperation.printOpsPerSec(new Sobel_F32(),TEST_TIME);
		ProfileOperation.printOpsPerSec(new SobelNaive_F32(),TEST_TIME);
		ProfileOperation.printOpsPerSec(new SobelOuter_F32(),TEST_TIME);
		ProfileOperation.printOpsPerSec(new SobelUnrolledOuter_F32(),TEST_TIME);
		ProfileOperation.printOpsPerSec(new SobelUnrolledOuter_F32_Sub(),TEST_TIME);
	}

	public static void main( String args[] ) {
		BenchmarkSobel benchmark = new BenchmarkSobel();

		BenchmarkSobel.border = true;
		benchmark.process();
	}
}


text:
<?php
	if(!defined('IN_MYBB')) {
		die;
	}

	function task_EE_imperator($task) {
		//Edit this if you're using a different install path
		require_once MYBB_ROOT.'/imperator/app/Imperator.php';

		$cron = new \imperator\Cron();
		$numChats = $cron->cleanChat();
		$numGames = $cron->cleanGames();

		add_task_log($task, 'EE_imperator cleanup task completed: '.$numChats.' chat messages and '.$numGames.' games deleted.');
	}


text:
import py
import sys
from rpython.rlib.debug import debug_print
from rpython.translator.translator import TranslationContext, graphof
from rpython.jit.metainterp.optimizeopt import ALL_OPTS_NAMES
from rpython.rlib.rarithmetic import is_valid_int

class BaseCompiledMixin(object):

    CPUClass = None
    basic = False

    def _get_TranslationContext(self):
        return TranslationContext()

    def _compile_and_run(self, t, entry_point, entry_point_graph, args):
        raise NotImplementedError

    # XXX backendopt is ignored
    def meta_interp(self, function, args, repeat=1, inline=False, trace_limit=sys.maxint,
                    backendopt=None, listcomp=False, **kwds): # XXX ignored
        from rpython.jit.metainterp.warmspot import WarmRunnerDesc
        from rpython.annotator.listdef import s_list_of_strings
        from rpython.annotator import model as annmodel

        for arg in args:
            assert is_valid_int(arg)

        self.pre_translation_hook()
        t = self._get_TranslationContext()
        if listcomp:
            t.config.translation.list_comprehension_operations = True

        arglist = ", ".join(['int(argv[%d])' % (i + 1) for i in range(len(args))])
        if len(args) == 1:
            arglist += ','
        arglist = '(%s)' % arglist
        if repeat != 1:
            src = py.code.Source("""
            def entry_point(argv):
                args = %s
                res = function(*args)
                for k in range(%d - 1):
                    res = function(*args)
                print res
                return 0
            """ % (arglist, repeat))
        else:
            src = py.code.Source("""
            def entry_point(argv):
                args = %s
                res = function(*args)
                print res
                return 0
            """ % (arglist,))
        exec src.compile() in locals()

        t.buildannotator().build_types(function, [int] * len(args),
                                       main_entry_point=True)
        t.buildrtyper().specialize()
        warmrunnerdesc = WarmRunnerDesc(t, translate_support_code=True,
                                        CPUClass=self.CPUClass,
                                        **kwds)
        for jd in warmrunnerdesc.jitdrivers_sd:
            jd.warmstate.set_param_threshold(3)          # for tests
            jd.warmstate.set_param_trace_eagerness(2)    # for tests
            jd.warmstate.set_param_trace_limit(trace_limit)
            jd.warmstate.set_param_inlining(inline)
            jd.warmstate.set_param_enable_opts(ALL_OPTS_NAMES)
        mixlevelann = warmrunnerdesc.annhelper
        entry_point_graph = mixlevelann.getgraph(entry_point, [s_list_of_strings],
                                                 annmodel.SomeInteger())
        warmrunnerdesc.finish()
        self.post_translation_hook()
        return self._compile_and_run(t, entry_point, entry_point_graph, args)

    def pre_translation_hook(self):
        pass

    def post_translation_hook(self):
        pass

    def check_loops(self, *args, **kwds):
        pass

    def check_loop_count(self, *args, **kwds):
        pass

    def check_tree_loop_count(self, *args, **kwds):
        pass

    def check_enter_count(self, *args, **kwds):
        pass

    def check_enter_count_at_most(self, *args, **kwds):
        pass

    def check_max_trace_length(self, *args, **kwds):
        pass

    def check_aborted_count(self, *args, **kwds):
        pass

    def check_aborted_count_at_least(self, *args, **kwds):
        pass

    def interp_operations(self, *args, **kwds):
        py.test.skip("interp_operations test skipped")

class CCompiledMixin(BaseCompiledMixin):
    slow = False

    def setup_class(cls):
        if cls.slow:
            from rpython.jit.conftest import option
            if not option.run_slow_tests:
                py.test.skip("use --slow to execute this long-running test")

    def _get_TranslationContext(self):
        t = TranslationContext()
        t.config.translation.gc = 'boehm'
        t.config.translation.list_comprehension_operations = True
        return t

    def _compile_and_run(self, t, entry_point, entry_point_graph, args):
        from rpython.translator.c.genc import CStandaloneBuilder as CBuilder
        # XXX patch exceptions
        cbuilder = CBuilder(t, entry_point, config=t.config)
        cbuilder.generate_source()
        self._check_cbuilder(cbuilder)
        exe_name = cbuilder.compile()
        debug_print('---------- Test starting ----------')
        stdout = cbuilder.cmdexec(" ".join([str(arg) for arg in args]))
        res = int(stdout)
        debug_print('---------- Test done (%d) ----------' % (res,))
        return res

    def _check_cbuilder(self, cbuilder):
        pass


text:
set -e

BRANCH=$(git symbolic-ref HEAD | awk -F/ '{print $3}')
OSX_BRANCH=${OSX_BRANCH:-${BRANCH}-osx}

if test -n "$(git status --porcelain)"; then
  echo "$(basename $0): Working copy not clean. Exiting."
  exit 1
fi

if [[ -n "$(git branch | egrep "^ *$OSX_BRANCH")" ]]; then
    git checkout $OSX_BRANCH
    if git merge $BRANCH --no-edit; then
        git checkout $BRANCH
        exit 0
    fi
    echo "WARNING: Can't merge, falling back to overwriting branch"
    git checkout $BRANCH
    git branch -D $OSX_BRANCH
fi

git checkout -b $OSX_BRANCH
sed 's/^/osx_image: xcode61 n/'  .travis.yml
sed -i '' -e 's/^language: c/language: objective-c/' .travis.yml
git add .travis.yml
git commit -m "change language to objective-c to test OS X"
git checkout $BRANCH


text:
package com.navercorp.pinpoint.common.util.logger;

import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * @author Woonduk Kang(emeroad)
 */
public class StdoutCommonLoggerTest {

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

    @Test
    public void testLogging() {
        LoggerHolder loggerHolder = new LoggerHolder("StdoutCommonLoggerTest");
        CommonLogger commonLogger = loggerHolder.getLogger();

        commonLogger.debug("info test");
//        assertMessage(getOut(), null);

        commonLogger.info("info test 1");
        assertMessage(loggerHolder.getOut(), "info test 1");

        commonLogger.info("info test 2");
        assertMessage(loggerHolder.getOut(), "info test 2");

        commonLogger.warn("warn test");
        assertMessage(loggerHolder.getError(), "warn test");

        commonLogger.warn("warn test error", new Exception("testException"));
        assertMessage(loggerHolder.getError(), "warn test");
    }

    private void assertMessage(String out, String message) {
        logger.debug("log-message {}", out);
        Assert.assertTrue(out.contains(message));

    }

    private static class LoggerHolder {
        private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        private final PrintStream out = new PrintStream(outputStream);

        private final ByteArrayOutputStream errOutputStream = new ByteArrayOutputStream();
        private final PrintStream err = new PrintStream(errOutputStream);

        private final StdoutCommonLogger logger;

        public LoggerHolder(String loggerName) {
            logger = new StdoutCommonLogger(loggerName, out, err);
        }

        public CommonLogger getLogger() {
            return logger;
        }

        private String getOut() {
            return getLogMessage(this.outputStream);
        }

        private String getError() {
            return getLogMessage(this.errOutputStream);
        }

        private String getLogMessage(ByteArrayOutputStream byteArrayOutputStream) {
            String message = byteArrayOutputStream.toString();
            byteArrayOutputStream.reset();
            return message;
        }
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Physcia farrea f. farrea

### Remarks
null


text:
#include "cvfont.h"
/*
 * Document-class: OpenCV::CvFont
 *
 * Font structure that can be passed to text rendering functions.
 * see CvMat#put_text, CvMat#put_text!
 */

__NAMESPACE_BEGIN_OPENCV
__NAMESPACE_BEGIN_CVFONT

VALUE rb_klass;

int
rb_font_option_line_type(VALUE font_option)
{
  VALUE line_type = LOOKUP_HASH(font_option, "line_type");
  if (FIXNUM_P(line_type)) {
    return FIX2INT(line_type);
  }
  else if (line_type == ID2SYM(rb_intern("aa"))) {
    return CV_AA;
  }
  return 0;
}

VALUE
rb_class()
{
  return rb_klass;
}

VALUE
rb_allocate(VALUE klass)
{
  CvFont *ptr;
  return Data_Make_Struct(klass, CvFont, 0, -1, ptr);
}

/*
 * Create font object
 * @overload new(face, font_option = nil)
 * @param face [Symbol] Font name identifier. Only a subset of Hershey fonts (http://sources.isc.org/utils/misc/hershey-font.txt) are supported now:
 *   - :simplex - normal size sans-serif font
 *   - :plain - small size sans-serif font
 *   - :duplex - normal size sans-serif font (more complex than :simplex)
 *   - :complex - normal size serif font
 *   - :triplex - normal size serif font (more complex than :complex)
 *   - :complex_small - smaller version of :complex
 *   - :script_simplex - hand-writing style font
 *   - :script_complex - more complex variant of :script_simplex
 *
 * @param font_option [Hash] should be Hash include these keys.
 * @option font_option [Number] :hscale Horizontal scale. If equal to 1.0, the characters have the original width depending on the font type. If equal to 0.5, the characters are of half the original width.
 * @option font_option [Number] :vscale Vertical scale. If equal to 1.0, the characters have the original height depending on the font type. If equal to 0.5, the characters are of half the original height.
 * @option font_option [Number] :shear Approximate tangent of the character slope relative to the vertical line. Zero value means a non-italic font, 1.0f means ~45 degree slope, etc.
 * @option font_option [Number] :thickness Thickness of the text strokes.
 * @option font_option [Number] :line_type Type of the strokes, see CvMat#Line description.
 * @option font_option [Number] :italic If value is not nil or false that means italic or oblique font.
 *
 * @example Create Font
 *   OpenCV::CvFont.new(:simplex, :hscale => 2, :vslace => 2, :italic => true)
 *   # create 2x bigger than normal, italic type font.
 *
 * @opencv_func cvInitFont
 */
VALUE
rb_initialize(int argc, VALUE *argv, VALUE self)
{
  VALUE face, font_option;
  rb_scan_args(argc, argv, "11", &face, &font_option);
  Check_Type(face, T_SYMBOL);
  face = rb_hash_lookup(rb_const_get(cCvFont::rb_class(), rb_intern("FACE")), face);
  if (NIL_P(face)) {
    rb_raise(rb_eArgError, "undefined face.");
  }
  font_option = FONT_OPTION(font_option);

  int font_face = NUM2INT(face);
  if (FO_ITALIC(font_option)) {
    font_face |= CV_FONT_ITALIC;
  }
  try {
    cvInitFont(CVFONT(self),
	       font_face,
	       FO_HSCALE(font_option),
	       FO_VSCALE(font_option),
	       FO_SHEAR(font_option),
	       FO_THICKNESS(font_option),
	       FO_LINE_TYPE(font_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return self;
}

/*
 * Returns font face
 * @overload face
 * @return [Fixnum] Font face
 */
VALUE
rb_face(VALUE self)
{
  return INT2FIX(CVFONT(self)->font_face);
}

/*
 * Returns hscale
 * @overload hscale
 * @return [Number] hscale
 */
VALUE
rb_hscale(VALUE self)
{
  return rb_float_new(CVFONT(self)->hscale);
}

/*
 * Returns vscale
 * @overload vscale
 * @return [Number] vscale
 */
VALUE
rb_vscale(VALUE self)
{
  return rb_float_new(CVFONT(self)->vscale);
}

/*
 * Returns shear
 * @overload shear
 * @return [Number] shear
 */
VALUE
rb_shear(VALUE self)
{
  return rb_float_new(CVFONT(self)->shear);
}

/*
 * Returns thickness
 * @overload thickness
 * @return [Fixnum] thickness
 */
VALUE
rb_thickness(VALUE self)
{
  return INT2FIX(CVFONT(self)->thickness);
}

/*
 * Returns line type
 * @overload line_type
 * @return [Fixnum] line_type
 */
VALUE
rb_line_type(VALUE self)
{
  return INT2FIX(CVFONT(self)->line_type);
}

/*
 * Returns italic or not
 * @overload italic
 * @return [Boolean] self is italic or not
 */
VALUE
rb_italic(VALUE self)
{
  return ((CVFONT(self)->font_face & CV_FONT_ITALIC) > 0) ? Qtrue : Qfalse;
}

void
init_ruby_class()
{
#if 0
  // For documentation using YARD
  VALUE opencv = rb_define_module("OpenCV");
#endif

  if (rb_klass)
    return;

  VALUE opencv = rb_module_opencv();
  rb_klass = rb_define_class_under(opencv, "CvFont", rb_cObject);
  rb_define_alloc_func(rb_klass, rb_allocate);
  VALUE face = rb_hash_new();
  rb_define_const(rb_klass, "FACE", face);
  rb_hash_aset(face, ID2SYM(rb_intern("simplex")), INT2FIX(CV_FONT_HERSHEY_SIMPLEX));
  rb_hash_aset(face, ID2SYM(rb_intern("plain")), INT2FIX(CV_FONT_HERSHEY_PLAIN));
  rb_hash_aset(face, ID2SYM(rb_intern("duplex")), INT2FIX(CV_FONT_HERSHEY_DUPLEX));
  rb_hash_aset(face, ID2SYM(rb_intern("triplex")), INT2FIX(CV_FONT_HERSHEY_TRIPLEX));
  rb_hash_aset(face, ID2SYM(rb_intern("complex_small")), INT2FIX(CV_FONT_HERSHEY_COMPLEX_SMALL));
  rb_hash_aset(face, ID2SYM(rb_intern("script_simplex")), INT2FIX(CV_FONT_HERSHEY_SCRIPT_SIMPLEX));
  rb_hash_aset(face, ID2SYM(rb_intern("script_complex")), INT2FIX(CV_FONT_HERSHEY_SCRIPT_COMPLEX));

  VALUE default_option = rb_hash_new();
  rb_define_const(rb_klass, "FONT_OPTION", default_option);
  rb_hash_aset(default_option, ID2SYM(rb_intern("hscale")), rb_float_new(1.0));
  rb_hash_aset(default_option, ID2SYM(rb_intern("vscale")), rb_float_new(1.0));
  rb_hash_aset(default_option, ID2SYM(rb_intern("shear")), INT2FIX(0));
  rb_hash_aset(default_option, ID2SYM(rb_intern("thickness")), INT2FIX(1));
  rb_hash_aset(default_option, ID2SYM(rb_intern("line_type")), INT2FIX(8));

  rb_define_method(rb_klass, "initialize", RUBY_METHOD_FUNC(rb_initialize), -1);
  rb_define_method(rb_klass, "face", RUBY_METHOD_FUNC(rb_face), 0);
  rb_define_method(rb_klass, "hscale", RUBY_METHOD_FUNC(rb_hscale), 0);
  rb_define_method(rb_klass, "vscale", RUBY_METHOD_FUNC(rb_vscale), 0);
  rb_define_method(rb_klass, "shear", RUBY_METHOD_FUNC(rb_shear), 0);
  rb_define_method(rb_klass, "thickness", RUBY_METHOD_FUNC(rb_thickness), 0);
  rb_define_method(rb_klass, "line_type", RUBY_METHOD_FUNC(rb_line_type), 0);
  rb_define_method(rb_klass, "italic", RUBY_METHOD_FUNC(rb_italic), 0);
}

__NAMESPACE_END_CVFONT
__NAMESPACE_END_OPENCV


text:
metro-bootstrap
===============

Simple bootstrap from Twitter with Metro style.
TalksLab production by [Guilherme Ferreira](http://twitter.com/gsferreira) (http://gsferreira.com), [Nelson Reis](http://twitter.com/nelsonreis) (http://nelsonreis.net/) and [Rui Neves](http://twitter.com/ruimlneves).

Demo
----

For a live preview of the theme, see [http://talkslab.github.com/metro-bootstrap](http://talkslab.github.com/metro-bootstrap).

Repository structure
----

In the repository you will find the following directories:

	app/
	├── fonts/
	│   └── (FontAwesome files)
	└── less/
	    └── (metro-bootstrap less files)
	dist/
	├── fonts/
	│   └── font-awesome/
	│   │   └── (FontAwesome files)
	└── css/
	    ├── metro-bootstrap.css
	    └── metro-bootstrap.min.css
	docs/
	└── (metro-bootstrap GitHub Pages)

We provide compiled CSS (`metro-bootstrap.css`) in the dist folder, as well as compiled and minified CSS (`metro-bootstrap.min.css`).

Instaling Dependencies
----

We manage dependencies using Bower.
Run `bower install` to download the required dependencies.

If don't have Grunt installed, execute the following steps from the command line:

1. Make sure you have node.js installed.
2. Install bower with `npm install -g bower`.

Compiling CSS
----

We compile metro-bootstrap using [Grunt](http://gruntjs.com/).
Run `grunt build` to compile the CSS into `/dist`.

If don't have Grunt installed, execute the following steps from the command line:

1. Make sure you have node.js installed.
2. Install `grunt-cli` globally with `npm install -g grunt-cli`.
3. Go to the `metro-bootstrap` directory, then run `npm install`. npm will look at package.json and automatically install the necessary dependencies.

License
----

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:

[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/TalksLab/metro-bootstrap/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
package org.apache.batik.svggen;

import java.awt.geom.Rectangle2D;

import org.apache.batik.test.AbstractTest;
import org.apache.batik.test.TestReport;

import org.apache.batik.dom.GenericDOMImplementation;

import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;

/**
 * Checks that no NullPointerException is thrown by default
 *
 * @author Vincent Hardy
 * @version $Id$
 */
public class DoubleString extends AbstractTest {
    public TestReport runImpl() throws Exception {
        // Get a DOMImplementation
        DOMImplementation domImpl =
            GenericDOMImplementation.getDOMImplementation();

        // Create an instance of org.w3c.dom.Document
        Document document = domImpl.createDocument(null, "svg", null);

        SVGGraphics2D g = new SVGGraphics2D(document);
        Rectangle2D r = new Rectangle2D.Float(0.5f, 0.5f, 2.33f, 2.33f);
        g.fill(r);

        return reportSuccess();
    }
}


text:
package org.apache.wicket.extensions.markup.html.repeater.data.grid;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

/**
 * A convenience implementation of {@link ICellPopulator} that adds a label that will display the
 * value of the specified property. Non-string properties will be converted to a string before
 * display.
 *

 * Example
 *
 *

 * ICellPopulator cityPopulator = new PropertyPopulator("address.city");
 *

 *
 * @param <T>
 * @author Igor Vaynberg (ivaynberg)
 */
public class PropertyPopulator<T> implements ICellPopulator<T>
{
	private static final long serialVersionUID = 1L;
	private final String property;

	/**
	 * Constructor
	 *
	 * @param property
	 *            property whose value will be displayed in the cell. uses wicket's
	 *            {@link PropertyModel} notation.
	 */
	public PropertyPopulator(final String property)
	{
		if (property == null)
		{
			throw new IllegalArgumentException("argument [property] cannot be null");
		}
		this.property = property;
	}

	/**
	 * @see org.apache.wicket.model.IDetachable#detach()
	 */
	@Override
	public void detach()
	{
	}

	/**
	 * @see org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator#populateItem(org.apache.wicket.markup.repeater.Item,
	 *      java.lang.String, org.apache.wicket.model.IModel)
	 */
	@Override
	public void populateItem(final Item<ICellPopulator<T>> cellItem, final String componentId,
		final IModel<T> rowModel)
	{
		cellItem.add(new Label(componentId, new PropertyModel<>(rowModel, property)));
	}
}


text:
/**
 * Application controller, which keeps track of our active state chain and
 * sets global scope variable accordingly.
 */
angular.module('storyboard').controller('ApplicationController',
    function ($scope, $state, $rootScope) {
        'use strict';

        /**
         * This method traverses the current active state tree to see if the
         * current state, or any of its parents, have a submenu declared.
         *
         * @param state
         */
        function hasSubmenu(state) {
            for (var stateName in state.views) {
                if (!!stateName.match(/^submenu@/)) {
                    return true;
                }
            }

            if (!!state.parent) {
                return hasSubmenu(state.parent);
            } else {
                return false;
            }
        }

        /**
         * Listen to changes in the state machine to trigger our submenu
         * scan.
         */
        $rootScope.$on('$stateChangeSuccess',
            function () {
                $scope.hasSubmenu = hasSubmenu($state.$current);
            });

        // Set a sane default.
        $scope.hasSubmenu = false;

    });


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

<title>ImportFilterManager (Jailer Subsetter API)</title>
<meta name="date" content="2022-06-07">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.jailer.importfilter

Class ImportFilterManager

java.lang.Object

net.sf.jailer.importfilter.ImportFilterManager

All Implemented Interfaces:

ImportFilterTransformer

public abstract class ImportFilterManager
extends java.lang.Object
implements ImportFilterTransformer

Manages filtering of data during import.

Author:

Ralf Wisser

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
MAPPINGTABLE_NAME_PREFIX

Constructor Summary

Constructors

Constructor and Description

ImportFilterManager(Session localSession,
                   java.io.OutputStreamWriter result,
                   java.util.Set<Table> progress,
                   Quoting targetQuoting,
                   ExecutionContext executionContext)

Constructor.

Method Summary

All Methods Instance Methods Abstract Methods Concrete Methods

Modifier and Type
Method and Description

void
createMappingTables(DBMS configuration,
                   java.io.OutputStreamWriter result)

Creates the DDL for the mapping tables.

void
dropMappingTables(java.io.OutputStreamWriter result)

Creates the DROP-statements for the mapping tables.

void
fillAndWriteMappingTables(EntityGraph entityGraph,
                         JobManager jobManager,
                         java.io.OutputStreamWriter dmlResultWriter,
                         int numberOfEntities,
                         Session targetSession,
                         DBMS targetDBMSConfiguration)

Insert the values of columns with non-derived-import-filters into the local database.

void
shutDown()

protected abstract void
sync(java.io.OutputStreamWriter result)

java.lang.String
transform(Column column,
         java.lang.String oldValue)

Transforms columns with import-Filters into SQL-expressions.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

MAPPINGTABLE_NAME_PREFIX

public static java.lang.String MAPPINGTABLE_NAME_PREFIX

Constructor Detail

ImportFilterManager

public ImportFilterManager(Session localSession,
                           java.io.OutputStreamWriter result,
                           java.util.Set<Table> progress,
                           Quoting targetQuoting,
                           ExecutionContext executionContext)
                    throws java.io.FileNotFoundException,
                           java.sql.SQLException

Constructor.

Parameters:

result - to write results into

targetQuoting -

Throws:

java.io.FileNotFoundException

java.sql.SQLException

Method Detail

createMappingTables

public void createMappingTables(DBMS configuration,
                                java.io.OutputStreamWriter result)
                         throws java.io.IOException,
                                java.sql.SQLException

Creates the DDL for the mapping tables.

Throws:

java.io.IOException

java.sql.SQLException

dropMappingTables

public void dropMappingTables(java.io.OutputStreamWriter result)
                       throws java.io.IOException,
                              java.sql.SQLException

Creates the DROP-statements for the mapping tables.

Throws:

java.io.IOException

java.sql.SQLException

sync

protected abstract void sync(java.io.OutputStreamWriter result)
                      throws java.io.IOException

Throws:

java.io.IOException

shutDown

public void shutDown()
              throws java.sql.SQLException

Throws:

java.sql.SQLException

fillAndWriteMappingTables

public void fillAndWriteMappingTables(EntityGraph entityGraph,
                                      JobManager jobManager,
                                      java.io.OutputStreamWriter dmlResultWriter,
                                      int numberOfEntities,
                                      Session targetSession,
                                      DBMS targetDBMSConfiguration)
                               throws CancellationException,
                                      java.sql.SQLException

Insert the values of columns with non-derived-import-filters into the local database.

Parameters:

entityGraph -

jobManager -

dmlResultWriter -

Throws:

CancellationException

java.sql.SQLException

transform

public java.lang.String transform(Column column,
                                  java.lang.String oldValue)

Description copied from interface: ImportFilterTransformer

Transforms columns with import-Filters into SQL-expressions.

Specified by:

transform in interface ImportFilterTransformer

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
from django.contrib import admin
from exhibitors.models import Exhibitor, Workshop, WorkshopEvents, Stand, Editorial, Book, Author, Category, Award, Volunteer, BookRegistered

# Register your models here.
admin.site.register(Exhibitor)
admin.site.register(Workshop)
admin.site.register(WorkshopEvents)
admin.site.register(Stand)
admin.site.register(Editorial)
admin.site.register(Book)
admin.site.register(Author)
admin.site.register(Category)
admin.site.register(Award)
admin.site.register(Volunteer)
admin.site.register(BookRegistered)


text:
layout: page
title: Pearl Precinct Studios Executive Retreat
date: 2016-05-24
author: Ronald Daniels
tags: weekly links, java
status: published
summary: Phasellus luctus vitae enim et hendrerit.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 04/13/2019
  endDate: 04/17/2019
  ctyhocn: DALWHHX
  groupCode: PPSER
published: true
---
Duis quis metus mi. Phasellus pellentesque ex eget sagittis auctor. Proin venenatis lacinia lorem vitae rutrum. Nullam ultrices varius velit, ut sollicitudin erat suscipit id. Quisque convallis sollicitudin volutpat. Suspendisse viverra, dui a vulputate dapibus, velit erat sollicitudin metus, at eleifend enim risus quis tellus. Praesent nisl diam, sodales quis mauris eu, accumsan vestibulum nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam eget diam vulputate, tincidunt quam et, pulvinar velit.
Praesent egestas dolor et ipsum rutrum, non molestie augue euismod. Quisque nibh odio, condimentum quis laoreet sit amet, eleifend id augue. Donec volutpat lorem elit, commodo molestie elit vulputate a. Sed orci mi, pulvinar facilisis mauris venenatis, consectetur molestie felis. Nam quis elementum neque. Sed non magna non dolor ultricies rhoncus vitae semper tortor. Morbi congue non felis vitae blandit. Donec purus sapien, congue in commodo non, malesuada ac sem. Curabitur vitae risus placerat, porta urna sed, placerat orci.

* Maecenas eleifend ex vel dui feugiat, eget porta erat bibendum
* Proin consequat purus sed efficitur tempus
* Nam ullamcorper nunc sed posuere commodo
* Duis finibus magna viverra nulla scelerisque ullamcorper.

Pellentesque ultricies vehicula ante. Nullam id neque ante. Cras consequat non nunc sit amet rutrum. Phasellus non porttitor eros. Pellentesque quam ex, posuere vel semper ac, malesuada sed diam. Aliquam rhoncus ipsum non nulla maximus interdum. Duis erat dui, aliquet id ligula ac, consectetur iaculis elit. Nulla dui dolor, convallis sed auctor quis, congue at ligula. Integer quis erat vel elit feugiat hendrerit. Cras lobortis cursus nunc, at ullamcorper nisl. Nullam gravida lobortis porttitor. Proin pharetra risus a orci facilisis, in feugiat nulla consequat. Cras quis mi erat.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Indentation;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
    internal sealed class CSharpSyntaxFormattingService : CSharpSyntaxFormatting, ISyntaxFormattingService
    {
        private readonly HostLanguageServices _services;

        [ExportLanguageServiceFactory(typeof(ISyntaxFormattingService), LanguageNames.CSharp), Shared]
        internal sealed class Factory : ILanguageServiceFactory
        {
            [ImportingConstructor]
            [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
            public Factory()
            {
            }

            public ILanguageService CreateLanguageService(HostLanguageServices languageServices)
                => new CSharpSyntaxFormattingService(languageServices);
        }

        private CSharpSyntaxFormattingService(HostLanguageServices languageServices)
            => _services = languageServices;

        public bool ShouldFormatOnTypedCharacter(
            ParsedDocument documentSyntax,
            char typedChar,
            int caretPosition,
            CancellationToken cancellationToken)
        {
            // first, find the token user just typed.
            var token = documentSyntax.Root.FindToken(Math.Max(0, caretPosition - 1), findInsideTrivia: true);
            if (token.IsMissing ||
                !ValidSingleOrMultiCharactersTokenKind(typedChar, token.Kind()) ||
                token.IsKind(SyntaxKind.EndOfFileToken, SyntaxKind.None) ||
                documentSyntax.SyntaxTree.IsInNonUserCode(caretPosition, cancellationToken))
            {
                return false;
            }

            // If the token is a )  we only want to format if it's the close paren
            // of a using statement.  That way if we have nested usings, the inner
            // using will align with the outer one when the user types the close paren.
            if (token.IsKind(SyntaxKind.CloseParenToken) && !token.Parent.IsKind(SyntaxKind.UsingStatement))
            {
                return false;
            }

            // If the token is a :  we only want to format if it's a labeled statement
            // or case.  When the colon is typed we'll want ot immediately have those
            // statements snap to their appropriate indentation level.
            if (token.IsKind(SyntaxKind.ColonToken) && !(token.Parent.IsKind(SyntaxKind.LabeledStatement) || token.Parent is SwitchLabelSyntax))
            {
                return false;
            }

            // Only format an { if it is the first token on a line.  We don't want to
            // mess with it if it's inside a line.
            if (token.IsKind(SyntaxKind.OpenBraceToken))
            {
                if (!token.IsFirstTokenOnLine(documentSyntax.Text))
                {
                    return false;
                }
            }

            return true;
        }

        public ImmutableArray<TextChange> GetFormattingChangesOnTypedCharacter(
            ParsedDocument document,
            int caretPosition,
            IndentationOptions indentationOptions,
            CancellationToken cancellationToken)
        {
            var root = document.Root;
            var token = root.FindToken(Math.Max(0, caretPosition - 1), findInsideTrivia: true);
            var formattingRules = GetFormattingRules(document, caretPosition, token);

            // Do not attempt to format on open/close brace if autoformat on close brace feature is
            // off, instead just smart indent.
            //
            // We want this behavior because it's totally reasonable for a user to want to not have
            // on automatic formatting because they feel it is too aggressive.  However, by default,
            // if you have smart-indentation on and are just hitting enter, you'll common have the
            // caret placed one indent higher than your current construct.  For example, if you have:
            //
            //      if (true)
            //          $ <-- smart indent will have placed the caret here here.
            //
            // This is acceptable given that the user may want to just write a simple statement there.
            // However, if they start writing `{`, then things should snap over to be:
            //
            //      if (true)
            //      {
            //
            // Importantly, this is just an indentation change, no actual 'formatting' is done.  We do
            // the same with close brace.  If you have:
            //
            //      if (...)
            //      {
            //          bad . ly ( for (mmated+code) )  ;
            //          $ <-- smart indent will have placed the care here.
            //
            // If the user hits `}` then we will properly smart indent the `}` to match the `{`.
            // However, we won't touch any of the other code in that block, unlike if we were
            // formatting.
            var onlySmartIndent =
                (token.IsKind(SyntaxKind.CloseBraceToken) && OnlySmartIndentCloseBrace(indentationOptions.AutoFormattingOptions)) ||
                (token.IsKind(SyntaxKind.OpenBraceToken) && OnlySmartIndentOpenBrace(indentationOptions.AutoFormattingOptions));

            if (onlySmartIndent)
            {
                // if we're only doing smart indent, then ignore all edits to this token that occur before
                // the span of the token. They're irrelevant and may screw up other code the user doesn't
                // want touched.
                var tokenEdits = FormatToken(document, indentationOptions, token, formattingRules, cancellationToken);
                return tokenEdits.Where(t => t.Span.Start >= token.FullSpan.Start).ToImmutableArray();
            }

            // if formatting range fails, do format token one at least
            var changes = FormatRange(document, indentationOptions, token, formattingRules, cancellationToken);
            if (changes.Length > 0)
            {
                return changes;
            }

            return FormatToken(document, indentationOptions, token, formattingRules, cancellationToken).ToImmutableArray();
        }

        private static bool OnlySmartIndentCloseBrace(in AutoFormattingOptions options)
        {
            // User does not want auto-formatting (either in general, or for close braces in
            // specific).  So we only smart indent close braces when typed.
            return !options.FormatOnCloseBrace || !options.FormatOnTyping;
        }

        private static bool OnlySmartIndentOpenBrace(in AutoFormattingOptions options)
        {
            // User does not want auto-formatting .  So we only smart indent open braces when typed.
            // Note: there is no specific option for controlling formatting on open brace.  So we
            // don't have the symmetry with OnlySmartIndentCloseBrace.
            return !options.FormatOnTyping;
        }

        private static IList<TextChange> FormatToken(
            ParsedDocument document, IndentationOptions options, SyntaxToken token, ImmutableArray<AbstractFormattingRule> formattingRules, CancellationToken cancellationToken)
        {
            var formatter = new CSharpSmartTokenFormatter(options, formattingRules, (CompilationUnitSyntax)document.Root, document.Text);
            return formatter.FormatToken(token, cancellationToken);
        }

        private static ImmutableArray<TextChange> FormatRange(
            ParsedDocument document,
            IndentationOptions options,
            SyntaxToken endToken,
            ImmutableArray<AbstractFormattingRule> formattingRules,
            CancellationToken cancellationToken)
        {
            if (!IsEndToken(endToken))
            {
                return ImmutableArray<TextChange>.Empty;
            }

            var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken);
            if (tokenRange == null || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
            {
                return ImmutableArray<TextChange>.Empty;
            }

            if (IsInvalidTokenKind(tokenRange.Value.Item1) || IsInvalidTokenKind(tokenRange.Value.Item2))
            {
                return ImmutableArray<TextChange>.Empty;
            }

            var formatter = new CSharpSmartTokenFormatter(options, formattingRules, (CompilationUnitSyntax)document.Root, document.Text);

            var changes = formatter.FormatRange(tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken);
            return changes.ToImmutableArray();
        }

        private static IEnumerable<AbstractFormattingRule> GetTypingRules(SyntaxToken tokenBeforeCaret)
        {
            // Typing introduces several challenges around formatting.
            // Historically we've shipped several triggers that cause formatting to happen directly while typing.
            // These include formatting of blocks when '}' is typed, formatting of statements when a ';' is typed, formatting of ```case```s when ':' typed, and many other cases.
            // However, formatting during typing can potentially cause problems.  This is because the surrounding code may not be complete,
            // or may otherwise have syntax errors, and thus edits could have unintended consequences.
            //
            // Because of this, we introduce an extra rule into the set of formatting rules whose purpose is to actually make formatting *more*
            // conservative and *less* willing willing to make edits to the tree.
            // The primary effect this rule has is to assume that more code is on a single line (and thus should stay that way)
            // despite what the tree actually looks like.
            //
            // It's ok that this is only during formatting that is caused by an edit because that formatting happens
            // implicitly and thus has to be more careful, whereas an explicit format-document call only happens on-demand
            // and can be more aggressive about what it's doing.
            //
            //
            // For example, say you have the following code.
            //
            // ```c#
            // class C
            // {
            //   int P { get {    return
            // }
            // ```
            //
            // Hitting ';' after 'return' should ideally only affect the 'return statement' and change it to:
            //
            // ```c#
            // class C
            // {
            //   int P { get { return;
            // }
            // ```
            //
            // During a normal format-document call, this is not what would happen.
            // Specifically, because the parser will consume the '}' into the accessor,
            // it will think the accessor spans multiple lines, and thus should not stay on a single line.  This will produce:
            //
            // ```c#
            // class C
            // {
            //   int P
            //   {
            //     get
            //     {
            //       return;
            //     }
            // ```
            //
            // Because it's ok for this to format in that fashion if format-document is invoked,
            // but should not happen during typing, we insert a specialized rule *only* during typing to try to control this.
            // During normal formatting we add 'keep on single line' suppression rules for blocks we find that are on a single line.
            // But that won't work since this span is not on a single line:
            //
            // ```c#
            // class C
            // {
            //   int P { get [|{    return;
            // }|]
            // ```
            //
            // So, during typing, if we see any parent block is incomplete, we'll assume that
            // all our parent blocks are incomplete and we will place the suppression span like so:
            //
            // ```c#
            // class C
            // {
            //   int P { get [|{     return;|]
            // }
            // ```
            //
            // This will have the desired effect of keeping these tokens on the same line, but only during typing scenarios.
            if (tokenBeforeCaret.Kind() is SyntaxKind.CloseBraceToken or
                SyntaxKind.EndOfFileToken)
            {
                return SpecializedCollections.EmptyEnumerable<AbstractFormattingRule>();
            }

            return SpecializedCollections.SingletonEnumerable(TypingFormattingRule.Instance);
        }

        private static bool IsEndToken(SyntaxToken endToken)
        {
            if (endToken.IsKind(SyntaxKind.OpenBraceToken))
            {
                return false;
            }

            return true;
        }

        // We'll autoformat on n, t, e, only if they are the last character of the below
        // keywords.
        private static bool ValidSingleOrMultiCharactersTokenKind(char typedChar, SyntaxKind kind)
            => typedChar switch
            {
                'n' => kind is SyntaxKind.RegionKeyword or SyntaxKind.EndRegionKeyword,
                't' => kind == SyntaxKind.SelectKeyword,
                'e' => kind == SyntaxKind.WhereKeyword,
                _ => true,
            };

        private static bool IsInvalidTokenKind(SyntaxToken token)
        {
            // invalid token to be formatted
            return token.IsKind(SyntaxKind.None) ||
                   token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
                   token.IsKind(SyntaxKind.EndOfFileToken);
        }

        private ImmutableArray<AbstractFormattingRule> GetFormattingRules(ParsedDocument document, int position, SyntaxToken tokenBeforeCaret)
        {
            var formattingRuleFactory = _services.WorkspaceServices.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
            return ImmutableArray.Create(formattingRuleFactory.CreateRule(document, position))
                                 .AddRange(GetTypingRules(tokenBeforeCaret))
                                 .AddRange(Formatter.GetDefaultFormattingRules(_services));
        }

        public ImmutableArray<TextChange> GetFormattingChangesOnPaste(ParsedDocument document, TextSpan textSpan, SyntaxFormattingOptions options, CancellationToken cancellationToken)
        {
            var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(document.Root, textSpan);
            var service = _services.GetRequiredService<ISyntaxFormattingService>();

            var rules = new List<AbstractFormattingRule>() { new PasteFormattingRule() };
            rules.AddRange(service.GetDefaultFormattingRules());

            var result = service.GetFormattingResult(document.Root, SpecializedCollections.SingletonEnumerable(formattingSpan), options, rules, cancellationToken);
            return result.GetTextChanges(cancellationToken).ToImmutableArray();
        }

        internal sealed class PasteFormattingRule : AbstractFormattingRule
        {
            public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
            {
                if (currentToken.Parent != null)
                {
                    var currentTokenParentParent = currentToken.Parent.Parent;
                    if (currentToken.Kind() == SyntaxKind.OpenBraceToken && currentTokenParentParent != null &&
                        (currentTokenParentParent.Kind() == SyntaxKind.SimpleLambdaExpression ||
                         currentTokenParentParent.Kind() == SyntaxKind.ParenthesizedLambdaExpression ||
                         currentTokenParentParent.Kind() == SyntaxKind.AnonymousMethodExpression))
                    {
                        return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
                    }
                }

                return nextOperation.Invoke(in previousToken, in currentToken);
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OccurencesOfLetters
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = Console.ReadLine();
            var count = new int[26];
            foreach (var symbol in text)
            {
                if (char.IsLetter(symbol))
                {
                    count[symbol - 'a']++;
                }
            }
            for (int i = 0; i < count.Length; i++)
            {
                if (count[i] > 0)
                {
                    Console.WriteLine($"{((char)(i+'a'))} - {count[i]}");
                }
            }

        }
    }
}


text:
@interface UIViewLayoutVC : UIViewController

@end


text:
<?php

$t_exporter = $this->getVar('t_exporter');
$va_exporters = ca_data_exporters::getExporters($t_exporter->get('table_num'));

print $vs_control_box = caFormControlBox(
		CaFormSubmitButton($this->request, __CA_NAV_BUTTON_SAVE__, _t("Execute data export"), 'caBatchMetadataExportForm').' '.
		caNavButton($this->request, __CA_NAV_BUTTON_CANCEL__, _t("Cancel"), 'manage', 'MetadataExport', 'Index', array()),
		'',
		''
	);
?>

<?php print _t("You are about to export a set of %1 using the %2 exporter",$va_exporters[$t_exporter->getPrimaryKey()]['exporter_type'],$t_exporter->getLabelForDisplay()); ?>

<?php
		print caFormTag($this->request, 'ExportData/'.$this->request->getActionExtra(), 'caBatchMetadataExportForm', null, 'POST', 'multipart/form-data', '_top', array('disableUnsavedChangesWarning' => true, 'noTimestamp' => true));

		print caHTMLHiddenInput('exporter_id', array('value' => $t_exporter->getPrimaryKey()));

		print "
"._t('Search expression')."
\n".caHTMLTextInput('search', array('id' => 'caExportSearchExpr'), array('width' => '300px'))."
\n";
?>
		</form>

<?php
	print $vs_control_box;

?>


text:
Crawling Vinmonopolet-data and indexing it to a `norch` search index, using [`vinmonopolet`](https://github.com/rexxars/vinmonopolet) and [`search-index-indexer`](https://github.com/eklem/search-index-indexer) library.

Has these features:
* Removing unwanted key/value pars by it's keys
* Changing values to arrays for defined keys. Preparing for being used as filters.
* Copying value of defined key to id-value. Makes it easy to update index.
* Creating image URL based on id/code.
* Pushing filter.category to product.productType when different for better filter functionality.


text:
import numpy as np
import matplotlib.pyplot as plt

# create evenly sampled times from 0 to 5 sec at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()


text:
void initializeSharedResources() {
    std::cout << "Shared resources initialized." << std::endl;
}

std::atomic<bool> initialized{false};
std::mutex mutex{};

void function() {
    if (!initialized) {
        std::unique_lock<std::mutex> lock{mutex};
        if (!initialized) {
            initializeSharedResources();
            initialized = true;
        }
    }
    std::cout << "OK" << std::endl;
}

int main() {
    std::vector<std::thread> threads{};

    for (int i{0}; i < 5; ++i)
        threads.push_back(std::thread{function});

    for (auto& thread : threads)
        thread.join();

    return 0;
}


text:
import re
import os
import pdb
import fileinput
import unicodecsv
import pprint

# Configure variables
county = 'Lane'
outfile = '20080520__or__primary__lane__precinct.csv'

headers = ['county', 'precinct', 'office', 'district', 'party', 'candidate', 'votes']
party_prefixes = ['DEM', 'REP']

office_lookup = {
	'United States President': 'President',
	'United States Senator': 'U.S. Senate',
	'Representative in Congress': 'U.S. House',
	'Secretary of State': 'Secretary of State',
	'State Treasurer': 'State Treasurer',
	'Attorney General': 'Attorney General',
	'State Representative': 'State House',
	'State Senator': 'State Senate'
}

candidate_lookup = {
	'WRITE-IN': 'Write-in',
	'OVER VOTES': 'Over Votes',
	'UNDER VOTES': 'Under Votes'
}

def main():
	currentCanvass = ""
	allCanvasses = []
	divisionRE = re.compile("   \w")

	# read from stdin
	for line in fileinput.input():
		if divisionRE.match(line):
			previousCanvass = OfficeCanvass(currentCanvass)

			if previousCanvass.party in party_prefixes:
				allCanvasses.append(previousCanvass)

			currentCanvass = ""

		currentCanvass += line

	# printCanvasses(allCanvasses)
	writeCSV(allCanvasses)

def writeCSV(allCanvasses):
	with open(outfile, 'wb') as csvfile:
		w = unicodecsv.writer(csvfile, encoding='utf-8')
		w.writerow(headers)

		for canvass in allCanvasses:
			for precinct, results in canvass.results.iteritems():
				for index, result in enumerate(results):
					normalisedOffice = office_lookup[canvass.office] # Normalise the office
					candidate = canvass.candidates[index]
					normalisedCandidate = candidate_lookup.get(candidate, candidate) # Normalise the candidate

					row = [county, precinct, normalisedOffice, canvass.district,
							canvass.party, normalisedCandidate, result]

					print row
					w.writerow(row)

def printCanvasses(allCanvasses):
	pp = pprint.PrettyPrinter(indent=4)

	for canvass in allCanvasses:
		print canvass.office
		print canvass.district
		print canvass.candidates
		pp.pprint(canvass.results)
		print "====="

class OfficeCanvass(object):
	def __init__(self, text):
		self.lines = text.split('\r\n') # File uses Windows line endings
		self.header = []
		self.table = []
		self.results = {}
		self.district = ""
		self.party = ""
		self.candidates = []

		self.hyphenRE = re.compile("(-----)")
		self.endOfTableRE = re.compile("OFFICIAL CANVASS|TOTALS")
		self.districtRE = re.compile(" (\d\d?)\w\w District")

		self.parseTitle()
		self.parseOfficePartyDistrict()
		self.populateHeaderAndTable()
		self.parseHeader()
		self.parseResults()

	def __repr__(self):
		return self.title+self.party+self.office

	def parseTitle(self):
		self.title = self.lines[0].strip()

	def parseOfficePartyDistrict(self):
		prefix = self.title[0:3]
		self.office = self.title

		if prefix in party_prefixes:
			self.party = prefix
			self.office = self.title[4:] # Remove party from office

		m = self.districtRE.search(self.office)
		if m:
			self.district = m.group(1)
			self.office = self.office.replace(m.group(0), "") # Remove district from office

	def populateHeaderAndTable(self):
		inTable = False

		for line in self.lines[1:]:
			if not inTable:
				self.header.append(line)
				if self.hyphenRE.search(line):
					inTable = True
			else:
				if self.endOfTableRE.search(line):
					break

				self.table.append(line)

	def parseHeader(self):
		# 1. Remove the diagonal printing
		i = 0
		headerLines = self.header

		# pdb.set_trace()

		for index, line in enumerate(headerLines):
			if index > 0 and not line.endswith("-----"): # Don't increment first and last lines
				i += 1

			headerLines[index] = line[i:]

		# 2. Find out where the columns are
		cols = []
		longestString = len(headerLines[-1])

		for m in self.hyphenRE.finditer(headerLines[-1]):
			for i, g in enumerate(m.groups()):
				cols.append(m.span(i))

		# 3. Make sure all strings are the same length
		for i, line in enumerate(headerLines):
			headerLines[i] = headerLines[i].ljust(longestString)

		# 4. Create 2D array of characters to easily zip()
		bitmap = []
		for line in headerLines[:-1]: #skip line of hyphens
			bitmap.append(list(line))

		# 5. Read vertical columns of characters as the names, removing unused spaces
		names = []
		for i, col in enumerate(cols):
			name = ""
			for colNum in range(col[0], col[1]):
				name += "".join(zip(*bitmap)[colNum]) + " "
			names.append(" ".join(name.split()))

		self.candidates = names

	def parseResults(self):
		for line in self.table:
			columns = line.split()
			candidateCount = len(self.candidates)

			votes = columns[-candidateCount:]
			del(columns[-candidateCount:])

			precinct = " ".join(columns)
			self.results[precinct] = votes

# Default function is main()
if __name__ == '__main__':
	main()


text:
@interface RecipeDetailViewController ()

@end

@implementation RecipeDetailViewController{

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

	self.title = self.recipe.name;
    self.prepTimeLabel.text = self.recipe.prepTime;
    self.recipeImageView.image = [UIImage imageNamed:self.recipe.image];

    NSMutableString *ingredientsText = [NSMutableString string];
    for (NSString* ingredient in self.recipe.ingredients) {
        [ingredientsText appendFormat:@"%@\n", ingredient];
    }
    self.ingredientsTextView.text = ingredientsText;

    self.bannerView = [[ADBannerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, 320, 50)];
    [self.bannerView setDelegate:self];
    [UIView beginAnimations:@"animateAdBannerOn" context:NULL];

    // Assumes the banner view is just off the bottom of the screen.
    self.bannerView.frame = CGRectOffset(self.bannerView.frame, 0, -self.bannerView.frame.size.height);

    [UIView commitAnimations];

    [self.view addSubview:self.bannerView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
    NSLog(@"Failed to retrieve ad");

    [UIView beginAnimations:@"animateAdBannerOff" context:NULL];

    // Assumes the banner view is placed at the bottom of the screen.
    self.bannerView.frame = CGRectOffset(self.bannerView.frame, 0, self.bannerView.frame.size.height);

    [UIView commitAnimations];

    [self.bannerView removeFromSuperview];

    _admobBannerView = [[GADBannerView alloc]
                        initWithFrame:CGRectMake(0.0,0.0,
                                                 GAD_SIZE_320x50.width,
                                                 GAD_SIZE_320x50.height)];

    // 3
    self.admobBannerView.adUnitID = @"ca-app-pub-5104806357489598/9820115066";  //to be change
    self.admobBannerView.rootViewController = self;
    self.admobBannerView.delegate = self;
    [UIView beginAnimations:@"animateAdBannerOn" context:NULL];

    // Assumes the banner view is just off the bottom of the screen.
    self.admobBannerView.frame = CGRectOffset(self.admobBannerView.frame, 0, -self.admobBannerView.frame.size.height);

    [UIView commitAnimations];
    // 4
    [self.view addSubview:self.admobBannerView];
    [self.admobBannerView loadRequest:[GADRequest request]];
}

- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error {
    [self.admobBannerView removeFromSuperview];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
#ifndef __WEBMDSHOW_COMMON_SCRATCHBUF_HPP__
#define __WEBMDSHOW_COMMON_SCRATCHBUF_HPP__

#pragma once

#include <vector>

#include "chromium/base/basictypes.h"

namespace WebmUtil
{

class ScratchBuf
{
public:
    ScratchBuf();
    virtual ~ScratchBuf();

    int32 Fill(uint8 val, int32 length);

    int32 Erase(uint32 offset, int32 length);
    int32 Erase(uint64 offset, int32 length);

    int32 Rewrite(uint32 offset, const uint8* ptr_data, int32 length);
    int32 Rewrite(uint64 offset, const uint8* ptr_data, int32 length);

    void Write(const uint8* ptr_data, int32 length);
    void Write4Float(float val);
    void Write1String(const char* ptr_str);
    void Write1UTF8(const wchar_t* ptr_str);

    virtual void Write8UInt(uint64 val);
    virtual void Write4UInt(uint32 val);
    virtual void Write2UInt(uint16 val);
    virtual void Write1UInt(uint8 val);
    virtual void WriteUInt(uint64 val, int32 size);

    const uint8* GetBufferPtr() const;
    uint64 GetBufferLength() const;

    void Reset();

protected:
    std::vector<uint8> buf_;

private:
    DISALLOW_COPY_AND_ASSIGN(ScratchBuf);
};

class EbmlScratchBuf : public ScratchBuf
{
public:
    EbmlScratchBuf();
    virtual ~EbmlScratchBuf();

    void Serialize8UInt(uint64 val);
    void Serialize4Float(float val);
    void Serialize4UInt(uint32 val);
    void Serialize2UInt(uint16 val);
    void Serialize1UInt(uint8 val);

    int32 RewriteID(uint32 offset, uint32 id, int32 length);
    int32 RewriteID(uint64 offset, uint32 id, int32 length);
    int32 RewriteUInt(uint32 offset, uint64 val, int32 length);
    int32 RewriteUInt(uint64 offset, uint64 val, int32 length);

    virtual void Write8UInt(uint64 val);
    virtual void Write4UInt(uint32 val);
    virtual void Write2UInt(uint16 val);
    virtual void Write1UInt(uint8 val);
    virtual void WriteUInt(uint64 val, int32 size);

    void WriteID4(uint32 id);
    void WriteID3(uint32 id);
    void WriteID2(uint16 id);
    void WriteID1(uint8 id);
private:
    DISALLOW_COPY_AND_ASSIGN(EbmlScratchBuf);
};

} // WebmUtil namespace

#endif // __WEBMDSHOW_COMMON_SCRATCHBUF_HPP__


text:
from openprovider.models import Reseller, Address

from . import betamaxed

@betamaxed
def test_reseller_retrieve(api):
    r = api.reseller.retrieve()
    assert isinstance(r, Reseller)
    assert isinstance(r.address, Address)


text:
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  set(CMAKE_INSTALL_PREFIX "/usr/local")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  if(BUILD_TYPE)
    string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  else()
    set(CMAKE_INSTALL_CONFIG_NAME "")
  endif()
  message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()

# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
  if(COMPONENT)
    message(STATUS "Install component: \"${COMPONENT}\"")
    set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  else()
    set(CMAKE_INSTALL_COMPONENT)
  endif()
endif()

if(NOT CMAKE_INSTALL_LOCAL_ONLY)
  # Include the install script for each subdirectory.
  include("/Users/raymondtay/GPUMLib/src/examples/ATS/cmake_install.cmake")
  include("/Users/raymondtay/GPUMLib/src/examples/BP/cmake_install.cmake")
  include("/Users/raymondtay/GPUMLib/src/examples/MBP/cmake_install.cmake")
  include("/Users/raymondtay/GPUMLib/src/examples/RAN/cmake_install.cmake")
  include("/Users/raymondtay/GPUMLib/src/examples/RBF/cmake_install.cmake")
  include("/Users/raymondtay/GPUMLib/src/examples/DBN/cmake_install.cmake")
  include("/Users/raymondtay/GPUMLib/src/examples/reduction/cmake_install.cmake")
  include("/Users/raymondtay/GPUMLib/src/examples/SVM/cmake_install.cmake")

endif()


text:
package com.monopoly.Packages;

/**
 * Created by matthew on 2016/11/5.
 */
abstract public class PackageFactory {

    abstract public EventsPackage getEventsPackage();
    abstract public LandsPackage getLandsPackage();
}


text:
<?php

namespace WPWooCommerceDDelivery;
class DDeliveryShipping extends \WC_Shipping_Method {
	const DELIVERY_ID = 'ddelivery-id';
	const API_KEY_FIELD = 'apikey';
	const IS_DEBUG_FIELD = 'is_debug';
	const IS_DEBUG_DEFAULT_NO = 'no';

	/**
	 * Constructor for your shipping class
	 *
	 * @access public
	 * @return void
	 */
	public function __construct() {
		$this->id                 = self::DELIVERY_ID;
		$this->method_title       = __( 'DDelivery' );
		$this->method_description = __( 'Доставка через DDelivery' );

		$this->enabled = "yes";
		$this->title   = "DDelivery";
		parent::__construct();
		$this->init();
	}

	public static function getOptionsGroup() {
		return 'woocommerce_' . DDeliveryShipping::DELIVERY_ID . '_settings';
	}

	/**
	 *
	 */
	public function init() {
		$this->init_form_fields();
		$this->init_settings();

		add_action( 'woocommerce_update_options_shipping_' . $this->id,
		            array( $this, 'process_admin_options' ) );
	}

	/**
	 * админская часть - поля настройки
	 */
	public function init_form_fields() {
		$this->form_fields = array(
			self::API_KEY_FIELD  => array(
				'title'       => __( 'Апи ключ' ),
				'type'        => 'text',
				'description' => __( 'Ключ можно найти в личном кабинете DDelivery' ),
				'default'     => '',
				'desc_tip'    => true,
			),
			self::IS_DEBUG_FIELD => array(
				'title'       => __( 'Дебаг режим' ),
				'type'        => 'checkbox',
				'description' => __( 'В консоли чекаута показываются отладочные сообщения' ),
				'default'     => 'no',
				'desc_tip'    => true,
				'label'       => __( 'Включить дебаг' )
			),
		);
	}

	public static function checkoutFields( $fields ) {
		return $fields;
	}

	public static function shippingFields( $fields ) {
		return $fields;
	}

	/**
	 * регистрация доставки в woocommerce
	 *
	 * @param $methods
	 *
	 * @return mixed
	 */
	public static function addShippingToFrontend( $methods ) {
		$methods[ self::DELIVERY_ID ] = __CLASS__;

		return $methods;
	}

	/**
	 * то что выводится на страничке в настройках в админке
	 */
	public function admin_options() {
		if ( ! $this->instance_id ) {
			echo '
' . esc_html( $this->get_method_title() ) . '
';
		}
		if ( ! empty( $this->settings[ self::API_KEY_FIELD ] ) ) {

			$container = Helper::createContainer();
			try {
				$ddeliveryEndpoint = get_bloginfo( 'url' ) . Router::buildRestUrl( 'ddeliveryEndpoint' ) .
				                     "?action=admin";
				$token             = $container->getBusiness()
				                               ->renderAdmin( $ddeliveryEndpoint );
				if ( empty( $token ) ) {
					throw new \Exception( 'Пустой токен получен от DDelivery. Проверьте корректность ключа.' );
				}
				echo "
Ключ привязан! Перейти в настройки
";
			} catch ( \Exception $exception ) {
				echo 'Ошибка: ' . $exception->getMessage();
			}
		}
		echo wp_kses_post( wpautop( $this->get_method_description() ) );
		echo $this->get_admin_options_html();
	}

	/**
	 * типичный рассчет цены. читается при пересчете с аяксом. надо хранить в сессии цену рассчета
	 *
	 * @see Controller::actionSavePrice()
	 *
	 * @param array $package
	 */
	public function calculate_shipping( $package = array() ) {
		$price = WC()->session->get( Core::SESSION_FIELD_PRICE,
		                             false );
		if ( false === $price ) {
			$price = 400;
		}
		$this->add_rate( array(
			                 'id'       => $this->id,
			                 'label'    => $this->title,
			                 'cost'     => $price,
			                 'calc_tax' => 'per_order'
		                 ) );
	}
}


text:
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { TranslateModule } from '@ngx-translate/core';
import { DirectivesModule, ModalsModule, ModalsService } from '@rucken/core';
import { ModalModule } from 'ngx-bootstrap/modal';
import { MessageModalComponent } from './message-modal.component';
import { WebModalsService } from './modals.service';

@NgModule({
  imports: [
    CommonModule,
    ModalsModule,
    ModalModule.forRoot(),
    DirectivesModule,
    TranslateModule.forChild(),
    FontAwesomeModule
  ],
  providers: [WebModalsService, { provide: ModalsService, useClass: WebModalsService }],
  declarations: [MessageModalComponent],
  entryComponents: [MessageModalComponent],
  exports: [ModalModule, ModalsModule, MessageModalComponent, DirectivesModule]
})
export class WebModalsModule {}