text:
<?php

/**
 * @namespace
 */
namespace Yandex\OAuth;

use Guzzle\Http\Client;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Guzzle\Http\Exception\RequestException;
use Yandex\OAuth\Exception\AuthRequestException;
use Yandex\OAuth\Exception\AuthResponseException;

/**
 * Class OAuthClient implements Yandex OAuth protocol
 *
 * @category Yandex
 * @package  OAuth
 *
 * @author   Eugene Zabolotniy <realbaziak@gmail.com>
 * @created  29.08.13 12:07
 */
class OAuthClient
{
    /*
     * Authentication types constants
     *
     * The "code" type means that the application will use an intermediate code to obtain an access token.
     * The "token" type will result a user is redirected back to the application with an access token in a URL
     */
    const CODE_AUTH_TYPE = 'code';
    const TOKEN_AUTH_TYPE = 'token';

    /**
     * @var string
     */
    private $clientId = '';

    /**
     * @var string
     */
    private $clientSecret = '';

    /**
     * @var string
     */
    protected $serviceScheme = 'https';

    /**
     * @var string
     */
    protected $serviceDomain = 'oauth.yandex.ru';

    /**
     * @var string
     */
    protected $servicePort = '';

    /**
     * @var string
     */
    protected $accessToken = '';

    /**
     * @param string $clientId
     * @param string $clientSecret
     */
    public function __construct($clientId = '', $clientSecret = '')
    {
        $this->setClientId($clientId);
        $this->setClientSecret($clientSecret);
    }

    /**
     * @param string $clientId
     *
     * @return self
     */
    public function setClientId($clientId)
    {
        $this->clientId = $clientId;

        return $this;
    }

    /**
     * @return string
     */
    public function getClientId()
    {
        return $this->clientId;
    }

    /**
     * @param string $clientSecret
     *
     * @return self
     */
    public function setClientSecret($clientSecret)
    {
        $this->clientSecret = $clientSecret;

        return $this;
    }

    /**
     * @return string
     */
    public function getClientSecret()
    {
        return $this->clientSecret;
    }

    /**
     * @param string $accessToken
     *
     * @return self
     */
    public function setAccessToken($accessToken)
    {
        $this->accessToken = $accessToken;

        return $this;
    }

    /**
     * @return string
     */
    public function getAccessToken()
    {
        return $this->accessToken;
    }

    /**
     * @param string $serviceDomain
     *
     * @return self
     */
    public function setServiceDomain($serviceDomain)
    {
        $this->serviceDomain = $serviceDomain;

        return $this;
    }

    /**
     * @return string
     */
    public function getServiceDomain()
    {
        return $this->serviceDomain;
    }

    /**
     * @param string $servicePort
     *
     * @return self
     */
    public function setServicePort($servicePort)
    {
        $this->servicePort = $servicePort;

        return $this;
    }

    /**
     * @return string
     */
    public function getServicePort()
    {
        return $this->servicePort;
    }

    /**
     * @param string $serviceScheme
     *
     * @return self
     */
    public function setServiceScheme($serviceScheme)
    {
        $this->serviceScheme = $serviceScheme;

        return $this;
    }

    /**
     * @return string
     */
    public function getServiceScheme()
    {
        return $this->serviceScheme;
    }

    /**
     * @param string $resource
     * @return string
     */
    public function getServiceUrl($resource = '')
    {
        return $this->serviceScheme . '://' . $this->serviceDomain . '/' . rawurlencode($resource);
    }

    /**
     * @param string $type
     * @param string $state optional string
     *
     * @return string
     */
    public function getAuthUrl($type = self::CODE_AUTH_TYPE, $state = null)
    {
        $url = $this->getServiceUrl('authorize') . '?response_type=' . $type . '&client_id=' . $this->clientId;
        if ($state) {
            $url .= '&state=' . $state;
        }

        return $url;
    }

    /**
     * Sends a redirect to the Yandex authentication page.
     *
     * @param bool   $exit  indicates whether to stop the PHP script immediately or not
     * @param string $type  a type of the authentication procedure
     * @param string $state optional string
     */
    public function authRedirect($exit = true, $type = self::CODE_AUTH_TYPE, $state = null)
    {
        header('Location: ' . $this->getAuthUrl($type, $state));

        if ($exit) {
            exit();
        }
    }

    /**
     * Exchanges a temporary code for an access token.
     *
     * @param $code
     *
     * @throws AuthRequestException on a known request error
     * @throws AuthResponseException on a response format error
     * @throws RequestException on an unknown request error
     *
     * @return self
     */
    public function requestAccessToken($code)
    {
        $client = new Client($this->getServiceUrl());

        $request = $client->post(
            'token', // to relative path "/token"
            null, // with no headers
            array(
                'grant_type'    => 'authorization_code',
                'code'          => $code,
                'client_id'     => $this->clientId,
                'client_secret' => $this->clientSecret
            )
        );

        try {

            $response = $request->send();

        } catch (ClientErrorResponseException $ex) {

            $result = $request->getResponse()->json();

            if (is_array($result) && isset($result['error'])) {
                // handle a service error message
                $message = 'Service responsed with error code "' . $result['error'] . '".';

                if (isset($result['error_description']) && $result['error_description']) {
                    $message .= ' Description "' . $result['error_description'] . '".';
                }
                throw new AuthRequestException($message, 0, $ex);
            }

            // unknown error. not parsed error
            throw $ex;
        }

        try {
            $result = $response->json();
        } catch (\RuntimeException $ex) {
            throw new AuthResponseException('Server response can\'t be parsed', 0, $ex);
        }

        if (!is_array($result)) {
            throw new AuthResponseException('Server response has unknown format');
        }

        if (!isset($result['access_token'])) {
            throw new AuthResponseException('Server response doesn\'t contain access token');
        }

        $this->setAccessToken($result['access_token']);

        return $this;
    }
}


text:
package org.samovich.cop2800.chapter14.assignment;

import javax.swing.*;

/**
 * Filename ReserveRoomApplication.java
 * Created by Valery Samovich
 * Written on 7/23/2016
 */
public class ReserveRoomApplication {
    public static void main(String[] args) {
        // instantiate an object of the ReserveRoomGUI
        ReserveRoomGUI reserveRoomGUI = new ReserveRoomGUI();
        reserveRoomGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        reserveRoomGUI.setVisible(true);
        reserveRoomGUI.setTitle("Reserve Room");
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\Routing;

/**
 * CompiledRoutes are returned by the RouteCompiler class.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class CompiledRoute
{
    private $variables;
    private $tokens;
    private $staticPrefix;
    private $regex;

    /**
     * Constructor.
     *
     * @param string $staticPrefix The static prefix of the compiled route
     * @param string $regex        The regular expression to use to match this route
     * @param array  $tokens       An array of tokens to use to generate URL for this route
     * @param array  $variables    An array of variables
     */
    public function __construct($staticPrefix, $regex, array $tokens, array $variables)
    {
        $this->staticPrefix = $staticPrefix;
        $this->regex = $regex;
        $this->tokens = $tokens;
        $this->variables = $variables;
    }

    /**
     * Returns the static prefix.
     *
     * @return string The static prefix
     */
    public function getStaticPrefix()
    {
        return $this->staticPrefix;
    }

    /**
     * Returns the regex.
     *
     * @return string The regex
     */
    public function getRegex()
    {
        return $this->regex;
    }

    /**
     * Returns the tokens.
     *
     * @return array The tokens
     */
    public function getTokens()
    {
        return $this->tokens;
    }

    /**
     * Returns the variables.
     *
     * @return array The variables
     */
    public function getVariables()
    {
        return $this->variables;
    }
}


text:
import classNames from 'classnames';
import React from 'react';

import styles from '../index.module.css';

export type OvalProps = JSX.IntrinsicElements['span'];

export function Oval({ children, className, ...props }: OvalProps) {
  return (
    <span {...props} className={classNames(styles.oval, className)}>
      {children}
    </span>
  );
}


text:
package io.github.yeagy.bss;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
    String name();
}


text:
This is a python wrapper, based on Boost Python, for code contained in
Willet et al. 2007, "Multiscale Poisson Intensity and Density Estimation".
The original Matlab code can be downloaded from:

http://willett.ece.wisc.edu/code/FreeDegree.zip

*** The original code is property of the respective authors. I do not own
it and I didn't have any part in the research which produced that code. I simply
wrote this wrapper because I found that code useful for my research.

## Installation

You need Boost Python installed. If you have a custom installation of Boost
Python, you can specify its root by using the BOOSTROOT environment variable.

Then you can install the code as:

> python setup.py install

## Usage

See the example.py script under Examples. Note that you need numpy, matplotlib
and scipy installed to run the example.


text:
package com.google.cloud.compute.v1;

import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.ApiMessage;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Generated;
import javax.annotation.Nullable;

@Generated("by GAPIC")
@BetaApi
public final class TestPermissionsResponse implements ApiMessage {
  private final List<String> permissions;

  private TestPermissionsResponse() {
    this.permissions = null;
  }

  private TestPermissionsResponse(List<String> permissions) {
    this.permissions = permissions;
  }

  @Override
  public Object getFieldValue(String fieldName) {
    if ("permissions".equals(fieldName)) {
      return permissions;
    }
    return null;
  }

  @Nullable
  @Override
  public ApiMessage getApiMessageRequestBody() {
    return null;
  }

  @Nullable
  @Override
  /**
   * The fields that should be serialized (even if they have empty values). If the containing
   * message object has a non-null fieldmask, then all the fields in the field mask (and only those
   * fields in the field mask) will be serialized. If the containing object does not have a
   * fieldmask, then only non-empty fields will be serialized.
   */
  public List<String> getFieldMask() {
    return null;
  }

  /** A subset of `TestPermissionsRequest.permissions` that the caller is allowed. */
  public List<String> getPermissionsList() {
    return permissions;
  }

  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }

  public static Builder newBuilder(TestPermissionsResponse prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }

  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
  }

  public static TestPermissionsResponse getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final TestPermissionsResponse DEFAULT_INSTANCE;

  static {
    DEFAULT_INSTANCE = new TestPermissionsResponse();
  }

  public static class Builder {
    private List<String> permissions;

    Builder() {}

    public Builder mergeFrom(TestPermissionsResponse other) {
      if (other == TestPermissionsResponse.getDefaultInstance()) return this;
      if (other.getPermissionsList() != null) {
        this.permissions = other.permissions;
      }
      return this;
    }

    Builder(TestPermissionsResponse source) {
      this.permissions = source.permissions;
    }

    /** A subset of `TestPermissionsRequest.permissions` that the caller is allowed. */
    public List<String> getPermissionsList() {
      return permissions;
    }

    /** A subset of `TestPermissionsRequest.permissions` that the caller is allowed. */
    public Builder addAllPermissions(List<String> permissions) {
      if (this.permissions == null) {
        this.permissions = new LinkedList<>();
      }
      this.permissions.addAll(permissions);
      return this;
    }

    /** A subset of `TestPermissionsRequest.permissions` that the caller is allowed. */
    public Builder addPermissions(String permissions) {
      if (this.permissions == null) {
        this.permissions = new LinkedList<>();
      }
      this.permissions.add(permissions);
      return this;
    }

    public TestPermissionsResponse build() {
      return new TestPermissionsResponse(permissions);
    }

    public Builder clone() {
      Builder newBuilder = new Builder();
      newBuilder.addAllPermissions(this.permissions);
      return newBuilder;
    }
  }

  @Override
  public String toString() {
    return "TestPermissionsResponse{" + "permissions=" + permissions + "}";
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o instanceof TestPermissionsResponse) {
      TestPermissionsResponse that = (TestPermissionsResponse) o;
      return Objects.equals(this.permissions, that.getPermissionsList());
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Objects.hash(permissions);
  }
}


