text:
"""
Custom Types for Virtool

"""
from datetime import datetime
from typing import Any, Awaitable, Callable, Dict, List, Sequence, Union

from aiohttp.web import Application, Request, Response

App = Union[Application, Dict[str, Any]]
Document = Dict[str, Union[Dict, List, bool, str, int, float, datetime]]
Projection = Union[Dict[str, bool], Sequence[str]]
RouteHandler = Callable[[Request], Awaitable[Response]]

redpajama_set_name: RedPajamaGithub


text:
App.FormController = Ember.Controller.extend({
  id:'',
  message: '',
  validated_fields: [],
  reset_fields:[],
  actions: {
    removeNotification: function() {
      $(this.id + '-notification').hide();
      this.set('message', "");
    }
  },
  showTooltip: function(field) {
    field_id = this.id + '-' + field;
    $(field_id).tooltip({
      title: 'Please enter ' + this.fieldname[field] + '.',
      placement: 'right',
      trigger: 'manual'
    }).tooltip('show');
  },
  hideTooltips: function() {
    for (var i=0; i< this.validated_fields.length; i++) {
      field_id = this.id + '-' + this.validated_fields[i];
      if (typeof($(field_id).data('tooltip')) !== 'undefined') {
        $(field_id).tooltip('destroy');
      }
    }
  },
  showNotification: function(message) {
    this.set('message', message);
    $(this.id + '-notification').show();
  },
  setDisable: function(state, element) {
    var id;
    if (typeof element === 'undefined') {
      id = this.id;
      $( id + ' :input').prop('disabled', state);
    } else {
      id = this.id + '-' + element;
      if (state) {
        $(id).prop('disabled', state);
      } else {
        $(id).removeProp('disabled');
      }
    }
  },
  validate: function(obj) {
    for (var i=0; i < this.validated_fields.length; i++) {
      field = this.validated_fields[i];
      if (!obj[field]) {
        throw {
          name: 'ValidationError',
          error: field + ' cannot be blank.',
          field: field
        };
      }
    }
  },
  prepare_commit: function(record) {
    try {
      this.hideTooltips();
      this.validate(record);
      this.setDisable(true);
    } catch (e) {
      if (e.name == 'ValidationError') {
        this.showTooltip(e.field);
        return false;
      }
      throw e;
    }
    return true;
  },
  reset_form: function() {
    this.setDisable(false);
    for (var i=0; i < this.reset_fields.length; i++) {
      field = this.reset_fields[i];
      this.set(field, '');
    }
  }
});


text:
typedef struct Vector3_s {
	float x;
	float y;
	float z;
} Vector3_t;

Vector3_t *NewVector3(float x, float y, float z);
void Vector3Set(Vector3_t *out, float x, float y, float z);
void Vector3Normalize(Vector3_t *out, Vector3_t *const in);
void Vector3Add(Vector3_t *out, Vector3_t *const term1, Vector3_t *const term2);
float Vector3Dot(Vector3_t *const term1, Vector3_t *const term2);

#endif


text:
from dxr.testing import DxrInstanceTestCase
from nose.tools import ok_

class BinaryFileTests(DxrInstanceTestCase):
    """Tests that we show something for binary files like images."""

    def test_png(self):
        """Make sure we show a preview of the png."""
        response = self.client().get('/code/source/red_circle.png')
        ok_('src="/code/raw/red_circle.png"' in response.data)
        response = self.client().get('/code/raw/red_circle.png')
        ok_(response.status_code, 200)

    def test_jpeg(self):
        """Make sure we show a preview of the jpeg."""
        response = self.client().get('/code/source/small_blue_circle.jpeg')
        ok_('src="/code/raw/small_blue_circle.jpeg"' in response.data)
        response = self.client().get('/code/raw/small_blue_circle.jpeg')
        ok_(response.status_code, 200)

    def test_jpg(self):
        """Make sure we show a preview of the jpg."""
        response = self.client().get('/code/source/Green circle.jpg')
        ok_('src="/code/raw/Green%20circle.jpg"' in response.data)
        response = self.client().get('/code/raw/Green circle.jpg')
        ok_(response.status_code, 200)

    def test_too_fat(self):
        """Make sure we don't show the preview icon for a file that's too big."""
        response = self.client().get('/code/source/')
        ok_('href="/code/source/Green%20circle.jpg" class="icon image too_fat"' in response.data)

    def test_svg(self):
        """Make sure we show the svg."""
        response = self.client().get('/code/source/yellow_circle.svg')
        ok_('src="/code/raw/yellow_circle.svg"' in response.data)
        response = self.client().get('/code/raw/yellow_circle.svg')
        ok_(response.status_code, 200)

    def test_some_bytes(self):
        """We want some_bytes to show in the folder index, but without its own page."""
        response = self.client().get('/code/source/')
        ok_('some_bytes' in response.data)
        response = self.client().get('/code/source/some_bytes')
        ok_(response.status_code, 404)

    def test_some_bytes(self):
        """We want some_bytes to show on search page, but not be clickable."""
        response = self.client().get('/code/search?q=path%3Asome_bytes&redirect=true')
        ok_('some_bytes' in response.data)
        ok_('href="/code/source/some_bytes"' not in response.data)


