text:
using namespace boost::spirit;

template <typename Iterator>
struct grammar : public qi::grammar<Iterator, double(), ascii::space_type>
{
	qi::rule<Iterator, double(), ascii::space_type> expr, term, fctr;
	double time;
	grammar(double t) : grammar::base_type(expr), time(t)
	{
		expr = term[_val = _1] >> *(('+' >> term[_val += _1]) | ('-' >> term[_val -= _1]));
		term = fctr[_val = _1] >> *(('*' >> fctr[_val *= _1]) | ('/' >> fctr[_val /= _1]));
		fctr = double_[_val = _1]
			| '(' >> expr[_val = _1] >> ')'
			| qi::no_case[qi::lit('t')][_val = time]
			| qi::no_case["cloud("] >> expr[_val = boost::phoenix::bind(cloud_, _1)] >> ")"
			| qi::no_case["rain("] >> expr[_val = boost::phoenix::bind(rain_, _1)] >> ")"
			| qi::no_case["wind_speed("] >> expr[_val = boost::phoenix::bind(wind_speed_, _1)] >> ")"
			| qi::no_case["air_temp("] >> expr[_val = boost::phoenix::bind(air_temp_, _1)] >> ")"
			;
	}
};

double rain_chance_;
double min_air_temp_;
double max_air_temp_;

perlin::noise cloud_;
perlin::noise rain_;
perlin::noise wind_speed_;
perlin::noise air_temp_;

std::string cloud_expr_;
std::string rain_expr_;
std::string wind_speed_expr_;
std::string air_temp_expr_;

std::random_device rd_;
std::mt19937 mt_;
bool rainfall_ = false;
bool stoprain_ = false;

void weather_init(unsigned int seed, weather_config *config)
{
	if (seed == 0)
		seed = rd_();
	mt_.seed(seed);

	if (config != nullptr)
	{
		rain_chance_ = config->rain_chance;
		min_air_temp_ = config->min_air_temp;
		max_air_temp_ = config->max_air_temp;

		cloud_.set_seed(mt_());
		cloud_.set_zero(config->cloud.zero);
		cloud_.set_amplitude(config->cloud.amplitude);
		cloud_.set_min_value(config->cloud.min);
		cloud_.set_max_value(config->cloud.max);
		cloud_.set_frequency(1.0 / config->cloud.period);
		cloud_.set_octave(config->cloud.octave);
		cloud_expr_ = config->cloud.expression != nullptr
			? config->cloud.expression : "cloud(T)";

		rain_.set_seed(mt_());
		rain_.set_zero(config->rain.zero);
		rain_.set_amplitude(config->rain.amplitude);
		rain_.set_min_value(config->rain.min);
		rain_.set_max_value(config->rain.max);
		rain_.set_frequency(1.0 / config->rain.period);
		rain_.set_octave(config->rain.octave);
		rain_expr_ = config->rain.expression != nullptr
			? config->rain.expression : "rain(T)";

		wind_speed_.set_seed(mt_());
		wind_speed_.set_zero(config->wind_speed.zero);
		wind_speed_.set_amplitude(config->wind_speed.amplitude);
		wind_speed_.set_min_value(config->wind_speed.min);
		wind_speed_.set_max_value(config->wind_speed.max);
		wind_speed_.set_frequency(1.0 / config->wind_speed.period);
		wind_speed_.set_octave(config->wind_speed.octave);
		wind_speed_expr_ = config->wind_speed.expression != nullptr
			? config->wind_speed.expression : "wind_speed(T)";

		air_temp_.set_seed(mt_());
		air_temp_.set_zero(config->air_temp.zero);
		air_temp_.set_amplitude(config->air_temp.amplitude);
		air_temp_.set_min_value(config->air_temp.min);
		air_temp_.set_max_value(config->air_temp.max);
		air_temp_.set_frequency(1.0 / config->air_temp.period);
		air_temp_.set_octave(config->air_temp.octave);
		air_temp_expr_ = config->air_temp.expression != nullptr
			? config->air_temp.expression : "air_temp(T)";
	}
}

void weather_simulate(double time, weather_info *info)
{
	double c = 0, r = 0, w = 0, a = 0;
	grammar<std::string::iterator> g(time);
	qi::phrase_parse(cloud_expr_.begin(), cloud_expr_.end(), g, ascii::space, c);
	qi::phrase_parse(rain_expr_.begin(), rain_expr_.end(), g, ascii::space, r);
	qi::phrase_parse(wind_speed_expr_.begin(), wind_speed_expr_.end(), g, ascii::space, w);
	qi::phrase_parse(air_temp_expr_.begin(), air_temp_expr_.end(), g, ascii::space, a);

	r = clamp<double>(r, rain_.min_value(), c);
	a *= (max_air_temp_ - min_air_temp_) / 2;
	a += min_air_temp_ + (max_air_temp_ - min_air_temp_) / 2;

	if (!rainfall_)
	{
		if (0 < r)
		{
			if (!stoprain_)
			{
				std::uniform_real_distribution<double> chance(0, 1);
				if (rain_chance_ < chance(mt_))
				{
					stoprain_ = true;
				}
			}
		}
		else
		{
			stoprain_ = false;
		}
	}

	r = stoprain_ ? 0 : r;
	rainfall_ = 0 < r;

	info->cloud = c;
	info->rain = r;
	info->air_temp = a;
	info->wind_speed = w;
}


text:
package shell

import (
	"strings"
)