text:
Contributing to `ci-github-bot` is fairly easy. This document shows you how to
get the project, run all provided tests and generate a production-ready build.

It also covers provided grunt tasks that help you develop with `ci-github-bot`.

## Dependencies

To make sure that the following instructions work, please install the following dependencies
on you machine:

- Node.js (comes with a bundles npm)
- Git

## Installation

To get the source of `ci-github-bot`, clone the git repository via:

````
$ git clone https://github.com/clickalicious/ci-github-bot
````

This will clone the complete source to your local machine. Navigate to the project folder
and install all needed dependencies via **npm**:

````
$ npm install
````

This commands installs everything which is required for building and testing the project.

## Testing
Internally `ci-github-bot` depends on **Grunt**, however we have masked all steps behind
simple tasks processed by **npm**.

### Source linting: `npm run lint`
`npm run lint` performs a lint for all, also part of `test`.

### Unit testing: `npm run test`
`npm run test` executes (as you might think) the unit tests, which are located
in `test/unit`. The task uses **karma**, the spectacular test runner, to execute the tests with
the **jasmine testing framework**.

## Building
### Standard build
You will probably being never required using the command `npm run build`, because it will create a production-ready
build of `ci-github-bot`. This task will also **lint**, **test** and **minify** the
source. After running this task, you'll find the following files in a generated
`/dist`folder:

````
dist/ci-github-bot.js
dist/ci-github-bot.min.js
````

## Developing
### `grunt watch`
This task will watch all relevant files. When it notices a change, it'll run the
**lint** and **test** tasks. Use this task while developing on the source
to make sure that every time you make a change, you get notified if your code is inconsistent
or doesn't pass the tests.

### `grunt dev`
This task extends `watch`. In addition, it will lint, test and copy the result into `demo/`.
After this, just like `watch`, it will run these steps every time a file has changed.
On top of that, this task supports **live reloading** (on default port).

## Contributing/Submitting changes

- Check out a new branch based on develop and name it to what you intend to do:
  - Example:
    ````
    $ git checkout -b BRANCH_NAME origin/develop
    ````
    If you get an error, you may need to fetch develop first by using
    ````
    $ git remote update && git fetch
    ````
  - Use one branch per fix/feature
- Make your changes
  - Make sure to provide a spec for unit tests.
  - Run your tests with either karma start or grunt test.
  - When all tests pass, everything's fine.
- Commit your changes
  - Please provide a git message that explains what you've done.
  - Commit to the forked repository.
- Make a pull request
  - Make sure you send the PR to the develop branch.
  - CirlceCI is watching you!

If you follow these instructions, your PR will land pretty safely in the main repo!


text:
from datetime import date

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.utils.functional import SimpleLazyObject, empty

class Period(object):
    DAY = 86400  # seconds
    WEEK = DAY * 7
    DAYS_28 = DAY * 28
    MONTH = DAY * 30
    LIFETIME = 0

PERIOD_CHOICES = (
    (Period.DAY, 'Day'),
    (Period.WEEK, 'Week'),
    (Period.DAYS_28, '28 days'),
    (Period.MONTH, 'Month'),
    (Period.LIFETIME, 'Lifetime'))

class RegisterLazilyManagerMixin(object):
    _lazy_entries = []

    def _register(self, defaults=None, **kwargs):
        """Fetch (update or create)  an instance, lazily.

        We're doing this lazily, so that it becomes possible to define
        custom enums in your code, even before the Django ORM is fully
        initialized.

        Domain.objects.SHOPPING = Domain.objects.register(
            ref='shopping',
            name='Webshop')
        Domain.objects.USERS = Domain.objects.register(
            ref='users',
            name='User Accounts')
        """
        f = lambda: self.update_or_create(defaults=defaults, **kwargs)[0]
        ret = SimpleLazyObject(f)
        self._lazy_entries.append(ret)
        return ret

    def clear_cache(self):
        """For testability"""
        for entry in self._lazy_entries:
            entry._wrapped = empty

class DomainManager(RegisterLazilyManagerMixin, models.Manager):

    def register(self, ref, name=''):
        return super(DomainManager, self)._register(
            defaults={'name': name},
            ref=ref)

    def get_by_natural_key(self, ref):
        return self.get(ref=ref)

class Domain(models.Model):
    objects = DomainManager()

    ref = models.CharField(
        max_length=100,
        unique=True,
        help_text="Unique reference ID for this domain")
    name = models.CharField(
        max_length=100,
        blank=True,
        help_text="Short descriptive name")

    def __str__(self):
        return self.name or self.ref

    def natural_key(self):
        return [self.ref]

class MetricManager(RegisterLazilyManagerMixin, models.Manager):

    def register(self, domain, ref, name='', description=''):
        return super(MetricManager, self)._register(
            defaults={'name': name,
                      'description': description},
            domain=domain,
            ref=ref)

    def get_by_natural_key(self, domain, ref):
        return self.get(source=domain,
                        ref=ref)

class Metric(models.Model):
    objects = MetricManager()

    domain = models.ForeignKey(Domain, on_delete=models.PROTECT)
    ref = models.CharField(
        max_length=100,
        help_text="Unique reference ID for this metric within the domain")
    name = models.CharField(
        max_length=100,
        blank=True,
        help_text="Short descriptive name")
    description = models.TextField(
        blank=True,
        help_text="Description")

    class Meta:
        unique_together = ('domain', 'ref')

    def __str__(self):
        return self.name or self.ref

    def natural_key(self):
        return [self.source, self.ref]

class AbstractStatisticQuerySet(models.QuerySet):

    order_field = None

    def narrow(self, metric=None, metrics=None, period=None):
        qs = self
        assert metric is None or metrics is None
        if metric is not None:
            metrics = [metric]
        if metrics is not None:
            qs = qs.filter(metric__in=metrics)
        if period:
            qs = qs.filter(period=period)
        return qs

    def record(self, metric, value, period, **kwargs):
        instance, _ = self.update_or_create(
            period=period,
            metric=metric,
            defaults={'value': value},
            **kwargs)
        return instance

    def most_recent(self, **kwargs):
        return self.narrow(**kwargs).order_by('-' + self.order_field).first()

class AbstractStatistic(models.Model):
    metric = models.ForeignKey(Metric, on_delete=models.PROTECT)
    value = models.BigIntegerField(
        # To support storing that no data is available, use: NULL
        null=True)
    period = models.IntegerField(choices=PERIOD_CHOICES)

    class Meta:
        abstract = True

class ByObjectMixin(models.Model):
    object_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
    object_id = models.PositiveIntegerField()
    object = GenericForeignKey(
        'object_type',
        'object_id')

    class Meta:
        abstract = True

class ByObjectQuerySetMixin(object):

    def record(self, **kwargs):
        object = kwargs.pop('object')
        ct = ContentType.objects.get_for_model(object)
        return super(ByObjectQuerySetMixin, self).record(
            object_id=object.pk,
            object_type=ct,
            **kwargs)

    def narrow(self, **kwargs):
        qs = self
        object = kwargs.pop('object', None)
        objects = kwargs.pop('objects', None)
        object_type = kwargs.pop('object_type', None)
        assert object is None or objects is None
        if object is not None:
            objects = [object]
        if object_type:
            qs = qs.filter(object_type=object_type)
        if type(objects) in (list, tuple, set):
            if not objects:
                qs = self.none()
            else:
                # Assumption: all objects are of same type
                ct = ContentType.objects.get_for_model(objects[0])
                qs = qs.filter(
                    object_type=ct,
                    object_id__in=[s.pk for s in objects])
        elif isinstance(objects, models.QuerySet):
            ct = ContentType.objects.get_for_model(objects.model)
            qs = qs.filter(
                object_type=ct,
                object_id__in=objects.values_list(
                    'id', flat=True))
        elif objects is None:
            pass
        elif isinstance(objects, models.query.EmptyQuerySet):
            qs = self.none()
        else:
            raise NotImplementedError
        return super(ByObjectQuerySetMixin, qs).narrow(**kwargs)

class ByDateMixin(models.Model):
    date = models.DateField(db_index=True)

    class Meta:
        abstract = True

class ByDateQuerySetMixin(object):

    order_field = 'date'

    def record(self, **kwargs):
        dt = kwargs.pop('date', date.today())
        return super(ByDateQuerySetMixin, self).record(date=dt, **kwargs)

    def narrow(self, **kwargs):
        """Up-to including"""
        from_date = kwargs.pop('from_date', None)
        to_date = kwargs.pop('to_date', None)
        date = kwargs.pop('date', None)
        qs = self
        if from_date:
            qs = qs.filter(date__gte=from_date)
        if to_date:
            qs = qs.filter(date__lte=to_date)
        if date:
            qs = qs.filter(date=date)
        return super(ByDateQuerySetMixin, qs).narrow(**kwargs)

class StatisticByDateQuerySet(
        ByDateQuerySetMixin,
        AbstractStatisticQuerySet):
    pass

class StatisticByDateAndObjectQuerySet(
        ByDateQuerySetMixin,
        ByObjectQuerySetMixin,
        AbstractStatisticQuerySet):
    pass

class StatisticByDate(ByDateMixin, AbstractStatistic):
    objects = StatisticByDateQuerySet.as_manager()

    class Meta:
        unique_together = [
            'date',
            'metric',
            'period']
        verbose_name = 'Statistic by date'
        verbose_name_plural = 'Statistics by date'

    def __str__(self):
        return '{date}: {value}'.format(
            date=self.date,
            value=self.value)

class StatisticByDateAndObject(
        ByDateMixin,
        ByObjectMixin,
        AbstractStatistic):
    objects = StatisticByDateAndObjectQuerySet.as_manager()

    class Meta:
        unique_together = [
            'date',
            'metric',
            'object_type',
            'object_id',
            'period']
        verbose_name = 'Statistic by date and object'
        verbose_name_plural = 'Statistics by date and object'

    def __str__(self):
        return '{date}: {value}'.format(
            date=self.date,
            value=self.value)


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

namespace Examples.Common.Services
{
    public class HelloService : IHelloService
    {
        public string Hello(string name)
        {
            return "Hello, " + name;
        }
    }
}


text:
package com.atum.tunetube.youtube;

import android.os.Environment;

import org.junit.Assert;
import org.junit.Test;

import java.util.List;

/**
 * Created by atum-martin on 18/05/2017.
 */

public class YoutubeLinkTest {
    /*@Before
    public void setupMocks(){
        mockStatic(Environment.class);
        when(Environment.getExternalStoragePublicDirectory("")).thenReturn(new File("/"));
    }*/

    @Test
    public void testYoutubeTrackHotlink(){

        YoutubeLink link = new YoutubeLink("/watch?v=28GpKacWLWI", "Abstract - Neverland (ft. Ruth B) (Prod. Blulake)");
        Assert.assertNotNull(link.getYoutubeTitle());
        Assert.assertNotNull(link.toString());
        Assert.assertNotNull(link.getVideoId());
        Assert.assertNotNull(link.getYoutubeUrl());
        Assert.assertNotNull(link.getYoutubeUrls());
        Assert.assertTrue(link.getRelatedItems().size() > 1);
    }

}


text:
create table user (
    name varchar2(300 char) not null,
    username varchar2(300 char) not null,
    password varchar2(300 char) not null,
    primary key (username),
);

create table user_role (
    username varchar2(300 char) not null,
    role varchar2(300 char) not null,
    foreign key (username) references user(username),
    primary key (username, role)
);

create table todo_list (
    todo_list_id numeric(19) not null,
    name varchar2(2 char) not null,
    is_public boolean default false not null,
    owner varchar2(100 char) not null,
    foreign key (owner) references user(username),
    primary key (todo_list_id)
);

