text:
<?php

/**
 * Generated 2019-11-17T16:35:02+00:00 16.0.19506.12022
 */
namespace Office365\SharePoint;

use Office365\Runtime\ClientObject;
use Office365\Runtime\ResourcePath;

/**
 * Specifies
 * a push notification subscriber.<229>
 */
class PushNotificationSubscriber extends ClientObject
{
    /**
     * @return string
     */
    public function getCustomArgs()
    {
        if (!$this->isPropertyAvailable("CustomArgs")) {
            return null;
        }
        return $this->getProperty("CustomArgs");
    }
    /**
     * @var string
     */
    public function setCustomArgs($value)
    {
        $this->setProperty("CustomArgs", $value, true);
    }
    /**
     * @return string
     */
    public function getDeviceAppInstanceId()
    {
        if (!$this->isPropertyAvailable("DeviceAppInstanceId")) {
            return null;
        }
        return $this->getProperty("DeviceAppInstanceId");
    }
    /**
     * @var string
     */
    public function setDeviceAppInstanceId($value)
    {
        $this->setProperty("DeviceAppInstanceId", $value, true);
    }
    /**
     * @return string
     */
    public function getLastModifiedTimeStamp()
    {
        if (!$this->isPropertyAvailable("LastModifiedTimeStamp")) {
            return null;
        }
        return $this->getProperty("LastModifiedTimeStamp");
    }
    /**
     * @var string
     */
    public function setLastModifiedTimeStamp($value)
    {
        $this->setProperty("LastModifiedTimeStamp", $value, true);
    }
    /**
     * @return string
     */
    public function getRegistrationTimeStamp()
    {
        if (!$this->isPropertyAvailable("RegistrationTimeStamp")) {
            return null;
        }
        return $this->getProperty("RegistrationTimeStamp");
    }
    /**
     * @var string
     */
    public function setRegistrationTimeStamp($value)
    {
        $this->setProperty("RegistrationTimeStamp", $value, true);
    }
    /**
     * @return string
     */
    public function getServiceToken()
    {
        if (!$this->isPropertyAvailable("ServiceToken")) {
            return null;
        }
        return $this->getProperty("ServiceToken");
    }
    /**
     * @var string
     */
    public function setServiceToken($value)
    {
        $this->setProperty("ServiceToken", $value, true);
    }
    /**
     * @return string
     */
    public function getSubscriberType()
    {
        if (!$this->isPropertyAvailable("SubscriberType")) {
            return null;
        }
        return $this->getProperty("SubscriberType");
    }
    /**
     * @var string
     */
    public function setSubscriberType($value)
    {
        $this->setProperty("SubscriberType", $value, true);
    }
    /**
     * @return User
     */
    public function getUser()
    {
        if (!$this->isPropertyAvailable("User")) {
            $this->setProperty("User", new User($this->getContext(), new ResourcePath("User", $this->getResourcePath())));
        }
        return $this->getProperty("User");
    }
}


text:
package com.intouchapp.todolistapp.activities;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

import com.intouchapp.todolistapp.R;
import com.intouchapp.todolistapp.fragments.TodoListFragment;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new TodoListFragment())
                    .commit();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.doominoo.screens;

import com.doominoo.ScreensManager;
import com.doominoo.VideoPlayer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.geometry.Pos;
import javafx.scene.layout.StackPane;
import javafx.util.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by marcmarquez on 06/02/17.
 */
public class VideoPlayerScreen extends StackPane implements AppScreen {
    private ScreensManager manager;
    private VideoPlayer videoPlayer;
    private VideoPlayerOverlay overlay;
    private String backScreen;
    private static final Logger Log = LoggerFactory.getLogger( VideoPlayer.class);

    public VideoPlayerScreen(ScreensManager manager) throws IOException {
        this.manager = manager;
        initVideoPlayer();
        initVideoPlayerOverlay();
        setMinSize(0,0);
        setAlignment(Pos.TOP_LEFT);
        getChildren().add(videoPlayer.getPane());
        getChildren().add(overlay.getPane());
        settingKeyboardShortcuts();
    }

    private void settingKeyboardShortcuts() {
        setOnKeyReleased(keyEvent -> {
            switch (keyEvent.getCode()) {
                case ADD:
                    videoPlayer.increaseVolume();
                    break;
                case SUBTRACT:
                    videoPlayer.decreaseVolume();
                    break;
            }
        });
    }

    public void setBackScreen(String screen) {
        this.backScreen = screen;
        overlay.setBackScreen(screen);
    }

    public void setScreensManager(ScreensManager screensManager) {
        manager = screensManager;
        videoPlayer.setScreensManager(manager);
        overlay.setScreensManager(manager);
    }

    private void initVideoPlayer() throws IOException {
        videoPlayer = VideoPlayer.getPlayer(this);
    }

    private void initVideoPlayerOverlay() throws IOException {
        overlay = VideoPlayerOverlay.getPlayerOverlay(videoPlayer, manager);
        Timeline autoHideTimeline = new Timeline(new KeyFrame(
                Duration.seconds(10),
                actionEvent -> overlay.hide()
            ));
        autoHideTimeline.play();
        setOnKeyReleased(keyEvent -> {
            autoHideTimeline.play();
        });
        setOnKeyPressed(keyEvent -> {
            autoHideTimeline.stop();
            overlay.show();
        });

        setOnMouseMoved(keyEvent -> {
            autoHideTimeline.stop();
            autoHideTimeline.play();
            overlay.show();
        });

        overlay.setBackScreen(backScreen);

//        setOnMouseReleased(MouseEvent -> {
//            autoHideTimeline.play();
//        });
//        setOnMousePressed(MouseEvent -> {
//            autoHideTimeline.stop();
//            overlay.show();
//        });
    }

    public VideoPlayer getVideoPlayer() {
        return videoPlayer;
    }

    public VideoPlayerOverlay getOverlay() {
        return overlay;
    }
}


text:
import { exists } from 'https://deno.land/std@0.92.0/fs/exists.ts';
import { detect, EOL } from 'https://deno.land/std@0.92.0/fs/eol.ts';
import { ensureDir } from 'https://deno.land/std@0.92.0/fs/ensure_dir.ts';
import { ensureFile } from 'https://deno.land/std@0.92.0/fs/ensure_file.ts';
import { walk, WalkOptions as _WalkOptions } from 'https://deno.land/std@0.92.0/fs/walk.ts';

export type WalkOptions = _WalkOptions;

export {
  detect,
  exists,
  ensureDir,
  ensureFile,
  EOL,
  walk,
};