// ReplaceIgnoreCase works like strings.Replace but ignores cases.
func ReplaceIgnoreCase(s, old, new string) string {
	var buffer strings.Builder
	for {
		pos := strings.Index(strings.ToUpper(s), strings.ToUpper(old))
		if pos < 0 {
			buffer.WriteString(s)
			return buffer.String()
		}
		buffer.WriteString(s[:pos])
		buffer.WriteString(new)
		s = s[pos+len(old):]
	}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _resolve = require('resolve');

var _resolve2 = _interopRequireDefault(_resolve);

var _deepmerge = require('deepmerge');

var _deepmerge2 = _interopRequireDefault(_deepmerge);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _async = require('async');

var _async2 = _interopRequireDefault(_async);

var _gracefulFs = require('graceful-fs');

var _gracefulFs2 = _interopRequireDefault(_gracefulFs);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var tmp = './tmp/';

module.exports = function (grunt) {
    grunt.registerMultiTask('webdriver_stage', 'run wdio test runner', function () {
        if (!_gracefulFs2.default.existsSync(tmp)) {
            _gracefulFs2.default.mkdirSync(tmp);
        }

        var done = this.async();
        var opts = (0, _deepmerge2.default)(this.options(), this.data);
        var webdriverPath = _path2.default.dirname(_resolve2.default.sync('webdriverio'));
        var Launcher = require(_path2.default.join(webdriverPath, 'lib/launcher'));
        var ConfigParser = require(_path2.default.join(webdriverPath, 'lib/utils/ConfigParser'));

        if (typeof opts.configFile !== 'string') {
            grunt.log.error('You need to define "configFile" property with the path to your wdio.conf.js');
            return done(1);
        }

        // 如果指定了stages属性
        if (!_lodash2.default.isUndefined(opts.stages)) {
            // 必须为数组
            if (_lodash2.default.isArray(opts.stages)) {
                var filePath;

                var _ret = function () {
                    // 配置解析器
                    var configParser = new ConfigParser();

                    // 获取wdio.conf.js
                    filePath = _path2.default.resolve(process.cwd(), opts.configFile);

                    var configs = require(filePath).config;

                    // test files
                    var specs = configParser.getSpecs(configs.specs, configs.exclude);

                    if (specs) {
                        var _ret2 = function () {
                            var files = [];
                            var hasError = false;
                            opts.stages.forEach(function (item, index) {
                                var configParser_ = new ConfigParser();
                                var stageSpecs = configParser_.getSpecs(_lodash2.default.isArray(item) ? item : [item], []);

                                stageSpecs.forEach(function (spec) {
                                    if (!_lodash2.default.includes(specs, spec)) {
                                        grunt.log.error('无效测试文件 ' + spec + ' , 所有stages中指定的测试文件必须在wdio配置文件中声明');
                                        hasError = true;
                                    }
                                    if (!_lodash2.default.isString(spec)) {
                                        grunt.log.error('无效测试文件 ' + spec + ' , 此处必须为文件路径字符串');
                                        hasError = true;
                                    }
                                });

                                files[index] = stageSpecs;
                            });

                            var preFiles = files.reduce(function (pre, next) {
                                return pre.concat(next);
                            });

                            files[files.length] = specs.filter(function (item) {
                                return !_lodash2.default.includes(preFiles, item);
                            });

                            if (hasError) {
                                return {
                                    v: {
                                        v: done(false)
                                    }
                                };
                            } else {
                                _async2.default.eachOfLimit(files, 1, function (item, key, callback) {
                                    key += 1;
                                    // 创建新的配置文件
                                    var newFilename = tmp + 'wdio.config.' + new Date().getTime() + '.js';
                                    var newConfigs = _lodash2.default.clone(configs);
                                    newConfigs.specs = item;
                                    var newFileContent = 'exports.config=' + JSON.stringify(newConfigs);
                                    _gracefulFs2.default.writeFileSync(newFilename, newFileContent);

                                    var wdio = new Launcher(newFilename, opts);

                                    grunt.log.debug('开始执行第 ' + key + ' 阶段测试');
                                    wdio.run().then(function (code) {
                                        grunt.log.debug('第 ' + key + ' 阶段测试退出, 任务状态码: ' + code);
                                        callback();
                                    }, function (e) {
                                        grunt.log.error('第 ' + key + ' 阶段测试失败');
                                        callback();
                                    });
                                }, function (err) {
                                    if (err) {
                                        return done(false);
                                    } else {
                                        return done(true);
                                    }
                                });
                            }
                        }();

                        if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
                    }
                }();

                if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
            } else {
                grunt.log.error('property stages type must be Array.');
                return done(false);
            }
        } else {
            var wdio = new Launcher(opts.configFile, opts);

            grunt.log.debug('spawn wdio with these attributes:\n' + JSON.stringify(opts, null, 2));
            return wdio.run().then(function (code) {
                grunt.log.debug('wdio testrunner finished with exit code ' + code);
                return done(code === 0);
            }, function (e) {
                grunt.log.error('Something went wrong: ' + e);
                return done(false);
            });
        }
    });
};


text:
FactoryBot.define do
  factory :member_blog_page, class: Member::BlogPage, traits: [:cms_page] do
    route { "member/blog_page" }
    html { "
html
" }
  end
end


text:
module Notes
  class UpdateService < BaseService
    def execute(note)
      return note unless note.editable?

      old_mentioned_users = note.mentioned_users(current_user).to_a

      note.update(params.merge(updated_by: current_user))

      only_commands = false

      quick_actions_service = QuickActionsService.new(project, current_user)
      if quick_actions_service.supported?(note)
        content, update_params, message = quick_actions_service.execute(note, {})

        only_commands = content.empty?

        note.note = content
      end

      unless only_commands
        note.create_new_cross_references!(current_user)

        update_todos(note, old_mentioned_users)

        update_suggestions(note)
      end

      if quick_actions_service.commands_executed_count.to_i > 0
        if update_params.present?
          quick_actions_service.apply_updates(update_params, note)
          note.commands_changes = update_params
        end

        if only_commands
          delete_note(note, message)
          note = nil
        else
          note.save
        end
      end

      note
    end

    private

    def delete_note(note, message)
      # We must add the error after we call #save because errors are reset
      # when #save is called
      note.errors.add(:commands_only, message.presence || _('Commands did not apply'))

      Notes::DestroyService.new(project, current_user).execute(note)
    end

    def update_suggestions(note)
      return unless note.supports_suggestion?

      Suggestion.transaction do
        note.suggestions.delete_all
        Suggestions::CreateService.new(note).execute
      end

      # We need to refresh the previous suggestions call cache
      # in order to get the new records.
      note.reset
    end

    def update_todos(note, old_mentioned_users)
      return unless note.previous_changes.include?('note')

      TodoService.new.update_note(note, current_user, old_mentioned_users)
    end
  end
end


text:
// |reftest| skip -- obsolete test
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//-----------------------------------------------------------------------------
var BUGNUMBER = 350387;
var summary = 'Var declaration and let with same name';
var actual = '';
var expect = '';

expect = undefined + '';
actual = '';
let (x = 2)
{
  var x;
}
actual = x + '';
reportCompare(expect, actual, summary + ': 1');

//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------

function test()
{
  enterFunc ('test');
  printBugNumber(BUGNUMBER);
  printStatus (summary);

  expect = undefined + '';
  actual = '';
  (function () { let (x = 2) { var x; } actual = x + ''; })();
  reportCompare(expect, actual, summary + ': 2');

  exitFunc ('test');
}


text:
/* tslint:disable */
import * as React from 'react';
/* tslint:enable */
import {
  BaseComponent,
  assign,
  autobind
} from 'office-ui-fabric-react/lib/Utilities';
import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';
import { Toggle } from 'office-ui-fabric-react/lib/Toggle';
import { IPersonaProps } from 'office-ui-fabric-react/lib/Persona';
import { IContextualMenuItem } from 'office-ui-fabric-react/lib/ContextualMenu';
import {
  CompactPeoplePicker,
  IBasePickerSuggestionsProps,
  ListPeoplePicker,
  NormalPeoplePicker
} from 'office-ui-fabric-react/lib/Pickers';
import { IPersonaWithMenu } from 'office-ui-fabric-react/lib/components/pickers/PeoplePicker/PeoplePickerItems/PeoplePickerItem.Props';
import { people } from './PeoplePickerExampleData';
import './PeoplePicker.Types.Example.scss';
import { Promise } from 'es6-promise';

export interface IPeoplePickerExampleState {
  currentPicker?: number | string;
  delayResults?: boolean;
}

const suggestionProps: IBasePickerSuggestionsProps = {
  suggestionsHeaderText: 'Suggested People',
  noResultsFoundText: 'No results found',
  loadingText: 'Loading'
};

export class PeoplePickerTypesExample extends BaseComponent<any, IPeoplePickerExampleState> {
  private _peopleList;
  private contextualMenuItems: IContextualMenuItem[] = [
    {
      key: 'newItem',
      icon: 'circlePlus',
      name: 'New'
    },
    {
      key: 'upload',
      icon: 'upload',
      name: 'Upload'
    },
    {
      key: 'divider_1',
      name: '-',
    },
    {
      key: 'rename',
      name: 'Rename'
    },
    {
      key: 'properties',
      name: 'Properties'
    },
    {
      key: 'disabled',
      name: 'Disabled item',
      disabled: true
    }
  ];

  constructor() {
    super();
    this._peopleList = [];
    people.forEach((persona: IPersonaProps) => {
      let target: IPersonaWithMenu = {};

      assign(target, persona, { menuItems: this.contextualMenuItems });
      this._peopleList.push(target);
    });

    this.state = {
      currentPicker: 1,
      delayResults: false
    };
  }

  public render() {
    let currentPicker: JSX.Element;

    switch (this.state.currentPicker) {
      case 1:
        currentPicker = this._renderNormalPicker();
        break;
      case 2:
        currentPicker = this._renderCompactPicker();
        break;
      case 3:
        currentPicker = this._renderListPicker();
        break;
      case 4:
        currentPicker = this._renderPreselectedItemsPicker();
        break;
      case 5:
        currentPicker = this._renderLimitedSearch();
        break;
    }

    return (

        { currentPicker }

          <Dropdown label='Select People Picker Type'
            options={ [
              { key: 1, text: 'Normal' },
              { key: 2, text: 'Compact' },
              { key: 3, text: 'Members List' },
              { key: 4, text: 'Preselected Items' },
              { key: 5, text: 'Limit Search' }
            ] }
            selectedKey={ this.state.currentPicker }
            onChanged={ this._dropDownSelected }
          />
          <Toggle
            label='Delay Suggestion Results'
            defaultChecked={ false }
            onChanged={ this._toggleChange } />

    );
  }

  public _renderListPicker() {
    return (
      <ListPeoplePicker
        onResolveSuggestions={ this._onFilterChanged }
        getTextFromItem={ (persona: IPersonaProps) => persona.primaryText }
        className={ 'ms-PeoplePicker' }
        pickerSuggestionsProps={ suggestionProps }
        key={ 'list' }
      />
    );
  }

  public _renderNormalPicker() {
    return (
      <NormalPeoplePicker
        onResolveSuggestions={ this._onFilterChanged }
        getTextFromItem={ (persona: IPersonaProps) => persona.primaryText }
        pickerSuggestionsProps={ suggestionProps }
        className={ 'ms-PeoplePicker' }
        key={ 'normal' }
      />
    );
  }

  public _renderCompactPicker() {
    return (
      <CompactPeoplePicker
        onResolveSuggestions={ this._onFilterChanged }
        getTextFromItem={ (persona: IPersonaProps) => persona.primaryText }
        pickerSuggestionsProps={ suggestionProps }
        className={ 'ms-PeoplePicker' }
      />
    );
  }

  public _renderPreselectedItemsPicker() {
    return (
      <CompactPeoplePicker
        onResolveSuggestions={ this._onFilterChanged }
        getTextFromItem={ (persona: IPersonaProps) => persona.primaryText }
        className={ 'ms-PeoplePicker' }
        defaultSelectedItems={ people.splice(0, 3) }
        key={ 'list' }
        pickerSuggestionsProps={ suggestionProps }
      />
    );
  }

  public _renderLimitedSearch() {
    let limitedSearchSuggestionProps = suggestionProps;
    limitedSearchSuggestionProps.searchForMoreText = 'Load all Results';
    return (
      <CompactPeoplePicker
        onResolveSuggestions={ this._onFilterChangedWithLimit }
        getTextFromItem={ (persona: IPersonaProps) => persona.primaryText }
        className={ 'ms-PeoplePicker' }
        onGetMoreResults={ this._onFilterChanged }
        pickerSuggestionsProps={ limitedSearchSuggestionProps }
      />
    );
  }

  @autobind
  private _onFilterChanged(filterText: string, currentPersonas: IPersonaProps[], limitResults?: number) {
    if (filterText) {
      let filteredPersonas: IPersonaProps[] = this._filterPersonasByText(filterText);

      filteredPersonas = this._removeDuplicates(filteredPersonas, currentPersonas);
      filteredPersonas = limitResults ? filteredPersonas.splice(0, limitResults) : filteredPersonas;
      return this._filterPromise(filteredPersonas);
    } else {
      return [];
    }
  }

  @autobind
  private _onFilterChangedWithLimit(filterText: string, currentPersonas: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> {
    return this._onFilterChanged(filterText, currentPersonas, 3);
  }

  private _filterPromise(personasToReturn: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> {
    if (this.state.delayResults) {
      return this._convertResultsToPromise(personasToReturn);
    } else {
      return personasToReturn;
    }
  }

  private _listContainsPersona(persona: IPersonaProps, personas: IPersonaProps[]) {
    if (!personas || !personas.length || personas.length === 0) {
      return false;
    }
    return personas.filter(item => item.primaryText === persona.primaryText).length > 0;
  }

  private _filterPersonasByText(filterText: string): IPersonaProps[] {
    return this._peopleList.filter(item => this._doesTextStartWith(item.primaryText, filterText));
  }

  private _doesTextStartWith(text: string, filterText: string): boolean {
    return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
  }

  private _convertResultsToPromise(results: IPersonaProps[]): Promise<IPersonaProps[]> {
    return new Promise<IPersonaProps[]>((resolve, reject) => setTimeout(() => resolve(results), 2000));
  }

  private _removeDuplicates(personas: IPersonaProps[], possibleDupes: IPersonaProps[]) {
    return personas.filter(persona => !this._listContainsPersona(persona, possibleDupes));
  }

  @autobind
  private _toggleChange(toggleState: boolean) {
    this.setState({ delayResults: toggleState });
  }

  @autobind
  private _dropDownSelected(option: IDropdownOption) {
    this.setState({ currentPicker: option.key });
  }

}


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

  angular.module('cordHome', [])
    .controller('CordHomeCtrl', function ($log, $scope, $cookies, cordConfig, SubscriberUsers) {

      $scope.page.curr = 'dashboard';

      SubscriberUsers.query({subscriberId: $cookies.get('subscriberId')}).$promise
      .then(function(res){
        $scope.bundle_name = cordConfig.bundles[cordConfig.activeBundle].name;
        $scope.bundle_desc = cordConfig.bundles[cordConfig.activeBundle].desc;
        $scope.users = res;
      })
      .catch(function(){
        $log.error('Problem with resource', SubscriberUsers);
      });

      $log.debug('Cord Home Ctrl has been created.');
    });
}());


text:
package com.sequenceiq.ambari.shell.model;

public enum FocusType {

  HOST("HOST"),
  CLUSTER_BUILD("CLUSTER_BUILD"),
  ROOT("CLUSTER");

  private final String prefix;

  private FocusType(String prefix) {
    this.prefix = prefix;
  }

  public String prefix() {
    return prefix;
  }
}


text:
namespace BootstrapMvc
{
    using System;

    public enum ButtonType
    {
#if BOOTSTRAP3
        DefaultGray,
#endif
#if BOOTSTRAP4
        SecondaryWhite,

        [Obsolete("Use SecondaryWhite instead")]
        DefaultGray = SecondaryWhite,
#endif
        PrimaryBlue,
        InfoCyan,
        SuccessGreen,
        WarningOrange,
        DangerRed,
        Link,
    }
}


text:
package org.mJeliot.server.gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import org.mJeliot.model.Lecture;
import org.mJeliot.server.ServerController;

public class EditLectureInterface extends JFrame {
	private static final long serialVersionUID = 2607181184149678794L;
	private Lecture lecture = null;
	private JTextField lectureNameTextField = new JTextField(30);
	private JTextField lectureAdminPasswordTextField = new JTextField(30);
	private JTextField lectureClientPasswordTextField = new JTextField(30);
	private JButton cancelButton = new JButton("Cancel");
	private JButton okButton = new JButton("Ok");

	public EditLectureInterface(final ServerController controller) {
		super("Edit lecture");
		GridLayout layout = new GridLayout(4, 2);
		this.setLayout(layout);

		this.add(new JLabel("Lecture Name:"));
		this.add(this.lectureNameTextField);

		this.add(new JLabel("Admin Password:"));
		this.add(this.lectureAdminPasswordTextField);

		this.add(new JLabel("Client Password:"));
		this.add(this.lectureClientPasswordTextField);

		this.cancelButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
			}
		});
		this.add(cancelButton);

		this.okButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (lecture == null) {
					lecture = controller.addLecture(lectureNameTextField.getText());
				}
				lecture.setName(lectureNameTextField.getText());
				lecture.setAdminPassword(lectureAdminPasswordTextField.getText());
				lecture.setClientPassword(lectureClientPasswordTextField.getText());
				setVisible(false);
			}
		});
		this.add(okButton);

		this.pack();
	}
	public void addNewLecture() {
		this.lecture = null;
		this.lectureNameTextField.setText("");
		this.lectureAdminPasswordTextField.setText("");
		this.lectureClientPasswordTextField.setText("");
		this.setVisible(true);
	}
}