create table todo_list_item (
    todo_item_id numeric(19) not null,
    todo_list_id numeric(19) not null,
    name varchar2(2 char) not null,
    is_done boolean default false not null,

    primary key (todo_item_id),
    foreign key (todo_list_id) references todo_list(todo_list_id)
);


text:
#pragma once
#include <memory>
#include "NativeModulePerfLogger.h"

namespace facebook {
namespace react {

namespace BridgeNativeModulePerfLogger {
void enableLogging(std::unique_ptr<NativeModulePerfLogger> &&logger);
void disableLogging();

void moduleDataCreateStart(const char *moduleName, int32_t id);
void moduleDataCreateEnd(const char *moduleName, int32_t id);

/**
 * Create NativeModule platform object
 */
void moduleCreateStart(const char *moduleName, int32_t id);
void moduleCreateCacheHit(const char *moduleName, int32_t id);
void moduleCreateConstructStart(const char *moduleName, int32_t id);
void moduleCreateConstructEnd(const char *moduleName, int32_t id);
void moduleCreateSetUpStart(const char *moduleName, int32_t id);
void moduleCreateSetUpEnd(const char *moduleName, int32_t id);
void moduleCreateEnd(const char *moduleName, int32_t id);
void moduleCreateFail(const char *moduleName, int32_t id);

/**
 * JS require beginning
 */
void moduleJSRequireBeginningStart(const char *moduleName);
void moduleJSRequireBeginningCacheHit(const char *moduleName);
void moduleJSRequireBeginningEnd(const char *moduleName);
void moduleJSRequireBeginningFail(const char *moduleName);

/**
 * JS require ending
 */
void moduleJSRequireEndingStart(const char *moduleName);
void moduleJSRequireEndingEnd(const char *moduleName);
void moduleJSRequireEndingFail(const char *moduleName);

// Sync method calls
void syncMethodCallStart(const char *moduleName, const char *methodName);
void syncMethodCallArgConversionStart(
    const char *moduleName,
    const char *methodName);
void syncMethodCallArgConversionEnd(
    const char *moduleName,
    const char *methodName);
void syncMethodCallExecutionStart(
    const char *moduleName,
    const char *methodName);
void syncMethodCallExecutionEnd(const char *moduleName, const char *methodName);
void syncMethodCallReturnConversionStart(
    const char *moduleName,
    const char *methodName);
void syncMethodCallReturnConversionEnd(
    const char *moduleName,
    const char *methodName);
void syncMethodCallEnd(const char *moduleName, const char *methodName);
void syncMethodCallFail(const char *moduleName, const char *methodName);

// Async method calls
void asyncMethodCallStart(const char *moduleName, const char *methodName);
void asyncMethodCallArgConversionStart(
    const char *moduleName,
    const char *methodName);
void asyncMethodCallArgConversionEnd(
    const char *moduleName,
    const char *methodName);
void asyncMethodCallDispatch(const char *moduleName, const char *methodName);
void asyncMethodCallEnd(const char *moduleName, const char *methodName);
void asyncMethodCallFail(const char *moduleName, const char *methodName);

/**
 * Pre-processing async method call batch
 */
void asyncMethodCallBatchPreprocessStart();
void asyncMethodCallBatchPreprocessEnd(int batchSize);

// Async method call execution
void asyncMethodCallExecutionStart(
    const char *moduleName,
    const char *methodName,
    int32_t id);
void asyncMethodCallExecutionArgConversionStart(
    const char *moduleName,
    const char *methodName,
    int32_t id);
void asyncMethodCallExecutionArgConversionEnd(
    const char *moduleName,
    const char *methodName,
    int32_t id);
void asyncMethodCallExecutionEnd(
    const char *moduleName,
    const char *methodName,
    int32_t id);
void asyncMethodCallExecutionFail(
    const char *moduleName,
    const char *methodName,
    int32_t id);

} // namespace BridgeNativeModulePerfLogger

} // namespace react
} // namespace facebook


text:
package org.androdyne;

/**
 * Commonly used constants.
 **/
public class Constants
{
  /***************************************************************************
   * Public constants
   **/
  // Parameter separator in trace files
  public static final String PARAM_SEP  = ":";

  // BufferedReader/-Writer buffer size
  public static final int BUFSIZE       = 8192;

  // Trace file extensions
  public static final String TRACE_EXT  = ".trace";

}


text:
package mockit;

import java.awt.*;

import org.junit.*;
import org.junit.runners.*;
import static org.junit.Assert.*;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public final class MultiThreadedExpectationsTest
{
   static class Collaborator
   {
      int doSomething() { return -1; }
      void doSomethingElse() {}
   }

   @Mocked Collaborator mock;

   void useMockedCollaboratorFromWorkerThread()
   {
      Thread worker = new Thread() {
         @Override public void run() { mock.doSomethingElse(); }
      };
      worker.start();
      try { worker.join(); } catch (InterruptedException ignore) {}
   }

   @Test
   public void useMockedObjectFromWorkerThreadWhileVerifyingExpectation()
   {
      mock.doSomething();
      mock.doSomething();

      new Verifications() {{
         mock.doSomething();
         useMockedCollaboratorFromWorkerThread();
         times = 2;
      }};
   }

   @Test
   public void useMockedObjectFromWorkerThreadWhileRecordingAndVerifyingExpectation()
   {
      new Expectations() {{
         mock.doSomething();
         useMockedCollaboratorFromWorkerThread();
         result = 123;
      }};

      assertEquals(123, mock.doSomething());
      mock.doSomethingElse();

      new VerificationsInOrder() {{
         useMockedCollaboratorFromWorkerThread();
         mock.doSomething();
         mock.doSomethingElse();
      }};
   }

   @Test
   public void useMockedObjectFromWorkerThreadWhileRecordingStrictExpectation()
   {
      new StrictExpectations() {{
         mock.doSomething();
         useMockedCollaboratorFromWorkerThread();
         result = 123;
      }};

      assertEquals(123, mock.doSomething());
   }

   @Test
   public void executeInvalidExpectationBlockThenReplayRecordedExpectationFromAnotherThread() throws Exception
   {
      try {
         new Expectations(Runnable.class) {};
         fail();
      }
      catch (IllegalArgumentException ignore) {}

      new Expectations() {{
         mock.doSomething();
      }};

      Thread task = new Thread() {
         @Override public void run() { mock.doSomething(); }
      };
      task.start();
      task.join();
   }

   static class Dependency
   {
      void doSomething() {}
      static void doSomethingElse() {}
   }

   @Test
   public void verifyInvocationsReplayedInAnotherThreadWhoseClassIsNoLongerMocked_part1(
      @Mocked final Dependency dep, @Mocked final Graphics2D g2D, @Mocked final Runnable runnable)
   {
      new Thread() {
         @Override
         public void run()
         {
            dep.doSomething();
            g2D.dispose();
            runnable.run();
            Dependency.doSomethingElse();
         }
      }.start();
   }

   @Test
   public void verifyInvocationsReplayedInAnotherThreadWhoseClassIsNoLongerMocked_part2() throws Exception
   {
      Thread.sleep(10);
      new FullVerifications() {};
   }
}


text:
layout: docs
title:  "Materialized View Builder"
number: 9
---

# Materialized View Builder

TODO


text:
package org.apache.commons.text.similarity;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

/**
 * Tests {@link LongestCommonSubsequence}.
 */
public class LongestCommonSubsequenceTest {

    private static LongestCommonSubsequence subject;

    @BeforeAll
    public static void setup() {
        subject = new LongestCommonSubsequence();
    }

    @Test
    @SuppressWarnings("deprecation")
    public void testGettingLogestCommonSubsequenceNullNull() {
        assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, null));
    }

    @Test
    @SuppressWarnings("deprecation")
    public void testGettingLogestCommonSubsequenceNullString() {
        assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, "right"));
    }

    @Test
    @SuppressWarnings("deprecation")
    public void testGettingLogestCommonSubsequenceStringNull() {
        assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(" ", null));
    }

    @Test
    public void testGettingLongestCommonSubsequenceApplyNullNull() {
        assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, null));
    }

    @Test
    public void testGettingLongestCommonSubsequenceApplyNullString() {
        assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, "right"));
    }

    @Test
    public void testGettingLongestCommonSubsequenceApplyStringNull() {
        assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(" ", null));
    }

    @Test
    public void testGettingLongestCommonSubsequenceNullNull() {
        assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(null, null));
    }

    @Test
    public void testGettingLongestCommonSubsequenceNullString() {
        assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(null, "right"));
    }

    @Test
    public void testGettingLongestCommonSubsequenceStringNull() {
        assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(" ", null));
    }

    @Test
    @Deprecated
    public void testLogestCommonSubsequence() {
        assertThat(subject.logestCommonSubsequence("", "")).isEqualTo("");
        assertThat(subject.logestCommonSubsequence("left", "")).isEqualTo("");
        assertThat(subject.logestCommonSubsequence("", "right")).isEqualTo("");
        assertThat(subject.logestCommonSubsequence("frog", "fog")).isEqualTo("fog");
        assertThat(subject.logestCommonSubsequence("fly", "ant")).isEqualTo("");
        assertThat(subject.logestCommonSubsequence("elephant", "hippo")).isEqualTo("h");
        assertThat(subject.logestCommonSubsequence("ABC Corporation", "ABC Corp")).isEqualTo("ABC Corp");
        assertThat(subject.logestCommonSubsequence("D N H Enterprises Inc", "D & H Enterprises, Inc."))
            .isEqualTo("D  H Enterprises Inc");
        assertThat(subject.logestCommonSubsequence("My Gym Children's Fitness Center", "My Gym. Childrens Fitness"))
            .isEqualTo("My Gym Childrens Fitness");
        assertThat(subject.logestCommonSubsequence("PENNSYLVANIA", "PENNCISYLVNIA")).isEqualTo("PENNSYLVNIA");
        assertThat(subject.logestCommonSubsequence("left", "right")).isEqualTo("t");
        assertThat(subject.logestCommonSubsequence("leettteft", "ritttght")).isEqualTo("tttt");
        assertThat(subject.logestCommonSubsequence("the same string", "the same string")).isEqualTo("the same string");
    }

    @Test
    public void testLongestCommonSubsequence() {
        assertThat(subject.longestCommonSubsequence("", "")).isEqualTo("");
        assertThat(subject.longestCommonSubsequence("left", "")).isEqualTo("");
        assertThat(subject.longestCommonSubsequence("", "right")).isEqualTo("");
        assertThat(subject.longestCommonSubsequence("frog", "fog")).isEqualTo("fog");
        assertThat(subject.longestCommonSubsequence("fly", "ant")).isEqualTo("");
        assertThat(subject.longestCommonSubsequence("elephant", "hippo")).isEqualTo("h");
        assertThat(subject.longestCommonSubsequence("ABC Corporation", "ABC Corp")).isEqualTo("ABC Corp");
        assertThat(subject.longestCommonSubsequence("D N H Enterprises Inc", "D & H Enterprises, Inc."))
            .isEqualTo("D  H Enterprises Inc");
        assertThat(subject.longestCommonSubsequence("My Gym Children's Fitness Center", "My Gym. Childrens Fitness"))
            .isEqualTo("My Gym Childrens Fitness");
        assertThat(subject.longestCommonSubsequence("PENNSYLVANIA", "PENNCISYLVNIA")).isEqualTo("PENNSYLVNIA");
        assertThat(subject.longestCommonSubsequence("left", "right")).isEqualTo("t");
        assertThat(subject.longestCommonSubsequence("leettteft", "ritttght")).isEqualTo("tttt");
        assertThat(subject.longestCommonSubsequence("the same string", "the same string")).isEqualTo("the same string");
    }

    @Test
    public void testLongestCommonSubsequenceApply() {
        assertThat(subject.apply("", "")).isEqualTo(0);
        assertThat(subject.apply("left", "")).isEqualTo(0);
        assertThat(subject.apply("", "right")).isEqualTo(0);
        assertThat(subject.apply("frog", "fog")).isEqualTo(3);
        assertThat(subject.apply("fly", "ant")).isEqualTo(0);
        assertThat(subject.apply("elephant", "hippo")).isEqualTo(1);
        assertThat(subject.apply("ABC Corporation", "ABC Corp")).isEqualTo(8);
        assertThat(subject.apply("D N H Enterprises Inc", "D & H Enterprises, Inc.")).isEqualTo(20);
        assertThat(subject.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness")).isEqualTo(24);
        assertThat(subject.apply("PENNSYLVANIA", "PENNCISYLVNIA")).isEqualTo(11);
        assertThat(subject.apply("left", "right")).isEqualTo(1);
        assertThat(subject.apply("leettteft", "ritttght")).isEqualTo(4);
        assertThat(subject.apply("the same string", "the same string")).isEqualTo(15);
    }
}


