text:
package org.scalajs.openui5.sap.m

import org.scalajs.openui5.sap.ui.core._
import org.scalajs.openui5.util.{Settings, SettingsMap, noSettings}

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSName, ScalaJSDefined}

@ScalaJSDefined
trait TextSettings extends ControlSettings
object TextSettings extends TextSettingsBuilder(noSettings)

class TextSettingsBuilder(val dict: SettingsMap)
  extends Settings[TextSettings, TextSettingsBuilder](new TextSettingsBuilder(_))
    with TextSetters[TextSettings, TextSettingsBuilder]

trait TextSetters[T <: js.Object, B <: Settings[T,_]]
  extends ControlSetters[T, B] {

  def text(v: String) = setting("text", v)
  def textDirection(v: TextDirection) = setting("textDirection", v)
  def wrapping(v: Boolean) = setting("wrapping", v)
  def textAlign(v: TextAlign) = setting("textAlign", v)
  def width(v: CSSSize) = setting("width", v)
  def maxLines(v: Int) = setting("maxLines", v)
}

@JSName("sap.m.Text")
@js.native
class Text(id: js.UndefOr[String] = js.native,
           settings: js.UndefOr[TextSettings])
  extends Control {

  def this(id: String) = this(id, js.undefined)
  def this(settings: TextSettings) = this(js.undefined, settings)

  def setEnabled(enabled: Boolean): this.type = js.native
}


text:
package sk.builders.core;

import java.io.IOException;

import javax.swing.JButton;

import sk.builders.core.annotations.Bean;
import sk.builders.core.annotations.Config;
import sk.builders.game.GameLogic;
import sk.builders.game.bl.impl.GameApiImpl;
import sk.builders.game.bo.Map;
import sk.builders.game.bo.Person;
import sk.builders.game.bo.Position;
import sk.builders.game.interfaces.GameApi;
import sk.builders.gui.Displayer;
import sk.builders.gui.MainScreen;
import sk.builders.gui.bo.ImageBuffer;
import sk.builders.gui.listeners.ActionListeners;
import sk.builders.gui.listeners.ComboBoxListener;
import sk.builders.gui.listeners.MouseMotionEvent;
import sk.builders.gui.listeners.MousePositionRightPressed;
import sk.builders.mas.core.MasCore;

@Config
public class ObjectConfig {

    @Bean
    public Map map() throws IOException {
        return new Map();
    }

    @Bean
    public MousePositionRightPressed mousePositionRightPressed() {
        return new MousePositionRightPressed();
    }

    @Bean
    public GameApi gameApi() {
        return new GameApiImpl();
    }

    @Bean
    public MainScreen mainScreen() {
        return new MainScreen();
    }

    @Bean
    public MasCore masCore() {
        return new MasCore();
    }

    @Bean
    public Displayer displayMap() {
        return new Displayer();
    }

    @Bean
    public MouseMotionEvent mouseMotionEvent() {
        return new MouseMotionEvent();
    }

    @Bean
    public ActionListeners actionListeners() {
        return new ActionListeners();
    }

    @Bean
    public ImageBuffer imageBuffer() throws IOException {
        return new ImageBuffer();
    }

    @Bean
    public ComboBoxListener comboBoxListener() {
        return new ComboBoxListener();
    }

    @Bean
    public JButton save() {
        return new JButton("uloz");
    }

    @Bean
    public JButton load() {
        return new JButton("nacitaj");
    }

    @Bean
    public GameLogic gameLogic() {
        return new GameLogic();
    }
}

redpajama_set_name: RedPajamaGithub


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30201_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans15.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">WHITING
v
Well Name:
Pad Name: Surface Location: County:
Permit No: Gas Gatherer:

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">AFFIDAVIT AFFIRMING DISCUSSION WITH GAS GATHERER
Klose 21-27-3H Klose 27B 275 FNL & 1890 FWL, Section 27-T151N-R103W
McKenzie
Hiland Partner

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Whiting Oil and Gas Corporation (WPC) reviewed anticipated new well completion date and production rate information with its gas gatherer in preparing a Gas Capture Plan for the above subject wells.
Information provided by our gas gatherer was included in our Gas Capture Plan as required by the North Dakota Industrial
Commission to review and process our Applications for Permit to Drill. The legal description of the well surface location is as noted above:

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dated:

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">October 29, 2014

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">"97%"—
'1,
Brandon Rollins - Operations Engineer - Watford City
I
Whiting Oil and Gas Corporation

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">ACKNOWLEDGEMENT

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">STATE OF COLORADO

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">COUNTY OF DENVER

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">On this 29th day of October, 2014, before me, a Notary Public, personally appeared Brandon Rollins, who being by me
duly sworn, did say that he is the Operations Engineer - Watford City of Whiting Oil and Gas Corporation, and that the foregoing instrument was executed by him on behalf of said company as its free act and deed.
IN WITNESS WHEREOF, I have hereunto set my hand and affixed by Notarial Seal the day and year first above written.

    <p class="styleSans46.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">
/ "'1'! uuum' 57°" Exp'wes
\
0'5"

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">(SEAL)

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans45.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans21.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">NOTARY PUBLIC
My Commission Expires: é


text:
import { CompositeCommandManager } from '../command/composite.command.manager';

export class SelectionCommandManager extends CompositeCommandManager {
  constructor(model, manager) {
    super(manager);

    this.model = model;
  }

  filter(commands) {
    if (this.model.edit().status === 'edit') {
      const { cell } = this.model.navigation();
      if (cell && cell.column.type !== 'select') {
        return [];
      }
    }

    return super.filter(commands);
  }
}


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for PermissionRemovedEvent complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="PermissionRemovedEvent">
 *   <complexContent>
 *     <extension base="{urn:vim25}PermissionEvent">
 *       <sequence>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PermissionRemovedEvent")
public class PermissionRemovedEvent
    extends PermissionEvent
{

}


text:
#include "config.h"
#include "core/page/PagePopupClient.h"

#include "wtf/text/StringBuilder.h"

namespace blink {

#define addLiteral(literal, data)    data->append(literal, sizeof(literal) - 1)

void PagePopupClient::addJavaScriptString(const String& str, SharedBuffer* data)
{
    addLiteral("\"", data);
    StringBuilder builder;
    builder.reserveCapacity(str.length());
    for (unsigned i = 0; i < str.length(); ++i) {
        if (str[i] == '\r') {
            builder.append("\\r");
        } else if (str[i] == '\n') {
            builder.append("\\n");
        } else if (str[i] == '\\' || str[i] == '"') {
            builder.append('\\');
            builder.append(str[i]);
        } else {
            builder.append(str[i]);
        }
    }
    addString(builder.toString(), data);
    addLiteral("\"", data);
}

void PagePopupClient::addProperty(const char* name, const String& value, SharedBuffer* data)
{
    data->append(name, strlen(name));
    addLiteral(": ", data);
    addJavaScriptString(value, data);
    addLiteral(",\n", data);
}

void PagePopupClient::addProperty(const char* name, int value, SharedBuffer* data)
{
    data->append(name, strlen(name));
    addLiteral(": ", data);
    addString(String::number(value), data);
    addLiteral(",\n", data);
}

void PagePopupClient::addProperty(const char* name, unsigned value, SharedBuffer* data)
{
    data->append(name, strlen(name));
    addLiteral(": ", data);
    addString(String::number(value), data);
    addLiteral(",\n", data);
}

void PagePopupClient::addProperty(const char* name, bool value, SharedBuffer* data)
{
    data->append(name, strlen(name));
    addLiteral(": ", data);
    if (value)
        addLiteral("true", data);
    else
        addLiteral("false", data);
    addLiteral(",\n", data);
}

void PagePopupClient::addProperty(const char* name, double value, SharedBuffer* data)
{
    data->append(name, strlen(name));
    addLiteral(": ", data);
    addString(String::number(value), data);
    addLiteral(",\n", data);
}

void PagePopupClient::addProperty(const char* name, const Vector<String>& values, SharedBuffer* data)
{
    data->append(name, strlen(name));
    addLiteral(": [", data);
    for (unsigned i = 0; i < values.size(); ++i) {
        if (i)
            addLiteral(",", data);
        addJavaScriptString(values[i], data);
    }
    addLiteral("],\n", data);
}

void PagePopupClient::addProperty(const char* name, const IntRect& rect, SharedBuffer* data)
{
    data->append(name, strlen(name));
    addLiteral(": {", data);
    addProperty("x", rect.x(), data);
    addProperty("y", rect.y(), data);
    addProperty("width", rect.width(), data);
    addProperty("height", rect.height(), data);
    addLiteral("},\n", data);
}

} // namespace blink


text:
package uk.org.facetus.nt;

/**
 * A PoS tagger for reference names.
 *
 */
public class ReferenceNameTagger extends NameTagger {

    ReferenceNameTagger(String modelPath) {
        super(modelPath);
    }
}


text:
The demo shows how to use predictions produced by the Toxicity classifier.

## Setup

cd into the demo folder:

```sh
cd toxicity/demo
```

Install dependencies and prepare the build directory:

```sh
yarn
```

To watch files for changes, and launch a dev server:

```sh
yarn watch
```

## If you are developing toxicity locally, and want to test the changes in the demo

cd into the toxicity folder:
```sh
cd toxicity
```

Install dependencies:
```sh
yarn
```

Build and publish toxicity locally:
```sh
yarn publish-local
```

Cd into the demo and install dependencies:

```sh
cd demo
yarn
```

Link the local toxicity to the demo:
```sh
yarn link-local
```

Start the dev demo server:
```sh
yarn watch
```

To get future updates from the toxicity source code:
```
# cd up into the toxicity directory
cd ../
yarn publish-local
```


text:
package com.google.gapid.views;