text:
module StWidgets

end


text:
- [ ] Redraw Hamming(7,4,3) venn digram
- [ ] dimension notation on generator matrix and parity-check matrix
- [ ] introduce parity-check matrix from the perspective of "kernel" of mappings from (n) to (n-k)
- [ ] GH = 0 (meaning)


text:
using System;

namespace YuKu.MathExpression.Tests
{
    internal static class TypeExtensions
    {
        public static Object GetDefaultValue(this Type type)
        {
            if (type.IsValueType && Nullable.GetUnderlyingType(type) == null)
            {
                return Activator.CreateInstance(type);
            }
            return null;
        }
    }
}


text:
package ic2.api.energy.event;

import ic2.api.energy.tile.IEnergyTile;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.event.world.WorldEvent;

public class EnergyTileEvent extends WorldEvent
{
	public final IEnergyTile energyTile;

	public EnergyTileEvent(IEnergyTile energyTile)
	{
		super(((TileEntity) energyTile).worldObj);

		this.energyTile = energyTile;
	}
}


text:
(function(global) {

  "use strict";

  /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */

  var fabric = global.fabric || (global.fabric = { });

  if (fabric.Point) {
    fabric.warn('fabric.Point is already defined');
    return;
  }

  fabric.Point = Point;

  /**
   * Point class
   * @name Point
   * @memberOf fabric
   * @constructor
   * @param {Number} x
   * @param {Number} y
   * @return {fabric.Point} thisArg
   */
  function Point(x, y) {
    if (arguments.length > 0) {
      this.init(x, y);
    }
  }

  Point.prototype = /** @scope fabric.Point.prototype */ {

    constructor: Point,

    /**
     * Constructor
     * @method init
     * @param {Number} x left offset
     * @param {Number} y top offset
     */
    init: function (x, y) {
      this.x = x;
      this.y = y;
    },

    /**
     * Adds another point to this one and returns another one
     * @method add
     * @param {fabric.Point} that
     * @return {fabric.Point} new Point instance with added values
     */
    add: function (that) {
      return new Point(this.x + that.x, this.y + that.y);
    },

    /**
     * Adds another point to this one
     * @method addEquals
     * @param {fabric.Point} that
     * @return {fabric.Point} thisArg
     */
    addEquals: function (that) {
      this.x += that.x;
      this.y += that.y;
      return this;
    },

    /**
     * Adds value to this point and returns a new one
     * @method scalarAdd
     * @param {Number} scalar
     * @return {fabric.Point} new Point with added value
     */
    scalarAdd: function (scalar) {
      return new Point(this.x + scalar, this.y + scalar);
    },

    /**
     * Adds value to this point
     * @method scalarAddEquals
     * @param {Number} scalar
     * @param {fabric.Point} thisArg
     */
    scalarAddEquals: function (scalar) {
      this.x += scalar;
      this.y += scalar;
      return this;
    },

    /**
     * Subtracts another point from this point and returns a new one
     * @method subtract
     * @param {fabric.Point} that
     * @return {fabric.Point} new Point object with subtracted values
     */
    subtract: function (that) {
      return new Point(this.x - that.x, this.y - that.y);
    },

    /**
     * Subtracts another point from this point
     * @method subtractEquals
     * @param {fabric.Point} that
     * @return {fabric.Point} thisArg
     */
    subtractEquals: function (that) {
      this.x -= that.x;
      this.y -= that.y;
      return this;
    },

    /**
     * Subtracts value from this point and returns a new one
     * @method scalarSubtract
     * @param {Number} scalar
     * @return {fabric.Point}
     */
    scalarSubtract: function (scalar) {
      return new Point(this.x - scalar, this.y - scalar);
    },

    /**
     * Subtracts value from this point
     * @method scalarSubtractEquals
     * @param {Number} scalar
     * @return {fabric.Point} thisArg
     */
    scalarSubtractEquals: function (scalar) {
      this.x -= scalar;
      this.y -= scalar;
      return this;
    },

    /**
     * Miltiplies this point by a value and returns a new one
     * @method multiply
     * @param {Number} scalar
     * @return {fabric.Point}
     */
    multiply: function (scalar) {
      return new Point(this.x * scalar, this.y * scalar);
    },

    /**
     * Miltiplies this point by a value
     * @method multiplyEquals
     * @param {Number} scalar
     * @return {fabric.Point} thisArg
     */
    multiplyEquals: function (scalar) {
      this.x *= scalar;
      this.y *= scalar;
      return this;
    },

    /**
     * Divides this point by a value and returns a new one
     * @method divide
     * @param {Number} scalar
     * @return {fabric.Point}
     */
    divide: function (scalar) {
      return new Point(this.x / scalar, this.y / scalar);
    },

    /**
     * Divides this point by a value
     * @method divideEquals
     * @param {Number} scalar
     * @return {fabric.Point} thisArg
     */
    divideEquals: function (scalar) {
      this.x /= scalar;
      this.y /= scalar;
      return this;
    },

    /**
     * Returns true if this point is equal to another one
     * @method eq
     * @param {fabric.Point} that
     * @return {Boolean}
     */
    eq: function (that) {
      return (this.x === that.x && this.y === that.y);
    },

    /**
     * Returns true if this point is less than another one
     * @method lt
     * @param {fabric.Point} that
     * @return {Boolean}
     */
    lt: function (that) {
      return (this.x < that.x && this.y < that.y);
    },

    /**
     * Returns true if this point is less than or equal to another one
     * @method lte
     * @param {fabric.Point} that
     * @return {Boolean}
     */
    lte: function (that) {
      return (this.x <= that.x && this.y <= that.y);
    },

    /**

     * Returns true if this point is greater another one
     * @method gt
     * @param {fabric.Point} that
     * @return {Boolean}
     */
    gt: function (that) {
      return (this.x > that.x && this.y > that.y);
    },

    /**
     * Returns true if this point is greater than or equal to another one
     * @method gte
     * @param {fabric.Point} that
     * @return {Boolean}
     */
    gte: function (that) {
      return (this.x >= that.x && this.y >= that.y);
    },

    /**
     * Returns new point which is the result of linear interpolation with this one and another one
     * @method lerp
     * @param {fabric.Point} that
     * @param {Number} t
     * @return {fabric.Point}
     */
    lerp: function (that, t) {
      return new Point(this.x + (that.x - this.x) * t, this.y + (that.y - this.y) * t);
    },

    /**
     * Returns distance from this point and another one
     * @method distanceFrom
     * @param {fabric.Point} that
     * @return {Number}
     */
    distanceFrom: function (that) {
      var dx = this.x - that.x,
          dy = this.y - that.y;
      return Math.sqrt(dx * dx + dy * dy);
    },

    /**
     * Returns the point between this point and another one
     * @method midPointFrom
     * @param {fabric.Point} that
     * @return {fabric.Point}
     */
    midPointFrom: function (that) {
      return new Point(this.x + (that.x - this.x)/2, this.y + (that.y - this.y)/2);
    },

    /**
     * Returns a new point which is the min of this and another one
     * @method min
     * @param {fabric.Point} that
     * @return {fabric.Point}
     */
    min: function (that) {
      return new Point(Math.min(this.x, that.x), Math.min(this.y, that.y));
    },

    /**
     * Returns a new point which is the max of this and another one
     * @method max
     * @param {fabric.Point} that
     * @return {fabric.Point}
     */
    max: function (that) {
      return new Point(Math.max(this.x, that.x), Math.max(this.y, that.y));
    },

    /**
     * Returns string representation of this point
     * @method toString
     * @return {String}
     */
    toString: function () {
      return this.x + "," + this.y;
    },

    /**
     * Sets x/y of this point
     * @method setXY
     * @param {Number} x
     * @return {Number} y
     */
    setXY: function (x, y) {
      this.x = x;
      this.y = y;
    },

    /**
     * Sets x/y of this point from another point
     * @method setFromPoint
     * @param {fabric.Point} that
     */
    setFromPoint: function (that) {
      this.x = that.x;
      this.y = that.y;
    },

    /**
     * Swaps x/y of this point and another point
     * @method setFromPoint
     * @param {fabric.Point} that
     */
    swap: function (that) {
      var x = this.x,
          y = this.y;
      this.x = that.x;
      this.y = that.y;
      that.x = x;
      that.y = y;
    }
  };

})(typeof exports !== 'undefined' ? exports : this);


text:
	if(_id != _glState->renderbuffer) \
	{ \
		glBindRenderbuffer(_target, _id); \
		_glState->renderbuffer = _id; \
	}

namespace gls::internals
{

bool GLRenderbuffer::Create(GLState* gl_state, sizei samples, PixelFormat internal_format, sizei width, sizei height)
{
	if (_id)
		return false;

	_glState = gl_state;

	glGenRenderbuffers(1, &_id);
	if (!_id)
		return false;

	glBindRenderbuffer(GL_RENDERBUFFER, _id);
	_glState->renderbuffer = _id;
	_resType = ResourceType::Renderbuffer;
	_target = GL_RENDERBUFFER;

	glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GetGLEnum(internal_format), width, height);

	return true;
}

void GLRenderbuffer::Destroy()
{
	if (_id)
	{
		if (_id == _glState->renderbuffer)
		{
			glBindRenderbuffer(GL_RENDERBUFFER, 0);
			_glState->renderbuffer = 0;
		}
		glDeleteRenderbuffers(1, &_id);
		_id = 0;
	}
}

// =================== Framebuffer ==================

#undef STATE_MACHINE_HACK
#define STATE_MACHINE_HACK \
if(_id != _glState->drawFbuf) \
{ \
	glBindFramebuffer(_target, _id); \
	_glState->drawFbuf = _id; \
}