text:
"""
<Program Name>
  create_tar.py

<Started>
  May 2009

<Author>
  n2k8000@u.washington.edu
  Konstantin Pik

<Purpose>
  Builds up a .tar file with the files specified in the files
  string. This is hardcoded for now as the files shouldn't change
  and if they do it will be easier to add them to this script (separated
  by spaces).

  Function creates a file named deploy.tar.
  TODO: Specify outfilename as a parameter.

<Usage>
  Currently only takes one extra fn for simplicity & testing
  ./create_tar.py [extra_fn1 extra_fn2 extra_fnN]
"""

import os
import sys
import subprocess

def shellexec(cmd_str):
  """
  <Purpose>
    Uses subprocess to execute the command string in the shell.

  <Arguments>
    cmd_str:  The string to be treated as a command (or set of commands,
                separated by ;).

  <Exceptions>
    None.

  <Side Effects>
    None.

  <Returns>
    A tuple containing (stdout, strerr, returncode)

    Detailed:
    stdout: stdout printed to console during command execution.
    strerr: error (note: some programs print to strerr instead of stdout)
    returncode: the return code of our call. If there are multiple commands,
                then this is the return code of the last command executed.
  """

  # get a handle to the subprocess we're creating..
  handle = subprocess.Popen(cmd_str, shell=True,
      stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

  # execute and grab the stdout and err
  stdoutdata, strerrdata = handle.communicate("")

  # The return code...
  returncode = handle.returncode

  return stdoutdata, strerrdata, returncode

# TODO: add args as 'extra' script files to execute.
def main():
  """
  <Purpose>
    Main entyr point into the program. Checks that everytyhing is in order,
    and then creates the tar file to deploy.

  <Arguments>
    None.

  <Exceptions>
    None.

  <Side Effects>
    None.

  <Returns>
    None.
  """

  print "Starting tar-maker script.."
  # String of files we're going to be looking for
  files="runlocaltests.py testprocess.py verifyfiles.mix cleanup_deploy.py hashes.dict upgrade_nodes.sh deploy_helper.py"

  # TODO: add list of 'optional files' to include

  # get the files passed in as arguments
  files_from_args = ''
  # 1 skips this file name
  print

  for eachfile in range(1, len(sys.argv)):
    print "Adding custom file: "+sys.argv[eachfile]
    files_from_args+=' '+sys.argv[eachfile]
  print
  # mash the two strings together now
  files+=files_from_args

  # Total number of files split by spaces
  total_files=len(files.split(' '))

  # Counter for found files
  num_files_found=0

  # Temporary tar, incrementally we'll build it up
  # Will remove the temp files (since I use -update flag)
  # for building up the .tar
  if os.path.isfile('./deploy.tar.temp'):
    os.remove('./deploy.tar.temp')

  for filename in files.split(' '):
    print ' Looking for '+filename+' in '+os.getcwd()
    if os.path.isfile('./'+filename):
      print '  File found!'
      num_files_found += 1
      shellexec('tar -rf deploy.tar.temp '+filename)
    else:
      print '  WARNING: '+filename+' NOT FOUND'

  print
  print "Found "+str(num_files_found)+" of "+str(total_files)+" necessary files."
  print

  # Did we find all of the files?
  if num_files_found == total_files:
    print
    print 'All files found, finishing tar..'
    # rename the file to the final name.
    # this will over-write current deploy.tar in the dir if one exists
    shellexec('mv deploy.tar.temp deploy.tar')
    return 0
  else:
    print 'FATAL ERROR: Not all the files where found, please check that '
    print '            this script is in the same directory as the files. '
    print
    print "Cleaning up temp files..."

    # remove deploy.tar.temp only if it exists.
    if os.path.isfile('./deploy.tar.temp'):
      os.remove('./deploy.tar.temp')

    print
    print 'Finished (with errors)'
    return 1

if __name__ == "__main__":
  main()


text:
package main.java;

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

public class RadixSort9 {

	public static int getSignificant(final int num, final int raidix) {
		if (num < 0) {
			throw new IllegalArgumentException();
		}

		if (raidix < 0) {
			throw new IllegalArgumentException();
		}

		final int divisor = (int) Math.pow(10, raidix - 1);

		return (num / divisor) % 10;
	}

	final private static int N_BUCKETS = 10;

	public static void sort(final Integer[] a) {
		int min = Integer.MAX_VALUE;
		int max = Integer.MIN_VALUE;

		for (final int i : a) {
			if (min > i) {
				min = i;
			}
			if (max < i) {
				max = i;
			}
		}

		final int maxLen = (int) Math.log10(max - min) + 1;

		final List[] buckets = new List[N_BUCKETS];

		for (int radix = 1; radix <= maxLen; radix++) {
			initBuckets(buckets);
			for (final int i : a) {
				final int significant = getSignificant(i - min, radix);
				buckets[significant].add(i);
			}

			int counter = 0;
			for (final List l : buckets) {
				for (final Object obj : l) {
					a[counter++] = (Integer) obj;
				}
			}
		}
	}

	private final static void initBuckets(final List[] buckets) {
		for (int i = 0; i < buckets.length; i++) {
			if (buckets[i] == null) {
				buckets[i] = new ArrayList<Integer>();
			} else {
				buckets[i].clear();
			}

		}
	}
}


text:
/****************************************************************************************/
/*                                                                                */
/*                                       Pegasus                                        */
/*                                                                                */
/****************************************************************************************/

//! \file	NodeFileTabBar.h
//! \author	Kleber Garcia
//! \date	July 12th, 2015
//! \brief	Widget component representing a tab bar that holds a list of q objects.
//!         bar keeps state for dirty objects

#ifndef EDITOR_NODE_FILE_BAR_H
#define EDITOR_NODE_FILE_BAR_H

#include <QWidget>
#include <QTabBar>
#include <QVector>
#include "MessageControllers/AssetIOMessageController.h"

class QTabBar;
class PegasusDockWidget;

//! Advanced tab bar, for pegasus nodes
class NodeFileTabBar : public QWidget
{
    Q_OBJECT
public:

    //! Constructor
    NodeFileTabBar(PegasusDockWidget* parent = 0);

    //! Destructor
    virtual ~NodeFileTabBar();

    //! Opens an object into the tab bar
    //! \param object the object to insert into the tabbed bar
    //! \param extra data attached to this pegasus node object
    void Open(AssetInstanceHandle handle, const QString& displayName, QObject* extraData = nullptr);

    //! Closes an object from the tab bar
    //! \param tab index.
    void Close(int tabId);

    //! Gets the object count
    //! returns the total count of tabbed objects contained
    int GetTabCount() const { return mTabBar->count(); }

    //! Returns the tab object contained in the tab index
    //! \param the tab index
    //! \return the handle of this object
    AssetInstanceHandle GetTabObject(int tabIndex) { return mContainerList[tabIndex].mObject; }

    //! Sets this object extra data
    void SetExtraData(int index, QObject* obj);

    //! Gets this objects extra data
    QObject* GetExtraData(int index) const;

    //! Attempts to mark the current element in the tab editor as dirty
    void MarkCurrentAsDirty();

    //! Attempts to clear the current element's dirty flag
    void ClearCurrentDirty();

    //! Gets the current index of the tab selected
    int GetCurrentIndex() const { return mTabBar->currentIndex(); }

    //! Sets the current index of this tab.
    void SetCurrentIndex(int idx) { mTabBar->setCurrentIndex(idx); }

    //! Finds the index of the object passed, returns -1 if it doesnt exist
    int FindIndex(AssetInstanceHandle object) const;

signals:
    //signal fired when a runtime object is displayed
    void DisplayRuntimeObject(AssetInstanceHandle object);

    //signal fired when a runtime object is removed
    void RuntimeObjectRemoved(AssetInstanceHandle object, QObject* extraData);

    //! signal fired when a dirty element attempted to be closed is requested to be saved before being done.
    void SaveRuntimeObject(int tabId);

    //! signal that discards the elements changes
    void DiscardObjectChanges(AssetInstanceHandle object);

    //! Called when an object has been registered as dirty
    void RegisterDirtyObject(AssetInstanceHandle object);

    //! Called when an object has been unregistered as dirty
    void UnregisterDirtyObject(AssetInstanceHandle object);

private slots:
    void ReceiveTabIdChanged(int index);

    void ReceiveTabClosedRequested(int index);

private:
    //! Sets up the ui
    void SetupUi();

    struct FileTabContainer
    {
        bool mIsDirty;
        AssetInstanceHandle mObject;
        QString mDisplayName;
        QObject* mExtraData;
        FileTabContainer() : mIsDirty(false), mExtraData(nullptr) {}
    };

    QVector<FileTabContainer> mContainerList;
    QTabBar* mTabBar;

    PegasusDockWidget* mParent;

};

#endif


text:
FROM nicholsn/ansible:latest
MAINTAINER Nolan Nichols <nolan.nichols@gmail.com>

RUN apt-get update
RUN apt-get install -y git-core
#RUN ansible-pull -C master -d /opt -i provisioning/hosts -U https://github.com/niquery/niquery.git provisioning/base.yml


text:
require 'test_helper'

class CommentTest < ActiveSupport::TestCase
  setup :comments_setup
  teardown :comments_teardown

  test 'should be valid' do
    assert @comment.valid?, @comment.errors.full_messages
  end

  test 'text should be present' do
    @comment.text = '  '
    assert_not @comment.valid?
  end

  test 'text should not be too short' do
    @comment.text = 'a'
    assert_not @comment.valid?
  end

  test 'text should not be too long' do
    @comment.text = 'a' * 61
    assert_not @comment.valid?
  end

  test 'user should be present' do
    @comment.user = nil
    assert_not @comment.valid?
  end
end


text:
using System;
using UnityEditor;
using UnityEngine;

namespace Pathfinding {
	public class AstarUpdateWindow : EditorWindow {

		static GUIStyle largeStyle;
		static GUIStyle normalStyle;
		Version version;
		string summary;
		bool setReminder;

		public static AstarUpdateWindow Init (Version version, string summary) {

			// Get existing open window or if none, make a new one:
			AstarUpdateWindow window = EditorWindow.GetWindow<AstarUpdateWindow> (true,"",true);
			window.position = new Rect (Screen.currentResolution.width/2 - 300,Mathf.Max (5,Screen.currentResolution.height/3 - 150), 600, 400);
			window.version = version;
			window.summary = summary;
#if UNITY_4_6 || UNITY_5_0
			window.title = "New Version of the A* Pathfinding Project";
#else
			window.titleContent = new GUIContent("New Version of the A* Pathfinding Project");
#endif
			return window;
		}

		public void OnDestroy () {
			if ( version != null && !setReminder ) {
				Debug.Log ("Closed window, reminding again tomorrow");
				EditorPrefs.SetString ("AstarRemindUpdateDate", DateTime.UtcNow.AddDays(1).ToString(System.Globalization.CultureInfo.InvariantCulture));
				EditorPrefs.SetString ("AstarRemindUpdateVersion", version.ToString() );
			}
		}

		void OnGUI () {

			if ( largeStyle == null ) {
				largeStyle = EditorStyles.largeLabel;
				largeStyle.fontSize = 32;
				largeStyle.alignment = TextAnchor.UpperCenter;
				largeStyle.richText = true;

				normalStyle = EditorStyles.label;
				normalStyle.wordWrap = true;
				normalStyle.richText = true;
			}

			if ( version == null ) {
				return;
			}

			GUILayout.Label ("New Update Available!", largeStyle);
			GUILayout.Label ("There is a new version of the A* Pathfinding Project available for download.\n" +
			    "The new version is " + version + " you have " + AstarPath.Version + "\n\n"+
			                 "Summary:\n"+summary, normalStyle
			);

			GUILayout.FlexibleSpace ();

			GUILayout.BeginHorizontal ();
			GUILayout.FlexibleSpace ();

			GUILayout.BeginVertical ();

			Color col = GUI.color;
			GUI.backgroundColor *= new Color ( 0.5f,  1f, 0.5f);
			if (GUILayout.Button ("Take me to the download page!", GUILayout.Height ( 30 ), GUILayout.MaxWidth(300))) {
				Application.OpenURL (AstarUpdateChecker.GetURL ("download"));
			}
			GUI.backgroundColor = col;

			if (GUILayout.Button ("What's new? (full changelog)")) {
				Application.OpenURL (AstarUpdateChecker.GetURL ("changelog"));
			}

			GUILayout.EndVertical ();

			GUILayout.FlexibleSpace ();
			GUILayout.EndHorizontal ();

			GUILayout.FlexibleSpace ();

			GUILayout.BeginHorizontal ();

			if ( GUILayout.Button ("Skip this version", GUILayout.MaxWidth (100) ) ) {
				EditorPrefs.SetString ("AstarSkipUpToVersion", version.ToString());
				setReminder = true;
				Close();
			}

			if ( GUILayout.Button ("Remind me later ( 1 week )", GUILayout.MaxWidth (200) ) ) {
				EditorPrefs.SetString ("AstarRemindUpdateDate", DateTime.UtcNow.AddDays(7).ToString(System.Globalization.CultureInfo.InvariantCulture));
				EditorPrefs.SetString ("AstarRemindUpdateVersion", version.ToString() );
				setReminder = true;
				Close();
			}

			GUILayout.FlexibleSpace ();
			GUILayout.EndHorizontal ();
		}
	}
}


text:
<?xml version="1.0"?>
<!-- Copyright (C) 2012 The Android Open Source Project

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

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

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.android.gms.appinvite">
    <uses-sdk android:minSdkVersion="14"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application>
        <activity android:name=".PreviewActivity" android:exported="true" android:theme="@style/Theme.AppInvite.Preview">
            <intent-filter>
                <action android:name="com.google.android.gms.appinvite.ACTION_PREVIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
    </application>
</manifest>


text: create a react boilerplate


text:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "EppParser.hpp"
#include <xercesc/framework/MemBufInputSource.hpp>

void EppParser::init()
{
	countWarnings = 0;
	countErrors = 0;
	countFatals = 0;
	errorMessages->removeAllElements();
	parser.reset();
	parser.setExitOnFirstFatalError(false);
	parser.setValidationScheme(XercesDOMParser::Val_Auto);
	parser.setDoNamespaces(false);
	//parser.setDoNamespaces(true);
	parser.setDoSchema(false);
	parser.setErrorHandler(this);
	//parser.setCreateEntityReferenceNodes(false);
	//parser.setToCreateXMLDeclTypeNode(true);
	document = null;
}

void EppParser::addMessage( const DOMString& msg )
{
	errorMessages->addElement(msg);
}

EppParser::EppParser()
{
	errorMessages = new OldValueVectorOf<DOMString>(MAX_NUM_OF_ERRORS);
	init();
}

EppParser::EppParser( const DOMString& string )
{
	errorMessages = new OldValueVectorOf<DOMString>(MAX_NUM_OF_ERRORS);
	parse(string);
}

EppParser::EppParser( const char * string )
{
	errorMessages = new OldValueVectorOf<DOMString>(MAX_NUM_OF_ERRORS);
	parse(string);
}

EppParser::EppParser( const char * string, int length )
{
	errorMessages = new OldValueVectorOf<DOMString>(30);
	parse(string, length);
}

EppParser::~EppParser()
{
	if( errorMessages != null )
	{
		delete errorMessages;
	}
}

XercesDOMParser& EppParser::getParser()
{
	return parser;
}

void EppParser::parse( const DOMString& string )
{
	char * p = string.transcode();
	parse((const char *) p);
	XercesString::Delete(p);
}

void EppParser::parse( const char * string )
{
	parse(string, strlen(string));
}

void EppParser::parse( const char * string, int length )
{
	MemBufInputSource membuf((const XMLByte *) string, length, "epp", false);
	try
	{
		init();
		parser.parse(membuf);
		document = parser.getDocument();
	}
	catch( const XMLException& e )
	{
		countFatals++;
		addMessage(DOMString("[Unknown Error] XMLException message is:\n")
			+ e.getMessage());
	}
	catch( const DOMException& e )
	{
		countFatals++;

		char cCode [33];
		sprintf(cCode, "%d", e.code);
		char* pMsg = XMLString::transcode(e.msg);

		addMessage((XS("[Unknown Error] DOMException code is: ") + XS(cCode) + XS(", message is:\n") + XS(pMsg)));

		XercesString::Delete(pMsg);
	}
	catch( ... )
	{
		countFatals++;
		addMessage(DOMString("[Unknown Error] Unknown Exception"));
	}
}

void EppParser::parseFile( const char * file )
{
	try
	{
		init();
		parser.parse(file);
		document = parser.getDocument();
	}
	catch( const XMLException& e )
	{
		countFatals++;
		addMessage(DOMString("[Unknown Error] XMLException message is:\n")
			+ e.getMessage());
	}
	catch( const DOMException& e )
	{
		countFatals++;

		char cCode [32];
		sprintf(cCode, "%d", e.code);
		char* pMsg = XMLString::transcode(e.msg);

		addMessage((XS("[Unknown Error] DOMException code is: ") + XS(cCode) + XS(", message is:\n") + XS(pMsg)));

		XercesString::Delete(pMsg);

	}
	catch( ... )
	{
		countFatals++;
		addMessage(DOMString("[Unknown Error] Unknown Exception"));
	}
}

DOMDocument& EppParser::getDocument()
{
	return *document;
}

bool EppParser::hasError()
{
	return (countWarnings != 0) ||
		   (countErrors != 0) || (countFatals != 0);
}

EppResult * EppParser::getResult()
{
	if( ! this->hasError() )
	{
		return new EppResult(EppError::CODE_NO_ERROR);
	}

	EppResult * result = new EppResult(EppError::CODE_COMMAND_SYNTAX_ERROR);
	if( result == null )
	{
		return result;
	}

	if( this->errorMessages != null )
	{
		for( unsigned int i = 0; i < this->errorMessages->size(); i++ )
		{
			DOMString v = this->errorMessages->elementAt(i);
			result->addValue(v);
		}
	}

	return result;
}

DOMNode* EppParser::getRootNode()
{
	if( hasError() )
	{
		return NULL;
	}
	DOMDocument* doc = &getDocument();
	DOMNodeList* list = doc->getElementsByTagName(XS("epp"));
	if( (list == null) || (list->getLength() == 0) )
	{
		return NULL;
	}
	return list->item(0);
}

void EppParser::warning( const SAXParseException& e )
{
	countWarnings++;
	addMessage(DOMString("[Warning] ") + getLoc(e) + e.getMessage());
}

void EppParser::error( const SAXParseException& e )
{
	countErrors++;
	addMessage(DOMString("[Error] ") + getLoc(e) + e.getMessage());
}

void EppParser::fatalError( const SAXParseException& e )
{
	countFatals++;
	addMessage(DOMString("[Fatal] ") + getLoc(e) + e.getMessage());
}

void EppParser::resetErrors()
{
	countWarnings = 0;
	countErrors = 0;
	countFatals = 0;
}

DOMString EppParser::getLoc( const SAXParseException& e )
{
	DOMString s = DOMString(e.getSystemId());
	char buf[64];
	(void) ::sprintf(buf, "line:%d column:%d ", e.getLineNumber(), e.getColumnNumber());
	s += buf;

	return s;
}

DOMString EppParser::toString()
{
	DOMString str = DOMString("EppParser:");
	//	str += " warnings=" + countWarnings;
	//	str += " errors=" + countErrors;
	//	str += " fatals=" + countFatals;
	char buf[128];
	sprintf(buf, " warnings=%d errors=%d fatals=%d",
		countWarnings, countErrors, countFatals);
	str += buf;
	return str;
}


text:
package net.jproffa.test;

import net.jproffa.testproject.IterativeExample;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import net.jproffa.profiler.ClassBlacklist;
import net.jproffa.profiler.Util;
import net.jproffa.profiler.WithProfiling;

import static org.junit.Assert.*;
import org.junit.Rule;

public class BlacklistTest {

    @Rule public WithProfiling profiling = WithProfiling.rule();

    public BlacklistTest() {
    }

    @Test
    public void testProfileDataPackageBlacklist() {
        IterativeExample.iterativeFunction(5);
        List<String> blacklist = new ArrayList<String>();
        blacklist.add("net/jproffa/testproject/");
        String basicBlockCostsString = Util.getBasicBlockCostsString(false, blacklist);
        assertFalse(basicBlockCostsString.contains("com/mycompany/testproject/"));
    }

    @Test
    public void testProfileDataClassBlacklist() {
        IterativeExample.iterativeFunction(5);
        List<String> blacklist = new ArrayList<String>();
        blacklist.add("net/jproffa/testproject/IterativeExample");
        String basicBlockCostsString = Util.getBasicBlockCostsString(false, blacklist);
        assertFalse(basicBlockCostsString.contains("net/jproffa/testproject/IterativeExample"));
    }

    @Test
    public void testProfileDataMethodBlacklist() {
        IterativeExample.iterativeFunction(5);
        List<String> blacklist = new ArrayList<String>();
        blacklist.add("net/jproffa/testproject/IterativeExample.iterativeFunction");
        String basicBlockCostsString = Util.getBasicBlockCostsString(false, blacklist);
        assertFalse(basicBlockCostsString.contains("net/jproffa/testproject/IterativeExample.iterativeFunction"));

        IterativeExample.factorialWhileFunction(6);
        basicBlockCostsString = Util.getBasicBlockCostsString(false, blacklist);
        assertTrue(basicBlockCostsString.contains("net/jproffa/testproject/IterativeExample.factorialWhileFunction"));
    }

    @Test
    public void testDoesntAddIdenticalEntriesTwice() {
        ClassBlacklist.add(this.getClass(), this.getClass());
        int count = 0;
        for (String entry : ClassBlacklist.getBlacklist()) {
            if (entry.equals(this.getClass().getName().replace(".", "/"))) {
                ++count;
            }
        }
        assertEquals(1, count);
    }

}


text:
#ifdef __FreeBSD__
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: head/sys/netinet/sctp_auth.h 310590 2016-12-26 11:06:41Z tuexen $");
#endif

#ifndef _NETINET_SCTP_AUTH_H_
#define _NETINET_SCTP_AUTH_H_

#include <netinet/sctp_os.h>

/* digest lengths */
#define SCTP_AUTH_DIGEST_LEN_SHA1	20
#define SCTP_AUTH_DIGEST_LEN_SHA256	32
#define SCTP_AUTH_DIGEST_LEN_MAX	SCTP_AUTH_DIGEST_LEN_SHA256

/* random sizes */
#define SCTP_AUTH_RANDOM_SIZE_DEFAULT	32
#define SCTP_AUTH_RANDOM_SIZE_REQUIRED	32

/* union of all supported HMAC algorithm contexts */
typedef union sctp_hash_context {
	SCTP_SHA1_CTX sha1;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
	SCTP_SHA256_CTX sha256;
#endif
} sctp_hash_context_t;

typedef struct sctp_key {
	uint32_t keylen;
	uint8_t key[];
} sctp_key_t;

typedef struct sctp_shared_key {
	LIST_ENTRY(sctp_shared_key) next;
	sctp_key_t *key;	/* key text */
	uint32_t refcount;	/* reference count */
	uint16_t keyid;		/* shared key ID */
	uint8_t deactivated;	/* key is deactivated */
} sctp_sharedkey_t;

LIST_HEAD(sctp_keyhead, sctp_shared_key);

/* authentication chunks list */
typedef struct sctp_auth_chklist {
	uint8_t chunks[256];
	uint8_t num_chunks;
} sctp_auth_chklist_t;

/* hmac algos supported list */
typedef struct sctp_hmaclist {
	uint16_t max_algo;	/* max algorithms allocated */
	uint16_t num_algo;	/* num algorithms used */
	uint16_t hmac[];
} sctp_hmaclist_t;

/* authentication info */
typedef struct sctp_authinformation {
	sctp_key_t *random;	/* local random key (concatenated) */
	uint32_t random_len;	/* local random number length for param */
	sctp_key_t *peer_random;/* peer's random key (concatenated) */
	sctp_key_t *assoc_key;	/* cached concatenated send key */
	sctp_key_t *recv_key;	/* cached concatenated recv key */
	uint16_t active_keyid;	/* active send keyid */
	uint16_t assoc_keyid;	/* current send keyid (cached) */
	uint16_t recv_keyid;	/* last recv keyid (cached) */
} sctp_authinfo_t;

/*
 * Macros
 */
#define sctp_auth_is_required_chunk(chunk, list) ((list == NULL) ? (0) : (list->chunks[chunk] != 0))

/*
 * function prototypes
 */

/* socket option api functions */
extern sctp_auth_chklist_t *sctp_alloc_chunklist(void);
extern void sctp_free_chunklist(sctp_auth_chklist_t *chklist);
extern void sctp_clear_chunklist(sctp_auth_chklist_t *chklist);
extern sctp_auth_chklist_t *sctp_copy_chunklist(sctp_auth_chklist_t *chklist);
extern int sctp_auth_add_chunk(uint8_t chunk, sctp_auth_chklist_t *list);
extern int sctp_auth_delete_chunk(uint8_t chunk, sctp_auth_chklist_t *list);
extern size_t sctp_auth_get_chklist_size(const sctp_auth_chklist_t *list);
extern int sctp_serialize_auth_chunks(const sctp_auth_chklist_t *list,
    uint8_t *ptr);
extern int sctp_pack_auth_chunks(const sctp_auth_chklist_t *list,
    uint8_t *ptr);
extern int sctp_unpack_auth_chunks(const uint8_t *ptr, uint8_t num_chunks,
    sctp_auth_chklist_t *list);

/* key handling */
extern sctp_key_t *sctp_alloc_key(uint32_t keylen);
extern void sctp_free_key(sctp_key_t *key);
extern void sctp_print_key(sctp_key_t *key, const char *str);
extern void sctp_show_key(sctp_key_t *key, const char *str);
extern sctp_key_t *sctp_generate_random_key(uint32_t keylen);
extern sctp_key_t *sctp_set_key(uint8_t *key, uint32_t keylen);
extern sctp_key_t *sctp_compute_hashkey(sctp_key_t *key1, sctp_key_t *key2,
    sctp_key_t *shared);

/* shared key handling */
extern sctp_sharedkey_t *sctp_alloc_sharedkey(void);
extern void sctp_free_sharedkey(sctp_sharedkey_t *skey);
extern sctp_sharedkey_t *sctp_find_sharedkey(struct sctp_keyhead *shared_keys,
    uint16_t key_id);
extern int sctp_insert_sharedkey(struct sctp_keyhead *shared_keys,
    sctp_sharedkey_t *new_skey);
extern int sctp_copy_skeylist(const struct sctp_keyhead *src,
    struct sctp_keyhead *dest);
/* ref counts on shared keys, by key id */
extern void sctp_auth_key_acquire(struct sctp_tcb *stcb, uint16_t keyid);
extern void sctp_auth_key_release(struct sctp_tcb *stcb, uint16_t keyid,
    int so_locked);

/* hmac list handling */
extern sctp_hmaclist_t *sctp_alloc_hmaclist(uint16_t num_hmacs);
extern void sctp_free_hmaclist(sctp_hmaclist_t *list);
extern int sctp_auth_add_hmacid(sctp_hmaclist_t *list, uint16_t hmac_id);
extern sctp_hmaclist_t *sctp_copy_hmaclist(sctp_hmaclist_t *list);
extern sctp_hmaclist_t *sctp_default_supported_hmaclist(void);
extern uint16_t sctp_negotiate_hmacid(sctp_hmaclist_t *peer,
    sctp_hmaclist_t *local);
extern int sctp_serialize_hmaclist(sctp_hmaclist_t *list, uint8_t *ptr);
extern int sctp_verify_hmac_param(struct sctp_auth_hmac_algo *hmacs,
    uint32_t num_hmacs);

extern sctp_authinfo_t *sctp_alloc_authinfo(void);
extern void sctp_free_authinfo(sctp_authinfo_t *authinfo);

/* keyed-HMAC functions */
extern uint32_t sctp_get_auth_chunk_len(uint16_t hmac_algo);
extern uint32_t sctp_get_hmac_digest_len(uint16_t hmac_algo);
extern uint32_t sctp_hmac(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
    uint8_t *text, uint32_t textlen, uint8_t *digest);
extern int sctp_verify_hmac(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
    uint8_t *text, uint32_t textlen, uint8_t *digest, uint32_t digestlen);
extern uint32_t sctp_compute_hmac(uint16_t hmac_algo, sctp_key_t *key,
    uint8_t *text, uint32_t textlen, uint8_t *digest);
extern int sctp_auth_is_supported_hmac(sctp_hmaclist_t *list, uint16_t id);

/* mbuf versions */
extern uint32_t sctp_hmac_m(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
    struct mbuf *m, uint32_t m_offset, uint8_t *digest, uint32_t trailer);
extern uint32_t sctp_compute_hmac_m(uint16_t hmac_algo, sctp_key_t *key,
    struct mbuf *m, uint32_t m_offset, uint8_t *digest);

/*
 * authentication routines
 */
extern void sctp_clear_cachedkeys(struct sctp_tcb *stcb, uint16_t keyid);
extern void sctp_clear_cachedkeys_ep(struct sctp_inpcb *inp, uint16_t keyid);
extern int sctp_delete_sharedkey(struct sctp_tcb *stcb, uint16_t keyid);
extern int sctp_delete_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid);
extern int sctp_auth_setactivekey(struct sctp_tcb *stcb, uint16_t keyid);
extern int sctp_auth_setactivekey_ep(struct sctp_inpcb *inp, uint16_t keyid);
extern int sctp_deact_sharedkey(struct sctp_tcb *stcb, uint16_t keyid);
extern int sctp_deact_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid);