import static com.google.gapid.image.Images.noAlpha;
import static com.google.gapid.models.Thumbnails.THUMB_SIZE;
import static com.google.gapid.util.Loadable.MessageType.Error;
import static com.google.gapid.util.Ranges.count;
import static com.google.gapid.util.Ranges.first;
import static com.google.gapid.util.Ranges.last;
import static com.google.gapid.widgets.Widgets.createTreeForViewer;
import static com.google.gapid.widgets.Widgets.createTreeViewer;
import static com.google.gapid.widgets.Widgets.scheduleIfNotDisposed;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gapid.Server.GapisInitException;
import com.google.gapid.models.ApiContext;
import com.google.gapid.models.ApiContext.FilteringContext;
import com.google.gapid.models.AtomHierarchies;
import com.google.gapid.models.AtomHierarchies.AtomNode;
import com.google.gapid.models.AtomHierarchies.FilteredGroup;
import com.google.gapid.models.AtomStream;
import com.google.gapid.models.Capture;
import com.google.gapid.models.Models;
import com.google.gapid.models.Thumbnails;
import com.google.gapid.proto.service.Service;
import com.google.gapid.proto.service.Service.CommandGroup;
import com.google.gapid.proto.service.Service.CommandRange;
import com.google.gapid.proto.service.path.Path;
import com.google.gapid.service.atom.Atom;
import com.google.gapid.service.atom.DynamicAtom;
import com.google.gapid.service.snippets.CanFollow;
import com.google.gapid.service.snippets.Pathway;
import com.google.gapid.util.Events;
import com.google.gapid.util.Messages;
import com.google.gapid.util.MouseAdapter;
import com.google.gapid.util.Paths;
import com.google.gapid.util.Scheduler;
import com.google.gapid.util.SelectionHandler;
import com.google.gapid.views.Formatter.StylingString;
import com.google.gapid.widgets.Balloon;
import com.google.gapid.widgets.CopySources;
import com.google.gapid.widgets.LoadableImage;
import com.google.gapid.widgets.LoadableImageWidget;
import com.google.gapid.widgets.LoadablePanel;
import com.google.gapid.widgets.LoadingIndicator;
import com.google.gapid.widgets.MeasuringViewLabelProvider;
import com.google.gapid.widgets.SearchBox;
import com.google.gapid.widgets.Theme;
import com.google.gapid.widgets.Widgets;

import org.eclipse.jface.viewers.ILazyTreeContentProvider;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

/**
 * API command (atom) view displaying the commands with their hierarchy grouping in a tree.
 */