bool GLFramebuffer::Create(GLState* gl_state)
{
	if (_id)
		return false;

	_glState = gl_state;

	glGenFramebuffers(1, &_id);
	if (!_id)
		return false;

	_target = GL_DRAW_FRAMEBUFFER;
	_resType = ResourceType::Framebuffer;

	glBindFramebuffer(_target, _id);
	_glState->drawFbuf = _id;

	return true;
}

bool GLFramebuffer::CreateWithoutAttachments(GLState* gl_state, const FramebufferParams& params)
{
	if (Create(gl_state))
	{
		glFramebufferParameteri(_target, GL_FRAMEBUFFER_DEFAULT_WIDTH, params.width);
		glFramebufferParameteri(_target, GL_FRAMEBUFFER_DEFAULT_HEIGHT, params.height);
		glFramebufferParameteri(_target, GL_FRAMEBUFFER_DEFAULT_LAYERS, params.layers);
		glFramebufferParameteri(_target, GL_FRAMEBUFFER_DEFAULT_SAMPLES, params.samples);
		glFramebufferParameteri(_target, GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS, params.fixedSampleLocations);

		return true;
	}

	return false;
}

void GLFramebuffer::Destroy()
{
	if (_id)
	{
		if (_id == _glState->drawFbuf)
		{
			glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
			_glState->drawFbuf = 0;
		}

		if (_id == _glState->readFbuf)
		{
			glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
			_glState->readFbuf = 0;
		}

		glDeleteFramebuffers(1, &_id);
		_id = 0;
	}
}

void GLFramebuffer::AttachTexture(AttachmentBuffer attachment, ITexture* texture, int level)
{
	assert(_id);
	STATE_MACHINE_HACK

		glFramebufferTexture(_target, GetGLEnum(attachment), dyn_cast_ptr<GLTexture*>(texture)->GetID(), level);
}

void GLFramebuffer::AttachTextureLayer(AttachmentBuffer attachment, ITexture* texture, int level, int layer)
{
	assert(_id);
	STATE_MACHINE_HACK

		glFramebufferTextureLayer(_target, GetGLEnum(attachment), dyn_cast_ptr<GLTexture*>(texture)->GetID(), level, layer);
}

void GLFramebuffer::AttachTextureFace(AttachmentBuffer attachment, ITexture* texture, int level, CubeFace face)
{
	assert(_id);
	STATE_MACHINE_HACK

		glFramebufferTexture2D(_target, GetGLEnum(attachment), GetGLEnum(face), dyn_cast_ptr<GLTexture*>(texture)->GetID(), level);
}

void GLFramebuffer::AttachRenderbuffer(AttachmentBuffer attachment, IRenderbuffer* renderbuffer)
{
	assert(_id);
	STATE_MACHINE_HACK

		glFramebufferRenderbuffer(_target, GetGLEnum(attachment), GL_RENDERBUFFER, dyn_cast_ptr<GLRenderbuffer*>(renderbuffer)->GetID());
}

FramebufferStatus GLFramebuffer::CheckStatus()
{
	assert(_id);
	STATE_MACHINE_HACK

		GLenum status = glCheckFramebufferStatus(_target);

	return GetFromGLEnum<FramebufferStatus>(status);
}

void GLFramebuffer::InvalidateFramebuffer(int num_attachments, const AttachmentBuffer* attachments)
{
	assert(_id);
	STATE_MACHINE_HACK

		if (num_attachments < 1 || num_attachments > 16)
		{
			assert(false);
			return;
		}

	GLenum* attach_enums = (GLenum*)alloca(sizeof(GLenum) * num_attachments);
	for (int i = 0; i < num_attachments; ++i)
		attach_enums[i] = GetGLEnum(attachments[i]);

	glInvalidateFramebuffer(_target, num_attachments, attach_enums);
}

void GLFramebuffer::InvalidateSubFramebuffer(int num_attachments, const AttachmentBuffer* attachments, int x, int y, int width, int height)
{
	assert(_id);
	STATE_MACHINE_HACK

		if (num_attachments < 1 || num_attachments > 16)
		{
			assert(false);
			return;
		}

	GLenum* attach_enums = (GLenum*)alloca(sizeof(GLenum) * num_attachments);
	for (int i = 0; i < num_attachments; ++i)
		attach_enums[i] = GetGLEnum(attachments[i]);

	glInvalidateSubFramebuffer(_target, num_attachments, attach_enums, x, y, width, height);
}

} // namespace gls::internals


text:
package org.apache.camel.component.xmpp;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;

public class XmppRouteChatTest extends XmppBaseTest {

    protected MockEndpoint consumerEndpoint;
    protected MockEndpoint producerEndpoint;
    protected String body1 = "the first message";
    protected String body2 = "the second message";

    @Test
    public void testXmppChat() throws Exception {
        consumerEndpoint = context.getEndpoint("mock:out1", MockEndpoint.class);
        producerEndpoint = context.getEndpoint("mock:out2", MockEndpoint.class);

        consumerEndpoint.expectedBodiesReceived(body1, body2);
        producerEndpoint.expectedBodiesReceived(body1, body2);

        //will send chat messages to the consumer
        template.sendBody("direct:toConsumer", body1);
        Thread.sleep(50);
        template.sendBody("direct:toConsumer", body2);

        template.sendBody("direct:toProducer", body1);
        Thread.sleep(50);
        template.sendBody("direct:toProducer", body2);
        //    Th
        consumerEndpoint.assertIsSatisfied();
        producerEndpoint.assertIsSatisfied();

    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {

                from("direct:toConsumer")
                        .to(getConsumerUri());

                from("direct:toProducer")
                        .to(getProducerUri());

                from(getConsumerUri())
                        .to("mock:out1");

                from(getProducerUri())
                        .to("mock:out2");
            }
        };
    }

    protected String getProducerUri() {
        return "xmpp://" + getUrl()
               + "/camel_producer@apache.camel?connectionConfig=#customConnectionConfig&room=camel-test-producer@conference.apache.camel&user=camel_producer&password=secret&serviceName=apache.camel";
    }

    protected String getConsumerUri() {
        return "xmpp://" + getUrl()
               + "/camel_consumer@apache.camel?connectionConfig=#customConnectionConfig&room=camel-test-consumer@conference.apache.camel&user=camel_consumer&password=secret&serviceName=apache.camel";
    }

}


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

<title>simpleCsvLogger</title>
<meta name="date" content="2017-07-08">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.usfirst.frc.team1736.lib.Logging

Class simpleCsvLogger

java.lang.Object

org.usfirst.frc.team1736.lib.Logging.simpleCsvLogger

public class simpleCsvLogger
extends java.lang.Object

DESCRIPTION:

 Provides an API for FRC 1736 Robot Casserole datalogging on the robot during testing or matches.
 Will write lines into a CSV file with a unique name between calls to init() and close().
 output_dir is hardcoded to point to a specific 2016 folder on a flash drive connected to the
 roboRIO.

 USAGE:

Instantiate Class

Create global variables containing arrays of strings to represent the column (data vector)
 names and units

During teleop init or autonomous init, call the init() function to start logging data to a
 new file.

Once per loop, call the writeData() method with the full list of values to write to file (all
 must be converted to doubles).

During DisabledInit, call the close() method to close out any file which was being written to
 while the robot was doing something.

Post-match or -practice, extract the data logs from the USB drive(maybe using FTP?) and view
 with excel or your favourite software.

Constructor Summary

Constructors

Constructor and Description

simpleCsvLogger()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

int
close()

Closes the log file and ensures everything is written to disk.

int
forceSync()

Clears the buffer in memory and forces things to file.

int
init(java.lang.String[] data_fields,
    java.lang.String[] units_fields)

Determines a unique file name, and opens a file in the data captures directory and writes the
 initial lines to it.

int
writeData(double... data_elements)

Write a list of doubles to the output file, assuming it's open.

Methods inherited from class java.lang.Object

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

Constructor Detail

simpleCsvLogger

public simpleCsvLogger()

Method Detail

init

public int init(java.lang.String[] data_fields,
                java.lang.String[] units_fields)

Determines a unique file name, and opens a file in the data captures directory and writes the
 initial lines to it.

Parameters:

data_fields - A set of strings for signal names to write into the file

units_fields - A set of strings for signal units to write into the file

Returns:

0 on successful log open, -1 on failure

writeData

public int writeData(double... data_elements)

Write a list of doubles to the output file, assuming it's open. Creates a new line in the
 .csv log file.

Parameters:

data_elements - Values to write (any number of doubles, each as its own argument).
        Should have the same number of arguments here as signal names/units set during the
        call to init()

Returns:

0 on write success, -1 on failure.

forceSync

public int forceSync()

Clears the buffer in memory and forces things to file. Generally a good idea to use this as
 infrequently as possible (because it increases logging overhead), but definitely use it
 before the roboRIO might crash without a proper call to the close() method (during brownout,
 maybe?)

Returns:

Returns 0 on flush success or -1 on failure.

close

public int close()

Closes the log file and ensures everything is written to disk. init() must be called again in
 order to write to a new file.

Returns:

-1 on failure to close, 0 on success

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
EventTeamUpdateDo

        Got [ {{deleted_event_teams_keys|length}} ] EventTeams deleted!

        Got [ {{event_teams|length}} ] EventTeams written!

EventTeams deleted:

        {% for deleted_event_team_key in deleted_event_teams_keys %}

{{deleted_event_team_key.id}}

        {% endfor %}

EventTeams written:

        {% for event_team in event_teams %}

{{event_team.key.id}}

        {% endfor %}


text:
package me.zhouzhuo810.zzapidoc.version.entity;

import me.zhouzhuo810.zzapidoc.common.entity.BaseEntity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

/**
 * Created by zz on 2017/10/26.
 */
@Entity
@Table(name = "version_project")
public class VersionProjectEntity extends BaseEntity {

    public static final String PROPERTY_PRIVATE = "1";
    public static final String PROPERTY_PUBLIC = "0";

    @Column(name = "Name")
    private String name;
    @Column(name = "Note")
    private String note;
    @Column(name = "Property", length = 50)
    private String property = "0";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Milesia carpatica var. erythrosora Faull

### Remarks
null


text:
/*
 * This an unstable interface of wlroots. No guarantees are made regarding the
 * future consistency of this API.
 */
#ifndef WLR_USE_UNSTABLE
#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features"
#endif

#ifndef WLR_TYPES_WLR_DRM_LEASE_V1_H
#define WLR_TYPES_WLR_DRM_LEASE_V1_H

#include <wayland-server-core.h>

struct wlr_backend;
struct wlr_output;

struct wlr_drm_lease_v1_manager {
	struct wl_list devices; // wlr_drm_lease_device_v1::link;

	struct wl_display *display;
	struct wl_listener display_destroy;

	struct {
		/**
		 * Upon receiving this signal, call
		 * wlr_drm_lease_device_v1_grant_lease_request to grant a lease of the
		 * requested DRM resources, or
		 * wlr_drm_lease_device_v1_reject_lease_request to reject the request.
		 */
		struct wl_signal request;
	} events;
};

struct wlr_drm_lease_device_v1 {
	struct wl_list resources;
	struct wl_global *global;