extern void sctp_auth_get_cookie_params(struct sctp_tcb *stcb, struct mbuf *m,
    uint32_t offset, uint32_t length);
extern void sctp_fill_hmac_digest_m(struct mbuf *m, uint32_t auth_offset,
    struct sctp_auth_chunk *auth, struct sctp_tcb *stcb, uint16_t key_id);
extern struct mbuf *sctp_add_auth_chunk(struct mbuf *m, struct mbuf **m_end,
    struct sctp_auth_chunk **auth_ret, uint32_t *offset,
    struct sctp_tcb *stcb, uint8_t chunk);
extern int sctp_handle_auth(struct sctp_tcb *stcb, struct sctp_auth_chunk *ch,
    struct mbuf *m, uint32_t offset);
extern void sctp_notify_authentication(struct sctp_tcb *stcb,
    uint32_t indication, uint16_t keyid, uint16_t alt_keyid, int so_locked);
extern int sctp_validate_init_auth_params(struct mbuf *m, int offset,
    int limit);
extern void sctp_initialize_auth_params(struct sctp_inpcb *inp,
    struct sctp_tcb *stcb);

/* test functions */
#ifdef SCTP_HMAC_TEST
extern void sctp_test_hmac_sha1(void);
extern void sctp_test_authkey(void);
#endif
#endif /* __SCTP_AUTH_H__ */