public class AtomTree extends Composite implements Tab, Capture.Listener, AtomStream.Listener,
    ApiContext.Listener, AtomHierarchies.Listener, Thumbnails.Listener {
  protected static final Logger LOG = Logger.getLogger(AtomTree.class.getName());
  private static final int PREVIEW_HOVER_DELAY_MS = 500;

  private final Models models;
  private final LoadablePanel<Tree> loading;
  private final TreeViewer viewer;
  private final ImageProvider imageProvider;
  private final SelectionHandler<Tree> selectionHandler;
  private FilteredGroup root;

  public AtomTree(Composite parent, Models models, Widgets widgets) {
    super(parent, SWT.NONE);
    this.models = models;

    setLayout(new GridLayout(1, false));

    SearchBox search = new SearchBox(this);
    loading = new LoadablePanel<Tree>(this, widgets,
        p -> createTreeForViewer(p, SWT.H_SCROLL | SWT.V_SCROLL | SWT.VIRTUAL));
    Tree tree = loading.getContents();
    viewer = createTreeViewer(tree);
    imageProvider = new ImageProvider(models.thumbs, viewer, widgets.loading);
    viewer.setContentProvider(new AtomContentProvider(viewer));
    ViewLabelProvider labelProvider = new ViewLabelProvider(viewer, widgets.theme, imageProvider);
    viewer.setLabelProvider(labelProvider);

    search.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
    loading.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    models.capture.addListener(this);
    models.atoms.addListener(this);
    models.contexts.addListener(this);
    models.hierarchies.addListener(this);
    models.thumbs.addListener(this);
    addListener(SWT.Dispose, e -> {
      models.capture.removeListener(this);
      models.atoms.removeListener(this);
      models.contexts.removeListener(this);
      models.hierarchies.removeListener(this);
      models.thumbs.removeListener(this);
      imageProvider.reset();
    });

    search.addListener(Events.Search, e -> search(e.text, (e.detail & Events.REGEX) != 0));

    selectionHandler = new SelectionHandler<Tree>(LOG, tree) {
      @Override
      protected void updateModel(Event e) {
        Object selection = (tree.getSelectionCount() > 0) ? tree.getSelection()[0].getData() : null;
        if (selection instanceof FilteredGroup) {
          models.atoms.selectAtoms(((FilteredGroup)selection).group.getRange(), false);
        } else if (selection instanceof AtomNode) {
          models.atoms.selectAtoms(((AtomNode)selection).index, 1, false);
        }
      }
    };

    Menu popup = new Menu(tree);
    Widgets.createMenuItem(popup, "&Edit", SWT.MOD1 + 'E', e -> {
      TreeItem item = (tree.getSelectionCount() > 0) ? tree.getSelection()[0] : null;
      if (item != null && (item.getData() instanceof AtomNode)) {
        widgets.editor.showEditPopup(getShell(), ((AtomNode)item.getData()).index);
      }
    });
    tree.setMenu(popup);
    tree.addListener(SWT.MenuDetect, e -> {
      TreeItem item = tree.getItem(tree.toControl(e.x, e.y));
      if (item == null || !(item.getData() instanceof AtomNode)) {
        e.doit = false;
      }
    });

    MouseAdapter mouseHandler = new MouseAdapter() {
      private Future<?> lastScheduledFuture = Futures.immediateFuture(null);
      private TreeItem lastHoveredItem;
      private Balloon lastShownBalloon;

      @Override
      public void mouseMove(MouseEvent e) {
        updateHover(e.x, e.y);
      }

      @Override
      public void mouseScrolled(MouseEvent e) {
        updateHover(e.x, e.y);
      }

      @Override
      public void widgetSelected(SelectionEvent e) {
        // Scrollbar was moved / mouse wheel caused scrolling. This is required for systems with
        // a touchpad with scrolling inertia, where the view keeps scrolling long after the mouse
        // wheel event has been processed.
        Display disp = getDisplay();
        Point mouse = disp.map(null, tree, disp.getCursorLocation());
        updateHover(mouse.x, mouse.y);
      }

      @Override
      public void mouseDown(MouseEvent e) {
        Point location = new Point(e.x, e.y);
        CanFollow follow = (CanFollow)labelProvider.getFollow(location);
        if (follow != null) {
          models.follower.follow(getFollowPath(tree.getItem(location), follow.getPath()));
        }
      }

      private void updateHover(int x, int y) {
        TreeItem item = tree.getItem(new Point(x, y));
        if (item != null && (item.getData() instanceof FilteredGroup) &&
            item.getImage() != null && item.getImageBounds(0).contains(x, y)) {
          hover(item);
        } else {
          hover(null);

          CanFollow follow = (CanFollow)labelProvider.getFollow(new Point(x, y));
          setCursor((follow == null) ? null : getDisplay().getSystemCursor(SWT.CURSOR_HAND));
          if (follow != null) {
            models.follower.prepareFollow(getFollowPath(item, follow.getPath()));
          }
        }
      }

      private Path.Any getFollowPath(TreeItem item, Pathway path) {
        AtomNode atom = (AtomNode)item.getData();
        String field = ((com.google.gapid.service.snippets.FieldPath)path).getName();
        for (int i = 0; i < atom.atom.getFieldCount(); i++) {
          String actualField = atom.atom.getFieldInfo(i).getName();
          if (actualField.equalsIgnoreCase(field)) {
            return Paths.atomField(models.atoms.getPath(), atom.index, actualField);
          }
        }
        LOG.log(Level.WARNING, "Field " + path + " not found in atom " + atom.atom);
        return null;
      }

      private void hover(TreeItem item) {
        if (item != lastHoveredItem) {
          lastScheduledFuture.cancel(true);
          lastHoveredItem = item;
          if (item != null) {
            lastScheduledFuture = Scheduler.EXECUTOR.schedule(() ->
              Widgets.scheduleIfNotDisposed(
                  tree, () -> showBalloon(item, (FilteredGroup)item.getData())),
              PREVIEW_HOVER_DELAY_MS, TimeUnit.MILLISECONDS);
          }
          if (lastShownBalloon != null) {
            lastShownBalloon.close();
          }
        }
      }

      private void showBalloon(TreeItem item, FilteredGroup group) {
        if (lastShownBalloon != null) {
          lastShownBalloon.close();
        }
        Rectangle bounds = item.getImageBounds(0);
        lastShownBalloon = Balloon.createAndShow(tree, shell -> {
          LoadableImageWidget.forImageData(shell, loadImage(group), widgets.loading)
              .withImageEventListener(new LoadableImage.Listener() {
                @Override
                public void onLoaded(boolean success) {
                  if (success) {
                    Widgets.ifNotDisposed(shell,
                        () -> shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT)));
                  }
                }
              });
        }, new Point(bounds.x + bounds.width + 2, bounds.y + bounds.height / 2 - THUMB_SIZE / 2));
      }

      private ListenableFuture<ImageData> loadImage(FilteredGroup group) {
        return noAlpha(models.thumbs.getThumbnail(group.getIndexOfLastLeaf(), THUMB_SIZE));
      }
    };
    tree.addMouseListener(mouseHandler);
    tree.addMouseMoveListener(mouseHandler);
    tree.addMouseWheelListener(mouseHandler);
    tree.getVerticalBar().addSelectionListener(mouseHandler);

    CopySources.registerTreeAsCopySource(widgets.copypaste, viewer, object -> {
      if (object instanceof FilteredGroup) {
        Service.CommandGroup group = ((FilteredGroup)object).group;
        CommandRange range = group.getRange();
        return new String[] { group.getName(), "(" + first(range) + " - " + last(range) + ")" };
      } else if (object instanceof AtomNode) {
        AtomNode node = (AtomNode)object;
        return new String[] { node.index + ":", Formatter.toString((DynamicAtom)node.atom) };
      }
      return new String[] { String.valueOf(object) };
    });
  }

  private void search(String text, boolean regex) {
    if (root != null && !text.isEmpty()) {
      FilteredGroup parent = root;
      Object start = null;
      if (viewer.getTree().getSelectionCount() >= 1) {
        start = viewer.getTree().getSelection()[0].getData();
        if (start instanceof FilteredGroup) {
          parent = ((FilteredGroup)start).parent;
        } else if (start instanceof AtomNode) {
          parent = ((AtomNode)start).parent;
        } else {
          return;
        }
      }

      Pattern pattern = SearchBox.getPattern(text, regex);
      CommandRange range = parent.search(pattern, start, start instanceof AtomNode, true);
      if (range == null && (parent != root || start != null)) {
        range = root.search(pattern, null, false, false);
      }

      if (range != null) {
        models.atoms.selectAtoms(range, true);
      }
    }
  }

  @Override
  public Control getControl() {
    return this;
  }

  @Override
  public void reinitialize() {
    updateTree(false);
  }

  @Override
  public void onCaptureLoadingStart(boolean maintainState) {
    updateTree(true);
  }

  @Override
  public void onCaptureLoaded(GapisInitException error) {
    if (error != null) {
      loading.showMessage(Error, Messages.CAPTURE_LOAD_FAILURE);
    }
  }

  @Override
  public void onAtomsLoaded() {
    updateTree(false);
  }

  @Override
  public void onAtomsSelected(CommandRange range) {
    FilteredGroup group = root;
    selectionHandler.updateSelectionFromModel(
        () -> (group == null) ? null : group.getTreePathTo(range),
        selection -> viewer.setSelection(new TreeSelection(selection), true));
  }

  @Override
  public void onContextsLoaded() {
    updateTree(false);
  }

  @Override
  public void onContextSelected(FilteringContext context) {
    updateTree(false);
  }

  @Override
  public void onHierarchiesLoaded() {
    updateTree(false);
  }

  @Override
  public void onThumnailsChanged() {
    imageProvider.reset();
    viewer.refresh();
  }

  private void updateTree(boolean assumeLoading) {
    imageProvider.reset();
    root = null;

    if (assumeLoading || !models.atoms.isLoaded() || !models.contexts.isLoaded() ||
        !models.hierarchies.isLoaded()) {
      loading.startLoading();
      viewer.setInput(null);
      return;
    }

    loading.stopLoading();
    root = models.hierarchies.getHierarchy(
        models.atoms.getData(), models.contexts.getSelectedContext());
    viewer.setInput(root);
    viewer.getTree().setSelection(viewer.getTree().getItem(0));
    viewer.getTree().showSelection();

    if (models.atoms.getSelectedAtoms() != null) {
      onAtomsSelected(models.atoms.getSelectedAtoms());
    }
  }

  /**
   * Content provider for the command tree.
   */
  private static class AtomContentProvider implements ILazyTreeContentProvider {
    private final TreeViewer viewer;

    public AtomContentProvider(TreeViewer viewer) {
      this.viewer = viewer;
    }

    @Override
    public void updateChildCount(Object element, int currentChildCount) {
      FilteredGroup group = (FilteredGroup)element;
      viewer.setChildCount(element, group.getChildCount());
    }

    @Override
    public void updateElement(Object parent, int index) {
      FilteredGroup group = (FilteredGroup)parent;
      Object child = group.getChild(index);
      viewer.replace(parent, index, child);
      viewer.setHasChildren(child, child instanceof FilteredGroup);
    }

    @Override
    public Object getParent(Object element) {
      return null;
    }
  }

  /**
   * Image provider for the command tree. Groups that represent frames or draw calls will have
   * a thumbnail preview of the framebuffer in the tree.
   */
  private static class ImageProvider implements LoadingIndicator.Repaintable {
    private static final int PREVIEW_SIZE = 18;

    private final Thumbnails thumbs;
    private final TreeViewer viewer;
    private final LoadingIndicator loading;
    private final Map<FilteredGroup, LoadableImage> images = Maps.newIdentityHashMap();

    public ImageProvider(Thumbnails thumbs, TreeViewer viewer, LoadingIndicator loading) {
      this.thumbs = thumbs;
      this.viewer = viewer;
      this.loading = loading;
    }

    public Image getImage(FilteredGroup group) {
      LoadableImage image = images.get(group);
      if (image == null) {
        if (!shouldShowImage(group) || !thumbs.isReady()) {
          return null;
        }

        image = LoadableImage.forSmallImageData(
            viewer.getTree(), () -> loadImage(group), loading, this);
        images.put(group, image);
      }
      return image.getImage();
    }

    public void onPaint(FilteredGroup group) {
      LoadableImage image = images.get(group);
      if (image != null) {
        image.load();
      }
    }

    @Override
    public void repaint() {
      scheduleIfNotDisposed(viewer.getTree(), viewer::refresh);
    }

    private static boolean shouldShowImage(FilteredGroup group) {
      Atom atom = group.getLastLeaf();
      return atom != null && (atom.isDrawCall() || atom.isEndOfFrame());
    }

    private ListenableFuture<ImageData> loadImage(FilteredGroup group) {
      long index = group.getIndexOfLastDrawCall();
      if (index < 0) {
        index = group.getIndexOfLastLeaf();
      }
      return noAlpha(thumbs.getThumbnail(index, PREVIEW_SIZE));
    }

    public void reset() {
      for (LoadableImage image : images.values()) {
        image.dispose();
      }
      images.clear();
    }
  }

  /**
   * Label provider for the command tree.
   */
  private static class ViewLabelProvider extends MeasuringViewLabelProvider {
    private final ImageProvider imageProvider;

    public ViewLabelProvider(TreeViewer viewer, Theme theme, ImageProvider imageProvider) {
      super(viewer, theme);
      this.imageProvider = imageProvider;
    }

    @Override
    protected <S extends StylingString> S format(Object element, S string) {
      if (element instanceof FilteredGroup) {
        CommandGroup group = ((FilteredGroup)element).group;
        string.append(first(group.getRange()) + ": ", string.defaultStyle());
        string.append(group.getName(), string.labelStyle());
        long count = count(group.getRange());
        string.append(
            " (" + count + " Command" + (count != 1 ? "s" : "") + ")", string.structureStyle());
      } else if (element instanceof AtomNode) {
        AtomNode atom = (AtomNode)element;
        string.append(atom.index + ": ", string.defaultStyle());
        Formatter.format((DynamicAtom)atom.atom, string, string.identifierStyle());
      }
      return string;
    }

    @Override
    protected Image getImage(Object element) {
      Image result = null;
      if (element instanceof FilteredGroup) {
        result = imageProvider.getImage((FilteredGroup)element);
      }
      return result;
    }

    @Override
    protected boolean isFollowable(Object element) {
      return element instanceof AtomNode;
    }

    @Override
    protected void paint(Event event, Object element) {
      if (element instanceof FilteredGroup) {
        imageProvider.onPaint((FilteredGroup)element);
      }
      super.paint(event, element);
    }
  }
}


text:
from django.contrib import admin
from oscar.core.loading import get_model

WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')

admin.site.register(WishList)
admin.site.register(Line)


text:
package com.winsun.fruitmix.services;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.support.v4.content.LocalBroadcastManager;

import com.winsun.fruitmix.db.DBUtils;
import com.winsun.fruitmix.model.Media;
import com.winsun.fruitmix.parser.RemoteDataParser;
import com.winsun.fruitmix.parser.RemoteMediaParser;
import com.winsun.fruitmix.util.FNAS;
import com.winsun.fruitmix.util.LocalCache;
import com.winsun.fruitmix.util.OperationResult;
import com.winsun.fruitmix.util.Util;

import java.util.List;
import java.util.concurrent.ConcurrentMap;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p/>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class RetrieveRemoteMediaService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION_RETRIEVE_REMOTE_MEDIA = "com.winsun.fruitmix.services.action.retrieve_remote_media";

    public RetrieveRemoteMediaService() {
        super("RetrieveRemoteMediaService");
    }

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startActionRetrieveRemoteMedia(Context context) {
        Intent intent = new Intent(context, RetrieveRemoteMediaService.class);
        intent.setAction(ACTION_RETRIEVE_REMOTE_MEDIA);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_RETRIEVE_REMOTE_MEDIA.equals(action)) {
                handleActionRetrieveRemoteMedia();
            }
        }
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionRetrieveRemoteMedia() {

        List<Media> medias;

        ConcurrentMap<String, Media> mediaConcurrentMap;
        DBUtils dbUtils = DBUtils.SINGLE_INSTANCE;

        try {

            String json = FNAS.loadMedia();

            RemoteDataParser<Media> parser = new RemoteMediaParser();
            medias = parser.parse(json);

            mediaConcurrentMap = LocalCache.BuildMediaMapKeyIsUUID(medias);

            dbUtils.deleteAllRemoteMedia();
            dbUtils.insertRemoteMedias(mediaConcurrentMap);

        } catch (Exception e) {
            e.printStackTrace();

            medias = dbUtils.getAllRemoteMedia();

            mediaConcurrentMap = LocalCache.BuildMediaMapKeyIsUUID(medias);
        }

        LocalCache.RemoteMediaMapKeyIsUUID.clear();

        LocalCache.RemoteMediaMapKeyIsUUID.putAll(mediaConcurrentMap);

        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        Intent intent = new Intent(Util.REMOTE_MEDIA_RETRIEVED);
        intent.putExtra(Util.OPERATION_RESULT_NAME, OperationResult.SUCCEED.name());
        localBroadcastManager.sendBroadcast(intent);

    }

}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Throw NotFoundError exception</title>
<link rel="author" title="Intel" href="http://www.intel.com">
<link rel="author" title="Chunyan Wang" href="mailto:chunyanx.wang@intel.com">
<link rel="help" href="http://www.w3.org/TR/2015/WD-presentation-api-20150701/#starting-a-presentation-session">