text:
# Devicon-rails
[![Gem Version](https://badge.fury.io/rb/devicon-rails.svg)](https://badge.fury.io/rb/devicon-rails)
## Installation

Add this line to your application's Gemfile:

```ruby
gem 'devicon-rails'
```

And then execute:

    $ bundle

In your application.css add this line:
```css
/*
 *= require devicon
 *= require devicon-colors
 */
```

## Usage

Go to [devicon.fr](http://devicon.fr/) for more information

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/dezande/devicon-rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.

## License

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


text:
package game;

import ui.playRoom.PlayRoom;
import control.ConfigGen;
import control.Controler;
import control.net.Connecter;
import data.MainData;

public class StartGame {

	public StartGame(String APIToken, String secreatToken, String playerAName, String playerPhoto) {
		// TODO Auto-generated constructor stub

		PlayRoom playRoom = new PlayRoom(APIToken, secreatToken, playerAName, playerPhoto);
		int chessBoardWidth = playRoom.getChessBoard().getChessBoardWidth(), chessBoardHeight = playRoom.getChessBoard().getChessBoardHeight();
		MainData data = new MainData(chessBoardWidth, chessBoardHeight);
		Controler controler = new Controler(chessBoardWidth, chessBoardHeight);
		Connecter connecter = new Connecter(playRoom, data.getChessXYLoc(), APIToken, secreatToken, playerAName, playerPhoto);
		// set observer observable
		controler.getTransferAbsoluteToXY().addObserver(connecter);
		connecter.addObserver(playRoom);
		playRoom.getChatPanel().addObserver(connecter);
		data.getChessBox().addObserver(playRoom.getChessBoard());
		data.getChessBox().addObserver(data.getChessXYLoc());
		playRoom.getChessBoard().addObserver(controler.getTransferAbsoluteToXY());
		// set observer observable end
		data.getChessBox().initChess();
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String APIToken = args[0];
		String secreatToken = args[1];
		String playerAName = args[2];
		String playerPhoto = args[3];

		new StartGame(APIToken, secreatToken, playerAName, playerPhoto);
	}
}


text:
import {user, validate} from './auth';

const DRIVE_API = 'https://www.googleapis.com/drive/v3/';
const DRIVE_UPLOAD_API = 'https://www.googleapis.com/upload/drive/v3/';
const COMMON_FILE_FIELDS = 'kind,id,name,mimeType,appProperties,trashed,version,size';

function makeURL(base: string, defaults: IStringDict, options?: IStringDict): string {
  const url = new URL(base);
  for (const key in defaults) {
    url.searchParams.append(key, defaults[key]);
  }
  if (options) {
    for (const key in options) {
      url.searchParams.append(key, options[key]);
    }
  }
  return url.toString();
}

async function doFetch(url: string, init: RequestInit): Promise<Response> {
  if (!user.token) {
    throw new Error('Not logged in');
  }
  const response = await fetch(url, init);
  if (!response.ok) {
    if (response.status === 401 || response.status === 403) {
      validate(user.token);
    }
    if (response.status === 418) {
      throw new Error(`Alas, the Drive API has become a teapot. Your photos are probably getting wet.`);
    }
    throw new Error(`Couldn't fetch Drive API result: ${response.statusText}`);
  }
  return response;
}

export async function driveRequest(endpoint: string, options?: IStringDict, init: RequestInit = {}) {
  const url = makeURL(`${DRIVE_API}${endpoint}`, {
    access_token: user.token,
  }, options);
  const response = await doFetch(url, init);
  return response.json();
}

async function driveMediaRequest(endpoint: string, options?: IStringDict, init: RequestInit = {}) {
  const url = makeURL(`${DRIVE_API}${endpoint}`, {
    access_token: user.token,
    alt: 'media',
  }, options);
  const response = await doFetch(url, init);
  return response.blob();
}

async function driveUploadRequest(endpoint: string, body: Blob) {
  const url = makeURL(`${DRIVE_UPLOAD_API}${endpoint}`, {
    access_token: user.token,
    uploadType: 'media',
  });
  const response = await doFetch(url, {method: 'PATCH', body});
  return response.json();
}

export async function getFileMeta(fileId: string): Promise<DriveFile> {
  return driveRequest(`files/${fileId}`, {fields: COMMON_FILE_FIELDS});
}

export async function getFileContent(fileId: string): Promise<Blob | null> {
  return driveMediaRequest(`files/${fileId}`);
}

export async function createFileMeta(file: DriveFile): Promise<DriveFile> {
  return driveRequest(`files`, {fields: COMMON_FILE_FIELDS}, {
    body: JSON.stringify(file),
    headers: {'Content-Type': 'application/json'},
    method: 'POST',
  });
}

export async function updateFileMeta(file: DriveFile): Promise<DriveFile> {
  // Only certain fields get written
  const body: DriveFile = {
    appProperties: file.appProperties,
    mimeType: file.mimeType,
    name: file.name,
  };
  return driveRequest(`files/${file.id}`, {fields: COMMON_FILE_FIELDS}, {
    body: JSON.stringify(body),
    headers: {'Content-Type': 'application/json'},
    method: 'PATCH',
  });
}

export async function updateFileContent(fileId: string, body: Blob): Promise<DriveFile> {
  return driveUploadRequest(`files/${fileId}`, body);
}

export async function folderList(folderId: string): Promise<DriveFile[]> {
  let result: DriveFile[] = [];
  const request: IStringDict = {
    corpus: 'user',
    fields: `files(${COMMON_FILE_FIELDS})`,
    q: `'${folderId}' in parents`,
    spaces: 'drive',
  };
  let nextPageToken: string = '';

  do {
    if (nextPageToken) {
      request.nextPageToken = nextPageToken;
    }
    const list: DriveFileList = await driveRequest('files', request);
    result = result.concat(list.files);
    nextPageToken = list.nextPageToken;
  } while (nextPageToken);

  return result;
}


text:
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class sms_report_model extends model {
	public function __construct() {
		$this->db_config = pc_base::load_config('database');
		$this->db_setting = 'default';
		$this->table_name = 'sms_report';
		parent::__construct();
	}
}
?>


text: Run benchmark for single and multi threads on Android devices.


text:
package com.github.fcannizzaro.materialstepper.interfaces;

/**
 * @author Francesco Cannizzaro (fcannizzaro).
 */
public interface Nextable {

    boolean nextIf();

    boolean isOptional();

    void onStepVisible();

    String optional();

    String error();

}


text:
import each from './each'
import scroll from './scroll'

export default {
    each: each,
    scroll: scroll
}


text:
/**
 * @class Ext.menu.TextItem
 * @extends Ext.menu.BaseItem
 * Adds a static text string to a menu, usually used as either a heading or group separator.
 * @constructor
 * Creates a new TextItem
 * @param {Object/String} config If config is a string, it is used as the text to display, otherwise it
 * is applied as a config object (and should contain a <tt>text</tt> property).
 */
Ext.menu.TextItem = function(cfg){
    if(typeof cfg == 'string'){
        cfg = {text: cfg}
    }
    Ext.menu.TextItem.superclass.constructor.call(this, cfg);
};

Ext.extend(Ext.menu.TextItem, Ext.menu.BaseItem, {
    /**
     * @cfg {String} text The text to display for this item (defaults to '')
     */
    /**
     * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
     */
    hideOnClick : false,
    /**
     * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
     */
    itemCls : "x-menu-text",

    // private
    onRender : function(){
        var s = document.createElement("span");
        s.className = this.itemCls;
        s.innerHTML = this.text;
        this.el = s;
        Ext.menu.TextItem.superclass.onRender.apply(this, arguments);
    }
});


text:
import java.util.*;

// https://www.hackerrank.com/challenges/sparse-arrays
public class Solution {
    public static Boolean containsString(String s, String substring) {
        for (int j = 0, k = 0; j < s.length() && k < substring.length(); j++) {
            int len = 0;
        	while (k < substring.length() && j < s.length() && s.charAt(j) == substring.charAt(k)) {
                len++;
                k++;
                j++;
            }
            if (len == substring.length())
            	return true;
        }
        return false;
    }

    public static int countOcurences(String[] strings, String query) {
        int count = 0;
        for(String s : strings)
            //if (containsString(s, query))	   // implementation for substrings
        	if (s.equals(query))
                count++;
        return count;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        String[] strings = new String[N];
        for (int i = 0; i < N; i++)
            strings[i] = in.next();

        int Q = in.nextInt();
        String[] queries = new String[Q];
        for (int i = 0; i < Q; i++)
            queries[i] = in.next();

        for (String q : queries) {
            // count the number of occurences of each query in the list of strings
            int result = countOcurences(strings, q);
            System.out.println(result);
        }

        in.close();
    }
}


text:
package com.b2international.snowowl.snomed.reasoner;

import com.b2international.index.Index;
import com.b2international.snowowl.core.Repository;
import com.b2international.snowowl.core.RepositoryManager;
import com.b2international.snowowl.core.config.SnowOwlConfiguration;
import com.b2international.snowowl.core.setup.DefaultBootstrapFragment;
import com.b2international.snowowl.core.setup.Environment;
import com.b2international.snowowl.core.setup.PostRunCapableBootstrapFragment;
import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator;
import com.b2international.snowowl.snomed.datastore.config.SnomedClassificationConfiguration;
import com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration;
import com.b2international.snowowl.snomed.reasoner.classification.ClassificationTracker;
import com.b2international.snowowl.snomed.reasoner.external.SnomedExternalClassificationService;

/**
 * @since 7.0
 */
public final class SnomedReasonerBootstrap extends DefaultBootstrapFragment implements PostRunCapableBootstrapFragment {

	@Override
	public void postRun(final SnowOwlConfiguration configuration, final Environment env) {

		if (env.isServer() || env.isEmbedded()) {

			final RepositoryManager repositoryManager = env.service(RepositoryManager.class);
			final Repository repository = repositoryManager.get(SnomedDatastoreActivator.REPOSITORY_UUID);
			final Index repositoryIndex = repository.service(Index.class);

			final SnomedClassificationConfiguration classificationConfig = configuration
					.getModuleConfig(SnomedCoreConfiguration.class).getClassificationConfig();
			final ClassificationTracker classificationTracker = new ClassificationTracker(repositoryIndex,
					classificationConfig.getMaxReasonerRuns(), classificationConfig.getCleanupInterval());

			env.services().registerService(ClassificationTracker.class, classificationTracker);

			if (classificationConfig.isExternalClassificationServiceConfigured()) {
				SnomedExternalClassificationService externalClassificationService = new SnomedExternalClassificationService(classificationConfig);
				env.services().registerService(SnomedExternalClassificationService.class, externalClassificationService);
			}

		}

	}
}


text:
maintainer       'Opscode, Inc.'
maintainer_email 'cookbooks@opscode.com'
license          'Apache 2.0'
description      'This cookbook is used with test-kitchen to test the parent, rabbitmq cookbook.'
version          '1.0.0'

depends           'rabbitmq'


text:
package im.toss.sample;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

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

import im.toss.delegationadapter.ItemViewHolder;
import im.toss.delegationadapter.ListItemDelegationAdapter;
import im.toss.delegationadapter.ViewBinder;
import im.toss.delegationadapter.ViewBinderWithoutPayloads;
import im.toss.sample.model.Advertisement;
import im.toss.sample.model.Cat;
import im.toss.sample.model.DisplayableItem;
import im.toss.sample.model.Dog;
import im.toss.sample.model.Gecko;
import im.toss.sample.model.Snake;

public class MainJavaActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_simple_main);

    RecyclerView rv = (RecyclerView) findViewById(R.id.recyclerView);
    rv.setLayoutManager(new LinearLayoutManager(this));

    AnimalAdapter adapter = new AnimalAdapter();
    adapter.setItems(getAnimals());

    rv.setAdapter(adapter);
  }

  class AnimalAdapter extends ListItemDelegationAdapter<DisplayableItem> {

    AnimalAdapter() {

      addDelegate(createDelegateBuilder(Advertisement.class)
          .layout(R.layout.item_advertisement)
          .build());

      addDelegate(createDelegateBuilder(Cat.class)
          .layout(R.layout.item_cat)
          .binder(new ViewBinder<Cat>() {
            @Override
            public void onBindViewHolder(ItemViewHolder<Cat> vh, @NonNull Cat cat, @NonNull List<Object> payloads) {
              vh.getView(R.id.name, TextView.class).setText(cat.getName());
            }
          })
          .build());

      addDelegate(createDelegateBuilder(Dog.class)
          .layout(R.layout.item_dog)
          .binder(new ViewBinderWithoutPayloads<Dog>() {
            @Override
            public void onBindViewHolder(ItemViewHolder<Dog> vh, @NonNull Dog dog) {
              vh.getView(R.id.name, TextView.class).setText(dog.getName());
            }
          })
          .build());

      addDelegate(createDelegateBuilder(Gecko.class)
          .layout(R.layout.item_gecko)
          .binder(new ViewBinder<Gecko>() {
            @Override
            public void onBindViewHolder(ItemViewHolder<Gecko> vh, @NonNull Gecko gecko, @NonNull List<Object> payloads) {
              vh.getView(R.id.name, TextView.class).setText(gecko.getName());
              vh.getView(R.id.race, TextView.class).setText(gecko.getRace());
            }
          })
          .build());

      addDelegate(createDelegateBuilder(Snake.class)
          .layout(R.layout.item_snake)
          .binder(new ViewBinder<Snake>() {
            @Override
            public void onBindViewHolder(ItemViewHolder<Snake> vh, @NonNull Snake snake, @NonNull List<Object> payloads) {
              vh.getView(R.id.name, TextView.class).setText(snake.getName());
              vh.getView(R.id.race, TextView.class).setText(snake.getRace());
            }
          })
          .build());

      setFallbackDelegate(createDelegateBuilder(DisplayableItem.class)
          .layout(android.R.layout.simple_list_item_1)
          .binder(new ViewBinder<DisplayableItem>() {
            @Override
            public void onBindViewHolder(ItemViewHolder<DisplayableItem> vh, @NonNull DisplayableItem item, @NonNull List<Object> payloads) {
              vh.getView(android.R.id.text1, TextView.class).setText(item.toString());
            }
          })
          .build());
    }
  }

  private List<DisplayableItem> getAnimals() {
    List<DisplayableItem> animals = new ArrayList<>();

    animals.add(new Cat("American Curl"));
    animals.add(new Cat("Baliness"));
    animals.add(new Cat("Bengal"));
    animals.add(new Cat("Corat"));
    animals.add(new Cat("Manx"));
    animals.add(new Cat("Nebelung"));
    animals.add(new Dog("Aidi"));
    animals.add(new Dog("Chinook"));
    animals.add(new Dog("Appenzeller"));
    animals.add(new Dog("Collie"));
    animals.add(new Snake("Mub Adder", "Adder"));
    animals.add(new Snake("Texas Blind Snake", "Blind snake"));
    animals.add(new Snake("Tree Boa", "Boa"));
    animals.add(new Gecko("Fat-tailed", "Hemitheconyx"));
    animals.add(new Gecko("Stenodactylus", "Dune Gecko"));
    animals.add(new Gecko("Leopard Gecko", "Eublepharis"));
    animals.add(new Gecko("Madagascar Gecko", "Phelsuma"));
    animals.add(new Advertisement());
    animals.add(new Advertisement());
    animals.add(new Advertisement());
    animals.add(new Advertisement());
    animals.add(new Advertisement());

    Collections.shuffle(animals);
    return animals;
  }

}


text:
@interface UIFont (Helpers)
+ (UIFont *)italicFontOfSize:(CGFloat)size;
@end


text:
package org.avaje.metric.eclipse.enhancer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import org.avaje.metric.eclipse.enhancer.ui.preferences.PreferenceConstants;

import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * The activator controlling the plug-in life cycle
 */
public class EnhancerPlugin extends AbstractUIPlugin
{
    // The plug-in ID
    public static final String PLUGIN_ID = "org.avaje.metric.eclipse.enhancer";

    // The shared instance
    private static EnhancerPlugin plugin;

    public EnhancerPlugin()
    {
    }

    public static PrintStream createTransformLog()
    {
        IPath path = plugin.getStateLocation().addTrailingSeparator().append("enhance.log");

        try
        {
            OutputStream outputStream = null;

            if (getEnhanceDebugLevel() > 0)
            {
                File logFile = path.toFile();
                if (!logFile.exists())
                {
                    logFile.createNewFile();
                }

                outputStream = new FileOutputStream(logFile, true);
            }
            else
            {
                outputStream = new OutputStream()
                {
                    @Override public void write(int b)
                    {
                        // null writer
                    }
                };
            }

            return new PrintStream(outputStream);

        }
        catch (IOException e)
        {
            logError("Error creating log file [" + path.toString() + "]", e);
            return System.out;
        }
    }