	struct wlr_drm_lease_v1_manager *manager;
	struct wlr_backend *backend;

	struct wl_list connectors; // wlr_drm_lease_connector_v1::link
	struct wl_list leases; // wlr_drm_lease_v1::link
	struct wl_list requests; // wlr_drm_lease_request_v1::link
	struct wl_list link; // wlr_drm_lease_v1_manager::devices

	struct wl_listener backend_destroy;

	void *data;
};

struct wlr_drm_lease_v1;

struct wlr_drm_lease_connector_v1 {
	struct wl_list resources; // wl_resource_get_link

	struct wlr_output *output;
	struct wlr_drm_lease_device_v1 *device;
	/** NULL if no client is currently leasing this connector */
	struct wlr_drm_lease_v1 *active_lease;

	struct wl_listener destroy;

	struct wl_list link; // wlr_drm_lease_device_v1::connectors
};

struct wlr_drm_lease_request_v1 {
	struct wl_resource *resource;

	struct wlr_drm_lease_device_v1 *device;

	struct wlr_drm_lease_connector_v1 **connectors;
	size_t n_connectors;

	/** NULL until the lease is submitted */
	struct wlr_drm_lease_v1 *lease;

	bool invalid;

	struct wl_list link; // wlr_drm_lease_device_v1::requests
};

struct wlr_drm_lease_v1 {
	struct wl_resource *resource;

	struct wlr_drm_lease_device_v1 *device;

	struct wlr_drm_lease_connector_v1 **connectors;
	size_t n_connectors;

	uint32_t lessee_id;

	struct wl_list link; // wlr_drm_lease_device_v1::leases

	void *data;
};

/**
 * Creates a DRM lease manager. A DRM lease device will be created for each
 * DRM backend supplied in case of a wlr_multi_backend.
 * Returns NULL if no DRM backend is supplied.
 */
struct wlr_drm_lease_v1_manager *wlr_drm_lease_v1_manager_create(
	struct wl_display *display, struct wlr_backend *backend);

/**
 * Offers a wlr_output for lease.
 * Returns false if the output can't be offered to lease.
 */
bool wlr_drm_lease_v1_manager_offer_output(
	struct wlr_drm_lease_v1_manager *manager, struct wlr_output *output);

/**
 * Withdraws a previously offered output for lease. If the output is leased to
 * a client, a finished event will be send and the lease will be terminated.
 */
void wlr_drm_lease_v1_manager_withdraw_output(
	struct wlr_drm_lease_v1_manager *manager, struct wlr_output *output);

/**
 * Grants a client's lease request. The lease device will then provision the
 * DRM lease and transfer the file descriptor to the client. After calling this,
 * each wlr_output leased is destroyed, and will be re-issued through
 * wlr_backend.events.new_outputs when the lease is revoked.
 *
 * This will return NULL without leasing any resources if the lease is invalid;
 * this can happen for example if two clients request the same resources and an
 * attempt to grant both leases is made.
 */
struct wlr_drm_lease_v1 *wlr_drm_lease_request_v1_grant(
	struct wlr_drm_lease_request_v1 *request);

/**
 * Rejects a client's lease request. The output will still be available to
 * lease until withdrawn by the compositor.
 */
void wlr_drm_lease_request_v1_reject(struct wlr_drm_lease_request_v1 *request);

/**
 * Revokes a client's lease request. The output will still be available to
 * lease until withdrawn by the compositor.
 */
void wlr_drm_lease_v1_revoke(struct wlr_drm_lease_v1 *lease);

#endif


text:
#ifndef LD_BASE_ORIENTATION_HPP
#define LD_BASE_ORIENTATION_HPP
namespace Base {

/// Orthogonal orientations for 2D sprites.
enum class Orientation {
    // NOTE: don't change the order!
    NORMAL, ROTATE_90, ROTATE_180, ROTATE_270,
    FLIP_VERTICAL, TRANSPOSE_2, FLIP_HORIZONTAL, TRANSPOSE
};

/// Compose two orientations.
Orientation operator*(Orientation x, Orientation y);

}
#endif


text:
__BEGIN_DECLS
void expectFailureWithMessage(NSString *message, CDRSpecBlock block);
__END_DECLS


text:
// Copyright (c) 2013, Andre Caron (andre.l.caron@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <w32.hpp>
#include <w32.mt.hpp>
#include <w32.net.hpp>

#include <iostream>
#include <vector>

namespace echo {

    class Settings
    {
        w32::mt::Mutex myMutex;
    public:
        w32::net::ipv4::Address peer_host () const {
            return (w32::net::ipv4::Address::local());
        }

        w32::uint16 peer_port () const {
            return (9000);
        }

        w32::net::ipv4::EndPoint peer () const {
            return (w32::net::ipv4::EndPoint(peer_host(), peer_port()));
        }

        int threads () const {
            return (100);
        }

        int iterations () const {
            return (10);
        }

        w32::mt::Mutex& console_lock () {
            return (myMutex);
        }

        bool force_reset () const {
            return (true);
        }
    };

    w32::dword client_thread (Settings& settings)
    try
    {
        char data[16*1024];
        char copy[16*1024];
        const w32::dword size = sizeof(data);

        bool error = false;

        // Repeatedly bash on the server!
        for (int i=0; !error && (i < settings.iterations()); ++i)
        {
            // Connect to the server.
            w32::net::tcp::Stream stream(settings.peer());

            // Put the entire payload.
            w32::dword used = 0;
            int pass = 0;
            do {
                used += stream.put(data+used, size-used);
            }
            while ((pass > 0) && ((used+=pass) < size));
            if (used < size) {
                w32::mt::Mutex::Lock _(settings.console_lock());
                std::cout
                    << "could not send everything."
                    << std::endl;
                error = true; continue;
            }

            // Get the entire payload.
            pass = 0; used = 0;
            do {
                pass = stream.get(copy+used, size-used);
            }
            while ((pass > 0) && ((used+=pass) < size));
            if (used < size) {
                w32::mt::Mutex::Lock _(settings.console_lock());
                std::cout
                    << "could not read everything."
                    << std::endl;
                error = true; continue;
            }

            // Make sure we got an exact copy.
            if (!error && (std::memcmp(data, copy, size) != 0))
            {
                w32::mt::Mutex::Lock _(settings.console_lock());
                std::cout
                    << "received incoherent data."
                    << std::endl;
                error = true; continue;
            }

            // It's sometimes useful to force sending an RST packet (abortive
            // close).  For example, when load testing an echo server on the
            // loopback interface, client-side sockets stuck in the TIME_WAIT
            // state will limit the load we can generate (the client program
            // won't be able to connect to the server for several minutes).
            if (settings.force_reset()) {
                stream.linger(0);
            }
            else {
                stream.shutdown(w32::net::Socket::Shutdown::output());
            }
        }

        // If thread exits, any I/O operations (including pending writes who'se
        // payloads are lingering in the sockets' output buffer after the
        // sockets have been "closed") will be cancelled.  Prevent loss of data
        // by allowing all the I/O to complete.
        w32::mt::sleep(w32::Timespan(5*1000));

        // Let the main thread know an error occurred.
        return (error? EXIT_FAILURE : EXIT_SUCCESS);
    }
    catch (const w32::Error& error)
    {
        w32::mt::Mutex::Lock _(settings.console_lock());
        std::cerr
            << "Uncaught Win32 error: " << error << "."
            << std::endl;
        return (EXIT_FAILURE);
    }
    catch (const std::exception& error)
    {
        w32::mt::Mutex::Lock _(settings.console_lock());
        std::cerr
            << "Uncaught exception: " << error.what() << "."
            << std::endl;
        return (EXIT_FAILURE);
    }
    catch (...)
    {
        w32::mt::Mutex::Lock _(settings.console_lock());
        std::cerr
            << "Uncaught exception of unknown type."
            << std::endl;
        return (EXIT_FAILURE);
    }

    w32::dword client_thread (void * context)
    {
        return (client_thread(*static_cast<Settings*>(context)));
    }

    /*!
     * @brief Echo client demo program.
     */
    int client_main (int argc, wchar_t ** argv)
    {
        Settings settings;

        // Launch threads that will pound on the server.
        std::vector<w32::mt::Thread> threads;
        threads.reserve(settings.threads());
        w32::Waitable::Set waitset;
        for (int i = 0; (i < settings.threads()); ++i) {
            threads.push_back(w32::mt::Thread(
                w32::mt::Thread::function<client_thread>(), &settings));

            // Make sure we can monitor completion.
            waitset |= threads[i];
        }

        // Wait for all threads to complete.
        while (!waitset.empty())
        {
            std::cerr
                << "waiting for any thread to complete."
                << std::endl;

            // Block until at least one thread completes.
            const w32::dword i = w32::Waitable::any(waitset);

            { w32::mt::Mutex::Lock _(settings.console_lock());
                std::cerr
                    << "thread #" << i << " has joined."
                    << std::endl;
            }

            // Check for failure in the thread.
            w32::mt::Thread thread(w32::mt::Thread::proxy(waitset[i]));
            const w32::dword status = thread.status();
            if (status != EXIT_SUCCESS) {
                w32::mt::Mutex::Lock _(settings.console_lock());
                std::cerr
                    << "  (exited abnormally, status=" << status << ")"
                    << std::endl;
            }

            std::cerr
                << "removing thread #" << i << "."
                << std::endl;

            // Stop monitoring the thread.
            waitset.remove(i);
        }

        { w32::mt::Mutex::Lock _(settings.console_lock());
            std::cerr
                << "done!"
                << std::endl;
        }

        return (EXIT_SUCCESS);
    }

}

#include <w32/app/console-program.hpp>

namespace {

    int run (int argc, wchar_t ** argv)
    {
        const w32::net::Context _;
        return (echo::client_main(argc, argv));
    }

}

#include <w32/app/console-program.cpp>


text:
package com.github.thomasridd.flatsy;

import com.github.thomasridd.flatsy.operations.operators.OperatorCommandLineParser;
import com.github.thomasridd.flatsy.query.FlatsyCursor;
import com.github.thomasridd.flatsy.query.matchers.MatcherCommandLineParser;
import com.github.thomasridd.flatsy.util.FlatsyUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * See
 */
public class FlatsyCommandLine {
    FlatsyDatabase db;
    List<String> queryCommands = new ArrayList<>();

    public OutputStream defaultOut = System.out; // Convenience for tests

    /**
     * Create a new FlatsyCommandLine
     */
    public FlatsyCommandLine() {};

    /**
     * Create a new FlatsyCommandLine and run a command
     * @param command the command
     */
    public FlatsyCommandLine(String command) {
        runCommand(command);
    }

    /**
     * Create a new FlatsyCommandLine and run a list of commands
     * @param commands a list of commands
     */
    public FlatsyCommandLine(List<String> commands) {
        runScript(commands);
    }