Turn off 'Simulate Secondary Display' by 'Setting' app.


text:
package com.globant.androidrepository;

import com.globant.repository.NetworkOperationAdapter;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyOkHttpNetworkAdapter extends NetworkOperationAdapter<MyModelExample, String> {

    OkHttpClient mClient = new OkHttpClient();

    @Override
    public MyModelExample getModelFromNetworkSource(String itemId) {
        try {
            Request request = new Request.Builder()
                    .url("http://www.google.com")
                    .build();
            Response response = mClient.newCall(request).execute();
            return new MyModelExample();
        } catch (Exception e) {
            return null;
        }
    }
}


text:
if defined? Rails and Rails.version > '3'
  module Portier
    class Railtie < Rails::Railtie
      config.before_initialize do
        require 'portier/base'
        require 'portier/controller'
        ActiveRecord::Base.send     :extend, Portier::Base
        ActionController::Base.send :include, Portier::Controller
      end
    end
  end
end


text:
const assert = require('assert')
const util = require('util')

const parents = require('ldap-filter')

const Filter = require('./filter')

/// --- API

function NotFilter (options) {
  parents.NotFilter.call(this, options)
}
util.inherits(NotFilter, parents.NotFilter)
Filter.mixin(NotFilter)
module.exports = NotFilter

NotFilter.prototype._toBer = function (ber) {
  assert.ok(ber)

  return this.filter.toBer(ber)
}


text:
from gzip import GzipFile

# Python < 2.7 doesn't have context handling
class gzip_open(GzipFile):
    def __enter__(self):
        if hasattr(GzipFile, '__enter__'):
            return GzipFile.__enter__(self)
        else:
            return self

    def __exit__(self, exc_type, exc_value, traceback):
        if hasattr(GzipFile, '__exit__'):
            return GzipFile.__exit__(self, exc_type, exc_value, traceback)
        else:
            return self.close()


text:
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <glib/gprintf.h>
#include <gtk/gtk.h>
#include <unistd.h>

#ifdef WIN32
    #include <windows.h>
#else
    #include <sys/types.h>
    #include <sys/wait.h>
#endif

#ifndef WEXITSTATUS
#   define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
#endif

#include "constants.h"
#include "environment.h"
#include "utils.h"

#ifdef WIN32
    static gchar *slogmsg_info = "[Info] ";
    static gchar *slogmsg_thread = "[Thread]";
    static gchar *slogmsg_debug = "[Debug] ";
    static gchar *slogmsg_fatal = "[Fatal] ";
    static gchar *slogmsg_error = "[Error] ";
    static gchar *slogmsg_warning = "[Warning] ";
#else
    static gchar *slogmsg_info = "\e[1;34m[Info]\e[0m ";
    static gchar *slogmsg_thread = "\e[1;31m[Thread]\e[0m";
    static gchar *slogmsg_debug = "\e[1;32m[Debug]\e[0m ";
    static gchar *slogmsg_fatal = "\e[1;37;41m[Fatal]\e[0m ";
    static gchar *slogmsg_error = "\e[1;31m[Error]\e[0m ";
    static gchar *slogmsg_warning = "\e[1;33m[Warning]\e[0m ";
#endif

static gint slog_debug = 0;
static GtkWindow* parent = 0;
GThread* main_thread = 0;
extern pid_t typesetter_pid;

void slog_init (gint debug) {
    slog_debug = debug;
    main_thread = g_thread_self ();
}

gboolean in_debug_mode() {
    return slog_debug;
}

void slog_set_gui_parent (GtkWindow* p) {
    parent = p;
}

void slog (gint level, const gchar *fmt, ...) {
    gchar message[BUFSIZ];
    gchar* out;
    va_list vap;

    if (L_IS_TYPE (level, L_DEBUG) && !slog_debug) return;

    if (g_thread_self () != main_thread)
        g_fprintf (stderr, "%s", slogmsg_thread);

    if (L_IS_TYPE (level, L_DEBUG))
        g_fprintf (stderr, "%s", slogmsg_debug);
    else if (L_IS_TYPE (level, L_FATAL) || L_IS_TYPE (level, L_G_FATAL))
        g_fprintf (stderr, "%s", slogmsg_fatal);
    else if (L_IS_TYPE (level, L_ERROR) || L_IS_TYPE (level, L_G_ERROR))
        g_fprintf (stderr, "%s", slogmsg_error);
    else if (L_IS_TYPE (level, L_WARNING))
        g_fprintf (stderr, "%s", slogmsg_warning);
    else
        g_fprintf (stderr, "%s", slogmsg_info);

    va_start (vap, fmt);
    vsnprintf (message, BUFSIZ, fmt, vap);
    va_end (vap);
    fprintf (stderr, "%s", message);

    if (L_IS_GUI (level)) {
        GtkWidget* dialog;

        if (L_IS_TYPE (level, L_G_FATAL))
            out = g_strdup_printf (_("%s has encountered a serious error and "
                        "will require a restart. Your working data will be "
                        "restored when you reload your document. Please "
                        "report bugs at: http://dev.midnightcoding.org"),
                        PACKAGE_NAME);
        else
            out = g_strdup (message);

        dialog = gtk_message_dialog_new (parent,
                GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
                L_IS_TYPE (level,L_G_INFO)? GTK_MESSAGE_INFO: GTK_MESSAGE_ERROR,
                GTK_BUTTONS_OK,
                "%s", message);
        g_free (out);

        if (L_IS_TYPE (level, L_G_ERROR))
            gtk_window_set_title (GTK_WINDOW (dialog), "Error!");
        else if (L_IS_TYPE (level, L_G_FATAL))
            gtk_window_set_title (GTK_WINDOW (dialog), "Fatal Error!");
        else if (L_IS_TYPE (level, L_G_INFO))
            gtk_window_set_title (GTK_WINDOW (dialog), "Info");

        gtk_dialog_run (GTK_DIALOG (dialog));
        gtk_widget_destroy (dialog);
    }

    if (!L_IS_TYPE (level, L_INFO) &&
        !L_IS_TYPE (level, L_DEBUG) &&
        !L_IS_TYPE (level, L_ERROR) &&
        !L_IS_TYPE (level, L_G_INFO) &&
        !L_IS_TYPE (level, L_G_ERROR))
        exit (1);
}

gint utils_yes_no_dialog (const gchar* message) {
    GtkWidget* dialog;
    gint ret = 0;

    g_return_val_if_fail (message != NULL, 0);

    dialog = gtk_message_dialog_new (parent,
                 GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
                 GTK_MESSAGE_QUESTION,
                 GTK_BUTTONS_YES_NO,
                 "%s", message);

    gtk_window_set_title (GTK_WINDOW (dialog), _("Confirmation"));
    ret = gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);

    return ret;
}

gboolean utils_path_exists (const gchar* path) {
    if (NULL == path) return FALSE;
    gboolean result = FALSE;
    GFile* file = g_file_new_for_path (path);
    result = g_file_query_exists (file, NULL);
    g_object_unref (file);
    return result;
}

gboolean utils_set_file_contents (const gchar *filename, const gchar *text,
                                  gssize length) {
    /* g_file_set_contents may not work correctly on Windows. See the
     * API documentation of this function for details. Should Gummi
     * be affected, we might have to implement an alternative */
        GError* error = NULL;
        if (!g_file_set_contents(filename, text, length, &error)) {
            slog (L_ERROR, "%s\n", error->message);
            g_error_free(error);
            return FALSE;
        }
        return TRUE;
}

gboolean utils_copy_file (const gchar* source, const gchar* dest, GError** err) {
    gchar* contents;
    gsize length;

    g_return_val_if_fail (source != NULL, FALSE);
    g_return_val_if_fail (dest != NULL, FALSE);
    g_return_val_if_fail (err == NULL || *err == NULL, FALSE);

    if (!g_file_get_contents (source, &contents, &length, err))
        return FALSE;

    if (!g_file_set_contents (dest, contents, length, err))
        return FALSE;

    g_free (contents);

    return TRUE;
}

Tuple2 utils_popen_r (const gchar* cmd, const gchar* chdir) {
    gchar buf[BUFSIZ];
    int pout = 0;
    gchar* ret = NULL;
    gchar* rot = NULL;
    glong len = 0;
    gint status = 0;
    int n_args = 0;
    gchar** args = NULL;
    GError* error = NULL;

    g_assert (cmd != NULL);

    /* XXX: Set process pid, ugly... */
    if (!g_shell_parse_argv(cmd, &n_args, &args, &error)) {
        slog(L_G_FATAL, "%s", error->message);
        /* Not reached */
    }

    if (!g_spawn_async_with_pipes (chdir, args, NULL,
                G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
                NULL, NULL, &typesetter_pid, NULL, &pout, NULL, &error)) {
        slog(L_G_FATAL, "%s", error->message);
        /* Not reached */
    }

    // TODO: replace with GIOChannel implementation:
    while ((len = read (pout, buf, BUFSIZ)) > 0) {
        buf[len - (len == BUFSIZ)] = 0;
        rot = g_strdup (ret);
        g_free (ret);
        if (ret)
            ret = g_strconcat (rot, buf, NULL);
        else
            ret = g_strdup (buf);
        g_free (rot);
    }

    // close the file descriptor:
    close(pout);

    #ifdef WIN32 // TODO: check this
        status = WaitForSingleObject(typesetter_pid, INFINITE);
    #else
        waitpid(typesetter_pid, &status, 0);
    #endif

    // See bug 446:
    if (ret) {
        if (!g_utf8_validate (ret, -1, NULL)) {
            ret = g_convert_with_fallback (ret, -1, "UTF-8",
                    "ISO-8859-1", NULL, NULL, NULL, NULL);
        }
    }

    return (Tuple2){NULL, (gpointer)(glong)status, (gpointer)ret};
}