    public static int getDebugLevel()
    {
        if (plugin == null)
        {
            return 0;
        }

        IPreferenceStore store = plugin.getPreferenceStore();
        return store.getInt(PreferenceConstants.P_PLUGIN_DEBUG_LEVEL);
    }

    /**
     * Returns the shared instance
     *
     * @return the shared instance
     */
    public static EnhancerPlugin getDefault()
    {
        return plugin;
    }

    public static int getEnhanceDebugLevel()
    {
        if (plugin == null)
        {
            return 0;
        }

        IPreferenceStore store = plugin.getPreferenceStore();
        return store.getInt(PreferenceConstants.P_ENHANCE_DEBUG_LEVEL);
    }

    /**
     * Returns an image descriptor for the image file at the given plug-in relative path
     *
     * @param path the path
     * @return the image descriptor
     */
    public static ImageDescriptor getImageDescriptor(String path)
    {
        return imageDescriptorFromPlugin(PLUGIN_ID, path);
    }

    public static void logError(String msg, Exception e)
    {
        ILog log = plugin.getLog();
        log.log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, msg, e));
    }

    public static void logInfo(String msg)
    {
        logInfo(msg, null);
    }

    public static void logInfo(String msg, Exception e)
    {
        ILog log = plugin.getLog();
        log.log(new Status(IStatus.INFO, PLUGIN_ID, IStatus.OK, msg, e));
    }

    @Override public void start(BundleContext context) throws Exception
    {
        super.start(context);
        plugin = this;

    }

    @Override public void stop(BundleContext context) throws Exception
    {
        plugin = null;
        super.stop(context);
    }
}


text:
<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\ItemContrato;
use Illuminate\Http\Request;
use Session;

class ItemContratoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $keyword = $request->get('search');
        $perPage = 25;

        if (!empty($keyword)) {
            $itemcontrato = ItemContrato::where('item', 'LIKE', "%$keyword%")
				->orWhere('exercicio', 'LIKE', "%$keyword%")
				->orWhere('descricao', 'LIKE', "%$keyword%")
				->orWhere('quantidade', 'LIKE', "%$keyword%")
				->orWhere('unidade_medida', 'LIKE', "%$keyword%")
				->orWhere('valor_unitario', 'LIKE', "%$keyword%")
				->orWhere('valor_total', 'LIKE', "%$keyword%")
				->orWhere('contrato_id', 'LIKE', "%$keyword%")
				->paginate($perPage);
        } else {
            $itemcontrato = ItemContrato::paginate($perPage);
        }

        return view('item-contrato.index', compact('itemcontrato'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\View\View
     */
    public function create($contrato_id)
    {
        return view('item-contrato.create', compact('contrato_id'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store($contrato_id, Request $request)
    {

        $requestData = $request->all();

        $ultimo_item = ItemContrato::where('contrato_id', $contrato_id)->get()->last();

        if($ultimo_item != null)
            $requestData = array_add($requestData, 'item', $ultimo_item->item + 1);
        else
            $requestData = array_add($requestData, 'item', 1);

        $requestData = array_add($requestData, 'contrato_id', $contrato_id);

        ItemContrato::create($requestData);

        \Session::flash('flash_message',[
            'msg'=>"ItemContrato cadastrado com sucesso!",
            'class'=>"alert-success"
        ]);

        return redirect()->route('contratos.show', $contrato_id);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function show($contrato_id, $id)
    {
        $itemcontrato = ItemContrato::findOrFail($id);

        return view('item-contrato.show', compact('itemcontrato', 'contrato_id'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function edit($contrato_id, $id)
    {
        $itemcontrato = ItemContrato::findOrFail($id);

        return view('item-contrato.edit', compact('itemcontrato', 'contrato_id'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update($contrato_id, $id, Request $request)
    {

        $requestData = $request->all();

        $itemcontrato = ItemContrato::findOrFail($id);
        $itemcontrato->update($requestData);

        \Session::flash('flash_message',[
            'msg'=>"ItemContrato atualizado com sucesso!",
            'class'=>"alert-success"
        ]);

        return redirect()->route('contratos.show', $contrato_id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function destroy($contrato_id, $id)
    {
        ItemContrato::destroy($id);

        \Session::flash('flash_message',[
            'msg'=>"ItemContrato excluído com sucesso!",
            'class'=>"alert-success"
        ]);

        return redirect()->route('contratos.show', $contrato_id);
    }
}


text:
@class NSManagedObjectModel;
@class NSManagedObjectContext;

NS_ASSUME_NONNULL_BEGIN

extern NSString * const SQLiteStackDidConfiguredNotification;

@interface SQLiteStack : NSObject

+ (instancetype)defaultStack;
- (void)configureStackWithModelName:(NSString *)modelName
                           inBundle:(NSBundle *)bundle
                       withStoreURL:(NSURL *)storeURL
                     withCompletion:(void(^ _Nullable)(void))completion;

@property (strong, nonatomic, readonly) NSManagedObjectModel *objectModel;
@property (strong, nonatomic, readonly) NSManagedObjectContext *mainContext;

- (NSManagedObjectContext *)privateContext;

@end

NS_ASSUME_NONNULL_END


text:
Compiling/running unit tests
------------------------------------

Unit tests will be automatically compiled if dependencies were met in `./configure`
and tests weren't explicitly disabled.

After configuring, they can be run with `make check`.

To run the vivod tests manually, launch `src/test/test_vivo`.

To add more vivod tests, add `BOOST_AUTO_TEST_CASE` functions to the existing
.cpp files in the `test/` directory or add new .cpp files that
implement new BOOST_AUTO_TEST_SUITE sections.

To run the vivo-qt tests manually, launch `src/qt/test/test_vivo-qt`

To add more vivo-qt tests, add them to the `src/qt/test/` directory and
the `src/qt/test/test_main.cpp` file.


text:
require 'spec_helper'
require_relative '../../../../apps/editor/views/document/new_associated_document'

describe Editor::Views::Document::NewAssociatedDocument do
  let(:exposures) { Hash[foo: 'bar'] }
  let(:template)  { Lotus::View::Template.new('apps/editor/templates/document/new_associated_document.html.slim') }
  let(:view)      { Editor::Views::Document::NewAssociatedDocument.new(template, exposures) }
  let(:rendered)  { view.render }

  it "exposes #foo" do
    view.foo.must_equal exposures.fetch(:foo)
  end
end


text:
  <TITLE>
  EMBOSS
  </TITLE>

NUCLEIC CODON USAGE

Codon usage analysis

Program name	Description

cai

Calculate codon adaptation index

chips

Calculate Nc codon usage statistic

codcmp

Codon usage table comparison

codcopy

Copy and reformat a codon usage table

cusp

Create a codon usage table from nucleotide sequence(s)

syco

Draw synonymous codon usage statistic plot for a nucleotide sequence


text:
require "mongoid/validations/associated"
require "mongoid/validations/uniqueness"

I18n.load_path << File.join(
  File.dirname(__FILE__), "validations", "locale", "en.yml"
)

module Mongoid #:nodoc:
  # This module provides additional validations that ActiveModel does not
  # provide: validates_associated and validates_uniqueness_of
  module Validations
    extend ActiveSupport::Concern
    included do
      include ActiveModel::Validations
    end

    module ClassMethods #:nodoc:
      # Validates whether or not an association is valid or not. Will correctly
      # handle has one and has many associations.
      #
      # Example:
      #
      #   class Person
      #     include Mongoid::Document
      #     embeds_one :name
      #     embeds_many :addresses
      #
      #     validates_associated :name, :addresses
      #   end
      def validates_associated(*args)
        validates_with(AssociatedValidator, _merge_attributes(args))
      end

      # Validates whether or not a field is unique against the documents in the
      # database.
      #
      # Example:
      #
      #   class Person
      #     include Mongoid::Document
      #     field :title
      #
      #     validates_uniqueness_of :title
      #   end
      def validates_uniqueness_of(*args)
        validates_with(UniquenessValidator, _merge_attributes(args))
      end
    end
  end
end


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import router from './components'
import reducer from './reducer'
import rootSagas from './saga'
import history from 'libs/history';
import configureStore from './stores/configureStore'
import { AppContainer } from 'react-hot-loader';
import Root from './Root';

const store = configureStore(reducer);
store.runSaga(rootSagas);

const render = (Component, router) => {
  ReactDOM.render(
    <AppContainer>
      <Component store={store} router={router} />
    </AppContainer>,
    document.getElementById('root')
  )
}

render(Root, router);

if (module.hot) {
  module.hot.accept('./Root', () => {
    render(Root, router);
  });
  module.hot.accept('./components', () => {
    render(Root, router);
  });
  module.hot.accept("./reducer", () => {
    store.replaceReducer(reducer);
  });
  module.hot.accept("./saga", () => {
    store.runSaga(rootSagas);
  });
}


text:
Ext.define('PushDemo.store.Products', {
	extend: 'Ext.data.Store',
	model: 'PushDemo.model.Product',
	autoLoad: true,
	//remoteSort: true,
	//pageSize: 15,

	proxy: {
		type: 'ajax',
		api: {
			create: 'include/create.php',
			read: 'include/load.php',
			update: 'include/update.php',
			destroy: 'include/destroy.php'
		},
		reader: {
			type: 'json',
			root: 'data',
			successProperty: 'success',
			totalProperty: 'total'
		},
		writer: {
			encode: true,
			root: 'data'
		}
	}
});


text:
class TemperaturesController < ApplicationController
  protect_from_forgery

  def create
    @temperature = Temperature.new(temperature_params)
    @temperature.save
    render :show
  end

  def show
    @temperature = Temperature.find(params[:id])
  end

  private
  def temperature_params
    params.permit(:value, :room_id)
  end
end


text:
/*global describe, beforeEach, it*/
'use strict';
var assert = require('assert');

describe('smartgamer', function () {
  it('can be imported without blowing up', function () {
    var smartgamer= require('..');
    assert(smartgamer !== undefined);
  });
});

describe('init', function () {
	it('can be initialized without a smartgame', function () {
    var smartgamer= require('..');
		var gamer = smartgamer();

		assert(typeof gamer === 'object');
	});
});

describe('init', function () {
	it('can be initialized with a smartgame', function () {
		var fs = require('fs');
		var smartgamer = require('..');
		var sgf = require('smartgame');
		var simpleExample = fs.readFileSync('./example/sgf/simple_example.sgf', { encoding: 'utf8' });

		var gamer = smartgamer(sgf.parse(simpleExample));

		assert(typeof gamer === 'object');
	});
});

describe('load', function () {
	it('can load a smartgame after init', function () {
		var fs = require('fs');
		var smartgamer = require('..');
		var sgf = require('smartgame');
		var simpleExample = fs.readFileSync('./example/sgf/simple_example.sgf', { encoding: 'utf8' });

		var gamer = smartgamer();

		gamer.load(sgf.parse(simpleExample));

		assert(typeof gamer.getSmartgame() === 'object');
	});
});


text:
Develop: [![Build Status](https://travis-ci.org/bionikspoon/pivotal-github-status.svg?branch=develop)](https://travis-ci.org/bionikspoon/pivotal-github-status)

Master: [![Build Status](https://travis-ci.org/bionikspoon/pivotal-github-status.svg?branch=master)](https://travis-ci.org/bionikspoon/pivotal-github-status)

## Setup

### Part 1: Heroku (or anywhere)

* Launch Service
* Set the following env variables:
  - `GITHUB_ACCESS_TOKEN` - https://github.com/blog/1509-personal-api-tokens
    - _note_ - needs `repo` access
  - `PIVOTAL_ACCESS_TOKEN` - https://www.pivotaltracker.com/help/articles/api_token/
  - `SECRET_KEY` - use a url safe random string

### Part 2: Pivotal

* Go to your project -> settings -> webhooks: `pivotaltracker.com/projects/<project_id>/webhooks`
* Add a url pointing to your service with the following schema: `/pivotal/<string:owner>/<string:repo>/<string:secret_key>`
  - example: `https://62f143e5.ngrok.io/pivotal/bionikspoon/test_repo/secret_key`
* Repeat for each project on your team.

### Part 3: Github

* Go to your project -> settings -> webhooks: `github.com/<owner>/<repo>/settings/hooks`
* Add a url pointing to your service with the following schema: `/github/<string:secret_key>`
  - example: `https://62f143e5.ngrok.io/github/secret_key`
  - Settings:
    - content type: `application/json`
    - events: "let me select individual events" -> uncheck each -> check "Pull Request"
    - __SUPER IMPORTANT__: ^^.  Server untested with other event types. No idea what will happen.

      ![Github Screen 00](docs/imgs/github-screen-00.png)

      `...`

      ![Github Screen 01](docs/imgs/github-screen-01.png)

### Part 4: Done

:+1:

## Planning Docs

### Problem Statement

* Information from Pivotal doesn't translate to GithHub
* __Pain Point__: need to know when to merge PRs (status:accepted)

### Solution

* [x] Service that tags Github PRs with current Pivotal Status
* [ ] __Bonus Points__: Track sprints as mile stones
* [ ] __Bonus Points__: Turn this solution into a deployable SaaS
* [ ] __Bonus Points__: For tagging position (ex: story is above "must have for release line")

### Implementation

* [x] A service will listen to Pivotal hooks for changes and use Github's API to make changes
* [x] __Challenge__: Connecting pivotal stories to Github PRs
  - Solution: Searches PR title for story id
  - Example: "Create user profile  page [Fixes #1234567890]" finds story id: `#1234567890`
* [x] __Challenge__: Service will be managing GitHub labels, it shouldn't remove other labels
  - Solution: Service manages the following labels: `unstarted`, `started`, `finished`, `delivered`, `accepted`, `rejected` -- ignoring other labels.
* [x] __Challenge__: One Pull Request -> many stories
* [ ] __Challenge__: Service should proactively notify users about failures
  - For now, there's good logging
* [x] __Challenge__: __\*Security\*__. Strangers shouldn't be able to send fake data to the service.
  - Two part solution:
    1. Secret key passed by url guards the service.
    2. The service refetches data from Pivotal -- effectively data sent by webhook isn't trusted.
  - TODO: Figure out url whitelisting. (Need help)
* [x] __Challenge__: New PRs & Changes to PRs.  By only listening to Pivotal events, these PR's could get out of sync.  No Good!
  - Solution: Listen to GitHub PR events!


text:
package hrider.ui.design;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ResizeableTableHeader extends JTableHeader implements TableModelListener {

    //region Variables
    /**
     * If true, auto resizing of columns when
     * the TableModel invokes a tableChanged event
     * is enabled. The default is false.
     */
    protected boolean autoResizingEnabled;

    /**
     * If true, resizing of columns will
     * also take the width of header cells
     * into account. The default is false.
     */
    protected boolean includeHeaderWidth;
    //endregion

    //region Constructor
    /**
     * Constructs a {@code ResizeableTableHeader} with a default
     * {@code TableColumnModel}.
     */
    public ResizeableTableHeader() {
        this(null);
    }

    /**
     * Constructs a {@code ResizeableTableHeader} which is initialized with
     * {@code cm} as the column model.  If {@code cm} is
     * {@code null} this method will initialize the table header
     * with a default {@code TableColumnModel}.
     *
     * @param cm the column model for the table
     */
    public ResizeableTableHeader(TableColumnModel cm) {
        super(cm);

        this.autoResizingEnabled = false;
        this.includeHeaderWidth = false;

        addMouseListener(new ResizingMouseAdapter());
    }
    //endregion

    //region Public Methods
    /**
     * Sets the table associated with this header.
     * Also adds a TableModelListener to the table's
     * TableModel to allow resizing of columns if
     * data of table changed.
     *
     * @param table the new table
     */
    @Override
    public void setTable(JTable table) {
        JTable old = this.table;
        if (table != old) {
            if (old != null && old.getModel() != null) {
                old.getModel().removeTableModelListener(this);
            }
            if (table != null && table.getModel() != null) {
                table.getModel().addTableModelListener(this);
            }
        }
        this.table = table;
        firePropertyChange("table", old, table);
    }

    /**
     * Sets whether columns are resized on table model events.
     *
     * @param    autoResizingEnabled        true if columns are resized automatically
     * @see    #getAutoResizingEnabled
     */
    public void setAutoResizingEnabled(boolean autoResizingEnabled) {
        boolean old = this.autoResizingEnabled;
        this.autoResizingEnabled = autoResizingEnabled;
        firePropertyChange("autoResizingEnabled", old, autoResizingEnabled);
    }

    /**
     * Returns true if auto resizing is enabled.
     *
     * @return the {@code autoResizingEnabled} property
     * @see    #setAutoResizingEnabled
     */
    public boolean getAutoResizingEnabled() {
        return this.autoResizingEnabled;
    }

    /**
     * Sets whether the header's width are included on calculation
     *
     * @param    includeHeaderWidth        true if the headers are included
     * @see    #getIncludeHeaderWidth
     */
    public void setIncludeHeaderWidth(boolean includeHeaderWidth) {
        boolean old = this.includeHeaderWidth;
        this.includeHeaderWidth = includeHeaderWidth;
        firePropertyChange("includeHeaderWidth", old, this.autoResizingEnabled);
    }

    /**
     * Returns true, if the header's width are
     *
     * @return the {@code setIncludeHeaderWidth} property
     * @see    #setIncludeHeaderWidth
     */
    public boolean getIncludeHeaderWidth() {
        return this.includeHeaderWidth;
    }

    /**
     * Resizes the given column to fit all its content.
     *
     * @param column The {@code TableColumn} to resize.
     */
    public void resizeColumn(TableColumn column) {
        if (column != null) {
            adjustColumnWidth(column);
        }
    }

    /**
     * Resizes all columns to fit all their content.
     */
    public void resizeAllColumns() {
        for (int col = 0 ; col < this.table.getColumnCount() ; col++) {
            TableColumn column = this.table.getColumnModel().getColumn(col);
            adjustColumnWidth(column);
        }
    }

    /**
     * Sets preferred width, the minimum and maximum width for a given column.
     * The minimum and maximum widths are the bounds for the preferred width.
     * If the preferred width is not in the region of minmum and maximum,
     * it will be adjusted.
     * Also the user cannot resize columns out of this bounds by moving the edge
     * or double clicking it.
     * If a width is set to -1, no change is made to this value.
     *
     * @param column         The {@code TableColumn} to change.
     * @param preferredWidth The preferred width of the column.
     * @param minWidth       The minimum width of the column.
     * @param maxWidth       The maximum width of the column.
     * @see #setAllColumnWidths(int preferredWidth, int minWidth, int maxWidth)
     */
    public static void setColumnWidths(TableColumn column, int preferredWidth, int minWidth, int maxWidth) {
        if (column != null) {
            if (preferredWidth != -1) {
                column.setPreferredWidth(preferredWidth);
            }
            if (minWidth != -1) {
                column.setMinWidth(minWidth);
            }
            if (maxWidth != -1) {
                column.setMaxWidth(maxWidth);
            }
        }
    }

    /**
     * Sets preferred width, the minimum and maximum width for all columns.
     * See setColumnWidth() for further details.
     *
     * @param preferredWidth The preferred width of the column.
     * @param minWidth       The minimum width of the column.
     * @param maxWidth       The maximum width of the column.
     * @see #setColumnWidths(TableColumn column, int preferredWidth, int minWidth, int maxWidth)
     */
    public void setAllColumnWidths(int preferredWidth, int minWidth, int maxWidth) {
        for (int col = 0 ; col < this.table.getColumnCount() ; col++) {
            TableColumn column = this.table.getColumnModel().getColumn(col);
            setColumnWidths(column, preferredWidth, minWidth, maxWidth);
        }
    }

    /**
     * Listen for table model events from table model.
     * If new data is inserted, only determine the width
     * of new cell and adjust column width, if necessary.
     * If data is deleted or updated, call {@code resizeAllColumns()}.
     *
     * @param e The {@code TableModelEvent}
     */
    @Override
    public void tableChanged(TableModelEvent e) {
        if (this.autoResizingEnabled) {
            if (e.getType() == TableModelEvent.DELETE) {
                resizeAllColumns();
            }
            else {
                // for performance reason only adjust width, if
                // one of the new cell is greater than the column width.
                for (int col = 0 ; col < this.table.getColumnCount() ; col++) {
                    TableColumn column = this.table.getColumnModel().getColumn(col);
                    if (canResize(column)) {
                        int width = column.getPreferredWidth();
                        for (int row = e.getFirstRow() ; row <= e.getLastRow() && row < this.table.getRowCount() && row != -1 ; row++) {
                            TableCellRenderer renderer = this.table.getCellRenderer(row, col);
                            Component comp = renderer.getTableCellRendererComponent(this.table, this.table.getValueAt(row, col), false, false, row, col);
                            width = Math.max(width, comp.getPreferredSize().width + this.table.getColumnModel().getColumnMargin());
                        }
                        column.setPreferredWidth(width);
                    }
                }
            }

        }

    }
    //endregion

    //region Private Methods
    /**
     * Adjust the width of a column to fit all cells.
     *
     * @param column The column to adjust.
     */
    private void adjustColumnWidth(TableColumn column) {

        int width = 0;
        int col = this.table.convertColumnIndexToView(column.getModelIndex());

        // Determine width of header.
        if (this.includeHeaderWidth) {
            TableCellRenderer headerRenderer = column.getHeaderRenderer();
            if (headerRenderer == null) {
                headerRenderer = this.table.getTableHeader().getDefaultRenderer();
            }
            Component headerComp = headerRenderer.getTableCellRendererComponent(this.table, column.getHeaderValue(), false, false, 0, col);
            width = Math.max(width, headerComp.getPreferredSize().width);
        }

        // Determine max width of cells.
        for (int row = 0 ; row < this.table.getRowCount() ; row++) {
            TableCellRenderer renderer = this.table.getCellRenderer(row, col);
            Component comp = renderer.getTableCellRendererComponent(this.table, this.table.getValueAt(row, col), false, false, row, col);
            width = Math.max(width, comp.getPreferredSize().width);
        }
        // add column margins
        width += this.table.getColumnModel().getColumnMargin();

        column.setPreferredWidth(width);
    }

    /**
     * Returns true, if resizing for the table header is allowed and
     * if the column is resizeable.
     *
     * @param column The column to check
     * @return True, if the column is resizeable, otherwise false.
     */
    private boolean canResize(TableColumn column) {
        return column != null && getResizingAllowed() && column.getResizable();
    }

    /**
     * Gets the the column that will be resized for a specific point.
     * This method only return a column, if the point is within
     * the last 3 pixels + 3 pixels of next column. Otherwise it returns null.
     *
     * @param p The point to check, if we are in the resizing area.
     * @return The resizing column, if the point is in the resizing area,
     *         otherwise null.
     * @see #getResizingColumn(Point p, int column)
     */
    private TableColumn getResizingColumn(Point p) {
        return getResizingColumn(p, columnAtPoint(p));
    }

    /**
     * @see #getResizingColumn(Point p)
     */
    private TableColumn getResizingColumn(Point p, int column) {
        if (column == -1) {
            return null;
        }
        Rectangle r = getHeaderRect(column);
        r.grow(-3, 0);
        if (r.contains(p)) {
            return null;
        }
        int midPoint = r.x + r.width / 2;
        int columnIndex;
        if (getComponentOrientation().isLeftToRight()) {
            columnIndex = p.x < midPoint ? column - 1 : column;
        }
        else {
            columnIndex = p.x < midPoint ? column : column - 1;
        }
        if (columnIndex == -1) {
            return null;
        }
        return getColumnModel().getColumn(columnIndex);
    }

    /**
     * Listener that will resize a column, if a double click
     * in a resizing area is performed.
     */
    private class ResizingMouseAdapter extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
                TableColumn resizingColumn = getResizingColumn(e.getPoint());
                if (canResize(resizingColumn)) {
                    adjustColumnWidth(resizingColumn);
                }
            }
        }
    }
    //endregion
}


text:
<?php
require __DIR__ . '/../routes/monitoring.php';
require __DIR__ . '/../routes/api.php';


text:
<?php
namespace Oro\Bundle\EmailBundle\Form\EventListener;

use Doctrine\ORM\EntityManager;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Oro\Bundle\EmailBundle\Entity\Repository\EmailTemplateRepository;
use Oro\Bundle\NotificationBundle\Event\Handler\EmailNotificationHandler;

class BuildTemplateFormSubscriber implements EventSubscriberInterface
{
    /**
     * @var EntityManager
     */
    private $em;

    /**
     * Form factory.
     *
     * @var FormFactoryInterface
     */
    private $factory;

    /**
     * Constructor.
     *
     * @param EntityManager $em
     * @param FormFactoryInterface $factory
     */
    public function __construct(EntityManager $em, FormFactoryInterface $factory)
    {
        $this->em = $em;
        $this->factory = $factory;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SET_DATA => 'preSetData',
            FormEvents::PRE_SUBMIT   => 'preSubmit'
        );
    }

    /**
     * Removes or adds a template field based on the entity set.
     *
     * @param FormEvent $event
     */
    public function preSetData(FormEvent $event)
    {
        $notification = $event->getData();
        $form = $event->getForm();

        if (null === $notification) {
            return;
        }

        $entityName = $notification->getEntityName();

        if ($entityName) {
            if ($form->has('template')) {
                $config = $form->get('template')->getConfig()->getOptions();
                unset($config['choice_list']);
                unset($config['choices']);
            } else {
                $config = array();
            }

            $config['selectedEntity'] = $entityName;
            $config['query_builder'] = $this->getTemplateClosure($entityName);

            if (array_key_exists('auto_initialize', $config)) {
                $config['auto_initialize'] = false;
            }

            $form->add(
                $this->factory->createNamed(
                    'template',
                    'oro_email_template_list',
                    $notification->getTemplate(),
                    $config
                )
            );
        }
    }

    /**
     * Removes or adds a template field based on the entity set on submitted form.
     *
     * @param FormEvent $event
     */
    public function preSubmit(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();

        $entityName = isset($data['entityName']) ? $data['entityName'] : false;

        if ($entityName) {
            $config = $form->get('template')->getConfig()->getOptions();
            unset($config['choice_list']);
            unset($config['choices']);

            $config['selectedEntity'] = $entityName;
            $config['query_builder'] = $this->getTemplateClosure($entityName);

            if (array_key_exists('auto_initialize', $config)) {
                $config['auto_initialize'] = false;
            }

            $form->add(
                $this->factory->createNamed(
                    'template',
                    'oro_email_template_list',
                    null,
                    $config
                )
            );
        }
    }

    /**
     * @param string $entityName
     * @return callable
     */
    protected function getTemplateClosure($entityName)
    {
        return function (EmailTemplateRepository $templateRepository) use ($entityName) {
            return $templateRepository->getEntityTemplatesQueryBuilder($entityName);
        };
    }
}


text:
using namespace SDKTemplate;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;

Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
{
    { "Scenario 1", "SDKTemplate.Scenario1" },
    { "Scenario 2", "SDKTemplate.Scenario2" },
    { "Scenario 3", "SDKTemplate.Scenario3" },
    { "Scenario 4", "SDKTemplate.Scenario4" },
    { "Scenario 5", "SDKTemplate.Scenario5" },
    { "Scenario 6", "SDKTemplate.Scenario6" },
    { "Scenario 7", "SDKTemplate.Scenario7" },
    { "Scenario 8", "SDKTemplate.Scenario8" },
    { "Scenario 9", "SDKTemplate.Scenario9" },
    { "Scenario 10", "SDKTemplate.Scenario10" },
    { "Scenario 11", "SDKTemplate.Scenario11" },
    { "Scenario 12", "SDKTemplate.Scenario12" },
};

void HelperFunctions::UpdateCanvasSize(FrameworkElement^ root, FrameworkElement^ output, FrameworkElement^ inkCanvas)
{
    output->Width = root->ActualWidth;
    output->Height = root->ActualHeight / 2;
    inkCanvas->Width = root->ActualWidth;
    inkCanvas->Height = root->ActualHeight / 2;
}


text:
package org.cleanlogic.cesiumjs4gwt.showcase.examples;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.HTML;
import org.cesiumjs.cs.core.BoundingSphere;
import org.cesiumjs.cs.core.Matrix4;
import org.cesiumjs.cs.promise.Fulfill;
import org.cesiumjs.cs.scene.Cesium3DTileset;
import org.cesiumjs.cs.widgets.ViewerPanel;
import org.cesiumjs.cs.widgets.viewerCesium3DTilesInspectorMixin;
import org.cleanlogic.cesiumjs4gwt.showcase.basic.AbstractExample;
import org.cleanlogic.cesiumjs4gwt.showcase.components.store.ShowcaseExampleStore;

import javax.inject.Inject;

/**
 * @author Serge Silaev aka iSergio
 */
public class Tiles3DInspector extends AbstractExample {

    @Inject
    public Tiles3DInspector(ShowcaseExampleStore store) {
        super("3D Tiles Inspector", "Use the 3D Tiles inspector as a debugging tool for different tilesets.",
                new String[]{"Showcase", "Cesium", "3D Tiles"}, store);
    }

    @Override
    public void buildPanel() {
        final ViewerPanel csVPanel = new ViewerPanel();

        csVPanel.getViewer().extend(viewerCesium3DTilesInspectorMixin.instance());

        Cesium3DTileset tileset = (Cesium3DTileset) csVPanel.getViewer().scene().primitives().add(Cesium3DTileset.create(
                "https://beta.cesium.com/api/assets/1461?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkYWJmM2MzNS02OWM5LTQ3OWItYjEyYS0xZmNlODM5ZDNkMTYiLCJpZCI6NDQsImFzc2V0cyI6WzE0NjFdLCJpYXQiOjE0OTkyNjQ3NDN9.vuR75SqPDKcggvUrG_vpx0Av02jdiAxnnB1fNf-9f7s"));
        csVPanel.getViewer().cesium3DTilesInspector.viewModel.tileset = tileset;

        tileset.readyPromise().then(new Fulfill<Cesium3DTileset>() {
            @Override
            public void onFulfilled(Cesium3DTileset value) {
                BoundingSphere boundingSphere = value.boundingSphere();
                csVPanel.getViewer().camera.viewBoundingSphere(boundingSphere,
                        new org.cesiumjs.cs.core.HeadingPitchRange(0.0, -0.5, boundingSphere.radius / 4.0));
                csVPanel.getViewer().camera.lookAtTransform(Matrix4.IDENTITY());
            }
        });

        contentPanel.add(new HTML("
Use the 3D Tiles inspector as a debugging tool for different tilesets.
"));
        contentPanel.add(csVPanel);

        initWidget(contentPanel);
    }

    @Override
    public String[] getSourceCodeURLs() {
        String[] sourceCodeURLs = new String[1];
        sourceCodeURLs[0] = GWT.getModuleBaseURL() + "examples/" + "Tiles3DInspector.txt";
        return sourceCodeURLs;
    }
}


text:
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="url"
            type="java.lang.String" />
    </data>

    <com.example.ibanez_xiphos.databindingsample.ui.custom.SquareRelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/photo_item_padding">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@{url}" />

    </com.example.ibanez_xiphos.databindingsample.ui.custom.SquareRelativeLayout>

</layout>


text:
    background-color: #2d2d31;
    border-radius: 0px;
    border: 4px solid #5588bb;
}

#XfceNotifyWindow:hover {
    border: 4px solid #4477aa;
}

#XfceNotifyWindow label,
#XfceNotifyWindow image {
    font-family: Monaco;
    font-size: 16;
    color: #cccccc;
}

#XfceNotifyWindow label#summary {
    font-weight: Bold;
    color: #997799;
}

#XfceNotifyWindow button {
    border-style: none;
    background-image: none;
    background-color: #202020;
    color: #ffffff;
}

#XfceNotifyWindow button:hover {
    border-style: none;
    background-image: none;
    background-color: #404040;
    color: #ffffff;
}

#XfceNotifyWindow progressbar {
    border-radius: 3px;
}

#XfceNotifyWindow progressbar progress {
    min-height: 16px;
    background-image: none;
    background-color: shade(#ab3737, 1.2);
}

#XfceNotifyWindow progressbar trough {
    min-height: 16px;
    background-image: none;
    background-color: #ffdb1a;
    border: 1px solid shade(#000000, 0.6);
    border-radius: 3px;
}


text:
package semanticMarkup.ling.learn.knowledge;

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;

import semanticMarkup.know.lib.WordNetPOSKnowledgeBase;
import semanticMarkup.ling.learn.Configuration;
import semanticMarkup.ling.learn.Learner;
import semanticMarkup.ling.learn.dataholder.DataHolder;
import semanticMarkup.ling.learn.utility.LearnerUtility;
import semanticMarkup.ling.transform.ITokenizer;
import semanticMarkup.ling.transform.lib.OpenNLPSentencesTokenizer;
import semanticMarkup.ling.transform.lib.OpenNLPTokenizer;

public class AndOrTagSetterTest {
	private AndOrTagSetter tester;
	private Configuration configuration;
	private LearnerUtility myLearnerUtility;

	@Before
	public void initialize() {
		this.configuration = new Configuration();
		ITokenizer tokenizer = new OpenNLPTokenizer(
				this.configuration.getOpenNLPTokenizerDir());
		ITokenizer sentenceDetector = new OpenNLPSentencesTokenizer(
				this.configuration.getOpenNLPSentenceDetectorDir());
		WordNetPOSKnowledgeBase wordNetPOSKnowledgeBase = null;
		try {
			wordNetPOSKnowledgeBase = new WordNetPOSKnowledgeBase(this.configuration.getWordNetDictDir(), false);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.myLearnerUtility = new LearnerUtility(sentenceDetector,
				tokenizer, wordNetPOSKnowledgeBase);

		this.tester = new AndOrTagSetter(this.myLearnerUtility);
	}

	@Test
	public void testIsIsAndOrSentence(){
		String sentencePtn = null;
		String ptn1 = null;
		String ptn2 = null;
		List<String> words = new ArrayList<String>();

//		// case 1
//		words.clear();
//		words.addAll(Arrays.asList("posterior and <M>dorsal</M> to foramen for nerve <N>ii</N>".split(" ")));
//		sentencePtn = "q&mqqbqn";
//		ptn1="^(?:[mbq,]{0,10}[onp]+(?:,|(?=&)))+&(?:[mbq,]{0,10}[onp]+)"; // n,n,n&n
//		ptn2="^(?:[mbq,]{0,10}(?:,|(?=&)))+&(?:[mbq,]{0,10})[onp]+"; // m,m,&mn
//
//		assertEquals("isIsAndOrSentence case 1", false,
//				tester.isIsAndOrSentenceHelper(words, sentencePtn, ptn1, ptn2));

		// case 2
		words.clear();
		words.addAll(Arrays.asList("elongate and <O>passes</O> anterolaterally through orbital ? oor".split(" ")));
		sentencePtn = "q&obqqbq";
		ptn1="^(?:[mbq,]{0,10}[onp]+(?:,|(?=&)))+&(?:[mbq,]{0,10}[onp]+)"; // n,n,n&n
		ptn2="^(?:[mbq,]{0,10}(?:,|(?=&)))+&(?:[mbq,]{0,10})[onp]+"; // m,m,&mn

		assertEquals("isIsAndOrSentence case 2", true,
				tester.isIsAndOrSentenceHelper(words, sentencePtn, ptn1, ptn2));

		// case 3
		words.clear();
		words.addAll(Arrays.asList("<O>divides</O> within otic <N>capsule</N> at the <N>level</N> of the postorbital process".split(" ")));
		sentencePtn = "q,obqnbbnbbqq";
		ptn1="^(?:[mbq,]{0,10}[onp]+(?:,|(?=&)))+&(?:[mbq,]{0,10}[onp]+)"; // n,n,n&n
		ptn2="^(?:[mbq,]{0,10}(?:,|(?=&)))+&(?:[mbq,]{0,10})[onp]+"; // m,m,&mn

		assertEquals("isIsAndOrSentence case 3", false,
				tester.isIsAndOrSentenceHelper(words, sentencePtn, ptn1, ptn2));

	}

}


text:
import {
  settings,
  addUpdateListener,
} from '../settings.js';
import {
  map,
  filter,
  range,
  findIndexes,
  chunkBy,
  flatMap,
  concatBytes,
} from '../utils/arrays.js';
import {
  rgbToHue,
} from '../utils/colors.js';
import {
  pipe,
} from '../utils/functions.js';
import {
  rand,
  randInt,
} from '../utils/math.js';

/**
 * Instructions for building a meeba
 *
 * @typedef Commands
 * @prop {number} size - the size/area of the meeba
 * @prop {SpikeCommand[]} spikes - the spikes to attach to the meeba
 * @prop {number} hue - the hue of the meeba from 0 to 360
 */

/**
 * Parsed representation of a single gene
 *
 * @typedef Gene
 * @prop {number} type - the control-byte for the gene
 * @prop {number} location - where in the gene appears, 0 (start) to 1 (end)
 * @prop {Uint8Array} bytes - remaining bytes of the gene
 */

/**
 * Instructions for building a spike
 *
 * @typedef SpikeCommand
 * @prop {number} length - length of spike in pixels
 * @prop {number} angle - position around meeba circumference (in turns)
 */

/**
 * Dynamically calculated genome settings
 *
 * @typedef DynamicGenomeSettings
 * @prop {number} maxGeneCount
 * @prop {number} maxGeneSize
 * @prop {number} chanceMutateBit
 * @prop {number} chanceDropByte
 * @prop {number} chanceRepeatByte
 * @prop {number} chanceTransposeByte
 * @prop {number} chanceDropGene
 * @prop {number} chanceRepeatGene
 * @prop {number} chanceTransposeGene
 * @prop {{byte: number, maxRoll: number}[]} controlByteRolls
 */

const { core, genome: fixed } = settings;
const dynamic = /** @type {DynamicGenomeSettings} */ ({});
addUpdateListener(() => {
  dynamic.maxGeneCount = 2 * fixed.averageGeneCount;
  dynamic.maxGeneSize = 2 * fixed.averageGeneSize;

  const volatilityAdjustment = core.volatility / 100;
  dynamic.chanceMutateBit = fixed.baseChanceMutateBit * volatilityAdjustment;
  dynamic.chanceDropByte = fixed.baseChanceDropByte * volatilityAdjustment;
  dynamic.chanceRepeatByte = fixed.baseChanceRepeatByte * volatilityAdjustment;
  dynamic.chanceTransposeByte = fixed.baseChanceTransposeByte * volatilityAdjustment;
  dynamic.chanceDropGene = fixed.baseChanceDropGene * volatilityAdjustment;
  dynamic.chanceRepeatGene = fixed.baseChanceRepeatGene * volatilityAdjustment;
  dynamic.chanceTransposeGene = fixed.baseChanceTransposeGene * volatilityAdjustment;

  const {
    percentSpikeGenes,
    percentSizeGenes,
    percentRedGenes,
    percentGreenGenes,
    percentBlueGenes,
  } = fixed;
  const BYTES = [
    { byte: 0xF0, chance: percentSizeGenes },
    { byte: 0xF1, chance: percentSpikeGenes },
    { byte: 0xF2, chance: percentRedGenes },
    { byte: 0xF3, chance: percentGreenGenes },
    { byte: 0xF4, chance: percentBlueGenes },
  ];
  const ratioToOne = 1 / BYTES.reduce((sum, { chance }) => sum + chance, 0);

  // Too clever by half, but will get us an array with "rolls" from 0 - 1
  dynamic.controlByteRolls = BYTES.reduce((rolls, { byte, chance }, i) => {
    const maxRoll = chance * ratioToOne + rolls[i].maxRoll;
    rolls.push({ byte, maxRoll });
    return rolls;
  }, [{ byte: 0, maxRoll: 0 }]).slice(1);
});

/**
 * Returns a random control byte based on the odds in the CONTROL_BYTES array
 *
 * @returns {number}
 */
const randControlByte = () => {
  const { controlByteRolls } = dynamic;
  const roll = rand();
  const matchingByte = controlByteRolls.find(({ maxRoll }) => roll < maxRoll)
    || controlByteRolls[controlByteRolls.length - 1]; // Make TypeScript happy
  return matchingByte.byte;
};

/**
 * Returns a gene with a control byte followed a random number of
 * randomly generated bytes (not yet formatted as a Uint8Array)
 *
 * @returns {number[]}
 */
const randGene = () => {
  const body = range(randInt(1, dynamic.maxGeneSize)).map(() => randInt(0, 256));
  return [randControlByte(), ...body];
};

/**
 * Creates a new random genome encoded as a Uint8Array
 *
 * @returns {Uint8Array}
 */
export const createGenome = () => {
  const size = randInt(1, dynamic.maxGeneCount);
  return Uint8Array.from(flatMap(range(size), randGene));
};

/**
 * Count the number of 1 bits in series of bytes
 *
 * @param {Uint8Array} bytes
 * @returns {number} - number of 1's
 */
const countBits = bytes => bytes.reduce((count, byte) => (
  count + byte.toString(2).split('').filter(bit => bit === '1').length
), 0);

/**
 * Find the indexes of any control bytes in a genome
 *
 * @param {Uint8Array|number[]} genome - the full genome
 * @returns {number[]}
 */
const findControlIndexes = genome => findIndexes(Array.from(genome), byte => byte >= 0xF0);

/**
 * Split a full genome into an array of gene objects by control byte
 *
 * @param {Uint8Array} genome - the full genome
 * @returns {Gene[]}
 */
const toGenes = genome => findControlIndexes(genome)
  .map((index, i, indexes) => ({
    type: genome[index],
    location: index / genome.length,
    bytes: genome.slice(index + 1, indexes[i + 1]),
  }));

/**
 * Count up the bits of all genes that match a certain type
 *
 * @param {number} typeByte
 * @param {Gene[]} genes
 * @returns {number}
 */
const countTypeBits = (typeByte, genes) => genes
  .filter(({ type }) => type === typeByte)
  .reduce((sum, { bytes }) => sum + countBits(bytes), 0);

/**
 * Read a spike gene, returning the basic instructions for building a spike object
 *
 * @param {Gene} gene - the spike gene
 * @returns {SpikeCommand}
 */
const readSpikeGene = ({ location, bytes }) => ({
  angle: location,
  length: Math.floor(countBits(bytes) / fixed.bitsPerSpikeLength),
});

/**
 * Interprets a genome, returning a command object with instructions
 * for building a meeba based on the encoded genes
 *
 * @param {Uint8Array} genome
 * @returns {Commands}
 */
export const readGenome = (genome) => {
  const genes = toGenes(genome);

  const size = Math.floor(countTypeBits(0xF0, genes) / fixed.bitsPerMass);

  const spikes = genes
    .filter(({ type }) => type === 0xF1)
    .map(readSpikeGene);

  const hue = rgbToHue({
    r: countTypeBits(0xF2, genes),
    g: countTypeBits(0xF3, genes),
    b: countTypeBits(0xF4, genes),
  });

  return { size, spikes, hue };
};

/**
 * Mutates a byte by applying possible single-point mutations to its bits
 *
 * @param {number} byte
 * @returns {number}
 */
const mutateBits = (byte) => {
  const xorMask = parseInt(range(8)
    .map(() => (rand() < dynamic.chanceMutateBit ? '1' : '0'))
    .join(''), 2);

  // eslint-disable-next-line no-bitwise
  return byte ^ xorMask;
};

/**
 * Repeats random items in an array or Uint8array
 *
 * @param {array|Uint8Array} arr
 * @param {number} chance - chance from 0 to 1 an item is repeated
 * @returns {array}
 */
const repeatItems = (arr, chance) => {
  const repeated = [];

  for (let i = 0; i < arr.length; i += 1) {
    repeated.push(arr[i]);
    if (rand() < chance) {
      i -= 1;
    }
  }

  return repeated;
};

/**
 * Shuffle random items in an array or Uint8array
 *
 * @param {array|Uint8Array} arr
 * @param {number} chance - chance from 0 to 1 an item is shuffled
 * @returns {array}
 */
const transposeItems = (arr, chance) => {
  const transposed = [];
  const toTranspose = [];

  for (const item of arr) {
    if (rand() < chance) {
      toTranspose.push(item);
    } else {
      transposed.push(item);
    }
  }

  for (const item of toTranspose) {
    transposed.splice(randInt(0, transposed.length), 0, item);
  }

  return transposed;
};

/**
 * Joins an array of gene bytes into one Uint8Array
 *
 * @param {Uint8Array[]} geneArray
 * @returns {Uint8Array}
 */
const joinGeneArray = geneArray => concatBytes(...geneArray);

/**
 * Creates a mutated copy of an existing genome
 *
 * @param {Uint8Array} genome
 * @returns {Uint8Array}
 */
export const replicateGenome = genome => pipe(genome)
  .into(map, mutateBits)
  .into(filter, () => rand() >= dynamic.chanceDropByte)
  .into(repeatItems, dynamic.chanceRepeatByte)
  .into(transposeItems, dynamic.chanceTransposeByte)
  .into(chunkBy, findControlIndexes)
  .into(filter, () => rand() >= dynamic.chanceDropGene)
  .into(repeatItems, dynamic.chanceRepeatGene)
  .into(transposeItems, dynamic.chanceTransposeGene)
  .into(joinGeneArray)
  .done();


text:
var express = require('express');
var demand = require('must');

var ReactEngine = require('react-engine');
var view = require('react-engine/lib/expressView');

var engine = ReactEngine.server.create({});

var init = require('../../server/initViewEngine.js');

var options = {

	'name': 'foo',
	'brand': 'foo',

	'less': 'public',
	'static': 'public',
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': '.jsx',
	'custom engine': engine,
	'view': view,

	'auto update': true,
	'session': true,
	'auth': true,
	'user model': 'User',
	'cookie secret': 'Secret'

};

describe("initViewEngine", function () {
  var keystone = require('../../index.js');
  var app = express();
  keystone.init(options);
  keystone.set('app', app);
  it("should set view", function() {
    demand(typeof app.get('view')).must.be('function');
  });
});


text:
@import ImageIO;
@import CoreImage;

static size_t getAssetBytesCallback(void *info, void *buffer, off_t position, size_t count) {
    ALAssetRepresentation *representation = (__bridge id)info;

    NSError *error = nil;
    size_t bytes = [representation getBytes:(uint8_t *)buffer fromOffset:position length:count error:&error];

    if (bytes == 0 && error) {
        NSLog(@"Error while reading asset: %@", error);
    }

    return bytes;
}

static void releaseAssetCallback(void *info) {
    CFRelease(info);
}

@implementation ALAssetRepresentation (SafeLoading)

- (CGImageRef)loadImageOfSize:(CGFloat)maxLongSide CF_RETURNS_RETAINED {
    CGSize originalImageSize = CGSizeMake([self.metadata[@"PixelWidth"] floatValue], [self.metadata[@"PixelHeight"] floatValue]);
    CGImageRef img;

    // just correct EXIF-Rotation and resize image if needed
    CGDataProviderDirectCallbacks callbacks = {
        .version = 0,
        .getBytePointer = NULL,
        .releaseBytePointer = NULL,
        .getBytesAtPosition = getAssetBytesCallback,
        .releaseInfo = releaseAssetCallback,
    };

    CGDataProviderRef provider = CGDataProviderCreateDirect((void *)CFBridgingRetain(self), [self size], &callbacks);
    CGImageSourceRef source = CGImageSourceCreateWithDataProvider(provider, NULL);

    NSDictionary *options;
    if (maxLongSide != 0.0) {
        if (self.metadata[@"AdjustmentXMP"]) {
            CGSize croppedImageSize  = self.dimensions;
            CGFloat cropToMaxSize = MIN(maxLongSide / croppedImageSize.width * originalImageSize.width, maxLongSide / croppedImageSize.height * originalImageSize.height);
            options = @{(NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                        (NSString *)kCGImageSourceThumbnailMaxPixelSize : @(cropToMaxSize),
                        };
        } else {
            options = @{(NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                        (NSString *)kCGImageSourceThumbnailMaxPixelSize : @(maxLongSide),
                        (NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES,
                        };
        }
    } else {
        options = @{(NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                    (NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES,
                    };
    }
    img = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef)options);
    CFRelease(source);
    CFRelease(provider);

    if (self.metadata[@"AdjustmentXMP"]) {
        // some things have been done to this image in photos.app
        CGImageRef newImg = [self applyXMPAdjustment:img xmp:self.metadata[@"AdjustmentXMP"] maxSize:maxLongSide originalSize:originalImageSize orientation:self.orientation];
        CGImageRelease(img);
        img = newImg;
    }

    return img;
}

- (CGImageRef)applyXMPAdjustment:(CGImageRef)rawImage xmp:(NSString *)xmpString maxSize:(CGFloat)maxSize originalSize:(CGSize)originalImageSize orientation:(ALAssetOrientation)orientation CF_RETURNS_RETAINED {
    NSData *xmpData = [xmpString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;

    CIContext *context;

    // try hardware first
    EAGLContext *myEAGLContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    context = [CIContext contextWithEAGLContext:myEAGLContext options:@{ kCIContextWorkingColorSpace : [NSNull null] }];

    // check if we can render the image on hardware
    CGSize maxGPUImageSize = [context inputImageMaximumSize];
    if ((maxGPUImageSize.width < CGImageGetWidth(rawImage)) || (maxGPUImageSize.height < CGImageGetHeight(rawImage))) {
        context = nil;
    }

    // fallback to software renderer
    if (!context) {
        context = [CIContext contextWithOptions:@{ kCIContextUseSoftwareRenderer : @YES }];
    }

    // if we have no context here, bail out
    if (!context) {
        CGImageRetain(rawImage);
        return rawImage;
    }

    CIImage *image = [CIImage imageWithCGImage:rawImage];

    NSMutableArray *filterArray = [[CIFilter filterArrayFromSerializedXMP:xmpData
                                                         inputImageExtent:image.extent
                                                                    error:&error] mutableCopy];
    // something went wrong while initializing filters?
    if (!filterArray) {
        NSLog(@"Error during CIFilter creation: %@", error);
        CGImageRetain(rawImage);
        return rawImage;
    }

    // add scaling filters
    if (maxSize > 0.0) {
        if ((originalImageSize.width != CGImageGetWidth(rawImage)) || (originalImageSize.height != CGImageGetHeight(rawImage))) {
            CGFloat zoom = MIN(originalImageSize.width / CGImageGetWidth(rawImage), originalImageSize.height / CGImageGetHeight(rawImage));
            BOOL translationFound = NO, cropFound = NO;
            for (CIFilter *filter in filterArray) {
                if ([filter.name isEqualToString:@"CIAffineTransform"] && !translationFound) {
                    translationFound = YES;
                    CGAffineTransform t = [(NSValue *)[filter valueForKey:@"inputTransform"] CGAffineTransformValue];
                    t.tx /= zoom;
                    t.ty /= zoom;
                    [filter setValue:[NSValue valueWithCGAffineTransform:t] forKey:@"inputTransform"];
                }
                if ([filter.name isEqualToString:@"CICrop"] && !cropFound) {
                    cropFound = YES;
                    CGRect r = [(NSValue *)[filter valueForKey:@"inputRectangle"] CGRectValue];
                    r.origin.x /= zoom;
                    r.origin.y /= zoom;
                    r.size.width /= zoom;
                    r.size.height /= zoom;
                    [filter setValue:[NSValue valueWithCGRect:CGRectIntegral(r)] forKey:@"inputRectangle"];
                }
            }
        }
    }

    CGAffineTransform transform = CGAffineTransformIdentity;

    // fix exif transform
    switch (orientation) {
        case ALAssetOrientationDown:
        case ALAssetOrientationDownMirrored:
            transform = CGAffineTransformMakeRotation(M_PI);
            break;

        case ALAssetOrientationLeft:
        case ALAssetOrientationLeftMirrored:
            transform = CGAffineTransformMakeRotation(M_PI_2);
            break;

        case ALAssetOrientationRight:
        case ALAssetOrientationRightMirrored:
            transform = CGAffineTransformMakeRotation(-M_PI_2);
            break;

        case ALAssetOrientationUp:
        case ALAssetOrientationUpMirrored:
        default:
            // no rotation
            break;
    }

    // fix exif mirror
    switch (orientation) {

        case ALAssetOrientationDownMirrored:
        case ALAssetOrientationLeftMirrored:
        case ALAssetOrientationRightMirrored:
        case ALAssetOrientationUpMirrored:
            // mirror image
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;

        case ALAssetOrientationDown:
        case ALAssetOrientationLeft:
        case ALAssetOrientationRight:
        case ALAssetOrientationUp:
        default:
            // no mirroring
            break;
    }

    // if we calculated a transform, add a filter to the chain
    if (!CGAffineTransformIsIdentity(transform)) {
        CIFilter *transformFilter = [CIFilter filterWithName:@"CIAffineTransform"];
        [transformFilter setValue:[NSValue valueWithCGAffineTransform:transform] forKey:@"inputTransform"];
        [filterArray addObject:transformFilter];
    }

    // filter chain
    for (CIFilter *filter in filterArray) {
        [filter setValue:image forKey:kCIInputImageKey];
        image = [filter outputImage];
    }

    // render
    CGImageRef editedImage = [context createCGImage:image fromRect:image.extent];

    // return
    if (!editedImage) {
        CGImageRetain(rawImage);
        return rawImage;
    } else {
        return editedImage;
    }
}

@end

@implementation NSDictionary (AssetLoading)

- (CGSize)assetSize {
    // fetch EXIF rotation
    ALAssetOrientation orientation = [self[(NSString *)kCGImagePropertyOrientation] integerValue];

    // fetch pixel size
    CGSize assetSize = CGSizeMake([self[@"PixelWidth"] floatValue], [self[@"PixelHeight"] floatValue]);

    // check if XMP adjustment is neccessary
    if (self[@"AdjustmentXMP"]) {
        NSError *error;
        NSData *xmpData = [self[@"AdjustmentXMP"] dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *filterArray = [CIFilter filterArrayFromSerializedXMP:xmpData
                                                     inputImageExtent:CGRectMake(0, 0, assetSize.width, assetSize.height)
                                                                error:&error];
        if (!filterArray) {
            NSLog(@"Could not create filter array: %@", error);
        }

        // find crop filters in filter array as they change the size
        for (CIFilter *filter in filterArray) {
            if ([filter.name isEqualToString:@"CICrop"]) {
                CGRect r = [(NSValue *)[filter valueForKey:@"inputRectangle"] CGRectValue];
                assetSize = r.size;
            }
        }
    }

    // fix exif transform
    switch (orientation) {
        case ALAssetOrientationLeft:
        case ALAssetOrientationLeftMirrored:
        case ALAssetOrientationRight:
        case ALAssetOrientationRightMirrored: {
            CGFloat tmp = assetSize.width;
            assetSize.width = assetSize.height;
            assetSize.height = tmp;
            break;
        }

        case ALAssetOrientationUp:
        case ALAssetOrientationUpMirrored:
        case ALAssetOrientationDown:
        case ALAssetOrientationDownMirrored:
        default:
            // no rotation
            break;
    }
    return assetSize;
}

@end


text:
import mock
import time
from raven.utils.testutils import TestCase

from raven.base import Client
from raven.transport.threaded import ThreadedHTTPTransport
from raven.utils.urlparse import urlparse

class DummyThreadedScheme(ThreadedHTTPTransport):
    def __init__(self, *args, **kwargs):
        super(ThreadedHTTPTransport, self).__init__(*args, **kwargs)
        self.events = []
        self.send_delay = 0

    def send_sync(self, data, headers, success_cb, failure_cb):
        # delay sending the message, to allow us to test that the shutdown
        # hook waits correctly
        time.sleep(self.send_delay)

        self.events.append((data, headers, success_cb, failure_cb))

class ThreadedTransportTest(TestCase):
    def setUp(self):
        self.url = "threaded+http://some_username:some_password@localhost:8143/1"
        self.client = Client(dsn=self.url)

    @mock.patch('raven.transport.http.HTTPTransport.send')
    def test_does_send(self, send):
        self.client.captureMessage(message='foo')

        time.sleep(0.1)

        # TODO: This test could be more precise by ensuring it's sending the same params that are sent
        # to the ThreadedHTTPTransport.send() method
        self.assertEqual(send.call_count, 1)

    def test_shutdown_waits_for_send(self):
        url = urlparse(self.url)
        transport = DummyThreadedScheme(url)
        transport.send_delay = 0.5

        data = self.client.build_msg('raven.events.Message', message='foo')
        transport.async_send(data, None, None, None)

        time.sleep(0.1)

        # this should wait for the message to get sent
        transport.get_worker().main_thread_terminated()

        self.assertEqual(len(transport.events), 1)


text:
exports.info = { FormatID: '1432',
  FormatName: 'Microsoft PowerPoint Macro-Enabled Add-In',
  FormatVersion: '2007',
  FormatAliases: '',
  FormatFamilies: '',
  FormatTypes: 'Presentation',
  FormatDisclosure: '',
  FormatDescription: 'This is an outline record only, and requires further details, research or authentication to provide information that will enable users to further understand the format and to assess digital preservation risks associated with it if appropriate. If you are able to help by supplying any additional information concerning this entry, please return to the main PRONOM page and select 'Add an Entry'.',
  BinaryFileFormat: '',
  ByteOrders: '',
  ReleaseDate: '',
  WithdrawnDate: '',
  ProvenanceSourceID: '193',
  ProvenanceName: 'Central Digital Archive / Central Digital Archive',
  ProvenanceSourceDate: '14 Feb 2014',
  ProvenanceDescription: 'This format is identifiable via a container signature in DROID 6 and later.',
  LastUpdatedDate: '14 Feb 2014',
  FormatNote: '',
  FormatRisk: '',
  TechnicalEnvironment: '',
  FileFormatIdentifier:
   [ { Identifier: 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
       IdentifierType: 'MIME' },
     { Identifier: 'fmt/633', IdentifierType: 'PUID' } ],
  Developers:
   { DeveloperID: '93',
     DeveloperName: '',
     OrganisationName: 'Microsoft Corporation',
     DeveloperCompoundName: 'Microsoft Corporation' },
  Support:
   { SupportID: '93',
     SupportName: '',
     OrganisationName: 'Microsoft Corporation',
     SupportCompoundName: 'Microsoft Corporation' },
  ExternalSignature:
   { ExternalSignatureID: '1478',
     Signature: 'ppam',
     SignatureType: 'File extension' },
  RelatedFormat:
   { RelationshipType: 'Is subtype of',
     RelatedFormatID: '941',
     RelatedFormatName: 'Microsoft Powerpoint for Windows',
     RelatedFormatVersion: '2007 onwards' } }


text:
<?xml version="1.0" encoding="UTF-8"?>
<workspaceFilter version="1.0">
    <filter root="/tmp/sameparentconflicts/referenceable"/>
    <filter root="/tmp/sameparentconflicts/duplicate"/>
    <filter root="/tmp/differentparentconflicts/referenceable"/>
    <filter root="/tmp/differentparentconflicts/duplicate"/>
</workspaceFilter>


text:
package org.springframework.security.oauth2.client.jackson2;

import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Utility class for {@code JsonNode}.
 *
 * @author Joe Grandja
 * @since 5.3
 */
abstract class JsonNodeUtils {

	static final TypeReference<Set<String>> STRING_SET = new TypeReference<Set<String>>() {
	};

	static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<Map<String, Object>>() {
	};

	static String findStringValue(JsonNode jsonNode, String fieldName) {
		if (jsonNode == null) {
			return null;
		}
		JsonNode value = jsonNode.findValue(fieldName);
		return (value != null && value.isTextual()) ? value.asText() : null;
	}

	static <T> T findValue(JsonNode jsonNode, String fieldName, TypeReference<T> valueTypeReference,
			ObjectMapper mapper) {
		if (jsonNode == null) {
			return null;
		}
		JsonNode value = jsonNode.findValue(fieldName);
		return (value != null && value.isContainerNode()) ? mapper.convertValue(value, valueTypeReference) : null;
	}

	static JsonNode findObjectNode(JsonNode jsonNode, String fieldName) {
		if (jsonNode == null) {
			return null;
		}
		JsonNode value = jsonNode.findValue(fieldName);
		return (value != null && value.isObject()) ? value : null;
	}

}


text:
import { c3_chart_internal_fn } from './core';

export var isValue = function (v) {
    return v || v === 0;
};
export var isFunction = function (o) {
    return typeof o === 'function';
};
export var isArray = function (o) {
    return Array.isArray(o);
};
export var isString = function (o) {
    return typeof o === 'string';
};
export var isUndefined = function (v) {
return typeof v === 'undefined';
};
export var isDefined = function (v) {
    return typeof v !== 'undefined';
};
export var ceil10 = function (v) {
    return Math.ceil(v / 10) * 10;
};
export var asHalfPixel = function (n) {
    return Math.ceil(n) + 0.5;
};
export var diffDomain = function (d) {
    return d[1] - d[0];
};
export var isEmpty = function (o) {
    return typeof o === 'undefined' || o === null || (isString(o) && o.length === 0) || (typeof o === 'object' && Object.keys(o).length === 0);
};
export var notEmpty = function (o) {
    return !c3_chart_internal_fn.isEmpty(o);
};
export var getOption = function (options, key, defaultValue) {
    return isDefined(options[key]) ? options[key] : defaultValue;
};
export var hasValue = function (dict, value) {
    var found = false;
    Object.keys(dict).forEach(function (key) {
        if (dict[key] === value) { found = true; }
    });
    return found;
};
export var sanitise = function (str) {
    return typeof str === 'string' ? str.replace(/</g, '<').replace(/>/g, '>') : str;
};
export var getPathBox = function (path) {
    var box = path.getBoundingClientRect(),
        items = [path.pathSegList.getItem(0), path.pathSegList.getItem(1)],
        minX = items[0].x, minY = Math.min(items[0].y, items[1].y);
    return {x: minX, y: minY, width: box.width, height: box.height};
};


text:
package vspk

import "github.com/nuagenetworks/go-bambou/bambou"

// VSDIdentity represents the Identity of the object
var VSDIdentity = bambou.Identity{
	Name:     "vsd",
	Category: "vsds",
}

// VSDsList represents a list of VSDs
type VSDsList []*VSD

// VSDsAncestor is the interface of an ancestor of a VSD must implement.
type VSDsAncestor interface {
	VSDs(*bambou.FetchingInfo) (VSDsList, *bambou.Error)
	CreateVSDs(*VSD) *bambou.Error
}

// VSD represents the model of a vsd
type VSD struct {
	ID                          string        `json:"ID,omitempty"`
	ParentID                    string        `json:"parentID,omitempty"`
	ParentType                  string        `json:"parentType,omitempty"`
	Owner                       string        `json:"owner,omitempty"`
	URL                         string        `json:"URL,omitempty"`
	Name                        string        `json:"name,omitempty"`
	ManagementIP                string        `json:"managementIP,omitempty"`
	LastStateChange             int           `json:"lastStateChange,omitempty"`
	LastUpdatedBy               string        `json:"lastUpdatedBy,omitempty"`
	Address                     string        `json:"address,omitempty"`
	PeakCPUUsage                float64       `json:"peakCPUUsage,omitempty"`
	PeakMemoryUsage             float64       `json:"peakMemoryUsage,omitempty"`
	PeerAddresses               string        `json:"peerAddresses,omitempty"`
	Description                 string        `json:"description,omitempty"`
	Messages                    []interface{} `json:"messages,omitempty"`
	Disks                       []interface{} `json:"disks,omitempty"`
	AlreadyMarkedForUnavailable bool          `json:"alreadyMarkedForUnavailable"`
	UnavailableTimestamp        int           `json:"unavailableTimestamp,omitempty"`
	EntityScope                 string        `json:"entityScope,omitempty"`
	Location                    string        `json:"location,omitempty"`
	Mode                        string        `json:"mode,omitempty"`
	ProductVersion              string        `json:"productVersion,omitempty"`
	Status                      string        `json:"status,omitempty"`
	CurrentCPUUsage             float64       `json:"currentCPUUsage,omitempty"`
	CurrentMemoryUsage          float64       `json:"currentMemoryUsage,omitempty"`
	AverageCPUUsage             float64       `json:"averageCPUUsage,omitempty"`
	AverageMemoryUsage          float64       `json:"averageMemoryUsage,omitempty"`
	ExternalID                  string        `json:"externalID,omitempty"`
}

// NewVSD returns a new *VSD
func NewVSD() *VSD {

	return &VSD{}
}

// Identity returns the Identity of the object.
func (o *VSD) Identity() bambou.Identity {

	return VSDIdentity
}

// Identifier returns the value of the object's unique identifier.
func (o *VSD) Identifier() string {

	return o.ID
}

// SetIdentifier sets the value of the object's unique identifier.
func (o *VSD) SetIdentifier(ID string) {

	o.ID = ID
}

// Fetch retrieves the VSD from the server
func (o *VSD) Fetch() *bambou.Error {

	return bambou.CurrentSession().FetchEntity(o)
}

// Save saves the VSD into the server
func (o *VSD) Save() *bambou.Error {

	return bambou.CurrentSession().SaveEntity(o)
}

// Delete deletes the VSD from the server
func (o *VSD) Delete() *bambou.Error {

	return bambou.CurrentSession().DeleteEntity(o)
}

// Metadatas retrieves the list of child Metadatas of the VSD
func (o *VSD) Metadatas(info *bambou.FetchingInfo) (MetadatasList, *bambou.Error) {

	var list MetadatasList
	err := bambou.CurrentSession().FetchChildren(o, MetadataIdentity, &list, info)
	return list, err
}

// CreateMetadata creates a new child Metadata under the VSD
func (o *VSD) CreateMetadata(child *Metadata) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// Alarms retrieves the list of child Alarms of the VSD
func (o *VSD) Alarms(info *bambou.FetchingInfo) (AlarmsList, *bambou.Error) {

	var list AlarmsList
	err := bambou.CurrentSession().FetchChildren(o, AlarmIdentity, &list, info)
	return list, err
}

// CreateAlarm creates a new child Alarm under the VSD
func (o *VSD) CreateAlarm(child *Alarm) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// GlobalMetadatas retrieves the list of child GlobalMetadatas of the VSD
func (o *VSD) GlobalMetadatas(info *bambou.FetchingInfo) (GlobalMetadatasList, *bambou.Error) {

	var list GlobalMetadatasList
	err := bambou.CurrentSession().FetchChildren(o, GlobalMetadataIdentity, &list, info)
	return list, err
}

// CreateGlobalMetadata creates a new child GlobalMetadata under the VSD
func (o *VSD) CreateGlobalMetadata(child *GlobalMetadata) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// Jobs retrieves the list of child Jobs of the VSD
func (o *VSD) Jobs(info *bambou.FetchingInfo) (JobsList, *bambou.Error) {

	var list JobsList
	err := bambou.CurrentSession().FetchChildren(o, JobIdentity, &list, info)
	return list, err
}

// CreateJob creates a new child Job under the VSD
func (o *VSD) CreateJob(child *Job) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// VSDComponents retrieves the list of child VSDComponents of the VSD
func (o *VSD) VSDComponents(info *bambou.FetchingInfo) (VSDComponentsList, *bambou.Error) {

	var list VSDComponentsList
	err := bambou.CurrentSession().FetchChildren(o, VSDComponentIdentity, &list, info)
	return list, err
}

// CreateVSDComponent creates a new child VSDComponent under the VSD
func (o *VSD) CreateVSDComponent(child *VSDComponent) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// EventLogs retrieves the list of child EventLogs of the VSD
func (o *VSD) EventLogs(info *bambou.FetchingInfo) (EventLogsList, *bambou.Error) {

	var list EventLogsList
	err := bambou.CurrentSession().FetchChildren(o, EventLogIdentity, &list, info)
	return list, err
}

// CreateEventLog creates a new child EventLog under the VSD
func (o *VSD) CreateEventLog(child *EventLog) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessDomain.DomainObjects;

namespace BusinessDomain.Interface
{
    public interface ILikable
    {
        void Like(User userId);
        void Dislike(User userId);
    }
}