    /**
     * Create a new FlatsyCommandLine and run a script of commands
     * @param script a path to a script
     * @throws IOException if script cannot be opened
     */
    public FlatsyCommandLine(Path script) throws IOException {
        runScript(script);
    }

    /**
     * Create a new FlatsyCommandLine and run a script of commands
     * @param stream a stream for script commands
     */
    public FlatsyCommandLine(InputStream stream) {
        runScript(stream);
    }

    /**
     * Build a command using flatsy command line syntax
     *
     * @param command a Flatsy command
     * @return true if complete
     */
    public boolean runCommand(String command) {
        // skip out on blank lines
        if (command.trim().length() == 0) return true;

        // get the list of arguments
        List<String> args = FlatsyUtil.commandArguments(command);

        String action = args.get(0).trim();
        if (action.equalsIgnoreCase("from") || action.equalsIgnoreCase("select")) {

            // set the database root
            db = new FlatsyFlatFileDatabase(FlatsyUtil.pathsGet(args.get(1).trim()));
            queryCommands = new ArrayList<>();
            return true;
        } else if (action.equalsIgnoreCase("filter") || action.equalsIgnoreCase("where") || action.equalsIgnoreCase("and")) {

            // add to the query
            queryCommands.add(command);
            return true;
        } else if (action.equalsIgnoreCase("clear")) {

            // clear query commands
            queryCommands = new ArrayList<>();
            return true;
        } else if (action.equalsIgnoreCase("with")) {

            // Apply an operator to a single uri
            if (args.size() >= 3) {
                // get the uri
                String uri = args.get(1).trim();
                // parse the operator
                args = args.subList(2, args.size());
                FlatsyObject object = db.get(uri);

                OperatorCommandLineParser.applyFromCommand(object, args, defaultOut);
                return true;
            }
            return true;

        } else if (action.equalsIgnoreCase("print")) {
            System.out.println("");
            System.out.println("FROM " + db.toString());
            for (String query: queryCommands) {
                System.out.println(query);
            }
            return true;

        } else if (action.equalsIgnoreCase("delete") && args.size() > 1) {
            FlatsyObject object = db.get(args.get(1).trim());
            if (object.getType() != FlatsyObjectType.Null) {
                db.delete(object);
            }
            return true;
        } else {
            long start = System.currentTimeMillis();

            // run a command
            boolean result = applyOperation(command);

            long total = System.currentTimeMillis() - start;

            System.out.println(command + " >> Applied in " +  total + " milliseconds");

            return result;
        }
    }

    /**
     * Run a sequence of script commands
     *
     * @param commands a list of Flatsy query language commands
     * @return success
     */
    public boolean runScript(List<String> commands) {
        boolean result = true;
        for (String command: commands) {
            result = result && runCommand(command);
        }
        return result;
    }

    /**
     * Run a sequence of script commands from file
     *
     * @param path the file to run
     * @return success
     * @throws IOException if script cannot be read
     */
    public boolean runScript(Path path) throws IOException {
        boolean result = true;
        try(Scanner scanner = new Scanner(Files.newInputStream(path))) {
            while (scanner.hasNextLine()) {
                result = result && runCommand(scanner.nextLine());
            }
        }
        return result;
    }

    /**
     * Run a sequence of script commands from stream
     *
     * @param stream the input stream
     * @return success
     */
    public boolean runScript(InputStream stream) {
        boolean result = true;
        Scanner scanner = new Scanner(stream);
        while(scanner.hasNextLine()) {
            result = result && runCommand(scanner.nextLine());
        }
        return result;
    }

    /**
     * Create a cursor from a saved script
     *
     * @param scriptPath the path of the script
     * @return a flatsy cursor
     *
     * @throws IOException if the script cannot be read
     */
    public FlatsyCursor cursor(Path scriptPath) throws IOException {
        db = null;
        try(Scanner scanner = new Scanner(Files.newInputStream(scriptPath))) {
            while (scanner.hasNextLine()) {
                buildCursor(scanner.nextLine());
            }
        }
        return MatcherCommandLineParser.cursorFromFilterCommands(db, queryCommands);
    }

    /**
     * Create a cursor based on a command list
     *
     * @param commands an array of commands to run
     * @return a flatsy cursor
     */
    public FlatsyCursor cursor(List<String> commands) {
        for (String command: commands) {
            buildCursor(command);
        }
        return MatcherCommandLineParser.cursorFromFilterCommands(db, queryCommands);
    }

    /**
     * Create cursor based on currently saved query commands
     *
     * @return a flatsy cursor
     */
    public FlatsyCursor cursor() {
        return MatcherCommandLineParser.cursorFromFilterCommands(db, queryCommands);
    }

    /**
     * Add filters to the list of query commands ignoring any execute statements
     *
     * @param command a Flatsy command
     * @return true if complete
     */
    private boolean buildCursor(String command) {
        // skip out on blank lines
        if (command.trim().length() == 0) return true;

        // get the list of arguments
        List<String> args = FlatsyUtil.commandArguments(command);

        String action = args.get(0).trim();
        if (action.equalsIgnoreCase("select") || action.equalsIgnoreCase("from")) {

            // set the database root
            db = new FlatsyFlatFileDatabase(FlatsyUtil.pathsGet(args.get(1).trim()));
            queryCommands = new ArrayList<>();
            return true;
        } else if (action.equalsIgnoreCase("where") || action.equalsIgnoreCase("and") || action.equalsIgnoreCase("filter")) {

            // add to the query
            queryCommands.add(command);
            return true;
        } else if (action.equalsIgnoreCase("clear")) {
            queryCommands = new ArrayList<>();
            return true;
        }
        return false;
    }

    /**
     * Apply an operation to the cursor currently defined by queryCommands
     *
     * @param command an operation in Flatsy syntax
     * @return success
     */
    protected boolean applyOperation(String command) {
        // Simply chuck blank lines
        if (command.trim().equalsIgnoreCase("")) { return true;}

        // Generate the cursor for the file systems
        FlatsyCursor query = MatcherCommandLineParser.cursorFromFilterCommands(db, queryCommands);
        if (query == null) return false;

        // Generate the operator
        OperatorCommandLineParser.applyFromCommand(query, command, defaultOut);

        return true;
    }

    public static void main(String[] args) {
        FlatsyCommandLine cli = new FlatsyCommandLine();
        Scanner scanner = new Scanner(System.in);

        while(true) {
            System.out.print("flatsy >> ");
            String command = scanner.nextLine();
            cli.runCommand(command);
        }
    }
}


text:
if defined?(ActiveRecord::Base)
  Before('~@no-txn') do
    @__cucumber_use_txn = Cucumber::Rails::World.use_transactional_fixtures
    Cucumber::Rails::World.use_transactional_fixtures = true
  end

  Before('@no-txn') do
    @__cucumber_use_txn = Cucumber::Rails::World.use_transactional_fixtures
    Cucumber::Rails::World.use_transactional_fixtures = false
  end

  Before do
    if Cucumber::Rails::World.use_transactional_fixtures
      @__cucumber_ar_connection = ActiveRecord::Base.connection
      if @__cucumber_ar_connection.respond_to?(:increment_open_transactions)
        @__cucumber_ar_connection.increment_open_transactions
      else
        ActiveRecord::Base.__send__(:increment_open_transactions)
      end
      @__cucumber_ar_connection.begin_db_transaction
    end
    ActionMailer::Base.deliveries = [] if defined?(ActionMailer::Base)
  end

  After do
    if Cucumber::Rails::World.use_transactional_fixtures
      @__cucumber_ar_connection.rollback_db_transaction
      if @__cucumber_ar_connection.respond_to?(:decrement_open_transactions)
        @__cucumber_ar_connection.decrement_open_transactions
      else
        ActiveRecord::Base.__send__(:decrement_open_transactions)
      end
    end
    Cucumber::Rails::World.use_transactional_fixtures = @__cucumber_use_txn
  end
else
  module Cucumber::Rails
    def World.fixture_table_names; []; end # Workaround for projects that don't use ActiveRecord
  end
end


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Function get_check_failure</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Contract 1.0.0">
<link rel="up" href="../../reference.html#header.boost.contract.core.exception_hpp" title="Header <boost/contract/core/exception.hpp>">
<link rel="prev" href="set_check_failure.html" title="Function set_check_failure">
<link rel="next" href="check_failure.html" title="Function check_failure">

Home
Libraries
People
FAQ
More

Function get_check_failure

boost::contract::get_check_failure — Return failure handler currently set for implementation checks.

Synopsis

// In header: <boost/contract/core/exception.hpp>

failure_handler get_check_failure();

Description

This is often called only internally by this library.

Throws: This is declared noexcept (or throw() before C++11).

See Also:

  Throw on Failure,   Implementation Checks

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Returns:

A copy of the failure handler currently set.

Copyright © 2008-2019 Lorenzo Caminiti

        Distributed under the Boost Software License, Version 1.0 (see accompanying
        file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt)


text:
<?php

use danpai\string\Translation;

require __DIR__.'/vendor/autoload.php';

Translation::zhToEn("你好吗");


text:
/**
 * Created by apple on 2017/11/10.
 */
var log = function () {
    console.log.apply(console, arguments)
}

var e = function (selector) {
    return document.querySelector(selector)
}

var appendHtml = function (elem, html) {
    elem.insertAdjacentHTML('beforeend', html)
}

var bindEvent = function (elem, eventName, callback) {
    elem.addEventListener(eventName, callback)
}

var bindAllEvents = function (className, eventName, callback) {
    var elems = document.querySelectorAll(className)
    elems.forEach(function (e) {
        bindEvent(e, eventName, callback)
    })
}

var findElement = function (elem, selector) {
    return elem.querySelector(selector)
}

var toggleClass = function (elem, className) {
    if (elem.classList.contains(className)) {
        elem.classList.remove(className)
    } else {
        elem.classList.add(className)
    }
}

var removeClass = function (className) {
    var selector = "." + className
    log(selector)
    var elems = document.querySelectorAll(selector)
    log('all elems', elems)
    elems.forEach(function (e) {
        e.classList.remove(className)
    })
}


text:
"""
Tests for @cfunc and friends.
"""

import ctypes
import os
import subprocess
import sys
from collections import namedtuple

import numpy as np

from numba import cfunc, carray, farray, njit
from numba.core import types, typing, utils
import numba.core.typing.cffi_utils as cffi_support
from numba.tests.support import TestCase, tag, captured_stderr
from numba.tests.test_dispatcher import BaseCacheTest
import unittest
from numba.np import numpy_support

skip_cffi_unsupported = unittest.skipUnless(
    cffi_support.SUPPORTED,
    "CFFI not supported -- please install the cffi module",
)

def add_usecase(a, b):
    return a + b

def div_usecase(a, b):
    c = a / b
    return c

def square_usecase(a):
    return a ** 2

add_sig = "float64(float64, float64)"

div_sig = "float64(int64, int64)"

square_sig = "float64(float64)"

def objmode_usecase(a, b):
    object()
    return a + b

# Test functions for carray() and farray()

CARRAY_USECASE_OUT_LEN = 8

def make_cfarray_usecase(func):