gchar* utils_path_to_relative (const gchar* root, const gchar* target) {
    gchar* tstr = NULL;
    if ( (root != NULL) && (0 == strncmp (target, root, strlen (root))))
        tstr = g_strdup (target + strlen (root) + 1);
    else
        tstr = g_strdup (target);
    return tstr;
}

gchar* utils_get_tmp_tmp_dir (void) {
	/* brb, gonna go punch a wall */
    gchar *tmp_tmp = g_build_path
						(C_DIRSEP, g_get_home_dir(), "gtmp", NULL);
    g_mkdir_with_parents (tmp_tmp, DIR_PERMS);

    return tmp_tmp;
}

gboolean utils_glist_is_member (GList* list, gchar* item) {
    int nrofitems = g_list_length (list);
    int i;

    for (i=0;i<nrofitems;i++) {
        if (STR_EQU (item, g_list_nth_data (list,i))) {
            return TRUE;
        }
    }
    return FALSE;
}

gboolean utils_subinstr (const gchar* substr, const gchar* target,
        gboolean case_insens) {
    if (target != NULL && substr != NULL) {
        if (case_insens) {
            gchar* ntarget = g_utf8_strup(target, -1);
            gchar* nsubstr = g_utf8_strup(substr, -1);
            gboolean result = g_strstr_len(ntarget, -1, nsubstr) != NULL;
            g_free(ntarget);
            g_free(nsubstr);
            return result;
        }
        else {
            return g_strstr_len(target, -1, substr) != NULL;
        }
    }
    return FALSE;
}

gchar* g_substr(gchar* src, gint start, gint end) {
    gint len = end - start + 1;
    char* dst = g_malloc(len * sizeof(gchar));
    memset(dst, 0, len);
    return strncpy(dst, &src[start], end - start);
}

slist* slist_find (slist* head, const gchar* term, gboolean n, gboolean create) {
    slist* current = head;
    slist* prev = 0;

    while (current) {
        if (n) {
            if (0 == strncmp (current->first, term, strlen (term)))
                return current;
        } else {
            if (STR_EQU (current->first, term))
                return current;
        }
        prev = current;
        current = current->next;
    }
    if (create) {
        slog (L_WARNING, "can't find `%s', creating new field for it...\n",
                term);
        prev->next = g_new0 (slist, 1);
        current = prev->next;
        current->first = g_strdup (term);
        current->second = g_strdup ("");
    } else
        current = NULL;
    return current;
}

slist* slist_append (slist* head, slist* node) {
    slist* current = head;
    slist* prev = NULL;

    while (current) {
        prev = current;
        current = current->next;
    }
    prev->next = node;
    return head;
}

slist* slist_remove (slist* head, slist* node) {
    slist* current = head;
    slist* prev = NULL;

    while (current) {
        if (current == node) break;
        prev = current;
        current = current->next;
    }
    if (current) {
        if (current == head)
            head = head->next;
        else
            prev->next = current->next;
    }
    return head;
}


text:
//
//  HealthBar.h
//  CGP-Ex3
//
//  Created by Amir Blum on 5/5/15.
//  Copyright (c) 2015 Amir Blum. All rights reserved.
//

#ifndef __CGP_Ex3__HealthBar__
#define __CGP_Ex3__HealthBar__

#include <stdio.h>
#include "RenderableSceneNode.h"
#include "RenderComponent.h"

class HealthBar : public RenderableSceneNode {
private:
    int _maxUnits, _currentUnits;
protected:
    virtual void preRender();
public:
    HealthBar(int maxUnits, vec3 position, quat rotation, vec3 scale);
    virtual ~HealthBar();

    int getCurrentUnits();
    void setCurrentUnits(int currentUnits);
};

#endif /* defined(__CGP_Ex3__HealthBar__) */


text:
class UnionFind:
    def __init__(self, groups):
        self.leader_to_group = {}
        self.item_to_leader = {}

        for group in groups:
            leader = group[0]
            self.leader_to_group[leader] = []
            for item in group:
                self.leader_to_group[leader].append(item)
                self.item_to_leader[item] = leader

    def find(self, item):
        return self.item_to_leader[item]

    def union(self, item_1, item_2):
        leader_1 = self.item_to_leader[item_1]
        leader_2 = self.item_to_leader[item_2]

        if leader_1 == leader_2:
            return

        leader_of_smaller_group, leader_of_larger_group = (leader_1, leader_2) if len(self.leader_to_group[leader_1]) < len(self.leader_to_group[leader_2]) else (leader_2, leader_1)

        for item in self.leader_to_group[leader_of_smaller_group]:
            self.item_to_leader[item] = leader_of_larger_group

        self.leader_to_group[leader_of_larger_group] += self.leader_to_group[leader_of_smaller_group]
        del self.leader_to_group[leader_of_smaller_group]


text:
import os

current_path = os.path.dirname(os.path.abspath(__file__))
root_path = os.path.abspath( os.path.join(current_path, os.pardir))
data_path = os.path.abspath(os.path.join(root_path, os.pardir, os.pardir, 'data'))
data_launcher_path = os.path.join(data_path, 'launcher')

from xlog import Logger
log_file = os.path.join(data_launcher_path, "launcher.log")
xlog = Logger(file_name=log_file)


text:
1. In SQL Management Studio execute script **01. Schema.sql**. This will create a new database.
1. Open **02. Initiator - receive replies.sql** in new windows of SSMS, switch to a text mode Ctrl+T
1. Run **02. Initiator - receive replies.sql**. You will see messages that there was no data received.
1. Open **03. Initiator - send.sql** in new windows of SSMS, switch to a text mode Ctrl+T
1. Arrange these SSMS 2 windows side by side so that you can see the messages.
1. Run **03. Initiator - send.sql**. You will see messages appearing in all 2 windows.


text:
description: Interface for scorer.

<meta itemprop="name" content="tfr.keras.model.Scorer" />
<meta itemprop="path" content="Stable" />
<meta itemprop="property" content="__call__"/>

# tfr.keras.model.Scorer

    View source on GitHub

Interface for scorer.

The `Scorer` class is an abstract class to implement `score` in `ModelBuilder`
in tfr.keras.

To be implemented by subclasses:

*   `__call__()`: Contains the logic to score based on the context and example
    features.

Example subclass implementation:

```python
class SimpleScorer(Scorer):

  def __call__(self, context_features, example_features, mask):
    x = tf.concat([tensor for tensor in example_features.values()], -1)
    return tf.keras.layers.Dense(1)(x)
```

## Methods

__call__

View
source

@abc.abstractmethod
__call__(
    context_features: tfr.keras.model.TensorDict,
    example_features: tfr.keras.model.TensorDict,
    mask: tf.Tensor
) -> Union[TensorLike, TensorDict]

Scores all examples given context and returns logits.

<colgroup><col width="214px"><col></colgroup>

Args

`context_features`

maps from context feature keys to [batch_size,
feature_dims]-tensors of preprocessed context features.

`example_features`

maps from example feature keys to [batch_size,
list_size, feature_dims]-tensors of preprocessed example features.

`mask`

[batch_size, list_size]-tensor of mask for valid examples.

<colgroup><col width="214px"><col></colgroup>

Returns

A [batch_size, list_size]-tensor of logits or a dict mapping task name to
logits in the multi-task setting.


text:
import {BuildStatus, FastlaneStatus, fastlaneStatusToEnum} from '../common/constants';
import {Artifact} from './artifact';

const SHORT_SHA_LENGTH = 6;
const FINAL_STATES: Set<BuildStatus> = new Set([
  BuildStatus.FAILED, BuildStatus.INTERNAL_ISSUE, BuildStatus.MISSING_FASTFILE,
  BuildStatus.SUCCESS
]);

export interface BuildLogLine {
  message: string;
}

export interface BuildArtifactResponse {
  id: string;
  type: string;
}

export interface BuildResponse {
  number: number;
  project_id: string;
  status: FastlaneStatus;
  duration: number;
  description: string;
  trigger: string;
  lane: string;
  platform: string;
  parameters: {[param: string]: string};
  build_tools: {[tool: string]: string};
  clone_url: string;
  branch: string;
  ref: string;
  sha: string;
  timestamp: string;
  artifacts: BuildArtifactResponse[];
}

export class Build {
  readonly number: number;
  readonly projectId: string;
  readonly status: BuildStatus;
  readonly duration: number;
  readonly description: string;
  readonly trigger: string;
  readonly lane: string;
  readonly platform: string;
  readonly parameters: {[param: string]: string};
  readonly buildTools: {[tool: string]: string};
  readonly cloneUrl: string;
  readonly branch: string;
  readonly ref: string;
  readonly sha: string;
  readonly shortSha: string;
  readonly date: Date;
  readonly artifacts: Artifact[];