text:
namespace paddle {
namespace framework {
namespace ir {

ConvBiasFusePass::ConvBiasFusePass() {
  AddOpCompat(OpCompat("conv2d"))
      .AddInput("Input")
      .IsTensor()
      .End()
      .AddInput("Filter")
      .IsTensor()
      .End()
      .AddInput("Bias")
      .IsTensor()
      .IsOptional()
      .End()
      .AddOutput("Output")
      .IsTensor()
      .End()
      .AddAttr("strides")
      .IsType<std::vector<int>>()
      .End()
      .AddAttr("paddings")
      .IsType<std::vector<int>>()
      .End()
      .AddAttr("padding_algorithm")
      .IsOptional()
      .IsStringIn({"EXPLICIT", "SAME", "VALID"})
      .End()
      .AddAttr("groups")
      .IsNumGE(1)
      .End()
      .AddAttr("dilations")
      .IsType<std::vector<int>>()
      .End()
      .AddAttr("data_format")
      .IsStringIn({"NCHW", "NHWC", "AnyLayout"})
      .End();

  AddOpCompat(OpCompat("elementwise_add"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddInput("Y")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("axis")
      .IsIntIn({1, 3})
      .End();
}

Conv2DTransposeBiasFusePass::Conv2DTransposeBiasFusePass() {
  AddOpCompat(OpCompat("conv2d_transpose"))
      .AddInput("Input")
      .IsTensor()
      .End()
      .AddInput("Filter")
      .IsTensor()
      .End()
      .AddInput("Bias")
      .IsTensor()
      .IsOptional()
      .End()
      .AddOutput("Output")
      .IsTensor()
      .End()
      .AddAttr("output_padding")
      .IsType<std::vector<int>>()
      .IsOptional()
      .End()
      .AddAttr("output_size")
      .IsType<std::vector<int>>()
      .IsOptional()
      .End()
      .AddAttr("groups")
      .IsNumGE(1)
      .End()
      .AddAttr("dilations")
      .IsType<std::vector<int>>()
      .End()
      .AddAttr("strides")
      .IsType<std::vector<int>>()
      .End()
      .AddAttr("paddings")
      .IsType<std::vector<int>>()
      .End()
      .AddAttr("padding_algorithm")
      .IsOptional()
      .IsStringIn({"EXPLICIT", "SAME", "VALID"})
      .End()
      .AddAttr("data_format")
      .IsStringIn({"NCHW", "NHWC", "AnyLayout"})
      .End();

  AddOpCompat(OpCompat("elementwise_add"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddInput("Y")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("axis")
      .IsIntIn({1, 3})
      .End();
}

Conv3DBiasFusePass::Conv3DBiasFusePass() {
  AddOpCompat(OpCompat("conv3d"))
      .AddInput("Input")
      .IsTensor()
      .End()
      .AddInput("Filter")
      .IsTensor()
      .End()
      .AddOutput("Output")
      .IsTensor()
      .End()
      .AddAttr("strides")
      .IsType<std::vector<int>>()
      .End()
      .AddAttr("paddings")
      .IsType<std::vector<int>>()
      .End()
      .AddAttr("padding_algorithm")
      .IsOptional()
      .IsStringIn({"EXPLICIT", "SAME", "VALID"})
      .End()
      .AddAttr("groups")
      .IsNumGE(1)
      .End()
      .AddAttr("dilations")
      .IsType<std::vector<int>>()
      .End()
      .AddAttr("data_format")
      .IsStringIn({"NDHWC", "NCDHW"})
      .End();

  AddOpCompat(OpCompat("elementwise_add"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddInput("Y")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("axis")
      .IsNumGE(1)
      .End();
}

template <typename BinaryOperation>
phi::DenseTensor tensor_apply_eltwise(const phi::DenseTensor& vec_a,
                                      const phi::DenseTensor& vec_b,
                                      BinaryOperation f) {
  PADDLE_ENFORCE_EQ(vec_a.dims(),
                    vec_b.dims(),
                    platform::errors::InvalidArgument(
                        "Input two tensors must have same shape, but they are "
                        "different: %s, %s.",
                        vec_a.dims(),
                        vec_b.dims()));
  phi::DenseTensor vec_y;
  vec_y.Resize(vec_a.dims());
  const float* a = vec_a.data<float>();
  const float* b = vec_b.data<float>();
  float* y = vec_y.mutable_data<float>(platform::CPUPlace());
  for (int i = 0; i < vec_a.numel(); i++) {
    y[i] = f(a[i], b[i]);
  }
  return vec_y;
}

void ConvBiasFusePass::ApplyImpl(ir::Graph* graph) const {
  PADDLE_ENFORCE_NOT_NULL(
      graph, platform::errors::InvalidArgument("Graph cannot be nullptr."));
  FusePassBase::Init(name_scope_, graph);

  auto* scope = param_scope();
  PADDLE_ENFORCE_NOT_NULL(
      scope, platform::errors::InvalidArgument("Scope cannot be nullptr."));

  GraphPatternDetector gpd;
  auto* conv_input =
      gpd.mutable_pattern()
          ->NewNode(patterns::PDNodeName(name_scope_, "conv_input"))
          ->AsInput()
          ->assert_is_op_input(type(), "Input");
  patterns::ConvBias conv_bias_pattern(gpd.mutable_pattern(), name_scope_);
  conv_bias_pattern(conv_input, type());
  int found_conv_bias_count = 0;
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
    VLOG(4) << "handle ConvBias fuse";
    GET_IR_NODE_FROM_SUBGRAPH(conv_weight,
                              conv_weight,
                              conv_bias_pattern);                      // Filter
    GET_IR_NODE_FROM_SUBGRAPH(conv_out, conv_out, conv_bias_pattern);  // tmp
    GET_IR_NODE_FROM_SUBGRAPH(conv, conv, conv_bias_pattern);  // CONV op
    // bias
    GET_IR_NODE_FROM_SUBGRAPH(eltwise_bias, eltwise_bias, conv_bias_pattern);
    // output
    GET_IR_NODE_FROM_SUBGRAPH(eltwise_out, eltwise_out, conv_bias_pattern);
    // elementwise_add op
    GET_IR_NODE_FROM_SUBGRAPH(eltwise, eltwise, conv_bias_pattern);

    PADDLE_ENFORCE_NE(
        subgraph.count(conv_input),
        0,
        platform::errors::NotFound("Detector did not find conv input."));

    // check compat
    if (!IsCompat(subgraph, g)) {
      VLOG(3) << "Pass in op compat failed.";
      return;
    }

    // check if fuse can be done and if MKL-DNN should be used
    FuseOptions fuse_option = FindFuseOption(*conv, *eltwise);
    if (fuse_option == DO_NOT_FUSE || fuse_option == FUSE_NATIVE) {
      VLOG(3) << "do not perform " + type() + "+bias fuse";
      return;
    }

    auto* eltwise_bias_tensor =
        scope->FindVar(eltwise_bias->Name())->GetMutable<phi::DenseTensor>();

    auto input_names = conv->Op()->InputNames();
    bool has_bias = std::find(input_names.begin(), input_names.end(), "Bias") !=
                    input_names.end();

    if (has_bias && conv->Op()->Input("Bias").size() > 0) {
      auto conv_bias_names = conv->Op()->Input("Bias");
      // add eltwise bias to existing conv bias
      PADDLE_ENFORCE_EQ(conv_bias_names.size(),
                        1,
                        platform::errors::NotFound("Can not find var Bias."));
      auto* conv_bias_var = scope->FindVar(conv_bias_names[0]);
      auto* conv_bias_tensor = conv_bias_var->GetMutable<phi::DenseTensor>();
      PADDLE_ENFORCE_EQ(
          conv_bias_tensor->dims(),
          eltwise_bias_tensor->dims(),
          platform::errors::InvalidArgument(
              "Conv bias tensor and eltwise bias tensor "
              "must have same shape, but they are different: %s, %s.",
              conv_bias_tensor->dims(),
              eltwise_bias_tensor->dims()));
      *conv_bias_tensor = tensor_apply_eltwise(
          *conv_bias_tensor, *eltwise_bias_tensor, std::plus<float>());

      conv->Op()->SetOutput("Output",
                            std::vector<std::string>({eltwise_out->Name()}));

      GraphSafeRemoveNodes(graph, {eltwise, conv_out});

      IR_NODE_LINK_TO(conv, eltwise_out);
    } else {
      // take eltwise bias as conv bias
      OpDesc desc;

      desc.SetInput(
          "Input", std::vector<std::string>({subgraph.at(conv_input)->Name()}));
      desc.SetInput("Filter", std::vector<std::string>({conv_weight->Name()}));
      desc.SetInput("Bias", std::vector<std::string>({eltwise_bias->Name()}));
      desc.SetOutput("Output", std::vector<std::string>({eltwise_out->Name()}));
      desc.SetType(type());

      for (auto& attr : conv->Op()->GetAttrMap()) {
        desc.SetAttr(attr.first, attr.second);
      }
      for (auto& attr : conv->Op()->GetRuntimeAttrMap()) {
        desc.SetAttr(attr.first, attr.second);
      }
      auto conv_bias_node = g->CreateOpNode(&desc);

      IR_NODE_LINK_TO(subgraph.at(conv_input), conv_bias_node);
      IR_NODE_LINK_TO(conv_weight, conv_bias_node);
      IR_NODE_LINK_TO(eltwise_bias, conv_bias_node);
      IR_NODE_LINK_TO(conv_bias_node, eltwise_out);

      GraphSafeRemoveNodes(graph, {conv, eltwise, conv_out});
    }

    found_conv_bias_count++;
  };
  gpd(graph, handler);
  AddStatis(found_conv_bias_count);
  if ((!Has("disable_logs") || !Get<bool>("disable_logs")) &&
      found_conv_bias_count > 0) {
    string::PrettyLogDetail("---    fused %d %s with elementwise_add as bias",
                            found_conv_bias_count,
                            type());
  }
}
}  // namespace ir
}  // namespace framework
}  // namespace paddle
REGISTER_PASS(conv_bias_mkldnn_fuse_pass,
              paddle::framework::ir::ConvBiasFusePass);
REGISTER_PASS_CAPABILITY(conv_bias_mkldnn_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .LE("conv2d", 1)
            .LE("elementwise_add", 1));

REGISTER_PASS(conv_transpose_bias_mkldnn_fuse_pass,
              paddle::framework::ir::Conv2DTransposeBiasFusePass);
REGISTER_PASS_CAPABILITY(conv_transpose_bias_mkldnn_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .LE("conv2d_transpose", 2)
            .LE("elementwise_add", 1));

REGISTER_PASS(conv3d_bias_mkldnn_fuse_pass,
              paddle::framework::ir::Conv3DBiasFusePass);


text: az.plot_kde(mu_posterior, values2=tau_posterior)


text:
## Copyright 2015 JAXIO http://www.jaxio.com
##
## 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.
##
$output.java($WebFaces, "CustomExceptionHandler")##

$output.require("java.util.Iterator")##
$output.require("javax.faces.context.ExceptionHandler")##
$output.require("javax.faces.context.ExceptionHandlerWrapper")##
$output.require("javax.faces.event.ExceptionQueuedEvent")##
$output.require("javax.persistence.OptimisticLockException")##
$output.require("org.springframework.dao.DataIntegrityViolationException")##
$output.require("org.springframework.security.access.AccessDeniedException")##
$output.require($WebUtil, "ExceptionUtil")##
$output.require($WebUtil, "MessageUtil")##

/**
 * Exception handling is configured here, in web.xml (see error-page tag) and in faces-config.xml.
 */
public class $output.currentClass extends ExceptionHandlerWrapper {

    private ExceptionHandler wrapped;

    /**
     * Construct a new exception handler around the given wrapped exception handler.
     * @param wrapped The wrapped exception handler.
     */
    public ${output.currentClass}(ExceptionHandler wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public void handle() {
        Iterator<ExceptionQueuedEvent> unhandledExceptionQueuedEvents = getUnhandledExceptionQueuedEvents().iterator();

        if (unhandledExceptionQueuedEvents.hasNext()) {
            Throwable e = unhandledExceptionQueuedEvents.next().getContext().getException();

            // map general purpose exception to error message
            if (ExceptionUtil.isCausedBy(e, OptimisticLockException.class)) {
                MessageUtil.getInstance().error("error_concurrent_modification");
                unhandledExceptionQueuedEvents.remove();
            } else if (ExceptionUtil.isCausedBy(e, DataIntegrityViolationException.class)) {
                MessageUtil.getInstance().error("error_data_integrity_violation");
                unhandledExceptionQueuedEvents.remove();
            } else if (ExceptionUtil.isCausedBy(e, AccessDeniedException.class)) {
                // works only if the spring security filter is before the exception filter,
                // that is if the exception filter handles the exception first.
                MessageUtil.getInstance().error("error_access_denied");
                unhandledExceptionQueuedEvents.remove();
            }
            // exception will be handled by the wrapped exception handler.
        }

        wrapped.handle();
    }

    @Override
    public ExceptionHandler getWrapped() {
        return wrapped;
    }
}


text:
import { SlickGridQuickFilter2Page } from './app.po';

describe('slick-grid-quick-filter2 App', () => {
  let page: SlickGridQuickFilter2Page;

  beforeEach(() => {
    page = new SlickGridQuickFilter2Page();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to app!');
  });
});


text:
namespace onnxruntime {
namespace contrib {

template <typename T1, typename T2>
class DropoutGrad final : public OpKernel {
 public:
  DropoutGrad(const OpKernelInfo& info) : OpKernel{info} {
  }

  Status Compute(OpKernelContext* context) const override;
};

}  // namespace contrib
}  // namespace onnxruntime


text:
angular-video
=============

A directive that takes in a vimeo or a youtube url and converts it into an embedded friendly url and the displays it.

###Contributing
angular-video is a free and open source library, and we appreciate any help you're willing to give.

### What it does
* Converts any url into an embedded friendly url (according to vimeo's and youtube's preference)
* Gets the trusted resource url using angular's trustAsResourceUrl() functionality

### Available url formats
* http://www.youtube.com/watch?v=[xyzxyz]
* http://youtu.be/[xyzxyz]
* http://www.youtube.com/embed/[xyzxyz]
* http://vimeo.com/[xyzxyz]

### Getting Started
Download the code, and include the anguvideo.js file in your page. Then add the angvideo module to your Angular App file, e.g.
```html
var app = angular.module('app', ["anguvideo"]);
```

### Usage

```html
<anguvideo ng-model="modelContainingURL" width="100%" height="200"></anguvideo>
```

```html
<div anguvideo ng-model="modelContainingURL" width="250" height="250"></div>
```
### Description of attributes
| Attribute        | Description           | Required | Example  |
| :------------- |:-------------| :-----:| :-----|
| ngModel | An angular model containing the URL | Yes | $scope.URL |
| width | The desired width of the video | No | 50% or 500px |
| height | The desired height of the video | No | 400 |
| hideControls | Set to hide YouTube title and player controls | No | true |

### License
The anguvideo project is covered by the [MIT License](http://opensource.org/licenses/MIT "MIT License").

The MIT License (MIT)

Copyright (c) 2014 Mariandi Stylianou, and contributors to the angular-video project.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nat. Arr. Brit. Pl. (London) 1: 604 (1821)

#### Original name
Agaricus badipus J. Otto

### Remarks
null


text:
package org.qi4j.library.http;

import javax.servlet.Filter;
import org.qi4j.api.mixin.Mixins;
import org.qi4j.api.service.ServiceComposite;

/**
 * JAVADOC
 */
// START SNIPPET: filterservice
@Mixins( UnitOfWorkFilter.class )
public interface UnitOfWorkFilterService extends Filter, ServiceComposite
{
}
// END SNIPPET: filterservice


text:
import sinon from 'sinon';
import assert from 'assert';
import React from 'react';
import utils from 'react-addons-test-utils';
import ProductList from '../../src/components/ProductList';

describe('component ProductList', () => {
    let productList;

    const defaultProps = {
        products: [],
        isFetching: false,
        didInvalidate: false,
        fetchProductsIfNeeded: sinon.spy(),
        showProductPage: sinon.spy(),
    };

    function renderProductList(props) {
        const renderer = utils.createRenderer();
        renderer.render(<ProductList {...props} />);
        const output = renderer.getRenderOutput();

        return {
            props,
            output,
            renderer,
        };
    }

    beforeEach(() => {
        productList = renderProductList(defaultProps);
    });

    it('should render correctly if no products', () => {
        const { output } = productList;
        const text = output.props.children;
        assert.deepEqual(text.props.children, 'No product available.');
    });

    it('should render products correctly', () => {
        const props = Object.assign({}, defaultProps, {
            products: [{
                id: 42,
                thumbnail: 'some url',
                price: 'THE PRICE',
                stock: 'THE STOCK',
            }],
        });
        productList = renderProductList(props);

        const { output } = productList;
        assert.deepEqual(
            output.props.children.length, 1,
            'Not the good amount of rendered products'
        );

        const rootView = output.props.children[0];
        const touchable = rootView.props.children[0];
        const view = touchable.props.children;
        const [ image, textView ] = view.props.children;
        assert.deepEqual(image.props.source.uri, 'some url');

        const [ price, stock ] = textView.props.children;
        assert.notEqual(
            price.props.children.indexOf('THE PRICE'),
            -1,
            'The price is not correctly rendered'
        );
        assert.notEqual(
            stock.props.children.indexOf('THE STOCK'),
            -1,
            'The stock is not correctly rendered'
        );
    });
});


text:
require 'keyring_liberator'
require 'keyring'
require 'name_whisperer'
require 'shellwords'

module Pod
  class Command
    class Keys
      class Rm < Keys
        self.summary = 'Removes key-value pairs from a project.'

        self.description = <<-DESC
            Removes a key, and it's value from a project.

            If Wildcards are included, it will remove the keys matching the pattern.
            E.g.: `pod keys rm \"G*og*\"` will remove *all* the keys that begin
            with 'G', have 'og' in the middle and end with anything.

            To nuke all the keys, run either `pod keys rm "*"` or `pod keys rm --all`

            A second optional operator can be done to force a project name.
        DESC

        self.arguments = [CLAide::Argument.new('key', true), CLAide::Argument.new('project_name', false)]

        def self.options
          [[
            '--all', 'Remove all the stored keys without asking'
          ]].concat(super)
        end

        def initialize(argv)
          @key_name = argv.shift_argument
          @project_name = argv.shift_argument
          @wipe_all = argv.flag?('all')
          super
        end

        def validate!
          super
          verify_podfile_exists!
          help! 'A key name is required for lookup.' unless @key_name || @wipe_all
        end

        def run
          keyring = get_current_keyring
          unless keyring
            raise Informative, 'Could not find a project to remove the key from.'
          end

          if @wipe_all
            @key_name = '*'
          end

          matching_keys = matches(keyring.keys)
          if matching_keys.count > 0
            messages = matching_keys.map { |e| delete_key(e, keyring) }
            raise Informative, messages.join("\n")
          else
            raise Informative, "Could not find key that matched \"#{@key_name}\"."
          end
        end

        def delete_key(key, keyring)
          keyring.save(key, '')
          keyring.keys.delete key
          CocoaPodsKeys::KeyringLiberator.save_keyring(keyring)

          prefix = CocoaPodsKeys::Keyring.keychain_prefix
          login = prefix + keyring.name
          delete_generic = `security delete-generic-password -a #{key.shellescape} -l #{login.shellescape} 2>&1`

          if delete_generic.include? 'security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.'
            return "Removed value for #{key}, but could not delete from Keychain."
          elsif delete_generic.include? 'password has been deleted.'
            return "Removed value for #{key}, and deleted associated key in Keychain."
          else
            return "Removed value for #{key}."
          end
        end

        def matches(keys)
          if @key_name.include? '*'
            keys.select { |e| e =~ create_regex(@key_name) }
          else
            keys.select { |e| e == @key_name }
          end
        end

        def create_regex(pattern)
          regex_str = "^#{pattern.gsub('*', '.*')}$"
          Regexp.new(regex_str)
        end
      end
    end
  end
end


text:
(function() {
	'use strict';

	var root = this;

	root.define([
		'views/item/JuiBasicPaginator'
		],
		function( Juibasicpaginator ) {

			describe('Juibasicpaginator Itemview', function () {

				it('should be an instance of Juibasicpaginator Itemview', function () {
					var JuiBasicPaginator = new Juibasicpaginator();
					expect( JuiBasicPaginator ).to.be.an.instanceof( Juibasicpaginator );
				});

				it('should have more test written', function(){
					expect( false ).to.be.ok;
				});
			});

		});

}).call( this );


text:
import * as R from '../ramda/dist/index';

declare const number: number;
declare const number_string_to_number_string_tuple: (
  x: number,
  y: string,
) => [number, string];
declare const string_array: string[];

// @dts-jest:pass:snap -> (list: R.List<string>) => [number, string[]]
R.mapAccum(number_string_to_number_string_tuple, number);
// @dts-jest:pass:snap -> [number, string[]]
R.mapAccum(number_string_to_number_string_tuple)(number)(string_array);
// @dts-jest:pass:snap -> [number, string[]]
R.mapAccum(number_string_to_number_string_tuple, number, string_array);


text:
/* automatically generated by rust-bindgen */

#![allow(
    dead_code,
    non_snake_case,
    non_camel_case_types,
    non_upper_case_globals
)]

#[repr(C)]
pub struct BaseWithVtable__bindgen_vtable(::std::os::raw::c_void);
/// This should have an explicit vtable.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct BaseWithVtable<T> {
    pub vtable_: *const BaseWithVtable__bindgen_vtable,
    pub t: T,
    pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>,
}
impl<T> Default for BaseWithVtable<T> {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
/// This should not have an explicit vtable.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DerivedWithNoVirtualMethods {
    pub _base: BaseWithVtable<*mut ::std::os::raw::c_char>,
}
#[test]
fn bindgen_test_layout_DerivedWithNoVirtualMethods() {
    assert_eq!(
        ::std::mem::size_of::<DerivedWithNoVirtualMethods>(),
        16usize,
        concat!("Size of: ", stringify!(DerivedWithNoVirtualMethods))
    );
    assert_eq!(
        ::std::mem::align_of::<DerivedWithNoVirtualMethods>(),
        8usize,
        concat!("Alignment of ", stringify!(DerivedWithNoVirtualMethods))
    );
}
impl Default for DerivedWithNoVirtualMethods {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
/// This should not have an explicit vtable.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DerivedWithVirtualMethods {
    pub _base: BaseWithVtable<*mut ::std::os::raw::c_char>,
}
#[test]
fn bindgen_test_layout_DerivedWithVirtualMethods() {
    assert_eq!(
        ::std::mem::size_of::<DerivedWithVirtualMethods>(),
        16usize,
        concat!("Size of: ", stringify!(DerivedWithVirtualMethods))
    );
    assert_eq!(
        ::std::mem::align_of::<DerivedWithVirtualMethods>(),
        8usize,
        concat!("Alignment of ", stringify!(DerivedWithVirtualMethods))
    );
}
impl Default for DerivedWithVirtualMethods {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
/// This should not have any vtable.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct BaseWithoutVtable<U> {
    pub u: U,
    pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<U>>,
}
impl<U> Default for BaseWithoutVtable<U> {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[repr(C)]
pub struct DerivedWithVtable__bindgen_vtable(::std::os::raw::c_void);
/// This should have an explicit vtable.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DerivedWithVtable {
    pub vtable_: *const DerivedWithVtable__bindgen_vtable,
    pub _base: BaseWithoutVtable<*mut ::std::os::raw::c_char>,
}
#[test]
fn bindgen_test_layout_DerivedWithVtable() {
    assert_eq!(
        ::std::mem::size_of::<DerivedWithVtable>(),
        16usize,
        concat!("Size of: ", stringify!(DerivedWithVtable))
    );
    assert_eq!(
        ::std::mem::align_of::<DerivedWithVtable>(),
        8usize,
        concat!("Alignment of ", stringify!(DerivedWithVtable))
    );
}
impl Default for DerivedWithVtable {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
/// This should not have any vtable.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct DerivedWithoutVtable {
    pub _base: BaseWithoutVtable<*mut ::std::os::raw::c_char>,
}
#[test]
fn bindgen_test_layout_DerivedWithoutVtable() {
    assert_eq!(
        ::std::mem::size_of::<DerivedWithoutVtable>(),
        8usize,
        concat!("Size of: ", stringify!(DerivedWithoutVtable))
    );
    assert_eq!(
        ::std::mem::align_of::<DerivedWithoutVtable>(),
        8usize,
        concat!("Alignment of ", stringify!(DerivedWithoutVtable))
    );
}
impl Default for DerivedWithoutVtable {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[test]
fn __bindgen_test_layout_BaseWithVtable_open0_ptr_char_close0_instantiation() {
    assert_eq!(
        ::std::mem::size_of::<BaseWithVtable<*mut ::std::os::raw::c_char>>(),
        16usize,
        concat!(
            "Size of template specialization: ",
            stringify!(BaseWithVtable<*mut ::std::os::raw::c_char>)
        )
    );
    assert_eq!(
        ::std::mem::align_of::<BaseWithVtable<*mut ::std::os::raw::c_char>>(),
        8usize,
        concat!(
            "Alignment of template specialization: ",
            stringify!(BaseWithVtable<*mut ::std::os::raw::c_char>)
        )
    );
}
#[test]
fn __bindgen_test_layout_BaseWithVtable_open0_ptr_char_close0_instantiation_1()
{
    assert_eq!(
        ::std::mem::size_of::<BaseWithVtable<*mut ::std::os::raw::c_char>>(),
        16usize,
        concat!(
            "Size of template specialization: ",
            stringify!(BaseWithVtable<*mut ::std::os::raw::c_char>)
        )
    );
    assert_eq!(
        ::std::mem::align_of::<BaseWithVtable<*mut ::std::os::raw::c_char>>(),
        8usize,
        concat!(
            "Alignment of template specialization: ",
            stringify!(BaseWithVtable<*mut ::std::os::raw::c_char>)
        )
    );
}
#[test]
fn __bindgen_test_layout_BaseWithoutVtable_open0_ptr_char_close0_instantiation()
{
    assert_eq!(
        ::std::mem::size_of::<BaseWithoutVtable<*mut ::std::os::raw::c_char>>(),
        8usize,
        concat!(
            "Size of template specialization: ",
            stringify!(BaseWithoutVtable<*mut ::std::os::raw::c_char>)
        )
    );
    assert_eq!(
        ::std::mem::align_of::<BaseWithoutVtable<*mut ::std::os::raw::c_char>>(
        ),
        8usize,
        concat!(
            "Alignment of template specialization: ",
            stringify!(BaseWithoutVtable<*mut ::std::os::raw::c_char>)
        )
    );
}
#[test]
fn __bindgen_test_layout_BaseWithoutVtable_open0_ptr_char_close0_instantiation_1(
) {
    assert_eq!(
        ::std::mem::size_of::<BaseWithoutVtable<*mut ::std::os::raw::c_char>>(),
        8usize,
        concat!(
            "Size of template specialization: ",
            stringify!(BaseWithoutVtable<*mut ::std::os::raw::c_char>)
        )
    );
    assert_eq!(
        ::std::mem::align_of::<BaseWithoutVtable<*mut ::std::os::raw::c_char>>(
        ),
        8usize,
        concat!(
            "Alignment of template specialization: ",
            stringify!(BaseWithoutVtable<*mut ::std::os::raw::c_char>)
        )
    );
}


text:
package com.google.errorprone.util;

import static com.google.errorprone.util.ASTHelpers.enclosingClass;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;

import com.google.errorprone.VisitorState;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import java.util.Set;
import javax.lang.model.element.Modifier;

/**
 * Describes visibilities available via VisibleForTesting annotations, and provides methods to
 * establish whether a given {@link Tree} should be visible.
 */
public enum Visibility implements Comparable<Visibility> {
  // In order of ascending visibility.
  NONE {
    @Override
    public boolean shouldBeVisible(Tree tree, VisitorState state) {
      return false;
    }

    @Override
    public boolean shouldBeVisible(Symbol symbol, VisitorState state) {
      return false;
    }

    @Override
    public String description() {
      return "not be used";
    }
  },
  PRIVATE {
    @Override
    public boolean shouldBeVisible(Tree tree, VisitorState state) {
      return shouldBeVisible(getSymbol(tree), state);
    }

    @Override
    public boolean shouldBeVisible(Symbol symbol, VisitorState state) {
      Symbol outermostClass = null;
      for (Tree parent : state.getPath()) {
        if (parent instanceof ClassTree) {
          outermostClass = getSymbol(parent);
        }
      }
      return outermostClass == null || ASTHelpers.outermostClass(symbol).equals(outermostClass);
    }

    @Override
    public String description() {
      return "private visibility";
    }
  },
  PACKAGE_PRIVATE {
    @Override
    public boolean shouldBeVisible(Tree tree, VisitorState state) {
      return PACKAGE_PRIVATE.shouldBeVisible(getSymbol(tree), state);
    }

    @Override
    public boolean shouldBeVisible(Symbol symbol, VisitorState state) {
      JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit();
      PackageSymbol packge = compilationUnit.packge;
      // TODO(ghm): Should we handle the default (unnamed) package here?
      return symbol.packge().equals(packge);
    }

    @Override
    public String description() {
      return "default (package private) visibility";
    }
  },
  PROTECTED {
    // Rules https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.2
    @Override
    public boolean shouldBeVisible(Tree tree, VisitorState state) {
      if (PACKAGE_PRIVATE.shouldBeVisible(tree, state)) {
        return true;
      }
      Symbol symbol = getSymbol(tree);
      ClassTree classTree = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
      if (symbol.isStatic()) {
        if (classTree == null) {
          return false;
        }
        return hasEnclosingClassExtending(enclosingClass(symbol).type, state, classTree);
      }
      // Anonymous subclasses will match on the synthetic constructor.
      if (tree instanceof NewClassTree) {
        return false;
      }
      if (!(tree instanceof ExpressionTree)) {
        return hasEnclosingClassExtending(enclosingClass(symbol).type, state, classTree);
      }
      if (tree instanceof MemberSelectTree
          && ((MemberSelectTree) tree).getIdentifier().contentEquals("super")) {
        // Allow qualified super calls.
        return true;
      }
      if (tree instanceof MemberSelectTree || tree instanceof MemberReferenceTree) {
        ExpressionTree receiver = ASTHelpers.getReceiver((ExpressionTree) tree);
        return receiver.toString().equals("super")
            || hasEnclosingClassOfSuperType(getType(receiver), state, classTree);
      }
      // If there's no receiver, we must be accessing it via an implicit "this", or we're
      // using unqualified "super".
      return true;
    }

    @Override
    public boolean shouldBeVisible(Symbol symbol, VisitorState state) {
      if (PACKAGE_PRIVATE.shouldBeVisible(symbol, state)) {
        return true;
      }
      ClassTree classTree = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
      return classTree != null
          && hasEnclosingClassExtending(enclosingClass(symbol).type, state, classTree);
    }

    private boolean hasEnclosingClassOfSuperType(
        Type type, VisitorState state, ClassTree classTree) {
      for (ClassSymbol encl = getSymbol(classTree); encl != null; encl = enclosingClass(encl)) {
        if (encl.isStatic()) {
          break;
        }
        if (ASTHelpers.isSubtype(type, encl.type, state)) {
          return true;
        }
      }
      return false;
    }

    private boolean hasEnclosingClassExtending(Type type, VisitorState state, ClassTree classTree) {
      for (ClassSymbol encl = getSymbol(classTree); encl != null; encl = enclosingClass(encl)) {
        if (encl.isStatic()) {
          break;
        }
        if (ASTHelpers.isSubtype(encl.type, type, state)) {
          return true;
        }
      }
      return false;
    }

    @Override
    public String description() {
      return "protected visibility";
    }
  },
  PUBLIC {
    @Override
    public boolean shouldBeVisible(Tree tree, VisitorState state) {
      return true;
    }

    @Override
    public boolean shouldBeVisible(Symbol symbol, VisitorState state) {
      return true;
    }

    @Override
    public String description() {
      return "public visibility";
    }
  };

  /**
   * Whether {@code tree} should be visible from the path in {@code state} assuming we're in prod
   * code.
   */
  public abstract boolean shouldBeVisible(Tree tree, VisitorState state);

  /**
   * Whether {@code symbol} should be visible from the path in {@code state} assuming we're in prod
   * code.
   */
  public abstract boolean shouldBeVisible(Symbol symbol, VisitorState state);

  public static Visibility fromModifiers(Set<Modifier> modifiers) {
    if (modifiers.contains(Modifier.PRIVATE)) {
      return Visibility.PRIVATE;
    }
    if (modifiers.contains(Modifier.PUBLIC)) {
      return Visibility.PUBLIC;
    }
    if (modifiers.contains(Modifier.PROTECTED)) {
      return Visibility.PROTECTED;
    }
    return Visibility.PACKAGE_PRIVATE;
  }

  public boolean isAtLeastAsRestrictiveAs(Visibility visibility) {
    return compareTo(visibility) <= 0;
  }

  public boolean isMoreVisibleThan(Visibility visibility) {
    return compareTo(visibility) > 0;
  }

  /**
   * A fragment describing this visibility, to fit in a phrase like "restricted to [...]".
   *
   * <p>This is complicated by {@code NONE}, which doesn't describe a Java visibility.
   */
  public abstract String description();
}


text:
package com.unascribed.lanthanoid.init;

import com.unascribed.lanthanoid.Lanthanoid;
import com.unascribed.lanthanoid.client.TextureCompositorImpl.BlockBackdrop;
import com.unascribed.lanthanoid.client.TextureCompositorImpl.BlockType;
import com.unascribed.lanthanoid.util.TextureCompositor;

public class LMachines {
	public static void init() {
		TextureCompositor compositor = Lanthanoid.inst.compositor;
		if (compositor != null) {
			compositor.addBlock("machineCobbleSide", 0xFFFFFF, BlockType.MACHINE_BLOCK, BlockBackdrop.COBBLESTONE);
			compositor.addBlock("machineCobbleTop", 0xFFFFFF, BlockType.MACHINE_BLOCK_TOP, BlockBackdrop.COBBLESTONE);
			compositor.addBlock("machineCobbleBottom", 0xFFFFFF, BlockType.MACHINE_BLOCK_BOTTOM, BlockBackdrop.COBBLESTONE);

			compositor.addBlock("machineCombustorFrontWorking", 0xFFFFFF, BlockType.MACHINE_COMBUSTOR_WORKING, BlockBackdrop.COBBLESTONE);
			compositor.addBlock("machineCombustorFrontIdle", 0xFFFFFF, BlockType.MACHINE_COMBUSTOR_IDLE, BlockBackdrop.COBBLESTONE);

			int holmium = LMaterials.colors.get("Holmium");
			int yttrium = LMaterials.colors.get("Yttrium");

			compositor.addBlock("machineWaypointTopHolmium", holmium, BlockType.WAYPOINT_TOP, BlockBackdrop.NONE);
			compositor.addBlock("machineWaypointBottomHolmium", holmium, BlockType.WAYPOINT_BOTTOM, BlockBackdrop.NONE);
			compositor.addBlock("machineWaypointSideHolmium", holmium, BlockType.WAYPOINT_SIDE, BlockBackdrop.NONE);

			compositor.addBlock("machineWaypointTopYttrium", yttrium, BlockType.WAYPOINT_TOP, BlockBackdrop.NONE);
			compositor.addBlock("machineWaypointBottomYttrium", yttrium, BlockType.WAYPOINT_BOTTOM, BlockBackdrop.NONE);
			compositor.addBlock("machineWaypointSideYttrium", yttrium, BlockType.WAYPOINT_SIDE, BlockBackdrop.NONE);

			compositor.addBlock("machineWaypointSideDiamond", LMaterials.colors.get("Diamond"), BlockType.WAYPOINT_SIDE_DIAMOND, BlockBackdrop.WAYPOINT_SIDE_HOLMIUM);
			compositor.addBlock("machineWaypointSideRaspite", LMaterials.colors.get("Raspite"), BlockType.WAYPOINT_SIDE_TRIANGLE, BlockBackdrop.WAYPOINT_SIDE_HOLMIUM);
			compositor.addBlock("machineWaypointSideDiaspore", LMaterials.colors.get("Diaspore"), BlockType.WAYPOINT_SIDE_CIRCLE, BlockBackdrop.WAYPOINT_SIDE_YTTRIUM);
		}
	}
}


text: <!DOCTYPE html>


text:
package org.xbmc.kore.utils;

import android.content.Context;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageButton;

/**
 * A class, that can be used as a TouchListener on any view (e.g. a Button).
 * It cyclically runs a clickListener, emulating keyboard-like behaviour. First
 * click is fired immediately, next after initialInterval, and subsequent after
 * repeatInterval.
 *
 * <p>Interval is scheduled after the onClick completes, so it has to run fast.
 * If it runs slow, it does not generate skipped onClicks.
 */
public class RepeatListener implements View.OnTouchListener {
    private static final String TAG = LogUtils.makeLogTag(RepeatListener.class);

    private static Handler repeatHandler = new Handler();

    private int initialInterval;
    private final int repeatInterval;
    private final View.OnClickListener clickListener;

    private Runnable handlerRunnable = new Runnable() {
        @Override
        public void run() {
            if (downView.isShown()) {
                if (repeatInterval >= 0) {
                    repeatHandler.postDelayed(this, repeatInterval);
                }
                clickListener.onClick(downView);
            }
        }
    };

    /**
     * Animations for down/up
     */
    private Animation animDown;
    private Animation animUp;

    private View downView;

    private Context context;

    /**
     * Constructor for a repeat listener
     *
     * @param initialInterval The interval after first click event
     * @param repeatInterval The interval after second and subsequent click events
     * @param clickListener The OnClickListener, that will be called periodically
     */
    public RepeatListener(int initialInterval, int repeatInterval, View.OnClickListener clickListener) {
        this(initialInterval, repeatInterval, clickListener, null, null, null);
    }

    public RepeatListener(int initialInterval, int repeatInterval, View.OnClickListener clickListener,
                          Animation animDown, Animation animUp) {
        this(initialInterval, repeatInterval, clickListener, animUp, animDown, null);
    }

    /**
     * Constructor for a repeat listener, with animation and vibration
     *
     * @param initialInterval The interval after first click event. If negative, no repeat will occur
     * @param repeatInterval The interval after second and subsequent click events. If negative, no repeat will occur
     * @param clickListener The OnClickListener, that will be called periodically
     * @param animDown Animation to play on touch
     * @param animUp Animation to play on release
     * @param context Context used to access preferences and services
     */
    public RepeatListener(int initialInterval, int repeatInterval, View.OnClickListener clickListener,
                          Animation animDown, Animation animUp, Context context) {
        this.initialInterval = initialInterval;
        this.repeatInterval = repeatInterval;
        this.clickListener = clickListener;

        this.animDown = animDown;
        this.animUp = animUp;

        this.context = context;
    }

    /**
     * Handle touch events.
     *
     * Note: For buttons, this event Handler returns false, so that the other event handlers
     * of buttons get called. For other views this event Handler consumes the event
     * @param view
     * @param motionEvent
     * @return
     */
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                UIUtils.handleVibration(context);
                repeatHandler.removeCallbacks(handlerRunnable);
                if (initialInterval >= 0) {
                    repeatHandler.postDelayed(handlerRunnable, initialInterval);
                }
                downView = view;

                if (animDown != null) {
                    animDown.setFillAfter(true);
                    view.startAnimation(animDown);
                }
                break;
            case MotionEvent.ACTION_UP:
                clickListener.onClick(view);
                view.playSoundEffect(SoundEffectConstants.CLICK);
                // Fallthrough
            case MotionEvent.ACTION_CANCEL:
                repeatHandler.removeCallbacks(handlerRunnable);
                downView = null;

                if (animUp != null) {
                    view.startAnimation(animUp);
                }
                break;
        }
        // Consume the event for views other than buttons
        return !((view instanceof Button) || (view instanceof ImageButton));
    }
}


text:
[Kubernetes](http://kubernetes.io) is a system for managing containerized applications across a cluster of machines.
Kubernetes runs all applications in containers.
In the default setup, this is performed using the Docker engine, but Kubernetes also features support for using rkt as its container runtime backend.
This allows a Kubernetes cluster to leverage some of rkt's security features and native pod support.

## Configuring rkt as the Kubernetes container runtime

The container runtime is configured at the _kubelet_ level.
The kubelet is the agent that runs on each machine to manage containers.
The kubelet provides several flags to use rkt as the container runtime:

- `--container-runtime=rkt` Sets the node's container runtime to rkt.
- `--rkt-api-endpoint=HOST:PORT` Sets the endpoint of the rkt API service. Default to `localhost:15441`.
- `--rkt-path=PATH_TO_RKT_BINARY` Sets the path of the rkt binary. If empty, it will search for rkt in `$PATH`.
- `--rkt-stage1-image=STAGE1_NAME` Sets the name of the stage1 image, e.g. `coreos.com/rkt/stage1-coreos`. If not set, the default stage1 image (`coreos.com/rkt/stage1-coreos`) is used.

Check the [rktnetes getting started guide](http://kubernetes.io/docs/getting-started-guides/rkt/) for information about setting up and using a rktnetes cluster.

## Configuring rkt using supported setup tools
The [coreos-kubernetes](https://github.com/coreos/coreos-kubernetes) and [coreos-baremetal](https://github.com/coreos/coreos-baremetal) repos both support configuring rkt as the Kubernetes runtime out of the box.

Check out the coreos-kubernetes repo if you want to spin up a cluster on [AWS](https://coreos.com/kubernetes/docs/latest/kubernetes-on-aws.html) or [locally with vagrant](https://coreos.com/kubernetes/docs/latest/kubernetes-on-vagrant-single.html). The common configuration option here is setting `CONTAINER_RUNTIME` environment variable to rkt.

For baremetal, check out the Kubernetes guides [here](https://github.com/coreos/coreos-baremetal/blob/master/Documentation/kubernetes.md)

### Current Status

Integration of rkt as a container runtime was officially [announced in the Kubernetes 1.3 release](http://blog.kubernetes.io/2016/07/rktnetes-brings-rkt-container-engine-to-Kubernetes.html).
Known issues and tips for using rkt with Kubernetes can be found in the [rktnetes notes](http://kubernetes.io/docs/getting-started-guides/rkt/notes/).


text:
class BudgetsController < ApplicationController
  before_action :authenticate_user!
  before_action :require_time_zone
  before_action :set_and_authorize_budget, except: [:index, :new, :create]

  def index
    respond_to do |f|
      f.html
      f.json { render :json => { active: current_user.budgets.active, inactive: current_user.budgets.inactive,  completed: current_user.budgets.completed } }
    end
  end

  def new
    @budget = current_user.budgets.build
    render layout: false
  end

  def create
    @budget = current_user.budgets.build(budget_params)
    @budget.save ? (render :show, layout: false, status: 201) : (render :new, layout: false, status: 422)
  end

  def show
    render layout: false
  end

  def edit
    render layout: false
  end

  def update
    @budget.update(budget_params) ? (render :show, layout: false) : (render :edit, layout: false, status: 422)
  end

  def destroy
    @budget.destroy
    redirect_to user_budgets_path
  end

  private

  def set_and_authorize_budget
    @budget = Budget.find(params[:id])
    authorize @budget
  end

  def budget_params
    params.require(:budget).permit(:name, :start_date, :end_date, :limit, :categories_attributes => [:title])
  end

  # Ensure that users are not able to interact with budgets until they have timezones in order to avoid issues with dates.

  def require_time_zone
    redirect_to edit_user_time_zone_path, :alert => "Please set your timezone." unless current_user.time_zone
  end

end


text:
package metadata

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"golang.org/x/oauth2"

	"github.com/GoogleCloudPlatform/cloud-build-local/runner"
)

const (
	// fixedMetadataIP is the fixed IP available on all GCE instances that serves
	// metadata on port 80. Some client libraries connect directly to this IP,
	// rather than metadata.google.internal, so we need to listen on this IP.
	fixedMetadataIP = "169.254.169.254"
	// This subnet captures the fixed metadata IP. This subnet is a reserved link-local subnet.
	metadataLocalSubnet = "169.254.0.0/16"

	// This subnet captures metadataHostedIP. This subnet is a reserved private subnet.
	// This is the subnet used to create the cloudbuild docker network in the
	// hosted Cloud Build environment. All build steps are run connected to the
	// cloudbuild docker network.
	metadataHostedSubnet = "192.168.10.0/24"

	// localMetadata is the host:port for metadata when running the local builder.
	localMetadata = "http://localhost:8082"

	// Header constants
	headerKey   = "Metadata-Flavor"
	headerVal   = "Google"
	contentType = "Content-Type"
)

var (
	// metadataHostedIP is the IP that the metadata spoofer listens to in the
	// hosted cloudbuild environment. iptables is used to route tcp connections
	// going to 169.254.169.254 port 80 to this IP instead.
	metadataHostedIP = "192.168.10.5" // var for testing

	// httpTimeout is the timeout for http calls; var for testing
	httpTimeout = 10 * time.Second

	jsonHeader = http.Header{contentType: []string{"application/json"}}
)

// Updater encapsulates updating the spoofed metadata server.
type Updater interface {
	SetToken(context.Context, *Token) error
	SetProjectInfo(context.Context, ProjectInfo) error
	Ready(context.Context) bool // Returns true if metadata is up and running.
}

// ProjectInfo represents an incoming build request containing the project ID
// and number to make available as metadata.
type ProjectInfo struct {
	ProjectID  string `json:"project_id"`
	ProjectNum int64  `json:"project_num"`
}

// Token represents an OAuth token including the access token, account email,
// expiration, and scopes.
type Token struct {
	AccessToken string    `json:"access_token"`
	Expiry      time.Time `json:"expiry"`
	Email       string    `json:"email"`
	Scopes      []string
}

// Oauth2 converts a Token to a standard oauth2.Token.
func (t Token) Oauth2() *oauth2.Token {
	return &oauth2.Token{
		AccessToken: t.AccessToken,
		Expiry:      t.Expiry,
		TokenType:   "Bearer",
	}
}

// RealUpdater actually sends POST requests to update spoofed metadata.
type RealUpdater struct {
	Local bool
}

func (r RealUpdater) getAddress() string {
	addr := localMetadata
	if !r.Local {
		addr = metadataHostedIP
	}
	if !strings.HasPrefix(addr, "http") {
		addr = "http://" + addr
	}
	return addr
}

func doRequest(ctx context.Context, method, url string, body io.Reader, header http.Header) (io.ReadCloser, error) {
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}
	req.Header = header
	req.Header.Set(headerKey, headerVal)

	resp, err := http.DefaultClient.Do(req.WithContext(ctx))
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		defer resp.Body.Close()
		all, _ := ioutil.ReadAll(resp.Body)
		return nil, fmt.Errorf("%s failed (%d): %s", method, resp.StatusCode, string(all))
	}
	return resp.Body, nil
}

// SetToken updates the spoofed metadata server's credentials.
func (r RealUpdater) SetToken(ctx context.Context, tok *Token) error {
	scopes, err := getScopes(ctx, tok.AccessToken)
	if err != nil {
		return err
	}
	tok.Scopes = scopes
	var buf bytes.Buffer
	if err := json.NewEncoder(&buf).Encode(tok); err != nil {
		return err
	}

	ctx, cancel := context.WithTimeout(ctx, httpTimeout)
	defer cancel()
	body, err := doRequest(ctx, http.MethodPost, r.getAddress()+"/token", &buf, jsonHeader)
	if err != nil {
		return err
	}
	body.Close()
	return nil
}

// var for testing
var googleTokenInfoHost = "https://www.googleapis.com"

// getScopes returns the OAuth scopes provided by the access token.
//
// It determines this by POSTing to the tokeninfo API:
// https://developers.google.com/identity/protocols/OAuth2UserAgent#validatetoken
func getScopes(ctx context.Context, tok string) ([]string, error) {
	data := url.Values{}
	data.Set("access_token", tok)

	const maxTries = 3
	var err error
	for i := 0; i < maxTries; i++ {
		if i > 0 {
			delay := time.Millisecond * 150 * time.Duration(i)
			log.Printf("Waiting %v before retry...", delay)
			time.Sleep(delay)
		}

		var body io.ReadCloser
		ctx, cancel := context.WithTimeout(ctx, httpTimeout)
		defer cancel()
		body, err = doRequest(ctx, http.MethodPost, googleTokenInfoHost+"/oauth2/v3/tokeninfo",
			strings.NewReader(data.Encode()), http.Header{contentType: []string{"application/x-www-form-urlencoded"}})
		if err != nil {
			log.Printf("Error reading scopes on attempt #%d/%d: %v", i+1, maxTries, err)
			continue
		}
		defer body.Close()
		r := struct {
			Scope string `json:"scope"`
		}{}
		if err = json.NewDecoder(body).Decode(&r); err != nil {
			log.Printf("Error decoding scopes response on attempt #%d/%d: %v", i+1, maxTries, err)
			continue
		}
		return strings.Split(r.Scope, " "), nil
	}
	return nil, err
}

// SetProjectInfo updates the spoofed metadata server's project information.
func (r RealUpdater) SetProjectInfo(ctx context.Context, b ProjectInfo) error {
	var buf bytes.Buffer
	if err := json.NewEncoder(&buf).Encode(b); err != nil {
		return err
	}

	ctx, cancel := context.WithTimeout(ctx, httpTimeout)
	defer cancel()
	body, err := doRequest(ctx, http.MethodPost, r.getAddress()+"/build", &buf, jsonHeader)
	if err != nil {
		return err
	}

	defer body.Close()
	return nil
}

// Ready returns true if the metadata server is up and running.
func (r RealUpdater) Ready(ctx context.Context) bool {
	body, err := doRequest(ctx, http.MethodGet, r.getAddress()+"/ready", nil, http.Header{})
	if err != nil {
		log.Printf("Metadata not ready: %v", err)
		return false
	}
	body.Close()
	return true
}

// StartLocalServer starts the metadata server container for VMs running
// independent from the Cloud Build service.
//
// This version of Start*Server does not update iptables.
//
// The container listens on local port 8082, which is where RealUpdater POSTs
// to.
func StartLocalServer(ctx context.Context, r runner.Runner, metadataImage string) error {
	// Unlike the hosted Cloud Build service, the user's local machine is
	// not guaranteed to have the latest version, so we explicitly pull it.
	if err := r.Run(ctx, []string{"docker", "pull", metadataImage}, nil, os.Stdout, os.Stderr, ""); err != nil {
		return err
	}
	return startServer(ctx, r, metadataImage, false, fixedMetadataIP, metadataLocalSubnet)
}

// StartCloudServer starts the metadata server container for VMs running as
// part of the Cloud Build service.
//
// This version of Start*Server needs to make iptables rules that we don't
// want (or need) on a user's local machine.
//
// The container listens on local port 8082, which is where RealUpdater POSTs
// to.
func StartCloudServer(ctx context.Context, r runner.Runner, metadataImage string) error {
	if err := startServer(ctx, r, metadataImage, true, metadataHostedIP, metadataHostedSubnet); err != nil {
		return err
	}

	// In a separate goroutine, attach to the metadata server container so its
	// logs are properly captured and available for debugging.
	go func() {
		if err := r.Run(ctx, []string{"docker", "attach", "metadata"}, nil, os.Stdout, os.Stderr, ""); err != nil {
			log.Printf("docker attach failed: %v", err)
		}
	}()

	return nil
}

// CreateCloudbuildNetwork creates a cloud build network to link the build
// builds.
func CreateCloudbuildNetwork(ctx context.Context, r runner.Runner, subnet string) error {
	cmd := []string{"docker", "network", "create", "cloudbuild", "--subnet=" + subnet}
	return r.Run(ctx, cmd, nil, nil, os.Stderr, "")
}

func startServer(ctx context.Context, r runner.Runner, metadataImage string, iptables bool, ip, subnet string) error {
	if err := CreateCloudbuildNetwork(ctx, r, subnet); err != nil {
		return fmt.Errorf("Error creating network: %v", err)
	}

	// Run the spoofed metadata server.
	var cmd []string
	if !iptables {
		// In the local builder, we need to expose the port but it's nice to avoid 80.
		cmd = []string{"docker", "run", "-d", "-p=8082:80", "--name=metadata", metadataImage}
	} else {
		cmd = []string{"docker", "run", "-d", "--name=metadata", metadataImage}
	}
	if err := r.Run(ctx, cmd, nil, nil, os.Stderr, ""); err != nil {
		return err
	}

	// Redirect requests to metadata.google.internal and the fixed metadata IP to the metadata container.
	cmd = []string{"docker", "network", "connect", "--alias=metadata", "--alias=metadata.google.internal", "--ip=" + ip, "cloudbuild", "metadata"}
	if err := r.Run(ctx, cmd, nil, nil, os.Stderr, ""); err != nil {
		return fmt.Errorf("Error connecting metadata to network: %v", err)
	}

	if iptables {
		// Route the "real" metadata IP to the IP of our metadata spoofer.
		cmd = []string{"iptables",
			"-t", "nat", // In the nat table,
			"-A", "PREROUTING", // append this rule to the PREROUTING chain,
			"-p", "tcp", // for connections using TCP,
			"--destination", fixedMetadataIP, // intended for the metadata service,
			"--dport", "80", // intended for port 80.
			"-j", "DNAT", // This rule does destination NATting,
			"--to-destination", metadataHostedIP, // to our spoofed metadata container.
		}
		if err := r.Run(ctx, cmd, nil, os.Stdout, os.Stderr, ""); err != nil {
			return fmt.Errorf("Error updating iptables: %v", err)
		}
	}

	return nil
}

// CleanCloudbuildNetwork delete the cloudbuild network.
func CleanCloudbuildNetwork(ctx context.Context, r runner.Runner) error {
	return r.Run(ctx, []string{"docker", "network", "rm", "cloudbuild"}, nil, nil, os.Stderr, "")
}

// Stop stops the metadata server container and tears down the docker cloudbuild
// network used to route traffic to it.
// Try to clean both the container and the network before returning an error.
func (RealUpdater) Stop(ctx context.Context, r runner.Runner) error {
	errContainer := r.Run(ctx, []string{"docker", "rm", "-f", "metadata"}, nil, nil, os.Stderr, "")
	errNetwork := CleanCloudbuildNetwork(ctx, r)
	if errContainer != nil {
		return errContainer
	}
	return errNetwork
}


text:
class AppServiceAppIconLoader;
class ArcAppWindowDelegate;

namespace gfx {
class ImageSkia;
}

namespace views {
class Widget;
}

class Profile;

// A ui::BaseWindow for a chromeos launcher to control ARC applications.
class ArcAppWindow : public AppWindowBase,
                     public ImageDecoder::ImageRequest,
                     public AppIconLoaderDelegate {
 public:
  ArcAppWindow(int task_id,
               const arc::ArcAppShelfId& app_shelf_id,
               views::Widget* widget,
               ArcAppWindowDelegate* owner,
               Profile* profile);

  ~ArcAppWindow() override;

  void SetFullscreenMode(FullScreenMode mode) override;

  // Sets optional window title and icon. Note that |unsafe_icon_data_png| has
  // to be decoded in separate process for security reason.
  void SetDescription(
      const std::string& title,
      const std::vector<uint8_t>& unsafe_icon_data_png) override;

  FullScreenMode fullscreen_mode() const { return fullscreen_mode_; }

  int task_id() const { return task_id_; }

  const arc::ArcAppShelfId& app_shelf_id() const { return app_shelf_id_; }

  // ui::BaseWindow:
  bool IsActive() const override;
  void Close() override;

  // AppIconLoaderDelegate:
  void OnAppImageUpdated(const std::string& app_id,
                         const gfx::ImageSkia& image) override;

 private:
  // Ensures that default app icon is set.
  void SetDefaultAppIcon();

  // Sets the icon for the window.
  void SetIcon(const gfx::ImageSkia& icon);

  // ImageDecoder::ImageRequest:
  void OnImageDecoded(const SkBitmap& decoded_image) override;

  // Keeps associated ARC task id.
  const int task_id_;
  // Keeps ARC shelf grouping id.
  const arc::ArcAppShelfId app_shelf_id_;
  // Keeps current full-screen mode.
  FullScreenMode fullscreen_mode_ = FullScreenMode::kNotDefined;
  ArcAppWindowDelegate* const owner_;

  // Set to true in case image fetch is requested. This indicates that default
  // app icon is returned in |OnAppImageUpdated|.
  bool image_fetching_ = false;
  base::OneShotTimer apply_default_image_timer_;

  Profile* const profile_;

  // Loads the ARC app icon to the window icon keys. Nullptr once a custom icon
  // has been successfully set.
  std::unique_ptr<AppServiceAppIconLoader> app_icon_loader_;

  DISALLOW_COPY_AND_ASSIGN(ArcAppWindow);
};

#endif  // CHROME_BROWSER_UI_ASH_LAUNCHER_ARC_APP_WINDOW_H_


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis
{
    public static class ISymbolExtensions
    {
        /// <summary>
        /// Returns the constructed form of the ReducedFrom property,
        /// including the type arguments that were either inferred during reduction or supplied at the call site.
        /// </summary>
        public static IMethodSymbol GetConstructedReducedFrom(this IMethodSymbol method)
        {
            if (method.MethodKind != MethodKind.ReducedExtension)
            {
                // not a reduced extension method
                return null;
            }

            var reducedFrom = method.ReducedFrom;
            if (!reducedFrom.IsGenericMethod)
            {
                // not generic, no inferences were made
                return reducedFrom;
            }

            var typeArgs = new ITypeSymbol[reducedFrom.TypeParameters.Length];

            // first seed with any type arguments from reduced method
            for (int i = 0, n = method.TypeParameters.Length; i < n; i++)
            {
                var arg = method.TypeArguments[i];

                // make sure we don't construct with type parameters originating from reduced symbol.
                if (arg.Equals(method.TypeParameters[i]))
                {
                    arg = method.TypeParameters[i].ReducedFrom;
                }

                typeArgs[method.TypeParameters[i].ReducedFrom.Ordinal] = arg;
            }

            // add any inferences
            for (int i = 0, n = reducedFrom.TypeParameters.Length; i < n; i++)
            {
                var inferredType = method.GetTypeInferredDuringReduction(reducedFrom.TypeParameters[i]);
                if (inferredType != null)
                {
                    typeArgs[i] = inferredType;
                }
            }

            return reducedFrom.Construct(typeArgs);
        }
    }
}


text:
#include "config.h"

#ifndef HAVE_SOCKLEN_T
#define socklen_t int
#endif

/* These attempt to coax various unix flavours to declare all our
   needed tidbits in the system headers.  */
#if !defined(__FreeBSD__) && !defined(__APPLE__)
#define _POSIX_SOURCE
#endif /* Some BSDs break <sys/socket.h> if this is defined. */
#define _GNU_SOURCE
#define _XOPEN_SOURCE
#define _BSD_TYPES
#define __EXTENSIONS__
#define _ALL_SOURCE
#define _LARGE_FILE_API
#define _XOPEN_SOURCE_EXTENDED 1
#define _REENTRANT

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <stdbool.h>

#include "mf-runtime.h"
#include "mf-impl.h"

#ifdef _MUDFLAP
#error "Do not compile this file with -fmudflap!"
#endif

#ifndef LIBMUDFLAPTH
#error "pthreadstuff is to be included only in libmudflapth"
#endif

/* ??? Why isn't this done once in the header files.  */
DECLARE(void *, malloc, size_t sz);
DECLARE(void, free, void *ptr);
DECLARE(int, pthread_create, pthread_t *thr, const pthread_attr_t *attr,
	void * (*start) (void *), void *arg);

/* Multithreading support hooks.  */

#if !defined(HAVE_TLS) || defined(USE_EMUTLS)
/* We don't have TLS.  Ordinarily we could use pthread keys, but since we're
   commandeering malloc/free that presents a few problems.  The first is that
   we'll recurse from __mf_get_state to pthread_setspecific to malloc back to
   __mf_get_state during thread startup.  This can be solved with clever uses
   of a mutex.  The second problem is that thread shutdown is indistinguishable
   from thread startup, since libpthread is deallocating our state variable.
   I've no good solution for this.

   Which leaves us to handle this mess by totally by hand.  */

/* Yes, we want this prime.  If pthread_t is a pointer, it's almost always
   page aligned, and if we use a smaller power of 2, this results in "%N"
   being the worst possible hash -- all threads hash to zero.  */
#define LIBMUDFLAPTH_THREADS_MAX 1021

struct mf_thread_data
{
  pthread_t self;
  unsigned char used_p;
  unsigned char state;
};

static struct mf_thread_data mf_thread_data[LIBMUDFLAPTH_THREADS_MAX];
static pthread_mutex_t mf_thread_data_lock = PTHREAD_MUTEX_INITIALIZER;

#define PTHREAD_HASH(p) ((unsigned long) (p) % LIBMUDFLAPTH_THREADS_MAX)

static struct mf_thread_data *
__mf_find_threadinfo (int alloc)
{
  pthread_t self = pthread_self ();
  unsigned long hash = PTHREAD_HASH (self);
  unsigned long rehash;

#ifdef __alpha__
  /* Alpha has the loosest memory ordering rules of all.  We need a memory
     barrier to flush the reorder buffer before considering a *read* of a
     shared variable.  Since we're not always taking a lock, we have to do
     this by hand.  */
  __sync_synchronize ();
#endif

  rehash = hash;
  while (1)
    {
      if (mf_thread_data[rehash].used_p && mf_thread_data[rehash].self == self)
	return &mf_thread_data[rehash];

      rehash += 7;
      if (rehash >= LIBMUDFLAPTH_THREADS_MAX)
	rehash -= LIBMUDFLAPTH_THREADS_MAX;
      if (rehash == hash)
	break;
    }

  if (alloc)
    {
      pthread_mutex_lock (&mf_thread_data_lock);

      rehash = hash;
      while (1)
	{
	  if (!mf_thread_data[rehash].used_p)
	    {
	      mf_thread_data[rehash].self = self;
	      __sync_synchronize ();
	      mf_thread_data[rehash].used_p = 1;

	      pthread_mutex_unlock (&mf_thread_data_lock);
	      return &mf_thread_data[rehash];
	    }

	  rehash += 7;
	  if (rehash >= LIBMUDFLAPTH_THREADS_MAX)
	    rehash -= LIBMUDFLAPTH_THREADS_MAX;
	  if (rehash == hash)
	    break;
	}

      pthread_mutex_unlock (&mf_thread_data_lock);
    }

  return NULL;
}

enum __mf_state_enum
__mf_get_state (void)
{
  struct mf_thread_data *data = __mf_find_threadinfo (0);
  if (data)
    return data->state;

  /* If we've never seen this thread before, consider it to be in the
     reentrant state.  The state gets reset to active for the main thread
     in __mf_init, and for child threads in __mf_pthread_spawner.

     The trickiest bit here is that the LinuxThreads pthread_manager thread
     should *always* be considered to be reentrant, so that none of our
     hooks actually do anything.  Why?  Because that thread isn't a real
     thread from the point of view of the thread library, and so lots of
     stuff isn't initialized, leading to SEGV very quickly.  Even calling
     pthread_self is a bit suspect, but it happens to work.  */

  return reentrant;
}

void
__mf_set_state (enum __mf_state_enum new_state)
{
  struct mf_thread_data *data = __mf_find_threadinfo (1);
  data->state = new_state;
}
#endif

/* The following two functions are used only with __mf_opts.heur_std_data.
   We're interested in recording the location of the thread-local errno
   variable.

   Note that this doesn't handle TLS references in general; we have no
   visibility into __tls_get_data for when that memory is allocated at
   runtime.  Hopefully we get to see the malloc or mmap operation that
   eventually allocates the backing store.  */

/* Describe the startup information for a new user thread.  */
struct mf_thread_start_info
{
  /* The user's thread entry point and argument.  */
  void * (*user_fn)(void *);
  void *user_arg;
};

static void
__mf_pthread_cleanup (void *arg)
{
  if (__mf_opts.heur_std_data)
    __mf_unregister (&errno, sizeof (errno), __MF_TYPE_GUESS);

#if !defined(HAVE_TLS) || defined(USE_EMUTLS)
  struct mf_thread_data *data = __mf_find_threadinfo (0);
  if (data)
    data->used_p = 0;
#endif
}

static void *
__mf_pthread_spawner (void *arg)
{
  void *result = NULL;

  __mf_set_state (active);

  /* NB: We could use __MF_TYPE_STATIC here, but we guess that the thread
     errno is coming out of some dynamically allocated pool that we already
     know of as __MF_TYPE_HEAP. */
  if (__mf_opts.heur_std_data)
    __mf_register (&errno, sizeof (errno), __MF_TYPE_GUESS,
		   "errno area (thread)");

  /* We considered using pthread_key_t objects instead of these
     cleanup stacks, but they were less cooperative with the
     interposed malloc hooks in libmudflap.  */
  /* ??? The pthread_key_t problem is solved above...  */
  pthread_cleanup_push (__mf_pthread_cleanup, NULL);

  /* Extract given entry point and argument.  */
  struct mf_thread_start_info *psi = arg;
  void * (*user_fn)(void *) = psi->user_fn;
  void *user_arg = psi->user_arg;
  CALL_REAL (free, arg);

  result = (*user_fn)(user_arg);

  pthread_cleanup_pop (1 /* execute */);

  return result;
}

#if PIC
/* A special bootstrap variant. */
int
__mf_0fn_pthread_create (pthread_t *thr, const pthread_attr_t *attr,
			 void * (*start) (void *), void *arg)
{
  return -1;
}
#endif

#undef pthread_create
WRAPPER(int, pthread_create, pthread_t *thr, const pthread_attr_t *attr,
	 void * (*start) (void *), void *arg)
{
  struct mf_thread_start_info *si;

  TRACE ("pthread_create\n");

  /* Fill in startup-control fields.  */
  si = CALL_REAL (malloc, sizeof (*si));
  si->user_fn = start;
  si->user_arg = arg;

  /* Actually create the thread.  */
  return CALL_REAL (pthread_create, thr, attr, __mf_pthread_spawner, si);
}


text:
package org.fax4j;

import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.fax4j.FaxClientActionEvent.FaxClientActionEventID;
import org.fax4j.FaxJob.FaxJobPriority;
import org.fax4j.FaxMonitorEvent.FaxMonitorEventID;
import org.fax4j.common.Fax4JProvider;
import org.fax4j.common.Logger;
import org.fax4j.spi.AbstractFaxClientSpi;
import org.fax4j.spi.FaxClientSpi;
import org.fax4j.spi.FaxJobImpl;
import org.fax4j.spi.FaxJobMonitor;
import org.fax4j.spi.FaxJobMonitorImpl;
import org.fax4j.test.TestUtil;
import org.fax4j.test.TestUtil.EmptyFaxClientSpi;
import org.fax4j.test.TestUtil.TestFaxClientActionEventListener;
import org.fax4j.test.TestUtil.TestFaxMonitorEventListener;
import org.fax4j.util.IOHelper;
import org.fax4j.util.ReflectionHelper;
import org.junit.Assert;
import org.junit.Test;

/**
 * Test Class
 *
 * @author 	Sagie Gur-Ari
 */
public class FaxClientTest
{
	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test
	public void exampleTest() throws Exception
	{
		//data setup
		Properties configuration=new Properties();
		configuration.setProperty("org.fax4j.spi.type.map.test",EmptyFaxClientSpi.class.getName());
		File file=File.createTempFile("temp_",".txt");
		IOHelper.writeTextFile("TEST_DATA",file);
		file.deleteOnExit();

		//get new instance of a fax client
		FaxClient faxClient=FaxClientFactory.createFaxClient("test",configuration);

		//create a new fax job
		FaxJob faxJob=faxClient.createFaxJob();

		//set fax job values
		faxJob.setFile(file);
		faxJob.setPriority(FaxJobPriority.HIGH_PRIORITY);
		faxJob.setTargetAddress("555-555");
		faxJob.setTargetName("YourName");
		faxJob.setSenderEmail("myemail@mycompany.com");
		faxJob.setSenderName("MyName");

		//submit fax job
		faxClient.submitFaxJob(faxJob);

		file.delete();
	}

	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test(expected=FaxException.class)
	public void constructorEmptySPITest() throws Exception
	{
		FaxClient client=new FaxClient(null);
		Assert.assertEquals(client.getProvider().getName(),Fax4JProvider.FAX4J_PROVIDER.getName());
	}

	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test(expected=FaxException.class)
	public void constructorEmptySPILoggerTest() throws Exception
	{
		FaxClientSpi faxClientSpi=new FaxClientSpi()
		{
			/**
			 * Returns the internal logger.
			 *
			 * @return	The internal logger
			 */
			public Logger getLogger()
			{
				return null;
			}
			public FaxJob createFaxJob()
			{
				return null;
			}
			public void submitFaxJob(FaxJob faxJob)
			{
				//empty
			}
			public void suspendFaxJob(FaxJob faxJob)
			{
				//empty
			}
			public void resumeFaxJob(FaxJob faxJob)
			{
				//empty
			}
			public void cancelFaxJob(FaxJob faxJob)
			{
				//empty
			}
			public FaxJobStatus getFaxJobStatus(FaxJob faxJob)
			{
				return null;
			}
			public void addFaxClientActionEventListener(FaxClientActionEventListener listener)
			{
				//empty
			}
			public void removeFaxClientActionEventListener(FaxClientActionEventListener listener)
			{
				//empty
			}
			public void removeAllFaxClientActionEventListeners()
			{
				//empty
			}
			public void addFaxMonitorEventListener(FaxMonitorEventListener listener)
			{
				//empty
			}
			public void removeFaxMonitorEventListener(FaxMonitorEventListener listener)
			{
				//empty
			}
			public void removeAllFaxMonitorEventListeners()
			{
				//empty
			}
			public Provider getProvider()
			{
				return null;
			}
			public void initialize(Map<String,String> configuration,Logger logger,FaxJobMonitor faxJobMonitor)
			{
				//empty
			}
			public String getConfigurationValue(String key)
			{
				return null;
			}
			public void fireFaxMonitorEvent(FaxMonitorEventID id,FaxJob faxJob,FaxJobStatus faxJobStatus)
			{
				//empty
			}
			public FaxJobMonitor getFaxJobMonitor()
			{
				return null;
			}
			public FaxJobStatus[] pollForFaxJobStatues(FaxJob[] faxJobs)
			{
				return null;
			}
			public boolean isFaxMonitorEventsSupported()
			{
				return false;
			}
			public Map<String,String> getConfiguration()
			{
				return null;
			}
			public String getConfigurationValue(Enum<?> key)
			{
				return this.getConfigurationValue(key.toString());
			}
			public String getPropertyPart()
			{
				return null;
			}
		};
		FaxClient client=new FaxClient(faxClientSpi);
		Assert.assertEquals(client.getProvider().getName(),Fax4JProvider.FAX4J_PROVIDER.getName());
	}

	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test
	public void getProviderTest() throws Exception
	{
		EmptyFaxClientSpi faxClientSpi=(EmptyFaxClientSpi)TestUtil.createFaxClientSpi(EmptyFaxClientSpi.class.getName(),null);
		FaxClient faxClient=new FaxClient(faxClientSpi);
		Provider provider=faxClient.getProvider();
		Assert.assertNotNull(provider);
		Assert.assertEquals(faxClientSpi.getProvider(),provider);
	}

	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test
	public void faxJobCreatedEventTest() throws Exception
	{
		TestFaxClientActionEventListener listener=new TestFaxClientActionEventListener();
		EmptyFaxClientSpi faxClientSpi=(EmptyFaxClientSpi)TestUtil.createFaxClientSpi(EmptyFaxClientSpi.class.getName(),null);
		FaxClient faxClient=new FaxClient(faxClientSpi);
		faxClient.addFaxClientActionEventListener(listener);
		faxClient.createFaxJob();
		FaxClientActionEventID faxClientActionEventID=listener.getLastFaxEventID();
		Assert.assertNotNull(faxClientActionEventID);
		Assert.assertEquals(FaxClientActionEventID.CREATE_FAX_JOB,faxClientActionEventID);
	}

	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test
	public void faxJobSubmittedEventTest() throws Exception
	{
		String string="My Text Data";
		File file=File.createTempFile("temp_",".txt");
		file.deleteOnExit();
		IOHelper.writeTextFile(string,file);

		TestFaxClientActionEventListener listener=new TestFaxClientActionEventListener();
		EmptyFaxClientSpi faxClientSpi=(EmptyFaxClientSpi)TestUtil.createFaxClientSpi(EmptyFaxClientSpi.class.getName(),null);
		FaxClient faxClient=new FaxClient(faxClientSpi);
		faxClient.addFaxClientActionEventListener(listener);
		FaxJob faxJob=new FaxJobImpl();
		faxJob.setTargetAddress("123");
		faxJob.setFile(file);
		faxClient.submitFaxJob(faxJob);

		file.delete();

		FaxClientActionEventID faxClientActionEventID=listener.getLastFaxEventID();
		Assert.assertNotNull(faxClientActionEventID);
		Assert.assertEquals(FaxClientActionEventID.SUBMIT_FAX_JOB,faxClientActionEventID);
	}

	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test
	public void faxJobSuspendedEventTest() throws Exception
	{
		TestFaxClientActionEventListener listener=new TestFaxClientActionEventListener();
		EmptyFaxClientSpi faxClientSpi=(EmptyFaxClientSpi)TestUtil.createFaxClientSpi(EmptyFaxClientSpi.class.getName(),null);
		FaxClient faxClient=new FaxClient(faxClientSpi);
		faxClient.addFaxClientActionEventListener(listener);
		FaxJob faxJob=new FaxJobImpl();
		faxJob.setID("123");
		faxClient.suspendFaxJob(faxJob);
		FaxClientActionEventID faxClientActionEventID=listener.getLastFaxEventID();
		Assert.assertNotNull(faxClientActionEventID);
		Assert.assertEquals(FaxClientActionEventID.SUSPEND_FAX_JOB,faxClientActionEventID);
	}

	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test
	public void faxJobResumedEventTest() throws Exception
	{
		TestFaxClientActionEventListener listener=new TestFaxClientActionEventListener();
		EmptyFaxClientSpi faxClientSpi=(EmptyFaxClientSpi)TestUtil.createFaxClientSpi(EmptyFaxClientSpi.class.getName(),null);
		FaxClient faxClient=new FaxClient(faxClientSpi);
		faxClient.addFaxClientActionEventListener(listener);
		FaxJob faxJob=new FaxJobImpl();
		faxJob.setID("123");
		faxClient.resumeFaxJob(faxJob);
		FaxClientActionEventID faxClientActionEventID=listener.getLastFaxEventID();
		Assert.assertNotNull(faxClientActionEventID);
		Assert.assertEquals(FaxClientActionEventID.RESUME_FAX_JOB,faxClientActionEventID);
	}

	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test
	public void faxJobCancelledEventTest() throws Exception
	{
		TestFaxClientActionEventListener listener=new TestFaxClientActionEventListener();
		EmptyFaxClientSpi faxClientSpi=(EmptyFaxClientSpi)TestUtil.createFaxClientSpi(EmptyFaxClientSpi.class.getName(),null);
		FaxClient faxClient=new FaxClient(faxClientSpi);
		faxClient.addFaxClientActionEventListener(listener);
		FaxJob faxJob=new FaxJobImpl();
		faxJob.setID("123");
		faxClient.cancelFaxJob(faxJob);
		FaxClientActionEventID faxClientActionEventID=listener.getLastFaxEventID();
		Assert.assertNotNull(faxClientActionEventID);
		Assert.assertEquals(FaxClientActionEventID.CANCEL_FAX_JOB,faxClientActionEventID);
	}

	/**
	 * Test
	 *
	 * @throws 	Exception
	 * 			Any exception
	 */
	@Test
	public void faxJobStatusChangeEventTest() throws Exception
	{
		String string="My Text Data";
		File file=File.createTempFile("temp_",".txt");
		file.deleteOnExit();
		IOHelper.writeTextFile(string,file);

		EmptyFaxClientSpi faxClientSpi=(EmptyFaxClientSpi)TestUtil.createFaxClientSpi(EmptyFaxClientSpi.class.getName(),null);
		Field field=ReflectionHelper.getField(AbstractFaxClientSpi.class,"spiFaxJobMonitor");
		FaxJobMonitor faxJobMonitor=new FaxJobMonitorImpl();
		Map<String,String> configuration=faxClientSpi.getAllConfiguration();
		Map<String,String> map=new HashMap<String,String>(configuration);
		map.putAll(configuration);
		map.put("org.fax4j.monitor.polling.interval","100");
		faxJobMonitor.initialize(map,faxClientSpi.getLogger());
		field.set(faxClientSpi,faxJobMonitor);

		TestFaxMonitorEventListener listener=new TestFaxMonitorEventListener();
		FaxClient faxClient=new FaxClient(faxClientSpi);
		faxClient.addFaxMonitorEventListener(listener);
		FaxJob faxJob=new FaxJobImpl();
		faxJob.setTargetAddress("123");
		faxJob.setFile(file);
		faxClient.submitFaxJob(faxJob);

		file.delete();

		//wait for event
		Thread.sleep(120);

		FaxJobStatus faxJobStatus=listener.getLastFaxJobStatus();
		Assert.assertNotNull(faxJobStatus);
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="io.picopalette.apps.event_me.Activities.ListCreationActivity">

    <TextView
        android:id="@+id/titleTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textColor="@color/colorPrimaryDark"
        android:textAllCaps="true"
        android:textStyle="bold"
        android:textSize="25sp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintVertical_bias="0.016"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.135"
        android:id="@+id/linearLayout">

        <EditText
            android:id="@+id/listEditText"
            android:layout_width="wrap_content"
            android:layout_height="72dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_toStartOf="@+id/addFAB"
            android:hint="@string/list_title_hint"
            android:inputType="textCapWords|textPersonName" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/addFAB"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            app:fabSize="mini"
            app:srcCompat="@drawable/ic_add_white_24dp"
            android:layout_centerVertical="true"
            android:layout_alignParentEnd="true" />

    </RelativeLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/list_creation_RecyclerView"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="24dp"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/linearLayout"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp">

        </android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>


text:
'use strict';

var trim = require('trim-x');
var reNormalize = new RegExp('[' + require('white-space-x').string + ']+', 'g');

/**
 * This method strips leading and trailing white-space from a string,
 * replaces sequences of whitespace characters by a single space,
 * and returns the resulting string.
 *
 * @param {string} string - The string to be normalized.
 * @returns {string} The normalized string.
 * @example
 * var normalizeSpace = require('normalize-space-x');
 *
 * normalizeSpace(' \t\na \t\nb \t\n') === 'a b'; // true
 */
module.exports = function normalizeSpace(string) {
  return trim(string).replace(reNormalize, ' ');
};


text:
namespace blink {

class CSSAngleInterpolationType : public CSSInterpolationType {
 public:
  CSSAngleInterpolationType(PropertyHandle property,
                            const PropertyRegistration* registration = nullptr)
      : CSSInterpolationType(property, registration) {
    DCHECK(property.IsCSSCustomProperty());
  }

  InterpolationValue MaybeConvertNeutral(const InterpolationValue& underlying,
                                         ConversionCheckers&) const final;
  InterpolationValue MaybeConvertValue(const CSSValue&,
                                       const StyleResolverState*,
                                       ConversionCheckers&) const final;

  const CSSValue* CreateCSSValue(const InterpolableValue&,
                                 const NonInterpolableValue*,
                                 const StyleResolverState&) const final;

 private:
  // These methods only apply to CSSInterpolationTypes used by standard CSS
  // properties.
  // CSSAngleInterpolationType is only accessible via registered custom CSS
  // properties.
  InterpolationValue MaybeConvertStandardPropertyUnderlyingValue(
      const ComputedStyle&) const final {
    NOTREACHED();
    return nullptr;
  }
  void ApplyStandardPropertyValue(const InterpolableValue&,
                                  const NonInterpolableValue*,
                                  StyleResolverState&) const final {
    NOTREACHED();
  }
  InterpolationValue MaybeConvertInitial(const StyleResolverState&,
                                         ConversionCheckers&) const final {
    NOTREACHED();
    return nullptr;
  }
  InterpolationValue MaybeConvertInherit(const StyleResolverState&,
                                         ConversionCheckers&) const final {
    NOTREACHED();
    return nullptr;
  }
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_ANGLE_INTERPOLATION_TYPE_H_


text:
@interface TAStoreProductViewController ()

@end

@implementation TAStoreProductViewController

- (BOOL)shouldAutorotate {
    UIInterfaceOrientationMask applicationSupportedOrientations = [[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:[[UIApplication sharedApplication] keyWindow]];
    UIInterfaceOrientationMask viewControllerSupportedOrientations = [self supportedInterfaceOrientations];
    return viewControllerSupportedOrientations & applicationSupportedOrientations;
}

@end


text:
<?php

namespace App\Models;

/**
 * @property int        $id
 * @property int        $show_id
 * @property int        $appearance_id
 * @property Show       $show          (Via relations)
 * @property Appearance $appearance    (Via relations)
 * @method static self find_by_show_id_and_appearance_id(int $show_id, int $appearance_id)
 */
class ShowAppearance extends NSModel {
  public static $table_name = 'show_appearances';

  public static $belongs_to = [
    ['show'],
    ['appearance'],
  ];

  public static function makeRelation(int $show_id, int $appearance_id):void {
    $relation = new self();
    $relation->show_id = $show_id;
    $relation->appearance_id = $appearance_id;
    $relation->save();
  }
}


text:
import { Component } from '@angular/core';

@Component({
  selector: 'ngx-spinner-color',
  templateUrl: 'spinner-color.component.html',
})

export class SpinnerColorComponent {
}


text:
require 'incrimentia/version'

# Incriments a number
#
# @param [Fixnum] incriment by 1
def incriment(x)
	x + 1
end


text:
(function() {
	'use strict';

	var serviceModule = angular.module('eagle.service');
	serviceModule.service('$wrapState', function($state, $location, $stateParams) {
		var $wrapState = {};
		var _targetState = null;
		var _targetPriority = 0;

		// Go
		$wrapState.go = function(state, param, priority) {
			setTimeout(function() {
				_targetState = null;
				_targetPriority = 0;
			});

			if(typeof param !== "object") {
				param = {};
				priority = param;
			}

			priority = priority === true ? 1 : (priority || 0);
			if(_targetPriority > priority) {
				console.log("[Wrap State] Go - low priority:", state, "(Skip)");
				return false;
			}

			if(_targetState !== state || priority) {
				if($state.current && $state.current.name === state && angular.equals($state.params, param)) {
					console.log($state);
					console.log("[Wrap State] Go reload.");
					$state.reload();
				} else {
					console.log("[Wrap State] Go:", state, param, priority);
					$state.go(state, param);
				}
				_targetState = state;
				_targetPriority = priority;
				return true;
			} else {
				console.log("[Wrap State] Go:", state, "(Ignored)");
			}
			return false;
		};

		// Reload
		$wrapState.reload = function() {
			console.log("[Wrap State] Do reload.");
			$state.reload();
		};

		// Path
		$wrapState.path = function(path) {
			if(path !== undefined) {
				console.log("[Wrap State][Deprecated] Switch path:", path);
			}
			return $location.path(path);
		};

		// URL
		$wrapState.url = function(url) {
			if(url !== undefined) console.log("[Wrap State] Switch url:", url);
			return $location.url(url);
		};

		Object.defineProperties($wrapState, {
			// Origin $state
			origin: {
				get: function() {
					return $state;
				}
			},

			// Current
			current: {
				get: function() {
					return $state.current;
				}
			},

			// Parameter
			param: {
				get: function() {
					return $.extend({}, $location.search(), $stateParams);
				}
			}
		});

		return $wrapState;
	});
})();