text
stringlengths
2
99k
meta
dict
#include <gtest/gtest.h> #include "stl.hpp" #include "src/db/sqlite_store.hpp" using json11::Json; TEST(json_store, can_get_and_set) { shared_ptr<mx3::JsonStore> db = make_shared<mx3::SqliteStore>(":memory:"); Json value = db->get("nothing"); EXPECT_EQ(value.is_null(), true) << "should return null for non-existent values"; db->set("A", 15); Json v = db->get("A"); EXPECT_EQ(v.int_value(), 15); } TEST(json_store, can_set_twice) { shared_ptr<mx3::JsonStore> db = make_shared<mx3::SqliteStore>(":memory:"); Json value = db->get("nothing"); EXPECT_EQ(value.is_null(), true) << "should return null for non-existent values"; db->set("A", 15); db->set("B", 16); db->set("A", 17); Json v = db->get("A"); EXPECT_EQ(v.int_value(), 17); }
{ "pile_set_name": "Github" }
#pragma once #include "../common.hpp" namespace glm{ namespace detail { template<typename T> GLM_FUNC_QUALIFIER T mod289(T const& x) { return x - floor(x * (static_cast<T>(1.0) / static_cast<T>(289.0))) * static_cast<T>(289.0); } template<typename T> GLM_FUNC_QUALIFIER T permute(T const& x) { return mod289(((x * static_cast<T>(34)) + static_cast<T>(1)) * x); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<2, T, Q> permute(vec<2, T, Q> const& x) { return mod289(((x * static_cast<T>(34)) + static_cast<T>(1)) * x); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<3, T, Q> permute(vec<3, T, Q> const& x) { return mod289(((x * static_cast<T>(34)) + static_cast<T>(1)) * x); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<4, T, Q> permute(vec<4, T, Q> const& x) { return mod289(((x * static_cast<T>(34)) + static_cast<T>(1)) * x); } template<typename T> GLM_FUNC_QUALIFIER T taylorInvSqrt(T const& r) { return static_cast<T>(1.79284291400159) - static_cast<T>(0.85373472095314) * r; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<2, T, Q> taylorInvSqrt(vec<2, T, Q> const& r) { return static_cast<T>(1.79284291400159) - static_cast<T>(0.85373472095314) * r; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<3, T, Q> taylorInvSqrt(vec<3, T, Q> const& r) { return static_cast<T>(1.79284291400159) - static_cast<T>(0.85373472095314) * r; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<4, T, Q> taylorInvSqrt(vec<4, T, Q> const& r) { return static_cast<T>(1.79284291400159) - static_cast<T>(0.85373472095314) * r; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<2, T, Q> fade(vec<2, T, Q> const& t) { return (t * t * t) * (t * (t * static_cast<T>(6) - static_cast<T>(15)) + static_cast<T>(10)); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<3, T, Q> fade(vec<3, T, Q> const& t) { return (t * t * t) * (t * (t * static_cast<T>(6) - static_cast<T>(15)) + static_cast<T>(10)); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<4, T, Q> fade(vec<4, T, Q> const& t) { return (t * t * t) * (t * (t * static_cast<T>(6) - static_cast<T>(15)) + static_cast<T>(10)); } }//namespace detail }//namespace glm
{ "pile_set_name": "Github" }
_Testing helpers follows previous patterns shown in [Testing Components](../testing-components/), because helpers are rendered to templates just like components._ Helpers are best tested with rendering tests, but can also be tested with unit tests. Rendering tests will provide better coverage for helpers, as it more closely simulates the lifecycle of a helper than in isolation. We're going to demonstrate how to test helpers by testing the `format-currency` helper from [Writing Helpers](../../templates/writing-helpers/). > You can follow along by generating your own helper with `ember generate helper > format-currency`. ```javascript {data-filename=app/helpers/format-currency.js} import { helper } from '@ember/component/helper'; export function formatCurrency([value, ...rest], namedArgs) { let dollars = Math.floor(value / 100); let cents = value % 100; let sign = namedArgs.sign === undefined ? '$' : namedArgs.sign; if (cents.toString().length === 1) { cents = '0' + cents; } return `${sign}${dollars}.${cents}`; } export default helper(formatCurrency); ``` Let's start by testing the helper by showing a simple unit test and then move on to testing with a rendering test afterwards. Helpers are functions, which can be easily tested through `module` alone. ```javascript {data-filename=tests/unit/helpers/format-currency-test.js} import { formatCurrency } from 'my-app/helpers/format-currency'; import { module, test } from 'qunit'; module('Unit | Helper | format currency', function(hooks) { test('formats 199 with $ as currency sign', function(assert) { assert.equal(formatCurrency([199], { sign: '$' }), '$1.99'); }); }); ``` As seen in the [Writing Helpers](../../templates/writing-helpers/) guide. The helper function expects the unnamed arguments as an array as the first argument. It expects the named arguments as an object as the second argument. Now we can move on to a more complex test case that ensures our helper is rendered correctly as well. This can be done with the `setupRenderingTest` helper, as shown in [Testing Components](../testing-components/). ```javascript {data-filename=tests/integration/helpers/format-currency-test.js} import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Helper | format currency', function(hooks) { setupRenderingTest(hooks); test('formats 199 with $ as currency sign', async function(assert) { this.set('value', 199); this.set('sign', '$'); await render(hbs`{{format-currency value sign=sign}}`); assert.equal(this.element.textContent.trim(), '$1.99'); }); }); ``` We can now also properly test if a helper will respond to property changes. ```javascript {data-filename=tests/integration/helpers/format-currency-test.js} import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Helper | format currency', function(hooks) { setupRenderingTest(hooks); test('formats 199 with $ as currency sign', async function(assert) { this.set('value', 199); this.set('sign', '$'); await render(hbs`{{format-currency value sign=sign}}`); assert.equal(this.element.textContent.trim(), '$1.99'); this.set('sign', '€'); assert.equal(this.element.textContent.trim(), '€1.99', 'Value is formatted with €'); }); }); ``` <!-- eof - needed for pages that end in a code block -->
{ "pile_set_name": "Github" }
{ "compilerOptions": { "module": "esnext", "outDir": "dist/", "noImplicitAny": true, "sourceMap": true, "target": "ESNext", "allowJs": true, "checkJs": false, "pretty": true, "skipLibCheck": true, "strict": true, "moduleResolution": "node", "esModuleInterop": true, "lib": ["dom", "dom.iterable", "ESNext"], "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "isolatedModules": true, "types": ["googlemaps"] }, "include": ["src"], "exclude": ["node_modules", "**/*.spec.ts"] }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2016 - 2019 Rui Zhao <renyuneyun@gmail.com> * * This file is part of Easer. * * Easer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Easer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Easer. If not, see <http://www.gnu.org/licenses/>. */ package ryey.easer.core.data.storage; import android.content.Context; import androidx.annotation.NonNull; import com.orhanobut.logger.Logger; import java.io.IOException; import java.util.List; import ryey.easer.commons.local_skill.IllegalStorageDataException; import ryey.easer.core.data.Named; import ryey.easer.core.data.Verifiable; import ryey.easer.core.data.WithCreatedVersion; import ryey.easer.core.data.storage.backend.DataStorageBackendCommonInterface; public abstract class AbstractDataStorage<T extends Named & Verifiable & WithCreatedVersion, T_backend extends DataStorageBackendCommonInterface<T>> { protected final @NonNull Context context; protected final @NonNull T_backend[] storage_backend_list; protected AbstractDataStorage(@NonNull Context context, @NonNull T_backend[] storage_backend_list) { this.context = context; this.storage_backend_list = storage_backend_list; } @NonNull public List<String> list() { List<String> list = null; for (T_backend backend : storage_backend_list) { if (list == null) list = backend.list(); else list.addAll(backend.list()); } return list; } public boolean has(@NonNull String name) { for (T_backend backend : storage_backend_list) { if (backend.has(name)) return true; } return false; } @NonNull public T get(@NonNull String name) throws RequiredDataNotFoundException { for (T_backend backend : storage_backend_list) { try { T data = backend.get(name); if (data != null) return data; else Logger.v("data not found on backend <%s>", backend.getClass().getSimpleName()); } catch (IllegalStorageDataException e) { e.printStackTrace(); } } throw new RequiredDataNotFoundException("data <%s> not found", name); } /** * Add a new {@link T} if no existing valid data with the same name exists. * @param data The {@link T} going to be added. * @return {@code true} if no file conflict, {@code false} otherwise * @throws IOException If anything else happens (e.g. no disk space) */ public boolean add(T data) throws IOException { for (T_backend backend : storage_backend_list) { if (backend.has(data.getName())) { try { T existing_data = backend.get(data.getName()); if (existing_data.isValid()) return false; } catch (IllegalStorageDataException ignored) { Logger.v("replace an invalid existing data (%s)", data.getName()); backend.delete(data.getName()); break; } } } storage_backend_list[0].write(data); return true; } abstract boolean isSafeToDelete(String name); /** * Delete an existing {@link T} with name {@param name}. * This method checks whether the data is used by others or not. * @param name Name of the data * @return {@code true} if {@param name} is safely deleted, {@code false} if it is used by other events. */ public boolean delete(String name) { if (!isSafeToDelete(name)) return false; for (T_backend backend : storage_backend_list) { if (backend.has(name)) { backend.delete(name); return true; } } throw new IllegalStateException(); } /** * Edit an existing {@link T}, whose name may or may not be changed. * @param oldName The name of the data before editing. * @param data The {@link T} of the new data (whose name may be different with {@param oldName} because of user's change). * @return {@code true} if no name conflict; {@code false} otherwise. * @throws IOException See {@link #add(Named)} */ public boolean edit(String oldName, T data) throws IOException { if (oldName.equals(data.getName())) { update(data); return true; } if (!add(data)) return false; handleRename(oldName, data); for (T_backend backend : storage_backend_list) { if (backend.has(oldName)) { backend.delete(oldName); return true; } } throw new IllegalAccessError(); } /** * Update an existing {@link T} with the new {@param data} without changing the name. * @param data The new data which is going to replace the old data * @throws IOException See {@link #add(Named)} */ void update(T data) throws IOException { String name = data.getName(); for (T_backend backend : storage_backend_list) { if (backend.has(name)) { backend.delete(name); add(data); return; } } throw new IllegalAccessError(); } protected abstract void handleRename(String oldName, T data) throws IOException; }
{ "pile_set_name": "Github" }
App group defines 3 targets: - app_group_common, - app_group_client, - app_group_mainapp. A typical application is either a main app or a client of a main app, so it should depend on either app_group_client or app_group_client, but not on both.
{ "pile_set_name": "Github" }
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: yunwuxin <448901948@qq.com> // +---------------------------------------------------------------------- namespace think\console\input; class Definition { /** * @var Argument[] */ private $arguments; private $requiredCount; private $hasAnArrayArgument = false; private $hasOptional; /** * @var Option[] */ private $options; private $shortcuts; /** * 构造方法 * @param array $definition * @api */ public function __construct(array $definition = []) { $this->setDefinition($definition); } /** * 设置指令的定义 * @param array $definition 定义的数组 */ public function setDefinition(array $definition) { $arguments = []; $options = []; foreach ($definition as $item) { if ($item instanceof Option) { $options[] = $item; } else { $arguments[] = $item; } } $this->setArguments($arguments); $this->setOptions($options); } /** * 设置参数 * @param Argument[] $arguments 参数数组 */ public function setArguments($arguments = []) { $this->arguments = []; $this->requiredCount = 0; $this->hasOptional = false; $this->hasAnArrayArgument = false; $this->addArguments($arguments); } /** * 添加参数 * @param Argument[] $arguments 参数数组 * @api */ public function addArguments($arguments = []) { if (null !== $arguments) { foreach ($arguments as $argument) { $this->addArgument($argument); } } } /** * 添加一个参数 * @param Argument $argument 参数 * @throws \LogicException */ public function addArgument(Argument $argument) { if (isset($this->arguments[$argument->getName()])) { throw new \LogicException(sprintf('An argument with name "%s" already exists.', $argument->getName())); } if ($this->hasAnArrayArgument) { throw new \LogicException('Cannot add an argument after an array argument.'); } if ($argument->isRequired() && $this->hasOptional) { throw new \LogicException('Cannot add a required argument after an optional one.'); } if ($argument->isArray()) { $this->hasAnArrayArgument = true; } if ($argument->isRequired()) { ++$this->requiredCount; } else { $this->hasOptional = true; } $this->arguments[$argument->getName()] = $argument; } /** * 根据名称或者位置获取参数 * @param string|int $name 参数名或者位置 * @return Argument 参数 * @throws \InvalidArgumentException */ public function getArgument($name) { if (!$this->hasArgument($name)) { throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); } $arguments = is_int($name) ? array_values($this->arguments) : $this->arguments; return $arguments[$name]; } /** * 根据名称或位置检查是否具有某个参数 * @param string|int $name 参数名或者位置 * @return bool * @api */ public function hasArgument($name) { $arguments = is_int($name) ? array_values($this->arguments) : $this->arguments; return isset($arguments[$name]); } /** * 获取所有的参数 * @return Argument[] 参数数组 */ public function getArguments() { return $this->arguments; } /** * 获取参数数量 * @return int */ public function getArgumentCount() { return $this->hasAnArrayArgument ? PHP_INT_MAX : count($this->arguments); } /** * 获取必填的参数的数量 * @return int */ public function getArgumentRequiredCount() { return $this->requiredCount; } /** * 获取参数默认值 * @return array */ public function getArgumentDefaults() { $values = []; foreach ($this->arguments as $argument) { $values[$argument->getName()] = $argument->getDefault(); } return $values; } /** * 设置选项 * @param Option[] $options 选项数组 */ public function setOptions($options = []) { $this->options = []; $this->shortcuts = []; $this->addOptions($options); } /** * 添加选项 * @param Option[] $options 选项数组 * @api */ public function addOptions($options = []) { foreach ($options as $option) { $this->addOption($option); } } /** * 添加一个选项 * @param Option $option 选项 * @throws \LogicException * @api */ public function addOption(Option $option) { if (isset($this->options[$option->getName()]) && !$option->equals($this->options[$option->getName()])) { throw new \LogicException(sprintf('An option named "%s" already exists.', $option->getName())); } if ($option->getShortcut()) { foreach (explode('|', $option->getShortcut()) as $shortcut) { if (isset($this->shortcuts[$shortcut]) && !$option->equals($this->options[$this->shortcuts[$shortcut]]) ) { throw new \LogicException(sprintf('An option with shortcut "%s" already exists.', $shortcut)); } } } $this->options[$option->getName()] = $option; if ($option->getShortcut()) { foreach (explode('|', $option->getShortcut()) as $shortcut) { $this->shortcuts[$shortcut] = $option->getName(); } } } /** * 根据名称获取选项 * @param string $name 选项名 * @return Option * @throws \InvalidArgumentException * @api */ public function getOption($name) { if (!$this->hasOption($name)) { throw new \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name)); } return $this->options[$name]; } /** * 根据名称检查是否有这个选项 * @param string $name 选项名 * @return bool * @api */ public function hasOption($name) { return isset($this->options[$name]); } /** * 获取所有选项 * @return Option[] * @api */ public function getOptions() { return $this->options; } /** * 根据名称检查某个选项是否有短名称 * @param string $name 短名称 * @return bool */ public function hasShortcut($name) { return isset($this->shortcuts[$name]); } /** * 根据短名称获取选项 * @param string $shortcut 短名称 * @return Option */ public function getOptionForShortcut($shortcut) { return $this->getOption($this->shortcutToName($shortcut)); } /** * 获取所有选项的默认值 * @return array */ public function getOptionDefaults() { $values = []; foreach ($this->options as $option) { $values[$option->getName()] = $option->getDefault(); } return $values; } /** * 根据短名称获取选项名 * @param string $shortcut 短名称 * @return string * @throws \InvalidArgumentException */ private function shortcutToName($shortcut) { if (!isset($this->shortcuts[$shortcut])) { throw new \InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut)); } return $this->shortcuts[$shortcut]; } /** * 获取该指令的介绍 * @param bool $short 是否简洁介绍 * @return string */ public function getSynopsis($short = false) { $elements = []; if ($short && $this->getOptions()) { $elements[] = '[options]'; } elseif (!$short) { foreach ($this->getOptions() as $option) { $value = ''; if ($option->acceptValue()) { $value = sprintf(' %s%s%s', $option->isValueOptional() ? '[' : '', strtoupper($option->getName()), $option->isValueOptional() ? ']' : ''); } $shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : ''; $elements[] = sprintf('[%s--%s%s]', $shortcut, $option->getName(), $value); } } if (count($elements) && $this->getArguments()) { $elements[] = '[--]'; } foreach ($this->getArguments() as $argument) { $element = '<' . $argument->getName() . '>'; if (!$argument->isRequired()) { $element = '[' . $element . ']'; } elseif ($argument->isArray()) { $element .= ' (' . $element . ')'; } if ($argument->isArray()) { $element .= '...'; } $elements[] = $element; } return implode(' ', $elements); } }
{ "pile_set_name": "Github" }
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Renderer for {@link goog.ui.Palette}s. * * @author attila@google.com (Attila Bodis) */ goog.provide('goog.ui.PaletteRenderer'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.Role'); goog.require('goog.a11y.aria.State'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.NodeIterator'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classlist'); goog.require('goog.iter'); goog.require('goog.style'); goog.require('goog.ui.ControlRenderer'); goog.require('goog.userAgent'); /** * Default renderer for {@link goog.ui.Palette}s. Renders the palette as an * HTML table wrapped in a DIV, with one palette item per cell: * * <div class="goog-palette"> * <table class="goog-palette-table"> * <tbody class="goog-palette-body"> * <tr class="goog-palette-row"> * <td class="goog-palette-cell">...Item 0...</td> * <td class="goog-palette-cell">...Item 1...</td> * ... * </tr> * <tr class="goog-palette-row"> * ... * </tr> * </tbody> * </table> * </div> * * @constructor * @extends {goog.ui.ControlRenderer} */ goog.ui.PaletteRenderer = function() { goog.ui.ControlRenderer.call(this); }; goog.inherits(goog.ui.PaletteRenderer, goog.ui.ControlRenderer); goog.addSingletonGetter(goog.ui.PaletteRenderer); /** * Globally unique ID sequence for cells rendered by this renderer class. * @type {number} * @private */ goog.ui.PaletteRenderer.cellId_ = 0; /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * @type {string} */ goog.ui.PaletteRenderer.CSS_CLASS = goog.getCssName('goog-palette'); /** * Returns the palette items arranged in a table wrapped in a DIV, with the * renderer's own CSS class and additional state-specific classes applied to * it. * @param {goog.ui.Control} palette goog.ui.Palette to render. * @return {!Element} Root element for the palette. * @override */ goog.ui.PaletteRenderer.prototype.createDom = function(palette) { var classNames = this.getClassNames(palette); var element = palette.getDomHelper().createDom( goog.dom.TagName.DIV, classNames ? classNames.join(' ') : null, this.createGrid( /** @type {Array<Node>} */ (palette.getContent()), palette.getSize(), palette.getDomHelper())); goog.a11y.aria.setRole(element, goog.a11y.aria.Role.GRID); return element; }; /** * Returns the given items in a table with {@code size.width} columns and * {@code size.height} rows. If the table is too big, empty cells will be * created as needed. If the table is too small, the items that don't fit * will not be rendered. * @param {Array<Node>} items Palette items. * @param {goog.math.Size} size Palette size (columns x rows); both dimensions * must be specified as numbers. * @param {goog.dom.DomHelper} dom DOM helper for document interaction. * @return {!Element} Palette table element. */ goog.ui.PaletteRenderer.prototype.createGrid = function(items, size, dom) { var rows = []; for (var row = 0, index = 0; row < size.height; row++) { var cells = []; for (var column = 0; column < size.width; column++) { var item = items && items[index++]; cells.push(this.createCell(item, dom)); } rows.push(this.createRow(cells, dom)); } return this.createTable(rows, dom); }; /** * Returns a table element (or equivalent) that wraps the given rows. * @param {Array<Element>} rows Array of row elements. * @param {goog.dom.DomHelper} dom DOM helper for document interaction. * @return {!Element} Palette table element. */ goog.ui.PaletteRenderer.prototype.createTable = function(rows, dom) { var table = dom.createDom( goog.dom.TagName.TABLE, goog.getCssName(this.getCssClass(), 'table'), dom.createDom( goog.dom.TagName.TBODY, goog.getCssName(this.getCssClass(), 'body'), rows)); table.cellSpacing = 0; table.cellPadding = 0; return table; }; /** * Returns a table row element (or equivalent) that wraps the given cells. * @param {Array<Element>} cells Array of cell elements. * @param {goog.dom.DomHelper} dom DOM helper for document interaction. * @return {!Element} Row element. */ goog.ui.PaletteRenderer.prototype.createRow = function(cells, dom) { var row = dom.createDom( goog.dom.TagName.TR, goog.getCssName(this.getCssClass(), 'row'), cells); goog.a11y.aria.setRole(row, goog.a11y.aria.Role.ROW); return row; }; /** * Returns a table cell element (or equivalent) that wraps the given palette * item (which must be a DOM node). * @param {Node|string} node Palette item. * @param {goog.dom.DomHelper} dom DOM helper for document interaction. * @return {!Element} Cell element. */ goog.ui.PaletteRenderer.prototype.createCell = function(node, dom) { var cell = dom.createDom( goog.dom.TagName.TD, { 'class': goog.getCssName(this.getCssClass(), 'cell'), // Cells must have an ID, for accessibility, so we generate one here. 'id': goog.getCssName(this.getCssClass(), 'cell-') + goog.ui.PaletteRenderer.cellId_++ }, node); goog.a11y.aria.setRole(cell, goog.a11y.aria.Role.GRIDCELL); // Initialize to an unselected state. goog.a11y.aria.setState(cell, goog.a11y.aria.State.SELECTED, false); if (!goog.dom.getTextContent(cell) && !goog.a11y.aria.getLabel(cell)) { var ariaLabelForCell = this.findAriaLabelForCell_(cell); if (ariaLabelForCell) { goog.a11y.aria.setLabel(cell, ariaLabelForCell); } } return cell; }; /** * Descends the DOM and tries to find an aria label for a grid cell * from the first child with a label or title. * @param {!Element} cell The cell. * @return {string} The label to use. * @private */ goog.ui.PaletteRenderer.prototype.findAriaLabelForCell_ = function(cell) { var iter = new goog.dom.NodeIterator(cell); var label = ''; var node; while (!label && (node = goog.iter.nextOrValue(iter, null))) { if (node.nodeType == goog.dom.NodeType.ELEMENT) { label = goog.a11y.aria.getLabel(/** @type {!Element} */ (node)) || node.title; } } return label; }; /** * Overrides {@link goog.ui.ControlRenderer#canDecorate} to always return false. * @param {Element} element Ignored. * @return {boolean} False, since palettes don't support the decorate flow (for * now). * @override */ goog.ui.PaletteRenderer.prototype.canDecorate = function(element) { return false; }; /** * Overrides {@link goog.ui.ControlRenderer#decorate} to be a no-op, since * palettes don't support the decorate flow (for now). * @param {goog.ui.Control} palette Ignored. * @param {Element} element Ignored. * @return {null} Always null. * @override */ goog.ui.PaletteRenderer.prototype.decorate = function(palette, element) { return null; }; /** * Overrides {@link goog.ui.ControlRenderer#setContent} for palettes. Locates * the HTML table representing the palette grid, and replaces the contents of * each cell with a new element from the array of nodes passed as the second * argument. If the new content has too many items the table will have more * rows added to fit, if there are less items than the table has cells, then the * left over cells will be empty. * @param {Element} element Root element of the palette control. * @param {goog.ui.ControlContent} content Array of items to replace existing * palette items. * @override */ goog.ui.PaletteRenderer.prototype.setContent = function(element, content) { var items = /** @type {Array<Node>} */ (content); if (element) { var tbody = goog.dom.getElementsByTagNameAndClass( goog.dom.TagName.TBODY, goog.getCssName(this.getCssClass(), 'body'), element)[0]; if (tbody) { var index = 0; goog.array.forEach(tbody.rows, function(row) { goog.array.forEach(row.cells, function(cell) { goog.dom.removeChildren(cell); if (items) { var item = items[index++]; if (item) { goog.dom.appendChild(cell, item); } } }); }); // Make space for any additional items. if (index < items.length) { var cells = []; var dom = goog.dom.getDomHelper(element); var width = tbody.rows[0].cells.length; while (index < items.length) { var item = items[index++]; cells.push(this.createCell(item, dom)); if (cells.length == width) { var row = this.createRow(cells, dom); goog.dom.appendChild(tbody, row); cells.length = 0; } } if (cells.length > 0) { while (cells.length < width) { cells.push(this.createCell('', dom)); } var row = this.createRow(cells, dom); goog.dom.appendChild(tbody, row); } } } // Make sure the new contents are still unselectable. goog.style.setUnselectable(element, true, goog.userAgent.GECKO); } }; /** * Returns the item corresponding to the given node, or null if the node is * neither a palette cell nor part of a palette item. * @param {goog.ui.Palette} palette Palette in which to look for the item. * @param {Node} node Node to look for. * @return {Node} The corresponding palette item (null if not found). */ goog.ui.PaletteRenderer.prototype.getContainingItem = function(palette, node) { var root = palette.getElement(); while (node && node.nodeType == goog.dom.NodeType.ELEMENT && node != root) { if (node.tagName == goog.dom.TagName.TD && goog.dom.classlist.contains( /** @type {!Element} */ (node), goog.getCssName(this.getCssClass(), 'cell'))) { return node.firstChild; } node = node.parentNode; } return null; }; /** * Updates the highlight styling of the palette cell containing the given node * based on the value of the Boolean argument. * @param {goog.ui.Palette} palette Palette containing the item. * @param {Node} node Item whose cell is to be highlighted or un-highlighted. * @param {boolean} highlight If true, the cell is highlighted; otherwise it is * un-highlighted. */ goog.ui.PaletteRenderer.prototype.highlightCell = function( palette, node, highlight) { if (node) { var cell = this.getCellForItem(node); goog.asserts.assert(cell); goog.dom.classlist.enable( cell, goog.getCssName(this.getCssClass(), 'cell-hover'), highlight); // See http://www.w3.org/TR/2006/WD-aria-state-20061220/#activedescendent // for an explanation of the activedescendent. if (highlight) { goog.a11y.aria.setState( palette.getElementStrict(), goog.a11y.aria.State.ACTIVEDESCENDANT, cell.id); } else if ( cell.id == goog.a11y.aria.getState( palette.getElementStrict(), goog.a11y.aria.State.ACTIVEDESCENDANT)) { goog.a11y.aria.removeState( palette.getElementStrict(), goog.a11y.aria.State.ACTIVEDESCENDANT); } } }; /** * @param {Node} node Item whose cell is to be returned. * @return {Element} The grid cell for the palette item. */ goog.ui.PaletteRenderer.prototype.getCellForItem = function(node) { return /** @type {Element} */ (node ? node.parentNode : null); }; /** * Updates the selection styling of the palette cell containing the given node * based on the value of the Boolean argument. * @param {goog.ui.Palette} palette Palette containing the item. * @param {Node} node Item whose cell is to be selected or deselected. * @param {boolean} select If true, the cell is selected; otherwise it is * deselected. */ goog.ui.PaletteRenderer.prototype.selectCell = function(palette, node, select) { if (node) { var cell = /** @type {!Element} */ (node.parentNode); goog.dom.classlist.enable( cell, goog.getCssName(this.getCssClass(), 'cell-selected'), select); goog.a11y.aria.setState(cell, goog.a11y.aria.State.SELECTED, select); } }; /** * Returns the CSS class to be applied to the root element of components * rendered using this renderer. * @return {string} Renderer-specific CSS class. * @override */ goog.ui.PaletteRenderer.prototype.getCssClass = function() { return goog.ui.PaletteRenderer.CSS_CLASS; };
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <TVServices/TVSNetworkInterface.h> @class NSArray, NSString; @interface TVSEthernetInterface : TVSNetworkInterface { _Bool _active; _Bool _shouldUseDHCP; _Bool _shouldUseDefaultDNS; NSString *_IPAddress; NSString *_subnetMask; NSString *_routerAddress; NSArray *_dnsAddresses; } + (id)keyPathsForValuesAffectingPrimaryDNSAddress; + (id)_interfaceType; + (_Bool)_supportsInterface:(struct __SCNetworkInterface *)arg1; + (id)RJ45EthernetInterface; @property(copy, nonatomic) NSArray *dnsAddresses; // @synthesize dnsAddresses=_dnsAddresses; @property(copy, nonatomic) NSString *routerAddress; // @synthesize routerAddress=_routerAddress; @property(copy, nonatomic) NSString *subnetMask; // @synthesize subnetMask=_subnetMask; @property(nonatomic) _Bool shouldUseDefaultDNS; // @synthesize shouldUseDefaultDNS=_shouldUseDefaultDNS; @property(nonatomic) _Bool shouldUseDHCP; // @synthesize shouldUseDHCP=_shouldUseDHCP; @property(copy, nonatomic) NSString *IPAddress; // @synthesize IPAddress=_IPAddress; @property(nonatomic, getter=isActive) _Bool active; // @synthesize active=_active; - (void).cxx_destruct; @property(copy, nonatomic) NSString *primaryDNSAddress; - (id)_dnsAddressesForService:(struct __CFString *)arg1 domain:(struct __CFString *)arg2; - (_Bool)_setDNSWithAddresses:(id)arg1 forServiceRef:(struct __SCNetworkService *)arg2; - (_Bool)_commitChangesWithServiceRef:(struct __SCNetworkService *)arg1; - (void)_updateWithServiceRef:(struct __SCNetworkService *)arg1 interfaceRef:(struct __SCNetworkInterface *)arg2; - (id)description; @end
{ "pile_set_name": "Github" }
- Worked around path not convex crash under certain conditions. - Fixed FastScroller to use AppCompatTextView for popup.
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.10"> <CommonModule uuid="9b77e99b-b1d3-4368-a671-59e0ebba3f0e"> <Properties> <Name>ЛокализацияКлиент</Name> <Synonym> <v8:item> <v8:lang>ru</v8:lang> <v8:content>Локализация клиент</v8:content> </v8:item> </Synonym> <Comment/> <Global>false</Global> <ClientManagedApplication>true</ClientManagedApplication> <Server>false</Server> <ExternalConnection>false</ExternalConnection> <ClientOrdinaryApplication>true</ClientOrdinaryApplication> <ServerCall>false</ServerCall> <Privileged>false</Privileged> <ReturnValuesReuse>DontUse</ReturnValuesReuse> </Properties> </CommonModule> </MetaDataObject>
{ "pile_set_name": "Github" }
/** Automatically generated file. DO NOT MODIFY */ package com.example.mapdemo; public final class BuildConfig { public final static boolean DEBUG = true; }
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.openide.util.svg; import java.io.IOException; import java.net.URL; import javax.swing.Icon; import org.openide.util.lookup.ServiceProvider; import org.openide.util.spi.SVGLoader; @ServiceProvider(service=SVGLoader.class) public class SVGLoaderImpl implements SVGLoader { @Override public Icon loadIcon(URL url) throws IOException { return SVGIcon.load(url); } }
{ "pile_set_name": "Github" }
// // detail/wait_handler.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_WAIT_HANDLER_HPP #define BOOST_ASIO_DETAIL_WAIT_HANDLER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/addressof.hpp> #include <boost/asio/detail/fenced_block.hpp> #include <boost/asio/detail/handler_alloc_helpers.hpp> #include <boost/asio/detail/handler_invoke_helpers.hpp> #include <boost/asio/detail/wait_op.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { template <typename Handler> class wait_handler : public wait_op { public: BOOST_ASIO_DEFINE_HANDLER_PTR(wait_handler); wait_handler(Handler& h) : wait_op(&wait_handler::do_complete), handler_(BOOST_ASIO_MOVE_CAST(Handler)(h)) { } static void do_complete(io_service_impl* owner, operation* base, const boost::system::error_code& /*ec*/, std::size_t /*bytes_transferred*/) { // Take ownership of the handler object. wait_handler* h(static_cast<wait_handler*>(base)); ptr p = { boost::asio::detail::addressof(h->handler_), h, h }; BOOST_ASIO_HANDLER_COMPLETION((h)); // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::binder1<Handler, boost::system::error_code> handler(h->handler_, h->ec_); p.h = boost::asio::detail::addressof(handler.handler_); p.reset(); // Make the upcall if required. if (owner) { fenced_block b(fenced_block::half); BOOST_ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); boost_asio_handler_invoke_helpers::invoke(handler, handler.handler_); BOOST_ASIO_HANDLER_INVOCATION_END; } } private: Handler handler_; }; } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_DETAIL_WAIT_HANDLER_HPP
{ "pile_set_name": "Github" }
Shader "Hidden/Blend" { Properties { _MainTex ("Screen Blended", 2D) = "" {} _ColorBuffer ("Color", 2D) = "" {} } CGINCLUDE #include "UnityCG.cginc" struct v2f { float4 pos : SV_POSITION; float2 uv[2] : TEXCOORD0; }; struct v2f_mt { float4 pos : SV_POSITION; float2 uv[4] : TEXCOORD0; }; sampler2D _ColorBuffer; sampler2D _MainTex; half _Intensity; half4 _ColorBuffer_TexelSize; half4 _ColorBuffer_ST; half4 _MainTex_TexelSize; half4 _MainTex_ST; v2f vert( appdata_img v ) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); o.uv[0] = v.texcoord.xy; o.uv[1] = v.texcoord.xy; #if UNITY_UV_STARTS_AT_TOP if (_ColorBuffer_TexelSize.y < 0) o.uv[1].y = 1-o.uv[1].y; #endif return o; } v2f_mt vertMultiTap( appdata_img v ) { v2f_mt o; o.pos = UnityObjectToClipPos(v.vertex); o.uv[0] = v.texcoord.xy + _MainTex_TexelSize.xy * 0.5; o.uv[1] = v.texcoord.xy - _MainTex_TexelSize.xy * 0.5; o.uv[2] = v.texcoord.xy - _MainTex_TexelSize.xy * half2(1,-1) * 0.5; o.uv[3] = v.texcoord.xy + _MainTex_TexelSize.xy * half2(1,-1) * 0.5; return o; } half4 fragScreen (v2f i) : SV_Target { half4 toBlend = saturate (tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv[0], _MainTex_ST)) * _Intensity); return 1-(1-toBlend)*(1-tex2D(_ColorBuffer, UnityStereoScreenSpaceUVAdjust(i.uv[1], _ColorBuffer_ST))); } half4 fragAdd (v2f i) : SV_Target { return tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv[0].xy, _MainTex_ST)) * _Intensity + tex2D(_ColorBuffer, UnityStereoScreenSpaceUVAdjust(i.uv[1], _ColorBuffer_ST)); } half4 fragVignetteBlend (v2f i) : SV_Target { return tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv[0].xy, _MainTex_ST)) * tex2D(_ColorBuffer, UnityStereoScreenSpaceUVAdjust(i.uv[0], _ColorBuffer_ST)); } half4 fragMultiTap (v2f_mt i) : SV_Target { half4 outColor = tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv[0].xy, _MainTex_ST)); outColor += tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv[1].xy, _MainTex_ST)); outColor += tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv[2].xy, _MainTex_ST)); outColor += tex2D(_MainTex, UnityStereoScreenSpaceUVAdjust(i.uv[3].xy, _MainTex_ST)); return outColor * 0.25; } ENDCG Subshader { ZTest Always Cull Off ZWrite Off // 0: nicer & softer "screen" blend mode Pass { CGPROGRAM #pragma vertex vert #pragma fragment fragScreen ENDCG } // 1: simple "add" blend mode Pass { CGPROGRAM #pragma vertex vert #pragma fragment fragAdd ENDCG } // 2: used for "stable" downsampling Pass { CGPROGRAM #pragma vertex vertMultiTap #pragma fragment fragMultiTap ENDCG } // 3: vignette blending Pass { CGPROGRAM #pragma vertex vert #pragma fragment fragVignetteBlend ENDCG } } Fallback off } // shader
{ "pile_set_name": "Github" }
import is from 'core-js-pure/features/object/is'; QUnit.test('Object.is', assert => { assert.isFunction(is); assert.ok(is(1, 1), '1 is 1'); assert.ok(is(NaN, NaN), '1 is 1'); assert.ok(!is(0, -0), '0 isnt -0'); assert.ok(!is({}, {}), '{} isnt {}'); });
{ "pile_set_name": "Github" }
# Blender v2.81 (sub 16) OBJ File: 'Berzerker.blend' # www.blender.org mtllib fist_right.mtl o Fist_Plane.006 v -0.915338 -2.495692 0.200000 v 1.217395 -2.497374 0.200000 v -0.915681 -1.614735 0.200000 v 1.217395 -1.787374 0.200000 v -0.914076 -1.940738 0.200000 v 1.217395 -1.970375 0.200000 v 0.377852 -2.498425 0.200000 v 0.377852 -1.724693 0.200000 v 0.383984 -1.958675 0.200000 v 0.476506 -2.498425 0.200000 v 0.476506 -1.723857 0.200000 v 0.474754 -1.958452 0.200000 v 1.562717 -1.389855 0.200000 v 0.481955 -1.356931 0.200000 v 1.295915 -1.011076 0.200000 v 0.274020 -0.981306 0.200000 v 0.028024 -0.039269 0.200000 v -0.234590 -0.062176 0.200000 v -0.255344 0.049738 0.200000 v -0.290900 0.046812 0.200000 v 1.743723 -0.480281 0.200000 v 1.728559 -0.476117 0.200000 v -1.144576 -1.240229 0.200000 v 0.372596 -1.374999 0.200000 v -1.662922 -0.388045 0.200000 v -0.142118 -0.426543 0.200000 v -0.827349 0.060621 0.200000 v -0.405505 0.060270 0.200000 v -2.049829 0.254983 0.200000 v -0.829165 0.155078 0.200000 v -1.652478 0.870563 0.200000 v -0.853132 0.537292 0.200000 v -1.176917 1.604717 0.200000 v -0.791322 0.631899 0.200000 v 0.254810 0.929850 0.200000 v -0.393971 0.298881 0.200000 v 0.209399 0.458074 0.200000 v -0.343513 0.303927 0.200000 v -0.446951 0.158862 0.200000 v -0.448212 0.180306 0.200000 v -0.310663 0.204647 0.200000 v 0.178962 0.342633 0.200000 v 0.059567 0.130674 0.200000 v 0.199746 0.332778 0.200000 v -0.316747 0.189439 0.200000 v 0.031583 0.117291 0.200000 v -1.094086 1.715885 0.200000 v -0.261793 1.326566 0.200000 v -0.588382 2.500598 0.200000 v 0.206856 2.157055 0.200000 v -0.449098 2.497971 0.200000 v 0.088596 2.439126 0.200000 v 0.395344 0.990197 0.200000 v 0.346381 0.525879 0.200000 v 1.043884 1.864967 0.200000 v 1.085662 1.578471 0.200000 v -0.144086 1.276432 0.200000 v 0.546898 2.181032 0.200000 v -0.142825 1.305445 0.200000 v 0.312271 2.064980 0.200000 v 0.714645 -0.398927 0.200000 v 0.129746 0.011592 0.200000 v 1.673740 0.727283 0.200000 v 1.146968 1.448418 0.200000 v 1.722785 1.052430 0.200000 v 1.370393 1.450234 0.200000 v 1.275934 -0.840328 0.200000 v 0.818187 -0.469771 0.200000 v 2.040666 0.111500 0.200000 v 1.728237 0.603761 0.200000 v 2.042483 0.180526 0.200000 v 1.977093 0.525652 0.200000 v -0.915338 -2.495692 -0.200000 v 1.217395 -2.497374 -0.199988 v -0.915681 -1.614735 -0.199988 v 1.217395 -1.787374 -0.200000 v -0.914076 -1.940738 -0.199988 v 1.217395 -1.970375 -0.200000 v 0.377852 -2.498425 -0.200000 v 0.377852 -1.724693 -0.200000 v 0.383984 -1.958675 -0.200000 v 0.476506 -2.498425 -0.200000 v 0.476506 -1.723857 -0.200000 v 0.474754 -1.958452 -0.200000 v 1.562717 -1.389855 -0.199988 v 0.481955 -1.356931 -0.200000 v 1.295915 -1.011076 -0.200000 v 0.274020 -0.981306 -0.200000 v 0.028024 -0.039269 -0.200000 v -0.234590 -0.062176 -0.200000 v -0.255344 0.049738 -0.200000 v -0.290900 0.046812 -0.200000 v 1.743723 -0.480281 -0.200000 v 1.728559 -0.476117 -0.199988 v -1.144576 -1.240229 -0.199988 v 0.372596 -1.374999 -0.200000 v -1.662922 -0.388045 -0.199988 v -0.142118 -0.426543 -0.199988 v -0.827349 0.060621 -0.200000 v -0.405505 0.060270 -0.200000 v -2.049829 0.254983 -0.200000 v -0.829165 0.155078 -0.200000 v -1.652478 0.870563 -0.199988 v -0.853132 0.537292 -0.200000 v -1.176917 1.604717 -0.200000 v -0.791322 0.631899 -0.200000 v 0.254810 0.929850 -0.200000 v -0.393971 0.298881 -0.200000 v 0.209399 0.458074 -0.200000 v -0.343513 0.303927 -0.199988 v -0.446951 0.158862 -0.199988 v -0.448212 0.180306 -0.200000 v -0.310663 0.204647 -0.200000 v 0.178962 0.342633 -0.200000 v 0.059567 0.130674 -0.199988 v 0.199746 0.332778 -0.200000 v -0.316747 0.189439 -0.200000 v 0.031583 0.117291 -0.200000 v -1.094086 1.715885 -0.199988 v -0.261793 1.326566 -0.199988 v -0.588382 2.500598 -0.200000 v 0.206856 2.157055 -0.200000 v -0.449098 2.497971 -0.200000 v 0.088596 2.439126 -0.200000 v 0.395344 0.990197 -0.200000 v 0.346381 0.525879 -0.200000 v 1.043884 1.864967 -0.200000 v 1.085662 1.578471 -0.199988 v -0.144086 1.276432 -0.200000 v 0.546898 2.181032 -0.200000 v -0.142825 1.305445 -0.200000 v 0.312271 2.064980 -0.200000 v 0.714645 -0.398927 -0.200000 v 0.129746 0.011592 -0.200000 v 1.673740 0.727283 -0.199988 v 1.146968 1.448418 -0.200000 v 1.722785 1.052430 -0.200000 v 1.370393 1.450234 -0.200000 v 1.275934 -0.840328 -0.200000 v 0.818187 -0.469771 -0.200000 v 2.040666 0.111500 -0.200000 v 1.728237 0.603761 -0.200000 v 2.042483 0.180526 -0.200000 v 1.977093 0.525652 -0.200000 vt 0.654632 0.700000 vt 1.000000 0.700000 vt 1.000000 1.000000 vt 0.654632 1.000000 vt 0.654632 0.000000 vt 1.000000 0.000000 vt 0.000000 0.000000 vt 0.608316 0.000000 vt 0.608316 0.700000 vt 0.000000 0.700000 vt 0.608316 1.000000 vt 0.000000 1.000000 vt 1.000000 1.000000 vt 0.654632 1.000000 vt 1.000000 1.000000 vt 0.654632 1.000000 vt 1.000000 1.000000 vt 0.654632 1.000000 vt 1.000000 1.000000 vt 0.654632 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 0.608316 1.000000 vt 0.000000 1.000000 vt 0.608316 1.000000 vt 0.000000 1.000000 vt 0.608316 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 0.654632 0.700000 vt 0.654632 1.000000 vt 1.000000 1.000000 vt 1.000000 0.700000 vt 0.654632 0.000000 vt 1.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 0.700000 vt 0.608316 0.700000 vt 0.608316 0.000000 vt 0.000000 1.000000 vt 0.608316 1.000000 vt 0.654632 1.000000 vt 1.000000 1.000000 vt 0.654632 1.000000 vt 1.000000 1.000000 vt 0.654632 1.000000 vt 1.000000 1.000000 vt 0.654632 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 0.000000 1.000000 vt 0.608316 1.000000 vt 0.000000 1.000000 vt 0.608316 1.000000 vt 0.000000 1.000000 vt 0.608316 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 0.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 0.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vt 1.000000 1.000000 vn 0.0000 -0.0000 1.0000 vn 0.0000 0.0000 -1.0000 vn 0.0000 -0.0001 -1.0000 vn 0.0001 0.0003 -1.0000 vn -1.0000 0.0023 0.0000 vn 0.0014 -1.0000 0.0000 vn 1.0000 -0.0000 0.0000 vn -1.0000 -0.0049 0.0000 vn -0.0021 -1.0000 0.0000 vn -0.0025 1.0000 0.0000 vn 0.9997 0.0262 0.0000 vn 0.0000 -1.0000 0.0000 vn -1.0000 0.0075 0.0000 vn 0.7549 -0.6558 0.0000 vn -0.9999 0.0148 0.0000 vn -0.8749 -0.4843 0.0000 vn 0.6083 0.7937 0.0000 vn -0.8750 -0.4842 0.0000 vn -0.0820 0.9966 0.0000 vn 0.2997 0.9540 0.0000 vn -0.8884 -0.4590 0.0000 vn 0.2648 0.9643 0.0000 vn 0.9808 -0.1952 0.0000 vn -0.7775 0.6288 0.0000 vn 0.9999 0.0150 0.0000 vn -0.8533 -0.5215 0.0000 vn 0.8789 0.4770 0.0000 vn -0.8544 -0.5197 0.0000 vn 0.0008 1.0000 0.0000 vn 0.8795 0.4759 0.0000 vn 0.9998 0.0192 0.0000 vn -0.8569 -0.5156 0.0000 vn -0.8402 0.5423 0.0000 vn 0.8372 -0.5469 0.0000 vn -0.8393 0.5437 0.0000 vn -0.6423 -0.7664 0.0000 vn 0.4264 0.9045 0.0000 vn 0.2686 -0.9633 0.0000 vn 0.0995 -0.9950 0.0000 vn 0.9954 -0.0958 0.0000 vn 0.9983 0.0587 0.0000 vn 0.0099 -1.0000 0.0000 vn 0.6613 0.7501 0.0000 vn -0.2028 -0.9792 0.0000 vn -0.9285 0.3714 0.0000 vn 0.4284 0.9036 0.0000 vn -0.2713 0.9625 0.0000 vn 0.8217 -0.5699 0.0000 vn 0.4315 -0.9021 0.0000 vn -0.4237 -0.9058 0.0000 vn 0.1088 0.9941 0.0000 vn 0.9222 0.3866 0.0000 vn 0.8709 -0.4915 0.0000 vn -0.8406 0.5417 0.0000 vn 0.0189 0.9998 0.0000 vn -0.9945 0.1049 0.0000 vn -0.8578 0.5140 0.0000 vn -0.4434 0.8963 0.0000 vn 0.9895 0.1443 0.0000 vn 0.8183 -0.5747 0.0000 vn 0.5366 0.8438 0.0000 vn -0.4687 -0.8833 0.0000 vn -0.9991 0.0434 0.0000 vn -0.5745 -0.8185 0.0000 vn -0.6292 -0.7772 0.0000 vn 0.7613 -0.6484 0.0000 vn -0.8162 0.5778 0.0000 vn 0.7485 0.6631 0.0000 vn 0.9888 -0.1492 0.0000 vn -0.0081 1.0000 0.0000 vn 0.9997 -0.0263 0.0000 vn 0.9825 0.1862 0.0000 vn 0.7796 -0.6263 0.0000 vn -0.7628 0.6466 0.0000 vn 0.2995 0.9541 0.0000 usemtl Berzerker s off f 12/1/1 6/2/1 4/3/1 11/4/1 f 10/5/1 2/6/1 6/2/1 12/1/1 f 1/7/1 7/8/1 9/9/1 5/10/1 f 5/10/1 9/9/1 8/11/1 3/12/1 f 7/8/1 10/5/1 12/1/1 9/9/1 f 11/4/1 4/3/1 13/13/1 14/14/1 f 14/14/1 13/13/1 15/15/1 16/16/1 f 16/16/1 15/15/1 17/17/1 18/18/1 f 18/18/1 17/17/1 19/19/1 20/20/1 f 15/15/1 13/13/1 21/21/1 22/22/1 f 3/12/1 8/11/1 24/23/1 23/24/1 f 23/24/1 24/23/1 26/25/1 25/26/1 f 25/26/1 26/25/1 28/27/1 27/28/1 f 25/26/1 27/28/1 30/29/1 29/30/1 f 29/30/1 30/29/1 32/31/1 31/32/1 f 31/32/1 32/31/1 34/33/1 33/34/1 f 33/34/1 34/33/1 36/35/1 35/36/1 f 35/36/1 36/35/1 38/37/1 37/38/1 f 32/31/1 30/29/1 39/39/1 40/40/1 f 43/41/1 44/42/1 42/43/1 41/44/1 f 43/41/1 41/44/1 45/45/1 46/46/1 f 49/47/1 50/48/1 52/49/1 51/50/1 f 47/51/1 48/52/1 50/48/1 49/47/1 f 57/53/1 58/54/1 60/55/1 59/56/1 f 53/57/1 54/58/1 56/59/1 55/60/1 f 53/57/1 55/60/1 58/54/1 57/53/1 f 62/61/1 61/62/1 63/63/1 64/64/1 f 64/64/1 63/63/1 65/65/1 66/66/1 f 70/67/1 69/68/1 71/69/1 72/70/1 f 68/71/1 67/72/1 69/68/1 70/67/1 f 84/73/2 83/74/2 76/75/2 78/76/2 f 82/77/2 84/73/2 78/76/2 74/78/2 f 73/79/2 77/80/2 81/81/2 79/82/2 f 77/80/2 75/83/2 80/84/2 81/81/2 f 79/82/2 81/81/2 84/73/2 82/77/2 f 83/74/2 86/85/2 85/86/2 76/75/2 f 86/85/2 88/87/2 87/88/2 85/86/2 f 88/87/2 90/89/2 89/90/2 87/88/2 f 90/89/2 92/91/2 91/92/2 89/90/2 f 87/88/2 94/93/2 93/94/2 85/86/2 f 75/83/2 95/95/2 96/96/2 80/84/2 f 95/95/2 97/97/2 98/98/2 96/96/2 f 97/97/2 99/99/2 100/100/2 98/98/2 f 97/97/2 101/101/2 102/102/2 99/99/2 f 101/101/2 103/103/2 104/104/2 102/102/2 f 103/103/2 105/105/2 106/106/2 104/104/2 f 105/105/2 107/107/2 108/108/2 106/106/2 f 107/107/2 109/109/2 110/110/2 108/108/2 f 104/104/2 112/111/2 111/112/2 102/102/2 f 115/113/3 113/114/3 114/115/3 116/116/3 f 115/113/4 118/117/4 117/118/4 113/114/4 f 121/119/2 123/120/2 124/121/2 122/122/2 f 119/123/2 121/119/2 122/122/2 120/124/2 f 129/125/2 131/126/2 132/127/2 130/128/2 f 125/129/2 127/130/2 128/131/2 126/132/2 f 125/129/2 129/125/2 130/128/2 127/130/2 f 134/133/2 136/134/2 135/135/2 133/136/2 f 136/134/2 138/137/2 137/138/2 135/135/2 f 142/139/2 144/140/2 143/141/2 141/142/2 f 140/143/2 142/139/2 141/142/2 139/144/2 f 1/7/5 5/10/5 77/80/5 73/79/5 f 2/6/6 10/5/6 82/77/6 74/78/6 f 4/3/7 6/2/7 78/76/7 76/75/7 f 5/10/8 3/12/8 75/83/8 77/80/8 f 6/2/7 2/6/7 74/78/7 78/76/7 f 7/8/9 1/7/9 73/79/9 79/82/9 f 9/9/10 12/1/10 84/73/10 81/81/10 f 8/11/11 9/9/11 81/81/11 80/84/11 f 10/5/12 7/8/12 79/82/12 82/77/12 f 12/1/13 11/4/13 83/74/13 84/73/13 f 13/13/14 4/3/14 76/75/14 85/86/14 f 11/4/15 14/14/15 86/85/15 83/74/15 f 14/14/16 16/16/16 88/87/16 86/85/16 f 17/17/17 15/15/17 87/88/17 89/90/17 f 16/16/18 18/18/18 90/89/18 88/87/18 f 20/20/19 19/19/19 91/92/19 92/91/19 f 19/19/20 17/17/20 89/90/20 91/92/20 f 18/18/21 20/20/21 92/91/21 90/89/21 f 22/22/22 21/21/22 93/94/22 94/93/22 f 21/21/23 13/13/23 85/86/23 93/94/23 f 15/15/24 22/22/24 94/93/24 87/88/24 f 24/23/25 8/11/25 80/84/25 96/96/25 f 3/12/26 23/24/26 95/95/26 75/83/26 f 26/25/27 24/23/27 96/96/27 98/98/27 f 23/24/28 25/26/28 97/97/28 95/95/28 f 27/28/29 28/27/29 100/100/29 99/99/29 f 28/27/30 26/25/30 98/98/30 100/100/30 f 30/29/31 27/28/31 99/99/31 102/102/31 f 25/26/32 29/30/32 101/101/32 97/97/32 f 29/30/33 31/32/33 103/103/33 101/101/33 f 34/33/34 32/31/34 104/104/34 106/106/34 f 31/32/35 33/34/35 105/105/35 103/103/35 f 36/35/36 34/33/36 106/106/36 108/108/36 f 33/34/37 35/36/37 107/107/37 105/105/37 f 37/38/38 38/37/38 110/110/38 109/109/38 f 38/37/39 36/35/39 108/108/39 110/110/39 f 35/36/40 37/38/40 109/109/40 107/107/40 f 40/40/41 39/39/41 111/112/41 112/111/41 f 39/39/42 30/29/42 102/102/42 111/112/42 f 32/31/43 40/40/43 112/111/43 104/104/43 f 46/46/44 45/45/44 117/118/44 118/117/44 f 45/45/45 41/44/45 113/114/45 117/118/45 f 42/43/46 44/42/46 116/116/46 114/115/46 f 41/44/47 42/43/47 114/115/47 113/114/47 f 44/42/48 43/41/48 115/113/48 116/116/48 f 43/41/49 46/46/49 118/117/49 115/113/49 f 48/52/50 47/51/50 119/123/50 120/124/50 f 51/50/51 52/49/51 124/121/51 123/120/51 f 52/49/52 50/48/52 122/122/52 124/121/52 f 50/48/53 48/52/53 120/124/53 122/122/53 f 47/51/54 49/47/54 121/119/54 119/123/54 f 49/47/55 51/50/55 123/120/55 121/119/55 f 54/58/56 53/57/56 125/129/56 126/132/56 f 59/56/57 60/55/57 132/127/57 131/126/57 f 60/55/58 58/54/58 130/128/58 132/127/58 f 55/60/59 56/59/59 128/131/59 127/130/59 f 56/59/60 54/58/60 126/132/60 128/131/60 f 58/54/61 55/60/61 127/130/61 130/128/61 f 53/57/62 57/53/62 129/125/62 125/129/62 f 57/53/63 59/56/63 131/126/63 129/125/63 f 61/62/64 62/61/64 134/133/64 133/136/64 f 67/72/65 68/71/65 140/143/65 139/144/65 f 63/63/66 61/62/66 133/136/66 135/135/66 f 62/61/67 64/64/67 136/134/67 134/133/67 f 66/66/68 65/65/68 137/138/68 138/137/68 f 65/65/69 63/63/69 135/135/69 137/138/69 f 64/64/70 66/66/70 138/137/70 136/134/70 f 71/69/71 69/68/71 141/142/71 143/141/71 f 72/70/72 71/69/72 143/141/72 144/140/72 f 69/68/73 67/72/73 139/144/73 141/142/73 f 68/71/74 70/67/74 142/139/74 140/143/74 f 70/67/75 72/70/75 144/140/75 142/139/75
{ "pile_set_name": "Github" }
/* clang-format off */ /* * @brief Common SystemInit function for LPC17xx/40xx chips * * @note * Copyright(C) NXP Semiconductors, 2013 * All rights reserved. * * @par * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * LPC products. This software is supplied "AS IS" without any warranties of * any kind, and NXP Semiconductors and its licensor disclaim any and * all warranties, express or implied, including all implied warranties of * merchantability, fitness for a particular purpose and non-infringement of * intellectual property rights. NXP Semiconductors assumes no responsibility * or liability for the use of the software, conveys no license or rights under any * patent, copyright, mask work right, or any other intellectual property rights in * or to any products. NXP Semiconductors reserves the right to make changes * in the software without notification. NXP Semiconductors also makes no * representation or warranty that such application will be suitable for the * specified use without further testing or modification. * * @par * Permission to use, copy, modify, and distribute this software and its * documentation is hereby granted, under NXP Semiconductors' and its * licensor's relevant copyrights in the software, without fee, provided that it * is used in conjunction with NXP Semiconductors microcontrollers. This * copyright, permission, and disclaimer notice must appear in all copies of * this code. */ #include "board.h" /***************************************************************************** * Private types/enumerations/variables ****************************************************************************/ /***************************************************************************** * Public types/enumerations/variables ****************************************************************************/ /***************************************************************************** * Private functions ****************************************************************************/ /***************************************************************************** * Public functions ****************************************************************************/ /* Set up and initialize hardware prior to call to main */ void SystemInit(void) { unsigned int *pSCB_VTOR = (unsigned int *) 0xE000ED08; #if defined(__IAR_SYSTEMS_ICC__) extern void *__vector_table; *pSCB_VTOR = (unsigned int) &__vector_table; #elif defined(__CODE_RED) extern void *g_pfnVectors; *pSCB_VTOR = (unsigned int) &g_pfnVectors; #elif defined(__ARMCC_VERSION) extern void *__Vectors; *pSCB_VTOR = (unsigned int) &__Vectors; #endif #if defined(__FPU_PRESENT) && __FPU_PRESENT == 1 fpuInit(); #endif #if defined(NO_BOARD_LIB) /* Chip specific SystemInit */ Chip_SystemInit(); #else /* Setup system clocking and muxing */ Board_SystemInit(); #endif }
{ "pile_set_name": "Github" }
#!/bin/sh # Exit script wit ERRORLEVEL if any command fails set -e INSTALLOPTS="" if [ "$1" == "production" ]; then INSTALLOPTS="-a" fi # Clear vendor cache rm -rf ../vendor # Setup composer # Hash update information - https://getcomposer.org/download/ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file('sha384', 'composer-setup.php') === '795f976fe0ebd8b75f26a6dd68f78fd3453ce79f32ecb33e7fd087d39bfeb978342fb73ac986cd4f54edd0dc902601dc') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');" # Optimise for package install speed php composer.phar -n global require -n "hirak/prestissimo" # Grab dependencies php composer.phar install $INSTALLOPTS --ignore-platform-reqs
{ "pile_set_name": "Github" }
defmodule HexpmWeb.API.ReleaseControllerTest do use HexpmWeb.ConnCase, async: true alias Hexpm.Accounts.AuditLog alias Hexpm.Repository.{Package, RegistryBuilder, Release, Repository} setup do user = insert(:user) repository = insert(:repository) package = insert(:package, package_owners: [build(:package_owner, user: user)]) release = insert(:release, package: package, version: "0.0.1", has_docs: true, meta: build(:release_metadata, app: package.name) ) %{ user: user, repository: repository, organization: repository.organization, package: package, release: release } end describe "POST /api/packages/:name/releases" do test "create release and new package", %{user: user} do meta = %{ name: Fake.sequence(:package), version: "1.0.0", description: "Domain-specific language." } conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/packages/#{meta.name}/releases", create_tar(meta)) result = json_response(conn, 201) assert result["url"] =~ "api/packages/#{meta.name}/releases/1.0.0" assert result["html_url"] =~ "packages/#{meta.name}/1.0.0" assert result["publisher"]["username"] == user.username package = Hexpm.Repo.get_by!(Package, name: meta.name) package_owner = Hexpm.Repo.one!(assoc(package, :owners)) assert package_owner.id == user.id assert Hexpm.Store.get(:repo_bucket, "packages/#{package.name}", []) log = Hexpm.Repo.one!(AuditLog) assert log.user_id == user.id assert log.organization_id == nil assert log.action == "release.publish" assert log.params["package"]["name"] == meta.name assert log.params["release"]["version"] == "1.0.0" end test "update package", %{user: user, package: package} do meta = %{name: package.name, version: "1.0.0", description: "awesomeness"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/packages/#{package.name}/releases", create_tar(meta)) assert conn.status == 201 result = json_response(conn, 201) assert result["url"] =~ "/api/packages/#{package.name}/releases/1.0.0" assert result["html_url"] =~ "packages/#{package.name}/1.0.0" assert Hexpm.Repo.get_by(Package, name: package.name).meta.description == "awesomeness" assert Hexpm.Store.get(:repo_bucket, "packages/#{package.name}", []) end test "update package fails when version is invalid", %{user: user, package: package} do meta = %{name: package.name, version: "1.0-dev", description: "not-so-awesome"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/packages/#{package.name}/releases", create_tar(meta)) assert conn.status == 422 result = json_response(conn, 422) assert result["message"] =~ "Validation error" assert result["errors"] == %{"version" => "is invalid SemVer"} end test "create release checks if package name is correct", %{user: user, package: package} do meta = %{name: Fake.sequence(:package), version: "0.1.0", description: "description"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/packages/#{package.name}/releases", create_tar(meta)) result = json_response(conn, 422) assert result["errors"]["name"] == "metadata does not match package name" meta = %{name: package.name, version: "1.0.0", description: "description"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/packages/#{Fake.sequence(:package)}/releases", create_tar(meta)) # Bad error message but /api/publish solves it # https://github.com/hexpm/hexpm/issues/489 result = json_response(conn, 422) assert result["errors"]["name"] == "has already been taken" end end describe "POST /api/publish" do test "create release and new package", %{user: user} do meta = %{ name: Fake.sequence(:package), version: "1.0.0", description: "Domain-specific language." } conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) result = json_response(conn, 201) assert result["url"] =~ "api/packages/#{meta.name}/releases/1.0.0" assert result["html_url"] =~ "packages/#{meta.name}/1.0.0" package = Hexpm.Repo.get_by!(Package, name: meta.name) package_owner = Hexpm.Repo.one!(assoc(package, :owners)) assert package_owner.id == user.id log = Hexpm.Repo.one!(AuditLog) assert log.user_id == user.id assert log.organization_id == nil assert log.action == "release.publish" assert log.params["package"]["name"] == meta.name assert log.params["release"]["version"] == "1.0.0" end test "update package", %{user: user, package: package} do meta = %{name: package.name, version: "1.0.0", description: "awesomeness"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) assert conn.status == 201 result = json_response(conn, 201) assert result["url"] =~ "/api/packages/#{package.name}/releases/1.0.0" assert result["html_url"] =~ "packages/#{package.name}/1.0.0" assert Hexpm.Repo.get_by(Package, name: package.name).meta.description == "awesomeness" end test "create release authorizes existing package", %{package: package} do other_user = insert(:user) meta = %{name: package.name, version: "0.1.0", description: "description"} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(other_user)) |> post("api/publish", create_tar(meta)) |> json_response(403) end test "create release authorizes" do meta = %{name: Fake.sequence(:package), version: "0.1.0", description: "description"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", "WRONG") |> post("api/publish", create_tar(meta)) assert conn.status == 401 assert get_resp_header(conn, "www-authenticate") == ["Basic realm=hex"] end test "update package authorizes", %{package: package} do meta = %{name: package.name, version: "1.0.0", description: "Domain-specific language."} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", "WRONG") |> post("api/publish", create_tar(meta)) assert conn.status == 401 assert get_resp_header(conn, "www-authenticate") == ["Basic realm=hex"] end test "organization owned package", %{user: user, organization: organization} do package = insert( :package, package_owners: [build(:package_owner, user: organization.user)] ) meta = %{name: package.name, version: "1.0.0", description: "Domain-specific language."} insert(:organization_user, organization: organization, user: user, role: "write") build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) |> json_response(201) end test "organization owned package authorizes", %{user: user, organization: organization} do package = insert( :package, package_owners: [build(:package_owner, user: organization.user)] ) meta = %{name: package.name, version: "1.0.0", description: "Domain-specific language."} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) |> json_response(403) end test "organization owned package requries write permission", %{ user: user, organization: organization } do package = insert( :package, package_owners: [build(:package_owner, user: organization.user)] ) meta = %{name: package.name, version: "1.0.0", description: "Domain-specific language."} insert(:organization_user, organization: organization, user: user, role: "read") build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) |> json_response(403) end test "organization can publish package", %{organization: organization} do package = insert( :package, package_owners: [build(:package_owner, user: organization.user)] ) meta = %{name: package.name, version: "1.0.0", description: "Domain-specific language."} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(organization)) |> post("api/publish", create_tar(meta)) |> json_response(201) end test "create package validates", %{user: user, package: package} do meta = %{name: package.name, version: "1.0.0", links: "invalid", description: "description"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) result = json_response(conn, 422) assert result["errors"]["meta"]["links"] == "expected type map(string)" end test "create package casts proplist metadata", %{user: user, package: package} do meta = %{ name: package.name, version: "1.0.0", links: %{"link" => "http://localhost"}, extra: %{"key" => "value"}, description: "description" } conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) json_response(conn, 201) package = Hexpm.Repo.get_by!(Package, name: package.name) assert package.meta.links == %{"link" => "http://localhost"} assert package.meta.extra == %{"key" => "value"} end test "create releases", %{user: user} do meta = %{ name: Fake.sequence(:package), app: "other", version: "0.0.1", description: "description" } conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/packages/#{meta.name}/releases", create_tar(meta)) result = json_response(conn, 201) assert result["meta"]["app"] == "other" assert result["url"] =~ "/api/packages/#{meta.name}/releases/0.0.1" assert result["html_url"] =~ "packages/#{meta.name}/0.0.1" meta = %{name: meta.name, version: "0.0.2", description: "description"} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) |> json_response(201) package = Hexpm.Repo.get_by!(Package, name: meta.name) package_id = package.id assert [ %Release{package_id: ^package_id, version: %Version{major: 0, minor: 0, patch: 2}}, %Release{package_id: ^package_id, version: %Version{major: 0, minor: 0, patch: 1}} ] = Release.all(package) |> Hexpm.Repo.all() |> Release.sort() Hexpm.Repo.get_by!(assoc(package, :releases), version: "0.0.1") end test "create release also creates package", %{user: user} do meta = %{name: Fake.sequence(:package), version: "1.0.0", description: "Web framework"} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) |> json_response(201) Hexpm.Repo.get_by!(Package, name: meta.name) end test "update release", %{user: user} do meta = %{name: Fake.sequence(:package), version: "0.0.1", description: "description"} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/packages/#{meta.name}/releases", create_tar(meta)) |> json_response(201) build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish?replace=true", create_tar(meta)) |> json_response(200) package = Hexpm.Repo.get_by!(Package, name: meta.name) Hexpm.Repo.get_by!(assoc(package, :releases), version: "0.0.1") assert [%AuditLog{action: "release.publish"}, %AuditLog{action: "release.publish"}] = Hexpm.Repo.all(AuditLog) end test "update release with different and unresolved requirements", %{ user: user, package: package } do name = Fake.sequence(:package) reqs = [%{name: package.name, requirement: "~> 0.0.1", app: "app", optional: false}] meta = %{name: name, version: "0.0.1", requirements: reqs, description: "description"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) result = json_response(conn, 201) assert result["requirements"] == %{ package.name => %{"app" => "app", "optional" => false, "requirement" => "~> 0.0.1"} } # Disabled because of resolver bug # re-publish with unresolved requirement # reqs = [%{name: package.name, requirement: "~> 9.0", app: "app", optional: false}] # meta = %{name: name, version: "0.0.1", requirements: reqs, description: "description"} # conn = # build_conn() # |> put_req_header("content-type", "application/octet-stream") # |> put_req_header("authorization", key_for(user)) # |> post("api/packages/#{meta.name}/releases", create_tar(meta)) # # result = json_response(conn, 422) # assert result["errors"]["requirements"] =~ ~s(Failed to use "#{package.name}") end test "default to replace release if repalce option is not set", %{ user: user, package: package, release: release } do datetime = NaiveDateTime.utc_now() |> NaiveDateTime.add(-36000, :second) |> DateTime.from_naive!("Etc/UTC") Ecto.Changeset.change(package, inserted_at: datetime) |> Hexpm.Repo.update!() Ecto.Changeset.change(release, inserted_at: datetime) |> Hexpm.Repo.update!() meta = %{name: package.name, version: "0.0.1", description: "description"} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) |> json_response(200) end test "can update release within package one hour grace period", %{ user: user, package: package, release: release } do datetime = NaiveDateTime.utc_now() |> NaiveDateTime.add(-36000, :second) |> DateTime.from_naive!("Etc/UTC") Ecto.Changeset.change(package, inserted_at: datetime) |> Hexpm.Repo.update!() Ecto.Changeset.change(release, inserted_at: datetime) |> Hexpm.Repo.update!() meta = %{name: package.name, version: "0.0.1", description: "description"} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish?replace=true", create_tar(meta)) |> json_response(200) end test "cannot update release after grace period", %{ user: user, package: package, release: release } do Ecto.Changeset.change(package, inserted_at: %{DateTime.utc_now() | year: 2000}) |> Hexpm.Repo.update!() Ecto.Changeset.change(release, inserted_at: %{DateTime.utc_now() | year: 2000}) |> Hexpm.Repo.update!() meta = %{name: package.name, version: "0.0.1", description: "description"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish?replace=false", create_tar(meta)) result = json_response(conn, 422) assert result["errors"]["inserted_at"] == "can only modify a release up to one hour after creation" end test "create releases with requirements", %{user: user, package: package} do reqs = [%{name: package.name, requirement: "~> 0.0.1", app: "app", optional: false}] meta = %{ name: Fake.sequence(:package), version: "0.0.1", requirements: reqs, description: "description" } conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) result = json_response(conn, 201) assert result["requirements"] == %{ package.name => %{"app" => "app", "optional" => false, "requirement" => "~> 0.0.1"} } release = Hexpm.Repo.get_by!(Package, name: meta.name) |> assoc(:releases) |> Hexpm.Repo.get_by!(version: "0.0.1") |> Hexpm.Repo.preload(:requirements) assert [%{app: "app", requirement: "~> 0.0.1", optional: false}] = release.requirements end test "create releases with requirements validates requirement", %{ user: user, package: package } do reqs = [%{name: package.name, requirement: "~> invalid", app: "app", optional: false}] meta = %{ name: Fake.sequence(:package), version: "0.0.1", requirements: reqs, description: "description" } conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) result = json_response(conn, 422) assert result["errors"]["requirements"][package.name] == ~s(invalid requirement: "~> invalid") end test "create releases with requirements validates package name", %{user: user} do reqs = [%{name: "nonexistant_package", requirement: "~> 1.0", app: "app", optional: false}] meta = %{ name: Fake.sequence(:package), version: "0.0.1", requirements: reqs, description: "description" } conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) result = json_response(conn, 422) assert result["errors"]["requirements"]["nonexistant_package"] == "package does not exist in repository \"hexpm\"" end # Disabled because of resolver bug @tag :skip test "create releases with requirements validates resolution", %{user: user, package: package} do reqs = [%{name: package.name, requirement: "~> 1.0", app: "app", optional: false}] meta = %{ name: Fake.sequence(:package), version: "0.1.0", requirements: reqs, description: "description" } conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) result = json_response(conn, 422) assert result["errors"]["requirements"] =~ ~s(Failed to use "#{package.name}" because) end # Disabled because we stopped updating old registry @tag :skip test "create release updates old registry", %{user: user, package: package} do RegistryBuilder.full(Repository.hexpm()) registry_before = Hexpm.Store.get(:repo_bucket, "registry.ets.gz", []) reqs = [%{name: package.name, app: "app", requirement: "~> 0.0.1", optional: false}] meta = %{ name: Fake.sequence(:package), app: "app", version: "0.0.1", requirements: reqs, description: "description" } build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) |> json_response(201) registry_after = Hexpm.Store.get(:repo_bucket, "registry.ets.gz", []) assert registry_before != registry_after end test "create release updates new registry", %{user: user, package: package} do reqs = [%{name: package.name, app: "app", requirement: "~> 0.0.1", optional: false}] meta = %{ name: Fake.sequence(:package), app: "app", version: "0.0.1", requirements: reqs, description: "description" } build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish", create_tar(meta)) |> json_response(201) assert Hexpm.Store.get(:repo_bucket, "packages/#{meta.name}", []) end end describe "POST /api/:repository/packages/:name/releases" do test "new package authorizes", %{user: user, repository: repository} do meta = %{ name: Fake.sequence(:package), version: "1.0.0", description: "Domain-specific language." } build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post( "api/repos/#{repository.name}/packages/#{meta.name}/releases", create_tar(meta) ) |> json_response(403) end test "existing package authorizes", %{user: user, repository: repository} do package = insert( :package, repository_id: repository.id, package_owners: [build(:package_owner, user: user)] ) meta = %{name: package.name, version: "1.0.0", description: "Domain-specific language."} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post( "api/repos/#{repository.name}/packages/#{meta.name}/releases", create_tar(meta) ) |> json_response(403) end end describe "POST /api/repos/:repository/publish" do test "new package authorizes", %{user: user, repository: repository} do meta = %{ name: Fake.sequence(:package), version: "1.0.0", description: "Domain-specific language." } build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/repos/#{repository.name}/publish", create_tar(meta)) |> json_response(403) end test "existing package authorizes", %{user: user, repository: repository} do package = insert( :package, repository_id: repository.id, package_owners: [build(:package_owner, user: user)] ) meta = %{name: package.name, version: "1.0.0", description: "Domain-specific language."} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/repos/#{repository.name}/publish", create_tar(meta)) |> json_response(403) end test "new package requries write permission", %{user: user, repository: repository} do insert(:organization_user, organization: repository.organization, user: user, role: "read") meta = %{ name: Fake.sequence(:package), version: "1.0.0", description: "Domain-specific language." } build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/repos/#{repository.name}/publish", create_tar(meta)) |> json_response(403) refute Hexpm.Repo.get_by(Package, name: meta.name) end test "organization needs to have active billing", %{user: user} do repository = insert(:repository, organization: build(:organization, billing_active: false)) insert(:organization_user, organization: repository.organization, user: user, role: "write") meta = %{ name: Fake.sequence(:package), version: "1.0.0", description: "Domain-specific language." } build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/repos/#{repository.name}/publish", create_tar(meta)) |> json_response(403) refute Hexpm.Repo.get_by(Package, name: meta.name) end test "new package", %{user: user, repository: repository} do insert(:organization_user, organization: repository.organization, user: user, role: "write") meta = %{ name: Fake.sequence(:package), version: "1.0.0", description: "Domain-specific language." } result = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/repos/#{repository.name}/publish", create_tar(meta)) |> json_response(201) assert result["url"] =~ "api/repos/#{repository.name}/packages/#{meta.name}/releases/1.0.0" package = Hexpm.Repo.get_by!(Package, name: meta.name) assert package.repository_id == repository.id end test "existing package", %{user: user, repository: repository} do package = insert( :package, repository_id: repository.id, package_owners: [build(:package_owner, user: user)] ) insert(:organization_user, organization: repository.organization, user: user) meta = %{name: package.name, version: "1.0.0", description: "Domain-specific language."} result = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/repos/#{repository.name}/publish", create_tar(meta)) |> json_response(201) assert result["url"] =~ "api/repos/#{repository.name}/packages/#{meta.name}/releases/1.0.0" package = Hexpm.Repo.get_by!(Package, name: meta.name) assert package.repository_id == repository.id end test "can update private package after grace period", %{ user: user, repository: repository } do package = insert( :package, package_owners: [build(:package_owner, user: user)], repository_id: repository.id ) insert( :release, package: package, version: "0.0.1", inserted_at: %{DateTime.utc_now() | year: 2000} ) insert(:organization_user, organization: repository.organization, user: user) meta = %{name: package.name, version: "0.0.1", description: "description"} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/repos/#{repository.name}/publish?replace=true", create_tar(meta)) |> json_response(200) end test "cannot update release after grace period even when given replace flag", %{ user: user, package: package, release: release } do Ecto.Changeset.change(package, inserted_at: %{DateTime.utc_now() | year: 2000}) |> Hexpm.Repo.update!() Ecto.Changeset.change(release, inserted_at: %{DateTime.utc_now() | year: 2000}) |> Hexpm.Repo.update!() meta = %{name: package.name, version: "0.0.1", description: "description"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/publish?replace=true", create_tar(meta)) result = json_response(conn, 422) assert result["errors"]["inserted_at"] == "can only modify a release up to one hour after creation" end test "deafult to replace private package after grace period if replace param is not set", %{ user: user, repository: repository } do package = insert( :package, package_owners: [build(:package_owner, user: user)], repository_id: repository.id ) insert( :release, package: package, version: "0.0.1", inserted_at: %{DateTime.utc_now() | year: 2000} ) insert(:organization_user, organization: repository.organization, user: user) meta = %{name: package.name, version: "0.0.1", description: "description"} build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/repos/#{repository.name}/publish", create_tar(meta)) |> json_response(200) end test "cannot update private package after grace period if replace param is set to false", %{ user: user, repository: repository } do package = insert( :package, package_owners: [build(:package_owner, user: user)], repository_id: repository.id ) insert( :release, package: package, version: "0.0.1", inserted_at: %{DateTime.utc_now() | year: 2000} ) insert(:organization_user, organization: repository.organization, user: user) meta = %{name: package.name, version: "0.0.1", description: "description"} conn = build_conn() |> put_req_header("content-type", "application/octet-stream") |> put_req_header("authorization", key_for(user)) |> post("api/repos/#{repository.name}/publish?replace=false", create_tar(meta)) result = json_response(conn, 422) assert result["errors"]["inserted_at"] == "must include the --replace flag to update an existing release" end end describe "DELETE /api/packages/:name/releases/:version" do test "delete release validates release age", %{user: user, package: package, release: release} do Ecto.Changeset.change(package, inserted_at: %{DateTime.utc_now() | year: 2000}) |> Hexpm.Repo.update!() Ecto.Changeset.change(release, inserted_at: %{DateTime.utc_now() | year: 2000}) |> Hexpm.Repo.update!() conn = build_conn() |> put_req_header("authorization", key_for(user)) |> delete("api/packages/#{package.name}/releases/0.0.1") result = json_response(conn, 422) assert result["errors"]["inserted_at"] == "can only delete a release up to one hour after creation" end test "delete package validates dependants", %{user: user, package: package} do package2 = insert(:package) release2 = insert(:release, package: package2, version: "0.0.1") insert(:requirement, release: release2, dependency: package, requirement: "~> 0.0.1") result = build_conn() |> put_req_header("authorization", key_for(user)) |> delete("api/packages/#{package.name}/releases/0.0.1") |> json_response(422) assert result["errors"]["name"] == "you cannot delete this package because other packages depend on it" end test "delete release", %{user: user, package: package, release: release} do Ecto.Changeset.change(release, inserted_at: DateTime.add(DateTime.utc_now(), 60, :second)) |> Hexpm.Repo.update!() RegistryBuilder.full(Repository.hexpm()) build_conn() |> put_req_header("authorization", key_for(user)) |> delete("api/packages/#{package.name}/releases/0.0.1") |> response(204) refute Hexpm.Repo.get_by(Package, name: package.name) refute Hexpm.Repo.get_by(assoc(package, :releases), version: "0.0.1") refute Hexpm.Store.get(:repo_bucket, "packages/#{package.name}", []) [log] = Hexpm.Repo.all(AuditLog) assert log.user_id == user.id assert log.action == "release.revert" assert log.params["package"]["name"] == package.name assert log.params["release"]["version"] == "0.0.1" end test "delete non-last package release", %{user: user, package: package, release: release} do Ecto.Changeset.change(release, inserted_at: DateTime.add(DateTime.utc_now(), 60, :second)) |> Hexpm.Repo.update!() insert(:release, package: package) RegistryBuilder.full(Repository.hexpm()) build_conn() |> put_req_header("authorization", key_for(user)) |> delete("api/packages/#{package.name}/releases/0.0.1") |> response(204) assert Hexpm.Repo.get_by(Package, name: package.name) refute Hexpm.Repo.get_by(assoc(package, :releases), version: "0.0.1") assert Hexpm.Store.get(:repo_bucket, "packages/#{package.name}", []) end end describe "DELETE /api/repos/:repository/packages/:name/releases/:version" do test "authorizes", %{user: user, repository: repository} do package = insert( :package, repository_id: repository.id, package_owners: [build(:package_owner, user: user)] ) insert(:release, package: package, version: "0.0.1") build_conn() |> put_req_header("authorization", key_for(user)) |> delete("api/repos/#{repository.name}/packages/#{package.name}/releases/0.0.1") |> response(403) assert Hexpm.Repo.get_by(Package, name: package.name) assert Hexpm.Repo.get_by(assoc(package, :releases), version: "0.0.1") end test "organization needs to have active billing", %{user: user} do repository = insert(:repository, organization: build(:organization, billing_active: false)) insert(:organization_user, organization: repository.organization, user: user, role: "write") package = insert( :package, repository_id: repository.id, package_owners: [build(:package_owner, user: user)] ) insert(:release, package: package, version: "0.0.1") build_conn() |> put_req_header("authorization", key_for(user)) |> delete("api/repos/#{repository.name}/packages/#{package.name}/releases/0.0.1") |> response(403) assert Hexpm.Repo.get_by(Package, name: package.name) assert Hexpm.Repo.get_by(assoc(package, :releases), version: "0.0.1") end test "delete release", %{user: user, repository: repository} do package = insert( :package, repository_id: repository.id, package_owners: [build(:package_owner, user: user)] ) insert(:release, package: package, version: "0.0.1") insert(:organization_user, organization: repository.organization, user: user) build_conn() |> put_req_header("authorization", key_for(user)) |> delete("api/repos/#{repository.name}/packages/#{package.name}/releases/0.0.1") |> response(204) refute Hexpm.Repo.get_by(Package, name: package.name) refute Hexpm.Repo.get_by(assoc(package, :releases), version: "0.0.1") end test "can delete private package release after grace period", %{ user: user, repository: repository } do package = insert( :package, repository_id: repository.id, package_owners: [build(:package_owner, user: user)] ) insert( :release, package: package, version: "0.0.1", inserted_at: %{DateTime.utc_now() | year: 2000} ) insert(:organization_user, organization: repository.organization, user: user) build_conn() |> put_req_header("authorization", key_for(user)) |> delete("api/repos/#{repository.name}/packages/#{package.name}/releases/0.0.1") |> response(204) end end describe "GET /api/packages/:name/releases/:version" do test "get release", %{package: package, release: release} do result = build_conn() |> get("api/packages/#{package.name}/releases/#{release.version}") |> json_response(200) assert result["configs"]["mix.exs"] == ~s({:#{package.name}, "~> 0.0.1"}) assert result["url"] == "http://localhost:5000/api/packages/#{package.name}/releases/#{release.version}" assert result["html_url"] == "http://localhost:5000/packages/#{package.name}/#{release.version}" assert result["docs_html_url"] == "http://localhost:5002/#{package.name}/#{release.version}/" assert result["version"] == "#{release.version}" end test "get unknown release", %{package: package} do conn = get(build_conn(), "api/packages/#{package.name}/releases/1.2.3") assert conn.status == 404 conn = get(build_conn(), "api/packages/unknown/releases/1.2.3") assert conn.status == 404 end test "get release with invalid version", %{package: package} do conn = get(build_conn(), "api/packages/#{package.name}/releases/v1.2.3") assert json_response(conn, 400)["message"] == "invalid version: v1.2.3" end test "get release with requirements", %{package: package, release: release} do package2 = insert(:package) insert(:release, package: package2, version: "0.0.1") insert(:requirement, release: release, dependency: package2, requirement: "~> 0.0.1") result = build_conn() |> get("api/packages/#{package.name}/releases/#{release.version}") |> json_response(200) assert result["url"] =~ "/api/packages/#{package.name}/releases/#{release.version}" assert result["html_url"] =~ "/packages/#{package.name}/#{release.version}" assert result["version"] == "#{release.version}" assert result["requirements"][package2.name]["requirement"] == "~> 0.0.1" end end describe "GET /api/repos/:repository/packages/:name/releases/:version" do test "get release authorizes", %{user: user, repository: repository} do package = insert(:package, repository_id: repository.id) insert(:release, package: package, version: "0.0.1") build_conn() |> put_req_header("authorization", key_for(user)) |> get("api/repos/#{repository.name}/packages/#{package.name}/releases/0.0.1") |> json_response(403) end test "get release returns 403 for non-existant repository", %{user: user} do package = insert(:package) insert(:release, package: package, version: "0.0.1") build_conn() |> put_req_header("authorization", key_for(user)) |> get("api/repos/NONEXISTANT_REPOSITORY/packages/#{package.name}/releases/0.0.1") |> json_response(403) end test "get release", %{user: user, repository: repository} do package = insert(:package, repository_id: repository.id) insert(:release, package: package, version: "0.0.1", has_docs: true) insert(:organization_user, organization: repository.organization, user: user) result = build_conn() |> put_req_header("authorization", key_for(user)) |> get("api/repos/#{repository.name}/packages/#{package.name}/releases/0.0.1") |> json_response(200) assert result["url"] == "http://localhost:5000/api/repos/#{repository.name}/packages/#{package.name}/releases/0.0.1" assert result["html_url"] == "http://localhost:5000/packages/#{repository.name}/#{package.name}/0.0.1" assert result["docs_html_url"] == "http://#{repository.name}.localhost:5002/#{package.name}/0.0.1/" assert result["version"] == "0.0.1" end end describe "GET /api/packages/:name/releases/:version/downloads" do setup do user = insert(:user) repository = insert(:repository) package = insert(:package, package_owners: [build(:package_owner, user: user)]) relprev = insert(:release, package: package, version: "0.0.1") release = insert(:release, package: package, version: "0.0.2") insert(:download, release: relprev, downloads: 8, day: ~D[2000-01-01]) insert(:download, release: release, downloads: 1, day: ~D[2000-01-01]) insert(:download, release: release, downloads: 3, day: ~D[2000-02-01]) insert(:download, release: release, downloads: 2, day: ~D[2000-02-07]) insert(:download, release: release, downloads: 4, day: ~D[2000-02-08]) Hexpm.Repo.refresh_view(Hexpm.Repository.ReleaseDownload) %{ user: user, repository: repository, package: package, release: release } end test "get release downloads (all by default)", %{package: package, release: release} do result = build_conn() |> get("api/packages/#{package.name}/releases/#{release.version}") |> json_response(200) assert result["version"] == "#{release.version}" assert result["downloads"] == 10 result = build_conn() |> get("api/packages/#{package.name}/releases/#{release.version}?downloads=all") |> json_response(200) assert result["version"] == "#{release.version}" assert result["downloads"] == 10 result = build_conn() |> get("api/packages/#{package.name}/releases/#{release.version}?downloads=xxx") |> json_response(200) assert result["version"] == "#{release.version}" assert result["downloads"] == 10 end test "get release downloads by day", %{package: package, release: release} do result = build_conn() |> get("api/packages/#{package.name}/releases/#{release.version}?downloads=day") |> json_response(200) assert result["version"] == "#{release.version}" assert result["downloads"] == [ ["2000-01-01", 1], ["2000-02-01", 3], ["2000-02-07", 2], ["2000-02-08", 4] ] end test "get release downloads by month", %{package: package, release: release} do result = build_conn() |> get("api/packages/#{package.name}/releases/#{release.version}?downloads=month") |> json_response(200) assert result["version"] == "#{release.version}" assert result["downloads"] == [ ["2000-01", 1], ["2000-02", 9] ] end end end
{ "pile_set_name": "Github" }
// // TabAViewController.m // SCNavigationController // // Created by 叔 陈 on 15/12/3. // Copyright © 2015年 叔 陈. All rights reserved. // #import "TabAViewController.h" #import "PictureViewController.h" @interface TabAViewController () @end @implementation TabAViewController - (void)viewDidLoad { [super viewDidLoad]; self.title = @"Navi A"; UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame]; imageView.image = [UIImage imageNamed:@"2.jpg"]; [self.view addSubview:imageView]; // Do any additional setup after loading the view. } - (IBAction)ButtonPressed:(id)sender { PictureViewController *vc = [[PictureViewController alloc]init]; [self.navigationController pushViewController:vc animated:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
{ "pile_set_name": "Github" }
public void async_json_array(){ String url = "http://androidquery.appspot.com/test/jsonarray.json"; aq.ajax(url, JSONArray.class, new AjaxCallback<JSONArray>(){ public void callback(String url, JSONArray ja, AjaxStatus status) { showResult(ja, status); } }); }
{ "pile_set_name": "Github" }
{ "animation": { "interpolate": true, "frametime": 16, "frames": [ 0, 1, 2, 3, 2, 1 ] } }
{ "pile_set_name": "Github" }
pushenv("RTM","correct") pushenv("LEWIS","correct")
{ "pile_set_name": "Github" }
/*** * Copyright (C) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. * * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ * * bingrequest.cpp - Simple cmd line application that makes an HTTP GET request to bing searching and outputting * the resulting HTML response body into a file. * * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ****/ #include <cpprest/filestream.h> #include <cpprest/http_client.h> using namespace utility; using namespace web::http; using namespace web::http::client; using namespace concurrency::streams; /* Can pass proxy information via environment variable http_proxy. Example: Linux: export http_proxy=http://192.1.8.1:8080 */ web::http::client::http_client_config client_config_for_proxy() { web::http::client::http_client_config client_config; #ifdef _WIN32 wchar_t* pValue = nullptr; std::unique_ptr<wchar_t, void (*)(wchar_t*)> holder(nullptr, [](wchar_t* p) { free(p); }); size_t len = 0; auto err = _wdupenv_s(&pValue, &len, L"http_proxy"); if (pValue) holder.reset(pValue); if (!err && pValue && len) { std::wstring env_http_proxy_string(pValue, len - 1); #else if (const char* env_http_proxy = std::getenv("http_proxy")) { std::string env_http_proxy_string(env_http_proxy); #endif if (env_http_proxy_string == U("auto")) client_config.set_proxy(web::web_proxy::use_auto_discovery); else client_config.set_proxy(web::web_proxy(env_http_proxy_string)); } return client_config; } #ifdef _WIN32 int wmain(int argc, wchar_t* args[]) #else int main(int argc, char* args[]) #endif { if (argc != 3) { printf("Usage: BingRequest.exe search_term output_file\n"); return -1; } const string_t searchTerm = args[1]; const string_t outputFileName = args[2]; // Open a stream to the file to write the HTTP response body into. auto fileBuffer = std::make_shared<streambuf<uint8_t>>(); file_buffer<uint8_t>::open(outputFileName, std::ios::out) .then([=](streambuf<uint8_t> outFile) -> pplx::task<http_response> { *fileBuffer = outFile; // Create an HTTP request. // Encode the URI query since it could contain special characters like spaces. http_client client(U("http://www.bing.com/"), client_config_for_proxy()); return client.request(methods::GET, uri_builder(U("/search")).append_query(U("q"), searchTerm).to_string()); }) // Write the response body into the file buffer. .then([=](http_response response) -> pplx::task<size_t> { printf("Response status code %u returned.\n", response.status_code()); return response.body().read_to_end(*fileBuffer); }) // Close the file buffer. .then([=](size_t) { return fileBuffer->close(); }) // Wait for the entire response body to be written into the file. .wait(); return 0; }
{ "pile_set_name": "Github" }
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.classfile.attribute.annotation; import proguard.classfile.*; import proguard.classfile.attribute.CodeAttribute; import proguard.classfile.attribute.annotation.target.TargetInfo; import proguard.classfile.attribute.annotation.target.visitor.TargetInfoVisitor; import proguard.classfile.attribute.annotation.visitor.*; /** * Representation of a type annotation. * * @author Eric Lafortune */ public class TypeAnnotation extends Annotation { public TargetInfo targetInfo; public TypePathInfo[] typePath; /** * Creates an uninitialized TypeAnnotation. */ public TypeAnnotation() { } /** * Creates an initialized TypeAnnotation. */ public TypeAnnotation(int u2typeIndex, int u2elementValuesCount, ElementValue[] elementValues, TargetInfo targetInfo, TypePathInfo[] typePath) { super(u2typeIndex, u2elementValuesCount, elementValues); this.targetInfo = targetInfo; this.typePath = typePath; } /** * Applies the given visitor to the target info. */ public void targetInfoAccept(Clazz clazz, TargetInfoVisitor targetInfoVisitor) { // We don't need double dispatching here, since there is only one // type of TypePathInfo. targetInfo.accept(clazz, this, targetInfoVisitor); } /** * Applies the given visitor to the target info. */ public void targetInfoAccept(Clazz clazz, Field field, TargetInfoVisitor targetInfoVisitor) { // We don't need double dispatching here, since there is only one // type of TypePathInfo. targetInfo.accept(clazz, field, this, targetInfoVisitor); } /** * Applies the given visitor to the target info. */ public void targetInfoAccept(Clazz clazz, Method method, TargetInfoVisitor targetInfoVisitor) { // We don't need double dispatching here, since there is only one // type of TypePathInfo. targetInfo.accept(clazz, method, this, targetInfoVisitor); } /** * Applies the given visitor to the target info. */ public void targetInfoAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, TargetInfoVisitor targetInfoVisitor) { // We don't need double dispatching here, since there is only one // type of TypePathInfo. targetInfo.accept(clazz, method, codeAttribute, this, targetInfoVisitor); } /** * Applies the given visitor to all type path elements. */ public void typePathInfosAccept(Clazz clazz, TypePathInfoVisitor typePathVisitor) { for (int index = 0; index < typePath.length; index++) { // We don't need double dispatching here, since there is only one // type of TypePathInfo. typePathVisitor.visitTypePathInfo(clazz, this, typePath[index]); } } /** * Applies the given visitor to all type path elements. */ public void typePathInfosAccept(Clazz clazz, Field field, TypePathInfoVisitor typePathVisitor) { for (int index = 0; index < typePath.length; index++) { // We don't need double dispatching here, since there is only one // type of TypePathInfo. typePathVisitor.visitTypePathInfo(clazz, field, this, typePath[index]); } } /** * Applies the given visitor to all type path elements. */ public void typePathInfosAccept(Clazz clazz, Method method, TypePathInfoVisitor typePathVisitor) { for (int index = 0; index < typePath.length; index++) { // We don't need double dispatching here, since there is only one // type of TypePathInfo. typePathVisitor.visitTypePathInfo(clazz, method, this, typePath[index]); } } /** * Applies the given visitor to all type path elements. */ public void typePathInfosAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, TypePathInfoVisitor typePathVisitor) { for (int index = 0; index < typePath.length; index++) { // We don't need double dispatching here, since there is only one // type of TypePathInfo. typePathVisitor.visitTypePathInfo(clazz, method, codeAttribute, typeAnnotation, typePath[index]); } } }
{ "pile_set_name": "Github" }
{ "version":"LAYAMATERIAL:01", "props":{ "shaderName":"SIMPLE", "cull":2, "blend":0, "srcBlend":1, "dstBlend":0, "alphaTest":false, "depthWrite":true, "renderQueue":1, "textures":[ { "name":"diffuseTexture", "path":"../texture/t0211.png" }, { "name":"normalTexture", "path":"" }, { "name":"specularTexture", "path":"" }, { "name":"emissiveTexture", "path":"" } ], "vectors":[ { "name":"ambientColor", "value":[ 0.6, 0.6, 0.6 ] }, { "name":"albedo", "value":[ 0.588, 0.588, 0.588, 1 ] }, { "name":"diffuseColor", "value":[ 1, 1, 1 ] }, { "name":"specularColor", "value":[ 1, 1, 1, 8 ] }, { "name":"emissionColor", "value":[ 0, 0, 0 ] } ] } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2020 PHYTEC Messtechnik GmbH * * SPDX-License-Identifier: Apache-2.0 */ #define DT_DRV_COMPAT gooddisplay_gd7965 #include <string.h> #include <device.h> #include <init.h> #include <drivers/display.h> #include <drivers/gpio.h> #include <drivers/spi.h> #include <sys/byteorder.h> #include "gd7965_regs.h" #include <logging/log.h> LOG_MODULE_REGISTER(gd7965, CONFIG_DISPLAY_LOG_LEVEL); /** * GD7965 compatible EPD controller driver. * * Currently only the black/white pannels are supported (KW mode), * also first gate/source should be 0. */ #define GD7965_SPI_FREQ DT_INST_PROP(0, spi_max_frequency) #define GD7965_BUS_NAME DT_INST_BUS_LABEL(0) #define GD7965_DC_PIN DT_INST_GPIO_PIN(0, dc_gpios) #define GD7965_DC_FLAGS DT_INST_GPIO_FLAGS(0, dc_gpios) #define GD7965_DC_CNTRL DT_INST_GPIO_LABEL(0, dc_gpios) #define GD7965_CS_PIN DT_INST_SPI_DEV_CS_GPIOS_PIN(0) #define GD7965_CS_FLAGS DT_INST_SPI_DEV_CS_GPIOS_FLAGS(0) #if DT_INST_SPI_DEV_HAS_CS_GPIOS(0) #define GD7965_CS_CNTRL DT_INST_SPI_DEV_CS_GPIOS_LABEL(0) #endif #define GD7965_BUSY_PIN DT_INST_GPIO_PIN(0, busy_gpios) #define GD7965_BUSY_CNTRL DT_INST_GPIO_LABEL(0, busy_gpios) #define GD7965_BUSY_FLAGS DT_INST_GPIO_FLAGS(0, busy_gpios) #define GD7965_RESET_PIN DT_INST_GPIO_PIN(0, reset_gpios) #define GD7965_RESET_CNTRL DT_INST_GPIO_LABEL(0, reset_gpios) #define GD7965_RESET_FLAGS DT_INST_GPIO_FLAGS(0, reset_gpios) #define EPD_PANEL_WIDTH DT_INST_PROP(0, width) #define EPD_PANEL_HEIGHT DT_INST_PROP(0, height) #define GD7965_PIXELS_PER_BYTE 8U /* Horizontally aligned page! */ #define GD7965_NUMOF_PAGES (EPD_PANEL_WIDTH / \ GD7965_PIXELS_PER_BYTE) #define GD7965_PANEL_FIRST_GATE 0U #define GD7965_PANEL_LAST_GATE (EPD_PANEL_HEIGHT - 1) #define GD7965_PANEL_FIRST_PAGE 0U #define GD7965_PANEL_LAST_PAGE (GD7965_NUMOF_PAGES - 1) struct gd7965_data { const struct device *reset; const struct device *dc; const struct device *busy; const struct device *spi_dev; struct spi_config spi_config; #if defined(GD7965_CS_CNTRL) struct spi_cs_control cs_ctrl; #endif }; static uint8_t gd7965_softstart[] = DT_INST_PROP(0, softstart); static uint8_t gd7965_pwr[] = DT_INST_PROP(0, pwr); /* Border and data polarity settings */ static uint8_t bdd_polarity; static bool blanking_on = true; static inline int gd7965_write_cmd(struct gd7965_data *driver, uint8_t cmd, uint8_t *data, size_t len) { struct spi_buf buf = {.buf = &cmd, .len = sizeof(cmd)}; struct spi_buf_set buf_set = {.buffers = &buf, .count = 1}; gpio_pin_set(driver->dc, GD7965_DC_PIN, 1); if (spi_write(driver->spi_dev, &driver->spi_config, &buf_set)) { return -EIO; } if (data != NULL) { buf.buf = data; buf.len = len; gpio_pin_set(driver->dc, GD7965_DC_PIN, 0); if (spi_write(driver->spi_dev, &driver->spi_config, &buf_set)) { return -EIO; } } return 0; } static inline void gd7965_busy_wait(struct gd7965_data *driver) { int pin = gpio_pin_get(driver->busy, GD7965_BUSY_PIN); while (pin > 0) { __ASSERT(pin >= 0, "Failed to get pin level"); LOG_DBG("wait %u", pin); k_sleep(K_MSEC(GD7965_BUSY_DELAY)); pin = gpio_pin_get(driver->busy, GD7965_BUSY_PIN); } } static int gd7965_update_display(const struct device *dev) { struct gd7965_data *driver = dev->data; LOG_DBG("Trigger update sequence"); if (gd7965_write_cmd(driver, GD7965_CMD_DRF, NULL, 0)) { return -EIO; } k_sleep(K_MSEC(GD7965_BUSY_DELAY)); return 0; } static int gd7965_blanking_off(const struct device *dev) { struct gd7965_data *driver = dev->data; if (blanking_on) { /* Update EPD pannel in normal mode */ gd7965_busy_wait(driver); if (gd7965_update_display(dev)) { return -EIO; } } blanking_on = false; return 0; } static int gd7965_blanking_on(const struct device *dev) { blanking_on = true; return 0; } static int gd7965_write(const struct device *dev, const uint16_t x, const uint16_t y, const struct display_buffer_descriptor *desc, const void *buf) { struct gd7965_data *driver = dev->data; uint16_t x_end_idx = x + desc->width - 1; uint16_t y_end_idx = y + desc->height - 1; uint8_t ptl[GD7965_PTL_REG_LENGTH] = {0}; size_t buf_len; LOG_DBG("x %u, y %u, height %u, width %u, pitch %u", x, y, desc->height, desc->width, desc->pitch); buf_len = MIN(desc->buf_size, desc->height * desc->width / GD7965_PIXELS_PER_BYTE); __ASSERT(desc->width <= desc->pitch, "Pitch is smaller then width"); __ASSERT(buf != NULL, "Buffer is not available"); __ASSERT(buf_len != 0U, "Buffer of length zero"); __ASSERT(!(desc->width % GD7965_PIXELS_PER_BYTE), "Buffer width not multiple of %d", GD7965_PIXELS_PER_BYTE); if ((y_end_idx > (EPD_PANEL_HEIGHT - 1)) || (x_end_idx > (EPD_PANEL_WIDTH - 1))) { LOG_ERR("Position out of bounds"); return -EINVAL; } /* Setup Partial Window and enable Partial Mode */ sys_put_be16(x, &ptl[GD7965_PTL_HRST_IDX]); sys_put_be16(x_end_idx, &ptl[GD7965_PTL_HRED_IDX]); sys_put_be16(y, &ptl[GD7965_PTL_VRST_IDX]); sys_put_be16(y_end_idx, &ptl[GD7965_PTL_VRED_IDX]); ptl[sizeof(ptl) - 1] = GD7965_PTL_PT_SCAN; LOG_HEXDUMP_DBG(ptl, sizeof(ptl), "ptl"); gd7965_busy_wait(driver); if (gd7965_write_cmd(driver, GD7965_CMD_PTIN, NULL, 0)) { return -EIO; } if (gd7965_write_cmd(driver, GD7965_CMD_PTL, ptl, sizeof(ptl))) { return -EIO; } /* Disable boarder output */ bdd_polarity |= GD7965_CDI_BDZ; if (gd7965_write_cmd(driver, GD7965_CMD_CDI, &bdd_polarity, sizeof(bdd_polarity))) { return -EIO; } if (gd7965_write_cmd(driver, GD7965_CMD_DTM2, (uint8_t *)buf, buf_len)) { return -EIO; } /* Update partial window and disable Partial Mode */ if (blanking_on == false) { if (gd7965_update_display(dev)) { return -EIO; } } /* Enable boarder output */ bdd_polarity &= ~GD7965_CDI_BDZ; if (gd7965_write_cmd(driver, GD7965_CMD_CDI, &bdd_polarity, sizeof(bdd_polarity))) { return -EIO; } if (gd7965_write_cmd(driver, GD7965_CMD_PTOUT, NULL, 0)) { return -EIO; } return 0; } static int gd7965_read(const struct device *dev, const uint16_t x, const uint16_t y, const struct display_buffer_descriptor *desc, void *buf) { LOG_ERR("not supported"); return -ENOTSUP; } static void *gd7965_get_framebuffer(const struct device *dev) { LOG_ERR("not supported"); return NULL; } static int gd7965_set_brightness(const struct device *dev, const uint8_t brightness) { LOG_WRN("not supported"); return -ENOTSUP; } static int gd7965_set_contrast(const struct device *dev, uint8_t contrast) { LOG_WRN("not supported"); return -ENOTSUP; } static void gd7965_get_capabilities(const struct device *dev, struct display_capabilities *caps) { memset(caps, 0, sizeof(struct display_capabilities)); caps->x_resolution = EPD_PANEL_WIDTH; caps->y_resolution = EPD_PANEL_HEIGHT; caps->supported_pixel_formats = PIXEL_FORMAT_MONO10; caps->current_pixel_format = PIXEL_FORMAT_MONO10; caps->screen_info = SCREEN_INFO_MONO_MSB_FIRST | SCREEN_INFO_EPD; } static int gd7965_set_orientation(const struct device *dev, const enum display_orientation orientation) { LOG_ERR("Unsupported"); return -ENOTSUP; } static int gd7965_set_pixel_format(const struct device *dev, const enum display_pixel_format pf) { if (pf == PIXEL_FORMAT_MONO10) { return 0; } LOG_ERR("not supported"); return -ENOTSUP; } static int gd7965_clear_and_write_buffer(const struct device *dev, uint8_t pattern, bool update) { struct display_buffer_descriptor desc = { .buf_size = GD7965_NUMOF_PAGES, .width = EPD_PANEL_WIDTH, .height = 1, .pitch = EPD_PANEL_WIDTH, }; uint8_t *line; line = k_malloc(GD7965_NUMOF_PAGES); if (line == NULL) { return -ENOMEM; } memset(line, pattern, GD7965_NUMOF_PAGES); for (int i = 0; i < EPD_PANEL_HEIGHT; i++) { gd7965_write(dev, 0, i, &desc, line); } k_free(line); if (update == true) { if (gd7965_update_display(dev)) { return -EIO; } } return 0; } static int gd7965_controller_init(const struct device *dev) { struct gd7965_data *driver = dev->data; uint8_t tmp[GD7965_TRES_REG_LENGTH]; gpio_pin_set(driver->reset, GD7965_RESET_PIN, 1); k_sleep(K_MSEC(GD7965_RESET_DELAY)); gpio_pin_set(driver->reset, GD7965_RESET_PIN, 0); k_sleep(K_MSEC(GD7965_RESET_DELAY)); gd7965_busy_wait(driver); LOG_DBG("Initialize GD7965 controller"); if (gd7965_write_cmd(driver, GD7965_CMD_PWR, gd7965_pwr, sizeof(gd7965_pwr))) { return -EIO; } if (gd7965_write_cmd(driver, GD7965_CMD_BTST, gd7965_softstart, sizeof(gd7965_softstart))) { return -EIO; } /* Turn on: booster, controller, regulators, and sensor. */ if (gd7965_write_cmd(driver, GD7965_CMD_PON, NULL, 0)) { return -EIO; } k_sleep(K_MSEC(GD7965_PON_DELAY)); gd7965_busy_wait(driver); /* Pannel settings, KW mode */ tmp[0] = GD7965_PSR_KW_R | GD7965_PSR_UD | GD7965_PSR_SHL | GD7965_PSR_SHD | GD7965_PSR_RST; if (gd7965_write_cmd(driver, GD7965_CMD_PSR, tmp, 1)) { return -EIO; } /* Set panel resolution */ sys_put_be16(EPD_PANEL_WIDTH, &tmp[GD7965_TRES_HRES_IDX]); sys_put_be16(EPD_PANEL_HEIGHT, &tmp[GD7965_TRES_VRES_IDX]); LOG_HEXDUMP_DBG(tmp, sizeof(tmp), "TRES"); if (gd7965_write_cmd(driver, GD7965_CMD_TRES, tmp, GD7965_TRES_REG_LENGTH)) { return -EIO; } bdd_polarity = GD7965_CDI_BDV1 | GD7965_CDI_N2OCP | GD7965_CDI_DDX0; tmp[GD7965_CDI_BDZ_DDX_IDX] = bdd_polarity; tmp[GD7965_CDI_CDI_IDX] = DT_INST_PROP(0, cdi); LOG_HEXDUMP_DBG(tmp, GD7965_CDI_REG_LENGTH, "CDI"); if (gd7965_write_cmd(driver, GD7965_CMD_CDI, tmp, GD7965_CDI_REG_LENGTH)) { return -EIO; } tmp[0] = DT_INST_PROP(0, tcon); if (gd7965_write_cmd(driver, GD7965_CMD_TCON, tmp, 1)) { return -EIO; } /* Enable Auto Sequence */ tmp[0] = GD7965_AUTO_PON_DRF_POF; if (gd7965_write_cmd(driver, GD7965_CMD_AUTO, tmp, 1)) { return -EIO; } if (gd7965_clear_and_write_buffer(dev, 0xff, false)) { return -1; } return 0; } static int gd7965_init(const struct device *dev) { struct gd7965_data *driver = dev->data; LOG_DBG(""); driver->spi_dev = device_get_binding(GD7965_BUS_NAME); if (driver->spi_dev == NULL) { LOG_ERR("Could not get SPI device for GD7965"); return -EIO; } driver->spi_config.frequency = GD7965_SPI_FREQ; driver->spi_config.operation = SPI_OP_MODE_MASTER | SPI_WORD_SET(8); driver->spi_config.slave = DT_INST_REG_ADDR(0); driver->spi_config.cs = NULL; driver->reset = device_get_binding(GD7965_RESET_CNTRL); if (driver->reset == NULL) { LOG_ERR("Could not get GPIO port for GD7965 reset"); return -EIO; } gpio_pin_configure(driver->reset, GD7965_RESET_PIN, GPIO_OUTPUT_INACTIVE | GD7965_RESET_FLAGS); driver->dc = device_get_binding(GD7965_DC_CNTRL); if (driver->dc == NULL) { LOG_ERR("Could not get GPIO port for GD7965 DC signal"); return -EIO; } gpio_pin_configure(driver->dc, GD7965_DC_PIN, GPIO_OUTPUT_INACTIVE | GD7965_DC_FLAGS); driver->busy = device_get_binding(GD7965_BUSY_CNTRL); if (driver->busy == NULL) { LOG_ERR("Could not get GPIO port for GD7965 busy signal"); return -EIO; } gpio_pin_configure(driver->busy, GD7965_BUSY_PIN, GPIO_INPUT | GD7965_BUSY_FLAGS); #if defined(GD7965_CS_CNTRL) driver->cs_ctrl.gpio_dev = device_get_binding(GD7965_CS_CNTRL); if (!driver->cs_ctrl.gpio_dev) { LOG_ERR("Unable to get SPI GPIO CS device"); return -EIO; } driver->cs_ctrl.gpio_pin = GD7965_CS_PIN; driver->cs_ctrl.gpio_dt_flags = GD7965_CS_FLAGS; driver->cs_ctrl.delay = 0U; driver->spi_config.cs = &driver->cs_ctrl; #endif return gd7965_controller_init(dev); } static struct gd7965_data gd7965_driver; static struct display_driver_api gd7965_driver_api = { .blanking_on = gd7965_blanking_on, .blanking_off = gd7965_blanking_off, .write = gd7965_write, .read = gd7965_read, .get_framebuffer = gd7965_get_framebuffer, .set_brightness = gd7965_set_brightness, .set_contrast = gd7965_set_contrast, .get_capabilities = gd7965_get_capabilities, .set_pixel_format = gd7965_set_pixel_format, .set_orientation = gd7965_set_orientation, }; DEVICE_AND_API_INIT(gd7965, DT_INST_LABEL(0), gd7965_init, &gd7965_driver, NULL, POST_KERNEL, CONFIG_APPLICATION_INIT_PRIORITY, &gd7965_driver_api);
{ "pile_set_name": "Github" }
--- title: More on Function Visibility actions: - 'checkAnswer' - 'hints' material: editor: language: sol startingCode: "zombiefactory.sol": | pragma solidity ^0.4.19; contract ZombieFactory { event NewZombie(uint zombieId, string name, uint dna); uint dnaDigits = 16; uint dnaModulus = 10 ** dnaDigits; struct Zombie { string name; uint dna; } Zombie[] public zombies; mapping (uint => address) public zombieToOwner; mapping (address => uint) ownerZombieCount; // edit function definition below function _createZombie(string _name, uint _dna) private { uint id = zombies.push(Zombie(_name, _dna)) - 1; zombieToOwner[id] = msg.sender; ownerZombieCount[msg.sender]++; NewZombie(id, _name, _dna); } function _generateRandomDna(string _str) private view returns (uint) { uint rand = uint(keccak256(_str)); return rand % dnaModulus; } function createRandomZombie(string _name) public { require(ownerZombieCount[msg.sender] == 0); uint randDna = _generateRandomDna(_name); _createZombie(_name, randDna); } } "zombiefeeding.sol": | pragma solidity ^0.4.19; import "./zombiefactory.sol"; contract ZombieFeeding is ZombieFactory { function feedAndMultiply(uint _zombieId, uint _targetDna) public { require(msg.sender == zombieToOwner[_zombieId]); Zombie storage myZombie = zombies[_zombieId]; _targetDna = _targetDna % dnaModulus; uint newDna = (myZombie.dna + _targetDna) / 2; _createZombie("NoName", newDna); } } answer: > pragma solidity ^0.4.19; contract ZombieFactory { event NewZombie(uint zombieId, string name, uint dna); uint dnaDigits = 16; uint dnaModulus = 10 ** dnaDigits; struct Zombie { string name; uint dna; } Zombie[] public zombies; mapping (uint => address) public zombieToOwner; mapping (address => uint) ownerZombieCount; function _createZombie(string _name, uint _dna) internal { uint id = zombies.push(Zombie(_name, _dna)) - 1; zombieToOwner[id] = msg.sender; ownerZombieCount[msg.sender]++; NewZombie(id, _name, _dna); } function _generateRandomDna(string _str) private view returns (uint) { uint rand = uint(keccak256(_str)); return rand % dnaModulus; } function createRandomZombie(string _name) public { require(ownerZombieCount[msg.sender] == 0); uint randDna = _generateRandomDna(_name); _createZombie(_name, randDna); } } --- **The code in our previous lesson has a mistake!** If you try compiling it, the compiler will throw an error. The issue is we tried calling the `_createZombie` function from within `ZombieFeeding`, but `_createZombie` is a `private` function inside `ZombieFactory`. This means none of the contracts that inherit from `ZombieFactory` can access it. ## Internal and External In addition to `public` and `private`, Solidity has two more types of visibility for functions: `internal` and `external`. `internal` is the same as `private`, except that it's also accessible to contracts that inherit from this contract. **(Hey, that sounds like what we want here!)**. `external` is similar to `public`, except that these functions can ONLY be called outside the contract — they can't be called by other functions inside that contract. We'll talk about why you might want to use `external` vs `public` later. For declaring `internal` or `external` functions, the syntax is the same as `private` and `public`: contract Sandwich { uint private sandwichesEaten = 0; function eat() internal { sandwichesEaten++; } } contract BLT is Sandwich { uint private baconSandwichesEaten = 0; function eatWithBacon() public returns (string) { baconSandwichesEaten++; // We can call this here because it's internal eat(); } } # Put it to the test 1. Change `_createZombie()` from `private` to `internal` so our other contract can access it. We've already focused you back to the proper tab, `zombiefactory.sol`.
{ "pile_set_name": "Github" }
# # Rules for building library # # ---------------------------------------------------------------------------- # common rules # ---------------------------------------------------------------------------- ROOT_PATH := ../.. include $(ROOT_PATH)/gcc.mk # ---------------------------------------------------------------------------- # library and objects # ---------------------------------------------------------------------------- LIBS := libcedarx.a DIRS := $(shell find . -maxdepth 4 -type d) DIRS += . SRCS := $(basename $(foreach dir,$(DIRS),$(wildcard $(dir)/*.[csS]))) OBJS := $(addsuffix .o,$(SRCS)) # extra include path INCLUDE_PATHS += $(foreach dir, $(DIRS), -I$(dir)) # library make rules include $(LIB_MAKE_RULES)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <!-- ~ << ~ Davinci ~ == ~ Copyright (C) 2016 - 2019 EDP ~ == ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ http://www.apache.org/licenses/LICENSE-2.0 ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. ~ >> ~ --> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="edp.davinci.dao.OrganizationMapper"> <insert id="insert" parameterType="edp.davinci.model.Organization"> <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() AS id </selectKey> insert organization <trim prefix="(" suffix=")" suffixOverrides=","> `name`, `user_id`, `project_num`, `member_num`, `role_num`, `allow_create_project`, `member_permission`, `create_time`, `create_by`, <if test='description != null and description != "" '> `description`, </if> <if test='avatar != null and avatar != "" '> `avatar` </if> </trim> values <trim prefix=" (" suffix=")" suffixOverrides=","> #{name, jdbcType=VARCHAR}, #{userId, jdbcType=BIGINT}, #{projectNum, jdbcType=INTEGER}, #{memberNum, jdbcType=INTEGER}, #{roleNum, jdbcType=INTEGER}, #{allowCreateProject, jdbcType=TINYINT}, #{memberPermission, jdbcType=SMALLINT}, #{createTime, jdbcType=TIMESTAMP}, #{createBy, jdbcType=BIGINT}, <if test='description != null and description != "" '> #{description, jdbcType=VARCHAR}, </if> <if test='avatar != null and avatar != "" '> #{avatar, jdbcType=VARCHAR} </if> </trim> </insert> <update id="updateProjectNum" parameterType="edp.davinci.model.Organization"> update organization <choose> <when test="projectNum > 0"> set `project_num`=#{projectNum,jdbcType=INTEGER} </when> <otherwise> set `project_num`=0 </otherwise> </choose> <where> `id`=#{id,jdbcType=BIGINT} </where> </update> <update id="updateMemberNum" parameterType="edp.davinci.model.Organization"> update organization <choose> <when test="memberNum > 0"> set `member_num`=#{memberNum,jdbcType=INTEGER} </when> <otherwise> set `member_num`=0 </otherwise> </choose> <where> `id`=#{id,jdbcType=BIGINT} </where> </update> <update id="updateRoleNum" parameterType="edp.davinci.model.Organization"> update organization <choose> <when test="roleNum > 0"> set `role_num`=#{roleNum,jdbcType=INTEGER} </when> <otherwise> set `role_num`=0 </otherwise> </choose> <where> `id`=#{id,jdbcType=BIGINT} </where> </update> <update id="addOneMemberNum" parameterType="java.util.Set"> update organization set `role_num`=(role_num + 1) where `id` in <foreach collection="set" index="index" item="item" open="(" close=")" separator=","> #{item} </foreach> </update> <select id="getJointlyOrganization" resultType="edp.davinci.dto.organizationDto.OrganizationInfo" parameterType="java.util.Set"> SELECT o.* FROM (organization o, ( SELECT `org_id`, COUNT(1) as c FROM rel_user_organization WHERE `user_id` in <foreach collection="list" index="index" item="item" open="(" close=")" separator=",">#{item} </foreach> GROUP BY `org_id` HAVING `c` > 1 ) o1 ) LEFT JOIN rel_user_organization ruo on ruo.`org_id` = o.`id` and ruo.`user_id` = #{userId} WHERE o.`id` = o1.`org_id` </select> </mapper>
{ "pile_set_name": "Github" }
#!/bin/bash for file in `git ls-files | grep .*_cfg_default.h`; do git mv $file `echo $file | sed -e 's/_cfg_default/_cfg_template/'` ; done
{ "pile_set_name": "Github" }
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-2020 Datadog, Inc. package errors import ( "fmt" "testing" "github.com/stretchr/testify/require" ) func TestNotFound(t *testing.T) { // New err := NewNotFound("foo") require.Error(t, err) require.Equal(t, `"foo" not found`, err.Error()) // Is require.True(t, IsNotFound(err)) require.False(t, IsNotFound(fmt.Errorf("fake"))) require.False(t, IsNotFound(fmt.Errorf(`"foo" not found`))) }
{ "pile_set_name": "Github" }
[General] BTBColor=#0A5C90 Colors=@Variant(\0\0\0\b\0\0\0\x2\0\0\0\x4\0\x65\0t\0\0\0\n\0\0\0\xe\0#\0\x63\0\x63\0\x30\0\x66\0\x35\0\x30\0\0\0\x4\0\x62\0t\0\0\0\n\0\0\0\xe\0#\0\x30\0\x41\0\x35\0\x43\0\x39\0\x30) Delay=2000 ETBColor=#cc0f50 LCDColors=@Variant(\0\0\0\b\0\0\0\x2\0\0\0\x4\0\x65\0t\0\0\0\n\0\0\0\xe\0#\0\x63\0\x63\0\x30\0\x66\0\x35\0\x30\0\0\0\x4\0\x62\0t\0\0\0\n\0\0\0\xe\0#\0\x30\0\x41\0\x35\0\x43\0\x39\0\x30) LEDColors=@Variant(\0\0\0\b\0\0\0\x2\0\0\0\x4\0\x65\0t\0\0\0\n\0\0\0\n\0w\0h\0i\0t\0\x65\0\0\0\x4\0\x62\0t\0\0\0\n\0\0\0\n\0w\0h\0i\0t\0\x65) Oversampling=true [Device] id=29 [ExtraEventButtons] buttonWidth=50 buttonlistmaxlen=11 buttonpalette=@Variant(\0\0\0\t\0\0\0\0), @Variant(\0\0\0\t\0\0\0\x18\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x6\0\0\0\0\0\0\0\0\0\0\0\x6\0\0\0\0\0\0\0\0\0\0\0\x6\0\0\0\0\0\0\0\0\0\0\0\x6\0\0\0\0\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x6?\xf0\0\0\0\0\0\0\0\0\0\x6?\xf0\0\0\0\0\0\0\0\0\0\x6?\xf0\0\0\0\0\0\0\0\0\0\x6?\xf0\0\0\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0), "@Variant(\0\0\0\t\0\0\0\x18\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\x1\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\x2\0\0\0\t\0\0\0\x4\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0(\0w\0r\0i\0t\0\x65\0W\0o\0r\0\x64\0(\0\x31\0,\0\x32\0\x36\0\x34\0\x32\0,\0{\0}\0)\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x6?\xf0\0\0\0\0\0\0\0\0\0\x6?\xf0\0\0\0\0\0\0\0\0\0\x6?\xf0\0\0\0\0\0\0\0\0\0\x6?\xf0\0\0\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\x2\0\0\0\0\0\0\0\t\0\0\0\x4\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\0\0\0\0\n\0\0\0\x2\0%)", @Variant(\0\0\0\t\0\0\0\0), @Variant(\0\0\0\t\0\0\0\0), @Variant(\0\0\0\t\0\0\0\0), @Variant(\0\0\0\t\0\0\0\0), @Variant(\0\0\0\t\0\0\0\0), @Variant(\0\0\0\t\0\0\0\0), @Variant(\0\0\0\t\0\0\0\0) buttonpaletteWidth=60, 60, 60, 60, 60, 60, 60, 60, 60, 60 buttonpalette_shortcuts=true buttonpalettemaxlen=11, 11, 11, 14, 14, 14, 14, 14, 14, 14 buttonsize=1 eventbuttontablecolumnwidths=70, 80, 100, 50, 150, 100, 80, 80, 80, 44 extraeventbuttoncolor=@Invalid() extraeventbuttontextcolor=@Invalid() extraeventsactions=@Invalid() extraeventsactionstrings=@Invalid() extraeventsbuttonsflags=0, 1, 1 extraeventsdescriptions=@Invalid() extraeventslabels=@Invalid() extraeventstypes=@Invalid() extraeventsvalues=@Invalid() extraeventsvisibility=@Invalid() [Modbus] PID_OFF_action= PID_ON_action= PID_SV_register=0 PID_d_register=0 PID_i_register=0 PID_p_register=0 PID_slave_ID=0 PIDmultiplier=0 SVmultiplier=1 baudrate=9600 bytesize=8 comport=COM4 host=127.0.0.1 input1bcd=false input1code=4 input1div=0 input1float=true input1FloatsAsInt=false input1mode=F input1register=450 input1slave=1 input2bcd=false input2code=4 input2div=0 input2float=true input2FloatsAsInt=false input2mode=F input2register=360 input2slave=1 input3bcd=false input3code=3 input3div=0 input3float=false input3FloatsAsInt=false input3mode=C input3register=0 input3slave=0 input4bcd=false input4code=3 input4div=0 input4float=false input4FloatsAsInt=false input4mode=C input4register=0 input4slave=0 input5bcd=false input5code=3 input5div=0 input5float=false input5FloatsAsInt=false input5mode=C input5register=0 input5slave=0 input6bcd=false input6code=3 input6div=0 input6float=false input6FloatsAsInt=false input6mode=C input6register=0 input6slave=0 input7bcd=false input7code=3 input7div=0 input7float=false input7FloatsAsInt=false input7mode=C input7register=0 input7slave=0 input8bcd=false input8code=3 input8div=0 input8float=false input8FloatsAsInt=false input8mode=C input8register=0 input8slave=0 littleEndianFloats=false parity=N port=502 stopbits=1 timeout=1 type=0 wordorderLittle=false [RoastProperties] roastertype=San Fransican [Sliders] ModeTempSliders=C eventslidercoarse=0, 0, 0, 0 eventslidersflags=1, 1, 1 eventslidertemp=0, 0, 0, 0 eventsliderunits=, , , slideractions=0, 0, 0, 0 slidercommands=, , , sliderfactors=1, 1, 1, 1 slidermax=100, 100, 100, 100 slidermin=0, 0, 0, 0 slideroffsets=0, 0, 0, 0 slidervisibilities=0, 0, 0, 0
{ "pile_set_name": "Github" }
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.MSHTMLApi { /// <summary> /// DispatchInterface HTMLElementEvents2 /// SupportByVersion MSHTML, 4 /// </summary> [SupportByVersion("MSHTML", 4)] [EntityType(EntityType.IsDispatchInterface), BaseType] public class HTMLElementEvents2 : DispHTMLGenericElement { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(HTMLElementEvents2); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public HTMLElementEvents2(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public HTMLElementEvents2(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLElementEvents2(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLElementEvents2(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLElementEvents2(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLElementEvents2(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLElementEvents2() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLElementEvents2(string progId) : base(progId) { } #endregion #region Properties #endregion #region Methods /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onhelp(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onhelp", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onclick(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onclick", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool ondblclick(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "ondblclick", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onkeypress(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onkeypress", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onkeydown(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onkeydown", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onkeyup(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onkeyup", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onmouseout(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onmouseout", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onmouseover(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onmouseover", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onmousemove(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onmousemove", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onmousedown(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onmousedown", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onmouseup(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onmouseup", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onselectstart(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onselectstart", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onfilterchange(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onfilterchange", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool ondragstart(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "ondragstart", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onbeforeupdate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onbeforeupdate", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onafterupdate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onafterupdate", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onerrorupdate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onerrorupdate", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onrowexit(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onrowexit", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onrowenter(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onrowenter", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void ondatasetchanged(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "ondatasetchanged", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void ondataavailable(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "ondataavailable", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void ondatasetcomplete(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "ondatasetcomplete", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onlosecapture(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onlosecapture", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onpropertychange(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onpropertychange", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onscroll(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onscroll", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onfocus(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onfocus", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onblur(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onblur", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onresize(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onresize", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool ondrag(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "ondrag", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void ondragend(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "ondragend", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool ondragenter(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "ondragenter", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool ondragover(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "ondragover", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void ondragleave(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "ondragleave", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool ondrop(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "ondrop", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onbeforecut(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onbeforecut", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool oncut(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "oncut", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onbeforecopy(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onbeforecopy", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool oncopy(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "oncopy", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onbeforepaste(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onbeforepaste", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onpaste(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onpaste", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool oncontextmenu(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "oncontextmenu", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onrowsdelete(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onrowsdelete", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onrowsinserted(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onrowsinserted", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void oncellchange(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "oncellchange", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onreadystatechange(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onreadystatechange", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onlayoutcomplete(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onlayoutcomplete", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onpage(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onpage", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onmouseenter(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onmouseenter", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onmouseleave(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onmouseleave", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onactivate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onactivate", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void ondeactivate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "ondeactivate", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onbeforedeactivate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onbeforedeactivate", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onbeforeactivate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onbeforeactivate", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onfocusin(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onfocusin", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onfocusout(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onfocusout", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onmove(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onmove", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool oncontrolselect(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "oncontrolselect", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onmovestart(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onmovestart", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onmoveend(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onmoveend", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onresizestart(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onresizestart", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public void onresizeend(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { Factory.ExecuteMethod(this, "onresizeend", pEvtObj); } /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersion("MSHTML", 4)] public bool onmousewheel(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { return Factory.ExecuteBoolMethodGet(this, "onmousewheel", pEvtObj); } #endregion #pragma warning restore } }
{ "pile_set_name": "Github" }
{ "_args": [ [ "weex-components", "E:\\workspace\\hongkong" ] ], "_from": "weex-components@latest", "_id": "weex-components@0.2.0", "_inCache": true, "_installable": true, "_location": "/weex-components", "_nodeVersion": "5.9.1", "_npmOperationalInternal": { "host": "packages-16-east.internal.npmjs.com", "tmp": "tmp/weex-components-0.2.0.tgz_1469004326378_0.3862996082752943" }, "_npmUser": { "email": "zhaojinjiang@me.com", "name": "jinjiang" }, "_npmVersion": "3.9.5", "_phantomChildren": {}, "_requested": { "name": "weex-components", "raw": "weex-components", "rawSpec": "", "scope": null, "spec": "latest", "type": "tag" }, "_requiredBy": [ "#USER" ], "_resolved": "https://registry.npmjs.org/weex-components/-/weex-components-0.2.0.tgz", "_shasum": "73cb41f88e2e1ceed86d95d1f5db4b0a213cfd53", "_shrinkwrap": null, "_spec": "weex-components", "_where": "E:\\workspace\\hongkong", "bugs": { "url": "https://github.com/weexteam/weex-components/issues" }, "dependencies": {}, "description": "A group of simple and useful weex components", "devDependencies": {}, "directories": {}, "dist": { "shasum": "73cb41f88e2e1ceed86d95d1f5db4b0a213cfd53", "tarball": "https://registry.npmjs.org/weex-components/-/weex-components-0.2.0.tgz" }, "gitHead": "6bb257e4725c7b72b3d939c9f063bd85b872351b", "homepage": "https://github.com/weexteam/weex-components#readme", "keywords": [ "weex", "webcomponents", "javascript", "html5", "android", "ios" ], "license": "GPL-3.0", "main": "./index.js", "maintainers": [ { "email": "ningli928@163.com", "name": "boboning" }, { "email": "zhaojinjiang@me.com", "name": "jinjiang" }, { "email": "luics.xu@gmail.com", "name": "luics" }, { "email": "tekkahs@gmail.com", "name": "mr.raindrop" }, { "email": "terrykingcha@gmail.com", "name": "terrykingcha" } ], "name": "weex-components", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/weexteam/weex-components.git" }, "scripts": {}, "version": "0.2.0" }
{ "pile_set_name": "Github" }
X-Account-Key: account5 X-UIDL: GmailId12880e8b115d0ae0 X-Mozilla-Status: 0000 X-Mozilla-Status2: 00000000 X-Mozilla-Keys: Delivered-To: mlsubscriber.tech@csmining.org Received: by 10.142.81.20 with SMTP id e20cs586503wfb; Sun, 9 May 2010 23:30:53 -0700 (PDT) Received: by 10.223.16.207 with SMTP id p15mr3676853faa.99.1273473052709; Sun, 09 May 2010 23:30:52 -0700 (PDT) Return-Path: <bounce-debian-user=mlsubscriber.tech=csmining.org@lists.debian.org> Received: from liszt.debian.org (liszt.debian.org [82.195.75.100]) by mx.google.com with ESMTP id o13si7607327fah.93.2010.05.09.23.30.52; Sun, 09 May 2010 23:30:52 -0700 (PDT) Received-SPF: pass (google.com: manual fallback record for domain of bounce-debian-user=mlsubscriber.tech=csmining.org@lists.debian.org designates 82.195.75.100 as permitted sender) client-ip=82.195.75.100; Authentication-Results: mx.google.com; spf=pass (google.com: manual fallback record for domain of bounce-debian-user=mlsubscriber.tech=csmining.org@lists.debian.org designates 82.195.75.100 as permitted sender) smtp.mail=bounce-debian-user=mlsubscriber.tech=csmining.org@lists.debian.org Received: from localhost (localhost [127.0.0.1]) by liszt.debian.org (Postfix) with QMQP id 24C3F13A54DF; Mon, 10 May 2010 06:30:47 +0000 (UTC) Old-Return-Path: <mihamina@gulfsat.mg> XChecker-Version: SpamAssassin 3.2.5 (2008-06-10) on liszt.debian.org XLevel: XStatus: No, score=-10.0 required=4.0 tests=GMAIL,LDOSUBSCRIBER, LDO_WHITELIST autolearn=failed version=3.2.5 X-Original-To: lists-debian-user@liszt.debian.org Delivered-To: lists-debian-user@liszt.debian.org Received: from localhost (localhost [127.0.0.1]) by liszt.debian.org (Postfix) with ESMTP id 84ED113A50D9 for <lists-debian-user@liszt.debian.org>; Mon, 10 May 2010 06:30:41 +0000 (UTC) X-Virus-Scanned: at lists.debian.org with policy bank en-ht X-AmavisStatus: No, score=-6 tagged_above=-10000 required=5.3 tests=[BAYES_00=-2, GMAIL=1, LDO_WHITELIST=-5] autolearn=no Received: from liszt.debian.org ([127.0.0.1]) by localhost (lists.debian.org [127.0.0.1]) (amavisd-new, port 2525) with ESMTP id ooP8m0oCY2q1 for <lists-debian-user@liszt.debian.org>; Mon, 10 May 2010 06:30:34 +0000 (UTC) X-policyd-weight: using cached result; rate:hard: -5 Received: from smtp-out.malagasy.com (smtp-out.malagasy.com [41.204.104.33]) (using TLSv1 with cipher DHE-RSA-AES256-SHA (256/256 bits)) (Client CN "smtp-out.malagasy.com", Issuer "smtp-out.malagasy.com" (not verified)) by liszt.debian.org (Postfix) with ESMTPS id 2031213A44DC for <debian-user@lists.debian.org>; Mon, 10 May 2010 06:30:34 +0000 (UTC) Received: from smtp.blueline.mg (static-104-61.blueline.mg [41.204.104.61]) (using TLSv1 with cipher ADH-AES256-SHA (256/256 bits)) (No client certificate requested) by smtp-out.malagasy.com (Postfix) with ESMTPS id 481688CDA5 for <debian-user@lists.debian.org>; Mon, 10 May 2010 09:30:30 +0300 (EAT) Received: from localhost (static-104-53.blueline.mg [41.204.104.53]) by smtp.blueline.mg (Postfix) with ESMTP id 3DBEA4305F7 for <debian-user@lists.debian.org>; Mon, 10 May 2010 09:30:30 +0300 (EAT) X-Virus-Scanned: par antivirus2.malagasy.com Received: from smtp.blueline.mg ([41.204.104.61]) by localhost (antivirus2.malagasy.com [41.204.104.53]) (amavisd-new, port 10024) with ESMTP id NBDNnymjgoAW for <debian-user@lists.debian.org>; Mon, 10 May 2010 09:30:22 +0300 (EAT) Received: from pbmiha.malagasy.com (static-104-10.blueline.mg [41.204.104.10]) (using TLSv1 with cipher AES256-SHA (256/256 bits)) (No client certificate requested) by smtp.blueline.mg (Postfix) with ESMTPS id 6ED4D4305E5 for <debian-user@lists.debian.org>; Mon, 10 May 2010 09:30:22 +0300 (EAT) Received: from localhost ([127.0.0.1] helo=pbmiha.malagasy.com) by pbmiha.malagasy.com with esmtp (Exim 4.69) (envelope-from <mihamina@gulfsat.mg>) id 1OBMVR-0001LQ-U7 for debian-user@lists.debian.org; Mon, 10 May 2010 09:30:21 +0300 Date: Mon, 10 May 2010 09:30:21 +0300 From: Mihamina Rakotomandimby <mihamina@gulfsat.mg> To: debian-user@lists.debian.org Subject: Re: Kde 3.5 ... Message-ID: <20100510093021.107e739f@pbmiha.malagasy.com> In-Reply-To: <201005091602.50128.lisi.reisz@csmining.org> References: <201005071123.48345.lisi.reisz@csmining.org> <201005091500.32195.lisi.reisz@csmining.org> <4BE6C70B.6000300@lorentz.leidenuniv.nl> <201005091602.50128.lisi.reisz@csmining.org> Organization: Gulfsat X-Mailer: Claws Mail 3.7.2 (GTK+ 2.18.3; x86_64-pc-linux-gnu) Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit X-Rc-Virus: 2007-09-13_01 X-Rc-Spam: 2008-11-04_01 Resent-Message-ID: <0m14pTBcqeE.A.FQC.Xg65LB@liszt> Resent-From: debian-user@lists.debian.org X-Mailing-List: <debian-user@lists.debian.org> archive/latest/576346 X-Loop: debian-user@lists.debian.org List-Id: <debian-user.lists.debian.org> List-Post: <mailto:debian-user@lists.debian.org> List-Help: <mailto:debian-user-request@lists.debian.org?subject=help> List-Subscribe: <mailto:debian-user-request@lists.debian.org?subject=subscribe> List-Unsubscribe: <mailto:debian-user-request@lists.debian.org?subject=unsubscribe> Precedence: list Resent-Sender: debian-user-request@lists.debian.org Resent-Date: Mon, 10 May 2010 06:30:47 +0000 (UTC) > Lisi <lisi.reisz@csmining.org> : > I do not have to give him reasons for my dislike. Your mind really suites proprietary softwares. -- Architecte Informatique chez Blueline/Gulfsat: Administration Systeme, Recherche & Developpement +261 34 29 155 34 / +261 33 11 207 36 -- To UNSUBSCRIBE, email to debian-user-REQUEST@lists.debian.org with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org Archive: http://lists.debian.org/20100510093021.107e739f@pbmiha.malagasy.com
{ "pile_set_name": "Github" }
limbo = require 'limbo' validator = require 'validator' _ = require 'lodash' app = require '../../server' {NoticeModel} = limbo.use 'talk' module.exports = noticeController = app.controller 'cms/notice', -> @ensure 'content', only: 'create' editableFields = [ 'content' 'postAt' ] @action 'readOne', (req, res, callback) -> {_id} = req.get() NoticeModel.findOne _id: _id, callback @action 'read', (req, res, callback) -> {postAt, limit, page} = req.get() limit or= 30 page or= 1 if postAt is '' NoticeModel .find postAt: null .sort _id: -1 .exec callback else query = NoticeModel.find(postAt: $ne: null) .sort postAt: -1 query = query.limit(limit) if limit query = query.skip(limit * (page - 1)) if page query.exec callback @action 'create', (req, res, callback) -> {_sessionUserId, content, postAt} = req.get() notice = new NoticeModel creator: _sessionUserId content: content notice.postAt = if validator.isDate(postAt) then new Date(postAt) notice.save callback @action 'update', (req, res, callback) -> {_id} = req.get() update = _.pick(req.get(), editableFields) update.updatedAt = new Date NoticeModel.findOneAndSave _id: _id, update, callback @action 'remove', (req, res, callback) -> {_id} = req.get() NoticeModel.remove _id: _id, callback
{ "pile_set_name": "Github" }
{# ############################################## REDISTRIBUTE MACRO #} {% macro render_redistribute(parent, indent) %} {% if 'redistribute' in parent %} {% for protocol_name in ['connected', 'ospf'] %} {% if protocol_name in parent['redistribute'] %} {% set protocol = parent['redistribute'][protocol_name] %} {% set line = [] %} {% set _ = line.append('redistribute') %} {% set _ = line.append(protocol['protocol']) %} {% if 'process_id' in protocol %} {% set _ = line.append(protocol['process_id']) %} {% endif %}{# process_id #} {% if 'match' in protocol %} {% set _ = line.append('match') %} {% set _ = line.append(protocol['match']|join(' ')) %} {% endif %}{# match #} {% if 'route_map' in protocol %} {% set _ = line.append('route-map') %} {% set _ = line.append(protocol['route_map']) %} {% endif %}{# route-map #} - "{{ indent }}{{ line|join(' ') }}" {% endif %}{# protocol #} {% endfor %}{# protocols #} {% endif %}{# redistribute #} {% endmacro %}
{ "pile_set_name": "Github" }
<configuration> <statusListener class="ch.qos.logback.core.status.NopStatusListener" /> <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"> <resetJUL>true</resetJUL> </contextListener> <!-- To enable JMX Management --> <jmxConfigurator/> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%.-1level|MAIL|%-30.30logger{0}|%msg%n</pattern> </encoder> </appender> <logger name="com.nixmash.springdata" level="info"/> <logger name="org.freemarker" level="off" /> <!--<include resource="logJpaToFile.xml" />--> <root level="OFF"> <appender-ref ref="console"/> </root> </configuration>
{ "pile_set_name": "Github" }
/* Generated by RuntimeBrowser on iPhone OS 3.0 Image: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ @interface WXParagraphProperties : NSObject { } + (void)initialize; + (void)readFrom:(struct _xmlNode { void *x1; NSInteger x2; char *x3; struct _xmlNode {} *x4; struct _xmlNode {} *x5; struct _xmlNode {} *x6; struct _xmlNode {} *x7; struct _xmlNode {} *x8; struct _xmlDoc {} *x9; struct _xmlNs {} *x10; char *x11; struct _xmlAttr {} *x12; struct _xmlNs {} *x13; void *x14; unsigned short x15; unsigned short x16; }*)arg1 to:(id)arg2 state:(id)arg3; + (void)readFrom:(struct _xmlNode { void *x1; NSInteger x2; char *x3; struct _xmlNode {} *x4; struct _xmlNode {} *x5; struct _xmlNode {} *x6; struct _xmlNode {} *x7; struct _xmlNode {} *x8; struct _xmlDoc {} *x9; struct _xmlNs {} *x10; char *x11; struct _xmlAttr {} *x12; struct _xmlNs {} *x13; void *x14; unsigned short x15; unsigned short x16; }*)arg1 to:(id)arg2 baseStyle:(id)arg3 state:(id)arg4; @end
{ "pile_set_name": "Github" }
apiVersion: v1 kind: Service metadata: name: {{ .Release.Name }}-db-master namespace: {{ .Values.global.namespace }} labels: {{- include "commonLabels" . | nindent 4 }} spec: selector: {{- include "postgres.master.serviceLabels" . | nindent 4 }} ports: - name: container port: 5432 protocol: TCP targetPort: 5432
{ "pile_set_name": "Github" }
/* lzo1x_oo.ch -- LZO1X compressed data optimizer This file is part of the LZO real-time data compression library. Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer <markus@oberhumer.com> http://www.oberhumer.com/opensource/lzo/ */ #define TEST_IP (ip < ip_end) #define TEST_OP (op <= op_end) #define TEST_IP_AND_TEST_OP (TEST_IP && TEST_OP) #define NO_LIT LZO_UINT_MAX /*********************************************************************** // ************************************************************************/ static void copy2(lzo_bytep ip, const lzo_bytep m_pos, lzo_uint off) { assert(off > 0); ip[0] = m_pos[0]; if (off == 1) ip[1] = m_pos[0]; else ip[1] = m_pos[1]; } static void copy3(lzo_bytep ip, const lzo_bytep m_pos, lzo_uint off) { assert(off > 0); ip[0] = m_pos[0]; if (off == 1) { ip[2] = ip[1] = m_pos[0]; } else if (off == 2) { ip[1] = m_pos[1]; ip[2] = m_pos[0]; } else { ip[1] = m_pos[1]; ip[2] = m_pos[2]; } } /*********************************************************************** // optimize a block of data. ************************************************************************/ LZO_PUBLIC(int) DO_OPTIMIZE ( lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem ) { lzo_bytep op; lzo_bytep ip; lzo_uint t; lzo_bytep m_pos; lzo_bytep const ip_end = in + in_len; lzo_bytep const op_end = out + *out_len; lzo_bytep litp = NULL; lzo_uint lit = 0; lzo_uint next_lit = NO_LIT; lzo_uint nl; unsigned long o_m1_a = 0, o_m1_b = 0, o_m2 = 0, o_m3_a = 0, o_m3_b = 0; LZO_UNUSED(wrkmem); *out_len = 0; op = out; ip = in; assert(in_len >= 3); if (*ip > 17) { t = *ip++ - 17; if (t < 4) goto match_next; goto first_literal_run; } assert(*ip < 16 || (*ip == 17 && in_len == 3)); while (TEST_IP_AND_TEST_OP) { t = *ip++; if (t >= 16) goto match; /* a literal run */ litp = ip - 1; if (t == 0) { t = 15; while (*ip == 0) { t += 255; ip++; } t += *ip++; } lit = t + 3; /* copy literals */ copy_literal_run: *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; first_literal_run: do *op++ = *ip++; while (--t > 0); t = *ip++; if (t >= 16) goto match; #if defined(LZO1X) m_pos = op - 1 - 0x800; #elif defined(LZO1Y) m_pos = op - 1 - 0x400; #endif m_pos -= t >> 2; m_pos -= *ip++ << 2; *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos++; lit = 0; goto match_done; /* handle matches */ do { if (t < 16) /* a M1 match */ { m_pos = op - 1; m_pos -= t >> 2; m_pos -= *ip++ << 2; if (litp == NULL) goto copy_m1; /* assert that there was a match just before */ assert(lit >= 1 && lit <= 3); assert(litp == ip - 2 - lit - 2); assert((lzo_uint)(*litp & 3) == lit); nl = ip[-2] & 3; /* test if a match follows */ if (nl == 0 && lit == 1 && ip[0] >= 16) { next_lit = nl; /* adjust length of previous short run */ lit += 2; *litp = LZO_BYTE((*litp & ~3) | lit); /* copy over the 2 literals that replace the match */ copy2(ip-2,m_pos,pd(op,m_pos)); o_m1_a++; } /* test if a literal run follows */ else if (nl == 0 && ip[0] < 16 && ip[0] != 0 && (lit + 2 + ip[0] < 16)) { t = *ip++; /* remove short run */ *litp &= ~3; /* copy over the 2 literals that replace the match */ copy2(ip-3+1,m_pos,pd(op,m_pos)); /* move literals 1 byte ahead */ litp += 2; if (lit > 0) lzo_memmove(litp+1,litp,lit); /* insert new length of long literal run */ lit += 2 + t + 3; assert(lit <= 18); *litp = LZO_BYTE(lit - 3); o_m1_b++; *op++ = *m_pos++; *op++ = *m_pos++; goto copy_literal_run; } copy_m1: *op++ = *m_pos++; *op++ = *m_pos++; } else { match: if (t >= 64) /* a M2 match */ { m_pos = op - 1; #if defined(LZO1X) m_pos -= (t >> 2) & 7; m_pos -= *ip++ << 3; t = (t >> 5) - 1; #elif defined(LZO1Y) m_pos -= (t >> 2) & 3; m_pos -= *ip++ << 2; t = (t >> 4) - 3; #endif if (litp == NULL) goto copy_m; nl = ip[-2] & 3; /* test if in beetween two long literal runs */ if (t == 1 && lit > 3 && nl == 0 && ip[0] < 16 && ip[0] != 0 && (lit + 3 + ip[0] < 16)) { assert(*litp == lit - 3); t = *ip++; /* copy over the 3 literals that replace the match */ copy3(ip-1-2,m_pos,pd(op,m_pos)); /* set new length of previous literal run */ lit += 3 + t + 3; assert(lit <= 18); *litp = LZO_BYTE(lit - 3); o_m2++; *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos++; goto copy_literal_run; } } else { if (t >= 32) /* a M3 match */ { t &= 31; if (t == 0) { t = 31; while (*ip == 0) { t += 255; ip++; } t += *ip++; } m_pos = op - 1; m_pos -= *ip++ >> 2; m_pos -= *ip++ << 6; } else /* a M4 match */ { m_pos = op; m_pos -= (t & 8) << 11; t &= 7; if (t == 0) { t = 7; while (*ip == 0) { t += 255; ip++; } t += *ip++; } m_pos -= *ip++ >> 2; m_pos -= *ip++ << 6; if (m_pos == op) goto eof_found; m_pos -= 0x4000; } if (litp == NULL) goto copy_m; nl = ip[-2] & 3; /* test if in beetween two matches */ if (t == 1 && lit == 0 && nl == 0 && ip[0] >= 16) { assert(litp == ip - 3 - lit - 2); assert((lzo_uint)(*litp & 3) == lit); next_lit = nl; /* make a previous short run */ lit += 3; *litp = LZO_BYTE((*litp & ~3) | lit); /* copy over the 3 literals that replace the match */ copy3(ip-3,m_pos,pd(op,m_pos)); o_m3_a++; } /* test if a literal run follows */ else if (t == 1 && lit <= 3 && nl == 0 && ip[0] < 16 && ip[0] != 0 && (lit + 3 + ip[0] < 16)) { assert(litp == ip - 3 - lit - 2); assert((lzo_uint)(*litp & 3) == lit); t = *ip++; /* remove short run */ *litp &= ~3; /* copy over the 3 literals that replace the match */ copy3(ip-4+1,m_pos,pd(op,m_pos)); /* move literals 1 byte ahead */ litp += 2; if (lit > 0) lzo_memmove(litp+1,litp,lit); /* insert new length of long literal run */ lit += 3 + t + 3; assert(lit <= 18); *litp = LZO_BYTE(lit - 3); o_m3_b++; *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos++; goto copy_literal_run; } } copy_m: *op++ = *m_pos++; *op++ = *m_pos++; do *op++ = *m_pos++; while (--t > 0); } match_done: if (next_lit == NO_LIT) { t = ip[-2] & 3; lit = t; litp = ip - 2; } else t = next_lit; assert(t <= 3); next_lit = NO_LIT; if (t == 0) break; /* copy literals */ match_next: do *op++ = *ip++; while (--t > 0); t = *ip++; } while (TEST_IP_AND_TEST_OP); } /* no EOF code was found */ *out_len = pd(op, out); return LZO_E_EOF_NOT_FOUND; eof_found: assert(t == 1); #if 0 printf("optimize: %5lu %5lu %5lu %5lu %5lu\n", o_m1_a, o_m1_b, o_m2, o_m3_a, o_m3_b); #endif LZO_UNUSED(o_m1_a); LZO_UNUSED(o_m1_b); LZO_UNUSED(o_m2); LZO_UNUSED(o_m3_a); LZO_UNUSED(o_m3_b); *out_len = pd(op, out); return (ip == ip_end ? LZO_E_OK : (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); } /* vim:set ts=4 sw=4 et: */
{ "pile_set_name": "Github" }
Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it
{ "pile_set_name": "Github" }
({ shouldDeps : { block : 'button', elem : 'icon', mod : 'vk' } })
{ "pile_set_name": "Github" }
# # Created by: Pearu Peterson, April 2002 # from __future__ import division, print_function, absolute_import __usage__ = """ Build linalg: python setup.py build Run tests if scipy is installed: python -c 'import scipy;scipy.linalg.test()' """ import math import numpy as np from numpy.testing import (assert_equal, assert_almost_equal, assert_, assert_array_almost_equal, assert_allclose) from pytest import raises as assert_raises from numpy import float32, float64, complex64, complex128, arange, triu, \ tril, zeros, tril_indices, ones, mod, diag, append, eye, \ nonzero from numpy.random import rand, seed from scipy.linalg import _fblas as fblas, get_blas_funcs, toeplitz, solve, \ solve_triangular try: from scipy.linalg import _cblas as cblas except ImportError: cblas = None REAL_DTYPES = [float32, float64] COMPLEX_DTYPES = [complex64, complex128] DTYPES = REAL_DTYPES + COMPLEX_DTYPES def test_get_blas_funcs(): # check that it returns Fortran code for arrays that are # fortran-ordered f1, f2, f3 = get_blas_funcs( ('axpy', 'axpy', 'axpy'), (np.empty((2, 2), dtype=np.complex64, order='F'), np.empty((2, 2), dtype=np.complex128, order='C')) ) # get_blas_funcs will choose libraries depending on most generic # array assert_equal(f1.typecode, 'z') assert_equal(f2.typecode, 'z') if cblas is not None: assert_equal(f1.module_name, 'cblas') assert_equal(f2.module_name, 'cblas') # check defaults. f1 = get_blas_funcs('rotg') assert_equal(f1.typecode, 'd') # check also dtype interface f1 = get_blas_funcs('gemm', dtype=np.complex64) assert_equal(f1.typecode, 'c') f1 = get_blas_funcs('gemm', dtype='F') assert_equal(f1.typecode, 'c') # extended precision complex f1 = get_blas_funcs('gemm', dtype=np.longcomplex) assert_equal(f1.typecode, 'z') # check safe complex upcasting f1 = get_blas_funcs('axpy', (np.empty((2, 2), dtype=np.float64), np.empty((2, 2), dtype=np.complex64)) ) assert_equal(f1.typecode, 'z') def test_get_blas_funcs_alias(): # check alias for get_blas_funcs f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64) assert f.typecode == 'c' assert g.typecode == 'c' f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64) assert f is g assert f is h class TestCBLAS1Simple(object): def test_axpy(self): for p in 'sd': f = getattr(cblas, p+'axpy', None) if f is None: continue assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5), [7, 9, 18]) for p in 'cz': f = getattr(cblas, p+'axpy', None) if f is None: continue assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5), [7, 10j-1, 18]) class TestFBLAS1Simple(object): def test_axpy(self): for p in 'sd': f = getattr(fblas, p+'axpy', None) if f is None: continue assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5), [7, 9, 18]) for p in 'cz': f = getattr(fblas, p+'axpy', None) if f is None: continue assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5), [7, 10j-1, 18]) def test_copy(self): for p in 'sd': f = getattr(fblas, p+'copy', None) if f is None: continue assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5]) for p in 'cz': f = getattr(fblas, p+'copy', None) if f is None: continue assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j]) def test_asum(self): for p in 'sd': f = getattr(fblas, p+'asum', None) if f is None: continue assert_almost_equal(f([3, -4, 5]), 12) for p in ['sc', 'dz']: f = getattr(fblas, p+'asum', None) if f is None: continue assert_almost_equal(f([3j, -4, 3-4j]), 14) def test_dot(self): for p in 'sd': f = getattr(fblas, p+'dot', None) if f is None: continue assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9) def test_complex_dotu(self): for p in 'cz': f = getattr(fblas, p+'dotu', None) if f is None: continue assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j) def test_complex_dotc(self): for p in 'cz': f = getattr(fblas, p+'dotc', None) if f is None: continue assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j) def test_nrm2(self): for p in 'sd': f = getattr(fblas, p+'nrm2', None) if f is None: continue assert_almost_equal(f([3, -4, 5]), math.sqrt(50)) for p in ['c', 'z', 'sc', 'dz']: f = getattr(fblas, p+'nrm2', None) if f is None: continue assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50)) def test_scal(self): for p in 'sd': f = getattr(fblas, p+'scal', None) if f is None: continue assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10]) for p in 'cz': f = getattr(fblas, p+'scal', None) if f is None: continue assert_array_almost_equal(f(3j, [3j, -4, 3-4j]), [-9, -12j, 12+9j]) for p in ['cs', 'zd']: f = getattr(fblas, p+'scal', None) if f is None: continue assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j]) def test_swap(self): for p in 'sd': f = getattr(fblas, p+'swap', None) if f is None: continue x, y = [2, 3, 1], [-2, 3, 7] x1, y1 = f(x, y) assert_array_almost_equal(x1, y) assert_array_almost_equal(y1, x) for p in 'cz': f = getattr(fblas, p+'swap', None) if f is None: continue x, y = [2, 3j, 1], [-2, 3, 7-3j] x1, y1 = f(x, y) assert_array_almost_equal(x1, y) assert_array_almost_equal(y1, x) def test_amax(self): for p in 'sd': f = getattr(fblas, 'i'+p+'amax') assert_equal(f([-2, 4, 3]), 1) for p in 'cz': f = getattr(fblas, 'i'+p+'amax') assert_equal(f([-5, 4+3j, 6]), 1) # XXX: need tests for rot,rotm,rotg,rotmg class TestFBLAS2Simple(object): def test_gemv(self): for p in 'sd': f = getattr(fblas, p+'gemv', None) if f is None: continue assert_array_almost_equal(f(3, [[3]], [-4]), [-36]) assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21]) for p in 'cz': f = getattr(fblas, p+'gemv', None) if f is None: continue assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j]) assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]), [-48-21j]) def test_ger(self): for p in 'sd': f = getattr(fblas, p+'ger', None) if f is None: continue assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]]) assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]), [[6, 8], [12, 16], [18, 24]]) assert_array_almost_equal(f(1, [1, 2], [3, 4], a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]]) for p in 'cz': f = getattr(fblas, p+'geru', None) if f is None: continue assert_array_almost_equal(f(1, [1j, 2], [3, 4]), [[3j, 4j], [6, 8]]) assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]), [[6, 8], [12, 16], [18, 24]]) for p in 'cz': for name in ('ger', 'gerc'): f = getattr(fblas, p+name, None) if f is None: continue assert_array_almost_equal(f(1, [1j, 2], [3, 4]), [[3j, 4j], [6, 8]]) assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]), [[6, 8], [12, 16], [18, 24]]) def test_syr_her(self): x = np.arange(1, 5, dtype='d') resx = np.triu(x[:, np.newaxis] * x) resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1]) y = np.linspace(0, 8.5, 17, endpoint=False) z = np.arange(1, 9, dtype='d').view('D') resz = np.triu(z[:, np.newaxis] * z) resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1]) rehz = np.triu(z[:, np.newaxis] * z.conj()) rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj()) w = np.c_[np.zeros(4), z, np.zeros(4)].ravel() for p, rtol in zip('sd', [1e-7, 1e-14]): f = getattr(fblas, p+'syr', None) if f is None: continue assert_allclose(f(1.0, x), resx, rtol=rtol) assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol) assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, y, incx=-2, offx=2, n=4), resx_reverse, rtol=rtol) a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F') b = f(1.0, x, a=a, overwrite_a=True) assert_allclose(a, resx, rtol=rtol) b = f(2.0, x, a=a) assert_(a is not b) assert_allclose(b, 3*resx, rtol=rtol) assert_raises(Exception, f, 1.0, x, incx=0) assert_raises(Exception, f, 1.0, x, offx=5) assert_raises(Exception, f, 1.0, x, offx=-2) assert_raises(Exception, f, 1.0, x, n=-2) assert_raises(Exception, f, 1.0, x, n=5) assert_raises(Exception, f, 1.0, x, lower=2) assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F')) for p, rtol in zip('cz', [1e-7, 1e-14]): f = getattr(fblas, p+'syr', None) if f is None: continue assert_allclose(f(1.0, z), resz, rtol=rtol) assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol) assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, w, incx=-3, offx=1, n=4), resz_reverse, rtol=rtol) a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F') b = f(1.0, z, a=a, overwrite_a=True) assert_allclose(a, resz, rtol=rtol) b = f(2.0, z, a=a) assert_(a is not b) assert_allclose(b, 3*resz, rtol=rtol) assert_raises(Exception, f, 1.0, x, incx=0) assert_raises(Exception, f, 1.0, x, offx=5) assert_raises(Exception, f, 1.0, x, offx=-2) assert_raises(Exception, f, 1.0, x, n=-2) assert_raises(Exception, f, 1.0, x, n=5) assert_raises(Exception, f, 1.0, x, lower=2) assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F')) for p, rtol in zip('cz', [1e-7, 1e-14]): f = getattr(fblas, p+'her', None) if f is None: continue assert_allclose(f(1.0, z), rehz, rtol=rtol) assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol) assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, w, incx=-3, offx=1, n=4), rehz_reverse, rtol=rtol) a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F') b = f(1.0, z, a=a, overwrite_a=True) assert_allclose(a, rehz, rtol=rtol) b = f(2.0, z, a=a) assert_(a is not b) assert_allclose(b, 3*rehz, rtol=rtol) assert_raises(Exception, f, 1.0, x, incx=0) assert_raises(Exception, f, 1.0, x, offx=5) assert_raises(Exception, f, 1.0, x, offx=-2) assert_raises(Exception, f, 1.0, x, n=-2) assert_raises(Exception, f, 1.0, x, n=5) assert_raises(Exception, f, 1.0, x, lower=2) assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F')) def test_syr2(self): x = np.arange(1, 5, dtype='d') y = np.arange(5, 9, dtype='d') resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x) resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1] + y[::-1, np.newaxis] * x[::-1]) q = np.linspace(0, 8.5, 17, endpoint=False) for p, rtol in zip('sd', [1e-7, 1e-14]): f = getattr(fblas, p+'syr2', None) if f is None: continue assert_allclose(f(1.0, x, y), resxy, rtol=rtol) assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol) assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol) assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10), resxy, rtol=rtol) assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3), resxy[:3, :3], rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10), resxy_reverse, rtol=rtol) a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F') b = f(1.0, x, y, a=a, overwrite_a=True) assert_allclose(a, resxy, rtol=rtol) b = f(2.0, x, y, a=a) assert_(a is not b) assert_allclose(b, 3*resxy, rtol=rtol) assert_raises(Exception, f, 1.0, x, y, incx=0) assert_raises(Exception, f, 1.0, x, y, offx=5) assert_raises(Exception, f, 1.0, x, y, offx=-2) assert_raises(Exception, f, 1.0, x, y, incy=0) assert_raises(Exception, f, 1.0, x, y, offy=5) assert_raises(Exception, f, 1.0, x, y, offy=-2) assert_raises(Exception, f, 1.0, x, y, n=-2) assert_raises(Exception, f, 1.0, x, y, n=5) assert_raises(Exception, f, 1.0, x, y, lower=2) assert_raises(Exception, f, 1.0, x, y, a=np.zeros((2, 2), 'd', 'F')) def test_her2(self): x = np.arange(1, 9, dtype='d').view('D') y = np.arange(9, 17, dtype='d').view('D') resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj() resxy = np.triu(resxy) resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj() resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj() resxy_reverse = np.triu(resxy_reverse) u = np.c_[np.zeros(4), x, np.zeros(4)].ravel() v = np.c_[np.zeros(4), y, np.zeros(4)].ravel() for p, rtol in zip('cz', [1e-7, 1e-14]): f = getattr(fblas, p+'her2', None) if f is None: continue assert_allclose(f(1.0, x, y), resxy, rtol=rtol) assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol) assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(), rtol=rtol) assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1), resxy, rtol=rtol) assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3), resxy[:3, :3], rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1), resxy_reverse, rtol=rtol) a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F') b = f(1.0, x, y, a=a, overwrite_a=True) assert_allclose(a, resxy, rtol=rtol) b = f(2.0, x, y, a=a) assert_(a is not b) assert_allclose(b, 3*resxy, rtol=rtol) assert_raises(Exception, f, 1.0, x, y, incx=0) assert_raises(Exception, f, 1.0, x, y, offx=5) assert_raises(Exception, f, 1.0, x, y, offx=-2) assert_raises(Exception, f, 1.0, x, y, incy=0) assert_raises(Exception, f, 1.0, x, y, offy=5) assert_raises(Exception, f, 1.0, x, y, offy=-2) assert_raises(Exception, f, 1.0, x, y, n=-2) assert_raises(Exception, f, 1.0, x, y, n=5) assert_raises(Exception, f, 1.0, x, y, lower=2) assert_raises(Exception, f, 1.0, x, y, a=np.zeros((2, 2), 'd', 'F')) def test_gbmv(self): seed(1234) for ind, dtype in enumerate(DTYPES): n = 7 m = 5 kl = 1 ku = 2 # fake a banded matrix via toeplitz A = toeplitz(append(rand(kl+1), zeros(m-kl-1)), append(rand(ku+1), zeros(n-ku-1))) A = A.astype(dtype) Ab = zeros((kl+ku+1, n), dtype=dtype) # Form the banded storage Ab[2, :5] = A[0, 0] # diag Ab[1, 1:6] = A[0, 1] # sup1 Ab[0, 2:7] = A[0, 2] # sup2 Ab[3, :4] = A[1, 0] # sub1 x = rand(n).astype(dtype) y = rand(m).astype(dtype) alpha, beta = dtype(3), dtype(-5) func, = get_blas_funcs(('gbmv',), dtype=dtype) y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab, x=x, y=y, beta=beta) y2 = alpha * A.dot(x) + beta * y assert_array_almost_equal(y1, y2) def test_sbmv_hbmv(self): seed(1234) for ind, dtype in enumerate(DTYPES): n = 6 k = 2 A = zeros((n, n), dtype=dtype) Ab = zeros((k+1, n), dtype=dtype) # Form the array and its packed banded storage A[arange(n), arange(n)] = rand(n) for ind2 in range(1, k+1): temp = rand(n-ind2) A[arange(n-ind2), arange(ind2, n)] = temp Ab[-1-ind2, ind2:] = temp A = A.astype(dtype) A = A + A.T if ind < 2 else A + A.conj().T Ab[-1, :] = diag(A) x = rand(n).astype(dtype) y = rand(n).astype(dtype) alpha, beta = dtype(1.25), dtype(3) if ind > 1: func, = get_blas_funcs(('hbmv',), dtype=dtype) else: func, = get_blas_funcs(('sbmv',), dtype=dtype) y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta) y2 = alpha * A.dot(x) + beta * y assert_array_almost_equal(y1, y2) def test_spmv_hpmv(self): seed(1234) for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES): n = 3 A = rand(n, n).astype(dtype) if ind > 1: A += rand(n, n)*1j A = A.astype(dtype) A = A + A.T if ind < 4 else A + A.conj().T c, r = tril_indices(n) Ap = A[r, c] x = rand(n).astype(dtype) y = rand(n).astype(dtype) xlong = arange(2*n).astype(dtype) ylong = ones(2*n).astype(dtype) alpha, beta = dtype(1.25), dtype(2) if ind > 3: func, = get_blas_funcs(('hpmv',), dtype=dtype) else: func, = get_blas_funcs(('spmv',), dtype=dtype) y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta) y2 = alpha * A.dot(x) + beta * y assert_array_almost_equal(y1, y2) # Test inc and offsets y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap, incx=2, incy=2, offx=n, offy=n) y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2] assert_array_almost_equal(y1[3::2], y2) assert_almost_equal(y1[4], ylong[4]) def test_spr_hpr(self): seed(1234) for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES): n = 3 A = rand(n, n).astype(dtype) if ind > 1: A += rand(n, n)*1j A = A.astype(dtype) A = A + A.T if ind < 4 else A + A.conj().T c, r = tril_indices(n) Ap = A[r, c] x = rand(n).astype(dtype) alpha = (DTYPES+COMPLEX_DTYPES)[mod(ind, 4)](2.5) if ind > 3: func, = get_blas_funcs(('hpr',), dtype=dtype) y2 = alpha * x[:, None].dot(x[None, :].conj()) + A else: func, = get_blas_funcs(('spr',), dtype=dtype) y2 = alpha * x[:, None].dot(x[None, :]) + A y1 = func(n=n, alpha=alpha, ap=Ap, x=x) y1f = zeros((3, 3), dtype=dtype) y1f[r, c] = y1 y1f[c, r] = y1.conj() if ind > 3 else y1 assert_array_almost_equal(y1f, y2) def test_spr2_hpr2(self): seed(1234) for ind, dtype in enumerate(DTYPES): n = 3 A = rand(n, n).astype(dtype) if ind > 1: A += rand(n, n)*1j A = A.astype(dtype) A = A + A.T if ind < 2 else A + A.conj().T c, r = tril_indices(n) Ap = A[r, c] x = rand(n).astype(dtype) y = rand(n).astype(dtype) alpha = dtype(2) if ind > 1: func, = get_blas_funcs(('hpr2',), dtype=dtype) else: func, = get_blas_funcs(('spr2',), dtype=dtype) u = alpha.conj() * x[:, None].dot(y[None, :].conj()) y2 = A + u + u.conj().T y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap) y1f = zeros((3, 3), dtype=dtype) y1f[r, c] = y1 y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj() assert_array_almost_equal(y1f, y2) def test_tbmv(self): seed(1234) for ind, dtype in enumerate(DTYPES): n = 10 k = 3 x = rand(n).astype(dtype) A = zeros((n, n), dtype=dtype) # Banded upper triangular array for sup in range(k+1): A[arange(n-sup), arange(sup, n)] = rand(n-sup) # Add complex parts for c,z if ind > 1: A[nonzero(A)] += 1j * rand((k+1)*n-(k*(k+1)//2)).astype(dtype) # Form the banded storage Ab = zeros((k+1, n), dtype=dtype) for row in range(k+1): Ab[-row-1, row:] = diag(A, k=row) func, = get_blas_funcs(('tbmv',), dtype=dtype) y1 = func(k=k, a=Ab, x=x) y2 = A.dot(x) assert_array_almost_equal(y1, y2) y1 = func(k=k, a=Ab, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = A.dot(x) assert_array_almost_equal(y1, y2) y1 = func(k=k, a=Ab, x=x, diag=1, trans=1) y2 = A.T.dot(x) assert_array_almost_equal(y1, y2) y1 = func(k=k, a=Ab, x=x, diag=1, trans=2) y2 = A.conj().T.dot(x) assert_array_almost_equal(y1, y2) def test_tbsv(self): seed(1234) for ind, dtype in enumerate(DTYPES): n = 6 k = 3 x = rand(n).astype(dtype) A = zeros((n, n), dtype=dtype) # Banded upper triangular array for sup in range(k+1): A[arange(n-sup), arange(sup, n)] = rand(n-sup) # Add complex parts for c,z if ind > 1: A[nonzero(A)] += 1j * rand((k+1)*n-(k*(k+1)//2)).astype(dtype) # Form the banded storage Ab = zeros((k+1, n), dtype=dtype) for row in range(k+1): Ab[-row-1, row:] = diag(A, k=row) func, = get_blas_funcs(('tbsv',), dtype=dtype) y1 = func(k=k, a=Ab, x=x) y2 = solve(A, x) assert_array_almost_equal(y1, y2) y1 = func(k=k, a=Ab, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = solve(A, x) assert_array_almost_equal(y1, y2) y1 = func(k=k, a=Ab, x=x, diag=1, trans=1) y2 = solve(A.T, x) assert_array_almost_equal(y1, y2) y1 = func(k=k, a=Ab, x=x, diag=1, trans=2) y2 = solve(A.conj().T, x) assert_array_almost_equal(y1, y2) def test_tpmv(self): seed(1234) for ind, dtype in enumerate(DTYPES): n = 10 x = rand(n).astype(dtype) # Upper triangular array A = triu(rand(n, n)) if ind < 2 else triu(rand(n, n)+rand(n, n)*1j) # Form the packed storage c, r = tril_indices(n) Ap = A[r, c] func, = get_blas_funcs(('tpmv',), dtype=dtype) y1 = func(n=n, ap=Ap, x=x) y2 = A.dot(x) assert_array_almost_equal(y1, y2) y1 = func(n=n, ap=Ap, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = A.dot(x) assert_array_almost_equal(y1, y2) y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1) y2 = A.T.dot(x) assert_array_almost_equal(y1, y2) y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2) y2 = A.conj().T.dot(x) assert_array_almost_equal(y1, y2) def test_tpsv(self): seed(1234) for ind, dtype in enumerate(DTYPES): n = 10 x = rand(n).astype(dtype) # Upper triangular array A = triu(rand(n, n)) if ind < 2 else triu(rand(n, n)+rand(n, n)*1j) A += eye(n) # Form the packed storage c, r = tril_indices(n) Ap = A[r, c] func, = get_blas_funcs(('tpsv',), dtype=dtype) y1 = func(n=n, ap=Ap, x=x) y2 = solve(A, x) assert_array_almost_equal(y1, y2) y1 = func(n=n, ap=Ap, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = solve(A, x) assert_array_almost_equal(y1, y2) y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1) y2 = solve(A.T, x) assert_array_almost_equal(y1, y2) y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2) y2 = solve(A.conj().T, x) assert_array_almost_equal(y1, y2) def test_trmv(self): seed(1234) for ind, dtype in enumerate(DTYPES): n = 3 A = (rand(n, n)+eye(n)).astype(dtype) x = rand(3).astype(dtype) func, = get_blas_funcs(('trmv',), dtype=dtype) y1 = func(a=A, x=x) y2 = triu(A).dot(x) assert_array_almost_equal(y1, y2) y1 = func(a=A, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = triu(A).dot(x) assert_array_almost_equal(y1, y2) y1 = func(a=A, x=x, diag=1, trans=1) y2 = triu(A).T.dot(x) assert_array_almost_equal(y1, y2) y1 = func(a=A, x=x, diag=1, trans=2) y2 = triu(A).conj().T.dot(x) assert_array_almost_equal(y1, y2) def test_trsv(self): seed(1234) for ind, dtype in enumerate(DTYPES): n = 15 A = (rand(n, n)+eye(n)).astype(dtype) x = rand(n).astype(dtype) func, = get_blas_funcs(('trsv',), dtype=dtype) y1 = func(a=A, x=x) y2 = solve(triu(A), x) assert_array_almost_equal(y1, y2) y1 = func(a=A, x=x, lower=1) y2 = solve(tril(A), x) assert_array_almost_equal(y1, y2) y1 = func(a=A, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = solve(triu(A), x) assert_array_almost_equal(y1, y2) y1 = func(a=A, x=x, diag=1, trans=1) y2 = solve(triu(A).T, x) assert_array_almost_equal(y1, y2) y1 = func(a=A, x=x, diag=1, trans=2) y2 = solve(triu(A).conj().T, x) assert_array_almost_equal(y1, y2) class TestFBLAS3Simple(object): def test_gemm(self): for p in 'sd': f = getattr(fblas, p+'gemm', None) if f is None: continue assert_array_almost_equal(f(3, [3], [-4]), [[-36]]) assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21]) for p in 'cz': f = getattr(fblas, p+'gemm', None) if f is None: continue assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]]) assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j]) def _get_func(func, ps='sdzc'): """Just a helper: return a specified BLAS function w/typecode.""" for p in ps: f = getattr(fblas, p+func, None) if f is None: continue yield f class TestBLAS3Symm(object): def setup_method(self): self.a = np.array([[1., 2.], [0., 1.]]) self.b = np.array([[1., 0., 3.], [0., -1., 2.]]) self.c = np.ones((2, 3)) self.t = np.array([[2., -1., 8.], [3., 0., 9.]]) def test_symm(self): for f in _get_func('symm'): res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.) assert_array_almost_equal(res, self.t) res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.) assert_array_almost_equal(res, self.t) res = f(a=self.a, b=self.b.T, side=1, c=self.c.T, alpha=1., beta=1.) assert_array_almost_equal(res, self.t.T) def test_summ_wrong_side(self): f = getattr(fblas, 'dsymm', None) if f is not None: assert_raises(Exception, f, **{'a': self.a, 'b': self.b, 'alpha': 1, 'side': 1}) # `side=1` means C <- B*A, hence shapes of A and B are to be # compatible. Otherwise, f2py exception is raised def test_symm_wrong_uplo(self): """SYMM only considers the upper/lower part of A. Hence setting wrong value for `lower` (default is lower=0, meaning upper triangle) gives a wrong result. """ f = getattr(fblas, 'dsymm', None) if f is not None: res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.) assert np.allclose(res, self.t) res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.) assert not np.allclose(res, self.t) class TestBLAS3Syrk(object): def setup_method(self): self.a = np.array([[1., 0.], [0., -2.], [2., 3.]]) self.t = np.array([[1., 0., 2.], [0., 4., -6.], [2., -6., 13.]]) self.tt = np.array([[5., 6.], [6., 13.]]) def test_syrk(self): for f in _get_func('syrk'): c = f(a=self.a, alpha=1.) assert_array_almost_equal(np.triu(c), np.triu(self.t)) c = f(a=self.a, alpha=1., lower=1) assert_array_almost_equal(np.tril(c), np.tril(self.t)) c0 = np.ones(self.t.shape) c = f(a=self.a, alpha=1., beta=1., c=c0) assert_array_almost_equal(np.triu(c), np.triu(self.t+c0)) c = f(a=self.a, alpha=1., trans=1) assert_array_almost_equal(np.triu(c), np.triu(self.tt)) # prints '0-th dimension must be fixed to 3 but got 5', # FIXME: suppress? # FIXME: how to catch the _fblas.error? def test_syrk_wrong_c(self): f = getattr(fblas, 'dsyrk', None) if f is not None: assert_raises(Exception, f, **{'a': self.a, 'alpha': 1., 'c': np.ones((5, 8))}) # if C is supplied, it must have compatible dimensions class TestBLAS3Syr2k(object): def setup_method(self): self.a = np.array([[1., 0.], [0., -2.], [2., 3.]]) self.b = np.array([[0., 1.], [1., 0.], [0, 1.]]) self.t = np.array([[0., -1., 3.], [-1., 0., 0.], [3., 0., 6.]]) self.tt = np.array([[0., 1.], [1., 6]]) def test_syr2k(self): for f in _get_func('syr2k'): c = f(a=self.a, b=self.b, alpha=1.) assert_array_almost_equal(np.triu(c), np.triu(self.t)) c = f(a=self.a, b=self.b, alpha=1., lower=1) assert_array_almost_equal(np.tril(c), np.tril(self.t)) c0 = np.ones(self.t.shape) c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0) assert_array_almost_equal(np.triu(c), np.triu(self.t+c0)) c = f(a=self.a, b=self.b, alpha=1., trans=1) assert_array_almost_equal(np.triu(c), np.triu(self.tt)) # prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress? def test_syr2k_wrong_c(self): f = getattr(fblas, 'dsyr2k', None) if f is not None: assert_raises(Exception, f, **{'a': self.a, 'b': self.b, 'alpha': 1., 'c': np.zeros((15, 8))}) # if C is supplied, it must have compatible dimensions class TestSyHe(object): """Quick and simple tests for (zc)-symm, syrk, syr2k.""" def setup_method(self): self.sigma_y = np.array([[0., -1.j], [1.j, 0.]]) def test_symm_zc(self): for f in _get_func('symm', 'zc'): # NB: a is symmetric w/upper diag of ONLY res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), np.diag([1, -1])) def test_hemm_zc(self): for f in _get_func('hemm', 'zc'): # NB: a is hermitian w/upper diag of ONLY res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), np.diag([1, 1])) def test_syrk_zr(self): for f in _get_func('syrk', 'zc'): res = f(a=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), np.diag([-1, -1])) def test_herk_zr(self): for f in _get_func('herk', 'zc'): res = f(a=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), np.diag([1, 1])) def test_syr2k_zr(self): for f in _get_func('syr2k', 'zc'): res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1])) def test_her2k_zr(self): for f in _get_func('her2k', 'zc'): res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1])) class TestTRMM(object): """Quick and simple tests for dtrmm.""" def setup_method(self): self.a = np.array([[1., 2., ], [-2., 1.]]) self.b = np.array([[3., 4., -1.], [5., 6., -2.]]) def test_ab(self): f = getattr(fblas, 'dtrmm', None) if f is not None: result = f(1., self.a, self.b) # default a is upper triangular expected = np.array([[13., 16., -5.], [5., 6., -2.]]) assert_array_almost_equal(result, expected) def test_ab_lower(self): f = getattr(fblas, 'dtrmm', None) if f is not None: result = f(1., self.a, self.b, lower=True) expected = np.array([[3., 4., -1.], [-1., -2., 0.]]) # now a is lower triangular assert_array_almost_equal(result, expected) def test_b_overwrites(self): # BLAS dtrmm modifies B argument in-place. # Here the default is to copy, but this can be overridden f = getattr(fblas, 'dtrmm', None) if f is not None: for overwr in [True, False]: bcopy = self.b.copy() result = f(1., self.a, bcopy, overwrite_b=overwr) # C-contiguous arrays are copied assert_(bcopy.flags.f_contiguous is False and np.may_share_memory(bcopy, result) is False) assert_equal(bcopy, self.b) bcopy = np.asfortranarray(self.b.copy()) # or just transpose it result = f(1., self.a, bcopy, overwrite_b=True) assert_(bcopy.flags.f_contiguous is True and np.may_share_memory(bcopy, result) is True) assert_array_almost_equal(bcopy, result) def test_trsm(): seed(1234) for ind, dtype in enumerate(DTYPES): tol = np.finfo(dtype).eps*1000 func, = get_blas_funcs(('trsm',), dtype=dtype) # Test protection against size mismatches A = rand(4, 5).astype(dtype) B = rand(4, 4).astype(dtype) alpha = dtype(1) assert_raises(Exception, func, alpha, A, B) assert_raises(Exception, func, alpha, A.T, B) n = 8 m = 7 alpha = dtype(-2.5) A = (rand(m, m) if ind < 2 else rand(m, m) + rand(m, m)*1j) + eye(m) A = A.astype(dtype) Au = triu(A) Al = tril(A) B1 = rand(m, n).astype(dtype) B2 = rand(n, m).astype(dtype) x1 = func(alpha=alpha, a=A, b=B1) assert_equal(B1.shape, x1.shape) x2 = solve(Au, alpha*B1) assert_allclose(x1, x2, atol=tol) x1 = func(alpha=alpha, a=A, b=B1, trans_a=1) x2 = solve(Au.T, alpha*B1) assert_allclose(x1, x2, atol=tol) x1 = func(alpha=alpha, a=A, b=B1, trans_a=2) x2 = solve(Au.conj().T, alpha*B1) assert_allclose(x1, x2, atol=tol) x1 = func(alpha=alpha, a=A, b=B1, diag=1) Au[arange(m), arange(m)] = dtype(1) x2 = solve(Au, alpha*B1) assert_allclose(x1, x2, atol=tol) x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1) x2 = solve(Au.conj().T, alpha*B2.conj().T) assert_allclose(x1, x2.conj().T, atol=tol) x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1) Al[arange(m), arange(m)] = dtype(1) x2 = solve(Al.conj().T, alpha*B2.conj().T) assert_allclose(x1, x2.conj().T, atol=tol)
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 17f654b833624b21bdb7784f7d9a4ae8 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
From social-admin@linux.ie Mon Jul 22 19:24:30 2002 Return-Path: <social-admin@linux.ie> Delivered-To: yyyy@localhost.netnoteinc.com Received: from localhost (localhost [127.0.0.1]) by phobos.labs.netnoteinc.com (Postfix) with ESMTP id 98BBD440C8 for <jm@localhost>; Mon, 22 Jul 2002 14:24:29 -0400 (EDT) Received: from dogma.slashnull.org [212.17.35.15] by localhost with IMAP (fetchmail-5.9.0) for jm@localhost (single-drop); Mon, 22 Jul 2002 19:24:29 +0100 (IST) Received: from webnote.net (mail.webnote.net [193.120.211.219]) by dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g6MFIB902770 for <jm+ilug-social@jmason.org>; Mon, 22 Jul 2002 16:18:11 +0100 Received: from lugh.tuatha.org (root@lugh.tuatha.org [194.125.145.45]) by webnote.net (8.9.3/8.9.3) with ESMTP id LAA31420 for <jm+ilug-social@jmason.org>; Mon, 22 Jul 2002 11:45:41 +0100 Received: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org (8.9.3/8.9.3) with ESMTP id LAA21951; Mon, 22 Jul 2002 11:45:02 +0100 Received: from mandark.labs.netnoteinc.com ([213.105.180.140]) by lugh.tuatha.org (8.9.3/8.9.3) with ESMTP id LAA21912 for <social@linux.ie>; Mon, 22 Jul 2002 11:44:56 +0100 X-Authentication-Warning: lugh.tuatha.org: Host [213.105.180.140] claimed to be mandark.labs.netnoteinc.com Received: from triton.labs.netnoteinc.com (lbedford@triton.labs.netnoteinc.com [192.168.2.12]) by mandark.labs.netnoteinc.com (8.11.6/8.11.6) with SMTP id g6MAitp08916 for <social@linux.ie>; Mon, 22 Jul 2002 11:44:56 +0100 Date: Mon, 22 Jul 2002 11:44:55 +0100 From: Liam Bedford <lbedford@lbedford.org> To: social@linux.ie Subject: Re: [ILUG-Social] Completely silent pc Message-Id: <20020722114455.080be6c6.lbedford@lbedford.org> In-Reply-To: <20020720181512.D23917@ie.suberic.net> References: <Pine.GSO.4.10.10207192318220.27597-100000@matrix> <20020720051950.GE28205@linuxmafia.com> <20020720181512.D23917@ie.suberic.net> Organization: Netnote International X-Mailer: Sylpheed version 0.7.8claws69 (GTK+ 1.2.10; i386-debian-linux-gnu) MIME-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-15 Content-Transfer-Encoding: 8bit Sender: social-admin@linux.ie Errors-To: social-admin@linux.ie X-Mailman-Version: 1.1 Precedence: bulk List-Id: Irish Linux Users' Group social events <social.linux.ie> X-Beenthere: social@linux.ie On Sat, 20 Jul 2002 18:15:12 +0100 kevin lyda claiming to think: > On Fri, Jul 19, 2002 at 10:19:50PM -0700, Rick Moen wrote: > > Some people strip down old 486 boxes, take out the hard drive, disable > > the fans, and run the thing from just a floppy drive or a CDR you've > > burned for the purpose. > > what about using a pcmcia card and a compaq flash card? or doing an > nfs boot to a server in a noiser part of the house? (the boiler room > or something like that) > hmm. there are versions of OpenBSD that run from a 32M compact flash IIRC. and antefacto's software ran in 64M. there are CF->IDE adapters anyway, so get a 256M CF (100¤+), mount it RO, and use that? /me is also in the market for one of the 60W fanless PSU's that antefacto had, if someone wants to get a few of them. L. -- dBP dBBBBb | If you're looking at me to be an accountant dBP | Then you will look but you will never see dBP dBBBK' | If you're looking at me to start having babies dBP dB' db | Then you can wish because I'm not here to fool around dBBBBP dBBBBP' | Belle & Sebastian (Family Tree) -- Irish Linux Users' Group Social Events: social@linux.ie http://www.linux.ie/mailman/listinfo/social for (un)subscription information. List maintainer: listmaster@linux.ie
{ "pile_set_name": "Github" }
/* Copyright 2013-2020 Homegear GmbH * * Homegear is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Homegear is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Homegear. If not, see <http://www.gnu.org/licenses/>. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef NO_SCRIPTENGINE #include "PhpEvents.h" #include "../GD/GD.h" namespace Homegear { std::mutex PhpEvents::eventsMapMutex; std::map<int32_t, std::shared_ptr<PhpEvents>> PhpEvents::eventsMap; PhpEvents::PhpEvents(std::string &token, std::function<void(std::string output, bool error)> &outputCallback, std::function<BaseLib::PVariable(std::string methodName, BaseLib::PVariable parameters, bool wait)> &rpcCallback) { _stopProcessing = false; _bufferCount = 0; _token = token; _outputCallback = outputCallback; _rpcCallback = rpcCallback; } PhpEvents::~PhpEvents() { stop(); } void PhpEvents::stop() { if (_stopProcessing) return; _stopProcessing = true; _processingConditionVariable.notify_all(); } bool PhpEvents::enqueue(std::shared_ptr<EventData> &entry) { try { if (!entry || _stopProcessing) return false; std::unique_lock<std::mutex> lock(_queueMutex); if (_stopProcessing) return true; if (_bufferCount >= _bufferSize) return false; { std::lock_guard<std::mutex> bufferGuard(_bufferMutex); _buffer[_bufferTail] = entry; _bufferTail = (_bufferTail + 1) % _bufferSize; ++_bufferCount; } _processingConditionVariable.notify_one(); return true; } catch (const std::exception &ex) { GD::bl->out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what()); } return false; } std::shared_ptr<PhpEvents::EventData> PhpEvents::poll(int32_t timeout) { if (timeout < 1) timeout = 10000; std::shared_ptr<EventData> eventData; if (_stopProcessing) return eventData; try { { std::unique_lock<std::mutex> lock(_queueMutex); if (!_processingConditionVariable.wait_for(lock, std::chrono::milliseconds(timeout), [&] { return _bufferCount > 0 || _stopProcessing; })) return eventData; if (_stopProcessing) return eventData; std::lock_guard<std::mutex> bufferGuard(_bufferMutex); eventData = _buffer[_bufferHead]; _buffer[_bufferHead].reset(); _bufferHead = (_bufferHead + 1) % _bufferSize; --_bufferCount; } } catch (const std::exception &ex) { GD::bl->out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what()); } return eventData; } void PhpEvents::addPeer(uint64_t peerId, int32_t channel, std::string &variable) { try { std::lock_guard<std::mutex> peersGuard(_peersMutex); if (channel > -1 && !variable.empty()) _peers[peerId][channel].insert(variable); else _peers.emplace(std::make_pair(peerId, std::map<int32_t, std::set<std::string>>())); } catch (const std::exception &ex) { GD::bl->out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what()); } } void PhpEvents::removePeer(uint64_t peerId, int32_t channel, std::string &variable) { try { std::lock_guard<std::mutex> peersGuard(_peersMutex); if (channel > -1 && !variable.empty()) { _peers[peerId][channel].erase(variable); if (_peers[peerId][channel].empty()) _peers[peerId].erase(channel); } else _peers.erase(peerId); } catch (const std::exception &ex) { GD::bl->out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what()); } } bool PhpEvents::peerSubscribed(uint64_t peerId, int32_t channel, std::string &variable) { try { std::lock_guard<std::mutex> peersGuard(_peersMutex); auto peerIterator = _peers.find(peerId); if (peerIterator != _peers.end()) { if (!peerIterator->second.empty() && channel > -1 && !variable.empty()) { auto channelIterator = peerIterator->second.find(channel); if (channelIterator == peerIterator->second.end()) return false; return channelIterator->second.find(variable) != channelIterator->second.end(); } else return true; } } catch (const std::exception &ex) { GD::bl->out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what()); } return false; } } #endif
{ "pile_set_name": "Github" }
<?php class YumStatisticsController extends YumController { const PAGE_SIZE=10; public function accessRules() { return array( array('allow', 'actions'=>array('index'), 'users'=>array(Yii::app()->user->name ), 'expression' => 'Yii::app()->user->isAdmin()' ), array('deny', 'users'=>array('*'))); } public function actions() { return array('index'); } public function actionIndex() { $this->layout = Yum::module()->adminLayout; //$this->layout = Yum::module()->baseLayout; $this->render('statistics', array( 'total_users' => YumUser::model()->count(), 'active_users' => YumUser::model()->count('status = '.YumUser::STATUS_ACTIVE), 'todays_registered_users' => YumUser::model()->count('createtime >= '.strtotime(date('Y-m-d'))), 'inactive_users' => YumUser::model()->count('status = '.YumUser::STATUS_INACTIVE), 'banned_users' => YumUser::model()->count('status = '.YumUser::STATUS_BANNED), 'admin_users' => YumUser::model()->count('superuser = 1'), // 'roles' => YumRole::model()->count(), // 'profiles' => YumProfile::model()->count(), // 'profile_fields' => YumProfileField::model()->count(), // 'profile_field_groups' => YumProfileFieldsGroup::model()->count(), // 'profile_views' => YumProfileVisit::model() !== false ? YumProfileVisit::model()->count() : null, // 'messages' => YumMessage::model()->count(), 'logins_today' => $this->loginsToday(), )); } public function getStartOfDay($time = 0) { if($time == 0) $time = time(); $hours = date("G", $time); $minutes = date("i", $time); $seconds = date("s", $time); $temp = $time; $temp -= ($hours * 3600); $temp -= ($minutes * 60); $temp -= $seconds; $today = $temp; $first = $today; return $first; } public function loginsToday() { $day = $this->getStartOfDay(time()); return YumUser::model()->count( 'lastvisit > :begin and lastvisit < :end', array( ':begin' => $day, ':end' => $day + 86400)); } }
{ "pile_set_name": "Github" }
#ifndef _EXDLL_H_ #define _EXDLL_H_ // only include this file from one place in your DLL. // (it is all static, if you use it in two places it will fail) #define EXDLL_INIT() { \ g_stringsize=string_size; \ g_stacktop=stacktop; \ g_variables=variables; } // For page showing plug-ins #define WM_NOTIFY_OUTER_NEXT (WM_USER+0x8) #define WM_NOTIFY_CUSTOM_READY (WM_USER+0xd) #define NOTIFY_BYE_BYE 'x' typedef struct _stack_t { struct _stack_t *next; TCHAR text[1]; // this should be the length of string_size } stack_t; static unsigned int g_stringsize; static stack_t **g_stacktop; static TCHAR *g_variables; static int __stdcall popstring(TCHAR *str); // 0 on success, 1 on empty stack static void __stdcall pushstring(const TCHAR *str); enum { INST_0, // $0 INST_1, // $1 INST_2, // $2 INST_3, // $3 INST_4, // $4 INST_5, // $5 INST_6, // $6 INST_7, // $7 INST_8, // $8 INST_9, // $9 INST_R0, // $R0 INST_R1, // $R1 INST_R2, // $R2 INST_R3, // $R3 INST_R4, // $R4 INST_R5, // $R5 INST_R6, // $R6 INST_R7, // $R7 INST_R8, // $R8 INST_R9, // $R9 INST_CMDLINE, // $CMDLINE INST_INSTDIR, // $INSTDIR INST_OUTDIR, // $OUTDIR INST_EXEDIR, // $EXEDIR INST_LANG, // $LANGUAGE __INST_LAST }; // utility functions (not required but often useful) static int __stdcall popstring(TCHAR *str) { stack_t *th; if (!g_stacktop || !*g_stacktop) return 1; th=(*g_stacktop); lstrcpy(str,th->text); *g_stacktop = th->next; GlobalFree((HGLOBAL)th); return 0; } static void __stdcall pushstring(const TCHAR *str) { stack_t *th; if (!g_stacktop) return; th=(stack_t*)GlobalAlloc(GPTR,sizeof(stack_t)+g_stringsize*sizeof(TCHAR)); lstrcpyn(th->text,str,g_stringsize); th->next=*g_stacktop; *g_stacktop=th; } static TCHAR * __stdcall getuservariable(int varnum) { if (varnum < 0 || varnum >= __INST_LAST) return NULL; return g_variables+varnum*g_stringsize; } static void __stdcall setuservariable(int varnum, const TCHAR *var) { if (var != NULL && varnum >= 0 && varnum < __INST_LAST) lstrcpy(g_variables + varnum*g_stringsize, var); } #endif//_EXDLL_H_
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>brewNoteWidget</class> <widget class="QWidget" name="brewNoteWidget"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>636</width> <height>448</height> </rect> </property> <property name="windowTitle"> <string>brewNote</string> </property> <property name="windowIcon"> <iconset resource="../brewtarget.qrc"> <normaloff>:/images/edit.svg</normaloff>:/images/edit.svg</iconset> </property> <layout class="QVBoxLayout" name="verticalLayout_2"> <item> <widget class="QScrollArea" name="scrollArea"> <property name="frameShape"> <enum>QFrame::Panel</enum> </property> <property name="widgetResizable"> <bool>true</bool> </property> <widget class="QWidget" name="scrollAreaWidgetContents"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>626</width> <height>438</height> </rect> </property> <property name="configSection" stdset="0"> <string notr="true">page_preboil</string> </property> <layout class="QHBoxLayout" name="horizontalLayout_2"> <item> <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> <widget class="QToolBox" name="toolBox_brewnote"> <property name="sizePolicy"> <sizepolicy hsizetype="Fixed" vsizetype="Minimum"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>252</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>252</width> <height>16777215</height> </size> </property> <property name="mouseTracking"> <bool>false</bool> </property> <property name="currentIndex"> <number>0</number> </property> <widget class="QWidget" name="page_preboil"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>242</width> <height>349</height> </rect> </property> <property name="configSection" stdset="0"> <string notr="true">page_preboil</string> </property> <attribute name="label"> <string>Preboil</string> </attribute> <layout class="QFormLayout" name="formLayout_2"> <item row="0" column="0"> <widget class="BtDensityLabel" name="btLabel_Sg"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string>SG</string> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="buddy"> <cstring>lineEdit_SG</cstring> </property> </widget> </item> <item row="0" column="1"> <widget class="BtDensityEdit" name="lineEdit_SG"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="toolTip"> <string>Preboil gravity</string> </property> <property name="alignment"> <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set> </property> <property name="editField" stdset="0"> <string notr="true">sg</string> </property> </widget> </item> <item row="1" column="0"> <widget class="BtVolumeLabel" name="btLabel_volIntoBk"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string>Volume</string> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="buddy"> <cstring>lineEdit_volIntoBK</cstring> </property> </widget> </item> <item row="1" column="1"> <widget class="BtVolumeEdit" name="lineEdit_volIntoBK"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="toolTip"> <string>Volume of wort collected</string> </property> <property name="editField" stdset="0"> <string notr="true">volumeIntoBK_l</string> </property> </widget> </item> <item row="2" column="0"> <widget class="BtTemperatureLabel" name="btLabel_strikeTemp"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string>Strike Temp</string> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="buddy"> <cstring>lineEdit_strikeTemp</cstring> </property> </widget> </item> <item row="2" column="1"> <widget class="BtTemperatureEdit" name="lineEdit_strikeTemp"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="toolTip"> <string>Temperature of strike water before dough in</string> </property> <property name="editField" stdset="0"> <string notr="true">strikeTemp_c</string> </property> </widget> </item> <item row="3" column="0"> <widget class="BtTemperatureLabel" name="btLabel_mashFinTemp"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string>Final Temp</string> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="buddy"> <cstring>lineEdit_mashFinTemp</cstring> </property> </widget> </item> <item row="3" column="1"> <widget class="BtTemperatureEdit" name="lineEdit_mashFinTemp"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="toolTip"> <string>Temperature of mash before mash out</string> </property> <property name="editField" stdset="0"> <string notr="true">mashFinTemp_c</string> </property> </widget> </item> </layout> </widget> <widget class="QWidget" name="page_postboil"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>242</width> <height>349</height> </rect> </property> <property name="configSection" stdset="0"> <string notr="true">page_postboil</string> </property> <attribute name="label"> <string>Postboil</string> </attribute> <layout class="QFormLayout" name="formLayout"> <item row="0" column="0"> <widget class="BtDensityLabel" name="btLabel_Og"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string>OG</string> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="buddy"> <cstring>lineEdit_OG</cstring> </property> </widget> </item> <item row="0" column="1"> <widget class="BtDensityEdit" name="lineEdit_OG"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="toolTip"> <string>Post boil gravity</string> </property> <property name="editField" stdset="0"> <string notr="true">og</string> </property> </widget> </item> <item row="1" column="0"> <widget class="BtVolumeLabel" name="btLabel_postBoilVol"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string>Postboil Volume</string> </property> <property name="scaledContents"> <bool>false</bool> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="wordWrap"> <bool>true</bool> </property> <property name="buddy"> <cstring>lineEdit_postBoilVol</cstring> </property> </widget> </item> <item row="1" column="1"> <widget class="BtVolumeEdit" name="lineEdit_postBoilVol"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="toolTip"> <string>Volume of wort in BK after boil</string> </property> <property name="editField" stdset="0"> <string notr="true">postBoilVolume_l</string> </property> </widget> </item> <item row="2" column="0"> <widget class="BtVolumeLabel" name="btLabel_volIntoFerm"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="toolTip"> <string>Volume of wort transferred to fermenter</string> </property> <property name="text"> <string>Volume into fermenter</string> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="wordWrap"> <bool>true</bool> </property> <property name="buddy"> <cstring>lineEdit_volIntoFerm</cstring> </property> </widget> </item> <item row="2" column="1"> <widget class="BtVolumeEdit" name="lineEdit_volIntoFerm"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="editField" stdset="0"> <string notr="true">volumeIntoFerm_l</string> </property> </widget> </item> <item row="3" column="0"> <widget class="BtTemperatureLabel" name="btLabel_pitchTemp"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string> Pitch Temp</string> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="wordWrap"> <bool>true</bool> </property> <property name="buddy"> <cstring>lineEdit_pitchTemp</cstring> </property> </widget> </item> <item row="3" column="1"> <widget class="BtTemperatureEdit" name="lineEdit_pitchTemp"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="toolTip"> <string>Temperature of wort when yeast is pitched</string> </property> <property name="editField" stdset="0"> <string notr="true">pitchTemp_c</string> </property> </widget> </item> </layout> </widget> <widget class="QWidget" name="page_postferment"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>242</width> <height>349</height> </rect> </property> <property name="configSection" stdset="0"> <string notr="true">page_postferment</string> </property> <attribute name="label"> <string>Postferment</string> </attribute> <layout class="QFormLayout" name="formLayout_5"> <item row="0" column="0"> <widget class="BtDensityLabel" name="btLabel_postFermentFg"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string notr="true">FG</string> </property> <property name="buddy"> <cstring>lineEdit_FG</cstring> </property> </widget> </item> <item row="0" column="1"> <widget class="BtDensityEdit" name="lineEdit_FG"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="toolTip"> <string>Final gravity</string> </property> <property name="editField" stdset="0"> <string notr="true">fg</string> </property> </widget> </item> <item row="1" column="0"> <widget class="BtVolumeLabel" name="btLabel_finalVolume"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string notr="true">Volume</string> </property> <property name="buddy"> <cstring>lineEdit_finalVol</cstring> </property> </widget> </item> <item row="1" column="1"> <widget class="BtVolumeEdit" name="lineEdit_finalVol"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>100</width> <height>0</height> </size> </property> <property name="maximumSize"> <size> <width>100</width> <height>16777215</height> </size> </property> <property name="toolTip"> <string>Volume of beer into serving keg/bottles</string> </property> <property name="editField" stdset="0"> <string notr="true">finalVolume_l</string> </property> </widget> </item> <item row="2" column="0"> <widget class="BtDateLabel" name="btLabel_fermentDate"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="text"> <string notr="true">Date</string> </property> <property name="buddy"> <cstring>lineEdit_fermentDate</cstring> </property> </widget> </item> <item row="2" column="1"> <widget class="QDateTimeEdit" name="lineEdit_fermentDate"> <property name="date"> <date> <year>2014</year> <month>10</month> <day>8</day> </date> </property> <property name="displayFormat"> <string>yyyy-dd-MM</string> </property> <property name="calendarPopup"> <bool>true</bool> </property> <property name="editField" stdset="0"> <string notr="true">fermentDate</string> </property> </widget> </item> </layout> </widget> </widget> </item> <item> <layout class="QVBoxLayout" name="verticalLayout"> <item> <layout class="QFormLayout" name="formLayout_3"> <property name="fieldGrowthPolicy"> <enum>QFormLayout::ExpandingFieldsGrow</enum> </property> <item row="0" column="0"> <widget class="QLabel" name="btLabel_effInfoBk"> <property name="statusTip"> <string>Percent efficiency into boil kettle</string> </property> <property name="text"> <string>Efficiency into boil kettle</string> </property> </widget> </item> <item row="0" column="1"> <widget class="BtDigitWidget" name="lcdnumber_effBK"> <property name="text"> <string/> </property> </widget> </item> <item row="1" column="0"> <widget class="BtDensityLabel" name="btLabel_projectedOg"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="statusTip"> <string>Expected OG, based on measured FG</string> </property> <property name="text"> <string>Projected OG</string> </property> <property name="editField" stdset="0"> <string notr="true">projOg</string> </property> <property name="configSection" stdset="0"> <string notr="true">page_preboil</string> </property> </widget> </item> <item row="1" column="1"> <widget class="BtDigitWidget" name="lcdnumber_projectedOG"> <property name="text"> <string/> </property> </widget> </item> <item row="2" column="0"> <widget class="QLabel" name="btLabel_brewHouseEff"> <property name="statusTip"> <string>Brewhouse efficiency</string> </property> <property name="text"> <string>Brewhouse efficiency</string> </property> </widget> </item> <item row="2" column="1"> <widget class="BtDigitWidget" name="lcdnumber_brewhouseEff"> <property name="text"> <string/> </property> </widget> </item> <item row="3" column="0"> <widget class="QLabel" name="btLabel_projectedAbv"> <property name="statusTip"> <string>Expected ABV based on recipe OG</string> </property> <property name="text"> <string>Projected ABV</string> </property> </widget> </item> <item row="3" column="1"> <widget class="BtDigitWidget" name="lcdnumber_projABV"> <property name="text"> <string/> </property> </widget> </item> <item row="4" column="0"> <widget class="QLabel" name="btlabel_Abv"> <property name="statusTip"> <string>ABV based on user-reported FG</string> </property> <property name="text"> <string>ABV</string> </property> </widget> </item> <item row="4" column="1"> <widget class="BtDigitWidget" name="lcdnumber_abv"> <property name="text"> <string/> </property> </widget> </item> <item row="5" column="0"> <widget class="QLabel" name="btLabel_yeastProjAtten"> <property name="statusTip"> <string>Yeast attenuation based on yeast specified in recipe</string> </property> <property name="text"> <string>Projected yeast attenuation</string> </property> </widget> </item> <item row="5" column="1"> <widget class="BtDigitWidget" name="lcdnumber_projAtten"> <property name="text"> <string/> </property> </widget> </item> <item row="6" column="0"> <widget class="QLabel" name="btLabel_yeastAtten"> <property name="statusTip"> <string>Yeast attentuation based on user-reported OG and FG</string> </property> <property name="text"> <string>Measured yeast attenuation</string> </property> </widget> </item> <item row="6" column="1"> <widget class="BtDigitWidget" name="lcdnumber_atten"> <property name="text"> <string/> </property> </widget> </item> </layout> </item> </layout> </item> </layout> </item> <item> <widget class="QGroupBox" name="groupBox_4"> <property name="title"> <string>Notes</string> </property> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="BtTextEdit" name="btTextEdit_brewNotes"> <property name="sizePolicy"> <sizepolicy hsizetype="Preferred" vsizetype="Expanding"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="mouseTracking"> <bool>false</bool> </property> </widget> </item> </layout> </widget> </item> </layout> </widget> </widget> </item> </layout> </widget> <layoutdefault spacing="4" margin="4"/> <customwidgets> <customwidget> <class>BtTemperatureEdit</class> <extends>QLineEdit</extends> <header>BtLineEdit.h</header> <slots> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> </slots> </customwidget> <customwidget> <class>BtTemperatureLabel</class> <extends>QLabel</extends> <header>BtLabel.h</header> <slots> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> </slots> </customwidget> <customwidget> <class>BtTextEdit</class> <extends>QPlainTextEdit</extends> <header location="global">BtTextEdit.h</header> </customwidget> <customwidget> <class>BtVolumeLabel</class> <extends>QLabel</extends> <header>BtLabel.h</header> <slots> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> </slots> </customwidget> <customwidget> <class>BtDensityLabel</class> <extends>QLabel</extends> <header>BtLabel.h</header> <slots> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> </slots> </customwidget> <customwidget> <class>BtVolumeEdit</class> <extends>QLineEdit</extends> <header>BtLineEdit.h</header> <slots> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> </slots> </customwidget> <customwidget> <class>BtDensityEdit</class> <extends>QLineEdit</extends> <header>BtLineEdit.h</header> <slots> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> </slots> </customwidget> <customwidget> <class>BtDigitWidget</class> <extends>QLabel</extends> <header>BtDigitWidget.h</header> </customwidget> <customwidget> <class>BtDateLabel</class> <extends>QLabel</extends> <header>BtLabel.h</header> </customwidget> </customwidgets> <resources> <include location="../brewtarget.qrc"/> </resources> <connections> <connection> <sender>btLabel_Sg</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_SG</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>70</x> <y>55</y> </hint> <hint type="destinationlabel"> <x>131</x> <y>55</y> </hint> </hints> </connection> <connection> <sender>btLabel_volIntoBk</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_volIntoBK</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>58</x> <y>81</y> </hint> <hint type="destinationlabel"> <x>131</x> <y>81</y> </hint> </hints> </connection> <connection> <sender>btLabel_strikeTemp</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_strikeTemp</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>48</x> <y>107</y> </hint> <hint type="destinationlabel"> <x>131</x> <y>107</y> </hint> </hints> </connection> <connection> <sender>btLabel_mashFinTemp</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_mashFinTemp</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>51</x> <y>133</y> </hint> <hint type="destinationlabel"> <x>131</x> <y>133</y> </hint> </hints> </connection> <connection> <sender>btLabel_Og</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_OG</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>125</x> <y>81</y> </hint> <hint type="destinationlabel"> <x>187</x> <y>81</y> </hint> </hints> </connection> <connection> <sender>btLabel_postBoilVol</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_postBoilVol</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>92</x> <y>107</y> </hint> <hint type="destinationlabel"> <x>187</x> <y>107</y> </hint> </hints> </connection> <connection> <sender>btLabel_volIntoFerm</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_volIntoFerm</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>76</x> <y>133</y> </hint> <hint type="destinationlabel"> <x>187</x> <y>133</y> </hint> </hints> </connection> <connection> <sender>btLabel_pitchTemp</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_pitchTemp</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>105</x> <y>159</y> </hint> <hint type="destinationlabel"> <x>187</x> <y>159</y> </hint> </hints> </connection> <connection> <sender>btLabel_postFermentFg</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_FG</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>50</x> <y>107</y> </hint> <hint type="destinationlabel"> <x>111</x> <y>107</y> </hint> </hints> </connection> <connection> <sender>btLabel_finalVolume</sender> <signal>labelChanged(Unit::unitDisplay,Unit::unitScale)</signal> <receiver>lineEdit_finalVol</receiver> <slot>lineChanged(Unit::unitDisplay,Unit::unitScale)</slot> <hints> <hint type="sourcelabel"> <x>38</x> <y>133</y> </hint> <hint type="destinationlabel"> <x>111</x> <y>133</y> </hint> </hints> </connection> </connections> <designerdata> <property name="gridDeltaX"> <number>10</number> </property> <property name="gridDeltaY"> <number>10</number> </property> <property name="gridSnapX"> <bool>true</bool> </property> <property name="gridSnapY"> <bool>true</bool> </property> <property name="gridVisible"> <bool>true</bool> </property> </designerdata> </ui>
{ "pile_set_name": "Github" }
--- ms.localizationpriority: medium ms.mktglfcycl: deploy description: Use Internet Explorer to collect data on computers running Windows Internet Explorer 8 through Internet Explorer 11 on Windows 10, Windows 8.1, or Windows 7. author: dansimp ms.prod: ie11 ms.assetid: a145e80f-eb62-4116-82c4-3cc35fd064b6 ms.reviewer: audience: itpro manager: dansimp ms.author: dansimp title: Collect data using Enterprise Site Discovery ms.sitesec: library ms.date: 07/27/2017 --- # Collect data using Enterprise Site Discovery [!INCLUDE [Microsoft 365 workloads end of support for IE11](../includes/microsoft-365-ie-end-of-support.md)] **Applies to:** - Windows 10 - Windows 8.1 - Windows 7 with Service Pack 1 (SP1) Use Internet Explorer to collect data on computers running Windows Internet Explorer 8 through Internet Explorer 11 on Windows 10, Windows 8.1, or Windows 7. This inventory information helps you build a list of websites used by your company so you can make more informed decisions about your IE deployments, including figuring out which sites might be at risk or require overhauls during future upgrades. >**Upgrade Readiness and Windows upgrades**<br> >You can use Upgrade Readiness to help manage your Windows 10 upgrades on devices running Windows 8.1 and Windows 7 (SP1). You can also use Upgrade Readiness to review several site discovery reports. For more information, see [Manage Windows upgrades with Upgrade Readiness](https://docs.microsoft.com/windows/deployment/upgrade/manage-windows-upgrades-with-upgrade-readiness). ## Before you begin Before you start, you need to make sure you have the following: - Latest cumulative security update (for all supported versions of Internet Explorer): 1. Go to the [Microsoft Security Bulletin](https://go.microsoft.com/fwlink/p/?LinkID=718223) page, and change the filter to **Windows Internet Explorer 11**. ![microsoft security bulletin techcenter](images/securitybulletin-filter.png) 2. Click the title of the latest cumulative security update, and then scroll down to the **Affected software** table. ![affected software section](images/affectedsoftware.png) 3. Click the link that represents both your operating system version and Internet Explorer 11, and then follow the instructions in the **How to get this update** section. - [Setup and configuration package](https://go.microsoft.com/fwlink/p/?LinkId=517719), including: - Configuration-related PowerShell scripts - IETelemetry.mof file - Sample System Center 2012 report templates You must use System Center 2012 R2 Configuration Manager or later for these samples to work. Both the PowerShell script and the Managed Object Format (.MOF) file need to be copied to the same location on the client device, before you run the scripts. ## What data is collected? Data is collected on the configuration characteristics of IE and the sites it browses, as shown here. |Data point |IE11 |IE10 |IE9 |IE8 |Description | |------------------------|-----|-----|-----|-----|------------------------------------------------------------------------| |URL | X | X | X | X |URL of the browsed site, including any parameters included in the URL. | |Domain | X | X | X | X |Top-level domain of the browsed site. | |ActiveX GUID | X | X | X | X |GUID of the ActiveX controls loaded by the site. | |Document mode | X | X | X | X |Document mode used by IE for a site, based on page characteristics. | |Document mode reason | X | X | | |The reason why a document mode was set by IE. | |Browser state reason | X | X | | |Additional information about why the browser is in its current state. Also called, browser mode. | |Hang count | X | X | X | X |Number of visits to the URL when the browser hung. | |Crash count | X | X | X | X |Number of visits to the URL when the browser crashed. | |Most recent navigation failure (and count) | X | X | X | X |Description of the most recent navigation failure (like, a 404 bad request or 500 internal server error) and the number of times it happened. | |Number of visits | X | X | X | X |Number of times a site has been visited. | |Zone | X | X | X | X |Zone used by IE to browse sites, based on browser settings. | >**Important**<br>By default, IE doesn’t collect this data; you have to turn this feature on if you want to use it. After you turn on this feature, data is collected on all sites visited by IE, except during InPrivate sessions. Additionally, the data collection process is silent, so there’s no notification to the employee. Therefore, you must get consent from the employee before you start collecting info. You must also make sure that using this feature complies with all applicable local laws and regulatory requirements. ### Understanding the returned reason codes The following tables provide more info about the Document mode reason, Browser state reason, and the Zone codes that are returned as part of your data collection. #### DocMode reason The codes in this table can tell you what document mode was set by IE for a webpage.<br>These codes only apply to Internet Explorer 10 and Internet Explorer 11. |Code |Description | |-----|------------| |3 |Page state is set by the `FEATURE_DOCUMENT_COMPATIBLE_MODE` feature control key.| |4 |Page is using an X-UA-compatible meta tag. | |5 |Page is using an X-UA-compatible HTTP header. | |6 |Page appears on an active **Compatibility View** list. | |7 |Page is using native XML parsing. | |8 |Page is using a special Quirks Mode Emulation (QME) mode that uses the modern layout engine, but the quirks behavior of Internet Explorer 5. | |9 |Page state is set by the browser mode and the page's DOCTYPE.| #### Browser state reason The codes in this table can tell you why the browser is in its current state. Also called “browser mode”.<br>These codes only apply to Internet Explorer 10 and Internet Explorer 11. |Code |Description | |-----|------------| |1 |Site is on the intranet, with the **Display intranet sites in Compatibility View** box checked. | |2 |Site appears on an active **Compatibility View** list, created in Group Policy. | |3 |Site appears on an active **Compatibility View** list, created by the user. | |4 |Page is using an X-UA-compatible tag. | |5 |Page state is set by the **Developer** toolbar. | |6 |Page state is set by the `FEATURE_BROWSER_EMULATION` feature control key. | |7 |Site appears on the Microsoft **Compatibility View (CV)** list. | |8 |Site appears on the **Quirks** list, created in Group Policy. | |11 |Site is using the default browser. | #### Zone The codes in this table can tell you what zone is being used by IE to browse sites, based on browser settings.<br>These codes apply to Internet Explorer 8, Internet Explorer 9, Internet Explorer 10, and Internet Explorer 11. |Code |Description | |-----|------------| |-1 |Internet Explorer is using an invalid zone. | |0 |Internet Explorer is using the Local machine zone. | |1 |Internet Explorer is using the Local intranet zone. | |2 |Internet Explorer is using the Trusted sites zone. | |3 |Internet Explorer is using the Internet zone. | |4 |Internet Explorer is using the Restricted sites zone. | ## Where is the data stored and how do I collect it? The data is stored locally, in an industry-standard WMI class, .MOF file or in an XML file, depending on your configuration. This file remains on the client computer until it’s collected. To collect the files, we recommend: - **WMI file**. Use Microsoft Configuration Manager or any agent that can read the contents of a WMI class on your computer. - **XML file**. Any agent that works with XML can be used. ## WMI Site Discovery suggestions We recommend that you collect your data for at most a month at a time, to capture a user’s typical workflow. We don’t recommend collecting data longer than that because the data is stored in a WMI provider and can fill up your computer’s hard drive. You may also want to collect data only for pilot users or a representative sample of people, instead of turning this feature on for everyone in your company. On average, a website generates about 250bytes of data for each visit, causing only a minor impact to Internet Explorer’s performance. Over the course of a month, collecting data from 20 sites per day from 1,000 users, you’ll get about 150MB of data:<p>250 bytes (per site visit) X 20 sites/day X 30 days = (approximately) 150KB X 1000 users = (approximately) 150MB >**Important**<br>The data collection process is silent, so there’s no notification to the employee. Therefore, you must get consent from the employee before you start collecting info. You must also make sure that using this feature complies with all applicable local laws and regulatory requirements. ## Getting ready to use Enterprise Site Discovery Before you can start to collect your data, you must run the provided PowerShell script (IETelemetrySetUp.ps1) on your client devices to start generating the site discovery data and to set up a place to store this data locally. Then, you must start collecting the site discovery data from the client devices, using one of these three options: - Collect your hardware inventory using the MOF Editor, while connecting to a client device.<p> -OR- - Collect your hardware inventory using the MOF Editor with a .MOF import file.<p> -OR- - Collect your hardware inventory using the SMS\DEF.MOF file (System Center Configuration Manager 2007 only) ### WMI only: Running the PowerShell script to compile the .MOF file and to update security privileges You need to set up your computers for data collection by running the provided PowerShell script (IETelemetrySetUp.ps1) to compile the .mof file and to update security privileges for the new WMI classes. >**Important**<br>You must run this script if you’re using WMI as your data output. It's not necessary if you're using XML as your data output. **To set up Enterprise Site Discovery** - Start PowerShell in elevated mode (using admin privileges) and run IETelemetrySetUp.ps1 by by-passing the PowerShell execution policy, using this command: `powershell -ExecutionPolicy Bypass .\IETelemetrySetUp.ps1`. For more info, see [about Execution Policies](https://go.microsoft.com/fwlink/p/?linkid=517460). ### WMI only: Set up your firewall for WMI data If you choose to use WMI as your data output, you need to make sure that your WMI data can travel through your firewall for the domain. If you’re sure, you can skip this section; otherwise, follow these steps: **To set up your firewall** 1. In **Control Panel**, click **System and Security**, and then click **Windows Firewall**. 2. In the left pane, click **Allow an app or feature through Windows Firewall** and scroll down to check the box for **Windows Management Instrumentation (WMI)**. 3. Restart your computer to start collecting your WMI data. ## Use PowerShell to finish setting up Enterprise Site Discovery You can determine which zones or domains are used for data collection, using PowerShell. If you don’t want to use PowerShell, you can do this using Group Policy. For more info, see [Use Group Policy to finish setting up Enterprise Site Discovery](#use-group-policy-to-finish-setting-up-enterprise-site-discovery). >**Important**<br>The .ps1 file updates turn on Enterprise Site Discovery and WMI collection for all users on a device. - **Domain allow list.** If you have a domain allow list, a comma-separated list of domains that should have this feature turned on, you should use this process. - **Zone allow list.** If you have a zone allow list, a comma-separated list of zones that should have this feature turned on, you should use this process. **To set up data collection using a domain allow list** - Start PowerShell in elevated mode (using admin privileges) and run IETelemetrySetUp.ps1, using this command: `.\IETelemetrySetUp.ps1 [other args] -SiteAllowList sharepoint.com,outlook.com,onedrive.com`. >**Important**<br>Wildcards, like \*.microsoft.com, aren’t supported. **To set up data collection using a zone allow list** - Start PowerShell in elevated mode (using admin privileges) and run IETelemetrySetUp.ps1, using this command: `.\IETelemetrySetUp.ps1 [other args] -ZoneAllowList Computer,Intranet,TrustedSites,Internet,RestrictedSites`. >**Important**<br>Only Computer, Intranet, TrustedSites, Internet, and RestrictedSites are supported. ## Use Group Policy to finish setting up Enterprise Site Discovery You can use Group Policy to finish setting up Enterprise Site Discovery. If you don’t want to use Group Policy, you can do this using PowerShell. For more info, see [Use Powershell to finish setting up Enterprise Site Discovery](#use-powershell-to-finish-setting-up-enterprise-site-discovery). >**Note**<br> All of the Group Policy settings can be used individually or as a group. **To set up Enterprise Site Discovery using Group Policy** - Open your Group Policy editor, and go to these new settings: |Setting name and location |Description |Options | |---------------------------|-------------|---------| |Administrative Templates\Windows Components\Internet Explorer\Turn on Site Discovery WMI output |Writes collected data to a WMI class, which can be aggregated using a client-management solution like Configuration Manager. |<ul><li>**On.** Turns on WMI recording.</li><li>**Off.** Turns off WMI recording.</li></ul> | |Administrative Templates\Windows Components\Internet Explorer\Turn on Site Discovery XML output |Writes collected data to an XML file, which is stored in your specified location. |<ul><li>**XML file path.** Including this turns on XML recording.</li><li>**Blank.** Turns off XML recording.</li></ul> | |Administrative Templates\Windows Components\Internet Explorer\Limit Site Discovery output by Zone |Manages which zone can collect data. |To specify which zones can collect data, you must include a binary number that represents your selected zones, based on this order:<p>0 – Restricted Sites zone<br>0 – Internet zone<br>0 – Trusted Sites zone<br>0 – Local Intranet zone<br>0 – Local Machine zone<p>**Example 1:** Include only the Local Intranet zone<p>Binary representation: *00010*, based on:<p>0 – Restricted Sites zone<br>0 – Internet zone<br>0 – Trusted Sites zone<br>1 – Local Intranet zone<br>0 – Local Machine zone<p>**Example 2:** Include only the Restricted Sites, Trusted Sites, and Local Intranet zones<p>Binary representation: *10110*, based on:<p>1 – Restricted Sites zone<br>0 – Internet zone<br>1 – Trusted Sites zone<br>1 – Local Intranet zone<br>1 – Local Machine zone | |Administrative Templates\Windows Components\Internet Explorer\Limit Site Discovery output by domain |Manages which domains can collect data |To specify which domains can collect data, you must include your selected domains, one domain per line, in the provided box. It should look like:<p>microsoft.sharepoint.com<br>outlook.com<br>onedrive.com<br>timecard.contoso.com<br>LOBApp.contoso.com | ### Combining WMI and XML Group Policy settings You can use both the WMI and XML settings individually or together: **To turn off Enterprise Site Discovery** <table> <tr> <th>Setting name</th> <th>Option</th> </tr> <tr> <td>Turn on Site Discovery WMI output</td> <td>Off</td> </tr> <tr> <td>Turn on Site Discovery XML output</td> <td>Blank</td> </tr> </table> **Turn on WMI recording only** <table> <tr> <th>Setting name</th> <th>Option</th> </tr> <tr> <td>Turn on Site Discovery WMI output</td> <td>On</td> </tr> <tr> <td>Turn on Site Discovery XML output</td> <td>Blank</td> </tr> </table> **To turn on XML recording only** <table> <tr> <th>Setting name</th> <th>Option</th> </tr> <tr> <td>Turn on Site Discovery WMI output</td> <td>Off</td> </tr> <tr> <td>Turn on Site Discovery XML output</td> <td>XML file path</td> </tr> </table> <strong>To turn on both WMI and XML recording</strong> <table> <tr> <th>Setting name</th> <th>Option</th> </tr> <tr> <td>Turn on Site Discovery WMI output</td> <td>On</td> </tr> <tr> <td>Turn on Site Discovery XML output</td> <td>XML file path</td> </tr> </table> ## Use Configuration Manager to collect your data After you’ve collected your data, you’ll need to get the local files off of your employee’s computers. To do this, use the hardware inventory process in Configuration Manager, using one of these options: - Collect your hardware inventory using the MOF Editor, while connecting to a client device.<p> -OR- - Collect your hardware inventory using the MOF Editor with a .MOF import file.<p> -OR- - Collect your hardware inventory using the SMS\DEF.MOF file (System Center Configuration Manager 2007 only) ### Collect your hardware inventory using the MOF Editor while connected to a client device You can collect your hardware inventory using the MOF Editor, while you’re connected to your client devices. **To collect your inventory** 1. From the Configuration Manager, click **Administration**, click **Client Settings**, double-click **Default Client Settings**, click **Hardware Inventory**, and then click **Set Classes**. ![Configuration Manager, showing the hardware inventory settings for client computers](images/configmgrhardwareinventory.png) 2. Click **Add**, click **Connect**, and connect to a computer that has completed the setup process and has already existing classes. 3. Change the **WMI Namespace** to `root\cimv2\IETelemetry`, and click **Connect**. ![Configuration Manager, with the Connect to Windows Management Instrumentation (WMI) box](images/ie11-inventory-addclassconnectscreen.png) 4. Select the check boxes next to the following classes, and then click **OK**: - IESystemInfo - IEURLInfo - IECountInfo 5. Click **OK** to close the default windows.<br> Your environment is now ready to collect your hardware inventory and review the sample reports. ### Collect your hardware inventory using the MOF Editor with a .MOF import file You can collect your hardware inventory using the MOF Editor and a .MOF import file. **To collect your inventory** 1. From the Configuration Manager, click **Administration**, click **Client Settings**, double-click **Default Client Settings**, click **Hardware Inventory**, and then click **Set Classes**. 2. Click **Import**, choose the MOF file from the downloaded package we provided, and click **Open**. 3. Pick the inventory items to install, and then click **Import**. 4. Click **OK** to close the default windows.<br> Your environment is now ready to collect your hardware inventory and review the sample reports. ### Collect your hardware inventory using the SMS\DEF.MOF file (System Center Configuration Manager 2007 only) You can collect your hardware inventory using the using the Systems Management Server (SMS\DEF.MOF) file. Editing this file lets you collect your data for System Center Configuration Manager 2007. If you aren’t using this version of Configuration Manager, you won’t want to use this option. **To collect your inventory** 1. Using a text editor like Notepad, open the SMS\DEF.MOF file, located in your `<configmanager_install_location>\inboxes\clifiles.src\hinv` directory. 2. Add this text to the end of the file: ``` [SMS_Report (TRUE), SMS_Group_Name ("IESystemInfo"), SMS_Class_ID ("MICROSOFT|IESystemInfo|1.0"), Namespace ("root\\\\cimv2\\\\IETelemetry") ] Class IESystemInfo: SMS_Class_Template { [SMS_Report (TRUE), Key ] String SystemKey; [SMS_Report (TRUE) ] String IEVer; }; [SMS_Report (TRUE), SMS_Group_Name ("IEURLInfo"), SMS_Class_ID ("MICROSOFT|IEURLInfo|1.0"), Namespace ("root\\\\cimv2\\\\IETelemetry") ] Class IEURLInfo: SMS_Class_Template { [SMS_Report (TRUE), Key ] String URL; [SMS_Report (TRUE) ] String Domain; [SMS_Report (TRUE) ] UInt32 DocMode; [SMS_Report (TRUE) ] UInt32 DocModeReason; [SMS_Report (TRUE) ] UInt32 Zone; [SMS_Report (TRUE) ] UInt32 BrowserStateReason; [SMS_Report (TRUE) ] String ActiveXGUID[]; [SMS_Report (TRUE) ] UInt32 CrashCount; [SMS_Report (TRUE) ] UInt32 HangCount; [SMS_Report (TRUE) ] UInt32 NavigationFailureCount; [SMS_Report (TRUE) ] UInt32 NumberOfVisits; [SMS_Report (TRUE) ] UInt32 MostRecentNavigationFailure; }; [SMS_Report (TRUE), SMS_Group_Name ("IECountInfo"), SMS_Class_ID ("MICROSOFT|IECountInfo|1.0"), Namespace ("root\\\\cimv2\\\\IETelemetry") ] Class IECountInfo: SMS_Class_Template { [SMS_Report (TRUE), Key ] String CountKey; [SMS_Report (TRUE) ] UInt32 CrashCount; [SMS_Report (TRUE) ] UInt32 HangCount; [SMS_Report (TRUE) ] UInt32 NavigationFailureCount; }; ``` 3. Save the file and close it to the same location. Your environment is now ready to collect your hardware inventory and review the sample reports. ## View the sample reports with your collected data The sample reports, **SCCM Report Sample – ActiveX.rdl** and **SCCM Report Sample – Site Discovery.rdl**, work with System Center 2012, so you can review your collected data. ### SCCM Report Sample – ActiveX.rdl Gives you a list of all of the ActiveX-related sites visited by the client computer. ![ActiveX.rdl report, lists all ActiveX-related sites visited by the client computer](images/configmgractivexreport.png) ### SCCM Report Sample – Site Discovery.rdl Gives you a list of all of the sites visited by the client computer. ![Site Discovery.rdl report, lists all websites visited by the client computer](images/ie-site-discovery-sample-report.png) ## View the collected XML data After the XML files are created, you can use your own solutions to extract and parse the data. The data will look like: ``` xml <IETelemetry> <IECountInfo> <CrashCount>[dword]</CrashCount> <HangCount>[dword]</HangCount> <NavigationFailureCount>[dword]</NavigationFailureCount> </IECountInfo> <IEURLInfo> <URL>[string]</URL> <ActiveXGUID> <GUID>[guid]</GUID> </ActiveXGUID> <DocModeReason>[dword]</DocModeReason> <DocMode>[dword]</DocMode> <NumberOfVisits>[dword]</NumberOfVisits> <BrowserStateReason>[dword]</BrowserStateReason> <Zone>[dword]</Zone> <CrashCount>[dword]</CrashCount> <HangCount>[dword]</HangCount> <NavigationFailureCount>[dword]</NavigationFailureCount> <Domain>[string]</Domain> <MostRecentNavigationFailure>[dword]</MostRecentNavigationFailure> </IEURLInfo> <IEURLInfo>…</IEURLInfo> <IEURLInfo>…</IEURLInfo> </IETelemetry> ``` You can import this XML data into the correct version of the Enterprise Mode Site List Manager, automatically adding the included sites to your Enterprise Mode site list. **To add your XML data to your Enterprise Mode site list** 1. Open the Enterprise Mode Site List Manager, click **File**, and then click **Bulk add from file**. ![Enterprise Mode Site List Manager with Bulk add from file option](images/bulkadd-emiesitelistmgr.png) 2. Go to your XML file to add the included sites to the tool, and then click **Open**.<br>Each site is validated and if successful, added to the global site list when you click **OK** to close the menu. If a site doesn’t pass validation, you can try to fix the issues or pick the site and click **Add to list** to ignore the validation problem. For more information about fixing validation problems, see [Fix validation problems using the Enterprise Mode Site List Manager](fix-validation-problems-using-the-enterprise-mode-site-list-manager.md). 3. Click **OK** to close the **Bulk add sites to the list** menu. ## Turn off data collection on your client devices After you’ve collected your data, you’ll need to turn Enterprise Site Discovery off. **To stop collecting data, using PowerShell** - On your client computer, start Windows PowerShell in elevated mode (using admin privileges) and run `IETelemetrySetUp.ps1`, using this command: `powershell -ExecutionPolicy Bypass .\IETelemetrySetUp.ps1 –IEFeatureOff`. >**Note**<br>Turning off data collection only disables the Enterprise Site Discovery feature – all data already written to WMI stays on your employee’s computer. **To stop collecting data, using Group Policy** 1. Open your Group Policy editor, go to `Administrative Templates\Windows Components\Internet Explorer\Turn on Site Discovery WMI output`, and click **Off**. 2. Go to `Administrative Templates\Windows Components\Internet Explorer\Turn on Site Discovery XML output`, and clear the file path location. ### Delete already stored data from client computers You can completely remove the data stored on your employee’s computers. **To delete all existing data** - On the client computer, start PowerShell in elevated mode (using admin privileges) and run these four commands: - `Remove-WmiObject -Namespace root/cimv2/IETelemetry IEURLInfo` - `Remove-WmiObject -Namespace root/cimv2/IETelemetry IESystemInfo` - `Remove-WmiObject -Namespace root/cimv2/IETelemetry IECountInfo` - `Remove-Item -Path 'HKCU:\Software\Microsoft\Internet Explorer\WMITelemetry'` ## Related topics * [Enterprise Mode Site List Manager (schema v.2) download](https://go.microsoft.com/fwlink/?LinkId=746562) * [Enterprise Mode for Internet Explorer 11 (IE11)](enterprise-mode-overview-for-ie11.md)
{ "pile_set_name": "Github" }
# Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/davidg/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #}
{ "pile_set_name": "Github" }
name: publish on: push: tags: - '*' jobs: docker: runs-on: ubuntu-latest env: REPOSITORY: unblockneteasemusic DOCKER_USERNAME: nondanee DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} steps: - name: Prepare id: prepare run: | ARCH=(amd64 arm/v6 arm/v7 arm64 386 ppc64le s390x) PLATFORM=$(printf ",linux/%s" "${ARCH[@]}") echo ::set-output name=build_platform::${PLATFORM:1} echo ::set-output name=image_name::${DOCKER_USERNAME}/${REPOSITORY} - name: Checkout uses: actions/checkout@v2 - name: Setup Buildx uses: crazy-max/ghaction-docker-buildx@v1 - name: Login run: | echo "${DOCKER_PASSWORD}" | docker login --username ${DOCKER_USERNAME} --password-stdin - name: Build run: | docker buildx build \ --tag ${{ steps.prepare.outputs.image_name }} \ --platform ${{ steps.prepare.outputs.build_platform }} \ --output "type=image,push=true" \ --file Dockerfile . - name: Check Manifest run: | docker buildx imagetools inspect ${{ steps.prepare.outputs.image_name }} npm: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 - name: Setup Node.js uses: actions/setup-node@v1 with: registry-url: https://registry.npmjs.org/ - name: Publish run: npm publish env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETCOREAPP namespace Microsoft.VisualStudio.TestPlatform.PlatformAbstractions { using System.Diagnostics; public static class ProcessStartInfoExtensions { /// <summary> /// Add environment variable that apply to this process and child processes. /// </summary> /// <param name="startInfo">The process start info</param> /// <param name="name">Environment Variable name. </param> /// <param name="value">Environment Variable value.</param> public static void AddEnvironmentVariable(this ProcessStartInfo startInfo, string name, string value) { startInfo.Environment[name] = value; } } } #endif
{ "pile_set_name": "Github" }
# LP:1434842 -- disable OSS drivers by default to allow pulseaudio to emulate blacklist snd-mixer-oss blacklist snd-pcm-oss
{ "pile_set_name": "Github" }
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // sv_user.c -- server code for moving users #include "cmd.h" #include "console.h" #include "pmove.h" #include "qwsvdef.h" #include "server.h" #include "sys.h" #include "world.h" static cvar_t cl_rollspeed = { "cl_rollspeed", "200" }; static cvar_t cl_rollangle = { "cl_rollangle", "2.0" }; static cvar_t sv_spectalk = { "sv_spectalk", "1" }; static cvar_t sv_mapcheck = { "sv_mapcheck", "1" }; /* ============================================================ USER STRINGCMD EXECUTION ============================================================ */ /* ================ SV_New_f Sends the first message from the server to a connected client. This will be sent on the initial connection and upon each server load. ================ */ static void SV_New_f(client_t *client) { const char *gamedir; int playernum; if (client->state == cs_spawned) return; client->state = cs_connected; client->connection_started = realtime; // send the info about the new client to all connected clients // SV_FullClientUpdate (client, &sv.reliable_datagram); // client->sendinfo = true; gamedir = Info_ValueForKey(svs.info, "*gamedir"); if (!gamedir[0]) gamedir = "qw"; //NOTE: This doesn't go through ClientReliableWrite since it's before the user //spawns. These functions are written to not overflow if (client->num_backbuf) { Con_Printf("WARNING %s: [SV_New] Back buffered (%d0, clearing", client->name, client->netchan.message.cursize); client->num_backbuf = 0; SZ_Clear(&client->netchan.message); } // send the serverdata MSG_WriteByte(&client->netchan.message, svc_serverdata); MSG_WriteLong(&client->netchan.message, PROTOCOL_VERSION); MSG_WriteLong(&client->netchan.message, svs.spawncount); MSG_WriteString(&client->netchan.message, gamedir); playernum = NUM_FOR_EDICT(client->edict) - 1; if (client->spectator) playernum |= 128; MSG_WriteByte(&client->netchan.message, playernum); // send full levelname MSG_WriteString(&client->netchan.message, PR_GetString(sv.edicts->v.message)); // send the movevars MSG_WriteFloat(&client->netchan.message, movevars.gravity); MSG_WriteFloat(&client->netchan.message, movevars.stopspeed); MSG_WriteFloat(&client->netchan.message, movevars.maxspeed); MSG_WriteFloat(&client->netchan.message, movevars.spectatormaxspeed); MSG_WriteFloat(&client->netchan.message, movevars.accelerate); MSG_WriteFloat(&client->netchan.message, movevars.airaccelerate); MSG_WriteFloat(&client->netchan.message, movevars.wateraccelerate); MSG_WriteFloat(&client->netchan.message, movevars.friction); MSG_WriteFloat(&client->netchan.message, movevars.waterfriction); MSG_WriteFloat(&client->netchan.message, movevars.entgravity); // send music MSG_WriteByte(&client->netchan.message, svc_cdtrack); MSG_WriteByte(&client->netchan.message, sv.edicts->v.sounds); // send server info string MSG_WriteByte(&client->netchan.message, svc_stufftext); MSG_WriteStringf(&client->netchan.message, "fullserverinfo \"%s\"\n", svs.info); } /* ================== SV_Soundlist_f ================== */ static void SV_Soundlist_f(client_t *client) { const char **soundlist; int nextsound; if (client->state != cs_connected) { Con_Printf("soundlist not valid -- already spawned\n"); return; } // handle the case of a level changing while a client was connecting if (atoi(Cmd_Argv(1)) != svs.spawncount) { Con_Printf("SV_Soundlist_f from different level\n"); SV_New_f(client); return; } nextsound = atoi(Cmd_Argv(2)); //NOTE: This doesn't go through ClientReliableWrite since it's before the user //spawns. These functions are written to not overflow if (client->num_backbuf) { Con_Printf("WARNING %s: [SV_Soundlist] Back buffered (%d0, clearing", client->name, client->netchan.message.cursize); client->num_backbuf = 0; SZ_Clear(&client->netchan.message); } MSG_WriteByte(&client->netchan.message, svc_soundlist); MSG_WriteByte(&client->netchan.message, nextsound); soundlist = sv.sound_precache + 1 + nextsound; while (*soundlist) { if (client->netchan.message.cursize >= (MAX_MSGLEN / 2)) break; MSG_WriteString(&client->netchan.message, *soundlist); soundlist++; nextsound++; } MSG_WriteByte(&client->netchan.message, 0); /* next msg */ if (*soundlist) MSG_WriteByte(&client->netchan.message, nextsound); else MSG_WriteByte(&client->netchan.message, 0); } /* ================== SV_Modellist_f ================== */ static void SV_Modellist_f(client_t *client) { const char **modellist; int nextmodel; if (client->state != cs_connected) { Con_Printf("modellist not valid -- already spawned\n"); return; } // handle the case of a level changing while a client was connecting if (atoi(Cmd_Argv(1)) != svs.spawncount) { Con_Printf("SV_Modellist_f from different level\n"); SV_New_f(client); return; } nextmodel = atoi(Cmd_Argv(2)); //NOTE: This doesn't go through ClientReliableWrite since it's before the user //spawns. These functions are written to not overflow if (client->num_backbuf) { Con_Printf("WARNING %s: [SV_Modellist] Back buffered (%d0, clearing", client->name, client->netchan.message.cursize); client->num_backbuf = 0; SZ_Clear(&client->netchan.message); } MSG_WriteByte(&client->netchan.message, svc_modellist); MSG_WriteByte(&client->netchan.message, nextmodel); modellist = sv.model_precache + 1 + nextmodel; while (*modellist) { if (client->netchan.message.cursize >= (MAX_MSGLEN / 2)) break; MSG_WriteString(&client->netchan.message, *modellist); modellist++; nextmodel++; } MSG_WriteByte(&client->netchan.message, 0); /* next msg */ if (*modellist) MSG_WriteByte(&client->netchan.message, nextmodel); else MSG_WriteByte(&client->netchan.message, 0); } /* ================== SV_PreSpawn_f ================== */ static void SV_PreSpawn_f(client_t *client) { unsigned buf; unsigned check; if (client->state != cs_connected) { Con_Printf("prespawn not valid -- already spawned\n"); return; } // handle the case of a level changing while a client was connecting if (atoi(Cmd_Argv(1)) != svs.spawncount) { Con_Printf("SV_PreSpawn_f from different level\n"); SV_New_f(client); return; } buf = atoi(Cmd_Argv(2)); if (buf >= sv.num_signon_buffers) buf = 0; if (!buf) { // should be three numbers following containing checksums check = atoi(Cmd_Argv(3)); // Con_DPrintf("Client check = %d\n", check); if (sv_mapcheck.value && check != sv.worldmodel->checksum && check != sv.worldmodel->checksum2) { SV_ClientPrintf(client, PRINT_HIGH, "Map model file does not match (%s), %i != %i/%i.\n" "You may need a new version of the map, or the proper install files.\n", sv.modelname, check, sv.worldmodel->checksum, sv.worldmodel->checksum2); SV_DropClient(client); return; } client->checksum = check; } //NOTE: This doesn't go through ClientReliableWrite since it's before the user //spawns. These functions are written to not overflow if (client->num_backbuf) { Con_Printf("WARNING %s: [SV_PreSpawn] Back buffered (%d0, clearing", client->name, client->netchan.message.cursize); client->num_backbuf = 0; SZ_Clear(&client->netchan.message); } SZ_Write(&client->netchan.message, sv.signon_buffers[buf], sv.signon_buffer_size[buf]); buf++; if (buf == sv.num_signon_buffers) { // all done prespawning MSG_WriteByte(&client->netchan.message, svc_stufftext); MSG_WriteStringf(&client->netchan.message, "cmd spawn %i 0\n", svs.spawncount); } else { // need to prespawn more MSG_WriteByte(&client->netchan.message, svc_stufftext); MSG_WriteStringf(&client->netchan.message, "cmd prespawn %i %i\n", svs.spawncount, buf); } } /* ================== SV_Spawn_f ================== */ static void SV_Spawn_f(client_t *client) { int i, length; client_t *recipient; edict_t *player; eval_t *val; int n; if (client->state != cs_connected) { Con_Printf("Spawn not valid -- already spawned\n"); return; } // handle the case of a level changing while a client was connecting if (atoi(Cmd_Argv(1)) != svs.spawncount) { Con_Printf("SV_Spawn_f from different level\n"); SV_New_f(client); return; } n = atoi(Cmd_Argv(2)); // make sure n is valid if (n < 0 || n > MAX_CLIENTS) { Con_Printf("SV_Spawn_f invalid client start\n"); SV_New_f(client); return; } // send all current names, colors, and frag counts // FIXME: is this a good thing? SZ_Clear(&client->netchan.message); // send current status of all other players // normally this could overflow, but no need to check due to backbuf recipient = svs.clients + n; for (i = n; i < MAX_CLIENTS; i++, recipient++) SV_FullClientUpdateToClient(recipient, client); // send all current light styles for (i = 0; i < MAX_LIGHTSTYLES; i++) { length = 3 + (sv.lightstyles[i] ? strlen(sv.lightstyles[i]) : 1); ClientReliableWrite_Begin(client, svc_lightstyle, length); ClientReliableWrite_Byte(client, (char)i); ClientReliableWrite_String(client, sv.lightstyles[i]); } // set up the edict player = client->edict; memset(&player->v, 0, progs->entityfields * 4); player->v.colormap = NUM_FOR_EDICT(player); player->v.team = 0; // FIXME player->v.netname = PR_SetString(client->name); client->entgravity = 1.0; val = GetEdictFieldValue(player, "gravity"); if (val) val->_float = 1.0; client->maxspeed = sv_maxspeed.value; val = GetEdictFieldValue(player, "maxspeed"); if (val) val->_float = sv_maxspeed.value; // // force stats to be updated // memset(client->stats, 0, sizeof(client->stats)); ClientReliableWrite_Begin(client, svc_updatestatlong, 6); ClientReliableWrite_Byte(client, STAT_TOTALSECRETS); ClientReliableWrite_Long(client, pr_global_struct->total_secrets); ClientReliableWrite_Begin(client, svc_updatestatlong, 6); ClientReliableWrite_Byte(client, STAT_TOTALMONSTERS); ClientReliableWrite_Long(client, pr_global_struct->total_monsters); ClientReliableWrite_Begin(client, svc_updatestatlong, 6); ClientReliableWrite_Byte(client, STAT_SECRETS); ClientReliableWrite_Long(client, pr_global_struct->found_secrets); ClientReliableWrite_Begin(client, svc_updatestatlong, 6); ClientReliableWrite_Byte(client, STAT_MONSTERS); ClientReliableWrite_Long(client, pr_global_struct->killed_monsters); // get the client to check and download skins // when that is completed, a begin command will be issued ClientReliableWrite_Begin(client, svc_stufftext, 8); ClientReliableWrite_String(client, "skins\n"); } /* ================== SV_SpawnSpectator ================== */ static void SV_SpawnSpectator(edict_t *player) { int i; edict_t *spawn; VectorCopy(vec3_origin, player->v.origin); VectorCopy(vec3_origin, player->v.view_ofs); player->v.view_ofs[2] = 22; /* search for an info_playerstart to spawn the spectator at */ for (i = MAX_CLIENTS - 1; i < sv.num_edicts; i++) { spawn = EDICT_NUM(i); if (!strcmp(PR_GetString(spawn->v.classname), "info_player_start")) { VectorCopy(spawn->v.origin, player->v.origin); return; } } } /* ================== SV_Begin_f ================== */ static void SV_Begin_f(client_t *client) { edict_t *player = client->edict; unsigned pmodel = 0, emodel = 0; int i; if (client->state == cs_spawned) return; // don't begin again client->state = cs_spawned; // handle the case of a level changing while a client was connecting if (atoi(Cmd_Argv(1)) != svs.spawncount) { Con_Printf("SV_Begin_f from different level\n"); SV_New_f(client); return; } if (client->spectator) { SV_SpawnSpectator(player); if (SpectatorConnect) { // copy spawn parms out of the client_t for (i = 0; i < NUM_SPAWN_PARMS; i++) (&pr_global_struct->parm1)[i] = client->spawn_parms[i]; // call the spawn function pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(player); PR_ExecuteProgram(SpectatorConnect); } } else { // copy spawn parms out of the client_t for (i = 0; i < NUM_SPAWN_PARMS; i++) (&pr_global_struct->parm1)[i] = client->spawn_parms[i]; // call the spawn function pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(player); PR_ExecuteProgram(pr_global_struct->ClientConnect); // actually spawn the player pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(player); PR_ExecuteProgram(pr_global_struct->PutClientInServer); } // clear the net statistics, because connecting gives a bogus picture client->netchan.frame_latency = 0; client->netchan.frame_rate = 0; client->netchan.drop_count = 0; client->netchan.good_count = 0; //check he's not cheating pmodel = atoi(Info_ValueForKey(client->userinfo, "pmodel")); emodel = atoi(Info_ValueForKey(client->userinfo, "emodel")); if (pmodel != sv.model_player_checksum || emodel != sv.eyes_player_checksum) SV_BroadcastPrintf(PRINT_HIGH, "%s WARNING: non standard player/eyes " "model detected\n", client->name); // if we are paused, tell the client if (sv.paused) { ClientReliableWrite_Begin(client, svc_setpause, 2); ClientReliableWrite_Byte(client, sv.paused); SV_ClientPrintf(client, PRINT_HIGH, "Server is paused.\n"); } #if 0 // // send a fixangle over the reliable channel to make sure it gets there // Never send a roll angle, because savegames can catch the server // in a state where it is expecting the client to correct the angle // and it won't happen if the game was just loaded, so you wind up // with a permanent head tilt ent = EDICT_NUM(1 + (client - svs.clients)); MSG_WriteByte(&client->netchan.message, svc_setangle); for (i = 0; i < 2; i++) MSG_WriteAngle(&client->netchan.message, ent->v.angles[i]); MSG_WriteAngle(&client->netchan.message, 0); #endif } //============================================================================= /* ================== SV_NextDownload_f ================== */ static void SV_NextDownload_f(client_t *client) { byte buffer[1024]; int r; int percent; int size; if (!client->download) return; r = client->downloadsize - client->downloadcount; if (r > 768) r = 768; r = fread(buffer, 1, r, client->download); ClientReliableWrite_Begin(client, svc_download, 6 + r); ClientReliableWrite_Short(client, r); client->downloadcount += r; size = client->downloadsize; if (!size) size = 1; percent = client->downloadcount * 100 / size; ClientReliableWrite_Byte(client, percent); ClientReliableWrite_SZ(client, buffer, r); if (client->downloadcount != client->downloadsize) return; fclose(client->download); client->download = NULL; } static void OutofBandPrintf(netadr_t where, const char *fmt, ...) { va_list argptr; char send[MAX_PRINTMSG]; send[0] = 0xff; send[1] = 0xff; send[2] = 0xff; send[3] = 0xff; send[4] = A2C_PRINT; va_start(argptr, fmt); vsnprintf(send + 5, sizeof(send) - 5, fmt, argptr); va_end(argptr); NET_SendPacket(strlen(send) + 1, send, where); } /* ================== SV_NextUpload ================== */ static void SV_NextUpload(client_t *client) { int percent; int size; if (!*client->uploadfn) { SV_ClientPrintf(client, PRINT_HIGH, "Upload denied\n"); ClientReliableWrite_Begin(client, svc_stufftext, 8); ClientReliableWrite_String(client, "stopul"); /* suck out rest of packet */ size = MSG_ReadShort(); MSG_ReadByte(); msg_readcount += size; return; } size = MSG_ReadShort(); percent = MSG_ReadByte(); if (!client->upload) { client->upload = fopen(client->uploadfn, "wb"); if (!client->upload) { Sys_Printf("Can't create %s\n", client->uploadfn); ClientReliableWrite_Begin(client, svc_stufftext, 8); ClientReliableWrite_String(client, "stopul"); *client->uploadfn = 0; return; } Sys_Printf("Receiving %s from %d...\n", client->uploadfn, client->userid); if (client->remote_snap) OutofBandPrintf(client->snap_from, "Server receiving %s from %d...\n", client->uploadfn, client->userid); } fwrite(net_message.data + msg_readcount, 1, size, client->upload); msg_readcount += size; Con_DPrintf("UPLOAD: %d received\n", size); if (percent != 100) { ClientReliableWrite_Begin(client, svc_stufftext, 8); ClientReliableWrite_String(client, "nextul\n"); } else { fclose(client->upload); client->upload = NULL; Sys_Printf("%s upload completed.\n", client->uploadfn); if (client->remote_snap) { char *path = strchr(client->uploadfn, '/'); path = path ? path + 1 : client->uploadfn; OutofBandPrintf(client->snap_from, "%s upload completed.\n" "To download, enter:\n" "download %s\n", client->uploadfn, path); } } } /* ================== SV_BeginDownload_f ================== */ static void SV_BeginDownload_f(client_t *client) { char name[MAX_OSPATH], *p; /* Lowercase name (needed for casesen file systems) */ snprintf(name, sizeof(name), "%s", Cmd_Argv(1)); for (p = name; *p; p++) *p = tolower(*p); // first off, no .. or global allow check if (strstr(name, "..") || !allow_download.value // leading dot is no good || *name == '.' // leading slash bad as well, must be in subdir || *name == '/' // next up, skin check || (strncmp(name, "skins/", 6) == 0 && !allow_download_skins.value) // now models || (strncmp(name, "progs/", 6) == 0 && !allow_download_models.value) // now sounds || (strncmp(name, "sound/", 6) == 0 && !allow_download_sounds.value) // now maps (note special case for maps, must not be in pak) || (strncmp(name, "maps/", 6) == 0 && !allow_download_maps.value) // MUST be in a subdirectory || !strstr(name, "/")) { // don't allow anything with .. path ClientReliableWrite_Begin(client, svc_download, 4); ClientReliableWrite_Short(client, -1); ClientReliableWrite_Byte(client, 0); return; } if (client->download) { fclose(client->download); client->download = NULL; } client->downloadsize = COM_FOpenFile(name, &client->download); client->downloadcount = 0; if (!client->download // special check for maps, if it came from a pak file, don't allow // download ZOID || (strncmp(name, "maps/", 5) == 0 && file_from_pak)) { if (client->download) { fclose(client->download); client->download = NULL; } Sys_Printf("Couldn't upload %s to %s\n", name, client->name); ClientReliableWrite_Begin(client, svc_download, 4); ClientReliableWrite_Short(client, -1); ClientReliableWrite_Byte(client, 0); return; } SV_NextDownload_f(client); Sys_Printf("Uploading %s to %s\n", name, client->name); } //============================================================================= /* ================== SV_Say ================== */ static void SV_Say(client_t *client, qboolean team) { client_t *recipient; int i, tmp; size_t len, space; const char *p; char text[2048]; char t1[32], *t2; if (Cmd_Argc() < 2) return; if (team) { strncpy(t1, Info_ValueForKey(client->userinfo, "team"), 31); t1[31] = 0; } if (client->spectator && (!sv_spectalk.value || team)) sprintf(text, "[SPEC] %s: ", client->name); else if (team) sprintf(text, "(%s): ", client->name); else { sprintf(text, "%s: ", client->name); } if (fp_messages) { if (!sv.paused && realtime < client->lockedtill) { SV_ClientPrintf(client, PRINT_CHAT, "You can't talk for %d more seconds\n", (int)(client->lockedtill - realtime)); return; } tmp = client->whensaidhead - fp_messages + 1; if (tmp < 0) tmp = 10 + tmp; if (!sv.paused && client->whensaid[tmp] && (realtime - client->whensaid[tmp] < fp_persecond)) { client->lockedtill = realtime + fp_secondsdead; if (fp_msg[0]) SV_ClientPrintf(client, PRINT_CHAT, "FloodProt: %s\n", fp_msg); else SV_ClientPrintf(client, PRINT_CHAT, "FloodProt: You can't talk for %d seconds.\n", fp_secondsdead); return; } client->whensaidhead++; if (client->whensaidhead > 9) client->whensaidhead = 0; client->whensaid[client->whensaidhead] = realtime; } len = strlen(text); space = sizeof(text) - len - 2; // -2 for \n and null terminator p = Cmd_Args(); if (*p == '"') { /* remove quotes */ strncat(text, p + 1, qmin(strlen(p) - 2, space)); text[len + qmin(strlen(p) - 2, space)] = 0; } else { strncat(text, p, space); text[len + qmin(strlen(p), space)] = 0; } strcat(text, "\n"); Sys_Printf("%s", text); recipient = svs.clients; for (i = 0; i < MAX_CLIENTS; i++, recipient++) { if (recipient->state != cs_spawned) continue; if (client->spectator && !sv_spectalk.value) if (!recipient->spectator) continue; if (team) { // the spectator team if (client->spectator) { if (!recipient->spectator) continue; } else { t2 = Info_ValueForKey(client->userinfo, "team"); if (strcmp(t1, t2) || client->spectator) continue; // on different teams } } SV_ClientPrintf(recipient, PRINT_CHAT, "%s", text); } } /* ================== SV_Say_f ================== */ static void SV_Say_f(client_t *client) { SV_Say(client, false); } /* ================== SV_Say_Team_f ================== */ static void SV_Say_Team_f(client_t *client) { SV_Say(client, true); } //============================================================================ /* ================= SV_Pings_f The client is showing the scoreboard, so send new ping times for all clients ================= */ static void SV_Pings_f(client_t *client) { client_t *pingclient; int i; pingclient = svs.clients; for (i = 0; i < MAX_CLIENTS; i++, pingclient++) { if (pingclient->state != cs_spawned) continue; ClientReliableWrite_Begin(client, svc_updateping, 4); ClientReliableWrite_Byte(client, i); ClientReliableWrite_Short(client, SV_CalcPing(pingclient)); ClientReliableWrite_Begin(client, svc_updatepl, 4); ClientReliableWrite_Byte(client, i); ClientReliableWrite_Byte(client, pingclient->lossage); } } /* ================== SV_Kill_f ================== */ static void SV_Kill_f(client_t *client) { edict_t *player = client->edict; if (player->v.health <= 0) { SV_ClientPrintf(client, PRINT_HIGH, "Can't suicide -- already dead!\n"); return; } pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(player); PR_ExecuteProgram(pr_global_struct->ClientKill); } /* ================== SV_TogglePause ================== */ void SV_TogglePause(const char *msg) { int i; client_t *cl; sv.paused ^= 1; if (msg) SV_BroadcastPrintf(PRINT_HIGH, "%s", msg); // send notification to all clients for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) { if (!cl->state) continue; ClientReliableWrite_Begin(cl, svc_setpause, 2); ClientReliableWrite_Byte(cl, sv.paused); } } /* ================== SV_Pause_f ================== */ static void SV_Pause_f(client_t *client) { char st[sizeof(client->name) + 32]; if (!pausable.value) { SV_ClientPrintf(client, PRINT_HIGH, "Pause not allowed.\n"); return; } if (client->spectator) { SV_ClientPrintf(client, PRINT_HIGH, "Spectators can not pause.\n"); return; } if (sv.paused) sprintf(st, "%s paused the game\n", client->name); else sprintf(st, "%s unpaused the game\n", client->name); SV_TogglePause(st); } /* ================= SV_Drop_f The client is going to disconnect, so remove the connection immediately ================= */ static void SV_Drop_f(client_t *client) { SV_EndRedirect(); if (!client->spectator) SV_BroadcastPrintf(PRINT_HIGH, "%s dropped\n", client->name); SV_DropClient(client); } /* ================= SV_PTrack_f Change the bandwidth estimate for a client ================= */ static void SV_PTrack_f(client_t *client) { int i; edict_t *ent, *tent; if (!client->spectator) return; if (Cmd_Argc() != 2) { // turn off tracking client->spec_track = 0; ent = EDICT_NUM(client - svs.clients + 1); tent = EDICT_NUM(0); ent->v.goalentity = EDICT_TO_PROG(tent); return; } i = atoi(Cmd_Argv(1)); if (i < 0 || i >= MAX_CLIENTS || svs.clients[i].state != cs_spawned || svs.clients[i].spectator) { SV_ClientPrintf(client, PRINT_HIGH, "Invalid client to track\n"); client->spec_track = 0; ent = EDICT_NUM(client - svs.clients + 1); tent = EDICT_NUM(0); ent->v.goalentity = EDICT_TO_PROG(tent); return; } client->spec_track = i + 1; // now tracking ent = EDICT_NUM(client - svs.clients + 1); tent = EDICT_NUM(i + 1); ent->v.goalentity = EDICT_TO_PROG(tent); } /* ================= SV_Rate_f Change the bandwidth estimate for a client ================= */ static void SV_Rate_f(client_t *client) { int rate; if (Cmd_Argc() != 2) { SV_ClientPrintf(client, PRINT_HIGH, "Current rate is %i\n", (int)(1.0 / client->netchan.rate + 0.5)); return; } rate = atoi(Cmd_Argv(1)); if (rate < 500) rate = 500; if (rate > 10000) rate = 10000; SV_ClientPrintf(client, PRINT_HIGH, "Net rate set to %i\n", rate); client->netchan.rate = 1.0 / rate; } /* ================= SV_Msg_f Change the message level for a client ================= */ static void SV_Msg_f(client_t *client) { if (Cmd_Argc() != 2) { SV_ClientPrintf(client, PRINT_HIGH, "Current msg level is %i\n", client->messagelevel); return; } client->messagelevel = atoi(Cmd_Argv(1)); SV_ClientPrintf(client, PRINT_HIGH, "Msg level set to %i\n", client->messagelevel); } /* ================== SV_SetInfo_f Allow clients to change userinfo ================== */ static void SV_SetInfo_f(client_t *client) { int i; char oldval[MAX_INFO_STRING]; if (Cmd_Argc() == 1) { Con_Printf("User info settings:\n"); Info_Print(client->userinfo); return; } if (Cmd_Argc() != 3) { Con_Printf("usage: setinfo [ <key> <value> ]\n"); return; } if (Cmd_Argv(1)[0] == '*') return; // don't set priveledged values strcpy(oldval, Info_ValueForKey(client->userinfo, Cmd_Argv(1))); Info_SetValueForKey(client->userinfo, Cmd_Argv(1), Cmd_Argv(2), MAX_INFO_STRING); // name is extracted below in ExtractFromUserInfo // strncpy (client->name, Info_ValueForKey (client->userinfo, "name") // , sizeof(client->name)-1); // SV_FullClientUpdate (client, &sv.reliable_datagram); // client->sendinfo = true; if (!strcmp(Info_ValueForKey(client->userinfo, Cmd_Argv(1)), oldval)) return; // key hasn't changed // process any changed values SV_ExtractFromUserinfo(client); i = client - svs.clients; MSG_WriteByte(&sv.reliable_datagram, svc_setinfo); MSG_WriteByte(&sv.reliable_datagram, i); MSG_WriteString(&sv.reliable_datagram, Cmd_Argv(1)); MSG_WriteString(&sv.reliable_datagram, Info_ValueForKey(client->userinfo, Cmd_Argv(1))); } /* ================== SV_ShowServerinfo_f Dumps the serverinfo info string ================== */ static void SV_ShowServerinfo_f(client_t *client) { Info_Print(svs.info); } static void SV_NoSnap_f(client_t *client) { if (*client->uploadfn) { *client->uploadfn = 0; SV_BroadcastPrintf(PRINT_HIGH, "%s refused remote screenshot\n", client->name); } } typedef struct { const char *name; void (*func)(client_t *client); } ucmd_t; static ucmd_t ucmds[] = { { "new", SV_New_f }, { "modellist", SV_Modellist_f }, { "soundlist", SV_Soundlist_f }, { "prespawn", SV_PreSpawn_f }, { "spawn", SV_Spawn_f }, { "begin", SV_Begin_f }, { "drop", SV_Drop_f }, { "pings", SV_Pings_f }, // issued by hand at client consoles { "rate", SV_Rate_f }, { "kill", SV_Kill_f }, { "pause", SV_Pause_f }, { "msg", SV_Msg_f }, { "say", SV_Say_f }, { "say_team", SV_Say_Team_f }, { "setinfo", SV_SetInfo_f }, { "serverinfo", SV_ShowServerinfo_f }, { "download", SV_BeginDownload_f }, { "nextdl", SV_NextDownload_f }, { "ptrack", SV_PTrack_f }, //ZOID - used with autocam { "snap", SV_NoSnap_f }, { NULL, NULL } }; /* ================== SV_ExecuteUserCommand ================== */ static void SV_ExecuteUserCommand(const char *cmdstring, client_t *client) { ucmd_t *command; Cmd_TokenizeString(cmdstring); SV_BeginRedirect(RD_CLIENT, client); for (command = ucmds; command->name; command++) if (!strcmp(Cmd_Argv(0), command->name)) { command->func(client); break; } if (!command->name) Con_Printf("Bad user command: %s\n", Cmd_Argv(0)); SV_EndRedirect(); } /* =========================================================================== USER CMD EXECUTION =========================================================================== */ /* =============== V_CalcRoll Used by view and sv_user =============== */ static float V_CalcRoll(vec3_t angles, vec3_t velocity) { vec3_t forward, right, up; float sign; float side; float value; AngleVectors(angles, forward, right, up); side = DotProduct(velocity, right); sign = side < 0 ? -1 : 1; side = fabs(side); value = cl_rollangle.value; if (side < cl_rollspeed.value) side = side * value / cl_rollspeed.value; else side = value; return side * sign; } //============================================================================ /* ================ AddAllEntsToPhysents For debugging ================ */ #if 0 static void AddAllEntsToPhysents(const edict_t *player, const vec3_t mins, const vec3_t maxs, physent_stack_t *pestack) { int i, entity, playernum; edict_t *check, *next; physent_t *physent; playernum = EDICT_TO_PROG(player); check = NEXT_EDICT(sv.edicts); physent = pestack->physents + pestack->numphysents; for (entity = 1; entity < sv.num_edicts; entity++, check = next) { next = NEXT_EDICT(check); if (check->free) continue; if (check->v.owner == playernum) continue; if (check->v.solid == SOLID_BSP || check->v.solid == SOLID_BBOX || check->v.solid == SOLID_SLIDEBOX) { if (check == player) continue; for (i = 0; i < 3; i++) if (check->v.absmin[i] > maxs[i] || check->v.absmax[i] < mins[i]) break; if (i != 3) continue; if (physent - pestack->physents == MAX_PHYSENTS) break; VectorCopy(check->v.origin, physent->origin); physent->info = entity; if (check->v.solid == SOLID_BSP) physent->model = sv.models[(int)(check->v.modelindex)]; else { physent->model = NULL; VectorCopy(check->v.mins, physent->mins); VectorCopy(check->v.maxs, physent->maxs); } physent++; } } pestack->numphysents = physent - pestack->physents; } #endif /* =========== SV_PreRunCmd =========== Done before running a player command. Clears the touch array */ static byte playertouch[(MAX_EDICTS + 7) / 8]; static void SV_PreRunCmd(void) { memset(playertouch, 0, sizeof(playertouch)); } static void SV_PlayerMove(client_t *client, const usercmd_t *cmd) { edict_t *player = client->edict; playermove_t pmove; physent_stack_t pestack; vec3_t mins, maxs; edict_t *entity; int i; if (!player->v.fixangle) VectorCopy(cmd->angles, player->v.v_angle); player->v.button0 = cmd->buttons & 1; player->v.button2 = (cmd->buttons & 2) >> 1; if (cmd->impulse) player->v.impulse = cmd->impulse; // // angles // show 1/3 the pitch angle and all the roll angle if (player->v.health > 0) { if (!player->v.fixangle) { player->v.angles[PITCH] = -player->v.v_angle[PITCH] / 3; player->v.angles[YAW] = player->v.v_angle[YAW]; } player->v.angles[ROLL] = V_CalcRoll(player->v.angles, player->v.velocity) * 4; } host_frametime = cmd->msec * 0.001; if (host_frametime > 0.1) host_frametime = 0.1; if (!client->spectator) { pr_global_struct->frametime = host_frametime; pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(player); PR_ExecuteProgram(pr_global_struct->PlayerPreThink); SV_RunThink(player); } for (i = 0; i < 3; i++) pmove.origin[i] = player->v.origin[i] + (player->v.mins[i] - player_mins[i]); VectorCopy(player->v.velocity, pmove.velocity); VectorCopy(player->v.v_angle, pmove.angles); pmove.spectator = client->spectator; pmove.waterjumptime = player->v.teleport_time; pmove.cmd = cmd; pmove.dead = player->v.health <= 0; pmove.oldbuttons = client->oldbuttons; movevars.entgravity = client->entgravity; movevars.maxspeed = client->maxspeed; /* Init the world's physent */ memset(&pestack.physents[0], 0, sizeof(pestack.physents[0])); pestack.physents[0].brushmodel = ConstBrushModel(&sv.worldmodel->model); pestack.numphysent = 1; for (i = 0; i < 3; i++) { mins[i] = pmove.origin[i] - 256; maxs[i] = pmove.origin[i] + 256; } #if 1 SV_AddLinksToPhysents(player, mins, maxs, &pestack); #else AddAllEntsToPmove(player, mins, maxs, &pestack); #endif #if 0 { int before, after; before = PM_TestPlayerPosition(pmove.origin); PlayerMove(&pmove, &pestack); after = PM_TestPlayerPosition(pmove.origin); if (player->v.health > 0 && before && !after) Con_Printf("player %s got stuck in playermove!!!!\n", client->name); } #else PlayerMove(&pmove, &pestack); #endif client->oldbuttons = pmove.oldbuttons; player->v.teleport_time = pmove.waterjumptime; player->v.waterlevel = pmove.waterlevel; player->v.watertype = pmove.watertype; if (pmove.onground) { const int entitynum = pmove.onground->entitynum; player->v.groundentity = EDICT_TO_PROG(EDICT_NUM(entitynum)); player->v.flags = (int)player->v.flags | FL_ONGROUND; } else player->v.flags = (int)player->v.flags & ~FL_ONGROUND; for (i = 0; i < 3; i++) player->v.origin[i] = pmove.origin[i] - (player->v.mins[i] - player_mins[i]); #if 0 // truncate velocity the same way the net protocol will for (i = 0; i < 3; i++) player->v.velocity[i] = (int)pmove.velocity[i]; #else VectorCopy(pmove.velocity, player->v.velocity); #endif VectorCopy(pmove.angles, player->v.v_angle); if (!client->spectator) { // link into place and touch triggers SV_LinkEdict(player, true); // touch other objects for (i = 0; i < pmove.numtouch; i++) { const int entitynum = pmove.touch[i]->entitynum; entity = EDICT_NUM(entitynum); if (!entity->v.touch) continue; if (playertouch[entitynum / 8] & (1 << (entitynum % 8))) continue; pr_global_struct->self = EDICT_TO_PROG(entity); pr_global_struct->other = EDICT_TO_PROG(player); PR_ExecuteProgram(entity->v.touch); playertouch[entitynum / 8] |= 1 << (entitynum % 8); } } } /* =========== SV_RunCmd =========== */ static void SV_RunCmd(client_t *client, const usercmd_t *cmd) { /* split up very long moves */ if (cmd->msec > 50) { usercmd_t split = *cmd; split.msec /= 2; SV_RunCmd(client, &split); split.impulse = 0; SV_RunCmd(client, &split); return; } SV_PlayerMove(client, cmd); } /* =========== SV_PostRunCmd =========== Done after running a player command. */ static void SV_PostRunCmd(client_t *client) { edict_t *player = client->edict; /* run post-think */ if (!client->spectator) { pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(player); PR_ExecuteProgram(pr_global_struct->PlayerPostThink); SV_RunNewmis(); } else if (SpectatorThink) { pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(player); PR_ExecuteProgram(SpectatorThink); } } /* =================== SV_ExecuteClientMessage The current net_message is parsed for the given client =================== */ void SV_ExecuteClientMessage(client_t *client) { edict_t *player = client->edict; qboolean move_issued = false; client_frame_t *frame; netchan_t *netchan; usercmd_t oldest, oldcmd, newcmd; int command, seq_hash, crc_offset, length; byte checksum, crc, *crc_buf; vec3_t origin; /* Calculate ping time */ netchan = &client->netchan; frame = &client->frames[netchan->incoming_acknowledged & UPDATE_MASK]; frame->ping_time = realtime - frame->senttime; /* * Make sure the reply sequence number matches the incoming * sequence number. If not, don't reply! */ if (netchan->incoming_sequence >= netchan->outgoing_sequence) netchan->outgoing_sequence = netchan->incoming_sequence; else client->send_message = false; /* save time for ping calculations */ frame = &client->frames[netchan->outgoing_sequence & UPDATE_MASK]; frame->senttime = realtime; frame->ping_time = -1; seq_hash = netchan->incoming_sequence; /* * Mark time so clients will know how much to predict other players. * No delta unless requested. */ client->localtime = sv.time; client->delta_sequence = -1; while (1) { if (msg_badread) { Con_Printf("SV_ReadClientMessage: badread\n"); SV_DropClient(client); return; } command = MSG_ReadByte(); if (command == -1) break; switch (command) { default: Con_Printf("SV_ReadClientMessage: unknown command char\n"); SV_DropClient(client); return; case clc_nop: break; case clc_delta: client->delta_sequence = MSG_ReadByte(); break; case clc_move: /* Only one move allowed - no cheating! */ if (move_issued) return; move_issued = true; crc_offset = MSG_GetReadCount(); checksum = MSG_ReadByte(); /* read loss percentage */ client->lossage = MSG_ReadByte(); MSG_ReadDeltaUsercmd(&nullcmd, &oldest); MSG_ReadDeltaUsercmd(&oldest, &oldcmd); MSG_ReadDeltaUsercmd(&oldcmd, &newcmd); if (client->state != cs_spawned) break; /* if the checksum fails, ignore the rest of the packet */ crc_buf = net_message.data + crc_offset + 1; length = MSG_GetReadCount() - crc_offset - 1; crc = COM_BlockSequenceCRCByte(crc_buf, length, seq_hash); if (crc != checksum) { Con_DPrintf("Failed command checksum for %s(%d) (%d != %d)\n", client->name, netchan->incoming_sequence, checksum, crc); return; } if (!sv.paused) { SV_PreRunCmd(); if (net_drop < 20) { while (net_drop > 2) { SV_RunCmd(client, &client->lastcmd); net_drop--; } if (net_drop > 1) SV_RunCmd(client, &oldest); if (net_drop > 0) SV_RunCmd(client, &oldcmd); } SV_RunCmd(client, &newcmd); SV_PostRunCmd(client); } client->lastcmd = newcmd; client->lastcmd.buttons = 0; // avoid multiple fires on lag break; case clc_stringcmd: SV_ExecuteUserCommand(MSG_ReadString(), client); break; case clc_tmove: origin[0] = MSG_ReadCoord(); origin[1] = MSG_ReadCoord(); origin[2] = MSG_ReadCoord(); /* only allowed by spectators */ if (client->spectator) { VectorCopy(origin, player->v.origin); SV_LinkEdict(player, false); } break; case clc_upload: SV_NextUpload(client); break; } } } /* ============== SV_UserInit ============== */ void SV_UserInit(void) { Cvar_RegisterVariable(&cl_rollspeed); Cvar_RegisterVariable(&cl_rollangle); Cvar_RegisterVariable(&sv_spectalk); Cvar_RegisterVariable(&sv_mapcheck); }
{ "pile_set_name": "Github" }
*%(basename)s:6: SyntaxError: Identifier 'x' has already been declared import {y, x, z} from "modules-import-redeclare1.mjs"; ^ SyntaxError: Identifier 'x' has already been declared
{ "pile_set_name": "Github" }
### What is the difference between the array methods `map()` and `forEach()`? #### Answer Both methods iterate through the elements of an array. `map()` maps each element to a new element by invoking the callback function on each element and returning a new array. On the other hand, `forEach()` invokes the callback function for each element but does not return a new array. `forEach()` is generally used when causing a side effect on each iteration, whereas `map()` is a common functional programming technique. #### Good to hear * Use `forEach()` if you need to iterate over an array and cause mutations to the elements without needing to return values to generate a new array. * `map()` is the right choice to keep data immutable where each value of the original array is mapped to a new array. ##### Additional links * [MDN docs for forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) * [MDN docs for map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) * [JavaScript — Map vs. ForEach](https://codeburst.io/javascript-map-vs-foreach-f38111822c0f) <!-- tags: (javascript) --> <!-- expertise: (1) -->
{ "pile_set_name": "Github" }
import Logger from '/imports/startup/server/logger'; import Users from '/imports/api/users'; import { check } from 'meteor/check'; export default function changeUserLock(meetingId, payload) { check(meetingId, String); check(payload, { userId: String, locked: Boolean, lockedBy: String, }); const { userId, locked, lockedBy } = payload; const selector = { meetingId, userId, }; const modifier = { $set: { locked, }, }; const cb = (err, numChanged) => { if (err) { return Logger.error(`Changing user lock setting: ${err}`); } if (!numChanged) { return Logger.info(`User's userId=${userId} lock status wasn't updated`); } return Logger.info(`User's userId=${userId} lock status was changed to: ${locked} by user userId=${lockedBy}`); }; return Users.update(selector, modifier, cb); }
{ "pile_set_name": "Github" }
/* vi: set sw=4 ts=4: */ /* * resize - set terminal width and height. * * Copyright 2006 Bernhard Reutner-Fischer * * Licensed under GPLv2 or later, see file LICENSE in this source tree. */ /* no options, no getopt */ //usage:#define resize_trivial_usage //usage: "" //usage:#define resize_full_usage "\n\n" //usage: "Resize the screen" #include "libbb.h" #define ESC "\033" #define old_termios_p ((struct termios*)&bb_common_bufsiz1) static void onintr(int sig UNUSED_PARAM) { tcsetattr(STDERR_FILENO, TCSANOW, old_termios_p); _exit(EXIT_FAILURE); } int resize_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; int resize_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM) { struct termios new; struct winsize w = { 0, 0, 0, 0 }; int ret; /* We use _stderr_ in order to make resize usable * in shell backticks (those redirect stdout away from tty). * NB: other versions of resize open "/dev/tty" * and operate on it - should we do the same? */ tcgetattr(STDERR_FILENO, old_termios_p); /* fiddle echo */ memcpy(&new, old_termios_p, sizeof(new)); new.c_cflag |= (CLOCAL | CREAD); new.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); bb_signals(0 + (1 << SIGINT) + (1 << SIGQUIT) + (1 << SIGTERM) + (1 << SIGALRM) , onintr); tcsetattr(STDERR_FILENO, TCSANOW, &new); /* save_cursor_pos 7 * scroll_whole_screen [r * put_cursor_waaaay_off [$x;$yH * get_cursor_pos [6n * restore_cursor_pos 8 */ fprintf(stderr, ESC"7" ESC"[r" ESC"[999;999H" ESC"[6n"); alarm(3); /* Just in case terminal won't answer */ //BUG: death by signal won't restore termios scanf(ESC"[%hu;%huR", &w.ws_row, &w.ws_col); fprintf(stderr, ESC"8"); /* BTW, other versions of resize recalculate w.ws_xpixel, ws.ws_ypixel * by calculating character cell HxW from old values * (gotten via TIOCGWINSZ) and recomputing *pixel values */ ret = ioctl(STDERR_FILENO, TIOCSWINSZ, &w); tcsetattr(STDERR_FILENO, TCSANOW, old_termios_p); if (ENABLE_FEATURE_RESIZE_PRINT) printf("COLUMNS=%d;LINES=%d;export COLUMNS LINES;\n", w.ws_col, w.ws_row); return ret; }
{ "pile_set_name": "Github" }
def extractLleeloweCom(item): ''' Parser for 'lleelowe.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
{ "pile_set_name": "Github" }
/* * Fixed function pipeline replacement using GL_ATI_fragment_shader * * Copyright 2008 Stefan Dösinger(for CodeWeavers) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include "config.h" #include "wine/port.h" #include <stdio.h> #include "wined3d_private.h" WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader); WINE_DECLARE_DEBUG_CHANNEL(d3d); /* Context activation for state handlers is done by the caller. */ /* Some private defines, Constant associations, etc. * Env bump matrix and per stage constant should be independent, * a stage that bump maps can't read the per state constant */ #define ATIFS_CONST_BUMPMAT(i) (GL_CON_0_ATI + i) #define ATIFS_CONST_STAGE(i) (GL_CON_0_ATI + i) #define ATIFS_CONST_TFACTOR GL_CON_6_ATI enum atifs_constant_value { ATIFS_CONSTANT_UNUSED = 0, ATIFS_CONSTANT_BUMP, ATIFS_CONSTANT_TFACTOR, ATIFS_CONSTANT_STAGE, }; /* GL_ATI_fragment_shader specific fixed function pipeline description. "Inherits" from the common one */ struct atifs_ffp_desc { struct ffp_frag_desc parent; GLuint shader; unsigned int num_textures_used; enum atifs_constant_value constants[WINED3D_MAX_TEXTURES]; }; struct atifs_private_data { struct wine_rb_tree fragment_shaders; /* A rb-tree to track fragment pipeline replacement shaders */ }; struct atifs_context_private_data { const struct atifs_ffp_desc *last_shader; }; static const char *debug_dstmod(GLuint mod) { switch(mod) { case GL_NONE: return "GL_NONE"; case GL_2X_BIT_ATI: return "GL_2X_BIT_ATI"; case GL_4X_BIT_ATI: return "GL_4X_BIT_ATI"; case GL_8X_BIT_ATI: return "GL_8X_BIT_ATI"; case GL_HALF_BIT_ATI: return "GL_HALF_BIT_ATI"; case GL_QUARTER_BIT_ATI: return "GL_QUARTER_BIT_ATI"; case GL_EIGHTH_BIT_ATI: return "GL_EIGHTH_BIT_ATI"; case GL_SATURATE_BIT_ATI: return "GL_SATURATE_BIT_ATI"; default: return "Unexpected modifier\n"; } } static const char *debug_argmod(GLuint mod) { switch(mod) { case GL_NONE: return "GL_NONE"; case GL_2X_BIT_ATI: return "GL_2X_BIT_ATI"; case GL_COMP_BIT_ATI: return "GL_COMP_BIT_ATI"; case GL_NEGATE_BIT_ATI: return "GL_NEGATE_BIT_ATI"; case GL_BIAS_BIT_ATI: return "GL_BIAS_BIT_ATI"; case GL_2X_BIT_ATI | GL_COMP_BIT_ATI: return "GL_2X_BIT_ATI | GL_COMP_BIT_ATI"; case GL_2X_BIT_ATI | GL_NEGATE_BIT_ATI: return "GL_2X_BIT_ATI | GL_NEGATE_BIT_ATI"; case GL_2X_BIT_ATI | GL_BIAS_BIT_ATI: return "GL_2X_BIT_ATI | GL_BIAS_BIT_ATI"; case GL_COMP_BIT_ATI | GL_NEGATE_BIT_ATI: return "GL_COMP_BIT_ATI | GL_NEGATE_BIT_ATI"; case GL_COMP_BIT_ATI | GL_BIAS_BIT_ATI: return "GL_COMP_BIT_ATI | GL_BIAS_BIT_ATI"; case GL_NEGATE_BIT_ATI | GL_BIAS_BIT_ATI: return "GL_NEGATE_BIT_ATI | GL_BIAS_BIT_ATI"; case GL_COMP_BIT_ATI | GL_NEGATE_BIT_ATI | GL_BIAS_BIT_ATI: return "GL_COMP_BIT_ATI | GL_NEGATE_BIT_ATI | GL_BIAS_BIT_ATI"; case GL_2X_BIT_ATI | GL_NEGATE_BIT_ATI | GL_BIAS_BIT_ATI: return "GL_2X_BIT_ATI | GL_NEGATE_BIT_ATI | GL_BIAS_BIT_ATI"; case GL_2X_BIT_ATI | GL_COMP_BIT_ATI | GL_BIAS_BIT_ATI: return "GL_2X_BIT_ATI | GL_COMP_BIT_ATI | GL_BIAS_BIT_ATI"; case GL_2X_BIT_ATI | GL_COMP_BIT_ATI | GL_NEGATE_BIT_ATI: return "GL_2X_BIT_ATI | GL_COMP_BIT_ATI | GL_NEGATE_BIT_ATI"; case GL_2X_BIT_ATI | GL_COMP_BIT_ATI | GL_NEGATE_BIT_ATI | GL_BIAS_BIT_ATI: return "GL_2X_BIT_ATI | GL_COMP_BIT_ATI | GL_NEGATE_BIT_ATI | GL_BIAS_BIT_ATI"; default: return "Unexpected argmod combination\n"; } } static const char *debug_register(GLuint reg) { switch(reg) { case GL_REG_0_ATI: return "GL_REG_0_ATI"; case GL_REG_1_ATI: return "GL_REG_1_ATI"; case GL_REG_2_ATI: return "GL_REG_2_ATI"; case GL_REG_3_ATI: return "GL_REG_3_ATI"; case GL_REG_4_ATI: return "GL_REG_4_ATI"; case GL_REG_5_ATI: return "GL_REG_5_ATI"; case GL_CON_0_ATI: return "GL_CON_0_ATI"; case GL_CON_1_ATI: return "GL_CON_1_ATI"; case GL_CON_2_ATI: return "GL_CON_2_ATI"; case GL_CON_3_ATI: return "GL_CON_3_ATI"; case GL_CON_4_ATI: return "GL_CON_4_ATI"; case GL_CON_5_ATI: return "GL_CON_5_ATI"; case GL_CON_6_ATI: return "GL_CON_6_ATI"; case GL_CON_7_ATI: return "GL_CON_7_ATI"; case GL_ZERO: return "GL_ZERO"; case GL_ONE: return "GL_ONE"; case GL_PRIMARY_COLOR: return "GL_PRIMARY_COLOR"; case GL_SECONDARY_INTERPOLATOR_ATI: return "GL_SECONDARY_INTERPOLATOR_ATI"; default: return "Unknown register\n"; } } static const char *debug_swizzle(GLuint swizzle) { switch(swizzle) { case GL_SWIZZLE_STR_ATI: return "GL_SWIZZLE_STR_ATI"; case GL_SWIZZLE_STQ_ATI: return "GL_SWIZZLE_STQ_ATI"; case GL_SWIZZLE_STR_DR_ATI: return "GL_SWIZZLE_STR_DR_ATI"; case GL_SWIZZLE_STQ_DQ_ATI: return "GL_SWIZZLE_STQ_DQ_ATI"; default: return "unknown swizzle"; } } static const char *debug_rep(GLuint rep) { switch(rep) { case GL_NONE: return "GL_NONE"; case GL_RED: return "GL_RED"; case GL_GREEN: return "GL_GREEN"; case GL_BLUE: return "GL_BLUE"; case GL_ALPHA: return "GL_ALPHA"; default: return "unknown argrep"; } } static const char *debug_op(GLuint op) { switch(op) { case GL_MOV_ATI: return "GL_MOV_ATI"; case GL_ADD_ATI: return "GL_ADD_ATI"; case GL_MUL_ATI: return "GL_MUL_ATI"; case GL_SUB_ATI: return "GL_SUB_ATI"; case GL_DOT3_ATI: return "GL_DOT3_ATI"; case GL_DOT4_ATI: return "GL_DOT4_ATI"; case GL_MAD_ATI: return "GL_MAD_ATI"; case GL_LERP_ATI: return "GL_LERP_ATI"; case GL_CND_ATI: return "GL_CND_ATI"; case GL_CND0_ATI: return "GL_CND0_ATI"; case GL_DOT2_ADD_ATI: return "GL_DOT2_ADD_ATI"; default: return "unexpected op"; } } static const char *debug_mask(GLuint mask) { switch(mask) { case GL_NONE: return "GL_NONE"; case GL_RED_BIT_ATI: return "GL_RED_BIT_ATI"; case GL_GREEN_BIT_ATI: return "GL_GREEN_BIT_ATI"; case GL_BLUE_BIT_ATI: return "GL_BLUE_BIT_ATI"; case GL_RED_BIT_ATI | GL_GREEN_BIT_ATI: return "GL_RED_BIT_ATI | GL_GREEN_BIT_ATI"; case GL_RED_BIT_ATI | GL_BLUE_BIT_ATI: return "GL_RED_BIT_ATI | GL_BLUE_BIT_ATI"; case GL_GREEN_BIT_ATI | GL_BLUE_BIT_ATI:return "GL_GREEN_BIT_ATI | GL_BLUE_BIT_ATI"; case GL_RED_BIT_ATI | GL_GREEN_BIT_ATI | GL_BLUE_BIT_ATI:return "GL_RED_BIT_ATI | GL_GREEN_BIT_ATI | GL_BLUE_BIT_ATI"; default: return "Unexpected writemask"; } } static void wrap_op1(const struct wined3d_gl_info *gl_info, GLuint op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod) { if(dstMask == GL_ALPHA) { TRACE("glAlphaFragmentOp1ATI(%s, %s, %s, %s, %s, %s)\n", debug_op(op), debug_register(dst), debug_dstmod(dstMod), debug_register(arg1), debug_rep(arg1Rep), debug_argmod(arg1Mod)); GL_EXTCALL(glAlphaFragmentOp1ATI(op, dst, dstMod, arg1, arg1Rep, arg1Mod)); } else { TRACE("glColorFragmentOp1ATI(%s, %s, %s, %s, %s, %s, %s)\n", debug_op(op), debug_register(dst), debug_mask(dstMask), debug_dstmod(dstMod), debug_register(arg1), debug_rep(arg1Rep), debug_argmod(arg1Mod)); GL_EXTCALL(glColorFragmentOp1ATI(op, dst, dstMask, dstMod, arg1, arg1Rep, arg1Mod)); } } static void wrap_op2(const struct wined3d_gl_info *gl_info, GLuint op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod) { if(dstMask == GL_ALPHA) { TRACE("glAlphaFragmentOp2ATI(%s, %s, %s, %s, %s, %s, %s, %s, %s)\n", debug_op(op), debug_register(dst), debug_dstmod(dstMod), debug_register(arg1), debug_rep(arg1Rep), debug_argmod(arg1Mod), debug_register(arg2), debug_rep(arg2Rep), debug_argmod(arg2Mod)); GL_EXTCALL(glAlphaFragmentOp2ATI(op, dst, dstMod, arg1, arg1Rep, arg1Mod, arg2, arg2Rep, arg2Mod)); } else { TRACE("glColorFragmentOp2ATI(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n", debug_op(op), debug_register(dst), debug_mask(dstMask), debug_dstmod(dstMod), debug_register(arg1), debug_rep(arg1Rep), debug_argmod(arg1Mod), debug_register(arg2), debug_rep(arg2Rep), debug_argmod(arg2Mod)); GL_EXTCALL(glColorFragmentOp2ATI(op, dst, dstMask, dstMod, arg1, arg1Rep, arg1Mod, arg2, arg2Rep, arg2Mod)); } } static void wrap_op3(const struct wined3d_gl_info *gl_info, GLuint op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod) { if(dstMask == GL_ALPHA) { /* Leave some free space to fit "GL_NONE, " in to align most alpha and color op lines */ TRACE("glAlphaFragmentOp3ATI(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n", debug_op(op), debug_register(dst), debug_dstmod(dstMod), debug_register(arg1), debug_rep(arg1Rep), debug_argmod(arg1Mod), debug_register(arg2), debug_rep(arg2Rep), debug_argmod(arg2Mod), debug_register(arg3), debug_rep(arg3Rep), debug_argmod(arg3Mod)); GL_EXTCALL(glAlphaFragmentOp3ATI(op, dst, dstMod, arg1, arg1Rep, arg1Mod, arg2, arg2Rep, arg2Mod, arg3, arg3Rep, arg3Mod)); } else { TRACE("glColorFragmentOp3ATI(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n", debug_op(op), debug_register(dst), debug_mask(dstMask), debug_dstmod(dstMod), debug_register(arg1), debug_rep(arg1Rep), debug_argmod(arg1Mod), debug_register(arg2), debug_rep(arg2Rep), debug_argmod(arg2Mod), debug_register(arg3), debug_rep(arg3Rep), debug_argmod(arg3Mod)); GL_EXTCALL(glColorFragmentOp3ATI(op, dst, dstMask, dstMod, arg1, arg1Rep, arg1Mod, arg2, arg2Rep, arg2Mod, arg3, arg3Rep, arg3Mod)); } } static GLuint register_for_arg(DWORD arg, const struct wined3d_gl_info *gl_info, unsigned int stage, GLuint *mod, GLuint *rep, GLuint tmparg) { GLenum ret; if(mod) *mod = GL_NONE; if(arg == ARG_UNUSED) { if (rep) *rep = GL_NONE; return -1; /* This is the marker for unused registers */ } switch(arg & WINED3DTA_SELECTMASK) { case WINED3DTA_DIFFUSE: ret = GL_PRIMARY_COLOR; break; case WINED3DTA_CURRENT: /* Note that using GL_REG_0_ATI for the passed on register is safe because * texture0 is read at stage0, so in the worst case it is read in the * instruction writing to reg0. Afterwards texture0 is not used any longer. * If we're reading from current */ ret = stage ? GL_REG_0_ATI : GL_PRIMARY_COLOR; break; case WINED3DTA_TEXTURE: ret = GL_REG_0_ATI + stage; break; case WINED3DTA_TFACTOR: ret = ATIFS_CONST_TFACTOR; break; case WINED3DTA_SPECULAR: ret = GL_SECONDARY_INTERPOLATOR_ATI; break; case WINED3DTA_TEMP: ret = tmparg; break; case WINED3DTA_CONSTANT: ret = ATIFS_CONST_STAGE(stage); break; default: FIXME("Unknown source argument %d\n", arg); ret = GL_ZERO; } if(arg & WINED3DTA_COMPLEMENT) { if(mod) *mod |= GL_COMP_BIT_ATI; } if(arg & WINED3DTA_ALPHAREPLICATE) { if(rep) *rep = GL_ALPHA; } else { if(rep) *rep = GL_NONE; } return ret; } static GLuint find_tmpreg(const struct texture_stage_op op[WINED3D_MAX_TEXTURES]) { int lowest_read = -1; int lowest_write = -1; int i; BOOL tex_used[WINED3D_MAX_TEXTURES]; memset(tex_used, 0, sizeof(tex_used)); for (i = 0; i < WINED3D_MAX_TEXTURES; ++i) { if (op[i].cop == WINED3D_TOP_DISABLE) break; if(lowest_read == -1 && (op[i].carg1 == WINED3DTA_TEMP || op[i].carg2 == WINED3DTA_TEMP || op[i].carg0 == WINED3DTA_TEMP || op[i].aarg1 == WINED3DTA_TEMP || op[i].aarg2 == WINED3DTA_TEMP || op[i].aarg0 == WINED3DTA_TEMP)) { lowest_read = i; } if (lowest_write == -1 && op[i].tmp_dst) lowest_write = i; if(op[i].carg1 == WINED3DTA_TEXTURE || op[i].carg2 == WINED3DTA_TEXTURE || op[i].carg0 == WINED3DTA_TEXTURE || op[i].aarg1 == WINED3DTA_TEXTURE || op[i].aarg2 == WINED3DTA_TEXTURE || op[i].aarg0 == WINED3DTA_TEXTURE) { tex_used[i] = TRUE; } } /* Temp reg not read? We don't need it, return GL_NONE */ if(lowest_read == -1) return GL_NONE; if(lowest_write >= lowest_read) { FIXME("Temp register read before being written\n"); } if(lowest_write == -1) { /* This needs a test. Maybe we are supposed to return 0.0/0.0/0.0/0.0, or fail drawprim, or whatever */ FIXME("Temp register read without being written\n"); return GL_REG_1_ATI; } else if(lowest_write >= 1) { /* If we're writing to the temp reg at earliest in stage 1, we can use register 1 for the temp result. * there may be texture data stored in reg 1, but we do not need it any longer since stage 1 already * read it */ return GL_REG_1_ATI; } else { /* Search for a free texture register. We have 6 registers available. GL_REG_0_ATI is already used * for the regular result */ for(i = 1; i < 6; i++) { if(!tex_used[i]) { return GL_REG_0_ATI + i; } } /* What to do here? Report it in ValidateDevice? */ FIXME("Could not find a register for the temporary register\n"); return 0; } } static const struct color_fixup_desc color_fixup_rg = { 1, CHANNEL_SOURCE_X, 1, CHANNEL_SOURCE_Y, 0, CHANNEL_SOURCE_ONE, 0, CHANNEL_SOURCE_ONE }; static const struct color_fixup_desc color_fixup_rgl = { 1, CHANNEL_SOURCE_X, 1, CHANNEL_SOURCE_Y, 0, CHANNEL_SOURCE_Z, 0, CHANNEL_SOURCE_W }; static const struct color_fixup_desc color_fixup_rgba = { 1, CHANNEL_SOURCE_X, 1, CHANNEL_SOURCE_Y, 1, CHANNEL_SOURCE_Z, 1, CHANNEL_SOURCE_W }; static BOOL op_reads_texture(const struct texture_stage_op *op) { return (op->carg0 & WINED3DTA_SELECTMASK) == WINED3DTA_TEXTURE || (op->carg1 & WINED3DTA_SELECTMASK) == WINED3DTA_TEXTURE || (op->carg2 & WINED3DTA_SELECTMASK) == WINED3DTA_TEXTURE || (op->aarg0 & WINED3DTA_SELECTMASK) == WINED3DTA_TEXTURE || (op->aarg1 & WINED3DTA_SELECTMASK) == WINED3DTA_TEXTURE || (op->aarg2 & WINED3DTA_SELECTMASK) == WINED3DTA_TEXTURE || op->cop == WINED3D_TOP_BLEND_TEXTURE_ALPHA; } static void atifs_color_fixup(const struct wined3d_gl_info *gl_info, struct color_fixup_desc fixup, GLuint reg) { if(is_same_fixup(fixup, color_fixup_rg)) { wrap_op1(gl_info, GL_MOV_ATI, reg, GL_RED_BIT_ATI | GL_GREEN_BIT_ATI, GL_NONE, reg, GL_NONE, GL_2X_BIT_ATI | GL_BIAS_BIT_ATI); wrap_op1(gl_info, GL_MOV_ATI, reg, GL_BLUE_BIT_ATI, GL_NONE, GL_ONE, GL_NONE, GL_NONE); wrap_op1(gl_info, GL_MOV_ATI, reg, GL_ALPHA, GL_NONE, GL_ONE, GL_NONE, GL_NONE); } else if(is_same_fixup(fixup, color_fixup_rgl)) { wrap_op1(gl_info, GL_MOV_ATI, reg, GL_RED_BIT_ATI | GL_GREEN_BIT_ATI, GL_NONE, reg, GL_NONE, GL_2X_BIT_ATI | GL_BIAS_BIT_ATI); } else if (is_same_fixup(fixup, color_fixup_rgba)) { wrap_op1(gl_info, GL_MOV_ATI, reg, GL_NONE, GL_NONE, reg, GL_NONE, GL_2X_BIT_ATI | GL_BIAS_BIT_ATI); wrap_op1(gl_info, GL_MOV_ATI, reg, GL_ALPHA, GL_NONE, reg, GL_NONE, GL_2X_BIT_ATI | GL_BIAS_BIT_ATI); } else { /* Should not happen - atifs_color_fixup_supported refuses other fixups. */ ERR("Unsupported color fixup.\n"); } } static BOOL op_reads_tfactor(const struct texture_stage_op *op) { return (op->carg0 & WINED3DTA_SELECTMASK) == WINED3DTA_TFACTOR || (op->carg1 & WINED3DTA_SELECTMASK) == WINED3DTA_TFACTOR || (op->carg2 & WINED3DTA_SELECTMASK) == WINED3DTA_TFACTOR || (op->aarg0 & WINED3DTA_SELECTMASK) == WINED3DTA_TFACTOR || (op->aarg1 & WINED3DTA_SELECTMASK) == WINED3DTA_TFACTOR || (op->aarg2 & WINED3DTA_SELECTMASK) == WINED3DTA_TFACTOR || op->cop == WINED3D_TOP_BLEND_FACTOR_ALPHA || op->aop == WINED3D_TOP_BLEND_FACTOR_ALPHA; } static BOOL op_reads_constant(const struct texture_stage_op *op) { return (op->carg0 & WINED3DTA_SELECTMASK) == WINED3DTA_CONSTANT || (op->carg1 & WINED3DTA_SELECTMASK) == WINED3DTA_CONSTANT || (op->carg2 & WINED3DTA_SELECTMASK) == WINED3DTA_CONSTANT || (op->aarg0 & WINED3DTA_SELECTMASK) == WINED3DTA_CONSTANT || (op->aarg1 & WINED3DTA_SELECTMASK) == WINED3DTA_CONSTANT || (op->aarg2 & WINED3DTA_SELECTMASK) == WINED3DTA_CONSTANT; } static GLuint gen_ati_shader(const struct texture_stage_op op[WINED3D_MAX_TEXTURES], const struct wined3d_gl_info *gl_info, enum atifs_constant_value *constants) { GLuint ret = GL_EXTCALL(glGenFragmentShadersATI(1)); unsigned int stage; GLuint arg0, arg1, arg2, extrarg; GLuint dstmod, argmod0, argmod1, argmod2, argmodextra; GLuint rep0, rep1, rep2; GLuint swizzle; GLuint tmparg = find_tmpreg(op); GLuint dstreg; BOOL tfactor_used = FALSE; if(!ret) { ERR("Failed to generate a GL_ATI_fragment_shader shader id\n"); return 0; } GL_EXTCALL(glBindFragmentShaderATI(ret)); checkGLcall("GL_EXTCALL(glBindFragmentShaderATI(ret))"); TRACE("glBeginFragmentShaderATI()\n"); GL_EXTCALL(glBeginFragmentShaderATI()); checkGLcall("GL_EXTCALL(glBeginFragmentShaderATI())"); /* Pass 1: Generate sampling instructions for perturbation maps */ for (stage = 0; stage < gl_info->limits.textures; ++stage) { if (op[stage].cop == WINED3D_TOP_DISABLE) break; if (op[stage].cop != WINED3D_TOP_BUMPENVMAP && op[stage].cop != WINED3D_TOP_BUMPENVMAP_LUMINANCE) continue; constants[stage] = ATIFS_CONSTANT_BUMP; TRACE("glSampleMapATI(GL_REG_%d_ATI, GL_TEXTURE_%d_ARB, GL_SWIZZLE_STR_ATI)\n", stage, stage); GL_EXTCALL(glSampleMapATI(GL_REG_0_ATI + stage, GL_TEXTURE0_ARB + stage, GL_SWIZZLE_STR_ATI)); if (op[stage + 1].projected == WINED3D_PROJECTION_NONE) swizzle = GL_SWIZZLE_STR_ATI; else if (op[stage + 1].projected == WINED3D_PROJECTION_COUNT4) swizzle = GL_SWIZZLE_STQ_DQ_ATI; else swizzle = GL_SWIZZLE_STR_DR_ATI; TRACE("glPassTexCoordATI(GL_REG_%d_ATI, GL_TEXTURE_%d_ARB, %s)\n", stage + 1, stage + 1, debug_swizzle(swizzle)); GL_EXTCALL(glPassTexCoordATI(GL_REG_0_ATI + stage + 1, GL_TEXTURE0_ARB + stage + 1, swizzle)); } /* Pass 2: Generate perturbation calculations */ for (stage = 0; stage < gl_info->limits.textures; ++stage) { GLuint argmodextra_x, argmodextra_y; struct color_fixup_desc fixup; if (op[stage].cop == WINED3D_TOP_DISABLE) break; if (op[stage].cop != WINED3D_TOP_BUMPENVMAP && op[stage].cop != WINED3D_TOP_BUMPENVMAP_LUMINANCE) continue; fixup = op[stage].color_fixup; if (fixup.x_source != CHANNEL_SOURCE_X || fixup.y_source != CHANNEL_SOURCE_Y) { FIXME("Swizzles not implemented\n"); argmodextra_x = GL_NONE; argmodextra_y = GL_NONE; } else { /* Nice thing, we get the color correction for free :-) */ argmodextra_x = fixup.x_sign_fixup ? GL_2X_BIT_ATI | GL_BIAS_BIT_ATI : GL_NONE; argmodextra_y = fixup.y_sign_fixup ? GL_2X_BIT_ATI | GL_BIAS_BIT_ATI : GL_NONE; } wrap_op3(gl_info, GL_DOT2_ADD_ATI, GL_REG_0_ATI + stage + 1, GL_RED_BIT_ATI, GL_NONE, GL_REG_0_ATI + stage, GL_NONE, argmodextra_x, ATIFS_CONST_BUMPMAT(stage), GL_NONE, GL_2X_BIT_ATI | GL_BIAS_BIT_ATI, GL_REG_0_ATI + stage + 1, GL_RED, GL_NONE); /* Don't use GL_DOT2_ADD_ATI here because we cannot configure it to read the blue and alpha * component of the bump matrix. Instead do this with two MADs: * * coord.a = tex.r * bump.b + coord.g * coord.g = tex.g * bump.a + coord.a * * The first instruction writes to alpha so it can be coissued with the above DOT2_ADD. * coord.a is unused. If the perturbed texture is projected, this was already handled * in the glPassTexCoordATI above. */ wrap_op3(gl_info, GL_MAD_ATI, GL_REG_0_ATI + stage + 1, GL_ALPHA, GL_NONE, GL_REG_0_ATI + stage, GL_RED, argmodextra_y, ATIFS_CONST_BUMPMAT(stage), GL_BLUE, GL_2X_BIT_ATI | GL_BIAS_BIT_ATI, GL_REG_0_ATI + stage + 1, GL_GREEN, GL_NONE); wrap_op3(gl_info, GL_MAD_ATI, GL_REG_0_ATI + stage + 1, GL_GREEN_BIT_ATI, GL_NONE, GL_REG_0_ATI + stage, GL_GREEN, argmodextra_y, ATIFS_CONST_BUMPMAT(stage), GL_ALPHA, GL_2X_BIT_ATI | GL_BIAS_BIT_ATI, GL_REG_0_ATI + stage + 1, GL_ALPHA, GL_NONE); } /* Pass 3: Generate sampling instructions for regular textures */ for (stage = 0; stage < gl_info->limits.textures; ++stage) { if (op[stage].cop == WINED3D_TOP_DISABLE) break; if (op[stage].projected == WINED3D_PROJECTION_NONE) swizzle = GL_SWIZZLE_STR_ATI; else if (op[stage].projected == WINED3D_PROJECTION_COUNT3) swizzle = GL_SWIZZLE_STR_DR_ATI; else swizzle = GL_SWIZZLE_STQ_DQ_ATI; if (op_reads_texture(&op[stage])) { if (stage > 0 && (op[stage - 1].cop == WINED3D_TOP_BUMPENVMAP || op[stage - 1].cop == WINED3D_TOP_BUMPENVMAP_LUMINANCE)) { TRACE("glSampleMapATI(GL_REG_%d_ATI, GL_REG_%d_ATI, GL_SWIZZLE_STR_ATI)\n", stage, stage); GL_EXTCALL(glSampleMapATI(GL_REG_0_ATI + stage, GL_REG_0_ATI + stage, GL_SWIZZLE_STR_ATI)); } else { TRACE("glSampleMapATI(GL_REG_%d_ATI, GL_TEXTURE_%d_ARB, %s)\n", stage, stage, debug_swizzle(swizzle)); GL_EXTCALL(glSampleMapATI(GL_REG_0_ATI + stage, GL_TEXTURE0_ARB + stage, swizzle)); } } } /* Pass 4: Generate the arithmetic instructions */ for (stage = 0; stage < WINED3D_MAX_TEXTURES; ++stage) { if (op[stage].cop == WINED3D_TOP_DISABLE) { if (!stage) { /* Handle complete texture disabling gracefully */ wrap_op1(gl_info, GL_MOV_ATI, GL_REG_0_ATI, GL_NONE, GL_NONE, GL_PRIMARY_COLOR, GL_NONE, GL_NONE); wrap_op1(gl_info, GL_MOV_ATI, GL_REG_0_ATI, GL_ALPHA, GL_NONE, GL_PRIMARY_COLOR, GL_NONE, GL_NONE); } break; } if (op[stage].tmp_dst) { /* If we're writing to D3DTA_TEMP, but never reading from it we * don't have to write there in the first place. Skip the entire * stage, this saves some GPU time. */ if (tmparg == GL_NONE) continue; dstreg = tmparg; } else { dstreg = GL_REG_0_ATI; } if (op[stage].cop == WINED3D_TOP_BUMPENVMAP || op[stage].cop == WINED3D_TOP_BUMPENVMAP_LUMINANCE) { /* Those are handled in the first pass of the shader (generation pass 1 and 2) already */ continue; } arg0 = register_for_arg(op[stage].carg0, gl_info, stage, &argmod0, &rep0, tmparg); arg1 = register_for_arg(op[stage].carg1, gl_info, stage, &argmod1, &rep1, tmparg); arg2 = register_for_arg(op[stage].carg2, gl_info, stage, &argmod2, &rep2, tmparg); dstmod = GL_NONE; argmodextra = GL_NONE; extrarg = GL_NONE; if (op_reads_tfactor(&op[stage])) tfactor_used = TRUE; if (op_reads_constant(&op[stage])) { if (constants[stage] != ATIFS_CONSTANT_UNUSED) FIXME("Constant %u already used.\n", stage); constants[stage] = ATIFS_CONSTANT_STAGE; } if (op_reads_texture(&op[stage]) && !is_identity_fixup(op[stage].color_fixup)) atifs_color_fixup(gl_info, op[stage].color_fixup, GL_REG_0_ATI + stage); switch (op[stage].cop) { case WINED3D_TOP_SELECT_ARG2: arg1 = arg2; argmod1 = argmod2; rep1 = rep2; /* fall through */ case WINED3D_TOP_SELECT_ARG1: wrap_op1(gl_info, GL_MOV_ATI, dstreg, GL_NONE, GL_NONE, arg1, rep1, argmod1); break; case WINED3D_TOP_MODULATE_4X: if(dstmod == GL_NONE) dstmod = GL_4X_BIT_ATI; /* fall through */ case WINED3D_TOP_MODULATE_2X: if(dstmod == GL_NONE) dstmod = GL_2X_BIT_ATI; dstmod |= GL_SATURATE_BIT_ATI; /* fall through */ case WINED3D_TOP_MODULATE: wrap_op2(gl_info, GL_MUL_ATI, dstreg, GL_NONE, dstmod, arg1, rep1, argmod1, arg2, rep2, argmod2); break; case WINED3D_TOP_ADD_SIGNED_2X: dstmod = GL_2X_BIT_ATI; /* fall through */ case WINED3D_TOP_ADD_SIGNED: argmodextra = GL_BIAS_BIT_ATI; /* fall through */ case WINED3D_TOP_ADD: dstmod |= GL_SATURATE_BIT_ATI; wrap_op2(gl_info, GL_ADD_ATI, GL_REG_0_ATI, GL_NONE, dstmod, arg1, rep1, argmod1, arg2, rep2, argmodextra | argmod2); break; case WINED3D_TOP_SUBTRACT: dstmod |= GL_SATURATE_BIT_ATI; wrap_op2(gl_info, GL_SUB_ATI, dstreg, GL_NONE, dstmod, arg1, rep1, argmod1, arg2, rep2, argmod2); break; case WINED3D_TOP_ADD_SMOOTH: argmodextra = argmod1 & GL_COMP_BIT_ATI ? argmod1 & ~GL_COMP_BIT_ATI : argmod1 | GL_COMP_BIT_ATI; /* Dst = arg1 + * arg2(1 -arg 1) * = arg2 * (1 - arg1) + arg1 */ wrap_op3(gl_info, GL_MAD_ATI, dstreg, GL_NONE, GL_SATURATE_BIT_ATI, arg2, rep2, argmod2, arg1, rep1, argmodextra, arg1, rep1, argmod1); break; case WINED3D_TOP_BLEND_CURRENT_ALPHA: if (extrarg == GL_NONE) extrarg = register_for_arg(WINED3DTA_CURRENT, gl_info, stage, NULL, NULL, -1); /* fall through */ case WINED3D_TOP_BLEND_FACTOR_ALPHA: if (extrarg == GL_NONE) extrarg = register_for_arg(WINED3DTA_TFACTOR, gl_info, stage, NULL, NULL, -1); /* fall through */ case WINED3D_TOP_BLEND_TEXTURE_ALPHA: if (extrarg == GL_NONE) extrarg = register_for_arg(WINED3DTA_TEXTURE, gl_info, stage, NULL, NULL, -1); /* fall through */ case WINED3D_TOP_BLEND_DIFFUSE_ALPHA: if (extrarg == GL_NONE) extrarg = register_for_arg(WINED3DTA_DIFFUSE, gl_info, stage, NULL, NULL, -1); wrap_op3(gl_info, GL_LERP_ATI, dstreg, GL_NONE, GL_NONE, extrarg, GL_ALPHA, GL_NONE, arg1, rep1, argmod1, arg2, rep2, argmod2); break; case WINED3D_TOP_BLEND_TEXTURE_ALPHA_PM: arg0 = register_for_arg(WINED3DTA_TEXTURE, gl_info, stage, NULL, NULL, -1); wrap_op3(gl_info, GL_MAD_ATI, dstreg, GL_NONE, GL_NONE, arg2, rep2, argmod2, arg0, GL_ALPHA, GL_COMP_BIT_ATI, arg1, rep1, argmod1); break; /* D3DTOP_PREMODULATE ???? */ case WINED3D_TOP_MODULATE_INVALPHA_ADD_COLOR: argmodextra = argmod1 & GL_COMP_BIT_ATI ? argmod1 & ~GL_COMP_BIT_ATI : argmod1 | GL_COMP_BIT_ATI; /* fall through */ case WINED3D_TOP_MODULATE_ALPHA_ADD_COLOR: if (!argmodextra) argmodextra = argmod1; wrap_op3(gl_info, GL_MAD_ATI, dstreg, GL_NONE, GL_SATURATE_BIT_ATI, arg2, rep2, argmod2, arg1, GL_ALPHA, argmodextra, arg1, rep1, argmod1); break; case WINED3D_TOP_MODULATE_INVCOLOR_ADD_ALPHA: argmodextra = argmod1 & GL_COMP_BIT_ATI ? argmod1 & ~GL_COMP_BIT_ATI : argmod1 | GL_COMP_BIT_ATI; /* fall through */ case WINED3D_TOP_MODULATE_COLOR_ADD_ALPHA: if (!argmodextra) argmodextra = argmod1; wrap_op3(gl_info, GL_MAD_ATI, dstreg, GL_NONE, GL_SATURATE_BIT_ATI, arg2, rep2, argmod2, arg1, rep1, argmodextra, arg1, GL_ALPHA, argmod1); break; case WINED3D_TOP_DOTPRODUCT3: wrap_op2(gl_info, GL_DOT3_ATI, dstreg, GL_NONE, GL_4X_BIT_ATI | GL_SATURATE_BIT_ATI, arg1, rep1, argmod1 | GL_BIAS_BIT_ATI, arg2, rep2, argmod2 | GL_BIAS_BIT_ATI); break; case WINED3D_TOP_MULTIPLY_ADD: wrap_op3(gl_info, GL_MAD_ATI, dstreg, GL_NONE, GL_SATURATE_BIT_ATI, arg1, rep1, argmod1, arg2, rep2, argmod2, arg0, rep0, argmod0); break; case WINED3D_TOP_LERP: wrap_op3(gl_info, GL_LERP_ATI, dstreg, GL_NONE, GL_NONE, arg0, rep0, argmod0, arg1, rep1, argmod1, arg2, rep2, argmod2); break; default: FIXME("Unhandled color operation %d on stage %d\n", op[stage].cop, stage); } arg0 = register_for_arg(op[stage].aarg0, gl_info, stage, &argmod0, NULL, tmparg); arg1 = register_for_arg(op[stage].aarg1, gl_info, stage, &argmod1, NULL, tmparg); arg2 = register_for_arg(op[stage].aarg2, gl_info, stage, &argmod2, NULL, tmparg); dstmod = GL_NONE; argmodextra = GL_NONE; extrarg = GL_NONE; switch (op[stage].aop) { case WINED3D_TOP_DISABLE: /* Get the primary color to the output if on stage 0, otherwise leave register 0 untouched */ if (!stage) { wrap_op1(gl_info, GL_MOV_ATI, GL_REG_0_ATI, GL_ALPHA, GL_NONE, GL_PRIMARY_COLOR, GL_NONE, GL_NONE); } break; case WINED3D_TOP_SELECT_ARG2: arg1 = arg2; argmod1 = argmod2; /* fall through */ case WINED3D_TOP_SELECT_ARG1: wrap_op1(gl_info, GL_MOV_ATI, dstreg, GL_ALPHA, GL_NONE, arg1, GL_NONE, argmod1); break; case WINED3D_TOP_MODULATE_4X: if (dstmod == GL_NONE) dstmod = GL_4X_BIT_ATI; /* fall through */ case WINED3D_TOP_MODULATE_2X: if (dstmod == GL_NONE) dstmod = GL_2X_BIT_ATI; dstmod |= GL_SATURATE_BIT_ATI; /* fall through */ case WINED3D_TOP_MODULATE: wrap_op2(gl_info, GL_MUL_ATI, dstreg, GL_ALPHA, dstmod, arg1, GL_NONE, argmod1, arg2, GL_NONE, argmod2); break; case WINED3D_TOP_ADD_SIGNED_2X: dstmod = GL_2X_BIT_ATI; /* fall through */ case WINED3D_TOP_ADD_SIGNED: argmodextra = GL_BIAS_BIT_ATI; /* fall through */ case WINED3D_TOP_ADD: dstmod |= GL_SATURATE_BIT_ATI; wrap_op2(gl_info, GL_ADD_ATI, dstreg, GL_ALPHA, dstmod, arg1, GL_NONE, argmod1, arg2, GL_NONE, argmodextra | argmod2); break; case WINED3D_TOP_SUBTRACT: dstmod |= GL_SATURATE_BIT_ATI; wrap_op2(gl_info, GL_SUB_ATI, dstreg, GL_ALPHA, dstmod, arg1, GL_NONE, argmod1, arg2, GL_NONE, argmod2); break; case WINED3D_TOP_ADD_SMOOTH: argmodextra = argmod1 & GL_COMP_BIT_ATI ? argmod1 & ~GL_COMP_BIT_ATI : argmod1 | GL_COMP_BIT_ATI; /* Dst = arg1 + * arg2(1 -arg 1) * = arg2 * (1 - arg1) + arg1 */ wrap_op3(gl_info, GL_MAD_ATI, dstreg, GL_ALPHA, GL_SATURATE_BIT_ATI, arg2, GL_NONE, argmod2, arg1, GL_NONE, argmodextra, arg1, GL_NONE, argmod1); break; case WINED3D_TOP_BLEND_CURRENT_ALPHA: if (extrarg == GL_NONE) extrarg = register_for_arg(WINED3DTA_CURRENT, gl_info, stage, NULL, NULL, -1); /* fall through */ case WINED3D_TOP_BLEND_FACTOR_ALPHA: if (extrarg == GL_NONE) extrarg = register_for_arg(WINED3DTA_TFACTOR, gl_info, stage, NULL, NULL, -1); /* fall through */ case WINED3D_TOP_BLEND_TEXTURE_ALPHA: if (extrarg == GL_NONE) extrarg = register_for_arg(WINED3DTA_TEXTURE, gl_info, stage, NULL, NULL, -1); /* fall through */ case WINED3D_TOP_BLEND_DIFFUSE_ALPHA: if (extrarg == GL_NONE) extrarg = register_for_arg(WINED3DTA_DIFFUSE, gl_info, stage, NULL, NULL, -1); wrap_op3(gl_info, GL_LERP_ATI, dstreg, GL_ALPHA, GL_NONE, extrarg, GL_ALPHA, GL_NONE, arg1, GL_NONE, argmod1, arg2, GL_NONE, argmod2); break; case WINED3D_TOP_BLEND_TEXTURE_ALPHA_PM: arg0 = register_for_arg(WINED3DTA_TEXTURE, gl_info, stage, NULL, NULL, -1); wrap_op3(gl_info, GL_MAD_ATI, dstreg, GL_ALPHA, GL_NONE, arg2, GL_NONE, argmod2, arg0, GL_ALPHA, GL_COMP_BIT_ATI, arg1, GL_NONE, argmod1); break; /* D3DTOP_PREMODULATE ???? */ case WINED3D_TOP_DOTPRODUCT3: wrap_op2(gl_info, GL_DOT3_ATI, dstreg, GL_ALPHA, GL_4X_BIT_ATI | GL_SATURATE_BIT_ATI, arg1, GL_NONE, argmod1 | GL_BIAS_BIT_ATI, arg2, GL_NONE, argmod2 | GL_BIAS_BIT_ATI); break; case WINED3D_TOP_MULTIPLY_ADD: wrap_op3(gl_info, GL_MAD_ATI, dstreg, GL_ALPHA, GL_SATURATE_BIT_ATI, arg1, GL_NONE, argmod1, arg2, GL_NONE, argmod2, arg0, GL_NONE, argmod0); break; case WINED3D_TOP_LERP: wrap_op3(gl_info, GL_LERP_ATI, dstreg, GL_ALPHA, GL_SATURATE_BIT_ATI, arg1, GL_NONE, argmod1, arg2, GL_NONE, argmod2, arg0, GL_NONE, argmod0); break; case WINED3D_TOP_MODULATE_INVALPHA_ADD_COLOR: case WINED3D_TOP_MODULATE_ALPHA_ADD_COLOR: case WINED3D_TOP_MODULATE_COLOR_ADD_ALPHA: case WINED3D_TOP_MODULATE_INVCOLOR_ADD_ALPHA: case WINED3D_TOP_BUMPENVMAP: case WINED3D_TOP_BUMPENVMAP_LUMINANCE: ERR("Application uses an invalid alpha operation\n"); break; default: FIXME("Unhandled alpha operation %d on stage %d\n", op[stage].aop, stage); } } if (tfactor_used && constants[ATIFS_CONST_TFACTOR - GL_CON_0_ATI] != ATIFS_CONSTANT_UNUSED) FIXME("Texture factor constant already used.\n"); constants[ATIFS_CONST_TFACTOR - GL_CON_0_ATI] = ATIFS_CONSTANT_TFACTOR; /* Assign unused constants to avoid reloading due to unused <-> bump matrix switches. */ for (stage = 0; stage < WINED3D_MAX_TEXTURES; ++stage) { if (constants[stage] == ATIFS_CONSTANT_UNUSED) constants[stage] = ATIFS_CONSTANT_BUMP; } TRACE("glEndFragmentShaderATI()\n"); GL_EXTCALL(glEndFragmentShaderATI()); checkGLcall("GL_EXTCALL(glEndFragmentShaderATI())"); return ret; } static void atifs_tfactor(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id) { struct atifs_context_private_data *ctx_priv = context->fragment_pipe_data; struct wined3d_context_gl *context_gl = wined3d_context_gl(context); const struct wined3d_gl_info *gl_info = context_gl->gl_info; struct wined3d_color color; if (!ctx_priv->last_shader || ctx_priv->last_shader->constants[ATIFS_CONST_TFACTOR - GL_CON_0_ATI] != ATIFS_CONSTANT_TFACTOR) return; wined3d_color_from_d3dcolor(&color, state->render_states[WINED3D_RS_TEXTUREFACTOR]); GL_EXTCALL(glSetFragmentShaderConstantATI(ATIFS_CONST_TFACTOR, &color.r)); checkGLcall("glSetFragmentShaderConstantATI(ATIFS_CONST_TFACTOR, &color.r)"); } static void set_bumpmat(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id) { DWORD stage = (state_id - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1); struct wined3d_context_gl *context_gl = wined3d_context_gl(context); const struct wined3d_gl_info *gl_info = context_gl->gl_info; float mat[2][2]; struct atifs_context_private_data *ctx_priv = context->fragment_pipe_data; if (!ctx_priv->last_shader || ctx_priv->last_shader->constants[stage] != ATIFS_CONSTANT_BUMP) return; mat[0][0] = *((float *)&state->texture_states[stage][WINED3D_TSS_BUMPENV_MAT00]); mat[1][0] = *((float *)&state->texture_states[stage][WINED3D_TSS_BUMPENV_MAT01]); mat[0][1] = *((float *)&state->texture_states[stage][WINED3D_TSS_BUMPENV_MAT10]); mat[1][1] = *((float *)&state->texture_states[stage][WINED3D_TSS_BUMPENV_MAT11]); /* GL_ATI_fragment_shader allows only constants from 0.0 to 1.0, but the bumpmat * constants can be in any range. While they should stay between [-1.0 and 1.0] because * Shader Model 1.x pixel shaders are clamped to that range negative values are used occasionally, * for example by our d3d9 test. So to get negative values scale -1;1 to 0;1 and undo that in the * shader(it is free). This might potentially reduce precision. However, if the hardware does * support proper floats it shouldn't, and if it doesn't we can't get anything better anyway. */ mat[0][0] = (mat[0][0] + 1.0f) * 0.5f; mat[1][0] = (mat[1][0] + 1.0f) * 0.5f; mat[0][1] = (mat[0][1] + 1.0f) * 0.5f; mat[1][1] = (mat[1][1] + 1.0f) * 0.5f; GL_EXTCALL(glSetFragmentShaderConstantATI(ATIFS_CONST_BUMPMAT(stage), (float *) mat)); checkGLcall("glSetFragmentShaderConstantATI(ATIFS_CONST_BUMPMAT(stage), mat)"); } static void atifs_stage_constant(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id) { DWORD stage = (state_id - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1); struct atifs_context_private_data *ctx_priv = context->fragment_pipe_data; struct wined3d_context_gl *context_gl = wined3d_context_gl(context); const struct wined3d_gl_info *gl_info = context_gl->gl_info; struct wined3d_color color; if (!ctx_priv->last_shader || ctx_priv->last_shader->constants[stage] != ATIFS_CONSTANT_STAGE) return; wined3d_color_from_d3dcolor(&color, state->texture_states[stage][WINED3D_TSS_CONSTANT]); GL_EXTCALL(glSetFragmentShaderConstantATI(ATIFS_CONST_STAGE(stage), &color.r)); checkGLcall("glSetFragmentShaderConstantATI(ATIFS_CONST_STAGE(stage), &color.r)"); } static void set_tex_op_atifs(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id) { struct atifs_context_private_data *ctx_priv = context->fragment_pipe_data; const struct atifs_ffp_desc *desc, *last_shader = ctx_priv->last_shader; struct wined3d_context_gl *context_gl = wined3d_context_gl(context); const struct wined3d_d3d_info *d3d_info = context->d3d_info; const struct wined3d_gl_info *gl_info = context_gl->gl_info; const struct wined3d_device *device = context->device; struct atifs_private_data *priv = device->fragment_priv; struct ffp_frag_settings settings; DWORD mapped_stage; unsigned int i; gen_ffp_frag_op(context, state, &settings, TRUE); desc = (const struct atifs_ffp_desc *)find_ffp_frag_shader(&priv->fragment_shaders, &settings); if (!desc) { struct atifs_ffp_desc *new_desc; if (!(new_desc = heap_alloc_zero(sizeof(*new_desc)))) { ERR("Out of memory\n"); return; } new_desc->num_textures_used = 0; for (i = 0; i < d3d_info->limits.ffp_blend_stages; ++i) { if (settings.op[i].cop == WINED3D_TOP_DISABLE) break; ++new_desc->num_textures_used; } new_desc->parent.settings = settings; new_desc->shader = gen_ati_shader(settings.op, gl_info, new_desc->constants); add_ffp_frag_shader(&priv->fragment_shaders, &new_desc->parent); TRACE("Allocated fixed function replacement shader descriptor %p.\n", new_desc); desc = new_desc; } /* GL_ATI_fragment_shader depends on the GL_TEXTURE_xD enable settings. Update the texture stages * used by this shader */ for (i = 0; i < desc->num_textures_used; ++i) { mapped_stage = context_gl->tex_unit_map[i]; if (mapped_stage != WINED3D_UNMAPPED_STAGE) { wined3d_context_gl_active_texture(context_gl, gl_info, mapped_stage); texture_activate_dimensions(state->textures[i], gl_info); } } GL_EXTCALL(glBindFragmentShaderATI(desc->shader)); ctx_priv->last_shader = desc; for (i = 0; i < WINED3D_MAX_TEXTURES; i++) { if (last_shader && last_shader->constants[i] == desc->constants[i]) continue; switch (desc->constants[i]) { case ATIFS_CONSTANT_BUMP: set_bumpmat(context, state, STATE_TEXTURESTAGE(i, WINED3D_TSS_BUMPENV_MAT00)); break; case ATIFS_CONSTANT_TFACTOR: atifs_tfactor(context, state, STATE_RENDER(WINED3D_RS_TEXTUREFACTOR)); break; case ATIFS_CONSTANT_STAGE: atifs_stage_constant(context, state, STATE_TEXTURESTAGE(i, WINED3D_TSS_CONSTANT)); break; default: ERR("Unexpected constant type %u.\n", desc->constants[i]); } } } static void textransform(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id) { if (!isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL))) set_tex_op_atifs(context, state, state_id); } static void atifs_srgbwriteenable(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id) { if (state->render_states[WINED3D_RS_SRGBWRITEENABLE]) WARN("sRGB writes are not supported by this fragment pipe.\n"); } static const struct wined3d_state_entry_template atifs_fragmentstate_template[] = { {STATE_RENDER(WINED3D_RS_TEXTUREFACTOR), { STATE_RENDER(WINED3D_RS_TEXTUREFACTOR), atifs_tfactor }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_ALPHAFUNC), { STATE_RENDER(WINED3D_RS_ALPHATESTENABLE), NULL }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_ALPHAREF), { STATE_RENDER(WINED3D_RS_ALPHATESTENABLE), NULL }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_ALPHATESTENABLE), { STATE_RENDER(WINED3D_RS_ALPHATESTENABLE), state_alpha_test }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_COLORKEYENABLE), { STATE_RENDER(WINED3D_RS_ALPHATESTENABLE), NULL }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_FOGCOLOR), { STATE_RENDER(WINED3D_RS_FOGCOLOR), state_fogcolor }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_FOGDENSITY), { STATE_RENDER(WINED3D_RS_FOGDENSITY), state_fogdensity }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_FOGENABLE), { STATE_RENDER(WINED3D_RS_FOGENABLE), state_fog_fragpart }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_FOGTABLEMODE), { STATE_RENDER(WINED3D_RS_FOGENABLE), NULL }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_FOGVERTEXMODE), { STATE_RENDER(WINED3D_RS_FOGENABLE), NULL }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_FOGSTART), { STATE_RENDER(WINED3D_RS_FOGSTART), state_fogstartend }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_FOGEND), { STATE_RENDER(WINED3D_RS_FOGSTART), NULL }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE), { STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE), atifs_srgbwriteenable }, WINED3D_GL_EXT_NONE }, {STATE_COLOR_KEY, { STATE_COLOR_KEY, state_nop }, WINED3D_GL_EXT_NONE }, {STATE_RENDER(WINED3D_RS_SHADEMODE), { STATE_RENDER(WINED3D_RS_SHADEMODE), state_shademode }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_ALPHA_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_ALPHA_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_ALPHA_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_ALPHA_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_RESULT_ARG), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00), { STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00), set_bumpmat }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT01), { STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT10), { STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT11), { STATE_TEXTURESTAGE(0, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0, WINED3D_TSS_CONSTANT), { STATE_TEXTURESTAGE(0, WINED3D_TSS_CONSTANT), atifs_stage_constant }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_COLOR_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_COLOR_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_COLOR_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_COLOR_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_ALPHA_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_ALPHA_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_ALPHA_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_ALPHA_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_RESULT_ARG), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00), { STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00), set_bumpmat }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT01), { STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT10), { STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT11), { STATE_TEXTURESTAGE(1, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1, WINED3D_TSS_CONSTANT), { STATE_TEXTURESTAGE(1, WINED3D_TSS_CONSTANT), atifs_stage_constant }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_COLOR_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_COLOR_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_COLOR_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_COLOR_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_ALPHA_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_ALPHA_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_ALPHA_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_ALPHA_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_RESULT_ARG), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00), { STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00), set_bumpmat }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT01), { STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT10), { STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT11), { STATE_TEXTURESTAGE(2, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2, WINED3D_TSS_CONSTANT), { STATE_TEXTURESTAGE(2, WINED3D_TSS_CONSTANT), atifs_stage_constant }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_COLOR_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_COLOR_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_COLOR_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_COLOR_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_ALPHA_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_ALPHA_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_ALPHA_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_ALPHA_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_RESULT_ARG), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00), { STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00), set_bumpmat }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT01), { STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT10), { STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT11), { STATE_TEXTURESTAGE(3, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3, WINED3D_TSS_CONSTANT), { STATE_TEXTURESTAGE(3, WINED3D_TSS_CONSTANT), atifs_stage_constant }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_COLOR_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_COLOR_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_COLOR_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_COLOR_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_ALPHA_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_ALPHA_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_ALPHA_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_ALPHA_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_RESULT_ARG), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00), { STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00), set_bumpmat }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT01), { STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT10), { STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT11), { STATE_TEXTURESTAGE(4, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4, WINED3D_TSS_CONSTANT), { STATE_TEXTURESTAGE(4, WINED3D_TSS_CONSTANT), atifs_stage_constant }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_COLOR_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_COLOR_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_COLOR_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_COLOR_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_ALPHA_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_ALPHA_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_ALPHA_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_ALPHA_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_RESULT_ARG), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00), { STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00), set_bumpmat }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT01), { STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT10), { STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT11), { STATE_TEXTURESTAGE(5, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5, WINED3D_TSS_CONSTANT), { STATE_TEXTURESTAGE(5, WINED3D_TSS_CONSTANT), atifs_stage_constant }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_COLOR_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_COLOR_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_COLOR_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_COLOR_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_ALPHA_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_ALPHA_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_ALPHA_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_ALPHA_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_RESULT_ARG), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00), { STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00), set_bumpmat }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT01), { STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT10), { STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT11), { STATE_TEXTURESTAGE(6, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6, WINED3D_TSS_CONSTANT), { STATE_TEXTURESTAGE(6, WINED3D_TSS_CONSTANT), atifs_stage_constant }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_COLOR_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_COLOR_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_COLOR_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_COLOR_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_ALPHA_OP), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_ALPHA_ARG1), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_ALPHA_ARG2), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_ALPHA_ARG0), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_RESULT_ARG), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00), { STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00), set_bumpmat }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT01), { STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT10), { STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT11), { STATE_TEXTURESTAGE(7, WINED3D_TSS_BUMPENV_MAT00), NULL }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7, WINED3D_TSS_CONSTANT), { STATE_TEXTURESTAGE(7, WINED3D_TSS_CONSTANT), atifs_stage_constant }, WINED3D_GL_EXT_NONE }, { STATE_SAMPLER(0), { STATE_SAMPLER(0), sampler_texdim }, WINED3D_GL_EXT_NONE }, { STATE_SAMPLER(1), { STATE_SAMPLER(1), sampler_texdim }, WINED3D_GL_EXT_NONE }, { STATE_SAMPLER(2), { STATE_SAMPLER(2), sampler_texdim }, WINED3D_GL_EXT_NONE }, { STATE_SAMPLER(3), { STATE_SAMPLER(3), sampler_texdim }, WINED3D_GL_EXT_NONE }, { STATE_SAMPLER(4), { STATE_SAMPLER(4), sampler_texdim }, WINED3D_GL_EXT_NONE }, { STATE_SAMPLER(5), { STATE_SAMPLER(5), sampler_texdim }, WINED3D_GL_EXT_NONE }, { STATE_SAMPLER(6), { STATE_SAMPLER(6), sampler_texdim }, WINED3D_GL_EXT_NONE }, { STATE_SAMPLER(7), { STATE_SAMPLER(7), sampler_texdim }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(0,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(0, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), textransform }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(1,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(1, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), textransform }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(2,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(2, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), textransform }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(3,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(3, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), textransform }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(4,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(4, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), textransform }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(5,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(5, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), textransform }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(6,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(6, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), textransform }, WINED3D_GL_EXT_NONE }, {STATE_TEXTURESTAGE(7,WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), {STATE_TEXTURESTAGE(7, WINED3D_TSS_TEXTURE_TRANSFORM_FLAGS), textransform }, WINED3D_GL_EXT_NONE }, {STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), { STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL), set_tex_op_atifs }, WINED3D_GL_EXT_NONE }, {0 /* Terminate */, { 0, 0 }, WINED3D_GL_EXT_NONE }, }; /* Context activation is done by the caller. */ static void atifs_enable(const struct wined3d_context *context, BOOL enable) { const struct wined3d_gl_info *gl_info = wined3d_context_gl_const(context)->gl_info; if (enable) { gl_info->gl_ops.gl.p_glEnable(GL_FRAGMENT_SHADER_ATI); checkGLcall("glEnable(GL_FRAGMENT_SHADER_ATI)"); } else { gl_info->gl_ops.gl.p_glDisable(GL_FRAGMENT_SHADER_ATI); checkGLcall("glDisable(GL_FRAGMENT_SHADER_ATI)"); } } static void atifs_get_caps(const struct wined3d_adapter *adapter, struct fragment_caps *caps) { caps->wined3d_caps = WINED3D_FRAGMENT_CAP_PROJ_CONTROL; caps->PrimitiveMiscCaps = WINED3DPMISCCAPS_TSSARGTEMP | WINED3DPMISCCAPS_PERSTAGECONSTANT; caps->TextureOpCaps = WINED3DTEXOPCAPS_DISABLE | WINED3DTEXOPCAPS_SELECTARG1 | WINED3DTEXOPCAPS_SELECTARG2 | WINED3DTEXOPCAPS_MODULATE4X | WINED3DTEXOPCAPS_MODULATE2X | WINED3DTEXOPCAPS_MODULATE | WINED3DTEXOPCAPS_ADDSIGNED2X | WINED3DTEXOPCAPS_ADDSIGNED | WINED3DTEXOPCAPS_ADD | WINED3DTEXOPCAPS_SUBTRACT | WINED3DTEXOPCAPS_ADDSMOOTH | WINED3DTEXOPCAPS_BLENDCURRENTALPHA | WINED3DTEXOPCAPS_BLENDFACTORALPHA | WINED3DTEXOPCAPS_BLENDTEXTUREALPHA | WINED3DTEXOPCAPS_BLENDDIFFUSEALPHA | WINED3DTEXOPCAPS_BLENDTEXTUREALPHAPM | WINED3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR | WINED3DTEXOPCAPS_MODULATECOLOR_ADDALPHA | WINED3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA | WINED3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR | WINED3DTEXOPCAPS_DOTPRODUCT3 | WINED3DTEXOPCAPS_MULTIPLYADD | WINED3DTEXOPCAPS_LERP | WINED3DTEXOPCAPS_BUMPENVMAP; /* TODO: Implement WINED3DTEXOPCAPS_BUMPENVMAPLUMINANCE and WINED3DTEXOPCAPS_PREMODULATE */ /* GL_ATI_fragment_shader always supports 6 textures, which was the limit on r200 cards * which this extension is exclusively focused on(later cards have GL_ARB_fragment_program). * If the current card has more than 8 fixed function textures in OpenGL's regular fixed * function pipeline then the ATI_fragment_shader backend imposes a stricter limit. This * shouldn't be too hard since Nvidia cards have a limit of 4 textures with the default ffp * pipeline, and almost all games are happy with that. We can however support up to 8 * texture stages because we have a 2nd pass limit of 8 instructions, and per stage we use * only 1 instruction. * * The proper fix for this is not to use GL_ATI_fragment_shader on cards newer than the * r200 series and use an ARB or GLSL shader instead */ caps->MaxTextureBlendStages = WINED3D_MAX_TEXTURES; caps->MaxSimultaneousTextures = 6; } static DWORD atifs_get_emul_mask(const struct wined3d_gl_info *gl_info) { return GL_EXT_EMUL_ARB_MULTITEXTURE | GL_EXT_EMUL_EXT_FOG_COORD; } static void *atifs_alloc(const struct wined3d_shader_backend_ops *shader_backend, void *shader_priv) { struct atifs_private_data *priv; if (!(priv = heap_alloc_zero(sizeof(*priv)))) return NULL; wine_rb_init(&priv->fragment_shaders, wined3d_ffp_frag_program_key_compare); return priv; } /* Context activation is done by the caller. */ static void atifs_free_ffpshader(struct wine_rb_entry *entry, void *param) { struct atifs_ffp_desc *entry_ati = WINE_RB_ENTRY_VALUE(entry, struct atifs_ffp_desc, parent.entry); struct wined3d_context_gl *context_gl = param; const struct wined3d_gl_info *gl_info; gl_info = context_gl->gl_info; GL_EXTCALL(glDeleteFragmentShaderATI(entry_ati->shader)); checkGLcall("glDeleteFragmentShaderATI(entry->shader)"); heap_free(entry_ati); } /* Context activation is done by the caller. */ static void atifs_free(struct wined3d_device *device, struct wined3d_context *context) { struct wined3d_context_gl *context_gl = wined3d_context_gl(context); struct atifs_private_data *priv = device->fragment_priv; wine_rb_destroy(&priv->fragment_shaders, atifs_free_ffpshader, context_gl); heap_free(priv); device->fragment_priv = NULL; } static BOOL atifs_color_fixup_supported(struct color_fixup_desc fixup) { /* We only support sign fixup of the first two channels. */ return is_identity_fixup(fixup) || is_same_fixup(fixup, color_fixup_rg) || is_same_fixup(fixup, color_fixup_rgl) || is_same_fixup(fixup, color_fixup_rgba); } static BOOL atifs_alloc_context_data(struct wined3d_context *context) { struct atifs_context_private_data *priv; if (!(priv = heap_alloc_zero(sizeof(*priv)))) return FALSE; context->fragment_pipe_data = priv; return TRUE; } static void atifs_free_context_data(struct wined3d_context *context) { heap_free(context->fragment_pipe_data); } const struct wined3d_fragment_pipe_ops atifs_fragment_pipeline = { atifs_enable, atifs_get_caps, atifs_get_emul_mask, atifs_alloc, atifs_free, atifs_alloc_context_data, atifs_free_context_data, atifs_color_fixup_supported, atifs_fragmentstate_template, };
{ "pile_set_name": "Github" }
# $NetBSD: Makefile,v 1.5 2016/08/24 10:29:50 wiz Exp $ DISTNAME= urw-fonts-2.0 CATEGORIES= fonts MASTER_SITES= http://pkgs.fedoraproject.org/repo/pkgs/urw-fonts/urw-fonts-2.0.tar.bz2/c5cc8237e4289fc6ebeaa296174fa504/ EXTRACT_SUFX= .tar.bz2 MAINTAINER= pkgsrc-users@NetBSD.org #HOMEPAGE= http://download.gimp.org/pub/gimp/fonts/ COMMENT= Standard postscript fonts (cyrillicized) LICENSE= gnu-gpl-v2 WRKSRC= ${WRKDIR}/fonts USE_LANGUAGES= # none NO_BUILD= yes FONTS_DIR= ${PREFIX}/share/fonts/urw INSTALLATION_DIRS= share/fonts/urw do-install: for ext in afm pfb; \ do \ for f in ${WRKSRC}/*.$${ext}; \ do \ ${INSTALL_DATA} $${f} ${DESTDIR}${FONTS_DIR}; \ done; \ done .include "../../mk/bsd.pkg.mk"
{ "pile_set_name": "Github" }
%% @author Marc Worrell <marc@worrell.nl> %% @copyright 2009 Marc Worrell %% Date: 2009-04-28 %% @doc Open a dialog that asks confirmation to delete a resource. %% Copyright 2009 Marc Worrell %% %% Licensed under the Apache License, Version 2.0 (the "License"); %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% http://www.apache.org/licenses/LICENSE-2.0 %% %% Unless required by applicable law or agreed to in writing, software %% distributed under the License is distributed on an "AS IS" BASIS, %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(action_admin_dialog_delete_rsc). -author("Marc Worrell <marc@worrell.nl"). %% interface functions -export([ render_action/4, event/2 ]). -include_lib("zotonic_core/include/zotonic.hrl"). render_action(TriggerId, TargetId, Args, Context) -> Id = z_convert:to_integer(proplists:get_value(id, Args)), OnSuccess = proplists:get_all_values(on_success, Args), Postback = {delete_rsc_dialog, Id, OnSuccess}, {PostbackMsgJS, _PickledPostback} = z_render:make_postback(Postback, click, TriggerId, TargetId, ?MODULE, Context), {PostbackMsgJS, Context}. %% @doc Fill the dialog with the delete confirmation template. The next step will ask to delete the resource %% @spec event(Event, Context1) -> Context2 event(#postback{message={delete_rsc_dialog, Id, OnSuccess}}, Context) -> case z_acl:rsc_deletable(Id, Context) of true -> Vars = [ {on_success, OnSuccess}, {id, Id} ], z_render:dialog(?__("Confirm delete", Context), {cat, "_action_dialog_delete_rsc.tpl"}, Vars, Context); false -> z_render:growl_error(?__("You are not allowed to delete this page.", Context), Context) end.
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: a2d92a77769be44d2a8b1ac0d864184a timeCreated: 1469052897 licenseType: Free PluginImporter: serializedVersion: 1 iconMap: {} executionOrder: {} isPreloaded: 0 platformData: Any: enabled: 1 settings: {} Editor: enabled: 0 settings: DefaultValueInitialized: true userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
{ "icao": "hs", "name": "General Aviation Thailand", "callsign": { "name": "Hotel Sierra", "callsignFormats": [ "@@@" ] }, "fleets": { "default": [ ["BE36", 5], ["C172", 5], ["C182", 5], ["C208", 3], ["C337", 5], ["C510", 3], ["C550", 7], ["C750", 3], ["E135", 1], ["E50P", 1], ["E545", 1], ["E55P", 1], ["P28A", 5] ], "cessna": [ ["C208", 2], ["C337", 5], ["C510", 2], ["C550", 5], ["C750", 2] ], "lightGA": [ ["BE36", 5], ["C172", 5], ["C182", 5], ["C208", 1], ["P28A", 5] ], "fastGA": [ ["C510", 1], ["C550", 2], ["C750", 1], ["E135", 1], ["E50P", 1], ["E545", 1], ["E55P", 1] ] } }
{ "pile_set_name": "Github" }
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1001 &100100000 Prefab: m_ObjectHideFlags: 1 serializedVersion: 2 m_Modification: m_TransformParent: {fileID: 0} m_Modifications: [] m_RemovedComponents: [] m_ParentPrefab: {fileID: 0} m_RootGameObject: {fileID: 1105457086738104} m_IsPrefabParent: 1 --- !u!1 &1105457086738104 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 224525241888118476} - component: {fileID: 222516048781656936} - component: {fileID: 114449823977643292} - component: {fileID: 114267058075094406} m_Layer: 5 m_Name: EditorButtonJump m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1539546867676356 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4791804203800714} - component: {fileID: 212288209519828114} m_Layer: 0 m_Name: Icon m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4791804203800714 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1539546867676356} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 8, y: 8, z: 10} m_Children: [] m_Father: {fileID: 224525241888118476} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &114267058075094406 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1105457086738104} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 8119b3ca34da40d4085e0cc140debf80, type: 3} m_Name: m_EditorClassIdentifier: spriteRenderer: {fileID: 212288209519828114} --- !u!114 &114449823977643292 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1105457086738104} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.9215687, g: 0.9215687, b: 0.9215687, a: 0} m_RaycastTarget: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 21300000, guid: 4df834905b3d954448ebe7e06d6aa771, type: 3} m_Type: 0 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 m_FillAmount: 1 m_FillClockwise: 1 m_FillOrigin: 0 --- !u!212 &212288209519828114 SpriteRenderer: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1539546867676356} m_Enabled: 1 m_CastShadows: 0 m_ReceiveShadows: 0 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_Materials: - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_SelectedEditorRenderState: 0 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 m_Sprite: {fileID: 21300000, guid: 47369a531bb4b3b48be03e6ab58b30ec, type: 3} m_Color: {r: 1, g: 1, b: 1, a: 1} m_FlipX: 0 m_FlipY: 0 m_DrawMode: 0 m_Size: {x: 5.12, y: 5.12} m_AdaptiveModeThreshold: 0.5 m_SpriteTileMode: 0 --- !u!222 &222516048781656936 CanvasRenderer: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1105457086738104} --- !u!224 &224525241888118476 RectTransform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1105457086738104} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: -1} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4791804203800714} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 0, y: 0} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 40, y: 40} m_Pivot: {x: 0.5, y: 0.5}
{ "pile_set_name": "Github" }
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one // or more contributor license agreements. Licensed under the Elastic License; // you may not use this file except in compliance with the Elastic License. package common import ( "errors" "reflect" "testing" "github.com/stretchr/testify/require" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/validation/field" commonv1 "github.com/elastic/cloud-on-k8s/pkg/apis/common/v1" "github.com/elastic/cloud-on-k8s/pkg/utils/k8s" ) func Test_workaroundStatusUpdateError(t *testing.T) { initialPod := corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "name"}} updatedPod := corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "name"}, Status: corev1.PodStatus{Message: "updated"}} tests := []struct { name string err error wantErr error wantUpdate bool }{ { name: "no error", err: nil, wantErr: nil, wantUpdate: false, }, { name: "different error", err: errors.New("something else"), wantErr: errors.New("something else"), wantUpdate: false, }, { name: "validation error", err: apierrors.NewInvalid(initialPod.GroupVersionKind().GroupKind(), initialPod.Name, field.ErrorList{}), wantErr: nil, wantUpdate: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { client := k8s.WrappedFakeClient(&initialPod) err := workaroundStatusUpdateError(tt.err, client, &updatedPod) require.Equal(t, tt.wantErr, err) // get back the pod to check if it was updated var pod corev1.Pod require.NoError(t, client.Get(k8s.ExtractNamespacedName(&initialPod), &pod)) require.Equal(t, tt.wantUpdate, pod.Status.Message == "updated") }) } } func TestLowestVersionFromPods(t *testing.T) { versionLabel := "version-label" type args struct { currentVersion string pods []corev1.Pod versionLabel string } tests := []struct { name string args args want string }{ { name: "all pods have the same version: return it", args: args{ pods: []corev1.Pod{ {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{versionLabel: "7.7.0"}}}, {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{versionLabel: "7.7.0"}}}, }, currentVersion: "", versionLabel: versionLabel, }, want: "7.7.0", }, { name: "return the lowest running version", args: args{ pods: []corev1.Pod{ {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{versionLabel: "7.7.0"}}}, {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{versionLabel: "7.6.0"}}}, }, currentVersion: "", versionLabel: versionLabel, }, want: "7.6.0", }, { name: "cannot parse version from pods: return the current version", args: args{ pods: []corev1.Pod{ {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{versionLabel: "invalid"}}}, }, currentVersion: "7.7.0", versionLabel: versionLabel, }, want: "7.7.0", }, { name: "no pods: return the current version", args: args{ pods: []corev1.Pod{}, currentVersion: "7.7.0", versionLabel: versionLabel, }, want: "7.7.0", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := LowestVersionFromPods(tt.args.currentVersion, tt.args.pods, tt.args.versionLabel); got != tt.want { t.Errorf("LowestVersionFromPods() = %v, want %v", got, tt.want) } }) } } func TestDeploymentStatus(t *testing.T) { type args struct { current commonv1.DeploymentStatus dep appsv1.Deployment pods []corev1.Pod versionLabel string } tests := []struct { name string args args want commonv1.DeploymentStatus }{ { name: "happy path: set all status fields", args: args{ current: commonv1.DeploymentStatus{}, dep: appsv1.Deployment{ Status: appsv1.DeploymentStatus{ AvailableReplicas: 3, Conditions: []appsv1.DeploymentCondition{ { Type: appsv1.DeploymentAvailable, Status: corev1.ConditionTrue, }, }, }, }, pods: []corev1.Pod{ {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"version-label": "7.7.0"}}}, {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"version-label": "7.7.0"}}}, {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"version-label": "7.7.0"}}}, }, versionLabel: "version-label", }, want: commonv1.DeploymentStatus{ AvailableNodes: 3, Version: "7.7.0", Health: commonv1.GreenHealth, }, }, { name: "red health", args: args{ current: commonv1.DeploymentStatus{}, dep: appsv1.Deployment{ Status: appsv1.DeploymentStatus{ AvailableReplicas: 3, Conditions: []appsv1.DeploymentCondition{ { Type: appsv1.DeploymentAvailable, Status: corev1.ConditionFalse, }, }, }, }, pods: []corev1.Pod{ {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"version-label": "7.7.0"}}}, {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"version-label": "7.7.0"}}}, {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"version-label": "7.7.0"}}}, }, versionLabel: "version-label", }, want: commonv1.DeploymentStatus{ AvailableNodes: 3, Version: "7.7.0", Health: commonv1.RedHealth, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := DeploymentStatus(tt.args.current, tt.args.dep, tt.args.pods, tt.args.versionLabel); !reflect.DeepEqual(got, tt.want) { t.Errorf("DeploymentStatus() = %v, want %v", got, tt.want) } }) } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="de" xml:lang="de"> <head> <!-- * * Copyright 2008, Haiku. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * Humdinger <humdingerb@gmail.com> * Translators: * Humdinger * Matthias * taos * --> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta name="robots" content="all" /> <title>Media</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="../../Haiku-doc.css" /> </head> <body> <div id="banner"> <div><span>User guide</span></div> </div> <div class="nav"> <div class="inner"> <ul class="lang-menu"> <li class="now">Deutsch&nbsp;<span class="dropdown-caret">&#9660;</span></li> <li><a href="../../id/preferences/media.html">Bahasa Indonesia</a></li> <li><a href="../../ca/preferences/media.html">Català</a></li> <li><a href="../../en/preferences/media.html">English</a></li> <li><a href="../../es/preferences/media.html">Español</a></li> <li><a href="../../fr/preferences/media.html">Français</a></li> <li><a href="../../fur/preferences/media.html">Furlan</a></li> <li><a href="../../it/preferences/media.html">Italiano</a></li> <li><a href="../../hu/preferences/media.html">Magyar</a></li> <li><a href="../../pl/preferences/media.html">Polski</a></li> <li><a href="../../pt_PT/preferences/media.html">Português</a></li> <li><a href="../../pt_BR/preferences/media.html">Português (Brazil)</a></li> <li><a href="../../ro/preferences/media.html">Română</a></li> <li><a href="../../sk/preferences/media.html">Slovenčina</a></li> <li><a href="../../fi/preferences/media.html">Suomi</a></li> <li><a href="../../sv_SE/preferences/media.html">Svenska</a></li> <li><a href="../../tr/preferences/media.html">Türkçe</a></li> <li><a href="../../zh_CN/preferences/media.html"> 中文 [中文]</a></li> <li><a href="../../ru/preferences/media.html">Русский</a></li> <li><a href="../../uk/preferences/media.html">Українська</a></li> <li><a href="../../jp/preferences/media.html">日本語</a></li> </ul> <span>  «  <a href="locale.html">Locale</a>  ::  <a href="../preferences.html" class="uplink">Einstellungen</a>  ::  <a href="network.html">Netzwerk</a>  » </span></div> </div> <div id="content"> <div> <h2><img src="../../images/prefs-images/media-icon_64.png" alt="media-icon_64.png" width="64" height="64" /><acronym title="Media">Audio &amp; Video</acronym></h2> <table summary="quickinfo" border="0" cellspacing="0" cellpadding="2"> <tr><td>Deskbar:</td><td style="width:15px;"></td><td><span class="menu">Einstellungen</span></td></tr> <tr><td>Ort:</td><td></td><td><span class="path">/boot/system/preferences/Media</span></td></tr> <tr><td>Einstellungen:</td><td></td><td><span class="path">~/config/settings/Media/*</span><br /> <span class="path">~/config/settings/System Audio Mixer</span><br /> <span class="path">~/config/settings/MediaPrefs Settings</span> - Speichert die Position des Programmfensters.</td></tr> </table> <p>Dieses Thema wurde noch nicht beschrieben. Wer daran arbeiten möchte, meldet sich bitte auf der <a href="http://www.freelists.org/list/haiku-doc">Documentation Mailingliste</a>.</p> </div> </div> <div class="nav"> <div class="inner"><span>  «  <a href="locale.html">Locale</a>  ::  <a href="../preferences.html" class="uplink">Einstellungen</a>  ::  <a href="network.html">Netzwerk</a>  » </span></div> </div> </body> </html>
{ "pile_set_name": "Github" }
Chart.StackedBar.js =================== **This repository is no longer maintained since [Chart.js v2.0](https://github.com/chartjs/Chart.js) includes StackedBars per default. I highly recommend you to upgrade your project using Chart.js to the latest version of Chart.js. Thank you all for your support, your contributions, your questions, answers and hints!** ------ *StackedBar plugin for Chart.js* [chartjs.org](http://www.chartjs.org) ## Documentation You can find the documentation under `/docs` ## License Chart.StackedBar.js is available under the [MIT license](http://opensource.org/licenses/MIT). ## Bugs & issues When reporting bugs or issues, if you could include a link to a simple [jsbin](http://jsbin.com) or similar demonstrating the issue, that'd be really helpful.
{ "pile_set_name": "Github" }
class WopiController < ActionController::Base include WopiUtil skip_before_action :verify_authenticity_token before_action :load_vars, :authenticate_user_from_token! before_action :verify_proof! # Only used for checkfileinfo def file_get_endpoint check_file_info end def file_contents_get_endpoint # get_file response.headers['X-WOPI-ItemVersion'] = @asset.version response.body = @asset.file.download send_data response.body, disposition: 'inline', content_type: 'text/plain' end def post_file_endpoint override = request.headers['X-WOPI-Override'] case override when 'GET_LOCK' get_lock when 'PUT_RELATIVE' put_relative when 'LOCK' old_lock = request.headers['X-WOPI-OldLock'] if old_lock.nil? lock else unlock_and_relock end when 'UNLOCK' unlock when 'REFRESH_LOCK' refresh_lock when 'GET_SHARE_URL' render body: nil, status: :not_implemented else render body: nil, status: :not_found end end # Only used for putfile def file_contents_post_endpoint logger.warn 'WOPI: post_file_contents called' put_file end private def check_file_info asset_owner_id = @asset.id.to_s asset_owner_id = @asset.created_by_id.to_s if @asset.created_by_id msg = { BaseFileName: @asset.file_name, OwnerId: asset_owner_id, Size: @asset.file_size, UserId: @user.id.to_s, Version: @asset.version.to_s, SupportsExtendedLockLength: true, SupportsGetLock: true, SupportsLocks: true, SupportsUpdate: true, # Setting all users to business until we figure out # which should NOT be business LicenseCheckForEditIsEnabled: true, UserFriendlyName: @user.name, UserCanWrite: @can_write, UserCanNotWriteRelative: true, CloseUrl: @close_url, DownloadUrl: url_for(controller: 'assets', action: 'download', id: @asset.id, host: ENV['WOPI_USER_HOST']), HostEditUrl: url_for(controller: 'assets', action: 'edit', id: @asset.id, host: ENV['WOPI_USER_HOST']), HostViewUrl: url_for(controller: 'assets', action: 'view', id: @asset.id, host: ENV['WOPI_USER_HOST']), BreadcrumbBrandName: @breadcrumb_brand_name, BreadcrumbBrandUrl: @breadcrumb_brand_url, BreadcrumbFolderName: @breadcrumb_folder_name, BreadcrumbFolderUrl: @breadcrumb_folder_url } response.headers['X-WOPI-HostEndpoint'] = ENV['WOPI_ENDPOINT_URL'] response.headers['X-WOPI-MachineName'] = ENV['WOPI_ENDPOINT_URL'] response.headers['X-WOPI-ServerVersion'] = Scinote::Application::VERSION render json: msg end def put_relative render body: nil, status: :not_implemented end def lock lock = request.headers['X-WOPI-Lock'] logger.warn 'WOPI: lock; ' + lock.to_s return render body: nil, status: :not_found if lock.blank? @asset.with_lock do if @asset.locked? if @asset.lock == lock @asset.refresh_lock response.headers['X-WOPI-ItemVersion'] = @asset.version return render body: nil, status: :ok else response.headers['X-WOPI-Lock'] = @asset.lock return render body: nil, status: :conflict end else @asset.lock_asset(lock) response.headers['X-WOPI-ItemVersion'] = @asset.version return render body: nil, status: :ok end end end def unlock_and_relock logger.warn 'lock and relock' lock = request.headers['X-WOPI-Lock'] old_lock = request.headers['X-WOPI-OldLock'] return render body: nil, status: :bad_request if lock.blank? || old_lock.blank? @asset.with_lock do if @asset.locked? if @asset.lock == old_lock @asset.unlock @asset.lock_asset(lock) response.headers['X-WOPI-ItemVersion'] = @asset.version return render body: nil, status: :ok else response.headers['X-WOPI-Lock'] = @asset.lock return render body: nil, status: :conflict end else response.headers['X-WOPI-Lock'] = ' ' return render body: nil, status: :conflict end end end def unlock lock = request.headers['X-WOPI-Lock'] return render body: nil, status: :bad_request if lock.blank? @asset.with_lock do if @asset.locked? logger.warn "WOPI: current asset lock: #{@asset.lock}, unlocking lock #{lock}" if @asset.lock == lock @asset.unlock @asset.post_process_file # Space is already taken in put_file create_wopi_file_activity(@user, false) response.headers['X-WOPI-ItemVersion'] = @asset.version return render body: nil, status: :ok else response.headers['X-WOPI-Lock'] = @asset.lock return render body: nil, status: :conflict end else logger.warn 'WOPI: tried to unlock non-locked file' response.headers['X-WOPI-Lock'] = ' ' return render body: nil, status: :conflict end end end def refresh_lock lock = request.headers['X-WOPI-Lock'] return render body: nil, status: :bad_request if lock.nil? || lock.blank? @asset.with_lock do if @asset.locked? if @asset.lock == lock @asset.refresh_lock response.headers['X-WOPI-ItemVersion'] = @asset.version response.headers['X-WOPI-ItemVersion'] = @asset.version return render body: nil, status: :ok else response.headers['X-WOPI-Lock'] = @asset.lock return render body: nil, status: :conflict end else response.headers['X-WOPI-Lock'] = ' ' return render body: nil, status: :conflict end end end def get_lock @asset.with_lock do response.headers['X-WOPI-Lock'] = @asset.locked? ? @asset.lock : ' ' return render body: nil, status: :ok end end def put_file @asset.with_lock do lock = request.headers['X-WOPI-Lock'] if @asset.locked? if @asset.lock == lock logger.warn 'WOPI: replacing file' @team.release_space(@asset.estimated_size) @asset.update_contents(request.body) @asset.last_modified_by = @user @asset.save @team.take_space(@asset.estimated_size) @team.save @protocol&.update(updated_at: Time.now.utc) response.headers['X-WOPI-ItemVersion'] = @asset.version return render body: nil, status: :ok else logger.warn 'WOPI: wrong lock used to try and modify file' response.headers['X-WOPI-Lock'] = @asset.lock return render body: nil, status: :conflict end elsif !@asset.file_size.nil? && @asset.file_size.zero? logger.warn 'WOPI: initializing empty file' @team.release_space(@asset.estimated_size) @asset.update_contents(request.body) @asset.last_modified_by = @user @asset.save @team.save response.headers['X-WOPI-ItemVersion'] = @asset.version return render body: nil, status: :ok else logger.warn 'WOPI: trying to modify unlocked file' response.headers['X-WOPI-Lock'] = ' ' return render body: nil, status: :conflict end end end def load_vars @asset = Asset.find_by(id: params[:id]) if @asset.nil? render body: nil, status: :not_found else logger.warn "Found asset: #{@asset.id}" step_assoc = @asset.step result_assoc = @asset.result repository_cell_assoc = @asset.repository_cell @assoc = step_assoc unless step_assoc.nil? @assoc = result_assoc unless result_assoc.nil? @assoc = repository_cell_assoc unless repository_cell_assoc.nil? if @assoc.class == Step @protocol = @asset.step.protocol @team = @protocol.team elsif @assoc.class == Result @my_module = @assoc.my_module @team = @my_module.experiment.project.team elsif @assoc.class == RepositoryCell @repository = @assoc.repository_column.repository @team = @repository.team end end end def authenticate_user_from_token! wopi_token = params[:access_token] if wopi_token.nil? logger.warn 'WOPI: nil wopi token' return render body: nil, status: :unauthorized end @user = User.find_by_valid_wopi_token(wopi_token) if @user.nil? logger.warn 'WOPI: no user with this token found' return render body: nil, status: :unauthorized end logger.warn "WOPI: user found by token #{wopi_token} ID: #{@user.id}" # This is what we get for settings permission methods with # current_user @current_user = @user if @assoc.class == Step if @protocol.in_module? @can_read = can_read_protocol_in_module?(@protocol) @can_write = can_manage_protocol_in_module?(@protocol) @close_url = protocols_my_module_url(@protocol.my_module, only_path: false, host: ENV['WOPI_USER_HOST']) project = @protocol.my_module.experiment.project @breadcrumb_brand_name = project.name @breadcrumb_brand_url = project_url(project, only_path: false, host: ENV['WOPI_USER_HOST']) @breadcrumb_folder_name = @protocol.my_module.name else @can_read = can_read_protocol_in_repository?(@protocol) @can_write = can_manage_protocol_in_repository?(@protocol) @close_url = protocols_url(only_path: false, host: ENV['WOPI_USER_HOST']) @breadcrump_brand_name = 'Projects' @breadcrumb_brand_url = root_url(only_path: false, host: ENV['WOPI_USER_HOST']) @breadcrumb_folder_name = 'Protocol managament' end @breadcrumb_folder_url = @close_url elsif @assoc.class == Result @can_read = can_read_experiment?(@my_module.experiment) @can_write = can_manage_module?(@my_module) @close_url = results_my_module_url(@my_module, only_path: false, host: ENV['WOPI_USER_HOST']) @breadcrumb_brand_name = @my_module.experiment.project.name @breadcrumb_brand_url = project_url(@my_module.experiment.project, only_path: false, host: ENV['WOPI_USER_HOST']) @breadcrumb_folder_name = @my_module.name @breadcrumb_folder_url = @close_url elsif @assoc.class == RepositoryCell @can_read = can_read_repository?(@repository) @can_write = !@repository.is_a?(RepositorySnapshot) && can_edit_wopi_file_in_repository_rows? @close_url = repository_url(@repository, only_path: false, host: ENV['WOPI_USER_HOST']) @breadcrumb_brand_name = @team.name @breadcrumb_brand_url = @close_url @breadcrumb_folder_name = @assoc.repository_row.name @breadcrumb_folder_url = @close_url end return render body: nil, status: :not_found unless @can_read end def verify_proof! token = params[:access_token].encode('utf-8') timestamp = request.headers['X-WOPI-TimeStamp'].to_i signed_proof = request.headers['X-WOPI-Proof'] signed_proof_old = request.headers['X-WOPI-ProofOld'] url = request.original_url.upcase.encode('utf-8') if convert_to_unix_timestamp(timestamp) + 20.minutes >= Time.now if current_wopi_discovery.verify_proof(token, timestamp, signed_proof, signed_proof_old, url) logger.warn 'WOPI: proof verification: successful' else logger.warn 'WOPI: proof verification: not verified' render body: nil, status: :internal_server_error end else logger.warn 'WOPI: proof verification: timestamp too old; ' + timestamp.to_s render body: nil, status: :internal_server_error end rescue StandardError => e logger.warn 'WOPI: proof verification: failed; ' + e.message render body: nil, status: :internal_server_error end def can_edit_wopi_file_in_repository_rows? can_manage_repository_rows?(@repository) end end
{ "pile_set_name": "Github" }
using System.Linq.Dynamic.Core.Tests.Helpers.Models; using Xunit; namespace System.Linq.Dynamic.Core.Tests { public partial class QueryableTests { [Fact] public void ToArray_Dynamic() { // Arrange var testList = User.GenerateSampleModels(51); IQueryable testListQry = testList.AsQueryable(); // Act var realResult = testList.OrderBy(x => x.Roles.ToArray().First().Name).Select(x => x.Id); var testResult = testListQry.OrderBy("Roles.ToArray().First().Name").Select("Id"); // Assert Assert.Equal(realResult.ToArray(), testResult.ToDynamicArray().Cast<Guid>()); } } }
{ "pile_set_name": "Github" }
import Token from './Token' export default Token
{ "pile_set_name": "Github" }
0.022055 0.001444 0.003347 0.000051 0.000711 0.002840 0.000770 0.031995 0.000032 0.000672 0.002418 0.041191 0.003118 0.000651 0.030098 0.036305 0.080971 0.000030 0.000603 0.001690 0.024504 0.013009 0.010273 0.002481 0.000575 0.025072 0.019257 0.055261 0.008844 0.014795 0.000039 0.000795 0.001893 0.031869 0.016648 0.011109 0.001187 0.000635 0.025526 0.019946 0.064067 0.009874 0.014988 0.002384 0.037371 0.012217 0.007732 0.001247 0.038946 0.087636 0.009617 0.014871 0.013620 0.009903 0.000913 0.007686 0.015462 0.001307 0.105452 0.294888 0.005786 0.055177 0.000135 0.005758 0.000921 0.000204 0.006664 0.000202 0.000271 0.001183 0.014465 0.052909 0.008934 0.011875 0.026340 0.030088 0.000140 0.004842 0.003212 0.006004 0.008675 0.003571 0.000903 0.000186 0.005190 0.002717 0.005476 0.012716 0.004977 0.000197 0.008555 0.003867 0.003845 0.004704 0.002494 0.009954 0.000310 0.013952 0.005917 0.007863 0.009035 0.003952 0.001125 0.026881 0.010195 0.013223 0.055195 0.016455 0.035622 0.004156 0.005261 0.003445 0.002769 0.009789 0.007143 0.004220 0.047820 0.107649 0.263938 0.005710 0.000880 0.000216 0.000364 0.055369 0.011386 0.015804 0.000144 0.006765 0.005756 0.010733 0.001045 0.000247 0.008565 0.004842 0.012280 0.000190 0.000268 0.001274 0.019656 0.005781 0.010827 0.050470 0.011600 0.016561 0.022519 0.027590 0.003143 0.004496 0.000181 0.000234 0.001408 0.026143 0.012271 0.018232 0.054897 0.007771 0.007584 0.013915 0.022003 0.003258 0.004761 0.006957 0.005963 0.005497 0.002340 0.008161 0.010383 0.010917 0.009048 0.003349 0.011017 0.016004 0.049207 0.003288 0.004280 0.008931 0.093584
{ "pile_set_name": "Github" }
/* * Copyright (c) 2019 Trail of Bits, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <memory> #include <llvm/IRReader/IRReader.h> #include "rellic/BC/Version.h" #if LLVM_VERSION_NUMBER < LLVM_VERSION(3, 6) namespace llvm { class Module; template <typename ...Args> inline static std::unique_ptr<Module> parseIRFile(Args&... args) { return std::unique_ptr<Module>(ParseIRFile(args...)); } } // namespace llvm #endif
{ "pile_set_name": "Github" }
/* * Copyright (C) 2019 Intel Corporation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <list.h> #include <per_cpu.h> #include <schedule.h> #define CONFIG_SLICE_MS 10UL struct sched_iorr_data { /* keep list as the first item */ struct list_head list; uint64_t slice_cycles; uint64_t last_cycles; int64_t left_cycles; }; /* * @pre obj != NULL * @pre obj->data != NULL */ bool is_inqueue(struct thread_object *obj) { struct sched_iorr_data *data = (struct sched_iorr_data *)obj->data; return !list_empty(&data->list); } /* * @pre obj != NULL * @pre obj->data != NULL * @pre obj->sched_ctl != NULL * @pre obj->sched_ctl->priv != NULL */ void runqueue_add_head(struct thread_object *obj) { struct sched_iorr_control *iorr_ctl = (struct sched_iorr_control *)obj->sched_ctl->priv; struct sched_iorr_data *data = (struct sched_iorr_data *)obj->data; if (!is_inqueue(obj)) { list_add(&data->list, &iorr_ctl->runqueue); } } /* * @pre obj != NULL * @pre obj->data != NULL * @pre obj->sched_ctl != NULL * @pre obj->sched_ctl->priv != NULL */ void runqueue_add_tail(struct thread_object *obj) { struct sched_iorr_control *iorr_ctl = (struct sched_iorr_control *)obj->sched_ctl->priv; struct sched_iorr_data *data = (struct sched_iorr_data *)obj->data; if (!is_inqueue(obj)) { list_add_tail(&data->list, &iorr_ctl->runqueue); } } /* * @pre obj != NULL * @pre obj->data != NULL */ void runqueue_remove(struct thread_object *obj) { struct sched_iorr_data *data = (struct sched_iorr_data *)obj->data; list_del_init(&data->list); } static void sched_tick_handler(void *param) { struct sched_control *ctl = (struct sched_control *)param; struct sched_iorr_control *iorr_ctl = (struct sched_iorr_control *)ctl->priv; struct sched_iorr_data *data; struct thread_object *current; uint16_t pcpu_id = get_pcpu_id(); uint64_t now = rdtsc(); uint64_t rflags; obtain_schedule_lock(pcpu_id, &rflags); current = ctl->curr_obj; /* If no vCPU start scheduling, ignore this tick */ if (current != NULL ) { if (!(is_idle_thread(current) && list_empty(&iorr_ctl->runqueue))) { data = (struct sched_iorr_data *)current->data; /* consume the left_cycles of current thread_object if it is not idle */ if (!is_idle_thread(current)) { data->left_cycles -= now - data->last_cycles; data->last_cycles = now; } /* make reschedule request if current ran out of its cycles */ if (is_idle_thread(current) || data->left_cycles <= 0) { make_reschedule_request(pcpu_id, DEL_MODE_IPI); } } } release_schedule_lock(pcpu_id, rflags); } /* * @pre ctl->pcpu_id == get_pcpu_id() */ int sched_iorr_init(struct sched_control *ctl) { struct sched_iorr_control *iorr_ctl = &per_cpu(sched_iorr_ctl, ctl->pcpu_id); uint64_t tick_period = CYCLES_PER_MS; int ret = 0; ASSERT(get_pcpu_id() == ctl->pcpu_id, "Init scheduler on wrong CPU!"); ctl->priv = iorr_ctl; INIT_LIST_HEAD(&iorr_ctl->runqueue); /* The tick_timer is periodically */ initialize_timer(&iorr_ctl->tick_timer, sched_tick_handler, ctl, rdtsc() + tick_period, TICK_MODE_PERIODIC, tick_period); if (add_timer(&iorr_ctl->tick_timer) < 0) { pr_err("Failed to add schedule tick timer!"); ret = -1; } return ret; } void sched_iorr_deinit(struct sched_control *ctl) { struct sched_iorr_control *iorr_ctl = (struct sched_iorr_control *)ctl->priv; del_timer(&iorr_ctl->tick_timer); } void sched_iorr_init_data(struct thread_object *obj) { struct sched_iorr_data *data; data = (struct sched_iorr_data *)obj->data; INIT_LIST_HEAD(&data->list); data->left_cycles = data->slice_cycles = CONFIG_SLICE_MS * CYCLES_PER_MS; } static struct thread_object *sched_iorr_pick_next(struct sched_control *ctl) { struct sched_iorr_control *iorr_ctl = (struct sched_iorr_control *)ctl->priv; struct thread_object *next = NULL; struct thread_object *current = NULL; struct sched_iorr_data *data; uint64_t now = rdtsc(); current = ctl->curr_obj; data = (struct sched_iorr_data *)current->data; /* Ignore the idle object, inactive objects */ if (!is_idle_thread(current) && is_inqueue(current)) { data->left_cycles -= now - data->last_cycles; if (data->left_cycles <= 0) { /* replenish thread_object with slice_cycles */ data->left_cycles += data->slice_cycles; } /* move the thread_object to tail */ runqueue_remove(current); runqueue_add_tail(current); } /* * Pick the next runnable sched object * 1) get the first item in runqueue firstly * 2) if object picked has no time_cycles, replenish it pick this one * 3) At least take one idle sched object if we have no runnable one after step 1) and 2) */ if (!list_empty(&iorr_ctl->runqueue)) { next = get_first_item(&iorr_ctl->runqueue, struct thread_object, data); data = (struct sched_iorr_data *)next->data; data->last_cycles = now; while (data->left_cycles <= 0) { data->left_cycles += data->slice_cycles; } } else { next = &get_cpu_var(idle); } return next; } static void sched_iorr_sleep(struct thread_object *obj) { runqueue_remove(obj); } static void sched_iorr_wake(struct thread_object *obj) { runqueue_add_head(obj); } struct acrn_scheduler sched_iorr = { .name = "sched_iorr", .init = sched_iorr_init, .init_data = sched_iorr_init_data, .pick_next = sched_iorr_pick_next, .sleep = sched_iorr_sleep, .wake = sched_iorr_wake, .deinit = sched_iorr_deinit, };
{ "pile_set_name": "Github" }
#pragma checksum "C:\Users\panag\Desktop\anyplace\windows\AnyPlace\MyLocationPoiControl.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "2CE6A5D7B0EE237CE2A0E3E7B2EEA586" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Resources; using System.Windows.Shapes; using System.Windows.Threading; namespace AnyPlace { public partial class MyLocationPoiControl : System.Windows.Controls.UserControl { internal System.Windows.Controls.Grid grd_loc; internal System.Windows.Controls.TextBlock txt_direction; internal System.Windows.Controls.Button btn_source; private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/AnyPlace;component/MyLocationPoiControl.xaml", System.UriKind.Relative)); this.grd_loc = ((System.Windows.Controls.Grid)(this.FindName("grd_loc"))); this.txt_direction = ((System.Windows.Controls.TextBlock)(this.FindName("txt_direction"))); this.btn_source = ((System.Windows.Controls.Button)(this.FindName("btn_source"))); } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/.idea/react-demo01.iml" filepath="$PROJECT_DIR$/.idea/react-demo01.iml" /> </modules> </component> </project>
{ "pile_set_name": "Github" }
/* * This file is part of PowerDNS or dnsdist. * Copyright -- PowerDNS.COM B.V. and its contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * In addition, for the avoidance of any doubt, permission is granted to * link this program with OpenSSL and to (re)distribute the binaries * produced as the result of such linking. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "packetcache.hh" #include <cstdio> #include <signal.h> #include <cstring> #include <cstdlib> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <iostream> #include <string> #include <sys/stat.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <pthread.h> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h> #include <fstream> #include <boost/algorithm/string.hpp> #ifdef HAVE_LIBSODIUM #include <sodium.h> #endif #include "opensslsigners.hh" #include "dns.hh" #include "dnsbackend.hh" #include "ueberbackend.hh" #include "dnspacket.hh" #include "nameserver.hh" #include "distributor.hh" #include "logger.hh" #include "arguments.hh" #include "packethandler.hh" #include "statbag.hh" #include "tcpreceiver.hh" #include "misc.hh" #include "dynlistener.hh" #include "dynhandler.hh" #include "communicator.hh" #include "dnsproxy.hh" #include "utility.hh" #include "common_startup.hh" #include "dnsrecords.hh" #include "version.hh" #ifdef HAVE_LUA_RECORDS #include "minicurl.hh" #endif /* HAVE_LUA_RECORDS */ time_t s_starttime; string s_programname="pdns"; // used in packethandler.cc const char *funnytext= "*****************************************************************************\n"\ "Ok, you just ran pdns_server through 'strings' hoping to find funny messages.\n"\ "Well, you found one. \n"\ "Two ions are flying through their particle accelerator, says the one to the\n" "other 'I think I've lost an electron!' \n"\ "So the other one says, 'Are you sure?'. 'YEAH! I'M POSITIVE!'\n"\ " the pdns crew - pdns@powerdns.com\n" "*****************************************************************************\n"; // start (sys)logging /** \file receiver.cc \brief The main loop of powerdns This file is where it all happens - main is here, as are the two pivotal threads qthread() and athread() */ static void daemonize(void) { if(fork()) exit(0); // bye bye setsid(); int i=open("/dev/null",O_RDWR); /* open stdin */ if(i < 0) g_log<<Logger::Critical<<"Unable to open /dev/null: "<<stringerror()<<endl; else { dup2(i,0); /* stdin */ dup2(i,1); /* stderr */ dup2(i,2); /* stderr */ close(i); } } static int cpid; static void takedown(int i) { if(cpid) { g_log<<Logger::Error<<"Guardian is killed, taking down children with us"<<endl; kill(cpid,SIGKILL); exit(0); } } static void writePid(void) { if(!::arg().mustDo("write-pid")) return; string fname=::arg()["socket-dir"]; if (::arg()["socket-dir"].empty()) { if (::arg()["chroot"].empty()) fname = std::string(LOCALSTATEDIR) + "/pdns"; else fname = ::arg()["chroot"] + "/"; } else if (!::arg()["socket-dir"].empty() && !::arg()["chroot"].empty()) { fname = ::arg()["chroot"] + ::arg()["socket-dir"]; } fname += + "/" + s_programname + ".pid"; ofstream of(fname.c_str()); if(of) of<<getpid()<<endl; else g_log<<Logger::Error<<"Writing pid for "<<getpid()<<" to "<<fname<<" failed: "<<stringerror()<<endl; } int g_fd1[2], g_fd2[2]; FILE *g_fp; std::mutex g_guardian_lock; // The next two methods are not in dynhandler.cc because they use a few items declared in this file. static string DLCycleHandler(const vector<string>&parts, pid_t ppid) { kill(cpid, SIGKILL); // why? kill(cpid, SIGKILL); // why? sleep(1); return "ok"; } static string DLRestHandler(const vector<string>&parts, pid_t ppid) { string line; for(vector<string>::const_iterator i=parts.begin();i!=parts.end();++i) { if(i!=parts.begin()) line.append(1,' '); line.append(*i); } line.append(1,'\n'); std::lock_guard<std::mutex> l(g_guardian_lock); try { writen2(g_fd1[1],line.c_str(),line.size()+1); } catch(PDNSException &ae) { return "Error communicating with instance: "+ae.reason; } char mesg[512]; string response; while(fgets(mesg,sizeof(mesg),g_fp)) { if(*mesg=='\0') break; response+=mesg; } boost::trim_right(response); return response; } static int guardian(int argc, char **argv) { if(isGuarded(argv)) return 0; int infd=0, outfd=1; DynListener dlg(s_programname); dlg.registerFunc("QUIT",&DLQuitHandler, "quit daemon"); dlg.registerFunc("CYCLE",&DLCycleHandler, "restart instance"); dlg.registerFunc("PING",&DLPingHandler, "ping guardian"); dlg.registerFunc("STATUS",&DLStatusHandler, "get instance status from guardian"); dlg.registerRestFunc(&DLRestHandler); dlg.go(); string progname=argv[0]; bool first=true; cpid=0; g_guardian_lock.lock(); for(;;) { int pid; setStatus("Launching child"); if(pipe(g_fd1)<0 || pipe(g_fd2)<0) { g_log<<Logger::Critical<<"Unable to open pipe for coprocess: "<<stringerror()<<endl; exit(1); } if(!(g_fp=fdopen(g_fd2[0],"r"))) { g_log<<Logger::Critical<<"Unable to associate a file pointer with pipe: "<<stringerror()<<endl; exit(1); } setbuf(g_fp,0); // no buffering please, confuses select if(!(pid=fork())) { // child signal(SIGTERM, SIG_DFL); signal(SIGHUP, SIG_DFL); signal(SIGUSR1, SIG_DFL); signal(SIGUSR2, SIG_DFL); char **const newargv=new char*[argc+2]; int n; if(::arg()["config-name"]!="") { progname+="-"+::arg()["config-name"]; g_log<<Logger::Error<<"Virtual configuration name: "<<::arg()["config-name"]<<endl; } newargv[0]=strdup(const_cast<char *>((progname+"-instance").c_str())); for(n=1;n<argc;n++) { newargv[n]=argv[n]; } newargv[n]=0; g_log<<Logger::Error<<"Guardian is launching an instance"<<endl; close(g_fd1[1]); fclose(g_fp); // this closes g_fd2[0] for us if(g_fd1[0]!= infd) { dup2(g_fd1[0], infd); close(g_fd1[0]); } if(g_fd2[1]!= outfd) { dup2(g_fd2[1], outfd); close(g_fd2[1]); } if(execvp(argv[0], newargv)<0) { g_log<<Logger::Error<<"Unable to execvp '"<<argv[0]<<"': "<<stringerror()<<endl; char **p=newargv; while(*p) g_log<<Logger::Error<<*p++<<endl; exit(1); } g_log<<Logger::Error<<"execvp returned!!"<<endl; // never reached } else if(pid>0) { // parent close(g_fd1[0]); close(g_fd2[1]); if(first) { first=false; signal(SIGTERM, takedown); signal(SIGHUP, SIG_IGN); signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); writePid(); } g_guardian_lock.unlock(); int status; cpid=pid; for(;;) { int ret=waitpid(pid,&status,WNOHANG); if(ret<0) { g_log<<Logger::Error<<"In guardian loop, waitpid returned error: "<<stringerror()<<endl; g_log<<Logger::Error<<"Dying"<<endl; exit(1); } else if(ret) // something exited break; else { // child is alive // execute some kind of ping here if(DLQuitPlease()) takedown(1); // needs a parameter.. setStatus("Child running on pid "+itoa(pid)); sleep(1); } } g_guardian_lock.lock(); close(g_fd1[1]); fclose(g_fp); g_fp=0; if(WIFEXITED(status)) { int ret=WEXITSTATUS(status); if(ret==99) { g_log<<Logger::Error<<"Child requested a stop, exiting"<<endl; exit(1); } setStatus("Child died with code "+itoa(ret)); g_log<<Logger::Error<<"Our pdns instance exited with code "<<ret<<", respawning"<<endl; sleep(1); continue; } if(WIFSIGNALED(status)) { int sig=WTERMSIG(status); setStatus("Child died because of signal "+itoa(sig)); g_log<<Logger::Error<<"Our pdns instance ("<<pid<<") exited after signal "<<sig<<endl; #ifdef WCOREDUMP if(WCOREDUMP(status)) g_log<<Logger::Error<<"Dumped core"<<endl; #endif g_log<<Logger::Error<<"Respawning"<<endl; sleep(1); continue; } g_log<<Logger::Error<<"No clue what happened! Respawning"<<endl; } else { g_log<<Logger::Error<<"Unable to fork: "<<stringerror()<<endl; exit(1); } } } #if defined(__GLIBC__) && !defined(__UCLIBC__) #include <execinfo.h> static void tbhandler(int num) { g_log<<Logger::Critical<<"Got a signal "<<num<<", attempting to print trace: "<<endl; void *array[20]; //only care about last 17 functions (3 taken with tracing support) size_t size; char **strings; size_t i; size = backtrace (array, 20); strings = backtrace_symbols (array, size); //Need -rdynamic gcc (linker) flag for this to work for (i = 0; i < size; i++) //skip useless functions g_log<<Logger::Error<<strings[i]<<endl; signal(SIGABRT, SIG_DFL); abort();//hopefully will give core } #endif //! The main function of pdns, the pdns process int main(int argc, char **argv) { versionSetProduct(ProductAuthoritative); reportAllTypes(); // init MOADNSParser s_programname="pdns"; s_starttime=time(0); #if defined(__GLIBC__) && !defined(__UCLIBC__) signal(SIGSEGV,tbhandler); signal(SIGFPE,tbhandler); signal(SIGABRT,tbhandler); signal(SIGILL,tbhandler); #endif std::ios_base::sync_with_stdio(false); g_log.toConsole(Logger::Warning); try { declareArguments(); ::arg().laxParse(argc,argv); // do a lax parse if(::arg().mustDo("version")) { showProductVersion(); showBuildConfiguration(); exit(99); } if(::arg()["config-name"]!="") s_programname+="-"+::arg()["config-name"]; g_log.setName(s_programname); string configname=::arg()["config-dir"]+"/"+s_programname+".conf"; cleanSlashes(configname); if(::arg()["config"] != "default" && !::arg().mustDo("no-config")) // "config" == print a configuration file ::arg().laxFile(configname.c_str()); ::arg().laxParse(argc,argv); // reparse so the commandline still wins if(!::arg()["logging-facility"].empty()) { int val=logFacilityToLOG(::arg().asNum("logging-facility") ); if(val >= 0) g_log.setFacility(val); else g_log<<Logger::Error<<"Unknown logging facility "<<::arg().asNum("logging-facility") <<endl; } g_log.setLoglevel((Logger::Urgency)(::arg().asNum("loglevel"))); g_log.disableSyslog(::arg().mustDo("disable-syslog")); g_log.setTimestamps(::arg().mustDo("log-timestamp")); g_log.toConsole((Logger::Urgency)(::arg().asNum("loglevel"))); if(::arg().mustDo("help") || ::arg().mustDo("config")) { ::arg().set("daemon")="no"; ::arg().set("guardian")="no"; } if(::arg().mustDo("guardian") && !isGuarded(argv)) { if(::arg().mustDo("daemon")) { g_log.toConsole(Logger::Critical); daemonize(); } guardian(argc, argv); // never get here, guardian will reinvoke process cerr<<"Um, we did get here!"<<endl; } // we really need to do work - either standalone or as an instance #if defined(__GLIBC__) && !defined(__UCLIBC__) if(!::arg().mustDo("traceback-handler")) { g_log<<Logger::Warning<<"Disabling traceback handler"<<endl; signal(SIGSEGV,SIG_DFL); signal(SIGFPE,SIG_DFL); signal(SIGABRT,SIG_DFL); signal(SIGILL,SIG_DFL); } #endif #ifdef HAVE_LIBSODIUM if (sodium_init() == -1) { cerr<<"Unable to initialize sodium crypto library"<<endl; exit(99); } #endif openssl_thread_setup(); openssl_seed(); /* setup rng */ dns_random_init(); #ifdef HAVE_LUA_RECORDS MiniCurl::init(); #endif /* HAVE_LUA_RECORDS */ if(!::arg()["load-modules"].empty()) { vector<string> modules; stringtok(modules,::arg()["load-modules"], ", "); if (!UeberBackend::loadModules(modules, ::arg()["module-dir"])) { exit(1); } } BackendMakers().launch(::arg()["launch"]); // vrooooom! if(!::arg().getCommands().empty()) { cerr<<"Fatal: non-option"; if (::arg().getCommands().size() > 1) { cerr<<"s"; } cerr<<" ("; bool first = true; for (const auto& c : ::arg().getCommands()) { if (!first) { cerr<<", "; } first = false; cerr<<c; } cerr<<") on the command line, perhaps a '--setting=123' statement missed the '='?"<<endl; exit(99); } if(::arg().mustDo("help")) { cout<<"syntax:"<<endl<<endl; cout<<::arg().helpstring(::arg()["help"])<<endl; exit(0); } if(::arg().mustDo("config")) { string config = ::arg()["config"]; if (config == "default") { cout<<::arg().configstring(false, true); } else if (config == "diff") { cout<<::arg().configstring(true, false); } else if (config == "check") { try { if(!::arg().mustDo("no-config")) ::arg().file(configname.c_str()); ::arg().parse(argc,argv); exit(0); } catch(const ArgException &A) { cerr<<"Fatal error: "<<A.reason<<endl; exit(1); } } else { cout<<::arg().configstring(true, true); } exit(0); } if(::arg().mustDo("list-modules")) { auto modules = BackendMakers().getModules(); cout<<"Modules available:"<<endl; for(const auto& m : modules) cout<< m <<endl; _exit(99); } if(!::arg().asNum("local-port")) { g_log<<Logger::Error<<"Unable to launch, binding to no port or port 0 makes no sense"<<endl; exit(99); // this isn't going to fix itself either } if(!BackendMakers().numLauncheable()) { g_log<<Logger::Error<<"Unable to launch, no backends configured for querying"<<endl; exit(99); // this isn't going to fix itself either } if(::arg().mustDo("daemon")) { g_log.toConsole(Logger::None); if(!isGuarded(argv)) daemonize(); } if(isGuarded(argv)) { g_log<<Logger::Warning<<"This is a guarded instance of pdns"<<endl; dl=make_unique<DynListener>(); // listens on stdin } else { g_log<<Logger::Warning<<"This is a standalone pdns"<<endl; if(::arg().mustDo("control-console")) dl=make_unique<DynListener>(); else dl=std::unique_ptr<DynListener>(new DynListener(s_programname)); writePid(); } DynListener::registerFunc("SHOW",&DLShowHandler, "show a specific statistic or * to get a list", "<statistic>"); DynListener::registerFunc("RPING",&DLPingHandler, "ping instance"); DynListener::registerFunc("QUIT",&DLRQuitHandler, "quit daemon"); DynListener::registerFunc("UPTIME",&DLUptimeHandler, "get instance uptime"); DynListener::registerFunc("NOTIFY-HOST",&DLNotifyHostHandler, "notify host for specific domain", "<domain> <host>"); DynListener::registerFunc("NOTIFY",&DLNotifyHandler, "queue a notification", "<domain>"); DynListener::registerFunc("RELOAD",&DLReloadHandler, "reload all zones"); DynListener::registerFunc("REDISCOVER",&DLRediscoverHandler, "discover any new zones"); DynListener::registerFunc("VERSION",&DLVersionHandler, "get instance version"); DynListener::registerFunc("PURGE",&DLPurgeHandler, "purge entries from packet cache", "[<record>]"); DynListener::registerFunc("CCOUNTS",&DLCCHandler, "get cache statistics"); DynListener::registerFunc("QTYPES", &DLQTypesHandler, "get QType statistics"); DynListener::registerFunc("RESPSIZES", &DLRSizesHandler, "get histogram of response sizes"); DynListener::registerFunc("REMOTES", &DLRemotesHandler, "get top remotes"); DynListener::registerFunc("SET",&DLSettingsHandler, "set config variables", "<var> <value>"); DynListener::registerFunc("RETRIEVE",&DLNotifyRetrieveHandler, "retrieve slave domain", "<domain> [<ip>]"); DynListener::registerFunc("CURRENT-CONFIG",&DLCurrentConfigHandler, "retrieve the current configuration", "[diff]"); DynListener::registerFunc("LIST-ZONES",&DLListZones, "show list of zones", "[master|slave|native]"); DynListener::registerFunc("TOKEN-LOGIN", &DLTokenLogin, "Login to a PKCS#11 token", "<module> <slot> <pin>"); if(!::arg()["tcp-control-address"].empty()) { DynListener* dlTCP=new DynListener(ComboAddress(::arg()["tcp-control-address"], ::arg().asNum("tcp-control-port"))); dlTCP->go(); } // reparse, with error checking if(!::arg().mustDo("no-config")) ::arg().file(configname.c_str()); ::arg().parse(argc,argv); if(::arg()["server-id"].empty()) { char tmp[128]; if(gethostname(tmp, sizeof(tmp)-1) == 0) { ::arg().set("server-id")=tmp; } else { g_log<<Logger::Warning<<"Unable to get the hostname, NSID and id.server values will be empty: "<<stringerror()<<endl; } } UeberBackend::go(); N=std::make_shared<UDPNameserver>(); // this fails when we are not root, throws exception g_udpReceivers.push_back(N); size_t rthreads = ::arg().asNum("receiver-threads", 1); if (rthreads > 1 && N->canReusePort()) { g_udpReceivers.resize(rthreads); for (size_t idx = 1; idx < rthreads; idx++) { try { g_udpReceivers[idx] = std::make_shared<UDPNameserver>(true); } catch(const PDNSException& e) { g_log<<Logger::Error<<"Unable to reuse port, falling back to original bind"<<endl; break; } } } TN = make_unique<TCPNameserver>(); } catch(const ArgException &A) { g_log<<Logger::Error<<"Fatal error: "<<A.reason<<endl; exit(1); } try { declareStats(); } catch(PDNSException &PE) { g_log<<Logger::Error<<"Exiting because: "<<PE.reason<<endl; exit(1); } S.blacklist("special-memory-usage"); DLOG(g_log<<Logger::Warning<<"Verbose logging in effect"<<endl); showProductVersion(); try { mainthread(); } catch(PDNSException &AE) { if(!::arg().mustDo("daemon")) cerr<<"Exiting because: "<<AE.reason<<endl; g_log<<Logger::Error<<"Exiting because: "<<AE.reason<<endl; } catch(std::exception &e) { if(!::arg().mustDo("daemon")) cerr<<"Exiting because of STL error: "<<e.what()<<endl; g_log<<Logger::Error<<"Exiting because of STL error: "<<e.what()<<endl; } catch(...) { cerr<<"Uncaught exception of unknown type - sorry"<<endl; } exit(1); }
{ "pile_set_name": "Github" }
// Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Views.Module.Component.Help; import java.net.URL; import com.google.security.zynamics.binnavi.Help.CHelpFunctions; import com.google.security.zynamics.binnavi.Help.IHelpInformation; /** * Context-sensitive help information for tables that show function properties. */ public final class CFunctionViewsTableHelp implements IHelpInformation { @Override public String getText() { return "This table shows functions and their properties.\n\nAddress: Start address of the function\nName: Name of the function\nDescription: Description of the function\nModule: Name of the module this function belongs to\nForwarded to: Imported function this function is forwarded to\nBasic Blocks: Number of basic blocks in the function\nEdges: Number of edges in the view\nIn: Number of functions that call this function\nOut: Number of functions called by this function"; } @Override public URL getUrl() { return CHelpFunctions.urlify(CHelpFunctions.MAIN_WINDOW_FILE); } }
{ "pile_set_name": "Github" }
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SPU_GATHERING_COLLISION_TASK_H #define SPU_GATHERING_COLLISION_TASK_H #include "../PlatformDefinitions.h" //#define DEBUG_SPU_COLLISION_DETECTION 1 ///Task Description for SPU collision detection struct SpuGatherAndProcessPairsTaskDesc { ppu_address_t m_inPairPtr;//m_pairArrayPtr; //mutex variable uint32_t m_someMutexVariableInMainMemory; ppu_address_t m_dispatcher; uint32_t numOnLastPage; uint16_t numPages; uint16_t taskId; bool m_useEpa; struct CollisionTask_LocalStoreMemory* m_lsMemory; } #if defined(__CELLOS_LV2__) || defined(USE_LIBSPE2) __attribute__ ((aligned (128))) #endif ; void processCollisionTask(void* userPtr, void* lsMemory); void* createCollisionLocalStoreMemory(); void deleteCollisionLocalStoreMemory(); #if defined(USE_LIBSPE2) && defined(__SPU__) #include "../SpuLibspe2Support.h" #include <spu_intrinsics.h> #include <spu_mfcio.h> #include <SpuFakeDma.h> //#define DEBUG_LIBSPE2_SPU_TASK int main(unsigned long long speid, addr64 argp, addr64 envp) { printf("SPU: hello \n"); ATTRIBUTE_ALIGNED128(btSpuStatus status); ATTRIBUTE_ALIGNED16( SpuGatherAndProcessPairsTaskDesc taskDesc ) ; unsigned int received_message = Spu_Mailbox_Event_Nothing; bool shutdown = false; cellDmaGet(&status, argp.ull, sizeof(btSpuStatus), DMA_TAG(3), 0, 0); cellDmaWaitTagStatusAll(DMA_MASK(3)); status.m_status = Spu_Status_Free; status.m_lsMemory.p = createCollisionLocalStoreMemory(); cellDmaLargePut(&status, argp.ull, sizeof(btSpuStatus), DMA_TAG(3), 0, 0); cellDmaWaitTagStatusAll(DMA_MASK(3)); while ( btLikely( !shutdown ) ) { received_message = spu_read_in_mbox(); if( btLikely( received_message == Spu_Mailbox_Event_Task )) { #ifdef DEBUG_LIBSPE2_SPU_TASK printf("SPU: received Spu_Mailbox_Event_Task\n"); #endif //DEBUG_LIBSPE2_SPU_TASK // refresh the status cellDmaGet(&status, argp.ull, sizeof(btSpuStatus), DMA_TAG(3), 0, 0); cellDmaWaitTagStatusAll(DMA_MASK(3)); btAssert(status.m_status==Spu_Status_Occupied); cellDmaGet(&taskDesc, status.m_taskDesc.p, sizeof(SpuGatherAndProcessPairsTaskDesc), DMA_TAG(3), 0, 0); cellDmaWaitTagStatusAll(DMA_MASK(3)); #ifdef DEBUG_LIBSPE2_SPU_TASK printf("SPU:processCollisionTask\n"); #endif //DEBUG_LIBSPE2_SPU_TASK processCollisionTask((void*)&taskDesc, taskDesc.m_lsMemory); #ifdef DEBUG_LIBSPE2_SPU_TASK printf("SPU:finished processCollisionTask\n"); #endif //DEBUG_LIBSPE2_SPU_TASK } else { #ifdef DEBUG_LIBSPE2_SPU_TASK printf("SPU: received ShutDown\n"); #endif //DEBUG_LIBSPE2_SPU_TASK if( btLikely( received_message == Spu_Mailbox_Event_Shutdown ) ) { shutdown = true; } else { //printf("SPU - Sth. recieved\n"); } } // set to status free and wait for next task status.m_status = Spu_Status_Free; cellDmaLargePut(&status, argp.ull, sizeof(btSpuStatus), DMA_TAG(3), 0, 0); cellDmaWaitTagStatusAll(DMA_MASK(3)); } printf("SPU: shutdown\n"); return 0; } #endif // USE_LIBSPE2 #endif //SPU_GATHERING_COLLISION_TASK_H
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Query.InternalTrees { using System.Data.Entity.Core.Metadata.Edm; using System.Diagnostics; // <summary> // Represents an arbitrary nest operation - can be used anywhere // </summary> internal sealed class CollectOp : ScalarOp { #region constructors internal CollectOp(TypeUsage type) : base(OpType.Collect, type) { } private CollectOp() : base(OpType.Collect) { } #endregion #region public methods // <summary> // Pattern for use in transformation rules // </summary> internal static readonly CollectOp Pattern = new CollectOp(); // <summary> // 1 child - instance // </summary> internal override int Arity { get { return 1; } } // <summary> // Visitor pattern method // </summary> // <param name="v"> The BasicOpVisitor that is visiting this Op </param> // <param name="n"> The Node that references this Op </param> [DebuggerNonUserCode] internal override void Accept(BasicOpVisitor v, Node n) { v.Visit(this, n); } // <summary> // Visitor pattern method for visitors with a return value // </summary> // <param name="v"> The visitor </param> // <param name="n"> The node in question </param> // <returns> An instance of TResultType </returns> [DebuggerNonUserCode] internal override TResultType Accept<TResultType>(BasicOpVisitorOfT<TResultType> v, Node n) { return v.Visit(this, n); } #endregion } }
{ "pile_set_name": "Github" }
class Fastbit < Formula desc "Open-source data processing library in NoSQL spirit" homepage "https://sdm.lbl.gov/fastbit/" url "https://codeforge.lbl.gov/frs/download.php/416/fastbit-2.0.2.tar.gz" sha256 "a9d6254fcc32da6b91bf00285c7820869950bed25d74c993da49e1336fd381b4" head "https://codeforge.lbl.gov/anonscm/fastbit/trunk", :using => :svn bottle do cellar :any sha256 "2805a5e4739ab396077fad99782174b25def6d0c8ce3d3728ed39fed2160f286" => :el_capitan sha256 "33aa7e0a593b07b6d1615200b06ccd6eecd742beac345bd94b262f1b386d3591" => :yosemite sha256 "f2da8bed14e66f334f870cec65c678961f925d519bddefc74ef806b493346833" => :mavericks sha256 "d62226b902928b479e2835848a8eafdcd52557cb4249c59bd15cc1bd23d1e67e" => :mountain_lion end conflicts_with "iniparser", :because => "Both install `include/dictionary.h`" depends_on :java needs :cxx11 def install ENV.cxx11 system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" libexec.install lib/"fastbitjni.jar" bin.write_jar_script libexec/"fastbitjni.jar", "fastbitjni" end test do assert_equal prefix.to_s, shell_output("#{bin}/fastbit-config --prefix").chomp (testpath/"test.csv").write <<-EOS Potter,Harry Granger,Hermione Weasley,Ron EOS system bin/"ardea", "-d", testpath, "-m", "a:t,b:t", "-t", testpath/"test.csv" end end
{ "pile_set_name": "Github" }
package gui import ( . "gopkg.in/check.v1" ) type ChangePasswordDetailsSuite struct{} var _ = Suite(&ChangePasswordDetailsSuite{}) func (s *ChangePasswordDetailsSuite) Test_validatePasswords_SuccesfulValidation(c *C) { err := validateNewPassword("pass", "pass") c.Assert(err, IsNil) } func (s *ChangePasswordDetailsSuite) Test_validatePasswords_FailedMistmatch(c *C) { err := validateNewPassword("passone", "passtwo") c.Assert(err, NotNil) c.Assert(err, ErrorMatches, "\\[localized\\] The passwords do not match") } func (s *ChangePasswordDetailsSuite) Test_validatePasswords_FailedFieldMissing(c *C) { err := validateNewPassword("pass", "") c.Assert(err, NotNil) c.Assert(err, ErrorMatches, "\\[localized\\] The passwords do not match") } func (s *ChangePasswordDetailsSuite) Test_validatePasswords_FailedFieldsMissing(c *C) { err := validateNewPassword("", "") c.Assert(err, NotNil) c.Assert(err, ErrorMatches, "\\[localized\\] The password can't be empty") }
{ "pile_set_name": "Github" }
# OpenSees source code repository. This git repository contains all revisions to OpenSees source code since Version 2.3.2. Older revisions of the code are available upon request. If you plan on collaborating or even using OpenSees as your base code it is highly recommended that you FORK this repo to your own account and work on it there. We will not allow anybody to write to this repo. Only PULL requests will be considered. To fork the repo click on the FORK at the top of this page. For a brief outline on forking we suggest: https://www.atlassian.com/git/tutorials/comparing-workflows/forking-workflow For a brief introduction to using your new FORK we suggest: https://www.atlassian.com/git/tutorials/saving-changes ## Documentation The documentation for OpenSees is being moved to a parellel github repo: https://github.com/OpenSees/OpenSeesDocumentation The documentation (in its present form) can be viewed in the browser using the following url: https://OpenSees.github.io/OpenSeesDocumentation
{ "pile_set_name": "Github" }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.SecretManager.Tools.Internal; using Microsoft.Extensions.Tools.Internal; namespace Microsoft.Extensions.SecretManager.Tools { public class Program { private readonly IConsole _console; private readonly string _workingDirectory; public static int Main(string[] args) { DebugHelper.HandleDebugSwitch(ref args); int rc; new Program(PhysicalConsole.Singleton, Directory.GetCurrentDirectory()).TryRun(args, out rc); return rc; } public Program(IConsole console, string workingDirectory) { _console = console; _workingDirectory = workingDirectory; } public bool TryRun(string[] args, out int returnCode) { try { returnCode = RunInternal(args); return true; } catch (Exception exception) { var reporter = CreateReporter(verbose: true); reporter.Verbose(exception.ToString()); reporter.Error(Resources.FormatError_Command_Failed(exception.Message)); returnCode = 1; return false; } } internal int RunInternal(params string[] args) { CommandLineOptions options; try { options = CommandLineOptions.Parse(args, _console); } catch (CommandParsingException ex) { CreateReporter(verbose: false).Error(ex.Message); return 1; } if (options == null) { return 1; } if (options.IsHelp) { return 2; } var reporter = CreateReporter(options.IsVerbose); if (options.Command is InitCommandFactory initCmd) { initCmd.Execute(new CommandContext(null, reporter, _console), _workingDirectory); return 0; } string userSecretsId; try { userSecretsId = ResolveId(options, reporter); } catch (Exception ex) when (ex is InvalidOperationException || ex is FileNotFoundException) { reporter.Error(ex.Message); return 1; } var store = new SecretsStore(userSecretsId, reporter); var context = new Internal.CommandContext(store, reporter, _console); options.Command.Execute(context); return 0; } private IReporter CreateReporter(bool verbose) => new ConsoleReporter(_console, verbose, quiet: false); internal string ResolveId(CommandLineOptions options, IReporter reporter) { if (!string.IsNullOrEmpty(options.Id)) { return options.Id; } var resolver = new ProjectIdResolver(reporter, _workingDirectory); return resolver.Resolve(options.Project, options.Configuration); } } }
{ "pile_set_name": "Github" }
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_CONTINUOUS_DYNAMICS_WORLD_H #define BT_CONTINUOUS_DYNAMICS_WORLD_H #include "btDiscreteDynamicsWorld.h" ///btContinuousDynamicsWorld adds optional (per object) continuous collision detection for fast moving objects to the btDiscreteDynamicsWorld. ///This copes with fast moving objects that otherwise would tunnel/miss collisions. ///Under construction, don't use yet! Please use btDiscreteDynamicsWorld instead. class btContinuousDynamicsWorld : public btDiscreteDynamicsWorld { void updateTemporalAabbs(btScalar timeStep); public: btContinuousDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration); virtual ~btContinuousDynamicsWorld(); ///time stepping with calculation of time of impact for selected fast moving objects virtual void internalSingleStepSimulation( btScalar timeStep); virtual void calculateTimeOfImpacts(btScalar timeStep); virtual btDynamicsWorldType getWorldType() const { return BT_CONTINUOUS_DYNAMICS_WORLD; } }; #endif //BT_CONTINUOUS_DYNAMICS_WORLD_H
{ "pile_set_name": "Github" }
Solidity File SolContractDefinitionImpl(CONTRACT_DEFINITION) PsiElement(contract)('contract') PsiWhiteSpace(' ') PsiElement(Identifier)('test') PsiWhiteSpace(' ') PsiElement({)('{') PsiWhiteSpace('\n ') SolStateVariableDeclarationImpl(STATE_VARIABLE_DECLARATION) SolElementaryTypeNameImpl(ELEMENTARY_TYPE_NAME) SolNumberTypeImpl(NUMBER_TYPE) PsiElement(uIntNumType)('uint256') PsiWhiteSpace(' ') PsiElement(Identifier)('stateVar') PsiElement(;)(';') PsiWhiteSpace('\n ') PsiComment(comment)('/// This is a test function') PsiWhiteSpace('\n ') SolFunctionDefinitionImpl(FUNCTION_DEFINITION) PsiElement(function)('function') PsiWhiteSpace(' ') PsiElement(Identifier)('functionName') SolParameterListImpl(PARAMETER_LIST) PsiElement(()('(') SolParameterDefImpl(PARAMETER_DEF) SolBytesArrayTypeNameImpl(BYTES_ARRAY_TYPE_NAME) PsiElement(bytesNumType)('bytes32') PsiWhiteSpace(' ') PsiElement(Identifier)('input') PsiElement())(')') PsiWhiteSpace(' ') PsiElement(returns)('returns') PsiWhiteSpace(' ') SolParameterListImpl(PARAMETER_LIST) PsiElement(()('(') SolParameterDefImpl(PARAMETER_DEF) SolBytesArrayTypeNameImpl(BYTES_ARRAY_TYPE_NAME) PsiElement(bytesNumType)('bytes32') PsiWhiteSpace(' ') PsiElement(Identifier)('out') PsiElement())(')') PsiWhiteSpace(' ') SolBlockImpl(BLOCK) PsiElement({)('{') PsiElement(})('}') PsiWhiteSpace('\n') PsiElement(})('}')
{ "pile_set_name": "Github" }
/* * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.xerces.internal.dom; import java.io.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.UserDataHandler; /** * ParentNode inherits from ChildNode and adds the capability of having child * nodes. Not every node in the DOM can have children, so only nodes that can * should inherit from this class and pay the price for it. * <P> * ParentNode, just like NodeImpl, also implements NodeList, so it can * return itself in response to the getChildNodes() query. This eliminiates * the need for a separate ChildNodeList object. Note that this is an * IMPLEMENTATION DETAIL; applications should _never_ assume that * this identity exists. On the other hand, subclasses may need to override * this, in case of conflicting names. This is the case for the classes * HTMLSelectElementImpl and HTMLFormElementImpl of the HTML DOM. * <P> * While we have a direct reference to the first child, the last child is * stored as the previous sibling of the first child. First child nodes are * marked as being so, and getNextSibling hides this fact. * <P>Note: Not all parent nodes actually need to also be a child. At some * point we used to have ParentNode inheriting from NodeImpl and another class * called ChildAndParentNode that inherited from ChildNode. But due to the lack * of multiple inheritance a lot of code had to be duplicated which led to a * maintenance nightmare. At the same time only a few nodes (Document, * DocumentFragment, Entity, and Attribute) cannot be a child so the gain in * memory wasn't really worth it. The only type for which this would be the * case is Attribute, but we deal with there in another special way, so this is * not applicable. * <p> * This class doesn't directly support mutation events, however, it notifies * the document when mutations are performed so that the document class do so. * * <p><b>WARNING</b>: Some of the code here is partially duplicated in * AttrImpl, be careful to keep these two classes in sync! * * @xerces.internal * * @author Arnaud Le Hors, IBM * @author Joe Kesselman, IBM * @author Andy Clark, IBM * @LastModified: Apr 2019 */ public abstract class ParentNode extends ChildNode { /** Serialization version. */ static final long serialVersionUID = 2815829867152120872L; /** Owner document. */ protected CoreDocumentImpl ownerDocument; /** First child. */ protected ChildNode firstChild = null; // transients /** NodeList cache */ protected transient NodeListCache fNodeListCache = null; // // Constructors // /** * No public constructor; only subclasses of ParentNode should be * instantiated, and those normally via a Document's factory methods */ protected ParentNode(CoreDocumentImpl ownerDocument) { super(ownerDocument); this.ownerDocument = ownerDocument; } /** Constructor for serialization. */ public ParentNode() {} // // NodeList methods // /** * Returns a duplicate of a given node. You can consider this a * generic "copy constructor" for nodes. The newly returned object should * be completely independent of the source object's subtree, so changes * in one after the clone has been made will not affect the other. * <p> * Example: Cloning a Text node will copy both the node and the text it * contains. * <p> * Example: Cloning something that has children -- Element or Attr, for * example -- will _not_ clone those children unless a "deep clone" * has been requested. A shallow clone of an Attr node will yield an * empty Attr of the same name. * <p> * NOTE: Clones will always be read/write, even if the node being cloned * is read-only, to permit applications using only the DOM API to obtain * editable copies of locked portions of the tree. */ public Node cloneNode(boolean deep) { if (needsSyncChildren()) { synchronizeChildren(); } ParentNode newnode = (ParentNode) super.cloneNode(deep); // set owner document newnode.ownerDocument = ownerDocument; // Need to break the association w/ original kids newnode.firstChild = null; // invalidate cache for children NodeList newnode.fNodeListCache = null; // Then, if deep, clone the kids too. if (deep) { for (ChildNode child = firstChild; child != null; child = child.nextSibling) { newnode.appendChild(child.cloneNode(true)); } } return newnode; } // cloneNode(boolean):Node /** * Find the Document that this Node belongs to (the document in * whose context the Node was created). The Node may or may not * currently be part of that Document's actual contents. */ public Document getOwnerDocument() { return ownerDocument; } /** * same as above but returns internal type and this one is not overridden * by CoreDocumentImpl to return null */ CoreDocumentImpl ownerDocument() { return ownerDocument; } /** * NON-DOM * set the ownerDocument of this node and its children */ protected void setOwnerDocument(CoreDocumentImpl doc) { if (needsSyncChildren()) { synchronizeChildren(); } super.setOwnerDocument(doc); ownerDocument = doc; for (ChildNode child = firstChild; child != null; child = child.nextSibling) { child.setOwnerDocument(doc); } } /** * Test whether this node has any children. Convenience shorthand * for (Node.getFirstChild()!=null) */ public boolean hasChildNodes() { if (needsSyncChildren()) { synchronizeChildren(); } return firstChild != null; } /** * Obtain a NodeList enumerating all children of this node. If there * are none, an (initially) empty NodeList is returned. * <p> * NodeLists are "live"; as children are added/removed the NodeList * will immediately reflect those changes. Also, the NodeList refers * to the actual nodes, so changes to those nodes made via the DOM tree * will be reflected in the NodeList and vice versa. * <p> * In this implementation, Nodes implement the NodeList interface and * provide their own getChildNodes() support. Other DOMs may solve this * differently. */ public NodeList getChildNodes() { if (needsSyncChildren()) { synchronizeChildren(); } return this; } // getChildNodes():NodeList /** The first child of this Node, or null if none. */ public Node getFirstChild() { if (needsSyncChildren()) { synchronizeChildren(); } return firstChild; } // getFirstChild():Node /** The last child of this Node, or null if none. */ public Node getLastChild() { if (needsSyncChildren()) { synchronizeChildren(); } return lastChild(); } // getLastChild():Node final ChildNode lastChild() { // last child is stored as the previous sibling of first child return firstChild != null ? firstChild.previousSibling : null; } final void lastChild(ChildNode node) { // store lastChild as previous sibling of first child if (firstChild != null) { firstChild.previousSibling = node; } } /** * Move one or more node(s) to our list of children. Note that this * implicitly removes them from their previous parent. * * @param newChild The Node to be moved to our subtree. As a * convenience feature, inserting a DocumentNode will instead insert * all its children. * * @param refChild Current child which newChild should be placed * immediately before. If refChild is null, the insertion occurs * after all existing Nodes, like appendChild(). * * @return newChild, in its new state (relocated, or emptied in the case of * DocumentNode.) * * @throws DOMException(HIERARCHY_REQUEST_ERR) if newChild is of a * type that shouldn't be a child of this node, or if newChild is an * ancestor of this node. * * @throws DOMException(WRONG_DOCUMENT_ERR) if newChild has a * different owner document than we do. * * @throws DOMException(NOT_FOUND_ERR) if refChild is not a child of * this node. * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if this node is * read-only. */ public Node insertBefore(Node newChild, Node refChild) throws DOMException { // Tail-call; optimizer should be able to do good things with. return internalInsertBefore(newChild, refChild, false); } // insertBefore(Node,Node):Node /** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able * to control which mutation events are spawned. This version of the * insertBefore operation allows us to do so. It is not intended * for use by application programs. */ Node internalInsertBefore(Node newChild, Node refChild, boolean replace) throws DOMException { boolean errorChecking = ownerDocument.errorChecking; if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) { // SLOW BUT SAFE: We could insert the whole subtree without // juggling so many next/previous pointers. (Wipe out the // parent's child-list, patch the parent pointers, set the // ends of the list.) But we know some subclasses have special- // case behavior they add to insertBefore(), so we don't risk it. // This approch also takes fewer bytecodes. // NOTE: If one of the children is not a legal child of this // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children // have been transferred. (Alternative behaviors would be to // reparent up to the first failure point or reparent all those // which are acceptable to the target node, neither of which is // as robust. PR-DOM-0818 isn't entirely clear on which it // recommends????? // No need to check kids for right-document; if they weren't, // they wouldn't be kids of that DocFrag. if (errorChecking) { for (Node kid = newChild.getFirstChild(); // Prescan kid != null; kid = kid.getNextSibling()) { if (!ownerDocument.isKidOK(this, kid)) { throw new DOMException( DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null)); } } } while (newChild.hasChildNodes()) { insertBefore(newChild.getFirstChild(), refChild); } return newChild; } if (newChild == refChild) { // stupid case that must be handled as a no-op triggering events... refChild = refChild.getNextSibling(); removeChild(newChild); insertBefore(newChild, refChild); return newChild; } if (needsSyncChildren()) { synchronizeChildren(); } if (errorChecking) { if (isReadOnly()) { throw new DOMException( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); } if (newChild.getOwnerDocument() != ownerDocument && newChild != ownerDocument) { throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null)); } if (!ownerDocument.isKidOK(this, newChild)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null)); } // refChild must be a child of this node (or null) if (refChild != null && refChild.getParentNode() != this) { throw new DOMException(DOMException.NOT_FOUND_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null)); } // Prevent cycles in the tree // newChild cannot be ancestor of this Node, // and actually cannot be this boolean treeSafe = true; for (NodeImpl a = this; treeSafe && a != null; a = a.parentNode()) { treeSafe = newChild != a; } if(!treeSafe) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null)); } } // notify document ownerDocument.insertingNode(this, replace); // Convert to internal type, to avoid repeated casting ChildNode newInternal = (ChildNode)newChild; Node oldparent = newInternal.parentNode(); if (oldparent != null) { oldparent.removeChild(newInternal); } // Convert to internal type, to avoid repeated casting ChildNode refInternal = (ChildNode)refChild; // Attach up newInternal.ownerNode = this; newInternal.isOwned(true); // Attach before and after // Note: firstChild.previousSibling == lastChild!! if (firstChild == null) { // this our first and only child firstChild = newInternal; newInternal.isFirstChild(true); newInternal.previousSibling = newInternal; } else { if (refInternal == null) { // this is an append ChildNode lastChild = firstChild.previousSibling; lastChild.nextSibling = newInternal; newInternal.previousSibling = lastChild; firstChild.previousSibling = newInternal; } else { // this is an insert if (refChild == firstChild) { // at the head of the list firstChild.isFirstChild(false); newInternal.nextSibling = firstChild; newInternal.previousSibling = firstChild.previousSibling; firstChild.previousSibling = newInternal; firstChild = newInternal; newInternal.isFirstChild(true); } else { // somewhere in the middle ChildNode prev = refInternal.previousSibling; newInternal.nextSibling = refInternal; prev.nextSibling = newInternal; refInternal.previousSibling = newInternal; newInternal.previousSibling = prev; } } } changed(); // update cached length if we have any if (fNodeListCache != null) { if (fNodeListCache.fLength != -1) { fNodeListCache.fLength++; } if (fNodeListCache.fChildIndex != -1) { // if we happen to insert just before the cached node, update // the cache to the new node to match the cached index if (fNodeListCache.fChild == refInternal) { fNodeListCache.fChild = newInternal; } else { // otherwise just invalidate the cache fNodeListCache.fChildIndex = -1; } } } // notify document ownerDocument.insertedNode(this, newInternal, replace); checkNormalizationAfterInsert(newInternal); return newChild; } // internalInsertBefore(Node,Node,boolean):Node /** * Remove a child from this Node. The removed child's subtree * remains intact so it may be re-inserted elsewhere. * * @return oldChild, in its new state (removed). * * @throws DOMException(NOT_FOUND_ERR) if oldChild is not a child of * this node. * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if this node is * read-only. */ public Node removeChild(Node oldChild) throws DOMException { // Tail-call, should be optimizable return internalRemoveChild(oldChild, false); } // removeChild(Node) :Node /** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able * to control which mutation events are spawned. This version of the * removeChild operation allows us to do so. It is not intended * for use by application programs. */ Node internalRemoveChild(Node oldChild, boolean replace) throws DOMException { CoreDocumentImpl ownerDocument = ownerDocument(); if (ownerDocument.errorChecking) { if (isReadOnly()) { throw new DOMException( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); } if (oldChild != null && oldChild.getParentNode() != this) { throw new DOMException(DOMException.NOT_FOUND_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null)); } } ChildNode oldInternal = (ChildNode) oldChild; // notify document ownerDocument.removingNode(this, oldInternal, replace); // Save previous sibling for normalization checking. final ChildNode oldPreviousSibling = oldInternal.previousSibling(); // update cached length if we have any if (fNodeListCache != null) { if (fNodeListCache.fLength != -1) { fNodeListCache.fLength--; } if (fNodeListCache.fChildIndex != -1) { // if the removed node is the cached node // move the cache to its (soon former) previous sibling if (fNodeListCache.fChild == oldInternal) { fNodeListCache.fChildIndex--; fNodeListCache.fChild = oldPreviousSibling; } else { // otherwise just invalidate the cache fNodeListCache.fChildIndex = -1; } } } // Patch linked list around oldChild // Note: lastChild == firstChild.previousSibling if (oldInternal == firstChild) { // removing first child oldInternal.isFirstChild(false); firstChild = oldInternal.nextSibling; if (firstChild != null) { firstChild.isFirstChild(true); firstChild.previousSibling = oldInternal.previousSibling; } } else { ChildNode prev = oldInternal.previousSibling; ChildNode next = oldInternal.nextSibling; prev.nextSibling = next; if (next == null) { // removing last child firstChild.previousSibling = prev; } else { // removing some other child in the middle next.previousSibling = prev; } } // Remove oldInternal's references to tree oldInternal.ownerNode = ownerDocument; oldInternal.isOwned(false); oldInternal.nextSibling = null; oldInternal.previousSibling = null; changed(); // notify document ownerDocument.removedNode(this, replace); checkNormalizationAfterRemove(oldPreviousSibling); return oldInternal; } // internalRemoveChild(Node,boolean):Node /** * Make newChild occupy the location that oldChild used to * have. Note that newChild will first be removed from its previous * parent, if any. Equivalent to inserting newChild before oldChild, * then removing oldChild. * * @return oldChild, in its new state (removed). * * @throws DOMException(HIERARCHY_REQUEST_ERR) if newChild is of a * type that shouldn't be a child of this node, or if newChild is * one of our ancestors. * * @throws DOMException(WRONG_DOCUMENT_ERR) if newChild has a * different owner document than we do. * * @throws DOMException(NOT_FOUND_ERR) if oldChild is not a child of * this node. * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if this node is * read-only. */ public Node replaceChild(Node newChild, Node oldChild) throws DOMException { // If Mutation Events are being generated, this operation might // throw aggregate events twice when modifying an Attr -- once // on insertion and once on removal. DOM Level 2 does not specify // this as either desirable or undesirable, but hints that // aggregations should be issued only once per user request. // notify document ownerDocument.replacingNode(this); internalInsertBefore(newChild, oldChild, true); if (newChild != oldChild) { internalRemoveChild(oldChild, true); } // notify document ownerDocument.replacedNode(this); return oldChild; } /* * Get Node text content * @since DOM Level 3 */ public String getTextContent() throws DOMException { Node child = getFirstChild(); if (child != null) { Node next = child.getNextSibling(); if (next == null) { return hasTextContent(child) ? ((NodeImpl) child).getTextContent() : ""; } StringBuilder buf = new StringBuilder(); getTextContent(buf); return buf.toString(); } return ""; } // internal method taking a StringBuilder in parameter void getTextContent(StringBuilder buf) throws DOMException { Node child = getFirstChild(); while (child != null) { if (hasTextContent(child)) { ((NodeImpl) child).getTextContent(buf); } child = child.getNextSibling(); } } // internal method returning whether to take the given node's text content final boolean hasTextContent(Node child) { return child.getNodeType() != Node.COMMENT_NODE && child.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE && (child.getNodeType() != Node.TEXT_NODE || ((TextImpl) child).isIgnorableWhitespace() == false); } /* * Set Node text content * @since DOM Level 3 */ public void setTextContent(String textContent) throws DOMException { // get rid of any existing children Node child; while ((child = getFirstChild()) != null) { removeChild(child); } // create a Text node to hold the given content if (textContent != null && textContent.length() != 0){ appendChild(ownerDocument().createTextNode(textContent)); } } // // NodeList methods // /** * Count the immediate children of this node. Use to implement * NodeList.getLength(). * @return int */ private int nodeListGetLength() { if (fNodeListCache == null) { if (needsSyncChildren()) { synchronizeChildren(); } // get rid of trivial cases if (firstChild == null) { return 0; } if (firstChild == lastChild()) { return 1; } // otherwise request a cache object fNodeListCache = ownerDocument.getNodeListCache(this); } if (fNodeListCache.fLength == -1) { // is the cached length invalid ? int l; ChildNode n; // start from the cached node if we have one if (fNodeListCache.fChildIndex != -1 && fNodeListCache.fChild != null) { l = fNodeListCache.fChildIndex; n = fNodeListCache.fChild; } else { n = firstChild; l = 0; } while (n != null) { l++; n = n.nextSibling; } fNodeListCache.fLength = l; } return fNodeListCache.fLength; } // nodeListGetLength():int /** * NodeList method: Count the immediate children of this node * @return int */ public int getLength() { return nodeListGetLength(); } /** * Return the Nth immediate child of this node, or null if the index is * out of bounds. Use to implement NodeList.item(). * @param index int */ private Node nodeListItem(int index) { if (fNodeListCache == null) { if (needsSyncChildren()) { synchronizeChildren(); } // get rid of trivial case if (firstChild == lastChild()) { return index == 0 ? firstChild : null; } // otherwise request a cache object fNodeListCache = ownerDocument.getNodeListCache(this); } int i = fNodeListCache.fChildIndex; ChildNode n = fNodeListCache.fChild; boolean firstAccess = true; // short way if (i != -1 && n != null) { firstAccess = false; if (i < index) { while (i < index && n != null) { i++; n = n.nextSibling; } } else if (i > index) { while (i > index && n != null) { i--; n = n.previousSibling(); } } } else { // long way if (index < 0) { return null; } n = firstChild; for (i = 0; i < index && n != null; i++) { n = n.nextSibling; } } // release cache if reaching last child or first child if (!firstAccess && (n == firstChild || n == lastChild())) { fNodeListCache.fChildIndex = -1; fNodeListCache.fChild = null; ownerDocument.freeNodeListCache(fNodeListCache); // we can keep using the cache until it is actually reused // fNodeListCache will be nulled by the pool (document) if that // happens. // fNodeListCache = null; } else { // otherwise update it fNodeListCache.fChildIndex = i; fNodeListCache.fChild = n; } return n; } // nodeListItem(int):Node /** * NodeList method: Return the Nth immediate child of this node, or * null if the index is out of bounds. * @return org.w3c.dom.Node * @param index int */ public Node item(int index) { return nodeListItem(index); } // item(int):Node /** * Create a NodeList to access children that is use by subclass elements * that have methods named getLength() or item(int). ChildAndParentNode * optimizes getChildNodes() by implementing NodeList itself. However if * a subclass Element implements methods with the same name as the NodeList * methods, they will override the actually methods in this class. * <p> * To use this method, the subclass should implement getChildNodes() and * have it call this method. The resulting NodeList instance maybe * shared and cached in a transient field, but the cached value must be * cleared if the node is cloned. */ protected final NodeList getChildNodesUnoptimized() { if (needsSyncChildren()) { synchronizeChildren(); } return new NodeList() { /** * @see NodeList.getLength() */ public int getLength() { return nodeListGetLength(); } // getLength():int /** * @see NodeList.item(int) */ public Node item(int index) { return nodeListItem(index); } // item(int):Node }; } // getChildNodesUnoptimized():NodeList // // DOM2: methods, getters, setters // /** * Override default behavior to call normalize() on this Node's * children. It is up to implementors or Node to override normalize() * to take action. */ public void normalize() { // No need to normalize if already normalized. if (isNormalized()) { return; } if (needsSyncChildren()) { synchronizeChildren(); } ChildNode kid; for (kid = firstChild; kid != null; kid = kid.nextSibling) { kid.normalize(); } isNormalized(true); } /** * DOM Level 3 WD- Experimental. * Override inherited behavior from NodeImpl to support deep equal. */ public boolean isEqualNode(Node arg) { if (!super.isEqualNode(arg)) { return false; } // there are many ways to do this test, and there isn't any way // better than another. Performance may vary greatly depending on // the implementations involved. This one should work fine for us. Node child1 = getFirstChild(); Node child2 = arg.getFirstChild(); while (child1 != null && child2 != null) { if (!child1.isEqualNode(child2)) { return false; } child1 = child1.getNextSibling(); child2 = child2.getNextSibling(); } if (child1 != child2) { return false; } return true; } // // Public methods // /** * Override default behavior so that if deep is true, children are also * toggled. * @see Node * <P> * Note: this will not change the state of an EntityReference or its * children, which are always read-only. */ public void setReadOnly(boolean readOnly, boolean deep) { super.setReadOnly(readOnly, deep); if (deep) { if (needsSyncChildren()) { synchronizeChildren(); } // Recursively set kids for (ChildNode mykid = firstChild; mykid != null; mykid = mykid.nextSibling) { if (mykid.getNodeType() != Node.ENTITY_REFERENCE_NODE) { mykid.setReadOnly(readOnly,true); } } } } // setReadOnly(boolean,boolean) // // Protected methods // /** * Override this method in subclass to hook in efficient * internal data structure. */ protected void synchronizeChildren() { // By default just change the flag to avoid calling this method again needsSyncChildren(false); } /** * Checks the normalized state of this node after inserting a child. * If the inserted child causes this node to be unnormalized, then this * node is flagged accordingly. * The conditions for changing the normalized state are: * <ul> * <li>The inserted child is a text node and one of its adjacent siblings * is also a text node. * <li>The inserted child is is itself unnormalized. * </ul> * * @param insertedChild the child node that was inserted into this node * * @throws NullPointerException if the inserted child is <code>null</code> */ void checkNormalizationAfterInsert(ChildNode insertedChild) { // See if insertion caused this node to be unnormalized. if (insertedChild.getNodeType() == Node.TEXT_NODE) { ChildNode prev = insertedChild.previousSibling(); ChildNode next = insertedChild.nextSibling; // If an adjacent sibling of the new child is a text node, // flag this node as unnormalized. if ((prev != null && prev.getNodeType() == Node.TEXT_NODE) || (next != null && next.getNodeType() == Node.TEXT_NODE)) { isNormalized(false); } } else { // If the new child is not normalized, // then this node is inherently not normalized. if (!insertedChild.isNormalized()) { isNormalized(false); } } } // checkNormalizationAfterInsert(ChildNode) /** * Checks the normalized of this node after removing a child. * If the removed child causes this node to be unnormalized, then this * node is flagged accordingly. * The conditions for changing the normalized state are: * <ul> * <li>The removed child had two adjacent siblings that were text nodes. * </ul> * * @param previousSibling the previous sibling of the removed child, or * <code>null</code> */ void checkNormalizationAfterRemove(ChildNode previousSibling) { // See if removal caused this node to be unnormalized. // If the adjacent siblings of the removed child were both text nodes, // flag this node as unnormalized. if (previousSibling != null && previousSibling.getNodeType() == Node.TEXT_NODE) { ChildNode next = previousSibling.nextSibling; if (next != null && next.getNodeType() == Node.TEXT_NODE) { isNormalized(false); } } } // checkNormalizationAfterRemove(Node) // // Serialization methods // /** Serialize object. */ private void writeObject(ObjectOutputStream out) throws IOException { // synchronize children if (needsSyncChildren()) { synchronizeChildren(); } // write object out.defaultWriteObject(); } // writeObject(ObjectOutputStream) /** Deserialize object. */ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { // perform default deseralization ois.defaultReadObject(); // hardset synchildren - so we don't try to sync - it does not make any // sense to try to synchildren when we just deserialize object. needsSyncChildren(false); } // readObject(ObjectInputStream) /* * a class to store some user data along with its handler */ class UserDataRecord implements Serializable { /** Serialization version. */ private static final long serialVersionUID = 3258126977134310455L; Object fData; UserDataHandler fHandler; UserDataRecord(Object data, UserDataHandler handler) { fData = data; fHandler = handler; } } } // class ParentNode
{ "pile_set_name": "Github" }
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\PhotoMechanic; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class Rotation extends AbstractTag { protected $Id = 216; protected $Name = 'Rotation'; protected $FullName = 'PhotoMechanic::SoftEdit'; protected $GroupName = 'PhotoMechanic'; protected $g0 = 'PhotoMechanic'; protected $g1 = 'PhotoMechanic'; protected $g2 = 'Image'; protected $Type = 'int32s'; protected $Writable = true; protected $Description = 'Rotation'; protected $Values = array( 0 => array( 'Id' => 0, 'Label' => 0, ), 1 => array( 'Id' => 1, 'Label' => 90, ), 2 => array( 'Id' => 2, 'Label' => 180, ), 3 => array( 'Id' => 3, 'Label' => 270, ), ); }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>bundleid</key> <string>com.shorten-url.hzlzh</string> <key>connections</key> <dict> <key>29221F47-9904-4EE7-AAF9-D300BAFAF2EF</key> <array> <dict> <key>destinationuid</key> <string>162D1E3F-9D73-4C83-AD8C-869165521442</string> <key>modifiers</key> <integer>0</integer> <key>modifiersubtext</key> <string></string> </dict> <dict> <key>destinationuid</key> <string>82524AB3-0487-48D7-9CB8-7A456D78F473</string> <key>modifiers</key> <integer>0</integer> <key>modifiersubtext</key> <string></string> </dict> </array> <key>82E5133A-F114-4C1D-9FD4-365C395B6DF1</key> <array> <dict> <key>destinationuid</key> <string>FE7E3DAE-D8FF-4C84-AC14-4A1D11A10904</string> <key>modifiers</key> <integer>0</integer> <key>modifiersubtext</key> <string></string> </dict> </array> <key>FE7E3DAE-D8FF-4C84-AC14-4A1D11A10904</key> <array> <dict> <key>destinationuid</key> <string>29221F47-9904-4EE7-AAF9-D300BAFAF2EF</string> <key>modifiers</key> <integer>0</integer> <key>modifiersubtext</key> <string></string> </dict> </array> </dict> <key>createdby</key> <string>hzlzh</string> <key>description</key> <string>Shorten link with (goo.gl, bit.ly, t.cn, j.mp, is.gd, v.gd etc.)</string> <key>disabled</key> <false/> <key>name</key> <string>Shorten URL</string> <key>objects</key> <array> <dict> <key>config</key> <dict> <key>escaping</key> <integer>63</integer> <key>script</key> <string>''' Shorten URL v1.1 Github: https://github.com/hzlzh/Alfred-Workflows Author: hzlzh (hzlzh.dev@gmail.com) Twitter: @hzlzh Blog: https://zlz.im/Alfred-Workflows/ ''' import urllib import urllib2 import json import sys def getLink(type,service,url): if (('http' in url) == False): url = 'http://'+url if type == 'goo.gl': terms = urllib.quote_plus(url.strip()) data = json.dumps({"longUrl": url}) clen = len(data) req = urllib2.Request(service,data,{'Content-Type': 'application/json', 'Content-Length': clen}) f = urllib2.urlopen(req) data = f.read() output = json.loads(data)["id"] else: try: terms = urllib.quote_plus(url.strip()) url = service + terms data = urllib2.urlopen(url).read() except Exception, e: print '' if type == 'bit.ly': result = json.loads(data) if(result["status_code"] == 500): output = result["status_txt"] else: output = result["data"]["url"] elif type == 'j.mp': result = json.loads(data) if(result["status_code"] == 500): output = result["status_txt"] else: output = result["data"]["url"] elif type == 't.cn': result = json.loads(data) if('error_code' in result.keys()): output = result["error"] else: output = result["urls"][0]["url_short"] elif type == 'is.gd': result = json.loads(data) if('errorcode' in result.keys()): output = result["errormessage"] else: output = result["shorturl"] elif type == 'v.gd': result = json.loads(data) if('errorcode' in result.keys()): output = result["errormessage"] else: output = result["shorturl"] return output temp = '{query}' response = json.loads(temp) type = response['type'] service = response['api_url'] url = response['long_url'] last_output = getLink(type,service,url) if ('http' in last_output): print last_output else: print 'Error: '+ last_output</string> <key>type</key> <integer>3</integer> </dict> <key>type</key> <string>alfred.workflow.action.script</string> <key>uid</key> <string>29221F47-9904-4EE7-AAF9-D300BAFAF2EF</string> </dict> <dict> <key>config</key> <dict> <key>autopaste</key> <false/> <key>clipboardtext</key> <string></string> </dict> <key>type</key> <string>alfred.workflow.output.clipboard</string> <key>uid</key> <string>162D1E3F-9D73-4C83-AD8C-869165521442</string> </dict> <dict> <key>config</key> <dict> <key>action</key> <integer>0</integer> <key>argument</key> <integer>1</integer> <key>hotkey</key> <integer>37</integer> <key>hotmod</key> <integer>1179648</integer> <key>hotstring</key> <string>L</string> <key>leftcursor</key> <false/> <key>modsmode</key> <integer>0</integer> </dict> <key>type</key> <string>alfred.workflow.trigger.hotkey</string> <key>uid</key> <string>82E5133A-F114-4C1D-9FD4-365C395B6DF1</string> </dict> <dict> <key>config</key> <dict> <key>argumenttype</key> <integer>0</integer> <key>escaping</key> <integer>63</integer> <key>keyword</key> <string>short</string> <key>runningsubtext</key> <string>Loading services list.</string> <key>script</key> <string>''' Shorten URL v1.1 Github: https://github.com/hzlzh/Alfred-Workflows Author: hzlzh (hzlzh.dev@gmail.com) Twitter: @hzlzh Blog: https://zlz.im/Alfred-Workflows/ ''' from feedback import Feedback import urllib import urllib2 import json import sys query = '{query}' api = { 'goo.gl' : {'api_url':'https://www.googleapis.com/urlshortener/v1/url','title':'goo.gl','des':'http://goo.gl/'}, 'bit.ly' : {'api_url':'https://api-ssl.bitly.com/v3/shorten?format=json&amp;login=hzlzh&amp;apiKey=R_e8bcc43adaa5f818cc5d8a544a17d27d&amp;longUrl=','title':'bit.ly','des':'http://bit.ly/'}, 't.cn' : {'api_url':'https://api.weibo.com/2/short_url/shorten.json?access_token=2.00WSLtpB0GRHJ9745670860ceNWWiC&amp;url_long=','title':'t.cn','des':'http://t.cn/'}, 'j.mp' : {'api_url':'http://api.j.mp/v3//shorten?format=json&amp;login=hzlzh&amp;apiKey=R_e8bcc43adaa5f818cc5d8a544a17d27d&amp;longUrl=','title':'j.mp','des':'http://j.mp/'}, 'is.gd' : {'api_url':'http://is.gd/create.php?format=json&amp;url=','title':'is.gd','des':'http://is.gd/'}, 'v.gd' : {'api_url':'http://v.gd/create.php?format=json&amp;url=','title':'v.gd','des':'http://v.gd/'} } fb = Feedback() for title in api: fb.add_item(api[title]['title'], subtitle="Using %s" % api[title]['des'], arg='{"type":"'+title+'","api_url":"'+api[title]['api_url']+'","long_url":"'+query+'"}',icon='favicons/'+title+'.png') print fb </string> <key>subtext</key> <string>Include goo.gl, bit.ly, t.cn, j.mp, is.gd, v.gd etc.</string> <key>title</key> <string>Shorten URL</string> <key>type</key> <integer>3</integer> <key>withspace</key> <true/> </dict> <key>type</key> <string>alfred.workflow.input.scriptfilter</string> <key>uid</key> <string>FE7E3DAE-D8FF-4C84-AC14-4A1D11A10904</string> </dict> <dict> <key>config</key> <dict> <key>lastpathcomponent</key> <false/> <key>onlyshowifquerypopulated</key> <false/> <key>output</key> <integer>0</integer> <key>removeextension</key> <false/> <key>sticky</key> <false/> <key>text</key> <string>Copied to Clipboard!</string> <key>title</key> <string>{query}</string> </dict> <key>type</key> <string>alfred.workflow.output.notification</string> <key>uid</key> <string>82524AB3-0487-48D7-9CB8-7A456D78F473</string> </dict> </array> <key>readme</key> <string># Shorten URL v1.1 This workflow support URL shortener like (goo.gl, bit.ly, t.cn, j.mp, is.gd, v.gd), you can use Hotkey to trigger without open Alfred input window. # Project Source * Github: https://github.com/hzlzh/Alfred-Workflows * Blog Post: https://zlz.im/Alfred-Workflows/ # Contact * Andy Huang (hzlzh.dev@gmail.com) * Twitter: https://twitter.com/hzlzh (If you need more services to be added, please let me know.)</string> <key>uidata</key> <dict> <key>162D1E3F-9D73-4C83-AD8C-869165521442</key> <dict> <key>ypos</key> <real>10</real> </dict> <key>29221F47-9904-4EE7-AAF9-D300BAFAF2EF</key> <dict> <key>ypos</key> <real>10</real> </dict> <key>82524AB3-0487-48D7-9CB8-7A456D78F473</key> <dict> <key>ypos</key> <real>130</real> </dict> <key>82E5133A-F114-4C1D-9FD4-365C395B6DF1</key> <dict> <key>ypos</key> <real>10</real> </dict> <key>FE7E3DAE-D8FF-4C84-AC14-4A1D11A10904</key> <dict> <key>ypos</key> <real>10</real> </dict> </dict> <key>webaddress</key> <string>https://zlz.im/</string> </dict> </plist>
{ "pile_set_name": "Github" }
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # For netstat in serverspec. package 'net-tools' ruby_runtime 'any' do provider :system version '' end ruby_gem 'rack' do # Rack 1.6.2-1.6.4 broke 1.8 compat. version '1.6.1' end application '/opt/rack1' do file '/opt/rack1/config.ru' do content <<-EOH use Rack::ContentLength run proc {|env| [200, {'Content-Type' => 'text/plain'}, ['Hello world']] } EOH end rackup do port 8000 end end application '/opt/rack2' do file '/opt/rack2/Gemfile' do content <<-EOH source 'https://rubygems.org/' # See above ruby_gem[rack] for matching version. gem 'rack', '1.6.1' EOH end file '/opt/rack2/config.ru' do content <<-EOH use Rack::ContentLength run proc {|env| [200, {'Content-Type' => 'text/plain'}, [caller.first]] } EOH end bundle_install do vendor true end rackup do port 8001 end end include_recipe '::rails' include_recipe '::sinatra'
{ "pile_set_name": "Github" }
package com.alibaba.boot.velocity.controller; import com.alibaba.boot.velocity.VelocityLayoutProperties; import com.alibaba.boot.velocity.annotation.VelocityLayout; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * {@link VelocityLayout} {@link Controller} * * @author <a href="mailto:taogu.mxx@alibaba-inc.com">taogu.mxx</a> (Office) * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a> * @see BaseController * @since 2016.12.21 */ @Controller @VelocityLayout("/layout/default.vm") public class VelocityLayoutController extends BaseController { /** * To set required = false for Test Case */ @Autowired(required = false) private VelocityLayoutProperties velocityLayoutProperties = new VelocityLayoutProperties(); @RequestMapping(value = {"/layout"}) @VelocityLayout("/layout/layout.vm") public String layout(Model model) { // Overrides @VelocityLayout("/layout/layout.vm") // spring.velocity.layoutKey = layout_key model.addAttribute(velocityLayoutProperties.getLayoutKey(), "/layout/layout.vm"); return "index"; } @RequestMapping("/layout2") @VelocityLayout("/layout/layout2.vm") // Overrides @VelocityLayout("/layout/default.vm") public String layout2(Model model) { return "index"; } @RequestMapping("/layout3") // Uses @VelocityLayout("/layout/default.vm") public String layout3(Model model) { return "index"; } }
{ "pile_set_name": "Github" }
body.emergency_off_button_index { font-family: "Century Gothic", CenturyGothic, AppleGothic, sans-serif; text-align: center; header { padding: 10px 20px; margin-bottom: 30px; } #logo a { float: left; line-height: 20px; font-size: 14px; text-decoration: none; color: #000; } #links_container { float: right; } #links_container a { font-size: 14px; line-height: 20px; text-decoration: none; color: #000; margin-left: 15px; } #links_container a:visited { color: #000; } #links_container a:hover { color: #f00; } .clear { clear: both; } .modal { display: none; position: absolute; top: 0; bottom: 0; left: 0; right: 0; background-color: rgba(0,0,0,0.9); z-index: 10; .inner_modal { display: none; position: absolute; height: 125px; width: 500px; top:50%; left: 50%; margin-top: -150px; margin-left: -250px; padding: 10px 10px 30px; background-color: #eee; border-radius: 5px; border-top: 30px solid #aaa; } .modal_content { p { font-weight: bold; line-height: 45px; } .bar_container { margin-top: 10px; } } } .bar_container { height: 10px; width: 400px; margin: auto; background-color: #333; border: 7px solid rgba(0,0,0,0.5); } .inner_bar { height: 10px; width: 395px; background-color: #d40404; } h1 { font-size: 60px; line-height: 80px; } h2 { font-size: 40px; line-height: 80px; } button { height: 230px; width: 230px; margin: 30px; font-size: 26px; color: #fff; text-shadow: -1px -1px 0 rgba(0,0,0,0.3), 1px 1px 0 rgba(255,255,255,0.3); border-radius: 50%; border: 14px solid #d83a3a; background: rgb(211,25,25); background: -moz-radial-gradient(center, ellipse cover, rgba(211,25,25,1) 31%, rgba(173,0,0,1) 100%); background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(31%,rgba(211,25,25,1)), color-stop(100%,rgba(173,0,0,1))); background: -webkit-radial-gradient(center, ellipse cover, rgba(211,25,25,1) 31%,rgba(173,0,0,1) 100%); background: -o-radial-gradient(center, ellipse cover, rgba(211,25,25,1) 31%,rgba(173,0,0,1) 100%); background: -ms-radial-gradient(center, ellipse cover, rgba(211,25,25,1) 31%,rgba(173,0,0,1) 100%); background: radial-gradient(ellipse at center, rgba(211,25,25,1) 31%,rgba(173,0,0,1) 100%); box-shadow: 1px 1px 0 rgba(0,0,0,0.3), -1px -1px 0 rgba(0,0,0,0.2) inset, 1px 1px 5px rgba(255,255,255,0.4) inset; cursor: pointer; &:active { box-shadow: 1px 1px 0 rgba(0,0,0,0.3), 2px 2px 0 rgba(0,0,0,0.2) inset, 0px 0px 20px rgba(0,0,0,0.3) inset, 0px 0px 3px rgba(0,0,0,0.3) inset, -1px -1px 0 rgba(255,255,255,0.25) inset; } } .flicker { -webkit-animation: flicker 0.8s linear 2; } } @-webkit-keyframes flicker { 0% {opacity: 1;} 80% {opacity: 1;} 81% {opacity: 0;} 90% {opacity: 1;} 95% {opacity: 1;} 100% {opacity: 0;} }
{ "pile_set_name": "Github" }
export function factorialIterative(number: number) { if (number < 0) { return undefined; } let total = 1; for (let n = number; n > 1; n--) { total *= n; } return total; } export function factorial(n: number): number { if (n < 0) { return undefined; } if (n === 1 || n === 0) { return 1; } return n * factorial(n - 1); }
{ "pile_set_name": "Github" }
/* ============================================================ * * This file is a part of digiKam project * https://www.digikam.org * * Date : 2007-02-06 * Description : Setup view panel for dplugins. * * Copyright (C) 2018-2019 by Gilles Caulier <caulier dot gilles at gmail dot com> * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation; * either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * ============================================================ */ #ifndef DIGIKAM_SETUP_PLUGINS_H #define DIGIKAM_SETUP_PLUGINS_H // Qt includes #include <QScrollArea> namespace Digikam { class SetupPlugins : public QScrollArea { Q_OBJECT public: enum PluginTab { Generic = 0, Editor, Bqm }; public: explicit SetupPlugins(QWidget* const parent = nullptr); ~SetupPlugins(); void applySettings(); private: class Private; Private* const d; }; } // namespace Digikam #endif // DIGIKAM_SETUP_PLUGINS_H
{ "pile_set_name": "Github" }
{% autoescape None %} {% extends ../../../templates/base.html %} {% block title %}[{{instance.hostname}}:{{instance.pg_port}}] - Maintenance{% end %} {% block content %} {% include breadcrumb.html %} <div id="app"> <h3> Table: <strong>{{ table }}</strong> </h3> <div class="text-center" v-if="loading"> <img src="/images/ring-alt.svg" class="fa-fw fa-2x"> </div> <div v-cloak v-if="!loading"> <div class="row mb-2"> <div class="col"> <size-distribution-bar :height="'10px;'" :total="table.total_bytes" :cat1="table.table_size" :cat1raw="table.table_bytes" cat1label="Heap" :cat1bis="table.bloat_size" :cat1bisraw="table.bloat_bytes || 0" cat1bislabel="Heap Bloat" :cat2="table.index_size" :cat2raw="table.index_bytes" cat2label="Indexes" :cat2bis="table.index_bloat_size" :cat2bisraw="table.index_bloat_bytes" cat2bislabel="Indexes Bloat" :cat3="table.toast_size" :cat3raw="table.toast_bytes" cat3label="Toast" > </size-distribution-bar> </div> </div> <div class="row"> <div class="col"> <dl> <dt> Total </dt> <dd> {{! table.total_size }} <br> <span class="text-muted">~ {{! table.row_estimate }} rows</span> <small class="text-muted">(~ {{! table.n_dead_tup }} dead)</small> </dd> </dl> </div> <div class="col"> <dl> <dt> Heap <span class="bg-cat1 legend fa-fw d-inline-block">&nbsp;</span> </dt> <dd> {{! table.table_size }} <br> <em class="text-muted"> Bloat: {{! parseInt(table.bloat_bytes / table.table_bytes * 100) }}% <span class="small"> ({{! table.bloat_size }}) </span> </em> </dd> </dl> </div> <div class="col"> <dl> <dt> Indexes <span class="bg-cat2 legend fa-fw d-inline-block">&nbsp;</span> </dt> <dd> {{! table.index_size }} <br> <em class="text-muted"> Bloat: {{! parseInt(table.index_bloat_bytes / table.index_bytes * 100) }}% <span class="small"> ({{! table.index_bloat_size }}) </span> </em> </dd> </dl> </div> <div class="col"> <dl> <dt> <span class="bg-secondary legend fa-fw d-inline-block">&nbsp;</span> Toast </dt> <dd> {{! table.toast_size }} </dd> </dl> </div> <div class="col"> <dl> <dt> Fill Factor </dt> <dd> {{! table.fillfactor }}% </dd> </dl> </div> </div> <div class="row"> <div class="col-4"> Last ANALYZE: <em :title="getLatestAnalyze().date"> <strong v-if="getLatestAnalyze().date"> {{! getLatestAnalyze().date | relative_time }} </strong> <span v-else>N/A</span> <span v-if="getLatestAnalyze().auto">(auto)</span> </em> <span class="text-muted small" v-if="table.n_mod_since_analyze"> (~ {{! table.n_mod_since_analyze }} rows modified since then) </span> <br> <small> {{! table.analyze_count }} analyzes - {{! table.autoanalyze_count }} auto analyzes </small> </div> <div class="col-4"> Last VACUUM: <em :title="getLatestVacuum().date"> <strong v-if="getLatestVacuum().date"> {{! getLatestVacuum().date | relative_time }} </strong> <span v-else>N/A</span> <span v-if="getLatestVacuum().auto">(auto)</span> </em> <br> <small> {{! table.vacuum_count }} vacuums - {{! table.autovacuum_count }} auto vacuums </small> </div> </div> <div class="row"> <div class="col-4"> <div> <button type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#analyzeModal" v-on:click="checkSession"> ANALYZE </button> {% include includes/analyze_modal.html %} {% include includes/scheduled_analyze.html %} </div> </div> <div class="col-4"> <div> <button type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#vacuumModal" v-on:click="checkSession"> VACUUM </button> {% include includes/vacuum_modal.html %} {% include includes/scheduled_vacuum.html %} </div> </div> <div class="col-4"> <div> <button type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#reindexModal" v-on:click="reindexElementType='table';reindexElementName=table.name;checkSession($event)"> REINDEX </button> {% include includes/reindex_modal.html %} {% include includes/scheduled_reindex.html %} </div> </div> </div> <div class="row"> <div class="col"> <p class="text-danger" v-if="table.n_mod_since_analyze / table.n_live_tup > .5"> <i class="fa fa-exclamation-triangle"></i>The number of modified rows since last analyze is high, you should consider lauching an ANALYZE <br> <span class="pl-4 text-muted margin-left"> Out of date analyzes can result in stats not being accurate, which eventually leads to slow queries. </span> </p> <p class="text-danger" v-if="table.n_dead_tup / table.n_live_tup > .1"> <i class="fa fa-exclamation-triangle"></i>The number of dead tuples is high, you should consider running a VACUUM. <br> <span class="pl-4 text-muted margin-left"> Dead tuples waste space and slow down queries. </span> </p> <p class="text-danger" v-if="table.bloat_bytes / table.table_bytes > .5"> <i class="fa fa-exclamation-triangle"></i>Overall table bloat is high. You should consider running a Full VACUUUM. <br> <span class="pl-4 text-muted margin-left"> Table bloat wastes space and slows down queries. </span> </p> <p class="text-danger" v-if="table.index_bloat_bytes / table.index_bytes > .5"> <i class="fa fa-exclamation-triangle"></i>Overall index bloat is high. You should consider running a Full VACUUUM or REINDEX. <br> <span class="pl-4 text-muted margin-left"> Index bloat wastes space and slows down queries. </span> </p> </div> </div> <div class="d-flex"> <h4> Indexes <span class="text-muted small">({{! table.indexes.length }})</span> </h4> <div class="ml-auto"> <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Sort by {{! indexSortCriterias[indexSortCriteria][0] }}</button> <div class="dropdown-menu"> <h6 class="dropdown-header">Sort by:</h6> <a v-for="(criteria, key) in indexSortCriterias" class="dropdown-item" href="#" v-on:click="indexSortBy(key, criteria[1])"> <i :class="['fa fa-fw', {'fa-check': indexSortCriteria == key}]"></i> {{! criteria[0] }} </a> </div> </div> </div> {% include includes/reindex_modal.html %} <table class="table table-sm table-query table-striped table-bordered"> <tbody> <tr v-for="index in indexesSorted"> <td> <strong>{{! index.name }}</strong> <small> ({{! index.type }}) </small> <span v-if="index.tablespace"> <em class="text-muted small">in </em> {{! index.tablespace }} </span> </td> <td class="text-right align-middle"> <span :class="[indexSortCriteria == 'total_bytes' ? 'font-weight-bold' : '']"> {{! index.total_size }} </span> <small style="min-width: 70px;" :class="['d-inline-block', indexSortCriteria == 'bloat_ratio' ? 'font-weight-bold' : 'text-muted']"> <template v-if="index.bloat_bytes"> Bloat: {{! index.bloat_ratio.toFixed(1) }}% </template> </small> </td> <td class="align-middle text-right"> <span class="badge badge-secondary" v-if="index.scans"> {{! index.scans }} scans </span> </td> <td class="query" width="80%"> <pre><code class="sql">{{! index.def }}</code></pre> </td> <td class="align-middle" width="5%"> <button class="btn btn-outline-secondary btn-sm py-0" data-toggle="modal" data-target="#reindexModal" v-on:click="reindexElementType='index';reindexElementName=index.name;checkSession($event)">Reindex</button> <ul class="list list-unstyled mb-0" v-if="scheduledReindexes.length > 0"> <li v-for="scheduledReindex in scheduledReindexes" v-if="scheduledReindex.index == index.name"> <template v-if="scheduledReindex.status == 'todo'"> <em v-if="scheduledReindex.status == 'todo'"> <span class="text-muted" :title="scheduledReindex.datetime.toString()"><i class="fa fa-clock-o"></i> {{! scheduledReindex.datetime | relative_time(false) }}</span> </em> <button class="btn btn-link py-0" v-on:click="cancelReindex(scheduledReindex.id)" v-if="scheduledReindex.status == 'todo'">Cancel</button> </template> <template v-else-if="scheduledReindex.status == 'doing'"> <em class="text-muted"> <img id="loadingIndicator" src="/images/ring-alt.svg" class="fa-fw"> in progress </em> </template> <template v-else-if="scheduledReindex.status == 'canceled'"> <em class="text-muted">canceled</em> </template> <template v-else> <em class="text-muted">{{! scheduledReindex.status }}</em> </template> </li> </ul> </td> </tr> </tbody> </table> </div> </div> <script src="/js/lodash.min.js"></script> <script src="/js/moment.min.js"></script> <script src="/js/highlightjs/highlight.pack.js"></script> <script src="/js/vue.min.js"></script> <script src="/js/maintenance/vue.filter.relative-time.js"></script> <script src="/js/maintenance/vue.size-distribution-bar.js"></script> <script src="/js/daterangepicker.js"></script> <script src="/js/maintenance/temboard.maintenance.errors.js"></script> <script src="/js/maintenance/temboard.maintenance.table.js"></script> <script> var apiUrl = '/proxy/{{ instance.agent_address }}/{{ instance.agent_port }}/maintenance/{{ database }}/schema/{{ schema }}/table/{{ table }}'; var schemaApiUrl = '/proxy/{{ instance.agent_address }}/{{ instance.agent_port }}/maintenance/{{ database }}/schema/{{ schema }}'; var maintenanceBaseUrl = '/proxy/{{ instance.agent_address }}/{{ instance.agent_port }}/maintenance'; var agentLoginUrl = '/server/{{ instance.agent_address }}/{{ instance.agent_port }}/login'; var xsession = {{ json_encode(xsession) }}; </script> {% end %}
{ "pile_set_name": "Github" }
/* ioapi.c -- IO base function header for compress/uncompress .zip files using zlib + zip or unzip API Version 1.01e, February 12th, 2005 Copyright (C) 1998-2005 Gilles Vollant */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "zlib.h" #include "ioapi.h" /* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ #ifndef SEEK_CUR #define SEEK_CUR 1 #endif #ifndef SEEK_END #define SEEK_END 2 #endif #ifndef SEEK_SET #define SEEK_SET 0 #endif voidpf ZCALLBACK fopen_file_func OF(( voidpf opaque, const char* filename, int mode)); uLong ZCALLBACK fread_file_func OF(( voidpf opaque, voidpf stream, void* buf, uLong size)); uLong ZCALLBACK fwrite_file_func OF(( voidpf opaque, voidpf stream, const void* buf, uLong size)); long ZCALLBACK ftell_file_func OF(( voidpf opaque, voidpf stream)); long ZCALLBACK fseek_file_func OF(( voidpf opaque, voidpf stream, uLong offset, int origin)); int ZCALLBACK fclose_file_func OF(( voidpf opaque, voidpf stream)); int ZCALLBACK ferror_file_func OF(( voidpf opaque, voidpf stream)); voidpf ZCALLBACK fopen_file_func (opaque, filename, mode) voidpf opaque; const char* filename; int mode; { FILE* file = NULL; const char* mode_fopen = NULL; if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) mode_fopen = "rb"; else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) mode_fopen = "r+b"; else if (mode & ZLIB_FILEFUNC_MODE_CREATE) mode_fopen = "wb"; if ((filename!=NULL) && (mode_fopen != NULL)) file = fopen(filename, mode_fopen); return file; } uLong ZCALLBACK fread_file_func (opaque, stream, buf, size) voidpf opaque; voidpf stream; void* buf; uLong size; { uLong ret; ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); return ret; } uLong ZCALLBACK fwrite_file_func (opaque, stream, buf, size) voidpf opaque; voidpf stream; const void* buf; uLong size; { uLong ret; ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); return ret; } long ZCALLBACK ftell_file_func (opaque, stream) voidpf opaque; voidpf stream; { long ret; ret = ftell((FILE *)stream); return ret; } long ZCALLBACK fseek_file_func (opaque, stream, offset, origin) voidpf opaque; voidpf stream; uLong offset; int origin; { int fseek_origin=0; long ret; switch (origin) { case ZLIB_FILEFUNC_SEEK_CUR : fseek_origin = SEEK_CUR; break; case ZLIB_FILEFUNC_SEEK_END : fseek_origin = SEEK_END; break; case ZLIB_FILEFUNC_SEEK_SET : fseek_origin = SEEK_SET; break; default: return -1; } ret = 0; fseek((FILE *)stream, offset, fseek_origin); return ret; } int ZCALLBACK fclose_file_func (opaque, stream) voidpf opaque; voidpf stream; { int ret; ret = fclose((FILE *)stream); return ret; } int ZCALLBACK ferror_file_func (opaque, stream) voidpf opaque; voidpf stream; { int ret; ret = ferror((FILE *)stream); return ret; } void fill_fopen_filefunc (pzlib_filefunc_def) zlib_filefunc_def* pzlib_filefunc_def; { pzlib_filefunc_def->zopen_file = fopen_file_func; pzlib_filefunc_def->zread_file = fread_file_func; pzlib_filefunc_def->zwrite_file = fwrite_file_func; pzlib_filefunc_def->ztell_file = ftell_file_func; pzlib_filefunc_def->zseek_file = fseek_file_func; pzlib_filefunc_def->zclose_file = fclose_file_func; pzlib_filefunc_def->zerror_file = ferror_file_func; pzlib_filefunc_def->opaque = NULL; }
{ "pile_set_name": "Github" }