  constructor(build: BuildResponse) {
    this.number = build.number;
    this.projectId = build.project_id;
    this.description = build.description;
    this.trigger = build.trigger;
    this.lane = build.lane;
    this.platform = build.platform;
    this.parameters = build.parameters;
    this.buildTools = build.build_tools;
    this.cloneUrl = build.clone_url;
    this.branch = build.branch;
    this.ref = build.ref;
    this.duration = build.duration;
    this.sha = build.sha;
    this.shortSha = this.sha.slice(0, SHORT_SHA_LENGTH);
    this.status = fastlaneStatusToEnum(build.status);
    this.date = new Date(build.timestamp);
    this.artifacts = build.artifacts.map((artifact) => new Artifact(artifact));
  }

  isComplete(): boolean {
    return FINAL_STATES.has(this.status);
  }
}


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

#ifndef SEQAN_FIND_INDEX_LAMBDA_H
#define SEQAN_FIND_INDEX_LAMBDA_H

namespace seqan {

// ============================================================================
// Metafunction
// ============================================================================

// ----------------------------------------------------------------------------
// Metafunction DefaultFind<Index>
// ----------------------------------------------------------------------------

template <typename THaystack, typename THaystackSpec, typename TPattern>
struct DefaultFind<Index<THaystack, THaystackSpec>, TPattern>
{
    typedef Backtracking<Exact> Type;
};

// ============================================================================
// Functions
// ============================================================================

// ----------------------------------------------------------------------------
// Function _findImpl(..., Backtracking<Exact>)
// ----------------------------------------------------------------------------

template <typename TState, typename TIndex, typename TNeedle,
          typename TThreshold, typename TDelegate, typename TSpec>
SEQAN_FUNC_ENABLE_IF(IsSequence<TNeedle>, void)
_findImpl(TState & /* state */,
          TIndex & index,
          TNeedle const & needle,
          TThreshold /* threshold */,
          TDelegate && delegate,
          Backtracking<Exact, TSpec>)
{
    typedef typename Iterator<TIndex, TopDown<> >::Type TIndexIt;

    TIndexIt indexIt(index);

    if (goDown(indexIt, needle))
    {
        delegate(indexIt, TThreshold());
    }
}

// ----------------------------------------------------------------------------
// Function _findImpl(..., Backtracking<Edit/HammingDistance>)
// ----------------------------------------------------------------------------

template <typename TIndexIt, typename TNeedle, typename TNeedleIt,
          typename TThreshold, typename TDelegate, typename TDistance>
inline void
_findBacktracking(TIndexIt indexIt,
                  TNeedle const & needle,
                  TNeedleIt needleIt,
                  TThreshold errors,
                  TThreshold threshold,
                  TDelegate && delegate,
                  TDistance)
{
    // Exact case.
    if (errors == threshold)
    {
        if (goDown(indexIt, suffix(needle, position(needleIt, needle))))
            delegate(indexIt, errors);
    }
    // Approximate case.
    else if (errors < threshold)
    {
        // Base case.
        if (atEnd(needleIt, needle))
        {
            delegate(indexIt, errors);
        }
        // Recursive case.
        else
        {
            // Insertion.
            if (IsSameType<TDistance, EditDistance>::VALUE)
            {
                _findBacktracking(indexIt, needle, needleIt + 1,
                                  errors + 1, threshold, delegate, TDistance());
            }

            if (goDown(indexIt))
            {
                do
                {
                    // Mismatch.
                    TThreshold delta = !ordEqual(parentEdgeLabel(indexIt), value(needleIt));
                    _findBacktracking(indexIt, needle, needleIt + 1,
                                      errors + delta, threshold, delegate, TDistance());

                    // Deletion.
                    if (IsSameType<TDistance, EditDistance>::VALUE)
                    {
                        _findBacktracking(indexIt, needle, needleIt, errors + 1,
                                          threshold, delegate, TDistance());
                    }
                }
                while (goRight(indexIt));
            }
        }
    }
}

template <typename TState, typename TIndex, typename TNeedle,
          typename TThreshold, typename TDelegate, typename TDistance, typename TSpec>
SEQAN_FUNC_ENABLE_IF(IsSequence<TNeedle>, void)
_findImpl(TState & /* indexIt */,
          TIndex & index,
          TNeedle const & needle,
          TThreshold threshold,
          TDelegate && delegate,
          Backtracking<TDistance, TSpec>)
{
    typedef typename Iterator<TIndex, TopDown<> >::Type       TIndexIt;
    typedef typename Iterator<TNeedle const, Standard>::Type  TNeedleIt;

    TIndexIt indexIt(index);
    TNeedleIt needleIt = begin(needle, Standard());
    TThreshold errors = 0;

    _findBacktracking(indexIt, needle, needleIt, errors, threshold, delegate, TDistance());
}

// ----------------------------------------------------------------------------
// Function find(index, index, errors, [](...){}, Backtracking<TDistance>());
// ----------------------------------------------------------------------------

template <typename THaystack, typename THaystackSpec, typename TNeedle, typename TNeedleSpec,
          typename TThreshold, typename TDelegate, typename TDistance, typename TSpec>
inline void
find(Index<THaystack, THaystackSpec> & text,
     Index<TNeedle, TNeedleSpec> & pattern,
     TThreshold threshold,
     TDelegate && delegate,
     Backtracking<TDistance, TSpec>)
{
    typedef typename If<IsSameType<TDistance, Exact>,
                        HammingDistance, TDistance>::Type   TDistance_;
    typedef Backtracking<TDistance_, TSpec>                 TAlgorithm;
    typedef Index<THaystack, THaystackSpec>                 TText;
    typedef Index<TNeedle, TNeedleSpec>                     TPattern;
    typedef Finder_<TText, TPattern, TAlgorithm>            TFinder;

    TFinder finder;

    // This lambda is stored locally because _find() does not accept rvalue delegates.
    std::function<void(TFinder const &)> delegator = [&](TFinder const &)
    {
        delegate(_textIterator(finder), _patternIterator(finder), _getScore(finder));
    };

    _find(finder, text, pattern, threshold, delegator);
}

// ----------------------------------------------------------------------------
// Function find(index, wotdIndex, errors, [](...){}, Backtracking<TDistance>());
// ----------------------------------------------------------------------------

template <typename THaystack, typename THaystackSpec, typename TNeedle, typename TNeedleSpec,
          typename TThreshold, typename TDelegate, typename TDistance, typename TSpec>
inline void
find(Index<THaystack, THaystackSpec> & text,
     Index<TNeedle, IndexWotd<TNeedleSpec> > & pattern,
     TThreshold threshold,
     TDelegate && delegate,
     Backtracking<TDistance, TSpec>)
{
    typedef Index<THaystack, THaystackSpec>                 TText;
    typedef Index<TNeedle, IndexWotd<TNeedleSpec> >         TPattern;
    typedef Backtracking<TDistance, TSpec>                  TAlgorithm;

    typedef Finder<TText, TAlgorithm>                       TFinder_;
    typedef Pattern<TPattern, TAlgorithm>                   TPattern_;

    TFinder_ _finder(text);
    TPattern_ _pattern(pattern, length(back(host(pattern))));

    while (_resume(_finder, _pattern, threshold))
    {
        delegate(_finder.index_iterator, _pattern.index_iterator, _pattern.prefix_aligner.errors);
    }
}

}

#endif  // #ifndef SEQAN_FIND_INDEX_LAMBDA_H


text:
package App::Base::Daemon::Supervisor;
use 5.010;
use Moose::Role;
with 'App::Base::Daemon';
our $VERSION = "0.04";
$VERSION = eval $VERSION;

=head1 NAME

App::Base::Daemon::Supervisor - supervise daemon process

=head1 SYNOPSIS

    package App::Base::Daemon::Foo;
    use Moose;
    with 'App::Base::Daemon::Supervisor';

    sub documentation { return 'foo'; }
    sub options { ... }
    sub supervised_process {
        # the main daemon process
        while(1) {
            # check if supervisor is alive, exit otherwise
            $self->ping_supervisor;
            # do something
            ...
        }
    }
    sub supervised_shutdown {
        # this is called during shutdown
    }

=head1 DESCRIPTION

App::Base::Daemon::Supervisor allows to run code under supervision, it also
provides support for zero downtime reloading. When you run Supervisor based
daemon, the first process becomes a supervisor, it forks a child process which
invokes I<supervised_process> method that should contain the main daemon code.
Supervisor and worker connected with a socketpair. If the worker exits for some
reason, the supervisor detects it and starts a new worker after a small delay.
Worker should periodically call I<ping_supervisor> method, so it would be able
to detect the case when supervisor has been killed and exit.

If module needs hot reloading feature, it should redefine I<can_do_hot_reload>
method to return true value. In this case supervisor process sets a handler for
I<SIGUSR2> signal. When I<SIGUSR2> signal is received, supervisor starts a new
copy of the script via fork/exec, so this new copy runs a new code. New
supervisor starts a worker process and waits a signal that this new worker is
ready to do its job. To send that signal worker should invoke
I<ready_to_take_over> method.  Then the new supervisor receives that signal, it
sends I<SIGQUIT> to the old supervisor and waits for it to exit. After the old
supervisor exited (normally new supervisor detects that because it can flock
the pid file), the new supervisor sends signal to the worker,
I<ready_to_take_over> method in worker returns, and worker can start doing its
job. If supervisor receives I<SIGUSR2> when it is already in the process of
reloading, it ignores this signal. If supervisor didn't get I<SIGQUIT> in 60
seconds after starting hot reloading process, it sends I<SIGKILL> to the new
supervisor and resumes normal work.

=cut

use namespace::autoclean;
use Socket qw();
use POSIX qw(:errno_h);
use Time::HiRes;
use IO::Handle;
use Try::Tiny;

=head1 REQUIRED METHODS

Class consuming this role must implement the following methods:

=cut

=head2 supervised_process

The main daemon subroutine. Inside this subroutine you should periodically
check that supervisor is still alive using I<ping_supervisor> method. If
supervisor exited, daemon should also exit.

=cut

requires 'supervised_process';