    def cfarray_usecase(in_ptr, out_ptr, m, n):
        # Tuple shape
        in_ = func(in_ptr, (m, n))
        # Integer shape
        out = func(out_ptr, CARRAY_USECASE_OUT_LEN)
        out[0] = in_.ndim
        out[1:3] = in_.shape
        out[3:5] = in_.strides
        out[5] = in_.flags.c_contiguous
        out[6] = in_.flags.f_contiguous
        s = 0
        for i, j in np.ndindex(m, n):
            s += in_[i, j] * (i - j)
        out[7] = s

    return cfarray_usecase

carray_usecase = make_cfarray_usecase(carray)
farray_usecase = make_cfarray_usecase(farray)

def make_cfarray_dtype_usecase(func):
    # Same as make_cfarray_usecase(), but with explicit dtype.

    def cfarray_usecase(in_ptr, out_ptr, m, n):
        # Tuple shape
        in_ = func(in_ptr, (m, n), dtype=np.float32)
        # Integer shape
        out = func(out_ptr, CARRAY_USECASE_OUT_LEN, np.float32)
        out[0] = in_.ndim
        out[1:3] = in_.shape
        out[3:5] = in_.strides
        out[5] = in_.flags.c_contiguous
        out[6] = in_.flags.f_contiguous
        s = 0
        for i, j in np.ndindex(m, n):
            s += in_[i, j] * (i - j)
        out[7] = s

    return cfarray_usecase

carray_dtype_usecase = make_cfarray_dtype_usecase(carray)
farray_dtype_usecase = make_cfarray_dtype_usecase(farray)

carray_float32_usecase_sig = types.void(types.CPointer(types.float32),
                                        types.CPointer(types.float32),
                                        types.intp, types.intp)

carray_float64_usecase_sig = types.void(types.CPointer(types.float64),
                                        types.CPointer(types.float64),
                                        types.intp, types.intp)

carray_voidptr_usecase_sig = types.void(types.voidptr, types.voidptr,
                                        types.intp, types.intp)

class TestCFunc(TestCase):

    def test_basic(self):
        """
        Basic usage and properties of a cfunc.
        """
        f = cfunc(add_sig)(add_usecase)

        self.assertEqual(f.__name__, "add_usecase")
        self.assertEqual(f.__qualname__, "add_usecase")
        self.assertIs(f.__wrapped__, add_usecase)

        symbol = f.native_name
        self.assertIsInstance(symbol, str)
        self.assertIn("add_usecase", symbol)

        addr = f.address
        self.assertIsInstance(addr, utils.INT_TYPES)

        ct = f.ctypes
        self.assertEqual(ctypes.cast(ct, ctypes.c_void_p).value, addr)

        self.assertPreciseEqual(ct(2.0, 3.5), 5.5)

    @skip_cffi_unsupported
    def test_cffi(self):
        from numba.tests import cffi_usecases
        ffi, lib = cffi_usecases.load_inline_module()

        f = cfunc(square_sig)(square_usecase)

        res = lib._numba_test_funcptr(f.cffi)
        self.assertPreciseEqual(res, 2.25)  # 1.5 ** 2

    def test_locals(self):
        # By forcing the intermediate result into an integer, we
        # truncate the ultimate function result
        f = cfunc(div_sig, locals={'c': types.int64})(div_usecase)
        self.assertPreciseEqual(f.ctypes(8, 3), 2.0)

    def test_errors(self):
        f = cfunc(div_sig)(div_usecase)

        with captured_stderr() as err:
            self.assertPreciseEqual(f.ctypes(5, 2), 2.5)
        self.assertEqual(err.getvalue(), "")

        with captured_stderr() as err:
            res = f.ctypes(5, 0)
            # This is just a side effect of Numba zero-initializing
            # stack variables, and could change in the future.
            self.assertPreciseEqual(res, 0.0)
        err = err.getvalue()
        self.assertIn("ZeroDivisionError:", err)
        self.assertIn("Exception ignored", err)

    def test_llvm_ir(self):
        f = cfunc(add_sig)(add_usecase)
        ir = f.inspect_llvm()
        self.assertIn(f.native_name, ir)
        self.assertIn("fadd double", ir)

    def test_object_mode(self):
        """
        Object mode is currently unsupported.
        """
        with self.assertRaises(NotImplementedError):
            cfunc(add_sig, forceobj=True)(add_usecase)
        with self.assertTypingError() as raises:
            cfunc(add_sig)(objmode_usecase)
        self.assertIn("Untyped global name 'object'", str(raises.exception))

class TestCFuncCache(BaseCacheTest):

    here = os.path.dirname(__file__)
    usecases_file = os.path.join(here, "cfunc_cache_usecases.py")
    modname = "cfunc_caching_test_fodder"

    def run_in_separate_process(self):
        # Cached functions can be run from a distinct process.
        code = """if 1:
            import sys

            sys.path.insert(0, %(tempdir)r)
            mod = __import__(%(modname)r)
            mod.self_test()

            f = mod.add_usecase
            assert f.cache_hits == 1
            f = mod.outer
            assert f.cache_hits == 1
            f = mod.div_usecase
            assert f.cache_hits == 1
            """ % dict(tempdir=self.tempdir, modname=self.modname)

        popen = subprocess.Popen([sys.executable, "-c", code],
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = popen.communicate()
        if popen.returncode != 0:
            raise AssertionError("process failed with code %s: stderr follows\n%s\n"
                                 % (popen.returncode, err.decode()))

    def check_module(self, mod):
        mod.self_test()

    def test_caching(self):
        self.check_pycache(0)
        mod = self.import_module()
        self.check_pycache(6)  # 3 index, 3 data

        self.assertEqual(mod.add_usecase.cache_hits, 0)
        self.assertEqual(mod.outer.cache_hits, 0)
        self.assertEqual(mod.add_nocache_usecase.cache_hits, 0)
        self.assertEqual(mod.div_usecase.cache_hits, 0)
        self.check_module(mod)

        # Reload module to hit the cache
        mod = self.import_module()
        self.check_pycache(6)  # 3 index, 3 data

        self.assertEqual(mod.add_usecase.cache_hits, 1)
        self.assertEqual(mod.outer.cache_hits, 1)
        self.assertEqual(mod.add_nocache_usecase.cache_hits, 0)
        self.assertEqual(mod.div_usecase.cache_hits, 1)
        self.check_module(mod)

        self.run_in_separate_process()

class TestCArray(TestCase):
    """
    Tests for carray() and farray().
    """

    def run_carray_usecase(self, pointer_factory, func):
        a = np.arange(10, 16).reshape((2, 3)).astype(np.float32)
        out = np.empty(CARRAY_USECASE_OUT_LEN, dtype=np.float32)
        func(pointer_factory(a), pointer_factory(out), *a.shape)
        return out

    def check_carray_usecase(self, pointer_factory, pyfunc, cfunc):
        expected = self.run_carray_usecase(pointer_factory, pyfunc)
        got = self.run_carray_usecase(pointer_factory, cfunc)
        self.assertPreciseEqual(expected, got)

    def make_voidptr(self, arr):
        return arr.ctypes.data_as(ctypes.c_void_p)

    def make_float32_pointer(self, arr):
        return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_float))

    def make_float64_pointer(self, arr):
        return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_double))

    def check_carray_farray(self, func, order):
        def eq(got, expected):
            # Same layout, dtype, shape, etc.
            self.assertPreciseEqual(got, expected)
            # Same underlying data
            self.assertEqual(got.ctypes.data, expected.ctypes.data)

        base = np.arange(6).reshape((2, 3)).astype(np.float32).copy(order=order)

        # With typed pointer and implied dtype
        a = func(self.make_float32_pointer(base), base.shape)
        eq(a, base)
        # Integer shape
        a = func(self.make_float32_pointer(base), base.size)
        eq(a, base.ravel('K'))

        # With typed pointer and explicit dtype
        a = func(self.make_float32_pointer(base), base.shape, base.dtype)
        eq(a, base)
        a = func(self.make_float32_pointer(base), base.shape, np.float32)
        eq(a, base)

        # With voidptr and explicit dtype
        a = func(self.make_voidptr(base), base.shape, base.dtype)
        eq(a, base)
        a = func(self.make_voidptr(base), base.shape, np.int32)
        eq(a, base.view(np.int32))

        # voidptr without dtype
        with self.assertRaises(TypeError):
            func(self.make_voidptr(base), base.shape)
        # Invalid pointer type
        with self.assertRaises(TypeError):
            func(base.ctypes.data, base.shape)
        # Mismatching dtype
        with self.assertRaises(TypeError) as raises:
            func(self.make_float32_pointer(base), base.shape, np.int32)
        self.assertIn("mismatching dtype 'int32' for pointer",
                      str(raises.exception))

    def test_carray(self):
        """
        Test pure Python carray().
        """
        self.check_carray_farray(carray, 'C')

    def test_farray(self):
        """
        Test pure Python farray().
        """
        self.check_carray_farray(farray, 'F')

    def make_carray_sigs(self, formal_sig):
        """
        Generate a bunch of concrete signatures by varying the width
        and signedness of size arguments (see issue #1923).
        """
        for actual_size in (types.intp, types.int32, types.intc,
                            types.uintp, types.uint32, types.uintc):
            args = tuple(actual_size if a == types.intp else a
                         for a in formal_sig.args)
            yield formal_sig.return_type(*args)

    def check_numba_carray_farray(self, usecase, dtype_usecase):
        # With typed pointers and implicit dtype
        pyfunc = usecase
        for sig in self.make_carray_sigs(carray_float32_usecase_sig):
            f = cfunc(sig)(pyfunc)
            self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes)

        # With typed pointers and explicit (matching) dtype
        pyfunc = dtype_usecase
        for sig in self.make_carray_sigs(carray_float32_usecase_sig):
            f = cfunc(sig)(pyfunc)
            self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes)
        # With typed pointers and mismatching dtype
        with self.assertTypingError() as raises:
            f = cfunc(carray_float64_usecase_sig)(pyfunc)
        self.assertIn("mismatching dtype 'float32' for pointer type 'float64*'",
                      str(raises.exception))

        # With voidptr
        pyfunc = dtype_usecase
        for sig in self.make_carray_sigs(carray_voidptr_usecase_sig):
            f = cfunc(sig)(pyfunc)
            self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes)

    def test_numba_carray(self):
        """
        Test Numba-compiled carray() against pure Python carray()
        """
        self.check_numba_carray_farray(carray_usecase, carray_dtype_usecase)

    def test_numba_farray(self):
        """
        Test Numba-compiled farray() against pure Python farray()
        """
        self.check_numba_carray_farray(farray_usecase, farray_dtype_usecase)