text:
@interface UIControl (Private)

- (NSArray*)getBlockActionHandlers;
- (void)setActionHandlers:(NSArray*)actionHandlers;

@end

@implementation UIControl (Private)

- (NSArray*)getBlockActionHandlers
{
    NSArray *actionHandlersArray = objc_getAssociatedObject(self, kBlockActionHandlersArrayKey);

    if (!actionHandlersArray) {
        actionHandlersArray = [NSArray new];
        objc_setAssociatedObject(self, kBlockActionHandlersArrayKey, actionHandlersArray, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    return actionHandlersArray;
}

- (void)setActionHandlers:(NSArray *)actionHandlers
{
    objc_setAssociatedObject(self, kBlockActionHandlersArrayKey, actionHandlers, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

@implementation UIControl (BlockActions)

- (void)addAction:(ActionBlock)anActionBlock forControlEvents:(UIControlEvents)aControlEvents
{
    DXBlockActionHandler *blockHandler = [DXBlockActionHandler blockHandlerWithBlock:anActionBlock];

    [self addTarget:blockHandler
          action:@selector(callBlockAction:)
          forControlEvents:aControlEvents];

    NSArray *actionHandlers = [self getBlockActionHandlers];

    actionHandlers = [actionHandlers arrayByAddingObject:blockHandler];

    [self setActionHandlers:actionHandlers];
}

@end


text:
Ex3
================

``` r
setwd("C:\\Users\\Ben\\Documents\\R\\Ex3")
```

### Twitter API

This is R code to get twitter data using their API

``` r
#install.packages("devtools")
#devtools::install_github("mkearney/rtweet")
library(rtweet)
```

    ## Welcome to rtweet v0.4.1!

``` r
appname <- "AppName"
consumerKey <- "myKey"
consumerSecret <- "mySecretKey"
#twitter_token <- create_token(
#    app = appname,
#    consumer_key = consumerKey,
#    consumer_secret = consumerSecret)
mk <- as.data.frame(read.csv("mk_id.csv",colClasses = 'character'))
mk_follow <- NA
j <-0
for(i in mk$id){
  follows <- get_friends(i,parse = T)
  mk_follow[j+1] <- follows
  j <- j+1
}
```

We used python to get our data here is code: <https://github.com/BenEfrati/ex1/blob/master/network%20analysis/init.py>

The id is the twitter user id of MKs (Members of Knesset) The edges in the graph are friends of each user and the vertices are the MKs.

``` r
library(igraph)
```

    ##
    ## Attaching package: 'igraph'

    ## The following object is masked from 'package:rtweet':
    ##
    ##     %>%

    ## The following objects are masked from 'package:stats':
    ##
    ##     decompose, spectrum

    ## The following object is masked from 'package:base':
    ##
    ##     union

``` r
md_name <- as.data.frame(read.csv('mk_id.csv',colClasses = 'character'))
data_mk <- as.data.frame(read.csv('friends.csv',colClasses = 'character'))
new <- data_mk
new[] <- md_name$name[match(unlist(data_mk), md_name$id)]
new <- na.omit(new)
twitterg <- graph.data.frame(new, directed = F)
degr.score <- degree(twitterg)
V(twitterg)$size <- degr.score/15
V(twitterg)$name <- ifelse(V(twitterg)$size>10,V(twitterg)$name,NA)
#twitterg$layout <- layout.fruchterman.reingold(twitterg, niter=5000)
plot( twitterg, layout = layout.reingold.tilford,
      edge.width = 1,
      edge.arrow.width = 0.3,
      vertex.size = 5,
      edge.arrow.size = 0.5,
      vertex.size2 = 3,
      vertex.label.cex = 1,
      asp = 0.35,
      margin = -0.1)
```

![](twitter_files/figure-markdown_github/unnamed-chunk-3-1.png)

``` r
plot(twitterg,layout=layout.circle)
```

![](twitter_files/figure-markdown_github/unnamed-chunk-3-2.png)

``` r
igraph.options(plot.layout=layout.graphopt, vertex.size=7)

plot(twitterg, asp=0)
```

![](twitter_files/figure-markdown_github/unnamed-chunk-3-3.png)

on this graph you can see that there is connection almost between all the members, the few white areas shows on the missing connections but you can see by that graph that almost everyone connected

``` r
#restore names and sizes
twitterg <- graph.data.frame(new, directed = F)
```

three plots for the same graph, in first one is divided to three groups and the second plot is graphopt which try to optimize the view. the third is a circle. As we can see, all the Mks are connected so the edges overrides each other \#\#Centrality

### Compute betweenes

``` r
library(igraph)
between <- betweenness(twitterg)
maxBetweenes <- which.max(between)
cat("The actor with the maximum betweenes is:\n")
```

    ## The actor with the maximum betweenes is:

``` r
maxBetweenes
```

    ## Dov Khenin
    ##         14

### Compute Closeness

``` r
library(igraph)
close <- closeness(twitterg)
maxCloseness <- which.max(close)
cat("The actor with the maximum closeness is:\n")
```

    ## The actor with the maximum closeness is:

``` r
maxCloseness
```

    ## Nava Boker
    ##         50

### Compute Closeness

``` r
library(igraph)
eigen <- eigen_centrality(twitterg, directed = F)
maxEigen <- which.max(eigen$vector)
cat("The actor with the maximum eigenvector is:\n")
```

    ## The actor with the maximum eigenvector is:

``` r
maxEigen
```

    ## Dov Khenin
    ##         14

Communities
-----------

### First algorithm

cluster\_edge\_betweenness performs this algorithm by calculating the edge betweenness of the graph, removing the edge with the highest edge betweenness score, then recalculating edge betweenness of the edges and again removing the one with the highest score, etc.

``` r
set.seed(123)
tgc <- cluster_edge_betweenness(twitterg,directed = F)
print("Number of communities:")
```

    ## [1] "Number of communities:"

``` r
print(length(tgc))
```

    ## [1] 1

``` r
print("Size of communities:")
```

    ## [1] "Size of communities:"

``` r
print(sizes(tgc))
```

    ## Community sizes
    ##  1
    ## 73

``` r
print("Modularity is:")
```

    ## [1] "Modularity is:"

``` r
print(modularity(tgc))
```

    ## [1] 0

``` r
plot(tgc,twitterg)
```

![](twitter_files/figure-markdown_github/unnamed-chunk-8-1.png)

### Second algorithm

``` r
set.seed(123)
tgreedy <- cluster_leading_eigen(twitterg)
print("Number of communities:")
```

    ## [1] "Number of communities:"

``` r
print(length(tgreedy))
```

    ## [1] 2

``` r
print("Size of communities:")
```

    ## [1] "Size of communities:"

``` r
print(sizes(tgreedy))
```

    ## Community sizes
    ##  1  2
    ## 39 34

``` r
print("Modularity is:")
```

    ## [1] "Modularity is:"

``` r
print(modularity(tgreedy))
```

    ## [1] 0.1003118

``` r
plot(tgreedy,twitterg)
```

![](twitter_files/figure-markdown_github/unnamed-chunk-9-1.png)


text:
'''
8. The crossing river problemsolving techniques: BFS, GBFS
On one side of a river there are an adult, two children and a tiny little boat. The people
want to cross the river by boat. The tiny little boat can take either two children, either one child,
either one adult. Determine a sequence of moves to cross the river.

ACC -> binary representation
'''

import Queue

A = 3
B = 1
C = 2

class State:
    def __init__(self, conf):
        self._conf = conf

    def getState(self):
        return self._conf

    def move(self, arr):
        vals = [((self._conf & (1 << x)) > 0) for x in arr]
        uniq = set(vals)
        if len(uniq) != 1:
            return self
        else:
            now = State(self.getState())
            for x in arr:
                now._conf = now._conf ^ (1 << x)
            return now

    #BCCA
    def __eq__(self, other):
        return self.getState() == other.getState()

    def charFromPos(self, pos):
        if pos == 0:
            return "B"
        elif pos <= A:
            return "A"
        elif pos <= A + C:
            return "C"

    def __str__(self):
        binary = bin(self.getState())[2:].zfill(A + B + C)[::-1]
        left_side = [pos for pos in range(len(binary)) if binary[pos] == '0']
        right_side = [pos for pos in range(len(binary)) if binary[pos] == '1']
        left_str = ''.join([self.charFromPos(pos) for pos in left_side])
        right_str = ''.join([self.charFromPos(pos) for pos in right_side])
        return left_str.ljust(A + B + C + 10 - len(right_str)) + right_str

    def __repr__(self):
        return self.__str__()

    def __hash__(self):
        return self._conf

    def __cmp__(self, other):
        c1 = bin(self._conf).count('1')
        c2 = bin(other._conf).count('1')
        if c1 == c2:
            return 0
        elif c1 < c2:
            return -1
        else:
            return 1

class Problem:
    def __init__(self):
        self._initState = State(0)
        self._finalState = State((1 << (A + B + C)) - 1)

    def getInitialState():
        return self._initState

    def getFinalState():
        return self._finalState

    def expand(self, state):
        now = []
        #the bits are ordered like thos: 0 - boat, 1 .. A - adults, A + 1 .. A + C -> childs

        #move every adult first
        for i in range(0, A):
            now.append(state.move([0, i + 1]))

        #move every child
        for i in range(0, C):
            now.append(state.move([0, A + i + 1]))

        #move every pair of two children
        for i in range(0, C):
            for j in range(i + 1, C):
                now.append(state.move([0, A + i + 1, A + j + 1]))
        return now

    def heuristic(self, s1, s2):
        x1 = str(s1).count("1")
        x2 = str(s2).count("1")
        if x1 == x2:
            return 0
        elif x1 < x2:
            return -1
        else:
            return 1

class Controller:
    def __init__(self, problem):
        self._problem = problem

    def getProblem(self):
        return self._problem

    def orderStates(self, states):
        sortSt = sorted(states)
        return sortSt

    def findSol(self, now, dad):
        ans = [now]
        while now != self._problem._initState:
            now = dad[now]
            ans.insert(0, now)
        return ans

    def bfs(self, p):
        q = []
        vis = []
        dad = {}
        q.append(self._problem._initState)
        vis.append(self._problem._initState)
        while len(q) > 0:                           #while there are states in the queue
            now = q.pop(0)                          #get the first one
            if now == self._problem._finalState:
                return self.findSol(now, dad)
            for nxt in self._problem.expand(now):
                if nxt not in vis:
                    vis.append(nxt)
                    dad[nxt] = now
                    q.append(nxt)
        return []

    def gbfs(self, p):
        q = []
        vis = []
        dad = {}
        q.append(self._problem._initState)
        vis.append(self._problem._initState)
        while len(q) > 0:
            now = q.pop(0)
            if now == self._problem._finalState:
                return self.findSol(now, dad)
            for nxt in self.orderStates(self._problem.expand(now)):
                if nxt not in vis:
                    vis.append(nxt)
                    dad[nxt] = now
                    q.append(nxt)
        return []

class UI:
    def __init__(self, ctrl):
        self._ctrl = ctrl

    def printMainMenu(self):
        print("Currently having: " + str(B) + " boat " + str(A) + " adult(s) " + str(C) + " child(ren)\n")
        print("1. BFS")
        print("2. GBFS")
        print("3. Change the number of Adults: ")
        print("4. Change the number of Children: ")
        print("x. Exit")

    def run(self):
        global A, B, C
        while True:
            self.printMainMenu()
            op = raw_input("Input command: ")
            if op == "x":
                return
            elif op == "1":
                print("BFS: The road is: \n")
                path = self._ctrl.bfs(self)
                for x in path:
                    print(x)
                print("")
            elif op == "2":
                print("GBFS: The road is: \n")
                path = self._ctrl.gbfs(self)
                for x in path:
                    print(x)
                print("")
            elif op == "3":
                x = raw_input("A = ")
                try:
                    A = int(x)
                    if A < 0:
                        raise ValueError
                except ValueError as e:
                    print("Please insert a valid positive integer")
            elif op == "4":
                x = raw_input("C = ")
                try:
                    C = int(x)
                    if C < 0:
                        raise ValueError
                except ValueError as e:
                    print("Please insert a valid positive integer")
            else:
                print("Wrong command")

p = Problem()
ctrl = Controller(p)
ui = UI(ctrl)
ui.run()


text:
<?php

namespace Google\Cloud\Samples\CloudSQL\Postgres\Tests;

use Google\Cloud\Samples\CloudSQL\Postgres\Votes;
use PDO;
use PDOException;
use PDOStatement;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use RuntimeException;

class VotesTest extends TestCase
{
    private $conn;

    public function setUp(): void
    {
        $this->conn = $this->prophesize(PDO::class);
    }

    public function testCreateTableIfNotExistsTableExists()
    {
        $stmt = $this->prophesize(PDOStatement::class);
        $stmt->execute()->shouldBeCalled();

        $this->conn->prepare('SELECT 1 FROM votes')
            ->shouldBeCalled()
            ->willReturn($stmt->reveal());

        $this->conn->exec(Argument::any())->shouldNotBeCalled();

        $votes = new Votes($this->conn->reveal());
        $votes->createTableIfNotExists();
    }

    public function testCreateTableIfNotExistsTableDoesNotExist()
    {
        $stmt = $this->prophesize(PDOStatement::class);
        $stmt->execute()->shouldBeCalled()->willThrow(
            new PDOException('foo')
        );

        $this->conn->prepare('SELECT 1 FROM votes')
            ->shouldBeCalled()
            ->willReturn($stmt->reveal());

        $this->conn->exec(Argument::containingString('CREATE TABLE votes'))
            ->shouldBeCalled();

        $votes = new Votes($this->conn->reveal());
        $votes->createTableIfNotExists();
    }

    public function testListVotes()
    {
        $rows = [
            ['foo' => 'bar']
        ];

        $stmt = $this->prophesize(PDOStatement::class);
        $stmt->execute()->shouldBeCalled();
        $stmt->fetchAll(PDO::FETCH_ASSOC)->shouldBeCalled()
            ->willReturn($rows);

        $this->conn->prepare(Argument::type('string'))
            ->shouldBeCalled()
            ->willReturn($stmt->reveal());

        $votes = new Votes($this->conn->reveal());

        $this->assertEquals($rows, $votes->listVotes());
    }

    public function testGetCountByValue()
    {
        $val = 'TABS';
        $res = 10;

        $stmt = $this->prophesize(PDOStatement::class);
        $stmt->execute([$val])
            ->shouldBeCalled();

        $stmt->fetch(PDO::FETCH_COLUMN)
            ->shouldBeCalled()
            ->willReturn((string) $res);

        $this->conn->prepare(Argument::containingString('SELECT COUNT(vote_id)'))
            ->shouldBeCalled()
            ->willReturn($stmt->reveal());

        $votes = new Votes($this->conn->reveal());

        $this->assertEquals($res, $votes->getCountByValue($val));
    }

    public function testInsertVote()
    {
        $val = 'TABS';

        $stmt = $this->prophesize(PDOStatement::class);
        $stmt->bindParam('voteValue', $val)
            ->shouldBeCalled();

        $stmt->execute()->shouldBeCalled()->willReturn(true);

        $this->conn->prepare(Argument::containingString('INSERT INTO votes'))
            ->shouldBeCalled()
            ->willReturn($stmt->reveal());

        $votes = new Votes($this->conn->reveal());
        $this->assertTrue($votes->insertVote($val));
    }

    public function testInsertVoteFailed()
    {
        $this->expectException(RuntimeException::class);

        $val = 'TABS';

        $stmt = $this->prophesize(PDOStatement::class);
        $stmt->bindParam('voteValue', $val)
            ->shouldBeCalled();

        $stmt->execute()->shouldBeCalled()
            ->willThrow(new PDOException('Op failed'));

        $this->conn->prepare(Argument::containingString('INSERT INTO votes'))
            ->shouldBeCalled()
            ->willReturn($stmt->reveal());

        $votes = new Votes($this->conn->reveal());
        $votes->insertVote($val);
    }
}


text:
package org.apache.felix.eventadmin.bridge.useradmin;

import java.util.Arrays;
import java.util.Hashtable;

import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.service.useradmin.UserAdmin;
import org.osgi.service.useradmin.UserAdminEvent;
import org.osgi.service.useradmin.UserAdminListener;

/**
 * @author Felix Project Team
 */
public class UserAdminEventToEventAdminBridge implements UserAdminListener
{
    private final BundleContext m_context;

    public UserAdminEventToEventAdminBridge(final BundleContext context)
    {
        m_context = context;

        m_context
            .registerService(UserAdminListener.class.getName(), this, null);
    }

    public void roleChanged(final UserAdminEvent event)
    {
        final ServiceReference ref = m_context
            .getServiceReference(EventAdmin.class.getName());

        if(null != ref)
        {
            final EventAdmin eventAdmin = (EventAdmin) m_context.getService(ref);

            if(null != eventAdmin)
            {
                final String topic;

                switch(event.getType())
                {
                    case UserAdminEvent.ROLE_CHANGED:
                        topic = "org/osgi/service/useradmin/UserAdmin/ROLE_CHANGED";
                        break;
                    case UserAdminEvent.ROLE_CREATED:
                        topic = "org/osgi/service/useradmin/UserAdmin/ROLE_CREATED";
                        break;
                    case UserAdminEvent.ROLE_REMOVED:
                        topic = "org/osgi/service/useradmin/UserAdmin/ROLE_REMOVED";
                        break;
                    default:
                        m_context.ungetService(ref);
                        return;
                }

                final Hashtable properties = new Hashtable();

                properties.put(EventConstants.EVENT, event);

                properties.put("role", event.getRole());

                properties.put("role.name", event.getRole().getName());

                properties.put("role.type", new Integer(event.getRole().getType()));

                final ServiceReference eventRef = event
                    .getServiceReference();

                if(null == eventRef)
                {
                    throw new IllegalArgumentException(
                        "UserAdminEvent.getServiceReference() may not be null");
                }

                properties.put(EventConstants.SERVICE, eventRef);

                properties.put(EventConstants.SERVICE_ID, eventRef
                    .getProperty(EventConstants.SERVICE_ID));

                final Object objectClass = eventRef
                    .getProperty(Constants.OBJECTCLASS);

                if(!(objectClass instanceof String[])
                    || !Arrays.asList((String[]) objectClass).contains(
                        UserAdmin.class.getName()))
                {
                    throw new IllegalArgumentException(
                        "Bad objectclass: " + objectClass);
                }

                properties.put(EventConstants.SERVICE_OBJECTCLASS, objectClass);

                properties.put(EventConstants.SERVICE_PID, eventRef
                    .getProperty(EventConstants.SERVICE_PID));

                eventAdmin.postEvent(new Event(topic, properties));

                m_context.ungetService(ref);
            }
        }
    }
}


text:
cask 'font-raleway' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/trunk/ofl/raleway',
      using:      :svn,
      revision:   '50',
      trust_cert: true
  name 'Raleway'
  homepage 'https://www.google.com/fonts/specimen/Raleway'

  depends_on macos: '>= :sierra'

  font 'Raleway-Black.ttf'
  font 'Raleway-BlackItalic.ttf'
  font 'Raleway-Bold.ttf'
  font 'Raleway-BoldItalic.ttf'
  font 'Raleway-ExtraBold.ttf'
  font 'Raleway-ExtraBoldItalic.ttf'
  font 'Raleway-ExtraLight.ttf'
  font 'Raleway-ExtraLightItalic.ttf'
  font 'Raleway-Italic.ttf'
  font 'Raleway-Light.ttf'
  font 'Raleway-LightItalic.ttf'
  font 'Raleway-Medium.ttf'
  font 'Raleway-MediumItalic.ttf'
  font 'Raleway-Regular.ttf'
  font 'Raleway-SemiBold.ttf'
  font 'Raleway-SemiBoldItalic.ttf'
  font 'Raleway-Thin.ttf'
  font 'Raleway-ThinItalic.ttf'
end


text:
Demo Swift Browser

execution
'''
>$ swift smallswiftbrowser.swift
'''


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

describe EYCli::Controller::Accounts do
  it "returns the first account if we don't provide a name and the user has only one account" do
    expected = EYCli::Model::Account.new({:id => 1, :name => 'foo'})
    stub_request(:get, 'http://example.com/accounts').
      to_return(:status => 200, :body => to_json({'accounts' => [expected]}))

    account = subject.fetch_account
    account.should == expected
  end

  it "returns nil if we don't find the account by the name provided" do
    expected = EYCli::Model::Account.new({:id => 1, :name => 'foo'})
    stub_request(:get, 'http://example.com/accounts').
      to_return(:status => 200, :body => to_json({'accounts' => [expected]}))

    subject.fetch_account('bar').should be_nil
  end

  it "returns nil if the user hasn't created an account yet" do
    stub_request(:get, 'http://example.com/accounts').
      to_return(:status => 200, :body => to_json({'accounts' => []}))

    subject.fetch_account.should be_nil
  end

  it "returns the account selected by the user" do
    account1 = EYCli::Model::Account.new({:id => 1, :name => 'foo'})
    account2 = EYCli::Model::Account.new({:id => 2, :name => 'bar'})
    account3 = EYCli::Model::Account.new({:id => 3, :name => 'baz'})
    stub_request(:get, 'http://example.com/accounts').
      to_return(:status => 200, :body => to_json({'accounts' => [account1, account2, account3]}))

    EYCli.term.terminal.should_receive(:choose).and_return('bar')

    account = subject.fetch_account
    account.should == account2
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
    <property name="tu-build-number" type="int">10</property>
    <property name="tu-build-time" type="int">1433207198</property>
    <property name="tu-build-time-str" type="string">2015-06-01 21:06:38</property>
    <id>com.smorgasbork.grilltime</id>
    <name>GrillTime</name>
    <version>1.1.1</version>
    <publisher>priebe</publisher>
    <url>http://www.smorgasbork.com/</url>
    <description>A simple multi-segment grill timer</description>
    <copyright>2015 by priebe</copyright>
    <icon>appicon.png</icon>
    <fullscreen>false</fullscreen>
    <navbar-hidden>false</navbar-hidden>
    <analytics>false</analytics>
    <guid>bce8173a-7b85-4989-a9c1-7c141709fa52</guid>
    <property name="ti.ui.defaultunit" type="string">dp</property>
    <ios>
        <plist>
            <dict>
                <key>UISupportedInterfaceOrientations~iphone</key>
                <array>
                    <string>UIInterfaceOrientationPortrait</string>
                </array>
                <key>UISupportedInterfaceOrientations~ipad</key>
                <array>
                    <string>UIInterfaceOrientationPortrait</string>
                    <string>UIInterfaceOrientationPortraitUpsideDown</string>
                </array>
                <key>UIRequiresPersistentWiFi</key>
                <false/>
                <key>UIPrerenderedIcon</key>
                <false/>
                <key>UIStatusBarHidden</key>
                <false/>
                <key>UIStatusBarStyle</key>
                <string>UIStatusBarStyleDefault</string>
            </dict>
        </plist>
    </ios>
    <android xmlns:android="http://schemas.android.com/apk/res/android">
        <!-- the services tag must be added so that our service will run -->
        <services>
            <service type="interval" url="BackgroundNotification.js"/>
        </services>
        <manifest android:versionCode="1" android:versionName="1.0"
            package="com.smorgasbork.grilltime" xmlns:android="http://schemas.android.com/apk/res/android">
            <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21"/>
            <application android:debuggable="false"
                android:icon="@drawable/appicon"
                android:label="GrillTime"
                android:name="GrilltimeApplication" android:theme="@style/Grilltime">
                <activity
                    android:screenOrientation="portrait"
                    android:configChanges="keyboardHidden|orientation|screenSize"
                    android:label="@string/app_name"
                    android:name=".GrilltimeActivity" android:theme="@style/Theme.Titanium">
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN"/>
                        <category android:name="android.intent.category.LAUNCHER"/>
                    </intent-filter>
                </activity>
                <activity
                    android:screenOrientation="portrait"
                    android:configChanges="keyboardHidden|orientation|screenSize" android:name="org.appcelerator.titanium.TiActivity"/>
                <activity
                    android:screenOrientation="portrait"
                    android:configChanges="keyboardHidden|orientation|screenSize"
                    android:name="org.appcelerator.titanium.TiTranslucentActivity" android:theme="@style/Theme.AppCompat.Translucent"/>
                <activity
                    android:screenOrientation="portrait"
                    android:configChanges="screenSize" android:name="ti.modules.titanium.ui.android.TiPreferencesActivity"/>
                <service android:name="com.smorgasbork.grilltime.BackgroundNotificationService"/>
                <receiver android:name="bencoding.alarmmanager.AlarmNotificationListener"/>
                <receiver android:name="bencoding.alarmmanager.AlarmServiceListener"/>
            </application>
            <uses-permission android:name="android.permission.WAKE_LOCK"/>
            <uses-permission android:name="android.permission.VIBRATE"/>
        </manifest>
    </android>
    <modules>
        <module platform="android">bencoding.alarmmanager</module>
        <module platform="android">com.tripvi.drawerlayout</module>
        <module platform="android">so.hau.tomas.pager</module>
    </modules>
    <deployment-targets>
        <target device="android">true</target>
        <target device="blackberry">false</target>
        <target device="ipad">true</target>
        <target device="iphone">true</target>
        <target device="mobileweb">false</target>
    </deployment-targets>
    <sdk-version>4.1.0.GA</sdk-version>
</ti:app>


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE component SYSTEM "dtds/component.dtd">

<component name="ConversionFactor">

	<entity>

		<property name="id" key="true" type="Long"/>
		<property name="fromUnit" type="String" size="30"/>
		<property name="toUnit" type="String" size="30"/>
		<property name="factor" type="java.math.BigDecimal" scale="6"/>
		<property name="reverseFactor" type="java.math.BigDecimal" size="10" scale="6"/>

	</entity>

</component>


text:
package java.nio;

/**
 * A InvalidMarkException is thrown when reset()
 * is called on a buffer, but there is no mark set previously.
 *
 */
public class InvalidMarkException extends IllegalStateException {

	private static final long serialVersionUID = 1698329710438510774L;

	/**
	 * Constructs an InvalidMarkException.
	 */
	public InvalidMarkException() {
		super();
	}
}