=head2 supervised_shutdown

This subroutine is executed then daemon process is shutting down. Put cleanup
code inside.

=cut

requires 'supervised_shutdown';

=head1 ATTRIBUTES

=cut

=head2 is_supervisor

returns true inside supervisor process and false inside supervised daemon

=cut

has is_supervisor => (
    is      => 'rw',
    default => 1,
);

=head2 delay_before_respawn

how long supervisor should wait after child process exited before starting a
new child. Default value is 5.

=cut

has delay_before_respawn => (
    is      => 'rw',
    default => 5,
);

=head2 supervisor_pipe

File descriptor of the pipe to supervisor

=cut

has supervisor_pipe => (
    is     => 'rw',
    writer => '_supervisor_pipe',
);

has _child_pid => ( is => 'rw' );

=head1 METHODS

=cut

=head2 $self->ping_supervisor

Should only be called from supervised process. Checks if supervisor is alive
and initiates shutdown if it is not.

=cut

sub ping_supervisor {
    my $self = shift;
    my $pipe = $self->supervisor_pipe or $self->error("Supervisor pipe is not defined");
    say $pipe "ping";
    my $pong = <$pipe>;
    unless ( defined $pong ) {
        $self->error("Error reading from supervisor pipe: $!");
    }
    return;
}

=head2 $self->ready_to_take_over

Used to support hot reloading. If daemon support hot restart,
I<supervised_process> is called while the old daemon is still running.
I<supervised_process> should perform initialization, e.g. open listening
sockets, and then call this method. Method will cause termination of old daemon
and after return the new process may start serving clients.

=cut

sub ready_to_take_over {
    my $self = shift;
    my $pipe = $self->supervisor_pipe or confess "Supervisor pipe is not defined";
    say $pipe "takeover";
    my $ok = <$pipe>;
    defined($ok) or $self->error("Failed to take over");
    return;
}

=head2 $self->daemon_run

See L<App::Base::Daemon>

=cut

sub daemon_run {
    my $self = shift;
    $self->_set_hot_reload_handler;

    while (1) {
        socketpair my $chld, my $par, Socket::AF_UNIX, Socket::SOCK_STREAM, Socket::PF_UNSPEC;
        my $pid = fork;
        $self->_child_pid($pid);
        if ($pid) {
            local $SIG{QUIT} = sub {
                kill TERM => $pid;
                waitpid $pid, 0;
                exit 0;
            };
            $self->debug("Forked a supervised process $pid");
            $chld->close;
            $par->autoflush(1);
            $self->_supervisor_pipe($par);
            while (<$par>) {
                chomp;
                if ( $_ eq 'ping' ) {
                    say $par 'pong';
                }
                elsif ( $_ eq 'takeover' ) {
                    $self->_control_takeover;
                    say $par 'ok';
                }
                elsif ( $_ eq 'shutdown' ) {
                    $self->debug("Worker asked for shutdown");
                    kill KILL => $pid;
                    close $par;
                }
                else {
                    $self->warning("Received unknown command from the supervised process: $_");
                }
            }
            $self->debug("Child closed control connection");
            my $kid = waitpid $pid, 0;
            $self->warning("Supervised process $kid exited with status $?");
        }
        elsif ( not defined $pid ) {
            $self->warning("Couldn't fork: $!");
        }
        else {
            local $SIG{USR2};
            $par->close;
            $chld->autoflush(1);
            $self->_supervisor_pipe($chld);
            $self->is_supervisor(0);
            $self->supervised_process;
            exit 0;
        }
        Time::HiRes::usleep( 1_000_000 * $self->delay_before_respawn );
    }

    # for critic
    return;
}

# this initializes SIGUSR2 handler to perform hot reload
sub _set_hot_reload_handler {
    my $self = shift;

    return unless $self->can_do_hot_reload;
    my $upgrading;

    ## no critic (RequireLocalizedPunctuationVars)
    $SIG{USR2} = sub {
        return unless $ENV{APP_BASE_DAEMON_PID} == $$;
        if ($upgrading) {
            $self->warning("Received USR2, but hot reload is already in progress");
            return;
        }
        $self->warning("Received USR2, initiating hot reload");
        my $pid;
        unless ( defined( $pid = fork ) ) {
            $self->warning("Could not fork, cancelling reload");
        }
        unless ($pid) {
            exec( $ENV{APP_BASE_SCRIPT_EXE}, @{ $self->{orig_args} } )
              or $self->error("Couldn't exec: $!");
        }
        $upgrading = time;
        if ( $SIG{ALRM} ) {
            $self->warning("ALRM handler is already defined!");
        }
        $SIG{ALRM} = sub {
            $self->warning("Hot reloading timed out, cancelling");
            kill KILL => $pid;
            undef $upgrading;
        };
        alarm 60;
    };
    {
        my $usr2 = POSIX::SigSet->new( POSIX::SIGUSR2() );
        my $old  = POSIX::SigSet->new();
        POSIX::sigprocmask( POSIX::SIG_UNBLOCK(), $usr2, $old );
    }
    $self->debug("Set handler for USR2");

    return;
}

my $pid;

# kill the old daemon and lock pid file
sub _control_takeover {
    my $self = shift;

    ## no critic (RequireLocalizedPunctuationVars)

    # if it is first generation, when pid file should be already locked in App::Base::Daemon
    if ( $ENV{APP_BASE_DAEMON_GEN} > 1 and $ENV{APP_BASE_DAEMON_PID} != $$ ) {
        kill QUIT => $ENV{APP_BASE_DAEMON_PID};
        if ( $self->getOption('no-pid-file') ) {

            # we don't have pid file, so let's just poke it to death
            my $attempts = 14;
            while ( kill( ( $attempts == 1 ? 'KILL' : 'ZERO' ) => $ENV{APP_BASE_DAEMON_PID} )
                and $attempts-- )
            {
                Time::HiRes::usleep(500_000);
            }
        }
        else {
            local $SIG{ALRM} = sub {
                $self->warn("Couldn't lock the file. Sending KILL to previous generation process");
            };
            alarm 5;

            # We may fail because two reasons:
            # a) previous process didn't exit and still holds the lock
            # b) new process was started and locked pid
            $pid = try { File::Flock::Tiny->lock( $self->pid_file ) };
            unless ($pid) {

                # So let's try killing old process, if after that locking still will fail
                # then probably it is the case b) and we should exit
                kill KILL => $ENV{APP_BASE_DAEMON_PID};
                $SIG{ALRM} = sub { $self->error("Still couldn't lock pid file, aborting") };
                alarm 5;
                $pid = File::Flock::Tiny->lock( $self->pid_file );
            }
            alarm 0;
            $pid->write_pid;
        }
        $self->info( "Process $$, is generation $ENV{APP_BASE_DAEMON_GEN} of " . ref $self );
    }
    $ENV{APP_BASE_DAEMON_PID} = $$;
    return;
}

=head2 $self->handle_shutdown

See L<App::Base::Daemon>

=cut

sub handle_shutdown {
    my $self = shift;
    if ( $self->is_supervisor ) {
        kill TERM => $self->_child_pid if $self->_child_pid;
    }
    else {
        $self->supervised_shutdown;
    }

    return;
}

sub DEMOLISH {
    my $self = shift;
    shutdown $self->supervisor_pipe, 2 if $self->supervisor_pipe;
    return;
}

no Moose::Role;
1;

__END__

=head1 LICENSE AND COPYRIGHT

Copyright (C) 2010-2014 Binary.com

This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.

=cut


text:
using System;
using System.IO;
using System.Text;

namespace Engine.Serialization
{
    public static class BytePacker
    {
        public static void PackUInt8(byte[] buffer, byte val, ref int offset)
        {
            buffer[offset++] = val;
        }

        public static byte UnpackUInt8(byte[] buffer, ref int offset)
        {
            var val = buffer[offset++];
            return val;
        }

        public static void PackUInt16(byte[] buffer, ushort val, ref int offset)
        {
            buffer[offset++] = (byte)(val);
            buffer[offset++] = (byte)(val >> 8);
        }

        public static ushort UnpackUInt16(byte[] buffer, ref int offset)
        {
            ushort val = buffer[offset++];
            val |= (ushort)(buffer[offset++] << 8);
            return val;
        }

        public static void PackUInt32(byte[] buffer, uint val, ref int offset)
        {
            buffer[offset++] = (byte)(val);
            buffer[offset++] = (byte)(val >> 8);
            buffer[offset++] = (byte)(val >> 16);
            buffer[offset++] = (byte)(val >> 24);
        }

        public static uint UnpackUInt32(byte[] buffer, ref int offset)
        {
            uint val = buffer[offset++];
            val |= (uint)buffer[offset++] << 8;
            val |= (uint)buffer[offset++] << 16;
            val |= (uint)buffer[offset++] << 24;
            return val;
        }

        public static void PackUInt64(byte[] buffer, ulong val, ref int offset)
        {
            buffer[offset++] = (byte)(val);
            buffer[offset++] = (byte)(val >> 8);
            buffer[offset++] = (byte)(val >> 16);
            buffer[offset++] = (byte)(val >> 24);
            buffer[offset++] = (byte)(val >> 32);
            buffer[offset++] = (byte)(val >> 40);
            buffer[offset++] = (byte)(val >> 48);
            buffer[offset++] = (byte)(val >> 56);
        }

        public static ulong UnpackUInt64(byte[] buffer, ref int offset)
        {
            ulong val = buffer[offset++];
            val |= (ulong)buffer[offset++] << 8;
            val |= (ulong)buffer[offset++] << 16;
            val |= (ulong)buffer[offset++] << 24;
            val |= (ulong)buffer[offset++] << 32;
            val |= (ulong)buffer[offset++] << 40;
            val |= (ulong)buffer[offset++] << 48;
            val |= (ulong)buffer[offset++] << 56;
            return val;
        }