@skip_cffi_unsupported
class TestCffiStruct(TestCase):
    c_source = """
typedef struct _big_struct {
    int    i1;
    float  f2;
    double d3;
    float  af4[9];
} big_struct;

typedef struct _error {
    int bits:4;
} error;

typedef double (*myfunc)(big_struct*, size_t);
"""

    def get_ffi(self, src=c_source):
        from cffi import FFI

        ffi = FFI()
        ffi.cdef(src)
        return ffi

    def test_type_parsing(self):
        ffi = self.get_ffi()
        # Check struct typedef
        big_struct = ffi.typeof('big_struct')
        nbtype = cffi_support.map_type(big_struct, use_record_dtype=True)
        self.assertIsInstance(nbtype, types.Record)
        self.assertEqual(len(nbtype), 4)
        self.assertEqual(nbtype.typeof('i1'), types.int32)
        self.assertEqual(nbtype.typeof('f2'), types.float32)
        self.assertEqual(nbtype.typeof('d3'), types.float64)
        self.assertEqual(
            nbtype.typeof('af4'),
            types.NestedArray(dtype=types.float32, shape=(9,)),
        )

        # Check function typedef
        myfunc = ffi.typeof('myfunc')
        sig = cffi_support.map_type(myfunc, use_record_dtype=True)
        self.assertIsInstance(sig, typing.Signature)
        self.assertEqual(sig.args[0], types.CPointer(nbtype))
        self.assertEqual(sig.args[1], types.uintp)
        self.assertEqual(sig.return_type, types.float64)

    def test_cfunc_callback(self):
        ffi = self.get_ffi()
        big_struct = ffi.typeof('big_struct')
        nb_big_struct = cffi_support.map_type(big_struct, use_record_dtype=True)
        sig = cffi_support.map_type(ffi.typeof('myfunc'), use_record_dtype=True)

        @njit
        def calc(base):
            tmp = 0
            for i in range(base.size):
                elem = base[i]
                tmp += elem.i1 * elem.f2 / elem.d3
                tmp += base[i].af4.sum()
            return tmp

        @cfunc(sig)
        def foo(ptr, n):
            base = carray(ptr, n)
            return calc(base)

        # Make data
        mydata = ffi.new('big_struct[3]')
        ptr = ffi.cast('big_struct*', mydata)
        for i in range(3):
            ptr[i].i1 = i * 123
            ptr[i].f2 = i * 213
            ptr[i].d3 = (1 + i) * 213
            for j in range(9):
                ptr[i].af4[j] = i * 10 + j

        # Address of my data
        addr = int(ffi.cast('size_t', ptr))
        got = foo.ctypes(addr, 3)

        # Make numpy array from the cffi buffer
        array = np.ndarray(
            buffer=ffi.buffer(mydata),
            dtype=numpy_support.as_dtype(nb_big_struct),
            shape=3,
            )
        expect = calc(array)
        self.assertEqual(got, expect)

    def test_unsupport_bitsize(self):
        ffi = self.get_ffi()
        with self.assertRaises(ValueError) as raises:
            cffi_support.map_type(
                ffi.typeof('error'),
                use_record_dtype=True,
            )
        # When bitsize is provided, bitshift defaults to 0.
        self.assertEqual(
            "field 'bits' has bitshift, this is not supported",
            str(raises.exception)
        )

if __name__ == "__main__":
    unittest.main()


text:
/*
 * Pose2D.java
 *
 * Created on 8. Dezember 2007, 02:04
 *
 */

package de.naoth.rc.math;

import java.io.Serializable;

/**
 *
 * @author Heinrich Mellmann
 */
public class Pose2D implements Serializable
{
    public final Vector2D translation;
    public final double rotation;

    public Pose2D() {
      this(new Vector2D(), 0.0);
    }

    /** Creates a new instance of Pose2D */
    public Pose2D(double x, double y, double rotation)
    {
        this(new Vector2D(x, y),rotation);
    }//end Pose2D

    public Pose2D(Vector2D translation, double rotation)
    {
        this.translation = translation;
        this.rotation = Common.normalizeAngle(rotation);
    }//end Pose2D

    public Vector2D multiply(Vector2D point)
    {
        double s = Math.sin(rotation);
        double c = Math.cos(rotation);
        return (new Vector2D(point.x*c-point.y*s , point.x*s+point.y*c)).add(translation);
    }//end multiply

    public Pose2D add(Pose2D pose)
    {
        return new Pose2D(this.multiply(pose.translation), this.rotation+pose.rotation);
    }//end add

    public Pose2D subtract(Pose2D pose)
    {
        return new Pose2D(0,0,-pose.rotation).add(new Pose2D(this.translation.subtract(pose.translation), this.rotation));
    }//end subtract

    public String toString()
    {
        return "[ rotation = " + rotation + ", translation = " + translation + "]";
    }//end toString
}//end Pose2D


text:
using Orchard.ContentManagement.Records;

namespace Orchard.Core.Navigation.Models {
    public class ContentMenuItemPartRecord : ContentPartRecord {
        public virtual ContentItemRecord ContentMenuItemRecord { get; set; }
    }
}


text:
// Définition du LazyPipe pour utiliser Handlebars
'use strict';

var path     = require('path');
var _        = require('underscore');
var lazypipe = require('lazypipe');
var gulp     = require('gulp');
var gutil    = require('gulp-util');
var hb       = require('gulp-hb');
var rename   = require('gulp-rename');
var data     = require('gulp-data');
var dir      = require('require-dir');
var ENV      = require('../../tools/env');

var DEST     = path.resolve(ENV.html['dest-dir']);
var DEST_URL = DEST.replace(path.resolve(ENV.connect.baseDir), '')
                   .replace(path.sep, '/');

var genericDataFile  = path.resolve(path.join(ENV.html['data-dir'], 'data.json'));

var partials   = path.join(ENV.html['src-dir'], '{layouts,partials}', '**', '*.hbs');
var helpers   = './.gsk/tools/handlebars/helpers/**/*.js';

// UTILS
// ----------------------------------------------------------------------------
function processData(file) {
  var base = file.path.replace(ENV.html['src-dir'], ENV.html['data-dir']);
  var specificDataFile = base.replace('.hbs', '.json');
  var gData = {};
  var sData = {};

  try {
    gData = require(genericDataFile);
  } catch (e) {
    gutil.log(gutil.colors.yellow('WARN:'),
      'Unable to find data from',
      genericDataFile.replace(path.resolve('.'), '').slice(1)
    );
  }

  try {
    sData = require(specificDataFile);
  } catch (e) {
    gutil.log(gutil.colors.yellow('WARN:'),
      'Unable to find data from',
      specificDataFile.replace(path.resolve('.'), '').slice(1)
    );
  }

  var data  = _.extend({}, gData, sData);
  data.url  = file.path.replace(ENV.html['src-dir'], DEST_URL).replace('.hbs', '.html');

  return data;
}

module.exports = function () {
  var lazystream = lazypipe()
    .pipe(data, processData)
    .pipe(hb, {
      helpers: helpers,
      partials: partials,
      parsePartialName: function parsePartialName(options, file) {
        var partialName = file.path.replace(file.base,'');
        partialName = partialName.replace('.hbs','');
        partialName = partialName.replace('partials/','');
        partialName = partialName.replace(/\//g,'');
        return partialName;
      }
    })
    .pipe(rename, {
      extname: '.html'
    });

  return lazystream();
};


text:
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""

import logging
from pathlib import Path

import pytest
from flexmock import flexmock

from atomic_reactor.constants import INSPECT_CONFIG
from atomic_reactor.plugins.distribution_scope import (
    DisallowedDistributionScope,
    DistributionScopePlugin,
)
from atomic_reactor.util import DockerfileImages

class TestDistributionScope(object):
    def instantiate_plugin(self, workflow, parent_labels, current_scope, base_from_scratch=False):
        with open(Path(workflow.source.path) / "Dockerfile", 'wt') as df:
            df.write('FROM scratch\n')
            if current_scope:
                df.write('LABEL distribution-scope={}\n'.format(current_scope))

        workflow.build_dir.init_build_dirs(["x86_64"], workflow.source)

        if not base_from_scratch:
            (flexmock(workflow.imageutil)
                .should_receive('base_image_inspect')
                .and_return({INSPECT_CONFIG: {'Labels': parent_labels}}))
        else:
            flexmock(workflow.imageutil).should_receive('base_image_inspect').and_return({})

        dockerfile_images = DockerfileImages([])
        if base_from_scratch:
            dockerfile_images = DockerfileImages(['scratch'])
        workflow.data.dockerfile_images = dockerfile_images

        plugin = DistributionScopePlugin(workflow)
        plugin.log = logging.getLogger('plugin')
        return plugin

    @pytest.mark.parametrize('base_from_scratch', [True, False])
    @pytest.mark.parametrize(('parent_scope', 'current_scope', 'allowed'), [
        (None, None, True),
        (None, 'private', True),
        (None, 'authoritative-source-only', True),
        (None, 'restricted', True),
        (None, 'public', True),
        ('private', None, True),
        ('private', 'private', True),
        ('private', 'authoritative-source-only', False),
        ('private', 'restricted', False),
        ('private', 'public', False),
    ])
    def test_distribution_scope_allowed(self, workflow, base_from_scratch, parent_scope,
                                        current_scope, allowed, caplog):
        caplog.set_level(logging.ERROR, logger='atomic_reactor')
        plugin = self.instantiate_plugin(workflow,
                                         {'distribution-scope': parent_scope},
                                         current_scope,
                                         base_from_scratch=base_from_scratch)
        if base_from_scratch:
            allowed = True
        if allowed:
            with caplog.at_level(logging.DEBUG):
                plugin.run()

            # No errors logged
            assert not any(log.levelno >= logging.ERROR for log in caplog.records)

            if base_from_scratch:
                assert "no distribution scope set for" in caplog.text
        else:
            with pytest.raises(DisallowedDistributionScope):
                plugin.run()

            # Should log something at ERROR
            assert caplog.records

    @pytest.mark.parametrize('current_scope', [None, 'private'])
    def test_imported_parent_distribution_scope(self, workflow, caplog, current_scope):
        plugin = self.instantiate_plugin(workflow, None, current_scope)
        with caplog.at_level(logging.ERROR, logger='atomic_reactor'):
            plugin.run()

        # No errors logged
        assert not any(log.levelno >= logging.ERROR for log in caplog.records)

    @pytest.mark.parametrize('current_scope', [None, 'private'])
    def test_invalid_parent_distribution_scope(self, workflow, caplog, current_scope):
        plugin = self.instantiate_plugin(workflow,
                                         {'distribution-scope': 'invalid-choice'},
                                         current_scope)
        with caplog.at_level(logging.WARNING, logger='atomic_reactor'):
            plugin.run()

            if current_scope:
                # Warning logged (if we get as far as checking parent scope)
                assert 'invalid label' in caplog.text

    @pytest.mark.parametrize('parent_scope', [None, 'private'])
    def test_invalid_current_distribution_scope(self, workflow, caplog, parent_scope):
        plugin = self.instantiate_plugin(workflow,
                                         {'distribution-scope': parent_scope},
                                         'invalid-choice')
        with caplog.at_level(logging.WARNING, logger='atomic_reactor'):
            plugin.run()

            # Warning logged
            assert 'invalid label' in caplog.text