        public static void PackSInt32(byte[] buffer, int val, ref int offset)
        {
            uint uintValue;
            unsafe
            {
                uintValue = *((uint*)(&val));
            }
            PackUInt32(buffer, uintValue, ref offset);
        }

        public static int UnpackSInt32(byte[] buffer, ref int offset)
        {
            uint uintValue = UnpackUInt32(buffer, ref offset);

            int intValue;
            unsafe
            {
                intValue = *((int*)(&uintValue));
            }
            return intValue;
        }

        public static void PackSInt64(byte[] buffer, long val, ref int offset)
        {
            ulong ulongValue;
            unsafe
            {
                ulongValue = *((ulong*)(&val));
            }
            PackUInt64(buffer, ulongValue, ref offset);
        }

        public static long UnpackSInt64(byte[] buffer, ref int offset)
        {
            ulong ulongValue = UnpackUInt64(buffer, ref offset);
            long longValue;
            unsafe
            {
                longValue = *((long*)(&ulongValue));
            }
            return longValue;
        }

        public static void PackDouble(byte[] buffer, double val, ref int offset)
        {
            ulong longValue;
            unsafe
            {
                longValue = *((ulong*)(&val));
            }
            PackUInt64(buffer, longValue, ref offset);
        }

        public static double UnpackDouble(byte[] buffer, ref int offset)
        {
            ulong ulongValue = UnpackUInt64(buffer, ref offset);

            double doubleValue;
            unsafe
            {
                doubleValue = *((double*)(&ulongValue));
            }
            return doubleValue;
        }

        public static void PackString8(byte[] buffer, string val, ref int offset)
        {
            int len = 0;
            if (val != null)
            {
                len = Encoding.UTF8.GetBytes(val, 0, val.Length, buffer, offset + 1);
                if (len >= 256)
                    throw new ArgumentOutOfRangeException(nameof(val), "Can't pack string with more than 255 bytes");
            }

            buffer[offset++] = (byte)len;
            offset += len;
        }

        public static void PackString8(Stream stream, string val)
        {
            int len = 0;
            if (val == null)
            {
                stream.WriteByte(0);
                return;
            }

            var bytes = Encoding.UTF8.GetBytes(val);
            len = bytes.Length;
            if (len >= 256)
                throw new ArgumentOutOfRangeException(nameof(val), "Can't pack string with more than 255 bytes");

            stream.WriteByte((byte)len);
            stream.Write(bytes, 0, bytes.Length);
        }

        public static void PackString16(byte[] buffer, string val, ref int offset)
        {
            int len = 0;
            if (val != null)
            {
                len = Encoding.UTF8.GetBytes(val, 0, val.Length, buffer, offset + 2);
                if (len >= 65536)
                    throw new ArgumentOutOfRangeException(nameof(val), "Can't pack string with more than 65535 bytes");
            }

            buffer[offset++] = (byte)(len);
            buffer[offset++] = (byte)(len >> 8);
            offset += len;
        }

        public static string UnpackString16(byte[] buffer, ref int offset)
        {
            int len = buffer[offset++];
            len += (buffer[offset++] << 8);
            if (len == 0)
                return null;

            var val = Encoding.UTF8.GetString(buffer, offset, len);
            offset += len;
            return val;
        }

        public static string UnpackString8(byte[] buffer, ref int offset)
        {
            int len = buffer[offset++];
            if (len == 0)
                return null;

            var val = Encoding.UTF8.GetString(buffer, offset, len);
            offset += len;
            return val;
        }

        public static string UnpackString8(Stream stream)
        {
            int len = stream.ReadByte();
            if (len == 0)
                return null;

            var bytes = new byte[len];
            stream.Read(bytes, 0, len);
            return Encoding.UTF8.GetString(bytes, 0, len);
        }
    }
}


text:
Rails.application.routes.draw do
  require 'sidekiq/web'
  authenticate :user do
    mount Sidekiq::Web => '/sidekiq'
  end

  devise_for :users, :controllers => {:omniauth_callbacks => 'users/omniauth_callbacks'}
  devise_scope :user do
    delete 'sign_out', :to => 'devise/sessions#destroy', :as => :destroy_user_session
  end

  root to: 'static#index'
  get 'jems/all' => 'static#show', as: 'show_jem'

  get 'jems/new' => 'jems#new', as: 'new_jem'
  get 'jems/:id' => 'jems#show', as: 'jem'
  get 'jems' => 'jems#index', as: 'jems'
  post 'jems' => 'jems#create'
  get 'jems/:id/edit' => 'jems#edit', as: 'edit_jem'
  patch 'jems/:id' => 'jems#update'
  delete 'jems/:id' => 'jems#destroy', as: 'delete_jem'

  post 'jems/:id/scripts' => 'scripts#create', as: 'new_script'
  get 'jems/:id/scripts/:script_id' => 'scripts#show', as: 'script'
  delete 'script/:id' => 'scripts#destroy', as: 'delete_script'

  get '/auth/github' => 'auth#github', as: 'github_login'
  get '/auth/github/callback' => 'sessions#create', as: 'github_callback'

  post 'create_gem' => 'jems#gemify_jem', as: 'jemify_gem'
  post 'update_gem' => 'jems#gemify_updated_jem'
  get 'percentage_done' => 'jems#percentage_done', as: 'percentage_done'
  get 'get_gem_repo' => 'jems#get_gem_repo'
  post 'update_version' => 'jems#update_version'

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  # root 'welcome#index'

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end


text:
using std::string;
using std::stringstream;
using std::exception;

const double EARTH_RADIUS = 6378137.0;

sGeoCoord::sGeoCoord()
{
	sGeoCoord( 0.0, 0.0, COORDSYS_DDDDDDDD );
}

sGeoCoord::sGeoCoord( const double &lat, const double &lon,
					  const CoordinateSystem &system )
{
	latitude = lat;
	longitude = lon;
	coordSystem = system;
}

sGeoCoord sGeoCoord::To( const CoordinateSystem &system ) const
{
	if( system == coordSystem )
	{
		return GeoCoord( latitude, longitude, coordSystem );
	}

	if( latitude < 0 || longitude < 0 )
	{
		throw exception( "CoordinateSystem doesn't yet support negative values. Sorry." );
	}

	// Move the current coordinates to degree-system
	double lat;
	double lon;
	double degrees;
	double minutes;
	double seconds;

	switch( coordSystem )
	{
		case COORDSYS_DDDDDDDD:
			// Already in correct system
			lat = latitude;
			lon = longitude;
			break;

		case COORDSYS_DDMMMMMM:
			degrees = floor( latitude/100.0 );
			minutes = latitude - degrees*100.0;
			lat = degrees + minutes/60.0;

			degrees = floor( longitude/100.0 );
			minutes = longitude - degrees*100.0;
			lon = degrees + minutes/60.0;
			break;

		case COORDSYS_DDMMSSSS:
			throw exception( "Conversion from DDMMSSSS not implemented yet." );
			break;

		case COORDSYS_METERS:
			throw exception( "Conversion from meters to other systems is not supported. Yet." );
			break;

		default:
			throw exception( "Please, set the coordinate system to be something!" );
			break;
	}

	// Move to target system
	switch( system )
	{
		case CoordinateSystem::COORDSYS_DDDDDDDD:
			// Good, we don't need to do a thing
			break;

		case CoordinateSystem::COORDSYS_DDMMMMMM:
			degrees = floor( lat );
			minutes = (lat - degrees) * 60.0;
			lat = degrees*100.0 + minutes;

			degrees = floor( lon );
			minutes = (lon - degrees) * 60.0;
			lon = degrees*100.0 + minutes;
			break;

		case CoordinateSystem::COORDSYS_DDMMSSSS:
			throw exception( "Conversion to DDMMSSSS not implemented.." );
			break;

		case COORDSYS_METERS:
			throw exception( "Conversion from meters to other systems is not supported. Yet." );
			break;

		default:
			throw exception( "Please, set the coordinate system to be something!" );
			break;
	}

	return GeoCoord( lat, lon, system );
}

string sGeoCoord::String() const
{
	stringstream stream;
	stream << latitude << "," << longitude;
	return stream.str();
}

sGeoCoord sGeoCoord::Offset( const sGeoCoord &offset ) const
{
	GeoCoord pointA( latitude, longitude, coordSystem );
	GeoCoord pointB;

	double dLat; // Latitude difference, used when dealing with meters
	double dLon; // Longitude difference, same use.

	// Make sure we are in the correct system
	pointA = pointA.To( COORDSYS_DDDDDDDD );
	pointB.coordSystem = COORDSYS_DDDDDDDD;

	// Handle cases depending on the given offset's type
	switch( offset.coordSystem )
	{
		case COORDSYS_DDDDDDDD:
			pointB.latitude  = pointA.latitude  + offset.latitude;
			pointB.longitude = pointA.longitude + offset.longitude;
			break;

		case COORDSYS_METERS:
			// This requires math!
			dLat = offset.latitude / EARTH_RADIUS;
			dLon = offset.longitude / (EARTH_RADIUS * cos( M_PI * pointA.latitude / 180.0 ));
			pointB.latitude  = pointA.latitude  + dLat * 180.0/M_PI;
			pointB.longitude = pointA.longitude + dLon * 180.0/M_PI;
			break;

		default:
			throw exception( "Only coordinate offsets of types DDDDDDDD and METERS are accepted!" );
	}

	// Move the point back to the original system
	pointB = pointB.To( coordSystem );
	return pointB;
}


text:
import sublime, sublime_plugin

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from lib.formatter import ViewFormatter

class FormatGherkinCommand(sublime_plugin.TextCommand):

  def run(self, edit):
    ViewFormatter(sublime, self.view).format_view(edit)