code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* eslint-disable comma-style, operator-linebreak, space-unary-ops, no-multi-spaces, key-spacing, indent */ 'use strict' const analyzeHoldem = require('./lib/holdem') /** * Analyzes a given PokerHand which has been parsed by the HandHistory Parser hhp. * Relative player positions are calculated, i.e. cutoff, button, etc. * Players are included in order of action on flop. * * The analyzed hand then can be visualized by [hhv](https://github.com/thlorenz/hhv). * * For an example of an analyzed hand please view [json output of an analyzed * hand](https://github.com/thlorenz/hhv/blob/master/test/fixtures/holdem/actiononall.json). * * @name analyze * @function * @param {object} hand hand history as parsed by [hhp](https://github.com/thlorenz/hhp) * @return {object} the analyzed hand */ exports = module.exports = function analyze(hand) { if (!hand.info) throw new Error('Hand is missing info') if (hand.info.pokertype === 'holdem') return analyzeHoldem(hand) } exports.script = require('./lib/script') exports.storyboard = require('./lib/storyboard') exports.summary = require('./lib/summary') exports.strategicPositions = require('./lib/strategic-positions').list function wasActive(x) { return x.preflop[0] && x.preflop[0].type !== 'fold' } /** * Filters all players who didn't act in the hand or just folded. * * @name filterInactives * @function * @param {Array.<Object>} players all players in the hand * @return {Array.<Object>} all players that were active in the hand */ exports.filterInactives = function filterInactives(players) { if (players == null) return [] return players.filter(wasActive) }
thlorenz/hha
hha.js
JavaScript
mit
1,658
import { h, render, rerender, Component } from '../../src/preact'; let { expect } = chai; /*eslint-env browser, mocha */ /*global sinon, chai*/ /** @jsx h */ describe('render()', () => { let scratch; before( () => { scratch = document.createElement('div'); (document.body || document.documentElement).appendChild(scratch); }); beforeEach( () => { scratch.innerHTML = ''; }); after( () => { scratch.parentNode.removeChild(scratch); scratch = null; }); it('should create empty nodes (<* />)', () => { render(<div />, scratch); expect(scratch.childNodes) .to.have.length(1) .and.to.have.deep.property('0.nodeName', 'DIV'); scratch.innerHTML = ''; render(<span />, scratch); expect(scratch.childNodes) .to.have.length(1) .and.to.have.deep.property('0.nodeName', 'SPAN'); scratch.innerHTML = ''; render(<foo />, scratch); render(<x-bar />, scratch); expect(scratch.childNodes).to.have.length(2); expect(scratch.childNodes[0]).to.have.property('nodeName', 'FOO'); expect(scratch.childNodes[1]).to.have.property('nodeName', 'X-BAR'); }); it('should nest empty nodes', () => { render(( <div> <span /> <foo /> <x-bar /> </div> ), scratch); expect(scratch.childNodes) .to.have.length(1) .and.to.have.deep.property('0.nodeName', 'DIV'); let c = scratch.childNodes[0].childNodes; expect(c).to.have.length(3); expect(c).to.have.deep.property('0.nodeName', 'SPAN'); expect(c).to.have.deep.property('1.nodeName', 'FOO'); expect(c).to.have.deep.property('2.nodeName', 'X-BAR'); }); it('should apply string attributes', () => { render(<div foo="bar" data-foo="databar" />, scratch); let div = scratch.childNodes[0]; expect(div).to.have.deep.property('attributes.length', 2); expect(div).to.have.deep.property('attributes[0].name', 'foo'); expect(div).to.have.deep.property('attributes[0].value', 'bar'); expect(div).to.have.deep.property('attributes[1].name', 'data-foo'); expect(div).to.have.deep.property('attributes[1].value', 'databar'); }); it('should apply class as String', () => { render(<div class="foo" />, scratch); expect(scratch.childNodes[0]).to.have.property('className', 'foo'); }); it('should alias className to class', () => { render(<div className="bar" />, scratch); expect(scratch.childNodes[0]).to.have.property('className', 'bar'); }); it('should apply style as String', () => { render(<div style="top:5px; position:relative;" />, scratch); expect(scratch.childNodes[0]).to.have.deep.property('style.cssText') .that.matches(/top\s*:\s*5px\s*/) .and.matches(/position\s*:\s*relative\s*/); }); it('should only register on* functions as handlers', () => { let click = () => {}, onclick = () => {}; let proto = document.createElement('div').constructor.prototype; sinon.spy(proto, 'addEventListener'); render(<div click={ click } onClick={ onclick } />, scratch); expect(scratch.childNodes[0]).to.have.deep.property('attributes.length', 0); expect(proto.addEventListener).to.have.been.calledOnce .and.to.have.been.calledWithExactly('click', sinon.match.func); proto.addEventListener.restore(); }); it('should serialize style objects', () => { render(<div style={{ color: 'rgb(255, 255, 255)', background: 'rgb(255, 100, 0)', backgroundPosition: '0 0', 'background-size': 'cover', padding: 5, top: 100, left: '100%' }} />, scratch); let { style } = scratch.childNodes[0]; expect(style).to.have.property('color', 'rgb(255, 255, 255)'); expect(style).to.have.property('background').that.contains('rgb(255, 100, 0)'); expect(style).to.have.property('backgroundPosition').that.matches(/0(px)? 0(px)?/); expect(style).to.have.property('backgroundSize', 'cover'); expect(style).to.have.property('padding', '5px'); expect(style).to.have.property('top', '100px'); expect(style).to.have.property('left', '100%'); }); it('should serialize class/className', () => { render(<div class={{ no1: false, no2: 0, no3: null, no4: undefined, no5: '', yes1: true, yes2: 1, yes3: {}, yes4: [], yes5: ' ' }} />, scratch); let { className } = scratch.childNodes[0]; expect(className).to.be.a.string; expect(className.split(' ')) .to.include.members(['yes1', 'yes2', 'yes3', 'yes4', 'yes5']) .and.not.include.members(['no1', 'no2', 'no3', 'no4', 'no5']); }); it('should reconcile mutated DOM attributes', () => { let check = p => render(<input type="checkbox" checked={p} />, scratch, scratch.lastChild), value = () => scratch.lastChild.checked, setValue = p => scratch.lastChild.checked = p; check(true); expect(value()).to.equal(true); check(false); expect(value()).to.equal(false); check(true); expect(value()).to.equal(true); setValue(true); check(false); expect(value()).to.equal(false); setValue(false); check(true); expect(value()).to.equal(true); }); it('should render components', () => { class C1 extends Component { render() { return <div>C1</div>; } } sinon.spy(C1.prototype, 'render'); render(<C1 />, scratch); expect(C1.prototype.render) .to.have.been.calledOnce .and.to.have.been.calledWithMatch({}, {}) .and.to.have.returned(sinon.match({ nodeName:'div' })); expect(scratch.innerHTML).to.equal('<div>C1</div>'); }); it('should render components with props', () => { const PROPS = { foo:'bar', onBaz:()=>{} }; let constructorProps; class C2 extends Component { constructor(props) { super(props); constructorProps = props; } render(props) { return <div {...props} />; } } sinon.spy(C2.prototype, 'render'); render(<C2 {...PROPS} />, scratch); expect(constructorProps).to.deep.equal(PROPS); expect(C2.prototype.render) .to.have.been.calledOnce .and.to.have.been.calledWithMatch(PROPS, {}) .and.to.have.returned(sinon.match({ nodeName: 'div', attributes: PROPS })); expect(scratch.innerHTML).to.equal('<div foo="bar"></div>'); }); it('should render functional components', () => { const PROPS = { foo:'bar', onBaz:()=>{} }; const C3 = sinon.spy( props => <div {...props} /> ); render(<C3 {...PROPS} />, scratch); expect(C3) .to.have.been.calledOnce .and.to.have.been.calledWithExactly(PROPS) .and.to.have.returned(sinon.match({ nodeName: 'div', attributes: PROPS })); expect(scratch.innerHTML).to.equal('<div foo="bar"></div>'); }); it('should render nested functional components', () => { const PROPS = { foo:'bar', onBaz:()=>{} }; const Outer = sinon.spy( props => <Inner {...props} /> ); const Inner = sinon.spy( props => <div {...props}>inner</div> ); render(<Outer {...PROPS} />, scratch); expect(Outer) .to.have.been.calledOnce .and.to.have.been.calledWithExactly(PROPS) .and.to.have.returned(sinon.match({ nodeName: Inner, attributes: PROPS })); expect(Inner) .to.have.been.calledOnce .and.to.have.been.calledWithExactly(PROPS) .and.to.have.returned(sinon.match({ nodeName: 'div', attributes: PROPS, children: ['inner'] })); expect(scratch.innerHTML).to.equal('<div foo="bar">inner</div>'); }); it('should re-render nested functional components', () => { let doRender = null; class Outer extends Component { componentDidMount() { let i = 1; doRender = () => this.setState({ i: ++i }); } componentWillUnmount() {} render(props, { i }) { return <Inner i={i} {...props} />; } } sinon.spy(Outer.prototype, 'render'); sinon.spy(Outer.prototype, 'componentWillUnmount'); let j = 0; const Inner = sinon.spy( props => <div j={ ++j } {...props}>inner</div> ); render(<Outer foo="bar" />, scratch); // update & flush doRender(); rerender(); expect(Outer.prototype.componentWillUnmount) .not.to.have.been.called; expect(Inner).to.have.been.calledTwice; expect(Inner.secondCall) .to.have.been.calledWithExactly({ foo:'bar', i:2 }) .and.to.have.returned(sinon.match({ attributes: { j: 2, i: 2, foo: 'bar' } })); expect(scratch.innerHTML).to.equal('<div j="2" foo="bar" i="2">inner</div>'); // update & flush doRender(); rerender(); expect(Inner).to.have.been.calledThrice; expect(Inner.thirdCall) .to.have.been.calledWithExactly({ foo:'bar', i:3 }) .and.to.have.returned(sinon.match({ attributes: { j: 3, i: 3, foo: 'bar' } })); expect(scratch.innerHTML).to.equal('<div j="3" foo="bar" i="3">inner</div>'); }); it('should re-render nested components', () => { let doRender = null; class Outer extends Component { componentDidMount() { let i = 1; doRender = () => this.setState({ i: ++i }); } componentWillUnmount() {} render(props, { i }) { return <Inner i={i} {...props} />; } } sinon.spy(Outer.prototype, 'render'); sinon.spy(Outer.prototype, 'componentDidMount'); sinon.spy(Outer.prototype, 'componentWillUnmount'); let j = 0; class Inner extends Component { constructor(...args) { super(); this._constructor(...args); } _constructor() {} componentDidMount() {} componentWillUnmount() {} render(props) { return <div j={ ++j } {...props}>inner</div>; } } sinon.spy(Inner.prototype, '_constructor'); sinon.spy(Inner.prototype, 'render'); sinon.spy(Inner.prototype, 'componentDidMount'); sinon.spy(Inner.prototype, 'componentWillUnmount'); render(<Outer foo="bar" />, scratch); expect(Outer.prototype.componentDidMount).to.have.been.calledOnce; // update & flush doRender(); rerender(); expect(Outer.prototype.componentWillUnmount).not.to.have.been.called; expect(Inner.prototype._constructor).to.have.been.calledOnce; expect(Inner.prototype.componentWillUnmount).not.to.have.been.called; expect(Inner.prototype.componentDidMount).to.have.been.calledOnce; expect(Inner.prototype.render).to.have.been.calledTwice; expect(Inner.prototype.render.secondCall) .to.have.been.calledWith({ foo:'bar', i:2 }) .and.to.have.returned(sinon.match({ attributes: { j: 2, i: 2, foo: 'bar' } })); expect(scratch.innerHTML).to.equal('<div j="2" foo="bar" i="2">inner</div>'); // update & flush doRender(); rerender(); expect(Inner.prototype.componentWillUnmount).not.to.have.been.called; expect(Inner.prototype.componentDidMount).to.have.been.calledOnce; expect(Inner.prototype.render).to.have.been.calledThrice; expect(Inner.prototype.render.thirdCall) .to.have.been.calledWith({ foo:'bar', i:3 }) .and.to.have.returned(sinon.match({ attributes: { j: 3, i: 3, foo: 'bar' } })); expect(scratch.innerHTML).to.equal('<div j="3" foo="bar" i="3">inner</div>'); }); });
okmttdhr/preact-fork
test/browser/render.js
JavaScript
mit
10,825
/* * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/rendering/InlineBox.h" #include "core/rendering/InlineFlowBox.h" #include "core/rendering/PaintInfo.h" #include "core/rendering/RenderBlockFlow.h" #include "core/rendering/RootInlineBox.h" #include "platform/Partitions.h" #include "platform/fonts/FontMetrics.h" #ifndef NDEBUG #include <stdio.h> #endif using namespace std; namespace WebCore { struct SameSizeAsInlineBox { virtual ~SameSizeAsInlineBox() { } void* a[4]; FloatPoint b; float c; uint32_t d : 32; #ifndef NDEBUG bool f; #endif }; COMPILE_ASSERT(sizeof(InlineBox) == sizeof(SameSizeAsInlineBox), InlineBox_size_guard); #ifndef NDEBUG InlineBox::~InlineBox() { if (!m_hasBadParent && m_parent) m_parent->setHasBadChildList(); } #endif void InlineBox::remove() { if (parent()) parent()->removeChild(this); } void* InlineBox::operator new(size_t sz) { return partitionAlloc(Partitions::getRenderingPartition(), sz); } void InlineBox::operator delete(void* ptr) { partitionFree(ptr); } #ifndef NDEBUG const char* InlineBox::boxName() const { return "InlineBox"; } void InlineBox::showTreeForThis() const { if (m_renderer) m_renderer->showTreeForThis(); } void InlineBox::showLineTreeForThis() const { if (m_renderer) m_renderer->containingBlock()->showLineTreeAndMark(this, "*"); } void InlineBox::showLineTreeAndMark(const InlineBox* markedBox1, const char* markedLabel1, const InlineBox* markedBox2, const char* markedLabel2, const RenderObject* obj, int depth) const { int printedCharacters = 0; if (this == markedBox1) printedCharacters += fprintf(stderr, "%s", markedLabel1); if (this == markedBox2) printedCharacters += fprintf(stderr, "%s", markedLabel2); if (renderer() == obj) printedCharacters += fprintf(stderr, "*"); for (; printedCharacters < depth * 2; printedCharacters++) fputc(' ', stderr); showBox(printedCharacters); } void InlineBox::showBox(int printedCharacters) const { printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this); for (; printedCharacters < showTreeCharacterOffset; printedCharacters++) fputc(' ', stderr); fprintf(stderr, "\t%s %p\n", renderer() ? renderer()->renderName() : "No Renderer", renderer()); } #endif float InlineBox::logicalHeight() const { if (hasVirtualLogicalHeight()) return virtualLogicalHeight(); if (renderer()->isText()) return m_bitfields.isText() ? renderer()->style(isFirstLineStyle())->fontMetrics().height() : 0; if (renderer()->isBox() && parent()) return isHorizontal() ? toRenderBox(m_renderer)->height() : toRenderBox(m_renderer)->width(); ASSERT(isInlineFlowBox()); RenderBoxModelObject* flowObject = boxModelObject(); const FontMetrics& fontMetrics = renderer()->style(isFirstLineStyle())->fontMetrics(); float result = fontMetrics.height(); if (parent()) result += flowObject->borderAndPaddingLogicalHeight(); return result; } int InlineBox::baselinePosition(FontBaseline baselineType) const { return boxModelObject()->baselinePosition(baselineType, m_bitfields.firstLine(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine); } LayoutUnit InlineBox::lineHeight() const { return boxModelObject()->lineHeight(m_bitfields.firstLine(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine); } int InlineBox::caretMinOffset() const { return m_renderer->caretMinOffset(); } int InlineBox::caretMaxOffset() const { return m_renderer->caretMaxOffset(); } void InlineBox::dirtyLineBoxes() { markDirty(); for (InlineFlowBox* curr = parent(); curr && !curr->isDirty(); curr = curr->parent()) curr->markDirty(); } void InlineBox::deleteLine() { if (!m_bitfields.extracted() && m_renderer->isBox()) toRenderBox(m_renderer)->setInlineBoxWrapper(0); destroy(); } void InlineBox::extractLine() { m_bitfields.setExtracted(true); if (m_renderer->isBox()) toRenderBox(m_renderer)->setInlineBoxWrapper(0); } void InlineBox::attachLine() { m_bitfields.setExtracted(false); if (m_renderer->isBox()) toRenderBox(m_renderer)->setInlineBoxWrapper(this); } void InlineBox::adjustPosition(float dx, float dy) { m_topLeft.move(dx, dy); if (m_renderer->isReplaced()) toRenderBox(m_renderer)->move(dx, dy); } void InlineBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/) { if (!paintInfo.shouldPaintWithinRoot(renderer()) || (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection)) return; LayoutPoint childPoint = paintOffset; if (parent()->renderer()->style()->isFlippedBlocksWritingMode()) // Faster than calling containingBlock(). childPoint = renderer()->containingBlock()->flipForWritingModeForChild(toRenderBox(renderer()), childPoint); RenderBlock::paintAsInlineBlock(renderer(), paintInfo, childPoint); } bool InlineBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/) { // Hit test all phases of replaced elements atomically, as though the replaced element established its // own stacking context. (See Appendix E.2, section 6.4 on inline block/table elements in the CSS2.1 // specification.) LayoutPoint childPoint = accumulatedOffset; if (parent()->renderer()->style()->isFlippedBlocksWritingMode()) // Faster than calling containingBlock(). childPoint = renderer()->containingBlock()->flipForWritingModeForChild(toRenderBox(renderer()), childPoint); return renderer()->hitTest(request, result, locationInContainer, childPoint); } const RootInlineBox* InlineBox::root() const { if (m_parent) return m_parent->root(); ASSERT(isRootInlineBox()); return static_cast<const RootInlineBox*>(this); } RootInlineBox* InlineBox::root() { if (m_parent) return m_parent->root(); ASSERT(isRootInlineBox()); return static_cast<RootInlineBox*>(this); } bool InlineBox::nextOnLineExists() const { if (!m_bitfields.determinedIfNextOnLineExists()) { m_bitfields.setDeterminedIfNextOnLineExists(true); if (!parent()) m_bitfields.setNextOnLineExists(false); else if (nextOnLine()) m_bitfields.setNextOnLineExists(true); else m_bitfields.setNextOnLineExists(parent()->nextOnLineExists()); } return m_bitfields.nextOnLineExists(); } InlineBox* InlineBox::nextLeafChild() const { InlineBox* leaf = 0; for (InlineBox* box = nextOnLine(); box && !leaf; box = box->nextOnLine()) leaf = box->isLeaf() ? box : toInlineFlowBox(box)->firstLeafChild(); if (!leaf && parent()) leaf = parent()->nextLeafChild(); return leaf; } InlineBox* InlineBox::prevLeafChild() const { InlineBox* leaf = 0; for (InlineBox* box = prevOnLine(); box && !leaf; box = box->prevOnLine()) leaf = box->isLeaf() ? box : toInlineFlowBox(box)->lastLeafChild(); if (!leaf && parent()) leaf = parent()->prevLeafChild(); return leaf; } InlineBox* InlineBox::nextLeafChildIgnoringLineBreak() const { InlineBox* leaf = nextLeafChild(); if (leaf && leaf->isLineBreak()) return 0; return leaf; } InlineBox* InlineBox::prevLeafChildIgnoringLineBreak() const { InlineBox* leaf = prevLeafChild(); if (leaf && leaf->isLineBreak()) return 0; return leaf; } RenderObject::SelectionState InlineBox::selectionState() { return renderer()->selectionState(); } bool InlineBox::canAccommodateEllipsis(bool ltr, int blockEdge, int ellipsisWidth) const { // Non-replaced elements can always accommodate an ellipsis. if (!m_renderer || !m_renderer->isReplaced()) return true; IntRect boxRect(left(), 0, m_logicalWidth, 10); IntRect ellipsisRect(ltr ? blockEdge - ellipsisWidth : blockEdge, 0, ellipsisWidth, 10); return !(boxRect.intersects(ellipsisRect)); } float InlineBox::placeEllipsisBox(bool, float, float, float, float& truncatedWidth, bool&) { // Use -1 to mean "we didn't set the position." truncatedWidth += logicalWidth(); return -1; } void InlineBox::clearKnownToHaveNoOverflow() { m_bitfields.setKnownToHaveNoOverflow(false); if (parent() && parent()->knownToHaveNoOverflow()) parent()->clearKnownToHaveNoOverflow(); } FloatPoint InlineBox::locationIncludingFlipping() { if (!renderer()->style()->isFlippedBlocksWritingMode()) return FloatPoint(x(), y()); RenderBlockFlow* block = root()->block(); if (block->style()->isHorizontalWritingMode()) return FloatPoint(x(), block->height() - height() - y()); else return FloatPoint(block->width() - width() - x(), y()); } void InlineBox::flipForWritingMode(FloatRect& rect) { if (!renderer()->style()->isFlippedBlocksWritingMode()) return; root()->block()->flipForWritingMode(rect); } FloatPoint InlineBox::flipForWritingMode(const FloatPoint& point) { if (!renderer()->style()->isFlippedBlocksWritingMode()) return point; return root()->block()->flipForWritingMode(point); } void InlineBox::flipForWritingMode(LayoutRect& rect) { if (!renderer()->style()->isFlippedBlocksWritingMode()) return; root()->block()->flipForWritingMode(rect); } LayoutPoint InlineBox::flipForWritingMode(const LayoutPoint& point) { if (!renderer()->style()->isFlippedBlocksWritingMode()) return point; return root()->block()->flipForWritingMode(point); } } // namespace WebCore #ifndef NDEBUG void showTree(const WebCore::InlineBox* b) { if (b) b->showTreeForThis(); } void showLineTree(const WebCore::InlineBox* b) { if (b) b->showLineTreeForThis(); } #endif
lordmos/blink
Source/core/rendering/InlineBox.cpp
C++
mit
10,882
<?php /* OyatelCdrBundle:Default:index.html.twig */ class __TwigTemplate_fce6b668448a5b90084f0988441f2b64 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo " "; } public function getTemplateName() { return "OyatelCdrBundle:Default:index.html.twig"; } public function getDebugInfo() { return array ( 17 => 1,); } }
mehulsbhatt/cdr
app/cache/prod/twig/fc/e6/b668448a5b90084f0988441f2b64.php
PHP
mit
625
using System; using System.Globalization; #if UNIVERSAL using Windows.UI.Xaml.Data; using Windows.UI.Xaml; #else using System.Windows; using System.Windows.Data; #endif namespace Newport { public abstract class BaseConverter : DependencyObject, IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return OnConvert(value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return OnConvertBack(value); } public object Convert(object value, Type targetType, object parameter, string culture) { return OnConvert(value); } public object ConvertBack(object value, Type targetType, object parameter, string culture) { return OnConvertBack(value); } protected abstract object OnConvert(object value); protected abstract object OnConvertBack(object value); } }
z1c0/Newport
Newport/Converters/BaseConverter.cs
C#
mit
954
package dynamics.item; import java.util.List; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; public interface IMetaItem { IIcon getIcon(); String getUnlocalizedName(ItemStack stack); boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase player); boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ); ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player); void registerIcons(IIconRegister iconRegister); void addRecipe(); void addToCreativeList(Item item, int meta, List<ItemStack> result); boolean hasEffect(int renderPass); }
awesommist/DynamicLib
src/main/java/dynamics/item/IMetaItem.java
Java
mit
947
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { private: ListNode* reverseList(ListNode* head) { ListNode * reverse = NULL; ListNode * node = head; while (node) { head = node->next; node->next = reverse; reverse = node; node = head; } return reverse; } public: void reorderList(ListNode* head) { if (head == NULL || head->next == NULL) return; ListNode* slow = head; ListNode* fast = head; ListNode* tmp = NULL; while (fast->next != NULL && fast->next->next != NULL) { fast = fast->next->next; slow = slow->next; } fast = slow->next; slow->next = NULL; fast = reverseList(fast); while (fast != NULL) { slow = head->next; head->next = fast; fast = fast->next; head->next->next = slow; head = slow; } return; } };
hawkphantomnet/leetcode
ReorderList/Solution.cpp
C++
mit
1,125
#ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include "game/ui/general/loadingscreen.h" #include "framework/configfile.h" #include "framework/data.h" #include "framework/framework.h" #include "framework/renderer.h" #include "game/state/gamestate.h" #include "game/ui/battle/battleview.h" #include "game/ui/city/cityview.h" #include <algorithm> #include <cmath> namespace OpenApoc { ConfigOptionBool asyncLoading("Game", "ASyncLoading", "Load in background while displaying animated loading screen", true); LoadingScreen::LoadingScreen(std::future<void> task, std::function<sp<Stage>()> nextScreenFn, sp<Image> background, int scaleDivisor, bool showRotatingImage) : Stage(), loadingTask(std::move(task)), nextScreenFn(std::move(nextScreenFn)), backgroundimage(background), showRotatingImage(showRotatingImage), scaleDivisor(scaleDivisor) { } void LoadingScreen::begin() { // FIXME: This is now useless, as it doesn't actually load anything interesting here if (showRotatingImage) { loadingimage = fw().data->loadImage("ui/loading.png"); } if (!backgroundimage) { backgroundimage = fw().data->loadImage("ui/logo.png"); } fw().displaySetIcon(); loadingimageangle = 0; if (asyncLoading.get() == false) { loadingTask.wait(); } } void LoadingScreen::pause() {} void LoadingScreen::resume() {} void LoadingScreen::finish() {} void LoadingScreen::eventOccurred(Event *e) { std::ignore = e; } void LoadingScreen::update() { loadingimageangle += (float)(M_PI + 0.05f); if (loadingimageangle >= (float)(M_PI * 2.0f)) loadingimageangle -= (float)(M_PI * 2.0f); auto status = this->loadingTask.wait_for(std::chrono::seconds(0)); if (asyncLoading.get() == false) { LogAssert(status == std::future_status::ready); } switch (status) { case std::future_status::ready: { fw().stageQueueCommand({StageCmd::Command::REPLACE, nextScreenFn()}); return; } default: // Not yet finished return; } } void LoadingScreen::render() { int logow = fw().displayGetWidth() / scaleDivisor; int logoh = fw().displayGetHeight() / scaleDivisor; float logoscw = logow / static_cast<float>(backgroundimage->size.x); float logosch = logoh / static_cast<float>(backgroundimage->size.y); float logosc = std::min(logoscw, logosch); Vec2<float> logoPosition{fw().displayGetWidth() / 2 - (backgroundimage->size.x * logosc / 2), fw().displayGetHeight() / 2 - (backgroundimage->size.y * logosc / 2)}; Vec2<float> logoSize{backgroundimage->size.x * logosc, backgroundimage->size.y * logosc}; fw().renderer->drawScaled(backgroundimage, logoPosition, logoSize); if (loadingimage) { fw().renderer->drawRotated( loadingimage, Vec2<float>{24, 24}, Vec2<float>{fw().displayGetWidth() - 50, fw().displayGetHeight() - 50}, loadingimageangle); } } bool LoadingScreen::isTransition() { return false; } }; // namespace OpenApoc
steveschnepp/OpenApoc
game/ui/general/loadingscreen.cpp
C++
mit
2,976
<?php namespace System; class Controller { const DEFINITIONS = null; const VIEWS = null; }
headcruser/blog
src/lib/Controller.php
PHP
mit
101
package com.suelake.habbo.moderation; import java.util.Date; import com.blunk.util.TimeHelper; import com.suelake.habbo.communication.SerializableObject; import com.suelake.habbo.communication.ServerMessage; import com.suelake.habbo.spaces.Space; import com.suelake.habbo.users.User; /** * CallForHelp represents a 'cry for help' submitted by a logged in User. Moderating Users are supposed to handle this CallForHelp and inform the calling User how to deal with the reported issue. * * @author Nillus */ public class CallForHelp implements SerializableObject { /** * The database ID of this CallForHelp. */ public final int ID; /** * The User object of the calling user. */ private User m_sender; /** * The Space object representing */ private Space m_space; /** * The java.util.Date representing the moment this CallForHelp was sent. */ public final Date timeStamp; /** * The message (eg, 'The Hotel is on fire') sent by the calling User. */ public String text; public CallForHelp(int callID) { this.ID = callID; this.timeStamp = TimeHelper.getDateTime(); } public void setSender(User usr) { m_sender = usr; } public User getSender() { return m_sender; } public void setSpace(Space space) { m_space = space; } public Space getSpace() { return m_space; } @Override public void serialize(ServerMessage msg) { if (this.getSender() != null) { msg.appendNewArgument("User: " + this.getSender().name + " @ " + TimeHelper.formatDateTime(this.timeStamp)); msg.appendNewArgument(ModerationCenter.craftChatlogUrl(this.ID)); if (this.getSpace() != null) { msg.appendKV2Argument("id", Integer.toString(this.getSpace().ID)); msg.appendKV2Argument("name", "Space: \"" + this.getSpace().name + "\" (id: " + this.getSpace().ID + ", owner: " + this.getSpace().owner + ")"); msg.appendKV2Argument("type", (this.getSpace().isUserFlat()) ? "private" : "public"); msg.appendKV2Argument("port", "30000"); } msg.appendKV2Argument("text", this.text); } } }
Chnkr/Suelake
src/com/suelake/habbo/moderation/CallForHelp.java
Java
mit
2,056
//namespace Instinct.Collections.RoutedCommand //{ // /// <summary> // /// RoutedCommand // /// </summary> // public class RoutedCommand : ICommand // { // private byte _commandId; // private string _name; // private System.Type _ownerType; // private System.Collections.Specialized.BitVector32 _privateVector = new System.Collections.Specialized.BitVector32(); // #region Class Types // /// <summary> // /// PrivateFlags // /// </summary> // private enum PrivateVectorIndex : byte // { // /// <summary> // /// IsBlockedByRM // /// </summary> // IsBlockedByRM = 1 // } // #endregion Class Types // /// <summary> // /// Initializes a new instance of the <see cref="RoutedCommand"/> class. // /// </summary> // public RoutedCommand() // { // _name = string.Empty; // _ownerType = null; // } // /// <summary> // /// Initializes a new instance of the <see cref="RoutedCommand"/> class. // /// </summary> // /// <param name="name">The name.</param> // /// <param name="ownerType">Type of the owner.</param> // public RoutedCommand(string name, System.Type ownerType) // { // if ((name == null) || (name.Length == 0)) // { // throw new ArgumentNullException("name"); // } // if (ownerType == null) // { // throw new ArgumentNullException("ownerType"); // } // _name = name; // _ownerType = ownerType; // } // /// <summary> // /// Initializes a new instance of the <see cref="RoutedCommand"/> class. // /// </summary> // /// <param name="name">The name.</param> // /// <param name="ownerType">Type of the owner.</param> // /// <param name="commandId">The command id.</param> // internal RoutedCommand(string name, System.Type ownerType, byte commandId) // : this(name, ownerType) // { // _commandId = commandId; // } // /// <summary> // /// Occurs when [can execute changed]. // /// </summary> // public event System.EventHandler CanExecuteChanged // { // add { CommandManager.RequerySuggested += value; } // remove { CommandManager.RequerySuggested -= value; } // } // /// <summary> // /// Determines whether this instance can execute the specified parameter. // /// </summary> // /// <param name="parameter">The parameter.</param> // /// <param name="target">The target.</param> // /// <returns> // /// <c>true</c> if this instance can execute the specified parameter; otherwise, <c>false</c>. // /// </returns> // public bool CanExecute(object parameter, IInputElement target) // { // bool flag; // return CriticalCanExecute(parameter, target, false, out flag); // } // private bool CanExecuteImpl(object parameter, IInputElement target, bool trusted, out bool continueRouting) // { // if ((target != null) && !this.IsBlockedByRM) // { // CanExecuteRoutedEventArgs args = new CanExecuteRoutedEventArgs(this, parameter); // args.RoutedEvent = CommandManager.PreviewCanExecuteEvent; // this.CriticalCanExecuteWrapper(parameter, target, trusted, args); // if (!args.Handled) // { // args.RoutedEvent = CommandManager.CanExecuteEvent; // this.CriticalCanExecuteWrapper(parameter, target, trusted, args); // } // continueRouting = args.ContinueRouting; // return args.CanExecute; // } // continueRouting = false; // return false; // } // internal bool CriticalCanExecute(object parameter, IInputElement target, bool trusted, out bool continueRouting) // { // if ((target != null) && !InputElement.IsValid(target)) // { // throw new InvalidOperationException(TR.Get("Invalid_IInputElement", new object[] { target.GetType() })); // } // if (target == null) // { // target = FilterInputElement(Keyboard.FocusedElement); // } // return CanExecuteImpl(parameter, target, trusted, out continueRouting); // } // private void CriticalCanExecuteWrapper(object parameter, IInputElement target, bool trusted, CanExecuteRoutedEventArgs args) // { // DependencyObject o = (DependencyObject)target; // if (InputElement.IsUIElement(o)) // { // ((UIElement)o).RaiseEvent(args, trusted); // } // else if (InputElement.IsContentElement(o)) // { // ((ContentElement)o).RaiseEvent(args, trusted); // } // else if (InputElement.IsUIElement3D(o)) // { // ((UIElement3D)o).RaiseEvent(args, trusted); // } // } // public void Execute(object parameter, IInputElement target) // { // if ((target != null) && !InputElement.IsValid(target)) // { // throw new InvalidOperationException(TR.Get("Invalid_IInputElement", new object[] { target.GetType() })); // } // if (target == null) // { // target = FilterInputElement(Keyboard.FocusedElement); // } // this.ExecuteImpl(parameter, target, false); // } // internal bool ExecuteCore(object parameter, IInputElement target, bool userInitiated) // { // if (target == null) // { // target = FilterInputElement(Keyboard.FocusedElement); // } // return this.ExecuteImpl(parameter, target, userInitiated); // } // private bool ExecuteImpl(object parameter, IInputElement target, bool userInitiated) // { // if ((target == null) || this.IsBlockedByRM) // { // return false; // } // UIElement element2 = target as UIElement; // ContentElement element = null; // UIElement3D elementd = null; // ExecutedRoutedEventArgs args = new ExecutedRoutedEventArgs(this, parameter); // args.RoutedEvent = CommandManager.PreviewExecutedEvent; // if (element2 != null) // { // element2.RaiseEvent(args, userInitiated); // } // else // { // element = target as ContentElement; // if (element != null) // { // element.RaiseEvent(args, userInitiated); // } // else // { // elementd = target as UIElement3D; // if (elementd != null) // { // elementd.RaiseEvent(args, userInitiated); // } // } // } // if (!args.Handled) // { // args.RoutedEvent = CommandManager.ExecutedEvent; // if (element2 != null) // { // element2.RaiseEvent(args, userInitiated); // } // else if (element != null) // { // element.RaiseEvent(args, userInitiated); // } // else if (elementd != null) // { // elementd.RaiseEvent(args, userInitiated); // } // } // return args.Handled; // } // private static IInputElement FilterInputElement(IInputElement elem) // { // if ((elem != null) && InputElement.IsValid(elem)) // { // return elem; // } // return null; // } // bool ICommand.CanExecute(object parameter) // { // bool flag; // return CanExecuteImpl(parameter, FilterInputElement(Keyboard.FocusedElement), false, out flag); // } // void ICommand.Execute(object parameter) // { // this.Execute(parameter, FilterInputElement(Keyboard.FocusedElement)); // } // /// <summary> // /// Gets the command id. // /// </summary> // /// <value>The command id.</value> // internal byte CommandId // { // get { return _commandId; } // } // /// <summary> // /// Gets or sets a value indicating whether this instance is blocked by RM. // /// </summary> // /// <value> // /// <c>true</c> if this instance is blocked by RM; otherwise, <c>false</c>. // /// </value> // internal bool IsBlockedByRM // { // get { return _privateVector[(int)PrivateVectorIndex.IsBlockedByRM]; } // set { _privateVector[(int)PrivateVectorIndex.IsBlockedByRM] = value; } // } // /// <summary> // /// Gets the name. // /// </summary> // /// <value>The name.</value> // public string Name // { // get { return _name; } // } // /// <summary> // /// Gets the type of the owner. // /// </summary> // /// <value>The type of the owner.</value> // public System.Type OwnerType // { // get { return _ownerType; } // } // } //}
Grimace1975/bclcontrib
Core/System.CoreEx_/System.Core.Routing/Collections.1/RoutedCommand/RoutedCommand.cs
C#
mit
10,006
package config const ( OutputFormatText = "text" OutputFormatJSON = "json" OutputTargetStdout = "stdout" OutputTargetFile = "file" ) type Output struct { Format string `yaml:"format"` Target string `yaml:"target"` FileName string `yaml:"file_name"` }
chapsuk/frissgo
config/output.go
GO
mit
267
version https://git-lfs.github.com/spec/v1 oid sha256:f7df841464cae1b61b2fb488b6174926c0e0251ceddf1dd360b031ab9fb83c3c size 4289
yogeshsaroya/new-cdnjs
ajax/libs/angular.js/1.2.6/angular-sanitize.min.js
JavaScript
mit
129
package entities; import javax.persistence.*; import java.util.Set; @Entity @Table(name="store_locations") public class StoreLocation { private Long id; private String locationName; private Set<Sale> sales; public StoreLocation() { } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name="location_name") public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } @OneToMany(mappedBy = "storeLocation") public Set<Sale> getSales() { return sales; } public void setSales(Set<Sale> sales) { this.sales = sales; } }
yangra/SoftUni
Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/07.HibernateCodeFirst/SalesDatabase/src/main/java/entities/StoreLocation.java
Java
mit
834
<?php use DBA\AnswerSession; use DBA\JoinFilter; use DBA\MediaObject; use DBA\MediaType; use DBA\OrderFilter; use DBA\Query; use DBA\QueryFilter; use DBA\QueryResultTuple; use DBA\RandOrderFilter; use DBA\ResultTuple; /** * * @author Sein * * Bunch of useful static functions. */ class Util { /** * Calculates variable. Used in Templates. * @param $in mixed calculation to be done * @return mixed */ public static function calculate($in) { return $in; } public static function checkFolders() { $tempDir = STORAGE_PATH . TMP_FOLDER; if (!file_exists($tempDir)) { mkdir($tempDir); } $queryDir = STORAGE_PATH . QUERIES_FOLDER; if (!file_exists($queryDir)) { mkdir($queryDir); } $mediaDir = STORAGE_PATH . MEDIA_FOLDER; if (!file_exists($mediaDir)) { mkdir($mediaDir); } } public static function getValidityForMicroworker($microworkerId) { global $FACTORIES; $qF = new QueryFilter(AnswerSession::MICROWORKER_ID, $microworkerId, "="); $answerSessions = $FACTORIES::getAnswerSessionFactory()->filter(array($FACTORIES::FILTER => $qF)); foreach ($answerSessions as $answerSession) { if ($answerSession->getIsOpen() == 0) { return $answerSession->getCurrentValidity(); } } return -1; } /** * Get either a Gravatar URL or complete image tag for a specified email address. * * @param string $email The email address * @param string $s Size in pixels, defaults to 80px [ 1 - 2048 ] * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ] * @param string $r Maximum rating (inclusive) [ g | pg | r | x ] * @param bool $img True to return a complete IMG tag False for just the URL * @param array $atts Optional, additional key/value attributes to include in the IMG tag * @return String containing either just a URL or a complete image tag * @source https://gravatar.com/site/implement/images/php/ */ public static function getGravatarUrl($email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array()) { $url = 'https://www.gravatar.com/avatar/'; $url .= md5(strtolower(trim($email))); $url .= "?s=$s&d=$d&r=$r"; if ($img) { $url = '<img src="' . $url . '"'; foreach ($atts as $key => $val) { $url .= ' ' . $key . '="' . $val . '"'; } $url .= ' />'; } return $url; } /** * The progress of a query is updated, and if it changed it writes the new progress value to the DB * @param $queryId int * @param $force bool force the query to be calculated and updated */ public static function checkQueryUpdate($queryId, $force = false) { global $FACTORIES; $query = $FACTORIES::getQueryFactory()->get($queryId); if ($query->getIsClosed() == 1) { return; // query is already finished } $qF = new QueryFilter(QueryResultTuple::QUERY_ID, $queryId, "=", $FACTORIES::getQueryResultTupleFactory()); $jF = new JoinFilter($FACTORIES::getQueryResultTupleFactory(), ResultTuple::RESULT_TUPLE_ID, QueryResultTuple::RESULT_TUPLE_ID); $joined = $FACTORIES::getResultTupleFactory()->filter(array($FACTORIES::FILTER => $qF, $FACTORIES::JOIN => $jF)); $fullyEvaluated = true; $all = 0; $finishedCount = 0; for ($i = 0; $i < sizeof($joined[$FACTORIES::getResultTupleFactory()->getModelName()]); $i++) { /** @var $resultTuple ResultTuple */ $resultTuple = $joined[$FACTORIES::getResultTupleFactory()->getModelName()][$i]; if ($resultTuple->getIsFinal() == 0) { $fullyEvaluated = false; } else { $finishedCount++; } $all++; } $updated = $force; $progress = floor($finishedCount / $all * 100); if ($force) { $query->setProgress($progress); } if ($fullyEvaluated) { // all tuples of this query are final and therefore we can close the query $query->setIsClosed(1); $query->setProgress(100); $updated = true; } else if ($progress != $query->getProgress()) { $updated = true; $query->setProgress($progress); } if ($updated) { $FACTORIES::getQueryFactory()->update($query); } } /** * @param $resultTuples ResultTuple[] * @param $queryResultTuples QueryResultTuple[] * @param $excludingTuples int[] * @return ResultTuple */ public static function getTupleWeightedWithRankAndSigma($resultTuples, $queryResultTuples, $excludingTuples) { //global $DEBUG; if (sizeof($resultTuples) == 0) { return null; } $exclude = array(); foreach ($excludingTuples as $excludingTuple) { $exclude[$excludingTuple] = true; } $highestRank = 0; foreach ($queryResultTuples as $queryResultTuple) { if ($queryResultTuple->getRank() > $highestRank) { $highestRank = $queryResultTuple->getRank(); } } $totalCount = 0; //$DEBUG[] = "Getting tuple from " . sizeof($resultTuples) . " tuples, excluding " . sizeof($excludingTuples) . " ones.."; for ($i = 0; $i < sizeof($resultTuples); $i++) { if (isset($exclude[$resultTuples[$i]->getId()])) { continue; // exclude the already answered tuples } $add = 1; if ($resultTuples[$i]->getSigma() == -1) { $add += 2; // TODO: elaborate this value, or make it dependant from highest rank } $totalCount += $add + sqrt($highestRank - $queryResultTuples[$i]->getRank()); } if ($totalCount <= 0) { return null; } $random = random_int(0, $totalCount - 1); $currentCount = 0; for ($i = 0; $i < sizeof($resultTuples); $i++) { if (isset($exclude[$resultTuples[$i]->getId()])) { continue; // exclude the already answered tuples } $add = 1; if ($resultTuples[$i]->getSigma() == -1) { $add += 2; // TODO: elaborate this value, or make it dependant from highest rank } $currentCount += $add + sqrt($highestRank - $queryResultTuples[$i]->getRank()); if ($currentCount > $random) { return $resultTuples[$i]; } } return null; } /** * @param $resultSet1 ResultTuple * @param $resultSet2 ResultTuple * @param $randomOrder bool */ public static function prepare3CompareQuestion($resultSet1, $resultSet2, $randomOrder = true) { global $FACTORIES, $OBJECTS; $mediaObject1 = $FACTORIES::getMediaObjectFactory()->get($resultSet1->getObjectId1()); if (mt_rand(0, 1) == 0 || $randomOrder == false) { $mediaObject2 = $FACTORIES::getMediaObjectFactory()->get($resultSet1->getObjectId2()); $mediaObject3 = $FACTORIES::getMediaObjectFactory()->get($resultSet2->getObjectId2()); } else { $mediaObject2 = $FACTORIES::getMediaObjectFactory()->get($resultSet2->getObjectId2()); $mediaObject3 = $FACTORIES::getMediaObjectFactory()->get($resultSet1->getObjectId2()); } $value1 = new DataSet(); $value2 = new DataSet(); $value3 = new DataSet(); $value1->addValue('objData', array("serve.php?id=" . $mediaObject1->getChecksum())); $value2->addValue('objData', array("serve.php?id=" . $mediaObject2->getChecksum())); $value3->addValue('objData', array("serve.php?id=" . $mediaObject3->getChecksum())); $mediaType1 = $FACTORIES::getMediaTypeFactory()->get($mediaObject1->getMediaTypeId()); $mediaType2 = $FACTORIES::getMediaTypeFactory()->get($mediaObject2->getMediaTypeId()); $mediaType3 = $FACTORIES::getMediaTypeFactory()->get($mediaObject3->getMediaTypeId()); $value1->addValue('template', $mediaType1->getTemplate()); $value2->addValue('template', $mediaType2->getTemplate()); $value3->addValue('template', $mediaType3->getTemplate()); $OBJECTS['object1'] = $mediaObject1; $OBJECTS['object2'] = $mediaObject2; $OBJECTS['object3'] = $mediaObject3; $OBJECTS['value1'] = $value1; $OBJECTS['value2'] = $value2; $OBJECTS['value3'] = $value3; } /** * @param $mediaObject1 MediaObject * @param $mediaObject2 MediaObject * @param $randomOrder bool */ public static function prepare2CompareQuestion($mediaObject1, $mediaObject2, $randomOrder = true) { global $FACTORIES, $OBJECTS; $value1 = new DataSet(); $value2 = new DataSet(); if (random_int(0, 1) > 0 && $randomOrder) { $m = $mediaObject2; $mediaObject2 = $mediaObject1; $mediaObject1 = $m; } $value1->addValue('objData', array(new DataSet(array("data" => "serve.php/" . $mediaObject1->getChecksum(), "source" => $mediaObject1->getSource())))); $value2->addValue('objData', array(new DataSet(array("data" => "serve.php/" . $mediaObject2->getChecksum(), "source" => $mediaObject2->getSource())))); $mediaType1 = $FACTORIES::getMediaTypeFactory()->get($mediaObject1->getMediaTypeId()); $mediaType2 = $FACTORIES::getMediaTypeFactory()->get($mediaObject2->getMediaTypeId()); $value1->addValue('template', $mediaType1->getTemplate()); $value2->addValue('template', $mediaType2->getTemplate()); $OBJECTS['object1'] = $mediaObject1; $OBJECTS['object2'] = $mediaObject2; $OBJECTS['value1'] = $value1; $OBJECTS['value2'] = $value2; } /** * @param $playerId int * @return string null if player was not found */ public static function getPlayerNameById($playerId) { global $FACTORIES; return $FACTORIES::getPlayerFactory()->get($playerId)->getPlayerName(); } /** * @param $queries Query[] * @return Query */ public static function getQueryWeightedWithPriority($queries) { if (sizeof($queries) == 0) { return null; } $totalPriority = 0; foreach ($queries as $query) { $totalPriority += $query->getPriority() + 1; } $random = random_int(0, $totalPriority - 1); $currentPriority = 0; foreach ($queries as $query) { $currentPriority += $query->getPriority() + 1; if ($currentPriority > $random) { return $query; } } return $queries[sizeof($queries) - 1]; } /** * Converts a given string to hex code. * * @param string $string * string to convert * @return string converted string into hex */ public static function strToHex($string) { return implode(unpack("H*", $string)); } public static function getExtension($file) { $basename = explode(".", basename($file)); return strtolower($basename[sizeof($basename) - 1]); } /** * get the result tuple which consists of the two given media objects * @param $object1 MediaObject * @param $object2 MediaObject * @return ResultTuple */ public static function getResultTuple($object1, $object2) { global $FACTORIES; $qF1 = new QueryFilter(ResultTuple::OBJECT_ID1, $object1->getId(), "="); $qF2 = new QueryFilter(ResultTuple::OBJECT_ID2, $object2->getId(), "="); return $FACTORIES::getResultTupleFactory()->filter(array($FACTORIES::FILTER => array($qF1, $qF2)), true); } /** * Get a media object for the given checksum * @param $checksum string * @return MediaObject */ public static function getMediaObject($checksum) { global $FACTORIES; $qF = new QueryFilter(MediaObject::CHECKSUM, $checksum, "="); return $FACTORIES::getMediaObjectFactory()->filter(array($FACTORIES::FILTER => $qF), true); } /** * Get the media type for a given file. Type is determined by file extension. If the media type does not exist yet, it will be created. * @param $file string * @return MediaType */ public static function getMediaType($file) { global $FACTORIES; $extension = Util::getExtension($file); $qF = new QueryFilter(MediaType::EXTENSION, $extension, "="); $mediaType = $FACTORIES::getMediaTypeFactory()->filter(array($FACTORIES::FILTER => $qF), true); if ($mediaType == null) { // create this new media type $mediaType = new MediaType(0, $extension, $extension, null); $mediaType = $FACTORIES::getMediaTypeFactory()->save($mediaType); } return $mediaType; } /** * @param $mediaObjectId int * @return string */ public static function getMediaTypeNameForObject($mediaObjectId) { global $FACTORIES; $qF = new QueryFilter(MediaObject::MEDIA_OBJECT_ID, $mediaObjectId, "="); $jF = new JoinFilter($FACTORIES::getMediaTypeFactory(), MediaObject::MEDIA_TYPE_ID, MediaType::MEDIA_TYPE_ID); $joined = $FACTORIES::getMediaObjectFactory()->filter(array($FACTORIES::FILTER => $qF, $FACTORIES::JOIN => $jF)); if (sizeof($joined['MediaType']) == 0) { return "unknown"; } /** @var MediaType $mediaType */ $mediaType = $joined['MediaType'][0]; return $mediaType->getTypeName(); } /** * This filesize is able to determine the file size of a given file, also if it's bigger than 4GB which causes * some problems with the built-in filesize() function of PHP. * @param $file string Filepath you want to get the size from * @return int -1 if the file doesn't exist, else filesize */ public static function filesize($file) { if (!file_exists($file)) { return -1; } $fp = fopen($file, "rb"); $pos = 0; $size = 1073741824; fseek($fp, 0, SEEK_SET); while ($size > 1) { fseek($fp, $size, SEEK_CUR); if (fgetc($fp) === false) { fseek($fp, -$size, SEEK_CUR); $size = (int)($size / 2); } else { fseek($fp, -1, SEEK_CUR); $pos += $size; } } while (fgetc($fp) !== false) { $pos++; } return $pos; } /** * gives a security question * @return SessionQuestion */ public static function getSecurityQuestion() { global $FACTORIES; $question = null; $qF1 = new QueryFilter(ResultTuple::SIGMA, SECURITY_QUESTION_THRESHOLD, "<="); $qF2 = new QueryFilter(ResultTuple::SIGMA, 0, ">="); $oF = new RandOrderFilter(10); $resultTuples = $FACTORIES::getResultTupleFactory()->filter(array($FACTORIES::FILTER => array($qF1, $qF2), $FACTORIES::ORDER => $oF)); $questionType = SessionQuestion::TYPE_UNDEFINED; if (sizeof($resultTuples) >= 2 && mt_rand(0, 1) > 0) { $matching = array(); for ($i = 0; $i < sizeof($resultTuples); $i++) { for ($j = $i + 1; $j < sizeof($resultTuples); $j++) { if ($resultTuples[$i]->getObjectId1() == $resultTuples[$j]->getObjectId1() && $resultTuples[$i]->getObjectId1() != $resultTuples[$j]->getObjectId1()) { $matching = array($resultTuples[$i], $resultTuples[$j]); $i = sizeof($resultTuples); break; } } } if (sizeof($matching) > 0) { // three compare $questionType = SessionQuestion::TYPE_COMPARE_TRIPLE; $mediaObject1 = $FACTORIES::getMediaObjectFactory()->get($matching[0]->getObjectId1()); $mediaObject2 = $FACTORIES::getMediaObjectFactory()->get($matching[0]->getObjectId2()); $mediaObject3 = $FACTORIES::getMediaObjectFactory()->get($matching[1]->getObjectId2()); $question = new SessionQuestion($questionType, array($mediaObject1, $mediaObject2, $mediaObject3), $matching); } } if (sizeof($resultTuples) > 0 && $questionType == SessionQuestion::TYPE_UNDEFINED) { // two compare $questionType = SessionQuestion::TYPE_COMPARE_TWO; $mediaObject1 = $FACTORIES::getMediaObjectFactory()->get($resultTuples[0]->getObjectId1()); $mediaObject2 = $FACTORIES::getMediaObjectFactory()->get($resultTuples[0]->getObjectId2()); $question = new SessionQuestion($questionType, array($mediaObject1, $mediaObject2), array($resultTuples[0])); } return $question; } /** * Resizes the given image if it's too big * @param $path string */ public static function resizeImage($path) { $size = getimagesize($path); if ($size[0] <= IMAGE_MAX_WIDTH && $size[1] <= IMAGE_MAX_HEIGHT) { return; // we don't need to do a resize here } $ratio = $size[0] / $size[1]; // width/height if ($ratio > 1) { $width = IMAGE_MAX_WIDTH; $height = IMAGE_MAX_HEIGHT / $ratio; } else { $width = IMAGE_MAX_WIDTH * $ratio; $height = IMAGE_MAX_HEIGHT; } $src = imagecreatefromstring(file_get_contents($path)); $dst = imagecreatetruecolor($width, $height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1]); imagedestroy($src); imagejpeg($dst, $path); imagedestroy($dst); } /** * Tries to determine the IP of the client. * @return string 0.0.0.0 or the client IP */ public static function getIP() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } if (!$ip) { return "0.0.0.0"; } return $ip; } /** * Returns the username from the given userId * @param $id int ID for the user * @return string username or unknown-id */ public static function getUsernameById($id) { global $FACTORIES; $user = $FACTORIES::getUserFactory()->get($id); if ($user === null) { return "Unknown-$id"; } return $user->getUsername(); } public static function getUserAgentHeader() { return json_encode(getallheaders()); } /** * Cut a string to a certain number of letters. If the string is too long, instead replaces the last three letters with ... * @param $string String you want to short * @param $length Number of Elements you want the string to have * @return string Formatted string */ public static function shortenstring($string, $length) { // shorten string that would be too long $return = "<span title='$string'>"; if (strlen($string) > $length) { $return .= substr($string, 0, $length - 3) . "..."; } else { $return .= $string; } $return .= "</span>"; return $return; } /** * Formats the number with 1000s separators * @param $num int|string * @return string */ static function number($num = "") { $value = "$num"; if (strlen($value) == 0) { return "0"; } $string = $value[0]; for ($x = 1; $x < strlen($value); $x++) { if ((strlen($value) - $x) % 3 == 0) { $string .= "'"; } $string .= $value[$x]; } return $string; } /** * This sends a given email with text and subject to the address. * * @param string $address * email address of the receiver * @param string $subject * subject of the email * @param string $text * html content of the email * @return true on success, false on failure */ public static function sendMail($address, $subject, $text) { $header = "Content-type: text/html; charset=utf8\r\n"; $header .= "MIME-Version: 1.0\r\n"; $header .= "From: " . DEFAULT_EMAIL_FROM . " <" . NO_REPLY_EMAIL . ">\r\n"; if (!mail($address, $subject, $text, $header)) { return false; } return true; } /** * Generates a random string with mixedalphanumeric chars * * @param int $length * length of random string to generate * @return string random string */ public static function randomString($length) { $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $result = ""; for ($x = 0; $x < $length; $x++) { $result .= $charset[mt_rand(0, strlen($charset) - 1)]; } return $result; } /** * Refreshes the page with the current url, also includes the query string. */ public static function refresh() { global $_SERVER; $url = $_SERVER['PHP_SELF']; if (strlen($_SERVER['QUERY_STRING']) > 0) { $url .= "?" . $_SERVER['QUERY_STRING']; } header("Location: $url"); die(); } /** * @param int $queryId * @param int $lastId * @return SessionQuestion */ public static function getNextPruneQuestion($queryId = 0, $lastId = 0) { global $FACTORIES; $qF = new QueryFilter(ResultTuple::IS_FINAL, "0", "="); $oF = new OrderFilter(ResultTuple::RESULT_TUPLE_ID, "ASC LIMIT 1"); $options = array($FACTORIES::FILTER => array($qF), $FACTORIES::ORDER => $oF); if ($queryId > 0) { $options[$FACTORIES::JOIN] = new JoinFilter($FACTORIES::getQueryResultTupleFactory(), ResultTuple::RESULT_TUPLE_ID, QueryResultTuple::RESULT_TUPLE_ID); $options[$FACTORIES::FILTER][] = new QueryFilter(QueryResultTuple::QUERY_ID, $queryId, "=", $FACTORIES::getQueryResultTupleFactory()); } if ($lastId > 0) { $options[$FACTORIES::FILTER][] = new QueryFilter(ResultTuple::RESULT_TUPLE_ID, $lastId, ">", $FACTORIES::getResultTupleFactory()); } $resultTuple = $FACTORIES::getResultTupleFactory()->filter($options); if ($resultTuple == null || (sizeof($options[$FACTORIES::FILTER]) > 0 && sizeof($resultTuple['ResultTuple']) == 0)) { return null; } if (sizeof($options[$FACTORIES::FILTER]) > 0) { $resultTuple = $resultTuple['ResultTuple'][0]; } return new SessionQuestion( SessionQuestion::TYPE_COMPARE_TWO, array($FACTORIES::getMediaObjectFactory()->get($resultTuple->getObjectId1()), $FACTORIES::getMediaObjectFactory()->get($resultTuple->getObjectId2())), array($resultTuple) ); } /** * @param $queryId int * @param $lastId int * @return int */ public static function getPruneLeft($queryId, $lastId) { global $FACTORIES; $qF1 = new QueryFilter(ResultTuple::IS_FINAL, "0", "="); $oF = new OrderFilter(ResultTuple::RESULT_TUPLE_ID, "ASC"); $jF = new JoinFilter($FACTORIES::getQueryResultTupleFactory(), ResultTuple::RESULT_TUPLE_ID, QueryResultTuple::RESULT_TUPLE_ID); $qF2 = new QueryFilter(QueryResultTuple::QUERY_ID, $queryId, "=", $FACTORIES::getQueryResultTupleFactory()); $qF3 = new QueryFilter(ResultTuple::RESULT_TUPLE_ID, $lastId, ">", $FACTORIES::getResultTupleFactory()); $joined = $FACTORIES::getResultTupleFactory()->filter(array($FACTORIES::FILTER => array($qF1, $qF2, $qF3), $FACTORIES::JOIN => $jF, $FACTORIES::ORDER => $oF)); return sizeof($joined[$FACTORIES::getResultTupleFactory()->getModelName()]); } /** * @param $query Query * @return int[] */ public static function getQueryEvaluationProgress($query) { global $FACTORIES; $oF = new OrderFilter(ResultTuple::RESULT_TUPLE_ID, "ASC"); $jF = new JoinFilter($FACTORIES::getQueryResultTupleFactory(), ResultTuple::RESULT_TUPLE_ID, QueryResultTuple::RESULT_TUPLE_ID); $qF = new QueryFilter(QueryResultTuple::QUERY_ID, $query->getId(), "=", $FACTORIES::getQueryResultTupleFactory()); $joined = $FACTORIES::getResultTupleFactory()->filter(array($FACTORIES::FILTER => $qF, $FACTORIES::JOIN => $jF, $FACTORIES::ORDER => $oF)); $progress = array(0, 0, 0); /** @var $resultTuples ResultTuple[] */ $resultTuples = $joined[$FACTORIES::getResultTupleFactory()->getModelName()]; foreach ($resultTuples as $resultTuple) { $progress[0]++; // total if ($resultTuple->getIsFinal() == 1) { $progress[1]++; // finished } else if ($resultTuple->getSigma() >= 0) { $progress[2]++; // partial } } return $progress; } /** * @param $answerSession AnswerSession */ public static function saveGame($answerSession) { // TODO: save game } /** * Gets the userinfo from an oauth token from google * @param $accessToken * @return string */ public static function getUserinfo($accessToken) { return file_get_contents("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" . $accessToken); } }
s3inlc/cineast-evaluator
inc/Util.class.php
PHP
mit
24,052
const React = require('react') const Layout = require('./src/components/layout').default // Logs when the client route changes exports.onRouteUpdate = ({ location, prevLocation }) => { const body = document.querySelector('body') body.setAttribute('data-current-page', location.pathname) body.setAttribute('data-previous-page', prevLocation ? prevLocation.pathname : '/') } // Wraps every page in a component exports.wrapPageElement = ({ element, props }) => <Layout {...props}>{element}</Layout>
yowainwright/yowainwright.github.io
gatsby-browser.js
JavaScript
mit
504
<?php session_start(); include "../connection.php"; $error = false; if (isset($_SESSION['auth']) && $_SESSION['auth'] != false) { header('Location: index.php'); } else { $_SESSION['auth'] = false; } if (isset($_POST['username']) && isset($_POST['password'])) { // print_r($_POST); $username = $_POST['username']; $password = $_POST['password']; $query = mysqli_query($conn, "SELECT * FROM `user` WHERE `username`= '" . $username . "'") or die($conn); if (mysqli_num_rows($query) > 0) { $query = mysqli_query($conn, "SELECT * FROM `user` WHERE `username` = '" . $username . "' AND `password` = '" . $password . "'"); if (mysqli_num_rows($query) > 0) { $_SESSION['auth'] = $username; header('Location: index.php'); } else { $error = 'Mật khẩu không chính xác'; } } else { $error = 'Tài khoản không chính xác'; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <meta charset="utf-8"/> <title>Login Page - Ace Admin</title> <meta name="description" content="User login page"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/> <!-- bootstrap & fontawesome --> <link rel="stylesheet" href="assets/css/bootstrap.min.css"/> <link rel="stylesheet" href="assets/font-awesome/4.5.0/css/font-awesome.min.css"/> <!-- text fonts --> <link rel="stylesheet" href="assets/css/fonts.googleapis.com.css"/> <!-- ace styles --> <link rel="stylesheet" href="assets/css/ace.min.css"/> <!--[if lte IE 9]> <link rel="stylesheet" href="assets/css/ace-part2.min.css"/> <![endif]--> <link rel="stylesheet" href="assets/css/ace-rtl.min.css"/> <!--[if lte IE 9]> <link rel="stylesheet" href="assets/css/ace-ie.min.css"/> <![endif]--> <!-- HTML5shiv and Respond.js for IE8 to support HTML5 elements and media queries --> <!--[if lte IE 8]> <script src="assets/js/html5shiv.min.js"></script> <script src="assets/js/respond.min.js"></script> <![endif]--> </head> <body class="login-layout"> <div class="main-container"> <div class="main-content"> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <div class="login-container"> <?php if ($error != false) { ?> <div class="alert alert-warning"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Cảnh báo</strong> <?php echo $error ?> </div> <?php } ?> <div class="center"> <h1> <i class="ace-icon fa fa-leaf green"></i> <span class="red">Ace</span> <span class="white" id="id-text2">Application</span> </h1> <h4 class="blue" id="id-company-text">&copy; Company Name</h4> </div> <div class="space-6"></div> <div class="position-relative"> <div id="login-box" class="login-box visible widget-box no-border"> <div class="widget-body"> <div class="widget-main"> <h4 class="header blue lighter bigger"> <i class="ace-icon fa fa-coffee green"></i> Please Enter Your Information </h4> <div class="space-6"></div> <form action="" method="post"> <fieldset> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="text" class="form-control" name="username" placeholder="Username"/> <i class="ace-icon fa fa-user"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="password" class="form-control" name="password" placeholder="Password"/> <i class="ace-icon fa fa-lock"></i> </span> </label> </form> <div class="space"></div> <div class="clearfix"> <label class="inline"> <input type="checkbox" class="ace"/> <span class="lbl"> Remember Me</span> </label> <button type="submit" class="width-35 pull-right btn btn-sm btn-primary"> <i class="ace-icon fa fa-key"></i> <span class="bigger-110">Login</span> </button> </div> <div class="space-4"></div> </fieldset> </form> <div class="social-or-login center"> <span class="bigger-110">Or Login Using</span> </div> <div class="space-6"></div> <div class="social-login center"> <a class="btn btn-primary"> <i class="ace-icon fa fa-facebook"></i> </a> <a class="btn btn-info"> <i class="ace-icon fa fa-twitter"></i> </a> <a class="btn btn-danger"> <i class="ace-icon fa fa-google-plus"></i> </a> </div> </div><!-- /.widget-main --> <div class="toolbar clearfix"> <div> <a href="#" data-target="#forgot-box" class="forgot-password-link"> <i class="ace-icon fa fa-arrow-left"></i> I forgot my password </a> </div> <div> <a href="#" data-target="#signup-box" class="user-signup-link"> I want to register <i class="ace-icon fa fa-arrow-right"></i> </a> </div> </div> </div><!-- /.widget-body --> </div><!-- /.login-box --> <div id="forgot-box" class="forgot-box widget-box no-border"> <div class="widget-body"> <div class="widget-main"> <h4 class="header red lighter bigger"> <i class="ace-icon fa fa-key"></i> Retrieve Password </h4> <div class="space-6"></div> <p> Enter your email and to receive instructions </p> <form> <fieldset> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="email" class="form-control" placeholder="Email"/> <i class="ace-icon fa fa-envelope"></i> </span> </label> <div class="clearfix"> <button type="button" class="width-35 pull-right btn btn-sm btn-danger"> <i class="ace-icon fa fa-lightbulb-o"></i> <span class="bigger-110">Send Me!</span> </button> </div> </fieldset> </form> </div><!-- /.widget-main --> <div class="toolbar center"> <a href="#" data-target="#login-box" class="back-to-login-link"> Back to login <i class="ace-icon fa fa-arrow-right"></i> </a> </div> </div><!-- /.widget-body --> </div><!-- /.forgot-box --> <div id="signup-box" class="signup-box widget-box no-border"> <div class="widget-body"> <div class="widget-main"> <h4 class="header green lighter bigger"> <i class="ace-icon fa fa-users blue"></i> New User Registration </h4> <div class="space-6"></div> <p> Enter your details to begin: </p> <form> <fieldset> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="email" class="form-control" placeholder="Email"/> <i class="ace-icon fa fa-envelope"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="text" class="form-control" name="username" placeholder="Username"/> <i class="ace-icon fa fa-user"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="password" class="form-control" name="password" placeholder="Password"/> <i class="ace-icon fa fa-lock"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="password" class="form-control" placeholder="Repeat password"/> <i class="ace-icon fa fa-retweet"></i> </span> </label> <label class="block"> <input type="checkbox" class="ace"/> <span class="lbl"> I accept the <a href="#">User Agreement</a> </span> </label> <div class="space-24"></div> <div class="clearfix"> <button type="reset" class="width-30 pull-left btn btn-sm"> <i class="ace-icon fa fa-refresh"></i> <span class="bigger-110">Reset</span> </button> <button type="button" class="width-65 pull-right btn btn-sm btn-success"> <span class="bigger-110">Register</span> <i class="ace-icon fa fa-arrow-right icon-on-right"></i> </button> </div> </fieldset> </form> </div> <div class="toolbar center"> <a href="#" data-target="#login-box" class="back-to-login-link"> <i class="ace-icon fa fa-arrow-left"></i> Back to login </a> </div> </div><!-- /.widget-body --> </div><!-- /.signup-box --> </div><!-- /.position-relative --> <div class="navbar-fixed-top align-right"> <br/> &nbsp; <a id="btn-login-dark" href="#">Dark</a> &nbsp; <span class="blue">/</span> &nbsp; <a id="btn-login-blur" href="#">Blur</a> &nbsp; <span class="blue">/</span> &nbsp; <a id="btn-login-light" href="#">Light</a> &nbsp; &nbsp; &nbsp; </div> </div> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.main-content --> </div><!-- /.main-container --> <!-- basic scripts --> <!--[if !IE]> --> <script src="assets/js/jquery-2.1.4.min.js"></script> <!-- <![endif]--> <!--[if IE]> <script src="assets/js/jquery-1.11.3.min.js"></script> <![endif]--> <script type="text/javascript"> if ('ontouchstart' in document.documentElement) document.write("<script src='assets/js/jquery.mobile.custom.min.js'>" + "<" + "/script>"); </script> <!-- inline scripts related to this page --> <script type="text/javascript"> jQuery(function ($) { $(document).on('click', '.toolbar a[data-target]', function (e) { e.preventDefault(); var target = $(this).data('target'); $('.widget-box.visible').removeClass('visible');//hide others $(target).addClass('visible');//show target }); }); //you don't need this, just used for changing background jQuery(function ($) { $('#btn-login-dark').on('click', function (e) { $('body').attr('class', 'login-layout'); $('#id-text2').attr('class', 'white'); $('#id-company-text').attr('class', 'blue'); e.preventDefault(); }); $('#btn-login-light').on('click', function (e) { $('body').attr('class', 'login-layout light-login'); $('#id-text2').attr('class', 'grey'); $('#id-company-text').attr('class', 'blue'); e.preventDefault(); }); $('#btn-login-blur').on('click', function (e) { $('body').attr('class', 'login-layout blur-login'); $('#id-text2').attr('class', 'white'); $('#id-company-text').attr('class', 'light-blue'); e.preventDefault(); }); }); </script> </body> </html>
navatech-trainning/fashion-shopping
admin/login.php
PHP
mit
17,076
// Copyright (c) Sandeep Mistry. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "BLEConstantCharacteristic.h" BLEConstantCharacteristic::BLEConstantCharacteristic(const char* uuid, const unsigned char value[], unsigned char length) : BLEFixedLengthCharacteristic(uuid, BLERead, (unsigned char)0) { this->_valueLength = this->_valueSize = length; this->_value = (unsigned char*)value; } BLEConstantCharacteristic::BLEConstantCharacteristic(const char* uuid, const char* value) : BLEFixedLengthCharacteristic(uuid, BLERead, (unsigned char)0) { this->_valueLength = this->_valueSize = strlen(value); this->_value = (unsigned char*)value; } BLEConstantCharacteristic::~BLEConstantCharacteristic() { this->_value = NULL; // null so super destructor doesn't try to free } bool BLEConstantCharacteristic::setValue(const unsigned char /*value*/[], unsigned char /*length*/) { return false; } bool BLEConstantCharacteristic::setValue(const char* /*value*/) { return false; }
sandeepmistry/arduino-BLEPeripheral
src/BLEConstantCharacteristic.cpp
C++
mit
1,075
''' Example which moves objects around in a 2D world. This example requires matplotlib. The ros package doesnt have this as a rosdep though, since nothing else needs it. Just do a system install of matplotlib. ''' import roslib; roslib.load_manifest('hierarchical_interactive_planning') import numpy as np from scipy import linalg import hierarchical_interactive_planning as hip ###################################################################################################################### # World ###################################################################################################################### class MoveStuffWorld: def __init__(self, obs_map, objects, eps=1.0): ''' Args: objects (dict): Mapping from string object names to numpy arrays of their positions. ''' self.obs_map = obs_map self.objects = objects self.eps = eps def execute(self, op_instance): op_name = op_instance.operator_name if op_name == 'MoveTo': x_des = op_instance.target.args[0].val self.objects['robot'].position = x_des else: raise ValueError('Unknown operator: %s' % str(operator.name)) def entails(self, f): if isinstance(f, hip.ConjunctionOfFluents): return np.all([self.entails(fluent) for fluent in f.fluents]) if f.pred == RobotAtLoc: x_robot = self.objects['robot'].position x_des = f.args[0].val if linalg.norm(x_robot - x_des) < self.eps: return True else: return False else: raise ValueError('Unknown predicate: %s' % str(f.pred)) def contradicts(self, f): return False def plan_path(self, x_start, x_end, n_graph_points=1000, graph_conn_dist=1.0): '''Plan a collision free path from x_start to x_end. Returns: path (list of np.array): Path (or None if no path found). ''' # build a random graph x_min, x_max, y_min, y_max = self.obs_map.extent() points = np.zeros((n_graph_points, 2)) points[:,0] = np.random.uniform(x_min, x_max, n_graph_points) points[:,1] = np.random.uniform(y_min, y_max, n_graph_points) def action_generator(state): for neighbor in range(len(points)): d = linalg.norm(points[state] - points[neighbor]) if d < conn_dist: yield neighbor, neighbor, d # action, next_state, cost p = a_star.a_star( start, lambda s: s == goal, action_generator, lambda s: linalg.norm(points[goal] - points[s]) ) class Robot: def __init__(self, position): self.position = position class Box: def __init__(self, center, r): self.center = np.array(center) self.r = r ###################################################################################################################### # Predicates ###################################################################################################################### RobotAtLoc = hip.Predicate('RobotAtLoc', ['loc']) RobotLocFree = hip.Predicate('RobotLocFree', ['robot', 'loc']) ###################################################################################################################### # Suggesters ###################################################################################################################### def robot_path_suggester(world, current_state, goal): for f in goal.fluents: if f.pred == RobotAtLoc: x_des = f.args[0].val yield [] ###################################################################################################################### # Operators ###################################################################################################################### loc = hip.Variable('loc') path = hip.Variable('path') MoveTo = hip.Operator( 'MoveTo', target = RobotAtLoc((loc,)), suggesters = {path:robot_path_suggester}, preconditions = [], side_effects = hip.ConjunctionOfFluents([]), primitive = False, ) operators = [MoveTo] ###################################################################################################################### # Main ###################################################################################################################### def draw_objects(objects): for obj_name, obj in objects.items(): if isinstance(obj, Box): plt.plot([obj.center[0]], [obj.center[1]], 'x') vertices = [] r = obj.r for offset in [(r, r), (r, -r), (-r, -r), (-r, r)]: vertices.append(obj.center + np.array(offset)) vertices = np.array(vertices) plt.fill(vertices[:,0], vertices[:,1], 'm') elif isinstance(obj, Robot): plt.plot([obj.position[0]], [obj.position[1]], 'go', markersize=40) class ObstacleMap: def __init__(self, obs_array, res): '''2D obstacle map class. Args: obs_array (np.array of np.bool): Occupancy array. res (float): Size (height and width) of each cell in the occupancy array. ''' self.obs_array = obs_array self.res = res def pos_to_ind(self, p): '''Return array index for cell that contains x,y position. ''' ii, jj = np.array(p) / self.res return int(ii), int(jj) def ind_to_pos(self, ind): '''Return x,y position of center point of cell specified by index. ''' return np.array(ind) * self.res + 0.5 * self.res def is_occupied(self, p): ii, jj = self.pos_to_ind(p) return self.obs_array[ii,jj] def any_occupied(self, x0, x1, y0, y1): '''Return true if any cells within the bounding box are occupied. ''' i0, j0 = self.pos_to_ind((x0, y0)) i1, j1 = self.pos_to_ind((x1, y1)) i0 = max(0, i0) i1 = max(0, i1) j0 = max(0, j0) j1 = max(0, j1) return self.obs_array[i0:i1,j0:j1].any() def points(self): points = [] for ii in range(self.obs_array.shape[0]): for jj in range(self.obs_array.shape[1]): p = self.ind_to_pos((ii, jj)) points.append(p) return np.array(points) def occupied_points(self): points = [] for ii in range(self.obs_array.shape[0]): for jj in range(self.obs_array.shape[1]): p = self.ind_to_pos((ii, jj)) if self.is_occupied(p): points.append(p) return np.array(points) def extent(self): x_min, y_min = self.ind_to_pos((0, 0)) s = self.obs_array.shape x_max, y_max = self.ind_to_pos((s[0]-1, s[1]-1)) return x_min, y_min, x_max, y_max if __name__ == '__main__': import sys from matplotlib import pyplot as plt # load world map res = 1.0 obs_arr = plt.imread(sys.argv[1])[::-1,:].T obs_arr = obs_arr < obs_arr.max() / 2.0 obs_map = ObstacleMap(obs_arr, res) objects = { 'robot': Robot(np.array((50., 50.))), 'box1': Box((5., 5.), 4.), } start_state = hip.ConjunctionOfFluents([]) world = MoveStuffWorld(obs_map, objects) goal_symbol = hip.Symbol(np.array((10., 10.))) goal = hip.ConjunctionOfFluents([RobotAtLoc((goal_symbol,))]) # run HPN to generate plan tree = hip.HPlanTree() hip.hpn(operators, start_state, goal, world, tree=tree) fig = plt.figure() points_occ = obs_map.occupied_points() plt.plot(points_occ[:,0], points_occ[:,-1], 'bo') if 0: w = 5 occ = [] free = [] for x, y in obs_map.points(): if obs_map.any_occupied(x-w, x+w, y-w, y+w): occ.append((x, y)) else: free.append((x, y)) occ = np.array(occ) free = np.array(free) plt.plot(occ[:,0], occ[:,1], 'r.') plt.plot(free[:,0], free[:,1], 'g.') draw_objects(objects) x_min, x_max, y_min, y_max = obs_map.extent() plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.show()
jonbinney/python-planning
python_task_planning/examples/move_stuff/move_stuff.py
Python
mit
8,400
#ifndef __tcode_transport_tcp_pipeline_builder_h__ #define __tcode_transport_tcp_pipeline_builder_h__ #include <system_error> #include <common/rc_ptr.hpp> namespace tcode { namespace transport { class event_loop; namespace tcp { class pipeline; class pipeline_builder : public tcode::ref_counted< pipeline_builder > { public: pipeline_builder( void ){} virtual ~pipeline_builder( void ){} virtual event_loop& channel_loop( void ) = 0; virtual bool build( pipeline& p ){ return false; } private: }; }}} #endif
aoziczero/tcode
old/transport/tcp/pipeline_builder.hpp
C++
mit
526
using System; using UsgsClient.Common; namespace UsgsClient.Quakes { public class QuakesUriBuilder : IQuakesUriBuilder { private readonly IConfig _config; public QuakesUriBuilder(IConfig config) { this._config = config; } public Uri ForDetail( string quakeId) { var usgsUri = $"{_config.FeedUri}/detail/{quakeId}.geojson";; return new Uri(usgsUri); } public Uri ForSummary( Magnitude magnitude, Timeframe timeframe) { var usgsUri = $"{_config.FeedUri}/summary/{{magnitude}}_{{timeframe}}.geojson";; return new Uri(usgsUri .Replace("{magnitude}", MagnitudeTokenFormatter.Format(magnitude)) .Replace("{timeframe}", TimeframeTokenFormatter.Format(timeframe))); } } }
overridethis/usgsclient
UsgsClient/Quakes/QuakesUriBuilder.cs
C#
mit
907
package hudson.plugins.keepSlaveOffline; import org.kohsuke.stapler.DataBoundConstructor; import hudson.Extension; import hudson.model.Node; import hudson.model.Queue.FlyweightTask; import hudson.model.Queue.Task; import hudson.model.queue.CauseOfBlockage; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; public class OfflineKeeper extends NodeProperty<Node>{ private String reason; @DataBoundConstructor public OfflineKeeper(String reason){ this.reason=reason; } public String getReason(){ return reason; } @Extension // this marker indicates Hudson that this is an implementation of an extension point. public static final class NodePropertyDescriptorImpl extends NodePropertyDescriptor { public static final NodePropertyDescriptorImpl DESCRIPTOR = new NodePropertyDescriptorImpl(); public NodePropertyDescriptorImpl(){ super(OfflineKeeper.class); } /** * This human readable name is used in the configuration screen. */ public String getDisplayName() { return "Keep this slave offline after Hudson restart"; } } }
jenkinsci/keep-slave-offline
src/main/java/hudson/plugins/keepSlaveOffline/OfflineKeeper.java
Java
mit
1,221
package com.example.alexeyglushkov.wordteacher.quizletlistmodules.setlistmodule.view; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.alexeyglushkov.quizletservice.entities.QuizletSet; import com.example.alexeyglushkov.wordteacher.R; import com.example.alexeyglushkov.wordteacher.listmodule.view.BaseListAdaptor; import com.example.alexeyglushkov.wordteacher.listmodule.view.SimpleListFragment; /** * Created by alexeyglushkov on 07.08.16. */ public class QuizletSetListFragment extends SimpleListFragment<QuizletSet> { //// Creation, initialization, restoration public static QuizletSetListFragment create() { QuizletSetListFragment fragment = new QuizletSetListFragment(); fragment.initialize(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_quizlet_cards, container, false); } //// Creation Methods @Override protected BaseListAdaptor createAdapter() { return createSetAdapter(); } private QuizletSetAdapter createSetAdapter() { QuizletSetAdapter adapter = new QuizletSetAdapter(new QuizletSetAdapter.Listener() { @Override public void onSetClicked(View view, QuizletSet set) { QuizletSetListFragment.this.getPresenter().onRowClicked(set); } @Override public void onMenuClicked(View view, QuizletSet set) { QuizletSetListFragment.this.getPresenter().onRowMenuClicked(set, view); } }); return adapter; } }
soniccat/android-taskmanager
app_wordteacher_old/src/main/java/com/example/alexeyglushkov/wordteacher/quizletlistmodules/setlistmodule/view/QuizletSetListFragment.java
Java
mit
1,783
@extends('app') @section('header-text') Log into your account @endsection @section('header-subtext') Enter in your account information below @endsection @section('content') <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Login</div> <div class="panel-body"> @if (count($errors) > 0) <div class="alert alert-danger"> <strong>Whoops!</strong> There were some problems with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form class="form-horizontal" role="form" method="POST" action="{{ route('users.auth.doLogin') }}"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> @if ($message = \Session::pull('message')) <div class="form-group"> <div class="col-md-push-4 col-md-6"> <p class="text-success">{{ $message }}</p> </div> </div> @endif @if ( config('services.github.client_id') ) <div class="form-group"> <div class="col-md-push-4 col-md-6"> <a href="{{ route('users.auth.oauth', ['driver' => 'github']) }}" class="btn btn-block btn-social btn-github"> <i class="fa fa-github"></i> Sign in with GitHub </a> </div> </div> @endif <div class="form-group"> <label class="col-md-4 control-label">E-Mail Address</label> <div class="col-md-6"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span> <input type="email" class="form-control" name="email" value="{{ old('email') }}"> </div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Password</label> <div class="col-md-6"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-lock fa-fw"></i></span> <input type="password" class="form-control" name="password"> </div> </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <div class="checkbox"> <label> <input type="checkbox" name="remember"> Remember Me </label> </div> </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary" style="margin-right: 15px;"> Login </button> <a href="{{ route('users.auth.recover') }}">Forgot Your Password?</a> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
FujiMakoto/Pixel
resources/views/users/auth/login.blade.php
PHP
mit
3,349
import { handleActions } from 'redux-actions'; import { Map, OrderedMap } from 'immutable'; import initialState from '../store/initialState'; const App = handleActions({ WINDOW_LOADED: (state) => ({ ...state, windowLoaded: true }), CLOSE_LEGAL_HINT: (state) => ({ ...state, showLegalHint: false }), CONFIGURE_FIREBASE: (state, action) => ({ ...state, fireRef: action.payload }), SAVE_UID: (state, action) => ({ ...state, uid: action.payload }), SAVE_NAME: (state, action) => ({ ...state, userName: action.payload }), SAVE_USER_REF: (state, action) => ({ ...state, userRef: action.payload }), CONNECTED_TO_CHAT: (state) => ({ ...state, records: state.records.set('system:connected_to_chat', { msg: '歡迎加入聊天室!', user: 'system', send_time: Date.now(), user_color: '#ffc106' }) }), SET_MSG_TO_LIST: (state, action) => ({ ...state, records: OrderedMap(action.payload).map(record => ({ ...record, inActive: true })) }), ADD_MSG_TO_LIST: (state, action) => ({ ...state, records: state.records.set(action.payload.key, action.payload.value) }), REMOVE_MSG_FROM_LIST: (state, action) => ({ ...state, records: state.records.delete(action.payload) }), SET_WILL_SCROLL: (state, action) => ({ ...state, willScroll: action.payload }), SWITCH_MONITOR: (state, action) => ({ ...state, monitor: action.payload }), SET_PRESENCE: (state, action) => ({ ...state, presence: Map(action.payload) }), COUNTER_CHANGED: (state, action) => ({ ...state, onlineCounter: state.onlineCounter.update( state.presence.get(action.payload.key), 1, v => v - 1 ).update( action.payload.value.toString(), 0, v => v + 1 ), presence: state.presence.set(action.payload.key, action.payload.value) }), COUNTER_ADDED: (state, action) => ({ ...state, onlineCounter: state.onlineCounter.update( action.payload.value.toString(), 0, v => v + 1 ), presence: state.presence.set(action.payload.key, action.payload.value) }), COUNTER_REMOVED: (state, action) => ({ ...state, onlineCounter: state.onlineCounter.update( action.payload.value.toString(), 1, v => v - 1 ), presence: state.presence.delete(action.payload.key) }), SET_PLAYER: (state, action) => ({ ...state, player: action.payload }), TOGGLE_SHOW_CHAT: (state) => ({ ...state, showChat: !state.showChat }), CONTROL_UP: state => ({ ...state, control: 'up' }), CONTROL_DOWN: state => ({ ...state, control: 'down' }), CONTROL_LEFT: state => ({ ...state, control: 'left', controlStop: false }), CONTROL_RIGHT: state => ({ ...state, control: 'right', controlStop: false }), CONTROL_STOP: state => ({ ...state, control: 'stop' }), CONTROL_PAUSE: state => ({ ...state, control: state.pause ? 'pause' : 'play' }), CONTROL_SET_PAUSE: state => ({ ...state, control: 'pause' }), CONTROL_SET_PLAY: state => ({ ...state, control: 'play' }), STOP_CONTROL: state => ({ ...state, controlStop: true }), CONTROL_INTERACT: state => ({ ...state, control: 'interact' }), ON_ERROR: (state, action) => ({ ...state, players: state.players.update( action.payload.toString(), r => r.set("error", true) ) }), ON_LOAD: (state, action) => ({ ...state, players: state.players.update( action.payload.toString(), r => r.set("error", false) ) }), UPDATE_FRAMES: (state, action) => ({ ...state, players: state.players.update( action.payload.monitor.toString(), r => r.update("frames", frames => frames.push(action.payload.src).takeLast(10)) ) }), TOGGLE_LOADING: (state) => ({ ...state, loading: !state.loading }), PAUSE: (state) => ({ ...state, pause: !state.pause }), RELOAD: state => ({ ...state, reload: Math.floor(Math.random() * 10000).toString(), lastReload: state.reload }) }, initialState); export default App;
NTU-ArtFest22/Monitor-web
src/Reducers/index.js
JavaScript
mit
4,611
'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactcss = require('reactcss'); var _reactcss2 = _interopRequireDefault(_reactcss); var SliderPointer = (function (_ReactCSS$Component) { _inherits(SliderPointer, _ReactCSS$Component); function SliderPointer() { _classCallCheck(this, SliderPointer); _get(Object.getPrototypeOf(SliderPointer.prototype), 'constructor', this).apply(this, arguments); } _createClass(SliderPointer, [{ key: 'classes', value: function classes() { return { 'default': { picker: { width: '14px', height: '14px', borderRadius: '6px', transform: 'translate(-7px, -1px)', backgroundColor: 'rgb(248, 248, 248)', boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)' } } }; } }, { key: 'render', value: function render() { return _react2['default'].createElement('div', { style: this.styles().picker }); } }]); return SliderPointer; })(_reactcss2['default'].Component); module.exports = SliderPointer;
9o/react-color
lib/components/slider/SliderPointer.js
JavaScript
mit
3,128
'use strict'; // Declare app level module which depends on views, and components angular.module('collegeScorecard', [ 'ngRoute', 'ui.bootstrap', 'nemLogging', 'uiGmapgoogle-maps', 'collegeScorecard.common', 'collegeScorecard.footer', 'collegeScorecard.home', 'collegeScorecard.schools', 'collegeScorecard.compare', 'collegeScorecard.details', 'collegeScorecard.selectedSchoolsDirective', 'collegeScorecard.scorecardDataService', 'collegeScorecard.schoolsListService', 'collegeScorecard.schoolDataTranslationService' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/home'}); }]);
brianyamasaki/collegeScorecard
app/app.js
JavaScript
mit
658
package com.cg.registration.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; /** * Servlet implementation class Registration */ public class RegistrationServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Connection conn=null; private DataSource ds=null; public void init() throws ServletException { ServletContext context = getServletContext(); ds=(DataSource)context.getAttribute("appds"); try { conn=ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ String name=request.getParameter("name"); //String address=request.getParameter("address"); //String phone=request.getParameter("phone"); String username=request.getParameter("username"); String password=request.getParameter("password"); //System.out.println(name+address+phone+username+password); PrintWriter out = response.getWriter(); PreparedStatement ps = conn.prepareStatement("insert into EMS values(?,?,?)"); ps.setString(1, name); ps.setString(2, username); ps.setString(3, password); if(ps.executeUpdate()==1){ response.sendRedirect("login.jsp"); }else{ out.println("User Not registered"); request.getRequestDispatcher("/index2.jsp") .include(request, response); } ps.close(); } catch(Exception e) { e.printStackTrace(); } } }
brijeshsmita/commons-spring
EMSPhase3JSP/src/com/cg/registration/servlet/RegistrationServlet.java
Java
mit
2,047
// © Copyright 2013 Paul Thomas <paul@stackfull.com>. All Rights Reserved. // sf-virtual-repeat directive // =========================== // Like `ng-repeat` with reduced rendering and binding // (function(){ 'use strict'; // (part of the sf.virtualScroll module). var mod = angular.module('sf.virtualScroll'); var DONT_WORK_AS_VIEWPORTS = ['TABLE', 'TBODY', 'THEAD', 'TR', 'TFOOT']; var DONT_WORK_AS_CONTENT = ['TABLE', 'TBODY', 'THEAD', 'TR', 'TFOOT']; var DONT_SET_DISPLAY_BLOCK = ['TABLE', 'TBODY', 'THEAD', 'TR', 'TFOOT']; // Utility to clip to range function clip(value, min, max){ if( angular.isArray(value) ){ return angular.forEach(value, function(v){ return clip(v, min, max); }); } return Math.max(min, Math.min(value, max)); } mod.directive('sfVirtualRepeat', ['$log', '$rootElement', function($log, $rootElement){ return { require: '?ngModel', transclude: 'element', priority: 1000, terminal: true, compile: sfVirtualRepeatCompile }; // Turn the expression supplied to the directive: // // a in b // // into `{ value: "a", collection: "b" }` function parseRepeatExpression(expression){ var match = expression.match(/^\s*([\$\w]+)\s+in\s+([\S\s]*)$/); if (! match) { throw new Error("Expected sfVirtualRepeat in form of '_item_ in _collection_' but got '" + expression + "'."); } return { value: match[1], collection: match[2] }; } // Utility to filter out elements by tag name function isTagNameInList(element, list){ var t, tag = element.tagName.toUpperCase(); for( t = 0; t < list.length; t++ ){ if( list[t] === tag ){ return true; } } return false; } // Utility to find the viewport/content elements given the start element: function findViewportAndContent(startElement){ /*jshint eqeqeq:false, curly:false */ var root = $rootElement[0]; var e, n; // Somewhere between the grandparent and the root node for( e = startElement.parent().parent()[0]; e !== root; e = e.parentNode ){ // is an element if( e.nodeType != 1 ) break; // that isn't in the blacklist (tables etc.), if( isTagNameInList(e, DONT_WORK_AS_VIEWPORTS) ) continue; // has a single child element (the content), if( e.childElementCount != 1 ) continue; // which is not in the blacklist if( isTagNameInList(e.firstElementChild, DONT_WORK_AS_CONTENT) ) continue; // and no text. for( n = e.firstChild; n; n = n.nextSibling ){ if( n.nodeType == 3 && /\S/g.test(n.textContent) ){ break; } } if( n == null ){ // That element should work as a viewport. return { viewport: angular.element(e), content: angular.element(e.firstElementChild) }; } } throw new Error("No suitable viewport element"); } // Apply explicit height and overflow styles to the viewport element. // // If the viewport has a max-height (inherited or otherwise), set max-height. // Otherwise, set height from the current computed value or use // window.innerHeight as a fallback // function setViewportCss(viewport){ var viewportCss = {'overflow': 'auto'}, style = window.getComputedStyle ? window.getComputedStyle(viewport[0]) : viewport[0].currentStyle, maxHeight = style && style.getPropertyValue('max-height'), height = style && style.getPropertyValue('height'); if( maxHeight && maxHeight !== '0px' ){ viewportCss.maxHeight = maxHeight; }else if( height && height !== '0px' ){ viewportCss.height = height; }else{ viewportCss.height = window.innerHeight; } viewport.css(viewportCss); } // Apply explicit styles to the content element to prevent pesky padding // or borders messing with our calculations: function setContentCss(content){ var contentCss = { margin: 0, padding: 0, border: 0, 'box-sizing': 'border-box' }; content.css(contentCss); } // TODO: compute outerHeight (padding + border unless box-sizing is border) function computeRowHeight(element){ var style = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle, maxHeight = style && style.getPropertyValue('max-height'), height = style && style.getPropertyValue('height'); if( height && height !== '0px' && height !== 'auto' ){ $log.debug('Row height is "%s" from css height', height); }else if( maxHeight && maxHeight !== '0px' && maxHeight !== 'none' ){ height = maxHeight; $log.debug('Row height is "%s" from css max-height', height); }else if( element.clientHeight ){ height = element.clientHeight+'px'; $log.debug('Row height is "%s" from client height', height); }else{ throw new Error("Unable to compute height of row"); } angular.element(element).css('height', height); return parseInt(height, 10); } // The compile gathers information about the declaration. There's not much // else we could do in the compile step as we need a viewport parent that // is exculsively ours - this is only available at link time. function sfVirtualRepeatCompile(element, attr, linker) { var ident = parseRepeatExpression(attr.sfVirtualRepeat); return { post: sfVirtualRepeatPostLink }; // ---- // Set up the initial value for our watch expression (which is just the // start and length of the active rows and the collection length) and // adds a listener to handle child scopes based on the active rows. function sfVirtualRepeatPostLink(scope, iterStartElement, attrs){ var rendered = []; var rowHeight = 0; var scrolledToBottom = false; var stickyEnabled = "sticky" in attrs; var dom = findViewportAndContent(iterStartElement); // The list structure is controlled by a few simple (visible) variables: var state = 'ngModel' in attrs ? scope.$eval(attrs.ngModel) : {}; // - The index of the first active element state.firstActive = 0; // - The index of the first visible element state.firstVisible = 0; // - The number of elements visible in the viewport. state.visible = 0; // - The number of active elements state.active = 0; // - The total number of elements state.total = 0; // - The point at which we add new elements state.lowWater = state.lowWater || 100; // - The point at which we remove old elements state.highWater = state.highWater || 300; // - Keep the scroll event from constantly firing state.threshold = state.threshold || 1; var lastFixPos = 0; // TODO: now watch the water marks setContentCss(dom.content); setViewportCss(dom.viewport); // When the user scrolls, we move the `state.firstActive` dom.viewport.bind('scroll', sfVirtualRepeatOnScroll); // The watch on the collection is just a watch on the length of the // collection. We don't care if the content changes. scope.$watch(sfVirtualRepeatWatchExpression, sfVirtualRepeatListener, true); // and that's the link done! All the action is in the handlers... return; // ---- // Apply explicit styles to the item element function setElementCss (element) { var elementCss = { // no margin or it'll screw up the height calculations. margin: '0' }; if( !isTagNameInList(element[0], DONT_SET_DISPLAY_BLOCK) ){ // display: block if it's safe to do so elementCss.display = 'block'; } if( rowHeight ){ elementCss.height = rowHeight+'px'; } element.css(elementCss); } function makeNewScope (idx, colExpr, containerScope) { var childScope = containerScope.$new(), collection = containerScope.$eval(colExpr); childScope[ident.value] = collection[idx]; childScope.$index = idx; childScope.$first = (idx === 0); childScope.$last = (idx === (collection.length - 1)); childScope.$middle = !(childScope.$first || childScope.$last); childScope.$watch(function updateChildScopeItem(){ collection = containerScope.$eval(colExpr); childScope[ident.value] = collection[idx]; }); return childScope; } function addElements (start, end, colExpr, containerScope, insPoint) { var frag = document.createDocumentFragment(); var newElements = [], element, idx, childScope; for( idx = start; idx !== end; idx ++ ){ childScope = makeNewScope(idx, colExpr, containerScope); element = linker(childScope, angular.noop); setElementCss(element); newElements.push(element); frag.appendChild(element[0]); } insPoint.after(frag); return newElements; } function recomputeActive() { // We want to set the start to the low water mark unless the current // start is already between the low and high water marks. var start = clip(state.firstActive, state.firstVisible - state.lowWater, state.firstVisible - state.highWater); // Similarly for the end var end = clip(state.firstActive + state.active, state.firstVisible + state.visible + state.lowWater, state.firstVisible + state.visible + state.highWater ); state.firstActive = clip(start, 0, state.total - state.visible - state.lowWater); state.active = Math.min(end, state.total) - state.firstActive; } function sfVirtualRepeatOnScroll(evt){ if( !rowHeight ){ return; } var diff = Math.abs(evt.target.scrollTop - lastFixPos); if(diff > (state.threshold * rowHeight)){ // Enter the angular world for the state change to take effect. scope.$apply(function(){ state.firstVisible = Math.floor(evt.target.scrollTop / rowHeight); state.visible = Math.ceil(dom.viewport[0].clientHeight / rowHeight); $log.debug('scroll to row %o', state.firstVisible); var sticky = evt.target.scrollTop + evt.target.clientHeight >= evt.target.scrollHeight; recomputeActive(); $log.debug(' state is now %o', state); $log.debug(' sticky = %o', sticky); }); lastFixPos = evt.target.scrollTop; } } function sfVirtualRepeatWatchExpression(scope){ var coll = scope.$eval(ident.collection); if( coll && coll.length !== state.total ){ state.total = coll.length; recomputeActive(); } return { start: state.firstActive, active: state.active, len: coll ? coll.length : 0 }; } function destroyActiveElements (action, count) { var dead, ii, remover = Array.prototype[action]; for( ii = 0; ii < count; ii++ ){ dead = remover.call(rendered); dead.scope().$destroy(); dead.remove(); } } // When the watch expression for the repeat changes, we may need to add // and remove scopes and elements function sfVirtualRepeatListener(newValue, oldValue, scope){ var oldEnd = oldValue.start + oldValue.active, newElements; if( newValue === oldValue ){ $log.debug('initial listen'); newElements = addElements(newValue.start, oldEnd, ident.collection, scope, iterStartElement); rendered = newElements; if( rendered.length ){ rowHeight = computeRowHeight(newElements[0][0]); } }else{ var newEnd = newValue.start + newValue.active; var forward = newValue.start >= oldValue.start; var delta = forward ? newValue.start - oldValue.start : oldValue.start - newValue.start; var endDelta = newEnd >= oldEnd ? newEnd - oldEnd : oldEnd - newEnd; var contiguous = delta < (forward ? oldValue.active : newValue.active); $log.debug('change by %o,%o rows %s', delta, endDelta, forward ? 'forward' : 'backward'); if( !contiguous ){ $log.debug('non-contiguous change'); destroyActiveElements('pop', rendered.length); rendered = addElements(newValue.start, newEnd, ident.collection, scope, iterStartElement); }else{ if( forward ){ $log.debug('need to remove from the top'); destroyActiveElements('shift', delta); }else if( delta ){ $log.debug('need to add at the top'); newElements = addElements( newValue.start, oldValue.start, ident.collection, scope, iterStartElement); rendered = newElements.concat(rendered); } if( newEnd < oldEnd ){ $log.debug('need to remove from the bottom'); destroyActiveElements('pop', oldEnd - newEnd); }else if( endDelta ){ var lastElement = rendered[rendered.length-1]; $log.debug('need to add to the bottom'); newElements = addElements( oldEnd, newEnd, ident.collection, scope, lastElement); rendered = rendered.concat(newElements); } } if( !rowHeight && rendered.length ){ rowHeight = computeRowHeight(rendered[0][0]); } dom.content.css({'padding-top': newValue.start * rowHeight + 'px'}); } dom.content.css({'height': newValue.len * rowHeight + 'px'}); if( scrolledToBottom && stickyEnabled ){ dom.viewport[0].scrollTop = dom.viewport[0].clientHeight + dom.viewport[0].scrollHeight; } } } } }]); }());
looker/angular-virtual-scroll
src/virtual-repeat.js
JavaScript
mit
14,764
require('../helpers'); const assert = require('assert'); const ironium = require('../../src'); const Promise = require('bluebird'); describe('processing', ()=> { const errorCallbackQueue = ironium.queue('error-callback'); const errorPromiseQueue = ironium.queue('error-promise'); const errorGeneratorQueue = ironium.queue('error-generator'); function untilSuccessful(done) { ironium.runOnce((error)=> { if (error) setTimeout(()=> untilSuccessful(done)); else done(); }); } describe('with callback error', ()=> { // First two runs should fail, runs ends at 3 let runs = 0; before(()=> { errorCallbackQueue.eachJob((job, callback)=> { runs++; if (runs > 2) callback(); else callback(new Error('fail')); }); }); before(()=> errorCallbackQueue.queueJob('job')); before(untilSuccessful); it('should repeat until processed', ()=> { assert.equal(runs, 3); }); }); describe('with rejected promise', ()=> { // First two runs should fail, runs ends at 3 let runs = 0; before(()=> { errorPromiseQueue.eachJob(()=> { runs++; if (runs > 2) return Promise.resolve(); else return Promise.reject(new Error('fail')); }); }); before(()=> errorPromiseQueue.queueJob('job')); before(untilSuccessful); it('should repeat until processed', ()=> { assert.equal(runs, 3); }); }); describe('with generator error', ()=> { // First two runs should fail, runs ends at 3 let runs = 0; before(()=> { errorGeneratorQueue.eachJob(function*() { runs++; switch (runs) { case 1: { throw new Error('fail'); } case 2: { yield Promise.reject(Error('fail')); break; } } }); }); before(()=> errorGeneratorQueue.queueJob('job')); before(untilSuccessful); it('should repeat until processed', ()=> { assert.equal(runs, 3); }); }); });
djanowski/ironium
test/queues/error_test.js
JavaScript
mit
2,127
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def mainRoute(): return render_template('hello.html') @app.route('/jujitsu') def jujitsu(): return render_template('jujitsu.html') if __name__ == '__main__': app.run(debug=True,host='0.0.0.0', port=8080)
CrazyDiamond567/docker-cloud-test
unh698.py
Python
mit
302
/** * Created by Andrei on 10/14/2014. */ import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.net.InetAddress; public class ThreadPoolApp { public static void main (String[] args) { if (args.length < 2) ThreadPoolApp.error(); try { int numberOfJobs = Integer.parseInt(args[0]); int numberOfThreads = Integer.parseInt(args[1]); if ((numberOfJobs < 1) || (numberOfThreads < 1)) ThreadPoolApp.error(); ExecutorService pool = Executors.newFixedThreadPool(numberOfThreads); Job[] jobs = new Job[numberOfJobs]; for (int i = 0; i < numberOfJobs; i++) { if (i == 0) { jobs[0] = new Job(0){ public void run() { //Undertake required work, here we will emulate it by sleeping for a period System.out.println("Job: " + jobNumber + " is being processed by thread: " + Thread.currentThread().getName()); try { Thread.sleep((int)(1000)); System.out.println("Hello World!"); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //get current date time with Date() Date date = new Date(); System.out.println(dateFormat.format(date)); //get current date time with Calendar() Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime())); } catch (InterruptedException e) { //no cathing as example should not experience interruptions } System.out.println("Job: " + jobNumber + " is ending in thread: " + Thread.currentThread().getName()); } }; pool.execute(jobs[0]); } if (i == 1) { jobs[1] = new Job(1){ public void run() { //Undertake required work, here we will emulate it by sleeping for a period System.out.println("Job: " + jobNumber + " is being processed by thread: " + Thread.currentThread().getName()); try { Thread.sleep((int)(1000)); try { java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); System.out.println("Hostname of local machine: " + localMachine.getHostName()); } catch (Exception ex) { //comment } } catch (InterruptedException e) { //no cathing as example should not experience interruptions } System.out.println("Job: " + jobNumber + " is ending in thread: " + Thread.currentThread().getName()); } }; pool.execute(jobs[1]); } if ( i > 1) { jobs[i] = new Job(i); pool.execute(jobs[i]); } //pool.execute(jobs[i]); //executes the given command at some future time } pool.shutdown(); //Shutdown: previously submitted tasks are executed, //but no new tasks will be accepted. System.out.println(" Last line " + Thread.currentThread().getName()); } catch (NumberFormatException e) { ThreadPoolApp.error(); } } private static void error() { System.out.println("ThreadPoolApp must be run with two positive valued" + " integer arguments. The first detaling the number of jobs" + " the second the number of processing threads in the pool"); System.exit(0); //exit the program } }
abrabete/threadpool_example
IntelliJ/src/ThreadPoolApp.java
Java
mit
4,608
#ifndef WF_INPUT_DEVICE_HPP #define WF_INPUT_DEVICE_HPP #include <wayfire/nonstd/wlroots.hpp> namespace wf { class input_device_t { public: /** * General comment * @return The represented wlr_input_device */ wlr_input_device *get_wlr_handle(); /** * @param enabled Whether the compositor should handle input events from * the device * @return true if the device state was successfully changed */ bool set_enabled(bool enabled = true); /** * @return true if the compositor should receive events from the device */ bool is_enabled(); protected: wlr_input_device *handle; input_device_t(wlr_input_device *handle); }; } #endif /* end of include guard: WF_INPUT_DEVICE_HPP */
ammen99/wayfire
src/api/wayfire/input-device.hpp
C++
mit
758
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace ContactList { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
gyuwon/TDK2015
ContactList/App.xaml.cs
C#
mit
327
require 'wasted' begin require 'pry' # rescue LoadError end
tombroomfield/wasted
spec/spec_helper.rb
Ruby
mit
64
<?php namespace Oro\Bundle\EmailBundle\EventListener\Datagrid; use Oro\Bundle\DataGridBundle\Datasource\Orm\OrmDatasource; use Oro\Bundle\DataGridBundle\Event\BuildAfter; use Oro\Bundle\EmailBundle\Datagrid\EmailQueryFactory; class IncomingEmailGridListener { /** @var EmailQueryFactory */ protected $emailQueryFactory; /** * @param EmailQueryFactory $emailQueryFactory */ public function __construct(EmailQueryFactory $emailQueryFactory) { $this->emailQueryFactory = $emailQueryFactory; } /** * @param BuildAfter $event */ public function onBuildAfter(BuildAfter $event) { /** @var OrmDatasource $datasource */ $datasource = $event->getDatagrid()->getDatasource(); $this->emailQueryFactory->addFromEmailAddress($datasource->getQueryBuilder()); } }
orocrm/platform
src/Oro/Bundle/EmailBundle/EventListener/Datagrid/IncomingEmailGridListener.php
PHP
mit
847
<?php namespace GhaenCollege\ScrumBundle\Entity; use Doctrine\ORM\EntityRepository; /** * TestRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class TestRepository extends EntityRepository { }
mahmud-kasaei/Scrum4u
src/GhaenCollege/ScrumBundle/Entity/TestRepository.php
PHP
mit
264
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ReactiveProperty Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReactiveProperty Test")] [assembly: AssemblyCopyright("Copyright © 2015-2017 emoacht")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
emoacht/WlanProfileViewer
Source/ReactivePropertyTest/Properties/AssemblyInfo.cs
C#
mit
2,287
module.exports = { getDates: function(d) { var today = padDate(d); return { startTime: today + lowerBoundTime(), endTime: today + upperBoundTime() }; } }; function padDate (d){ function pad (n) { return n < 10 ? '0' + n : n } return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1 ) + '-' + pad(d.getUTCDate()) + 'T'; } function lowerBoundTime() { return '00:00:00Z'; } function upperBoundTime() { return '23:59:59Z'; }
iOnline247/heyo
utils/dateHelpers.js
JavaScript
mit
449
/** * Java Modular Image Synthesis Toolkit (JMIST) * Copyright (C) 2018 Bradley W. Kimmel * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package ca.eandb.jmist.framework.scatter; import ca.eandb.jmist.framework.Function1; import ca.eandb.jmist.framework.Random; import ca.eandb.jmist.framework.SurfacePointGeometry; import ca.eandb.jmist.math.Vector3; /** * A <code>SurfaceScatterer</code> representing a absorptive layer with sieve * effects in the ABM-B/ABM-U light transport models. * @author Brad Kimmel * @see ABMSurfaceScatterer */ public final class ABMSieveAbsorbingSurfaceScatterer implements SurfaceScatterer { /** Serialization version ID. */ private static final long serialVersionUID = -8261906690789778531L; /** The absorption coefficient of the medium (in m<sup>-1</sup>). */ private final Function1 absorptionCoefficient; /** The thickness of the medium (in meters). */ private final double thickness; /** * Creates a new <code>AbsorbingSurfaceScatterer</code>. * @param absorptionCoefficient The absorption coefficient of the medium * (in m<sup>-1</sup>). * @param thickness The thickness of the medium (in meters). */ public ABMSieveAbsorbingSurfaceScatterer(Function1 absorptionCoefficient, double thickness) { this.absorptionCoefficient = absorptionCoefficient; this.thickness = thickness; } @Override public Vector3 scatter(SurfacePointGeometry x, Vector3 v, boolean adjoint, double lambda, Random rnd) { double abs = absorptionCoefficient.evaluate(lambda); double p = -Math.log(1.0 - rnd.next()) * Math.cos(Math.abs(x.getNormal().dot(v))) / abs; return (p > thickness) ? v : null; } }
bwkimmel/jmist
jmist-core/src/main/java/ca/eandb/jmist/framework/scatter/ABMSieveAbsorbingSurfaceScatterer.java
Java
mit
2,738
module.exports = require("./src/moment-interval");
luisfarzati/moment-interval
index.js
JavaScript
mit
50
// namespace plexus var plexus = plexus || {}; window._plexus = plexus; (function(plx) { console.log("plexus.js [loaded]"); //------------------------------ // Plexus utilties functions //------------------------------ plx.each = function(obj, iterator, context) { if (!obj) return; if (obj instanceof Array) { for (var i = 0, li = obj.length; i <li; i++) { if (iterator.call(context, obj[i], i) === false) return; } } else { for (var key in obj) { if (iterator.call(context, obj[key], key) === false) return; } } }; plx.extend = function(target) { var sources = arguments.length >= 2 ? Array.prototype.slice.call(arguments, 1) : []; plx.each(sources, function(src) { for (var key in src) { if (src.hasOwnProperty(key)) target[key] = src[key]; } }); return target; }; var ClassLoader = { id: (0 | (Math.random() * 998)), instanceId: (0 | (Math.random() * 998)), compileSuper: function(func, name, id) { var str = func.toString(); var pstart = str.indexOf('('), pend = str.indexOf(')'); var params = str.substring(pstart + 1, pend); params = params.trim(); var bstart = str.indexOf('{'), bend = str.lastIndexOf('}'); var str = str.substring(bstart + 1, bend); while (str.indexOf('this._super') != -1) { var sp = str.indexOf('this._super'); var bp = str.indexOf('(', sp); var bbp = str.indexOf(')', bp); var superParams = str.substring(bp + 1, bbp); superParams = superParams.trim(); var coma = superParams ? ',' : ''; str = str.substring(0, sp) + 'ClassLoader[' + id + '].' + name + '.call(this' + coma + str.substring(bp + 1); } return Function(params, str); }, newId: function() { return this.id++; }, newInstanceId: function() { return this.instanceId++; } }; ClassLoader.compileSuper.ClassLoader = ClassLoader; plx.Class = function() { }; var FuncRegexTest = /\b_super\b/; var releaseMode = false; plx.Class.extend = function(props) { var _super = this.prototype; var prototype = Object.create(_super); var classId = ClassLoader.newId(); ClassLoader[classId] = _super; var desc = { writable: true, enumerable: false, configurable: true }; prototype.__instanceId = null; function Class() { this.__instanceId = ClassLoader.newInstanceId(); if (this.ctor) this.ctor.apply(this, arguments); }; Class.id = classId; desc.value = classId; Object.defineProperty(prototype, "__pid", desc); Class.prototype = prototype; desc.value = Class; Object.defineProperty(Class.prototype, 'constructor', desc); for(var idx = 0, li = arguments.length; idx < li; ++idx) { var prop = arguments[idx]; for (var name in prop) { var isFunc = (typeof prop[name] === 'function'); var override = (typeof _super[name] === 'function'); var hasSuperCall = FuncRegexTest.test(prop[name]); if (releaseMode && isFunc && override && hasSuperCall) { desc.value = ClassLoader.compileSuper(prop[name], name, classId); Object.defineProperty(prototype, name, desc); } else if(isFunc && override && hasSuperCall) { desc.value = (function(name, fn) { return function() { var tmp = this._super; this._super = _super[name]; var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]); Object.defineProperty(prototype, name, desc); } else if (isFunc) { desc.value = prop[name]; Object.defineProperty(prototype, name, desc); } else { prototype[name] = prop[name]; } // ... Getters and Setters ... ? } } Class.extend = plx.Class.extend; Class.implement = function(prop) { for (var name in prop) { prototype[name] = prop[name]; } }; return Class; }; //------------------------------ // Plexus GameObject //------------------------------ /** * @class GameObject */ var GameObject = plx.Class.extend({ _components: {}, _data: null, ctor: function() { this._id = (+new Date()).toString(16) + (Math.random() * 1000000000 | 0).toString(16) + (++GameObject.sNumOfObjects); }, getId: function() { return this._id; }, getUserData: function() { return this._data; }, setUserData: function(data) { // plx.extend(this._data, data); this._data = data; }, getComponent: function(component) { var name = component; if (typeof component === 'function') { name = component.prototype.name; } return this._components[name]; }, addComponent: function(component) { if (!component || !component.name) return; this._components[component.name] = component; if (typeof component.setOwner === 'function') component.setOwner(this); return this; }, // Remove component data by removing the reference to it. removeComponent: function(component) { // Allows either a component function or a string of a component name to be passed in. var name = component; if (typeof component === 'function') { name = component.prototype.name; } // Remove component data by removing the reference to it. component = this._components[name]; delete this._components[name]; if (typeof component.setOwner === 'function') component.setOwner(null); return this; }, getTag: function() { return this._tag; }, setTag: function(tagValue) { this._tag = tagValue; } }); GameObject.sNumOfObjects = 0; //------------------------------ // Plexus Component //------------------------------ /** * @class GameComponent */ var GameComponent = plx.Class.extend({ _owner: null, ctor: function() { }, getOwner: function() { return this._owner; }, setOwner: function(owner) { this._owner = owner; } }); //------------------------------ // Plexus System //------------------------------ /** * @class System */ var System = plexus.Class.extend({ _managedObjects: [], _managedSystems: [], ctor: function() { }, addSubSystem: function(sub) { if (sub && sub.name) { this._managedSystems[sub.name] = sub; this._managedSystems.push(sub); } }, removeSubSystem: function(sub) { var name = sub; if (typeof sub === 'function') { name = sub.prototype.name; } var origin = this._managedSystems[name]; delete this._managedSystems[name]; var idx = this._managedSystems.indexOf(origin); if (idx != -1) { this._managedSystems.splice(idx, 1); } return origin; }, addObject: function(obj) { this._managedObjects.push(obj); // added in subsystems. this._managedSystems.forEach(function(elt, i) { elt.order(obj); return true; }); }, removeObject: function(obj) { var index = this._managedObjects.indexOf(obj); if (index != -1) { this._managedObjects.splice(index, 1); // remove in subsystems. this._managedSystems.every(function(elt, i) { elt.unorder(elt); return true; }); } }, update: function(dt) { this._managedSystems.forEach(function(elt, i) { elt.update(dt); return true; }); } }); /** * @class SubSystem */ var SubSystem = plexus.Class.extend({ _managed: [], check: function(obj) { if (!this.name) return false; if (typeof obj.getComponent === 'function') return obj.getComponent(this.name); return false; }, order: function(obj) { if (this.check(obj)) { this._managed.push(obj); } }, unorder: function(obj) { var index = -1; if ((index = _managed.indexOf(obj)) != -1) { if (this.check(obj)) { this._managed.splice(index, 1); } } }, update: function(dt) { var self = this; // console.log(JSON.stringify(self._managed, null, 4)); this._managed.every(function(elt, i) { if (typeof self.updateObjectDelta === 'function') self.updateObjectDelta(elt, dt); return true; }, self); }, updateObjectDelta: function(obj, dt) { if (!this.name) return; var comp = obj.getComponent(this.name); comp && comp.update(dt); } }); //------------------------------ // SubSystems //------------------------------ var InputSystem = SubSystem.extend({ name: 'input', check: function(obj) { if (typeof obj.getComponent === 'function') { return obj.getComponent(this.name); } return false; } }); /** * @class PhysicsSystem */ var PhysicsSystem = SubSystem.extend({ name: 'physics', check: function(obj) { if (typeof obj.getComponent=== 'function') { return obj.getComponent(this.name); } return false; }, updateObjectDelta: function(obj, dt) { } }); /** * @class AnimatorSystem */ var AnimatorSystem = SubSystem.extend({ name: 'animator', check: function(obj) { if (typeof obj.getComponent === 'function') { return obj.getComponent(this.name); } return false; }, updateObjectDelta: function(obj, dt) { var comp = obj.getComponent(this.name); comp && comp.update(dt); } }); var _systemInstance = undefined; System.getInstance = function getSystem() { if (!_systemInstance) _systemInstance = new System; return _systemInstance; }; plx.GameSystem = System; plx.GameSubSystem = SubSystem; plx.InputSystem = InputSystem; plx.PhysicsSystem = PhysicsSystem; plx.AnimatorSystem = AnimatorSystem; plx.GameComponent = GameComponent; plx.GameObject = GameObject; })(plexus); // vi: ft=javascript sw=4 ts=4 et :
keyhom/xstudio-html5
src/plexus/js/plexus-base.js
JavaScript
mit
12,046
using System; namespace SingleSignOnKata.sso { public interface SingleSignOnRegistry { SSOToken RegisterNewSession(String userName, String password); bool IsValid(SSOToken token); void Unregister(SSOToken token); } }
emilybache/Single-Sign-On-Kata
CSharp/SingleSignOnKata/sso/SingleSignOnRegistry.cs
C#
mit
257
const http = require('http'); const server = http.createServer(); const io = require('socket.io'); const { spy } = require('sinon'); const { expect } = require('chai'); const client = require('./socket'); const TEST_URL = 'http://localhost:3001'; describe('test socket', () => { let sock; beforeEach( (done) => { sock = io(server); server.listen(3001, () => done()); }); afterEach((done) => { server.close( () => done()); sock.close(); }); it('should connect', (done) => { sock.on('connection', () => { done(); }); client(TEST_URL, {}); }); });
EPSI-I5-Kaamelott/Kaamelott-rasp
src/socket.test.js
JavaScript
mit
601
#!/usr/bin/env python # encoding: utf-8 """MoodleFUSE initialization """ import os import errno from moodlefuse.filesystem import Filesystem from moodlefuse.core import setup, config from moodlefuse.services import USERS MOODLEFUSE_DATABASE_FILE = 'moodlefuse.sqlite' MOODLEFUSE_CONFIG_FILE = 'moodlefuse.conf' MOODLEFUSE_HIDDEN_FOLDER = '.moodlefuse' DATABASE_CONF = 'alembic.ini' class MoodleFuse(object): def __init__(self, settings=None, testing=None): setup(settings) self._create_filesystem_root() Filesystem(config['LOCAL_MOODLE_FOLDER'], testing) def _create_filesystem_root(self): moodle_fs_path = config['LOCAL_MOODLE_FOLDER'] try: os.makedirs(moodle_fs_path) except OSError as e: if e.errno is not errno.EEXIST: raise e
BroganD1993/MoodleFUSE
moodlefuse/__init__.py
Python
mit
836
<?php namespace Ackintosh\Snidel; /** * @codeCoverageIgnore */ function msg_send() { return false; }
ackintosh/snidel
tests/msg_send.php
PHP
mit
108
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration, Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your need! */ class Version20120802054929 extends AbstractMigration { public function up(Schema $schema) { // this up() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); $this->addSql("CREATE TABLE users (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(25) NOT NULL, salt VARCHAR(32) NOT NULL, password VARCHAR(40) NOT NULL, email VARCHAR(60) NOT NULL, is_active TINYINT(1) NOT NULL, UNIQUE INDEX UNIQ_1483A5E9F85E0677 (username), UNIQUE INDEX UNIQ_1483A5E9E7927C74 (email), PRIMARY KEY(id)) ENGINE = InnoDB"); } public function down(Schema $schema) { // this down() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); $this->addSql("DROP TABLE users"); } }
theaudience-brett/podcasts
app/DoctrineMigrations/Version20120802054929.php
PHP
mit
1,101
require 'spec_helper' require 'date' require 'bigdecimal' require 'xeroid/objects/invoice' require 'xeroid/objects/account' require 'xeroid/objects/payment' module Xeroid::Objects describe Payment do let(:invoice) { Invoice.new(id: "abcde-12345-abcde-12345") } let(:account) { Account.new(code: "NWBC") } let(:amount) { BigDecimal.new("10.00") } let(:date) { Date.parse("2012-11-15") } let(:payment) { Payment.new(invoice: invoice, account: account, amount: amount, date: date) } it "can return its invoice" do payment.invoice.should == invoice end it "can return its account" do payment.account.should == account end it "can return its date" do payment.date.should == date end it "can return its amount" do payment.amount.should == amount end it "returns nil for currency_rate by default" do payment.currency_rate.should be_nil end context "with currency_rate" do let(:currency_rate) { BigDecimal.new("1.2") } let(:payment) { Payment.new(invoice: invoice, account: account, amount: amount, date: date, currency_rate: currency_rate) } it "can return its currency_rate" do payment.currency_rate.should == currency_rate end end end end
fidothe/xeroid
spec/xeroid/objects/payment_spec.rb
Ruby
mit
1,277
const sqlite = require('sqlite'); const exec = require('child_process').exec; const program = require('commander'); const config = require('./config'); const fetchGroups = require('./lib/fetch-groups'); const fetchMembers = require('./lib/fetch-members'); program .version('0.0.0') .option('-a, --accessToken [value]', 'Facebook access token') .parse(process.argv); if(program.accessToken) { callMe(); } else { program.help(); } async function callMe() { let db; try { db = await sqlite.open(config.dbName); } catch(err) { console.error('unable to connect to database: ', config.dbName); } await db.exec(` CREATE TABLE IF NOT EXISTS fb_groups( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, fb_group_id NUMERIC NOT NULL UNIQUE, fb_privacy TEXT NOT NULL, fb_bookmark_order INTEGER NOT NULL, timestamp DATETIME DEFAULT 'now' ); `); await db.exec(` CREATE TABLE IF NOT EXISTS fb_users( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, fb_user_id NUMERIC NOT NULL UNIQUE, timestamp DATETIME DEFAULT 'now' ); `); await db.exec(` CREATE TABLE IF NOT EXISTS fb_groups_users( id INTEGER PRIMARY KEY AUTOINCREMENT, group_id INTEGER NOT NULL REFERENCES fb_groups, user_id INTEGER NOT NULL REFERENCES db_users, is_admin BOOLEAN NOT NULL DEFAULT FALSE, timestamp DATETIME DEFAULT 'now', UNIQUE(group_id, user_id) ); `); const result = await fetchGroups(program.accessToken); result.data.forEach(async function(gr) { try { // Insert data for all the groups there await db.run(` INSERT OR IGNORE INTO fb_groups (name, fb_group_id, fb_privacy, fb_bookmark_order) SELECT :name, :id, :privacy, :bookmark_order `, { ':name': gr.name, ':id': gr.id, ':privacy': gr.privacy, ':bookmark_order': gr.bookmark_order, }); } catch(err) { console.error(err) } }); const groups = await db.all(`SELECT * FROM fb_groups`); groups.forEach(async function(gr) { let membersEmmiter = await fetchMembers({ accessToken: program.accessToken, groupId: gr.fb_group_id, }); let chunkNum = 0; let totalMembers = 0; let prevTimestamp = new Date(); console.log(`Processing group "${ gr.name }" with id ${gr.fb_group_id}`) await new Promise((res, rej) => { membersEmmiter.on('error', err => rej(err)); membersEmmiter.on('end', err => res()); membersEmmiter.on('load', async (res) => { const membersList = res.resp.data; const newTimestamp = new Date(); chunkNum += 1; totalMembers += membersList.length; console.log(`Processing #${ chunkNum } total of ${ totalMembers } members, lasted ${ (newTimestamp - prevTimestamp) / 1000 }s from group ${ gr.name } with id ${ gr.fb_group_id }`) prevTimestamp = newTimestamp; for(let i = 0, l = membersList.length; i < l; i++) { let member = membersList[i]; try { await db.run(` INSERT OR IGNORE INTO fb_users ( name, fb_user_id) SELECT :name, :id `, { ':name': member.name, ':id': member.id, }); let user = await db.get(`SELECT * FROM fb_users WHERE fb_user_id = :id`, { ':id': member.id, }); await db.run(` INSERT OR IGNORE INTO fb_groups_users ( group_id, user_id, is_admin) SELECT :group_id, :user_id, :is_admin `, { ':group_id': gr.id, ':user_id': user.id, ':is_admin': !!member.administrator, }); } catch (err) { console.error(err) } } }); }); }); }
suricactus/fb-group-members
index.js
JavaScript
mit
3,912
<?php namespace FS\Injection\Pico; if (!defined('ABSPATH')) { exit; // Exit if accessed directly. } class Engine { protected $delimiter; protected $pattern; public function __construct($delimiter = ['\{{2}', '\}{2}']) { $this->setDelimiter($delimiter); } public function setDelimiter(array $delimiter) { $this->delimiter = $delimiter; $this->pattern = "/{$delimiter[0]}\s*('?[\w\.]*'?)([\s?\|\w]*)\s?{$delimiter[1]}/"; return $this; } public function render($content, array $payload = []) { $engine = $this; return preg_replace_callback($this->pattern, function ($matches) use ($payload, $engine) { preg_match("/^'.*'$/", $matches[1], $alphanum); if ($alphanum) { $filters = explode('|', trim($matches[2])); return $engine->applyFilters(trim($alphanum[0], '\''), $filters); } $keys = explode('.', trim($matches[1])); $filters = explode('|', trim($matches[2])); $value = $payload; while ($keys) { $key = array_shift($keys); if (!isset($value[$key])) { return ''; } $value = $value[$key]; } return $engine->applyFilters($value, $filters); }, $content); } public function renderFile($filePath, array $payload = []) { return $this->render($this->getFileContent($filePath)); } protected function getFileContent($filePath) { return file_get_contents($filePath); } protected function applyFilters($value, array $filters) { $filters = array_filter($filters); if (!$filters) { return $value; } foreach ($filters as $filter) { $filter = trim($filter); $value = $filter($value); } return $value; } }
flagshipcompany/flagship-for-woocommerce
src/Injection/Pico/Engine.php
PHP
mit
1,971
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Mysql::Mgmt::V2017_12_01 module Models # # The properties used to create a new server. # class ServerPropertiesForCreate include MsRestAzure @@discriminatorMap = Hash.new @@discriminatorMap["Default"] = "ServerPropertiesForDefaultCreate" @@discriminatorMap["PointInTimeRestore"] = "ServerPropertiesForRestore" @@discriminatorMap["GeoRestore"] = "ServerPropertiesForGeoRestore" @@discriminatorMap["Replica"] = "ServerPropertiesForReplica" def initialize @createMode = "ServerPropertiesForCreate" end attr_accessor :createMode # @return [ServerVersion] Server version. Possible values include: '5.6', # '5.7' attr_accessor :version # @return [SslEnforcementEnum] Enable ssl enforcement or not when connect # to server. Possible values include: 'Enabled', 'Disabled' attr_accessor :ssl_enforcement # @return [StorageProfile] Storage profile of a server. attr_accessor :storage_profile # # Mapper for ServerPropertiesForCreate class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ServerPropertiesForCreate', type: { name: 'Composite', polymorphic_discriminator: 'createMode', uber_parent: 'ServerPropertiesForCreate', class_name: 'ServerPropertiesForCreate', model_properties: { version: { client_side_validation: true, required: false, serialized_name: 'version', type: { name: 'String' } }, ssl_enforcement: { client_side_validation: true, required: false, serialized_name: 'sslEnforcement', type: { name: 'Enum', module: 'SslEnforcementEnum' } }, storage_profile: { client_side_validation: true, required: false, serialized_name: 'storageProfile', type: { name: 'Composite', class_name: 'StorageProfile' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_mysql/lib/2017-12-01/generated/azure_mgmt_mysql/models/server_properties_for_create.rb
Ruby
mit
2,647
import * as HTTPStatus from 'http-status-codes'; import * as express from 'express'; import Logger from './Logger'; export default class ErrorHandler { private logger: Logger; constructor() { this.logger = new Logger('ErrorHandler'); } handleError(err: Error, _, res: express.Response, next: Function): express.Response { if (!err) { return next(); } this.logger.error('handleError', err.message); return res.status(HTTPStatus.INTERNAL_SERVER_ERROR).json({ message: process.env.NODE_ENV === 'development' ? err.message : 'Internal error', }); } }
simon-tannai/nodejs-typescript-boilerplate
src/utils/ErrorHandler.ts
TypeScript
mit
599
'use strict'; let mongoose = require('mongoose'), fs = require('fs'); require('../models/project-model'); let Project = mongoose.model('Project'); require('../models/user-model'); let User = mongoose.model('User'); let getCount = function(req, res, next) { Project.count({}, function(err, count) { if (err) { next(err); return; } res.status(200); res.json(count); }); }; let getByArea = function(req, res, next) { let currentArea = req.params.area; if (!currentArea || currentArea === "") { next({ message: "Bad request!", status: 404 }); return; } Project.find({ 'area': currentArea }).sort('-year') .exec(function(err, projects) { if (err) { next(err); return; } res.status(200); res.json(projects); }); }; let getById = function(req, res, next) { let currentId = req.params.id; if (!currentId || currentId === "") { next({ message: "Bad request!", status: 404 }); return; } Project.findOne({ '_id': currentId }, function(err, project) { if (err) { next(err); return; } else if (project === null) { next({ message: "Project not found!", status: 404 }); return; } res.status(200); res.json(project); }); }; let create = function(req, res, next) { var newProject = new Project(req.body); var authKey = req.headers['x-auth-key']; User.findOne({ 'authKey': authKey }, function(err, user) { if (err) { next(err); return; } else if (user === null) { next({ message: "Authentication failed!", status: 401 }); return; } newProject.save(function(err) { if (err) { let error = { message: err.message, status: 400 }; next(err); return; } else { res.status(201); res.json(newProject); } }); }); }; let bulckCreate = function(req, res, next) { let len = req.body.length; for (let i = 0; i < len; i++) { var newProject = new Project(req.body[i]); var fileName = newProject.fileName; var areaName = newProject.area; var filePath = './files/projects/' + areaName + '/' + fileName; var bitmap = fs.readFileSync(filePath); var bufer = new Buffer(bitmap).toString('base64'); newProject.file = bufer; newProject.save(function(err) { if (err) { let error = { message: err.message, status: 400 }; next(err); return; } else { } }); console.log(fileName); }; res.json({}); }; let controller = { getByArea, getById, create, bulckCreate }; module.exports = controller;
veselints/belin
controllers/projects-controller.js
JavaScript
mit
3,316
import Logger from 'utils/logger'; const logger = new Logger('[push-simple/serviceworker]'); function onPush(event) { logger.log("Received push message", event); let title = (event.data && event.data.text()) || "Yay a message"; let body = "We have received a push message"; let tag = "push-simple-demo-notification-tag"; var icon = '/assets/turtle-logo-120x120.png'; event.waitUntil( self.registration.showNotification(title, { body, icon, tag }) ) } function onPushSubscriptionChange(event) { logger.log("Push subscription change event detected", event); } self.addEventListener("push", onPush); self.addEventListener("pushsubscriptionchange", onPushSubscriptionChange);
rossta/serviceworker-rails-sandbox
app/assets/javascripts/push-simple/serviceworker.js
JavaScript
mit
697
var http = require('../simpleHttp'), config = require('../config'), zmq = require('zmq'), _ = require('lodash'), argv = require('yargs').argv, logic = (argv.logic ? require('./' + argv.logic).logic : require('./sampleLogic').logic), modelRoot = (argv.modelRoot ? argv.modelRoot : '/Store/TestOrg'); //Stuff going out var storeSocket = zmq.socket('push'); var zmqStoreLocation = 'tcp://' + config.realTimeStoreZmqHost + ':' + config.realTimeStoreZmqPort; storeSocket.connect(zmqStoreLocation); console.log('bound to store at ' + zmqStoreLocation); //Stuff coming in var blpSubscriberSocket = zmq.socket('pull'); var zmqBlpLocation = 'tcp://' + config.blpServerZmqHost + ':' + config.blpServerZmqPort; blpSubscriberSocket.bindSync(zmqBlpLocation); console.log('listening for stream updates at ' + zmqBlpLocation); var onNew = function(msg){ var val = JSON.parse(msg); var _publishReceived = (new Date()).getTime(); _.forEach(val,function(evt){ evt._metadata = evt._metadata ? evt._metadata : {}; evt._metadata.perfPublishReceived = _publishReceived; }); var updates = logic(val,modelRoot); if(updates){ _.forEach(updates,function(update){ //tell it where to go... if(update.path.indexOf(modelRoot) < 0){ update.path = modelRoot + update.path; } update.data._metadata = update.data._metadata ? update.data._metadata : {}; update.data._metadata.perfSendToStore = (new Date()).getTime(); storeSocket.send(JSON.stringify(update)); }); } }; //'message' is the zmq event, our preferred semantics would be 'POST' blpSubscriberSocket.on('message', onNew); var client = http.create(config.eventServerHttpHost, config.eventServerHttpPort, 3); client.post('/SubscribeStream',{ streamName: config.testStreamName, protocol: 'zmq', host: config.blpServerZmqHost, port: config.blpServerZmqPort });
JediMindtrick/Hyperloop
App3_BusinessLogicProcessor/serveBLP.js
JavaScript
mit
1,833
// Generated by jsScript 1.10.0 (function() { AutoForm.hooks({ updatePassword: { onSubmit: function(insertDoc, updateDoc, currentDoc) { if (insertDoc["new"] !== insertDoc.confirm) { sAlert.error('Passwords do not match'); return false; } Accounts.changePassword(insertDoc.old, insertDoc["new"], function(e) { $('.btn-primary').attr('disabled', null); if (e) { return sAlert.error(e.message); } else { return sAlert.success('Password Updated'); } }); return false; } } }); Template.account.events({ 'click .js-delete-account': function() { return Meteor.call('deleteAccount', Meteor.userId()); } }); Template.setUserName.helpers({ user: function() { return Meteor.user(); } }); }).call(this);
patrickbolle/meteor-starter-purejs
client/views/account/account.js
JavaScript
mit
879
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsIotLedDriver { // An interface used to get callbacks from the animator or in a chain of animation. internal interface IAnimationTickListner { // This callback will be fired on every animation tick. The time given is the // time since the last animation tick. bool NotifiyAnimationTick(int timeElapsedMs); } }
QuinnDamerell/WindowsIotLedDriver
WindowsIotLedDriver/Interfaces/IAnimationTickListener.cs
C#
mit
487
import sys import time as tmod import warnings import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() import pandas as pd warnings.simplefilter("ignore") sys.path.insert(0, "../FATS/") import FATS iterations = 100000 lc_size = 1000 random = np.random.RandomState(42) results = { "StetsonK": np.empty(iterations), "StetsonJ": np.empty(iterations), "AndersonDarling": np.empty(iterations)} for it in range(iterations): fs = FATS.FeatureSpace(featureList=list(results.keys())) # a simple time array from 0 to 99 with steps of 0.01 time = np.arange(0, 100, 100./lc_size).shape # create 1000 magnitudes with mu 0 and std 1 mags = random.normal(size=lc_size) # create 1000 magnitudes with difference <= 0.1% than mags mags2 = mags * random.uniform(0, 0.01, mags.size) # create two errors for the magnitudes equivalent to the 0.001% # of the magnitudes errors = random.normal(scale=0.00001, size=lc_size) errors2 = random.normal(scale=0.00001, size=lc_size) lc = np.array([ mags, # magnitude time, # time errors, # error mags, # magnitude2 mags, # aligned_magnitude mags, # aligned_magnitude2 time, # aligned_time errors, # aligned_error errors # aligned_error2 ]) fs.calculateFeature(lc) for k, v in fs.result("dict").items(): results[k][it] = v df = pd.DataFrame(results).describe() print df df.to_latex("features_montecarlo.tex", float_format='%.4f')
carpyncho/feets
res/paper/reports/features_montecarlo.py
Python
mit
1,591
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("squareSurface")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("squareSurface")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0a4f4820-8379-482d-949e-6e823a8caa1e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
LazarDL/TelerikHomeworks
C#1/Operators/squareSurface/Properties/AssemblyInfo.cs
C#
mit
1,402
<?php /** * Group * * This class has been auto-generated by the Doctrine ORM Framework * * @package LinkIgniter * @subpackage Models * @author YOUR_NAME_HERE <YOUR@NAME.HERE> * @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $ */ class Group extends Base_Group { }
linkworks/linkigniter
application/models/Group.php
PHP
mit
302
#!/usr/bin/ruby ## ##Author: Shashank Mathur ## # require "rubygems" require "json" require "net/http" require "uri" require 'open-uri' require 'nokogiri' require 'thread' require 'monitor' require 'io/console' require 'openssl' #Function to Analyze URL def analyze(url) #Preparing to call RESTapi and json results base_uri = "https://api.ssllabs.com/api/v2" fanalyzeuri = URI.parse("#{base_uri}/analyze?host=#{url}&startNew=on") analyzeuri = URI.parse("#{base_uri}/analyze?host=#{url}") fhttp = Net::HTTP.new(fanalyzeuri.host,fanalyzeuri.port) http = Net::HTTP.new(analyzeuri.host,analyzeuri.port) #Using SSL fhttp.use_ssl = true fhttp.verify_mode = OpenSSL::SSL::VERIFY_NONE http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE #Receiving JSON frequest = Net::HTTP::Get.new(fanalyzeuri.request_uri) fresponse = fhttp.request(frequest) request = Net::HTTP::Get.new(analyzeuri.request_uri) response = fhttp.request(request) #Parsing JSON result = JSON.parse(fresponse.body) #Waiting for endpoints to generate until result.has_key?("endpoints") response = fhttp.request(request) result = JSON.parse(response.body) sleep(2) end #Waiting for ipaddresses to populate result["endpoints"].each_index do |i| until result["endpoints"][i].has_key?("ipAddress") response = fhttp.request(request) result = JSON.parse(response.body) sleep(5) end #Check for status if ready until result["endpoints"][i]["statusMessage"] == "Ready" response = fhttp.request(request) result = JSON.parse(response.body) sleep(30) end end return result end #Function to get warnings def getwarnings(hostn, ipadr) #Getting Warning lines from actual SSLlabs web page since this info is not available through api yet doc = Nokogiri::HTML(open("https://www.ssllabs.com/ssltest/analyze.html?d=#{hostn}&s=#{ipadr}&hideResults=on")) #Printing warnings messages #doc.xpath("//div[contains(@class,'warningBox')]").each { |node| puts node.text} doc.xpath("//div[contains(@class,'warningBox')]").each { |node| puts node} end # Function to fetch details for hosts from ssllabs def fetchdtls(hname) joup=analyze(hname) puts "<table border=\"1\" style=\"border-spacing: 0px;float: left;margin: 8px; table-layout:fixed;font-family: monospace;\">" puts "<td colspan=\"3\" style=\"text-align: center; font-size: 25px; background-color: #f1c40f; color: #0c2c40;\"><a href=\"https://www.ssllabs.com/ssltest/analyze.html?d=#{hname}&hideResults=on\" target=\"_blank\">#{hname}</a></td>" puts "<tr><th style=\"background-color: #041317; color: #F2F2F2; font-size: 14px; font-family: sans-serif; padding: 6px 2px;\">IP</th><th style=\"background-color: #041317; color: #F2F2F2; font-size: 14px; font-family: sans-serif; padding: 6px 2px;\">Grade</th><th style=\"background-color: #041317; color: #F2F2F2; font-size: 14px; font-family: sans-serif; padding: 6px 2px;\">Warnings</th></tr>" joup["endpoints"].each_index do |i| puts "<tr>" puts "<td style=\"text-align: center; padding: 15px 8px; font-size:12px; background-color: #0c2c40; color: #f1c40f; font-weight: bold; word-wrap: break-word;\">" + joup['endpoints'][i]['ipAddress'] + "</td>" puts "<td style=\"text-align: center; padding: 15px 8px; font-size:38px; background-color: #0c2c40; color: #f1c40f; word-wrap: break-word;\">" + joup['endpoints'][i]['grade'] + "</td>" if joup["endpoints"][i]["hasWarnings"] puts "<td style=\"text-align: center; padding: 15px 8px; font-size:12px; background-color: #0c2c40; color: #f1c40f; word-wrap: break-word;\">" getwarnings(hname, joup['endpoints'][i]['ipAddress']) puts "</td>" else puts "<td style=\"text-align: center; padding: 15px 8px; font-size:12px; background-color: #0c2c40; color: #f1c40f; word-wrap: break-word; max-width: 100px;\">We do not have any warnings</td>" end end puts "</tr>" end # Array containing hostnames to check. Add any hosts you want to check in the domainnames.txt file. host = IO.readlines("domainnames.txt").map(&:chomp) # Beginning HTML puts "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />" puts "<body bgcolor=\"#C9DCE1\">" puts "<style> .warningBox {border: 1px solid #f1c40f; padding: 5px; background: #0c2c40; margin-top: 10px; font-weight: bold; color: #f1c40f;} </style>" puts "<style>a:visited {color: #089994}</style>" puts "<style>a:link {color: #3282BB}</style>" puts "<style>table, th, td {width: 50%}</style>" puts "<style>footer {position: absolute; bottom:0;}</style>" #Declaring thread related variables thread_count = 5 threads = Array.new(thread_count) work_queue = SizedQueue.new(thread_count) threads.extend(MonitorMixin) threads_available = threads.new_cond sysexit = false # Declaring array for storing results as well as the mutex results = Array.new results_mutex = Mutex.new # Creating Consumer and Producer for thread management consumer_thread = Thread.new do loop do break if sysexit && work_queue.length == 0 found_index = nil threads.synchronize do threads_available.wait_while do threads.select { |thread| thread.nil? || thread.status == false || thread["finished"].nil? == false}.length == 0 end found_index = threads.rindex { |thread| thread.nil? || thread.status == false || thread["finished"].nil? == false } end hostn = work_queue.pop threads[found_index] = Thread.new(hostn) do results_mutex.synchronize do results << fetchdtls(hostn) end Thread.current["finished"] = true threads.synchronize do threads_available.signal end end end end # Getting hosts processed in threads producer_thread = Thread.new do host.each do |hostn| work_queue << hostn threads.synchronize do threads_available.signal end end sysexit = true end # Joining producer_thread.join consumer_thread.join threads.each do |thread| thread.join unless thread.nil? end # Putting output puts results.compact puts "<footer>" puts "This page was generated at " + Time.now.strftime("%d/%m/%Y %H:%M") puts "</footer>"
shashankm/ssllabs-report
ssllabs-report.rb
Ruby
mit
6,298
import { View } from '../core/view'; import { Property } from '../core/properties'; /** * Represents an time picker. */ export class TimePicker extends View { /** * Gets the native [android.widget.TimePicker](http://developer.android.com/reference/android/widget/TimePicker.html) that represents the user interface for this component. Valid only when running on Android OS. */ android: any /* android.widget.TimePicker */; /** * Gets the native iOS [UIDatePicker](http://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIDatePicker_Class/index.html) that represents the user interface for this component. Valid only when running on iOS. */ ios: any /* UIDatePicker */; /** * Gets or sets the time hour. */ hour: number; /** * Gets or sets the time minute. */ minute: number; /** * Gets or sets the time. */ time: Date; /** * Gets or sets the max time hour. */ maxHour: number; /** * Gets or sets the max time minute. */ maxMinute: number; /** * Gets or sets the min time hour. */ minHour: number; /** * Gets or sets the min time minute. */ minMinute: number; /** * Gets or sets the minute interval. */ minuteInterval: number; /** * Gets or set the UIDatePickerStyle of the date picker in iOS 13.4+. Defaults to 0. * Valid values are numbers: * - 0: automatic (system picks the concrete style based on the current platform and date picker mode) * - 1: wheels (the date picker displays as a wheel picker) * - 2: compact (the date picker displays as a label that when tapped displays a calendar-style editor) * - 3: inline (the date pickers displays as an inline, editable field) */ iosPreferredDatePickerStyle: number; } export const hourProperty: Property<TimePicker, number>; export const maxHourProperty: Property<TimePicker, number>; export const minHourProperty: Property<TimePicker, number>; export const minuteProperty: Property<TimePicker, number>; export const maxMinuteProperty: Property<TimePicker, number>; export const minMinuteProperty: Property<TimePicker, number>; export const timeProperty: Property<TimePicker, Date>; export const minuteIntervalProperty: Property<TimePicker, number>; export const iosPreferredDatePickerStyleProperty: Property<TimePicker, number>;
NativeScript/NativeScript
packages/core/ui/time-picker/index.d.ts
TypeScript
mit
2,307
using System; namespace NgPlateVerifier { public class PlateInfo { public string PlateNumber { get; set; } public string Owner { get; set; } public string Color { get; set; } public string Model { get; set; } public string Chasis { get; set; } public string Status { get; set; } public DateTime LicenseIssueDate { get; set; } public DateTime LicenseExpiryDate { get; set; } } }
matmape/ngPlateNumberVerifier
PlateInfo.cs
C#
mit
455
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Container, TextInput, Label, Text, View, Button, } from 'react-native'; import LoginScreen from './Login.js'; import RegisterScreen from './Register.js'; import { StackNavigator, TabNavigator } from 'react-navigation'; export default class UserControlScreen extends Component { loginView(){ this.setState({view: <LoginScreen /> }) } constructor(){ super() this.loginView = this.loginView.bind(this) this.state = { view: <RegisterScreen press={this.loginView} /> } } render(){ return ( <View> </View> ) } }
nyc-fiery-skippers-2017/AwesomeProject
Users/UserControl.js
JavaScript
mit
671
require "spec_helper" RSpec.describe Realms::Cards::TradingPost do include_examples "type", :outpost include_examples "defense", 4 include_examples "factions", :trade_federation include_examples "cost", 3 describe "#primary_ability" do include_context "base_ability" do before do game.base_ability(card) end end context "authority" do it { expect { game.decide(:trading_post, :authority) }.to change { game.active_player.authority }.by(1) } end context "trade" do it { expect { game.decide(:trading_post, :trade) }.to change { game.active_turn.trade }.by(1) } end end describe "#scrap_ability" do include_context "scrap_ability" it { expect { game.scrap_ability(card) }.to change { game.active_turn.combat }.by(3) } end end
tonywok/realms
spec/cards/trading_post_spec.rb
Ruby
mit
809
import path from 'path'; const { SupRuntime, } = global; SupRuntime.registerPlugin('dependencyBundle', { loadAsset(player, asset, callback) { window.__dependencyBundles = window.__dependencyBundles || {}; const bundleScript = document.createElement('SCRIPT'); bundleScript.addEventListener('load', () => { callback(null, window.__dependencyBundles[asset.id]); }); bundleScript.src = path.join(player.dataURL, 'assets', asset.storagePath, 'bundle.js'); document.body.appendChild(bundleScript); }, });
antca/superpowers-package-manager-plugin
src/runtime/index.js
JavaScript
mit
538
let path = document.location.pathname, details, login, url; if (m = path.match(/^\/([\w-]+)\??.*?/)) { login = m[1].trim(); if (-1 === ['timeline', 'languages', 'blog', 'explore'].indexOf(login)) { url = 'http://coderstats.net/github#' + login; details = document.getElementsByClassName('vcard-details'); if (details.length > 0) { addLink(); } } } function addLink() { let li = document.createElement('li'); li.setAttribute('id', 'coderstats'); li.setAttribute('class', 'vcard-detail pt-1'); li.setAttribute('itemprop', 'url'); let span = document.createElement('span'); span.setAttribute('class', 'octicon'); span.setAttribute('style', 'margin-top:-2px;'); span.textContent = "📊"; li.appendChild(span) let a = document.createElement('a'); a.setAttribute('href', url); a.textContent = "CoderStats('" + login + "')"; li.appendChild(a); details[0].appendChild(li); }
coderstats/fxt_coderstats
coderstats/coderstats.js
JavaScript
mit
997
using System; using System.Runtime.InteropServices; namespace Vanara.PInvoke { public static partial class Kernel32 { /// <summary>The memory allocation attributes.</summary> [Flags] public enum GMEM { /// <summary>Combines GMEM_MOVEABLE and GMEM_ZEROINIT.</summary> GHND = 0x0042, /// <summary>Allocates fixed memory. The return value is a pointer.</summary> GMEM_FIXED = 0x0000, /// <summary> /// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap. /// <para>The return value is a handle to the memory object. To translate the handle into a pointer, use the GlobalLock function.</para> /// <para>This value cannot be combined with GMEM_FIXED.</para> /// </summary> GMEM_MOVEABLE = 0x0002, /// <summary>Initializes memory contents to zero.</summary> GMEM_ZEROINIT = 0x0040, /// <summary>Combines GMEM_FIXED and GMEM_ZEROINIT.</summary> GPTR = 0x0040, /// <summary> /// The function modifies the attributes of the memory object only (the dwBytes parameter is ignored). This value can only be /// used with <see cref="GlobalReAlloc"/>. /// </summary> GMEM_MODIFY = 0x0080, } /// <summary>The memory allocation attributes.</summary> [PInvokeData("MinWinBase.h")] [Flags] public enum LMEM { /// <summary>Allocates fixed memory. The return value is a pointer to the memory object.</summary> LMEM_FIXED = 0x0000, /// <summary> /// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap. /// The return value is a handle to the memory object. To translate the handle to a pointer, use the LocalLock function. This /// value cannot be combined with LMEM_FIXED. /// </summary> LMEM_MOVEABLE = 0x0002, /// <summary>Obsolete.</summary> [Obsolete] LMEM_NOCOMPACT = 0x0010, /// <summary>Obsolete.</summary> [Obsolete] LMEM_NODISCARD = 0x0020, /// <summary>Initializes memory contents to zero.</summary> LMEM_ZEROINIT = 0x0040, /// <summary> /// If the LMEM_MODIFY flag is specified in LocalReAlloc, this parameter modifies the attributes of the memory object, and the /// uBytes parameter is ignored. /// </summary> LMEM_MODIFY = 0x0080, /// <summary>Obsolete.</summary> [Obsolete] LMEM_DISCARDABLE = 0x0F00, /// <summary>Valid flags.</summary> LMEM_VALID_FLAGS = 0x0F72, /// <summary>Indicates that the local handle is not valid</summary> LMEM_INVALID_HANDLE = 0x8000, /// <summary>Combines LMEM_MOVEABLE and LMEM_ZEROINIT.</summary> LHND = LMEM_MOVEABLE | LMEM_ZEROINIT, /// <summary>Combines LMEM_FIXED and LMEM_ZEROINIT.</summary> LPTR = LMEM_FIXED | LMEM_ZEROINIT, /// <summary>Same as LMEM_MOVEABLE.</summary> NONZEROLHND = LMEM_MOVEABLE, /// <summary>Same as LMEM_FIXED.</summary> NONZEROLPTR = LMEM_FIXED } /// <summary>Allocates the specified number of bytes from the heap.</summary> /// <param name="uFlags"> /// <para> /// The memory allocation attributes. If zero is specified, the default is <c>GMEM_FIXED</c>. This parameter can be one or more of /// the following values, except for the incompatible combinations that are specifically noted. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>GHND0x0042</term> /// <term>Combines GMEM_MOVEABLE and GMEM_ZEROINIT.</term> /// </item> /// <item> /// <term>GMEM_FIXED0x0000</term> /// <term>Allocates fixed memory. The return value is a pointer.</term> /// </item> /// <item> /// <term>GMEM_MOVEABLE0x0002</term> /// <term> /// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap.The /// return value is a handle to the memory object. To translate the handle into a pointer, use the GlobalLock function.This value /// cannot be combined with GMEM_FIXED. /// </term> /// </item> /// <item> /// <term>GMEM_ZEROINIT0x0040</term> /// <term>Initializes memory contents to zero.</term> /// </item> /// <item> /// <term>GPTR0x0040</term> /// <term>Combines GMEM_FIXED and GMEM_ZEROINIT.</term> /// </item> /// </list> /// </para> /// <para>The following values are obsolete, but are provided for compatibility with 16-bit Windows. They are ignored.</para> /// </param> /// <param name="dwBytes"> /// The number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies <c>GMEM_MOVEABLE</c>, the function /// returns a handle to a memory object that is marked as discarded. /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to the newly allocated memory object.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // HGLOBAL WINAPI GlobalAlloc( _In_ UINT uFlags, _In_ SIZE_T dwBytes); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366574(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366574")] public static extern HGLOBAL GlobalAlloc(GMEM uFlags, SizeT dwBytes); /// <summary>Retrieves information about the specified global memory object.</summary> /// <param name="hMem"> /// A handle to the global memory object. This handle is returned by either the <c>GlobalAlloc</c> or <c>GlobalReAlloc</c> function. /// </param> /// <returns> /// <para>If the function succeeds, the return value specifies the allocation values and the lock count for the memory object.</para> /// <para> /// If the function fails, the return value is <c>GMEM_INVALID_HANDLE</c>, indicating that the global handle is not valid. To get /// extended error information, call <c>GetLastError</c>. /// </para> /// </returns> // UINT WINAPI GlobalFlags( _In_ HGLOBAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366577(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366577")] public static extern GMEM GlobalFlags([In] HGLOBAL hMem); /// <summary>Frees the specified global memory object and invalidates its handle.</summary> /// <param name="hMem"> /// A handle to the global memory object. This handle is returned by either the <c>GlobalAlloc</c> or <c>GlobalReAlloc</c> function. /// It is not safe to free memory allocated with <c>LocalAlloc</c>. /// </param> /// <returns> /// <para>If the function succeeds, the return value is <c>NULL</c>.</para> /// <para> /// If the function fails, the return value is equal to a handle to the global memory object. To get extended error information, call <c>GetLastError</c>. /// </para> /// </returns> // HGLOBAL WINAPI GlobalFree( _In_ HGLOBAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366579(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366579")] public static extern HGLOBAL GlobalFree(HGLOBAL hMem); /// <summary>Retrieves the handle associated with the specified pointer to a global memory block.</summary> /// <param name="pMem"> /// A pointer to the first byte of the global memory block. This pointer is returned by the <c>GlobalLock</c> function. /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to the specified global memory object.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // HGLOBAL WINAPI GlobalHandle( _In_ LPCVOID pMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366582(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366582")] public static extern HGLOBAL GlobalHandle([In] IntPtr pMem); /// <summary> /// <para>Locks a global memory object and returns a pointer to the first byte of the object's memory block.</para> /// <para> /// <c>Note</c> The global functions have greater overhead and provide fewer features than other memory management functions. New /// applications should use the heap functions unless documentation states that a global function should be used. For more /// information, see Global and Local Functions. /// </para> /// </summary> /// <param name="hMem"> /// <para>A handle to the global memory object. This handle is returned by either the GlobalAlloc or GlobalReAlloc function.</para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a pointer to the first byte of the memory block.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call GetLastError.</para> /// </returns> /// <remarks> /// <para> /// The internal data structures for each memory object include a lock count that is initially zero. For movable memory objects, /// <c>GlobalLock</c> increments the count by one, and the GlobalUnlock function decrements the count by one. Each successful call /// that a process makes to <c>GlobalLock</c> for an object must be matched by a corresponding call to <c>GlobalUnlock</c>. Locked /// memory will not be moved or discarded, unless the memory object is reallocated by using the GlobalReAlloc function. The memory /// block of a locked memory object remains locked until its lock count is decremented to zero, at which time it can be moved or discarded. /// </para> /// <para> /// Memory objects allocated with <c>GMEM_FIXED</c> always have a lock count of zero. For these objects, the value of the returned /// pointer is equal to the value of the specified handle. /// </para> /// <para>If the specified memory block has been discarded or if the memory block has a zero-byte size, this function returns <c>NULL</c>.</para> /// <para>Discarded objects always have a lock count of zero.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-globallock LPVOID GlobalLock( HGLOBAL hMem ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("winbase.h", MSDNShortId = "0d7deac2-c9c4-4adc-8a0a-edfc512a4d6c")] public static extern IntPtr GlobalLock(HGLOBAL hMem); /// <summary>Changes the size or attributes of a specified global memory object. The size can increase or decrease.</summary> /// <param name="hMem"> /// A handle to the global memory object to be reallocated. This handle is returned by either the <c>GlobalAlloc</c> or /// <c>GlobalReAlloc</c> function. /// </param> /// <param name="dwBytes"> /// The new size of the memory block, in bytes. If uFlags specifies <c>GMEM_MODIFY</c>, this parameter is ignored. /// </param> /// <param name="uFlags"> /// <para> /// The reallocation options. If <c>GMEM_MODIFY</c> is specified, the function modifies the attributes of the memory object only (the /// dwBytes parameter is ignored.) Otherwise, the function reallocates the memory object. /// </para> /// <para>You can optionally combine <c>GMEM_MODIFY</c> with the following value.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>GMEM_MOVEABLE0x0002</term> /// <term> /// Allocates movable memory.If the memory is a locked GMEM_MOVEABLE memory block or a GMEM_FIXED memory block and this flag is not /// specified, the memory can only be reallocated in place. /// </term> /// </item> /// </list> /// </para> /// <para>If this parameter does not specify <c>GMEM_MODIFY</c>, you can use the following value.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>GMEM_ZEROINIT0x0040</term> /// <term>Causes the additional memory contents to be initialized to zero if the memory object is growing in size.</term> /// </item> /// </list> /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to the reallocated memory object.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // HGLOBAL WINAPI GlobalReAlloc( _In_ HGLOBAL hMem, _In_ SIZE_T dwBytes, _In_ UINT uFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366590(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366590")] public static extern HGLOBAL GlobalReAlloc([In] HGLOBAL hMem, SizeT dwBytes, GMEM uFlags); /// <summary>Retrieves the current size of the specified global memory object, in bytes.</summary> /// <param name="hMem"> /// A handle to the global memory object. This handle is returned by either the <c>GlobalAlloc</c> or <c>GlobalReAlloc</c> function. /// </param> /// <returns> /// <para>If the function succeeds, the return value is the size of the specified global memory object, in bytes.</para> /// <para> /// If the specified handle is not valid or if the object has been discarded, the return value is zero. To get extended error /// information, call <c>GetLastError</c>. /// </para> /// </returns> // SIZE_T WINAPI GlobalSize( _In_ HGLOBAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366593(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366593")] public static extern SizeT GlobalSize([In] HGLOBAL hMem); /// <summary> /// <para> /// Decrements the lock count associated with a memory object that was allocated with <c>GMEM_MOVEABLE</c>. This function has no /// effect on memory objects allocated with <c>GMEM_FIXED</c>. /// </para> /// <para> /// <c>Note</c> The global functions have greater overhead and provide fewer features than other memory management functions. New /// applications should use the heap functions unless documentation states that a global function should be used. For more /// information, see Global and Local Functions. /// </para> /// </summary> /// <param name="hMem"> /// <para>A handle to the global memory object. This handle is returned by either the GlobalAlloc or GlobalReAlloc function.</para> /// </param> /// <returns> /// <para> /// If the memory object is still locked after decrementing the lock count, the return value is a nonzero value. If the memory object /// is unlocked after decrementing the lock count, the function returns zero and GetLastError returns <c>NO_ERROR</c>. /// </para> /// <para>If the function fails, the return value is zero and GetLastError returns a value other than <c>NO_ERROR</c>.</para> /// </returns> /// <remarks> /// <para> /// The internal data structures for each memory object include a lock count that is initially zero. For movable memory objects, the /// GlobalLock function increments the count by one, and <c>GlobalUnlock</c> decrements the count by one. For each call that a /// process makes to <c>GlobalLock</c> for an object, it must eventually call <c>GlobalUnlock</c>. Locked memory will not be moved or /// discarded, unless the memory object is reallocated by using the GlobalReAlloc function. The memory block of a locked memory /// object remains locked until its lock count is decremented to zero, at which time it can be moved or discarded. /// </para> /// <para> /// Memory objects allocated with <c>GMEM_FIXED</c> always have a lock count of zero. If the specified memory block is fixed memory, /// this function returns <c>TRUE</c>. /// </para> /// <para>If the memory object is already unlocked, <c>GlobalUnlock</c> returns <c>FALSE</c> and GetLastError reports <c>ERROR_NOT_LOCKED</c>.</para> /// <para> /// A process should not rely on the return value to determine the number of times it must subsequently call <c>GlobalUnlock</c> for /// a memory object. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-globalunlock BOOL GlobalUnlock( HGLOBAL hMem ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("winbase.h", MSDNShortId = "580a2873-7f06-47a1-acf5-c2b3c96e15e7")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GlobalUnlock(HGLOBAL hMem); /// <summary>Determines whether the calling process has read access to the memory at the specified address.</summary> /// <param name="lpfn">A pointer to a memory address.</param> /// <returns> /// <para>If the calling process has read access to the specified memory, the return value is zero.</para> /// <para> /// If the calling process does not have read access to the specified memory, the return value is nonzero. To get extended error /// information, call <c>GetLastError</c>. /// </para> /// <para> /// If the application is compiled as a debugging version, and the process does not have read access to the specified memory /// location, the function causes an assertion and breaks into the debugger. Leaving the debugger, the function continues as usual, /// and returns a nonzero value. This behavior is by design, as a debugging aid. /// </para> /// </returns> // BOOL WINAPI IsBadCodePtr( _In_ FARPROC lpfn); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366712(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366712")] [Obsolete("This function is obsolete and should not be used. Despite its name, it does not guarantee that the pointer is valid or that the memory pointed to is safe to use.")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsBadCodePtr(IntPtr lpfn); /// <summary>Verifies that the calling process has read access to the specified range of memory.</summary> /// <param name="lp">A pointer to the first byte of the memory block.</param> /// <param name="ucb">The size of the memory block, in bytes. If this parameter is zero, the return value is zero.</param> /// <returns> /// <para>If the calling process has read access to all bytes in the specified memory range, the return value is zero.</para> /// <para>If the calling process does not have read access to all bytes in the specified memory range, the return value is nonzero.</para> /// <para> /// If the application is compiled as a debugging version, and the process does not have read access to all bytes in the specified /// memory range, the function causes an assertion and breaks into the debugger. Leaving the debugger, the function continues as /// usual, and returns a nonzero value. This behavior is by design, as a debugging aid. /// </para> /// </returns> // BOOL WINAPI IsBadReadPtr( _In_ const VOID *lp, _In_ UINT_PTR ucb); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366713(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366713")] [Obsolete("This function is obsolete and should not be used. Despite its name, it does not guarantee that the pointer is valid or that the memory pointed to is safe to use.")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsBadReadPtr([In] IntPtr lp, SizeT ucb); /// <summary>Verifies that the calling process has read access to the specified range of memory.</summary> /// <param name="lpsz">A pointer to a null-terminated string, either Unicode or ASCII.</param> /// <param name="ucchMax"> /// The maximum size of the string, in <c>TCHARs</c>. The function checks for read access in all characters up to the string's /// terminating null character or up to the number of characters specified by this parameter, whichever is smaller. If this parameter /// is zero, the return value is zero. /// </param> /// <returns> /// <para> /// If the calling process has read access to all characters up to the string's terminating null character or up to the number of /// characters specified by ucchMax, the return value is zero. /// </para> /// <para> /// If the calling process does not have read access to all characters up to the string's terminating null character or up to the /// number of characters specified by ucchMax, the return value is nonzero. /// </para> /// <para> /// If the application is compiled as a debugging version, and the process does not have read access to the entire memory range /// specified, the function causes an assertion and breaks into the debugger. Leaving the debugger, the function continues as usual, /// and returns a nonzero value This behavior is by design, as a debugging aid. /// </para> /// </returns> // BOOL WINAPI IsBadStringPtr( _In_ LPCTSTR lpsz, _In_ UINT_PTR ucchMax); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366714(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "aa366714")] [Obsolete("This function is obsolete and should not be used. Despite its name, it does not guarantee that the pointer is valid or that the memory pointed to is safe to use.")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsBadStringPtr(string lpsz, SizeT ucchMax); /// <summary>Verifies that the calling process has write access to the specified range of memory.</summary> /// <param name="lp">A pointer to the first byte of the memory block.</param> /// <param name="ucb">The size of the memory block, in bytes. If this parameter is zero, the return value is zero.</param> /// <returns> /// <para>If the calling process has write access to all bytes in the specified memory range, the return value is zero.</para> /// <para>If the calling process does not have write access to all bytes in the specified memory range, the return value is nonzero.</para> /// <para> /// If the application is run under a debugger and the process does not have write access to all bytes in the specified memory range, /// the function causes a first chance STATUS_ACCESS_VIOLATION exception. The debugger can be configured to break for this condition. /// After resuming process execution in the debugger, the function continues as usual and returns a nonzero value This behavior is by /// design and serves as a debugging aid. /// </para> /// </returns> // BOOL WINAPI IsBadWritePtr( _In_ LPVOID lp, _In_ UINT_PTR ucb); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366716(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366716")] [Obsolete("This function is obsolete and should not be used. Despite its name, it does not guarantee that the pointer is valid or that the memory pointed to is safe to use.")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsBadWritePtr([In] IntPtr lp, SizeT ucb); /// <summary> /// <para>Allocates the specified number of bytes from the heap.</para> /// <para> /// <c>Note</c> The local functions have greater overhead and provide fewer features than other memory management functions. New /// applications should use the heap functions unless documentation states that a local function should be used. For more /// information, see Global and Local Functions. /// </para> /// </summary> /// <param name="uFlags"> /// <para> /// The memory allocation attributes. The default is the <c>LMEM_FIXED</c> value. This parameter can be one or more of the following /// values, except for the incompatible combinations that are specifically noted. /// </para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>LHND 0x0042</term> /// <term>Combines LMEM_MOVEABLE and LMEM_ZEROINIT.</term> /// </item> /// <item> /// <term>LMEM_FIXED 0x0000</term> /// <term>Allocates fixed memory. The return value is a pointer to the memory object.</term> /// </item> /// <item> /// <term>LMEM_MOVEABLE 0x0002</term> /// <term> /// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap. The /// return value is a handle to the memory object. To translate the handle to a pointer, use the LocalLock function. This value /// cannot be combined with LMEM_FIXED. /// </term> /// </item> /// <item> /// <term>LMEM_ZEROINIT 0x0040</term> /// <term>Initializes memory contents to zero.</term> /// </item> /// <item> /// <term>LPTR 0x0040</term> /// <term>Combines LMEM_FIXED and LMEM_ZEROINIT.</term> /// </item> /// <item> /// <term>NONZEROLHND</term> /// <term>Same as LMEM_MOVEABLE.</term> /// </item> /// <item> /// <term>NONZEROLPTR</term> /// <term>Same as LMEM_FIXED.</term> /// </item> /// </list> /// <para>The following values are obsolete, but are provided for compatibility with 16-bit Windows. They are ignored.</para> /// </param> /// <param name="uBytes"> /// <para> /// The number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies <c>LMEM_MOVEABLE</c>, the function /// returns a handle to a memory object that is marked as discarded. /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to the newly allocated memory object.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call GetLastError.</para> /// </returns> /// <remarks> /// <para> /// Windows memory management does not provide a separate local heap and global heap. Therefore, the <c>LocalAlloc</c> and /// GlobalAlloc functions are essentially the same. /// </para> /// <para> /// The movable-memory flags <c>LHND</c>, <c>LMEM_MOVABLE</c>, and <c>NONZEROLHND</c> add unnecessary overhead and require locking to /// be used safely. They should be avoided unless documentation specifically states that they should be used. /// </para> /// <para> /// New applications should use the heap functions unless the documentation specifically states that a local function should be used. /// For example, some Windows functions allocate memory that must be freed with LocalFree. /// </para> /// <para> /// If the heap does not contain sufficient free space to satisfy the request, <c>LocalAlloc</c> returns <c>NULL</c>. Because /// <c>NULL</c> is used to indicate an error, virtual address zero is never allocated. It is, therefore, easy to detect the use of a /// <c>NULL</c> pointer. /// </para> /// <para> /// If the <c>LocalAlloc</c> function succeeds, it allocates at least the amount requested. If the amount allocated is greater than /// the amount requested, the process can use the entire amount. To determine the actual number of bytes allocated, use the LocalSize function. /// </para> /// <para>To free the memory, use the LocalFree function. It is not safe to free memory allocated with <c>LocalAlloc</c> using GlobalFree.</para> /// <para>Examples</para> /// <para>The following code shows a simple use of <c>LocalAlloc</c> and LocalFree.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-localalloc DECLSPEC_ALLOCATOR HLOCAL LocalAlloc( UINT // uFlags, SIZE_T uBytes ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("winbase.h", MSDNShortId = "da8cd2be-ff4c-4da5-813c-8759a58228c9")] public static extern HLOCAL LocalAlloc(LMEM uFlags, SizeT uBytes); /// <summary>Retrieves information about the specified local memory object.</summary> /// <param name="hMem"> /// A handle to the local memory object. This handle is returned by either the <c>LocalAlloc</c> or <c>LocalReAlloc</c> function. /// </param> /// <returns> /// <para>If the function succeeds, the return value specifies the allocation values and the lock count for the memory object.</para> /// <para> /// If the function fails, the return value is <c>LMEM_INVALID_HANDLE</c>, indicating that the local handle is not valid. To get /// extended error information, call <c>GetLastError</c>. /// </para> /// </returns> // UINT WINAPI LocalFlags( _In_ HLOCAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366728(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366728")] public static extern LMEM LocalFlags([In] HLOCAL hMem); /// <summary> /// <para>Frees the specified local memory object and invalidates its handle.</para> /// <para> /// <c>Note</c> The local functions have greater overhead and provide fewer features than other memory management functions. New /// applications should use the heap functions unless documentation states that a local function should be used. For more /// information, see Global and Local Functions. /// </para> /// </summary> /// <param name="hMem"> /// <para> /// A handle to the local memory object. This handle is returned by either the LocalAlloc or LocalReAlloc function. It is not safe to /// free memory allocated with GlobalAlloc. /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is <c>NULL</c>.</para> /// <para> /// If the function fails, the return value is equal to a handle to the local memory object. To get extended error information, call GetLastError. /// </para> /// </returns> /// <remarks> /// <para> /// If the process tries to examine or modify the memory after it has been freed, heap corruption may occur or an access violation /// exception (EXCEPTION_ACCESS_VIOLATION) may be generated. /// </para> /// <para>If the hMem parameter is <c>NULL</c>, <c>LocalFree</c> ignores the parameter and returns <c>NULL</c>.</para> /// <para> /// The <c>LocalFree</c> function will free a locked memory object. A locked memory object has a lock count greater than zero. The /// LocalLock function locks a local memory object and increments the lock count by one. The LocalUnlock function unlocks it and /// decrements the lock count by one. To get the lock count of a local memory object, use the LocalFlags function. /// </para> /// <para> /// If an application is running under a debug version of the system, <c>LocalFree</c> will issue a message that tells you that a /// locked object is being freed. If you are debugging the application, <c>LocalFree</c> will enter a breakpoint just before freeing /// a locked object. This allows you to verify the intended behavior, then continue execution. /// </para> /// <para>Examples</para> /// <para>For an example, see LocalAlloc.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-localfree HLOCAL LocalFree( _Frees_ptr_opt_ HLOCAL hMem ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("winbase.h", MSDNShortId = "a0393983-cb43-4dfa-91a6-d82a5fb8de12")] public static extern HLOCAL LocalFree(HLOCAL hMem); /// <summary>Retrieves the handle associated with the specified pointer to a local memory object.</summary> /// <param name="pMem"> /// A pointer to the first byte of the local memory object. This pointer is returned by the <c>LocalLock</c> function. /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to the specified local memory object.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // HLOCAL WINAPI LocalHandle( _In_ LPCVOID pMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366733(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366733")] public static extern HLOCAL LocalHandle([In] IntPtr pMem); /// <summary>Locks a local memory object and returns a pointer to the first byte of the object's memory block.</summary> /// <param name="hMem"> /// A handle to the local memory object. This handle is returned by either the <c>LocalAlloc</c> or <c>LocalReAlloc</c> function. /// </param> /// <returns> /// <para>If the function succeeds, the return value is a pointer to the first byte of the memory block.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // LPVOID WINAPI LocalLock( _In_ HLOCAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366737(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366737")] public static extern IntPtr LocalLock([In] HLOCAL hMem); /// <summary> /// <para>Changes the size or the attributes of a specified local memory object. The size can increase or decrease.</para> /// <para> /// <c>Note</c> The local functions have greater overhead and provide fewer features than other memory management functions. New /// applications should use the heap functions unless documentation states that a local function should be used. For more /// information, see Global and Local Functions. /// </para> /// </summary> /// <param name="hMem"> /// <para> /// A handle to the local memory object to be reallocated. This handle is returned by either the LocalAlloc or <c>LocalReAlloc</c> function. /// </para> /// </param> /// <param name="uBytes"> /// <para>The new size of the memory block, in bytes. If uFlags specifies <c>LMEM_MODIFY</c>, this parameter is ignored.</para> /// </param> /// <param name="uFlags"> /// <para> /// The reallocation options. If <c>LMEM_MODIFY</c> is specified, the function modifies the attributes of the memory object only (the /// uBytes parameter is ignored.) Otherwise, the function reallocates the memory object. /// </para> /// <para>You can optionally combine <c>LMEM_MODIFY</c> with the following value.</para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>LMEM_MOVEABLE 0x0002</term> /// <term> /// Allocates fixed or movable memory. If the memory is a locked LMEM_MOVEABLE memory block or a LMEM_FIXED memory block and this /// flag is not specified, the memory can only be reallocated in place. /// </term> /// </item> /// </list> /// <para>If this parameter does not specify <c>LMEM_MODIFY</c>, you can use the following value.</para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>LMEM_ZEROINIT 0x0040</term> /// <term>Causes the additional memory contents to be initialized to zero if the memory object is growing in size.</term> /// </item> /// </list> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to the reallocated memory object.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call GetLastError.</para> /// </returns> /// <remarks> /// <para>If <c>LocalReAlloc</c> fails, the original memory is not freed, and the original handle and pointer are still valid.</para> /// <para> /// If <c>LocalReAlloc</c> reallocates a fixed object, the value of the handle returned is the address of the first byte of the /// memory block. To access the memory, a process can simply cast the return value to a pointer. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-localrealloc DECLSPEC_ALLOCATOR HLOCAL LocalReAlloc( // _Frees_ptr_opt_ HLOCAL hMem, SIZE_T uBytes, UINT uFlags ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("winbase.h", MSDNShortId = "88527ddd-e0c2-4a41-825e-d3a6df77fd2a")] public static extern HLOCAL LocalReAlloc(HLOCAL hMem, SizeT uBytes, LMEM uFlags); /// <summary> /// <para>Retrieves the current size of the specified local memory object, in bytes.</para> /// <para> /// <c>Note</c> The local functions have greater overhead and provide fewer features than other memory management functions. New /// applications should use the heap functions unless documentation states that a local function should be used. For more /// information, see Global and Local Functions. /// </para> /// </summary> /// <param name="hMem"> /// <para>A handle to the local memory object. This handle is returned by the LocalAlloc, LocalReAlloc, or LocalHandle function.</para> /// </param> /// <returns> /// <para> /// If the function succeeds, the return value is the size of the specified local memory object, in bytes. If the specified handle is /// not valid or if the object has been discarded, the return value is zero. To get extended error information, call GetLastError. /// </para> /// </returns> /// <remarks> /// <para>The size of a memory block may be larger than the size requested when the memory was allocated.</para> /// <para> /// To verify that the specified object's memory block has not been discarded, call the LocalFlags function before calling <c>LocalSize</c>. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-localsize SIZE_T LocalSize( HLOCAL hMem ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("winbase.h", MSDNShortId = "d1337845-d89c-4cd5-a584-36fe0c682c1a")] public static extern SizeT LocalSize(HLOCAL hMem); /// <summary> /// Decrements the lock count associated with a memory object that was allocated with <c>LMEM_MOVEABLE</c>. This function has no /// effect on memory objects allocated with <c>LMEM_FIXED</c>. /// </summary> /// <param name="hMem"> /// A handle to the local memory object. This handle is returned by either the <c>LocalAlloc</c> or <c>LocalReAlloc</c> function. /// </param> /// <returns> /// <para> /// If the memory object is still locked after decrementing the lock count, the return value is nonzero. If the memory object is /// unlocked after decrementing the lock count, the function returns zero and <c>GetLastError</c> returns <c>NO_ERROR</c>. /// </para> /// <para>If the function fails, the return value is zero and <c>GetLastError</c> returns a value other than <c>NO_ERROR</c>.</para> /// </returns> // BOOL WINAPI LocalUnlock( _In_ HLOCAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366747(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366747")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool LocalUnlock([In] HLOCAL hMem); /// <summary>Provides a handle to heap allocated memory.</summary> [StructLayout(LayoutKind.Sequential)] public struct HGLOBAL : IHandle { private IntPtr handle; /// <summary>Initializes a new instance of the <see cref="HGLOBAL"/> struct.</summary> /// <param name="preexistingHandle">An <see cref="IntPtr"/> object that represents the pre-existing handle to use.</param> public HGLOBAL(IntPtr preexistingHandle) => handle = preexistingHandle; /// <summary>Returns an invalid handle by instantiating a <see cref="HGLOBAL"/> object with <see cref="IntPtr.Zero"/>.</summary> public static HGLOBAL NULL => new HGLOBAL(IntPtr.Zero); /// <summary>Gets a value indicating whether this instance is a null handle.</summary> public bool IsNull => handle == IntPtr.Zero; /// <summary>Performs an explicit conversion from <see cref="HGLOBAL"/> to <see cref="IntPtr"/>.</summary> /// <param name="h">The handle.</param> /// <returns>The result of the conversion.</returns> public static explicit operator IntPtr(HGLOBAL h) => h.handle; /// <summary>Performs an implicit conversion from <see cref="IntPtr"/> to <see cref="HGLOBAL"/>.</summary> /// <param name="h">The pointer to a handle.</param> /// <returns>The result of the conversion.</returns> public static implicit operator HGLOBAL(IntPtr h) => new HGLOBAL(h); /// <summary>Implements the operator !=.</summary> /// <param name="h1">The first handle.</param> /// <param name="h2">The second handle.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(HGLOBAL h1, HGLOBAL h2) => !(h1 == h2); /// <summary>Implements the operator ==.</summary> /// <param name="h1">The first handle.</param> /// <param name="h2">The second handle.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(HGLOBAL h1, HGLOBAL h2) => h1.Equals(h2); /// <inheritdoc/> public override bool Equals(object obj) => obj is HGLOBAL h ? handle == h.handle : false; /// <inheritdoc/> public override int GetHashCode() => handle.GetHashCode(); /// <inheritdoc/> public IntPtr DangerousGetHandle() => handle; } /// <summary>Provides a handle to a local heap allocation.</summary> [StructLayout(LayoutKind.Sequential)] public struct HLOCAL : IHandle { private IntPtr handle; /// <summary>Initializes a new instance of the <see cref="HLOCAL"/> struct.</summary> /// <param name="preexistingHandle">An <see cref="IntPtr"/> object that represents the pre-existing handle to use.</param> public HLOCAL(IntPtr preexistingHandle) => handle = preexistingHandle; /// <summary>Returns an invalid handle by instantiating a <see cref="HLOCAL"/> object with <see cref="IntPtr.Zero"/>.</summary> public static HLOCAL NULL => new HLOCAL(IntPtr.Zero); /// <summary>Gets a value indicating whether this instance is a null handle.</summary> public bool IsNull => handle == IntPtr.Zero; /// <summary>Performs an explicit conversion from <see cref="HLOCAL"/> to <see cref="IntPtr"/>.</summary> /// <param name="h">The handle.</param> /// <returns>The result of the conversion.</returns> public static explicit operator IntPtr(HLOCAL h) => h.handle; /// <summary>Performs an implicit conversion from <see cref="IntPtr"/> to <see cref="HLOCAL"/>.</summary> /// <param name="h">The pointer to a handle.</param> /// <returns>The result of the conversion.</returns> public static implicit operator HLOCAL(IntPtr h) => new HLOCAL(h); /// <summary>Implements the operator !=.</summary> /// <param name="h1">The first handle.</param> /// <param name="h2">The second handle.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(HLOCAL h1, HLOCAL h2) => !(h1 == h2); /// <summary>Implements the operator ==.</summary> /// <param name="h1">The first handle.</param> /// <param name="h2">The second handle.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(HLOCAL h1, HLOCAL h2) => h1.Equals(h2); /// <inheritdoc/> public override bool Equals(object obj) => obj is HLOCAL h ? handle == h.handle : false; /// <inheritdoc/> public override int GetHashCode() => handle.GetHashCode(); /// <inheritdoc/> public IntPtr DangerousGetHandle() => handle; } } }
dahall/vanara
PInvoke/Kernel32/WinBase.MemMgmt.cs
C#
mit
44,045
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// #include <ImfTiledOutputFile.h> #include <ImfInputFile.h> #include <ImathRandom.h> #include <ImfTiledInputFile.h> #include <ImfChannelList.h> #include <ImfArray.h> #include <ImfThreading.h> #include <IlmThread.h> #include <half.h> #include <vector> #include <stdio.h> #include <assert.h> #include "tmpDir.h" using namespace OPENEXR_IMF_NAMESPACE; using namespace std; using namespace IMATH_NAMESPACE; namespace { void fillPixels (Array2D<half> &ph, int width, int height) { for (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x) ph[y][x] = sin (double (x)) + sin (y * 0.5); } void writeCopyReadONE (const char fileName[], int width, int height, LineOrder lorder, LevelRoundingMode rmode, int xSize, int ySize, Compression comp, bool triggerBuffering, bool triggerSeeks) { cout << "LineOrder " << lorder << ", buffer " << triggerBuffering << ", seek " << triggerSeeks << ", levelMode 0, " << "roundingMode " << rmode << ", " "compression " << comp << endl; Header hdr ((Box2i (V2i (0, 0), // display window V2i (width - 1, height -1))), (Box2i (V2i (0, 0), // data window V2i (width - 1, height - 1)))); hdr.compression() = comp; hdr.lineOrder() = INCREASING_Y; hdr.channels().insert ("H", Channel (HALF, 1, 1)); hdr.setTileDescription(TileDescription(xSize, ySize, ONE_LEVEL, rmode)); Array2D<half> ph1 (height, width); fillPixels (ph1, width, height); { FrameBuffer fb; fb.insert ("H", Slice (HALF, (char *) &ph1[0][0], sizeof (ph1[0][0]), sizeof (ph1[0][0]) * width)); cout << " writing" << flush; remove (fileName); TiledOutputFile out (fileName, hdr); out.setFrameBuffer (fb); int i; Rand32 rand1 = Rand32(); std::vector<int> tileYs = std::vector<int>(out.numYTiles()); std::vector<int> tileXs = std::vector<int>(out.numXTiles()); for (i = 0; i < out.numYTiles(); i++) { if (lorder == DECREASING_Y) tileYs[out.numYTiles()-1-i] = i; else tileYs[i] = i; } for (i = 0; i < out.numXTiles(); i++) { tileXs[i] = i; } if (triggerBuffering) { // shuffle the tile orders for (i = 0; i < out.numYTiles(); i++) std::swap(tileYs[i], tileYs[int(rand1.nextf(i,out.numYTiles()-1) + 0.5)]); for (i = 0; i < out.numXTiles(); i++) std::swap(tileXs[i], tileXs[int(rand1.nextf(i,out.numXTiles()-1) + 0.5)]); } for (int tileY = 0; tileY < out.numYTiles(); tileY++) for (int tileX = 0; tileX < out.numXTiles(); tileX++) out.writeTile (tileXs[tileX], tileYs[tileY]); } { cout << " reading" << flush; TiledInputFile in (fileName); const Box2i &dw = in.header().dataWindow(); int w = dw.max.x - dw.min.x + 1; int h = dw.max.y - dw.min.y + 1; int dwx = dw.min.x; int dwy = dw.min.y; Array2D<half> ph2 (h, w); FrameBuffer fb; fb.insert ("H", Slice (HALF, (char *) &ph2[-dwy][-dwx], sizeof (ph2[0][0]), sizeof (ph2[0][0]) * w)); in.setFrameBuffer (fb); int startTileY, endTileY; int dy; if ((lorder == DECREASING_Y && !triggerSeeks) || (lorder == INCREASING_Y && triggerSeeks) || (lorder == RANDOM_Y && triggerSeeks)) { startTileY = in.numYTiles() - 1; endTileY = -1; dy = -1; } else { startTileY = 0; endTileY = in.numYTiles(); dy = 1; } for (int tileY = startTileY; tileY != endTileY; tileY += dy) for (int tileX = 0; tileX < in.numXTiles(); ++tileX) in.readTile (tileX, tileY); cout << " comparing" << flush; assert (in.header().displayWindow() == hdr.displayWindow()); assert (in.header().dataWindow() == hdr.dataWindow()); assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio()); assert (in.header().screenWindowCenter() == hdr.screenWindowCenter()); assert (in.header().screenWindowWidth() == hdr.screenWindowWidth()); assert (in.header().lineOrder() == hdr.lineOrder()); assert (in.header().compression() == hdr.compression()); assert (in.header().channels() == hdr.channels()); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) assert (ph1[y][x] == ph2[y][x]); } remove (fileName); cout << endl; } void writeCopyReadMIP (const char fileName[], int width, int height, LineOrder lorder, LevelRoundingMode rmode, int xSize, int ySize, Compression comp, bool triggerBuffering, bool triggerSeeks) { cout << "LineOrder " << lorder << ", buffer " << triggerBuffering << ", seek " << triggerSeeks << ", levelMode 1, " << "roundingMode " << rmode << ", " "compression " << comp << endl; Header hdr ((Box2i (V2i (0, 0), // display window V2i (width - 1, height -1))), (Box2i (V2i (0, 0), // data window V2i (width - 1, height - 1)))); hdr.compression() = comp; hdr.lineOrder() = INCREASING_Y; hdr.channels().insert ("H", Channel (HALF, 1, 1)); hdr.setTileDescription(TileDescription(xSize, ySize, MIPMAP_LEVELS, rmode)); Array < Array2D<half> > levels; { cout << " writing" << flush; remove (fileName); TiledOutputFile out (fileName, hdr); int numLevels = out.numLevels(); levels.resizeErase (numLevels); int i; Rand32 rand1 = Rand32(); std::vector<int> shuffled_levels = std::vector<int>(numLevels); for (i = 0; i < numLevels; i++) shuffled_levels[i] = i; if (triggerBuffering) // shuffle the level order for (i = 0; i < numLevels; i++) std::swap(shuffled_levels[i], shuffled_levels[int(rand1.nextf(i,numLevels-1) + 0.5)]); for (int level = 0; level < numLevels; ++level) { const int slevel = shuffled_levels[level]; int levelWidth = out.levelWidth(slevel); int levelHeight = out.levelHeight(slevel); levels[slevel].resizeErase(levelHeight, levelWidth); fillPixels (levels[slevel], levelWidth, levelHeight); FrameBuffer fb; fb.insert ("H", Slice (HALF, (char *) &levels[slevel][0][0], sizeof (levels[slevel][0][0]), sizeof (levels[slevel][0][0]) * levelWidth)); out.setFrameBuffer (fb); std::vector<int> tileYs = std::vector<int>(out.numYTiles(slevel)); std::vector<int> tileXs = std::vector<int>(out.numXTiles(slevel)); for (i = 0; i < out.numYTiles(slevel); i++) { if (lorder == DECREASING_Y) tileYs[out.numYTiles(slevel)-1-i] = i; else tileYs[i] = i; } for (i = 0; i < out.numXTiles(slevel); i++) tileXs[i] = i; if (triggerBuffering) { // shuffle the tile orders for (i = 0; i < out.numYTiles(slevel); i++) std::swap(tileYs[i], tileYs[int(rand1.nextf(i,out.numYTiles(slevel)-1) + 0.5)]); for (i = 0; i < out.numXTiles(slevel); i++) std::swap(tileXs[i], tileXs[int(rand1.nextf(i,out.numXTiles(slevel)-1) + 0.5)]); } for (int tileY = 0; tileY < out.numYTiles(slevel); ++tileY) for (int tileX = 0; tileX < out.numXTiles(slevel); ++tileX) out.writeTile (tileXs[tileX], tileYs[tileY], slevel); } } { cout << " reading" << flush; TiledInputFile in (fileName); const Box2i &dw = in.header().dataWindow(); int dwx = dw.min.x; int dwy = dw.min.y; int numLevels = in.numLevels(); Array < Array2D<half> > levels2 (numLevels); int startTileY, endTileY; int dy; for (int level = 0; level < in.numLevels(); ++level) { int levelWidth = in.levelWidth(level); int levelHeight = in.levelHeight(level); levels2[level].resizeErase(levelHeight, levelWidth); FrameBuffer fb; fb.insert ("H", Slice (HALF, (char *) &levels2[level][-dwy][-dwx], sizeof (levels2[level][0][0]), sizeof (levels2[level][0][0]) * levelWidth)); in.setFrameBuffer (fb); if ((lorder == DECREASING_Y && !triggerSeeks) || (lorder == INCREASING_Y && triggerSeeks) || (lorder == RANDOM_Y && triggerSeeks)) { startTileY = in.numYTiles(level) - 1; endTileY = -1; dy = -1; } else { startTileY = 0; endTileY = in.numYTiles(level); dy = 1; } for (int tileY = startTileY; tileY != endTileY; tileY += dy) for (int tileX = 0; tileX < in.numXTiles (level); ++tileX) in.readTile (tileX, tileY, level); } cout << " comparing" << flush; assert (in.header().displayWindow() == hdr.displayWindow()); assert (in.header().dataWindow() == hdr.dataWindow()); assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio()); assert (in.header().screenWindowCenter() == hdr.screenWindowCenter()); assert (in.header().screenWindowWidth() == hdr.screenWindowWidth()); assert (in.header().lineOrder() == hdr.lineOrder()); assert (in.header().compression() == hdr.compression()); assert (in.header().channels() == hdr.channels()); for (int l = 0; l < numLevels; ++l) for (int y = 0; y < in.levelHeight(l); ++y) for (int x = 0; x < in.levelWidth(l); ++x) assert ((levels2[l])[y][x] == (levels[l])[y][x]); } remove (fileName); cout << endl; } void writeCopyReadRIP (const char fileName[], int width, int height, LineOrder lorder, LevelRoundingMode rmode, int xSize, int ySize, Compression comp, bool triggerBuffering, bool triggerSeeks) { cout << "LineOrder " << lorder << ", buffer " << triggerBuffering << ", seek " << triggerSeeks << ", levelMode 2, " << "roundingMode " << rmode << ", " "compression " << comp << endl; Header hdr ((Box2i (V2i (0, 0), // display window V2i (width - 1, height -1))), (Box2i (V2i (0, 0), // data window V2i (width - 1, height - 1)))); hdr.compression() = comp; hdr.lineOrder() = INCREASING_Y; hdr.channels().insert ("H", Channel (HALF, 1, 1)); hdr.setTileDescription(TileDescription(xSize, ySize, RIPMAP_LEVELS, rmode)); Array2D < Array2D<half> > levels; { cout << " writing" << flush; remove (fileName); TiledOutputFile out (fileName, hdr); levels.resizeErase (out.numYLevels(), out.numXLevels()); int i; Rand32 rand1 = Rand32(); std::vector<int> shuffled_xLevels = std::vector<int>(out.numXLevels()); std::vector<int> shuffled_yLevels = std::vector<int>(out.numYLevels()); for (i = 0; i < out.numXLevels(); i++) shuffled_xLevels[i] = i; for (i = 0; i < out.numYLevels(); i++) shuffled_yLevels[i] = i; if (triggerBuffering) { // shuffle the level orders for (i = 0; i < out.numXLevels(); i++) std::swap(shuffled_xLevels[i], shuffled_xLevels[int(rand1.nextf(i,out.numXLevels()-1) + 0.5)]); for (i = 0; i < out.numYLevels(); i++) std::swap(shuffled_yLevels[i], shuffled_yLevels[int(rand1.nextf(i,out.numYLevels()-1) + 0.5)]); } for (int ylevel = 0; ylevel < out.numYLevels(); ++ylevel) { const int sylevel = shuffled_yLevels[ylevel]; std::vector<int> tileYs = std::vector<int>(out.numYTiles(sylevel)); for (i = 0; i < out.numYTiles(sylevel); i++) { if (lorder == DECREASING_Y) tileYs[out.numYTiles(sylevel)-1-i] = i; else tileYs[i] = i; } if (triggerBuffering) // shuffle the tile orders for (i = 0; i < out.numYTiles(sylevel); i++) std::swap(tileYs[i], tileYs[int(rand1.nextf(i,out.numYTiles(sylevel)-1) + 0.5)]); for (int xlevel = 0; xlevel < out.numXLevels(); ++xlevel) { const int sxlevel = shuffled_xLevels[xlevel]; int levelWidth = out.levelWidth(sxlevel); int levelHeight = out.levelHeight(sylevel); levels[sylevel][sxlevel].resizeErase(levelHeight, levelWidth); fillPixels (levels[sylevel][sxlevel], levelWidth, levelHeight); FrameBuffer fb; fb.insert ("H", Slice (HALF, (char *) &levels[sylevel][sxlevel][0][0], sizeof (levels[sylevel][sxlevel][0][0]), sizeof (levels[sylevel][sxlevel][0][0]) * levelWidth)); out.setFrameBuffer (fb); std::vector<int> tileXs = std::vector<int>(out.numXTiles(sxlevel)); for (i = 0; i < out.numXTiles(sxlevel); i++) tileXs[i] = i; if (triggerBuffering) // shuffle the tile orders for (i = 0; i < out.numXTiles(sxlevel); i++) std::swap(tileXs[i], tileXs[int(rand1.nextf(i,out.numXTiles(sxlevel)-1) + 0.5)]); for (int tileY = 0; tileY < out.numYTiles(sylevel); ++tileY) for (int tileX = 0; tileX < out.numXTiles(sxlevel); ++tileX) out.writeTile(tileXs[tileX], tileYs[tileY], sxlevel, sylevel); } } } { cout << " reading" << flush; TiledInputFile in (fileName); const Box2i &dw = in.header().dataWindow(); int dwx = dw.min.x; int dwy = dw.min.y; int numXLevels = in.numXLevels(); int numYLevels = in.numYLevels(); Array2D < Array2D<half> > levels2 (numYLevels, numXLevels); int startTileY, endTileY; int dy; for (int ylevel = 0; ylevel < in.numYLevels(); ++ylevel) { if ((lorder == DECREASING_Y && !triggerSeeks) || (lorder == INCREASING_Y && triggerSeeks) || (lorder == RANDOM_Y && triggerSeeks)) { startTileY = in.numYTiles(ylevel) - 1; endTileY = -1; dy = -1; } else { startTileY = 0; endTileY = in.numYTiles(ylevel); dy = 1; } for (int xlevel = 0; xlevel < in.numXLevels(); ++xlevel) { int levelWidth = in.levelWidth(xlevel); int levelHeight = in.levelHeight(ylevel); levels2[ylevel][xlevel].resizeErase(levelHeight, levelWidth); FrameBuffer fb; fb.insert ("H", Slice (HALF, (char *) &levels2[ylevel][xlevel][-dwy][-dwx], sizeof (levels2[ylevel][xlevel][0][0]), sizeof (levels2[ylevel][xlevel][0][0]) * levelWidth)); in.setFrameBuffer (fb); for (int tileY = startTileY; tileY != endTileY; tileY += dy) for (int tileX = 0; tileX < in.numXTiles (xlevel); ++tileX) in.readTile (tileX, tileY, xlevel, ylevel); } } cout << " comparing" << flush; assert (in.header().displayWindow() == hdr.displayWindow()); assert (in.header().dataWindow() == hdr.dataWindow()); assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio()); assert (in.header().screenWindowCenter() == hdr.screenWindowCenter()); assert (in.header().screenWindowWidth() == hdr.screenWindowWidth()); assert (in.header().lineOrder() == hdr.lineOrder()); assert (in.header().compression() == hdr.compression()); assert (in.header().channels() == hdr.channels()); for (int ly = 0; ly < numYLevels; ++ly) for (int lx = 0; lx < numXLevels; ++lx) for (int y = 0; y < in.levelHeight(ly); ++y) for (int x = 0; x < in.levelWidth(lx); ++x) assert ((levels2[ly][lx])[y][x] == (levels[ly][lx])[y][x]); } remove (fileName); cout << endl; } void writeCopyRead (int w, int h, int xs, int ys) { const char *filename = IMF_TMP_DIR "imf_test_copy.exr"; for (int comp = 0; comp < NUM_COMPRESSION_METHODS; ++comp) { if (comp == B44_COMPRESSION || comp == B44A_COMPRESSION) continue; for (int lorder = 0; lorder < RANDOM_Y; ++lorder) { for (int rmode = 0; rmode < NUM_ROUNDINGMODES; ++rmode) { for (int tb = 0; tb <= 1; ++tb) { for (int ts = 0; ts <= 1; ++ts) { writeCopyReadONE (filename, w, h, (LineOrder)lorder, (LevelRoundingMode) rmode, xs, ys, Compression (comp), (bool)tb, (bool)ts); writeCopyReadMIP (filename, w, h, (LineOrder)lorder, (LevelRoundingMode) rmode, xs, ys, Compression (comp), (bool)tb, (bool)ts); writeCopyReadRIP (filename, w, h, (LineOrder)lorder, (LevelRoundingMode) rmode, xs, ys, Compression (comp), (bool)tb, (bool)ts); } } } } } } } // namespace void testTiledLineOrder () { try { cout << "Testing line orders for tiled files and " "buffered/unbuffered tile writes" << endl; const int W = 171; const int H = 259; const int XS = 55; const int YS = 55; int maxThreads = ILMTHREAD_NAMESPACE::supportsThreads()? 3: 0; for (int n = 0; n <= maxThreads; ++n) { if (ILMTHREAD_NAMESPACE::supportsThreads()) { setGlobalThreadCount (n); cout << "\nnumber of threads: " << globalThreadCount() << endl; } writeCopyRead (W, H, XS, YS); } cout << "ok\n" << endl; } catch (const std::exception &e) { cerr << "ERROR -- caught exception: " << e.what() << endl; assert (false); } }
jamesbigler/Legion
src/Support/openexr-2.0.1/IlmImfTest/testTiledLineOrder.cpp
C++
mit
21,673
package main import "fmt" // Bitcoin represents a number of Bitcoins type Bitcoin int func (b Bitcoin) String() string { return fmt.Sprintf("%d BTC", b) } // Wallet stores the number of Bitcoin someone owns type Wallet struct { balance Bitcoin } // Deposit will add some Bitcoin to a wallet func (w *Wallet) Deposit(amount Bitcoin) { w.balance += amount } // Withdraw subtracts some Bitcoin from the wallet func (w *Wallet) Withdraw(amount Bitcoin) { w.balance -= amount } // Balance returns the number of Bitcoin a wallet has func (w *Wallet) Balance() Bitcoin { return w.balance }
a233894432/Golang-lesson
src/my_example/gctt/pointers_demo/v2/wallet.go
GO
mit
595
import pymc3 as pm from lasagne.layers.helper import * from lasagne.layers.helper import __all__ as __helper__all__ __all__ = [ "find_parent", "find_root", ] + __helper__all__ def find_parent(layer): candidates = get_all_layers(layer)[::-1] found = None for candidate in candidates: if isinstance(candidate, pm.Model): found = candidate break return found def find_root(layer): model = find_parent(layer) if model is not None: return model.root else: return None
ferrine/gelato
gelato/layers/helper.py
Python
mit
551
import inspect __all__ = ['GenericVisitor'] class GenericVisitor(object): """ A generic visitor. To define handlers, subclasses should define :data:`visit_Foo` methods for each class :data:`Foo` they want to handle. If a specific method for a class :data:`Foo` is not found, the MRO of the class is walked in order until a matching method is found. The method signature is: .. code-block:: def visit_Foo(self, o, [*args, **kwargs]): pass The handler is responsible for visiting the children (if any) of the node :data:`o`. :data:`*args` and :data:`**kwargs` may be used to pass information up and down the call stack. You can also pass named keyword arguments, e.g.: .. code-block:: def visit_Foo(self, o, parent=None, *args, **kwargs): pass """ def __init__(self): handlers = {} # visit methods are spelt visit_Foo. prefix = "visit_" # Inspect the methods on this instance to find out which # handlers are defined. for (name, meth) in inspect.getmembers(self, predicate=inspect.ismethod): if not name.startswith(prefix): continue # Check the argument specification # Valid options are: # visit_Foo(self, o, [*args, **kwargs]) argspec = inspect.getfullargspec(meth) if len(argspec.args) < 2: raise RuntimeError("Visit method signature must be " "visit_Foo(self, o, [*args, **kwargs])") handlers[name[len(prefix):]] = meth self._handlers = handlers """ :attr:`default_args`. A dict of default keyword arguments for the visitor. These are not used by default in :meth:`visit`, however, a caller may pass them explicitly to :meth:`visit` by accessing :attr:`default_args`. For example:: .. code-block:: v = FooVisitor() v.visit(node, **v.default_args) """ default_args = {} @classmethod def default_retval(cls): """ A method that returns an object to use to populate return values. If your visitor combines values in a tree-walk, it may be useful to provide a object to combine the results into. :meth:`default_retval` may be defined by the visitor to be called to provide an empty object of appropriate type. """ return None def lookup_method(self, instance): """ Look up a handler method for a visitee. Parameters ---------- instance : object The instance to look up a method for. """ cls = instance.__class__ try: # Do we have a method handler defined for this type name return self._handlers[cls.__name__] except KeyError: # No, walk the MRO. for klass in cls.mro()[1:]: entry = self._handlers.get(klass.__name__) if entry: # Save it on this type name for faster lookup next time self._handlers[cls.__name__] = entry return entry raise RuntimeError("No handler found for class %s", cls.__name__) def visit(self, o, *args, **kwargs): """ Apply this Visitor to an object. Parameters ---------- o : object The object to be visited. *args Optional arguments to pass to the visit methods. **kwargs Optional keyword arguments to pass to the visit methods. """ ret = self._visit(o, *args, **kwargs) ret = self._post_visit(ret) return ret def _visit(self, o, *args, **kwargs): """Visit ``o``.""" meth = self.lookup_method(o) return meth(o, *args, **kwargs) def _post_visit(self, ret): """Postprocess the visitor output before returning it to the caller.""" return ret def visit_object(self, o, **kwargs): return self.default_retval()
opesci/devito
devito/tools/visitors.py
Python
mit
4,134
package xsmeral.pipe.context; import java.io.File; /** * A file system context, based on the notion of a single working directory. * @author Ron Šmeral (xsmeral@fi.muni.cz) */ public interface FSContext { /** * Sets the working directory to the given path (relative or absolute) */ public void setWorkingDir(String path); /** * Returns the working directory */ public String getWorkingDir(); /** * Returns a file with the specified path. * If the path is relative, it is resolved against the working directory. */ public File getFile(String path); }
rsmeral/semnet
PipedObjectProcessor/src/xsmeral/pipe/context/FSContext.java
Java
mit
619
//--------------------------------------------------------------------------- // // <copyright file="FillRuleValidation.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Runtime.InteropServices; using MS.Internal.PresentationCore; #if PRESENTATION_CORE using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; #else using SR=System.Windows.SR; using SRID=System.Windows.SRID; #endif namespace System.Windows.Media { internal static partial class ValidateEnums { /// <summary> /// Returns whether or not an enumeration instance a valid value. /// This method is designed to be used with ValidateValueCallback, and thus /// matches it's prototype. /// </summary> /// <param name="valueObject"> /// Enumeration value to validate. /// </param> /// <returns> 'true' if the enumeration contains a valid value, 'false' otherwise. </returns> public static bool IsFillRuleValid(object valueObject) { FillRule value = (FillRule) valueObject; return (value == FillRule.EvenOdd) || (value == FillRule.Nonzero); } } }
mind0n/hive
Cache/Libs/net46/wpf/src/Shared/MS/Internal/Generated/FillRuleValidation.cs
C#
mit
1,605
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasker.TaskAntImporter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tasker.TaskAntImporter")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1a5ccda4-fa92-4711-805b-6541cf3fb650")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Digiman/Tasker
Tasker.TaskAntImporter/Properties/AssemblyInfo.cs
C#
mit
1,420
# Die Class 1: Numeric # I worked on this challenge [by myself] # I spent [.5] hours on this challenge. # 0. Pseudocode # Input: integer amount of sides on a die object # Output: either integer number of sides or random integer # Steps: # => IF there is less than one side THEN # => => RAISE an Argument Error # => ELSE # => => allow the 'die' to be created with trait -size # => ENDIF # => When Sides is called (Die.sides) RETURN the number of sides # => When rolled return a RANDOM number between 1 and # of sides. # 1. Initial Solution #class Die # def initialize(sides) # @sides = sides # end # # def sides # return @sides # end # # def roll # return rand(1..@sides) # end #end # 3. Refactored Solution class Die def initialize(sides) if sides < 1 raise ArgumentError else @sides = sides end end def sides return @sides end def roll return rand(1..@sides) end end # 4. Reflection =begin What is an ArgumentError and why would you use one? It is an error that tells the user why their input won't work. You would use one to warn a user that the way they're trying to use the class or method is incorrect. It could be that the input is the wrong type or the wrong quantity or really anything that would cause the class and/or subsequent methods to fail. What new Ruby methods did you implement? What challenges and successes did you have in implementing them? I used rand() in order to call a random number between 1 and sides. There wasn't too much that could have gone wrong. What is a Ruby class? A class is like a framework that can be used to create an individual object. A class can have traits (like how Die had sides) and can have functions (die can be rolled to return a random number). Why would you use a Ruby class? It is useful to store many instances of data. For example, with a class Person, you can store the name, hometown, age, and profession of all the persons in that class without using a hash. You can also call methods on those persons (e.g. work, drive, eat, etc.). What is the difference between a local variable and an instance variable? Instance variables are available across methods for any instance or any object. Instance variables have an '@' before the variable name. They also change from object to object. Local variables are variables defined in a method and they're not available outside the method. They generally begin with lowercase letters or '_' Where can an instance variable be used? Within an instance of a class. =end
themcny/phase-0
week-5/die-class/my_solution.rb
Ruby
mit
2,564
// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Blake"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "8c5e74e" # define GIT_COMMIT_DATE "2022-03-05 11:47:21 +0000" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE);
BlakeBitcoin/BlakeBitcoin
src/version.cpp
C++
mit
2,628
import base64 import demistomock as demisto from WildFireReports import main import requests_mock def test_wildfire_report(mocker): """ Given: A sha256 represents a file uploaded to WildFire. When: internal-wildfire-get-report command is running. Then: Ensure that the command is running as expected. """ mock_sha256 = 'abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890' mocker.patch.object(demisto, 'command', return_value='internal-wildfire-get-report') mocker.patch.object(demisto, 'params', return_value={'server': 'https://test.com/', 'token': '123456'}) mocker.patch.object(demisto, 'args', return_value={'sha256': mock_sha256}) with open('test_data/response.pdf', 'rb') as file: file_content = b'' while byte := file.read(1): file_content += byte mocker.patch('WildFireReports.fileResult', return_value=file_content) # prevent file creation demisto_mock = mocker.patch.object(demisto, 'results') with requests_mock.Mocker() as m: m.post(f'https://test.com/publicapi/get/report?format=pdf&hash={mock_sha256}', content=file_content) main() assert demisto_mock.call_args_list[0][0][0]['data'] == base64.b64encode(file_content).decode() def test_report_not_found(mocker): """ Given: A sha256 represents a file not uploaded to WildFire. When: internal-wildfire-get-report command is running. Then: Ensure that the command is running as expected. """ mock_sha256 = 'abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567891' mocker.patch.object(demisto, 'command', return_value='internal-wildfire-get-report') mocker.patch.object(demisto, 'params', return_value={'server': 'https://test.com/', 'token': '123456'}) mocker.patch.object(demisto, 'args', return_value={'sha256': mock_sha256}) demisto_mock = mocker.patch.object(demisto, 'results') with requests_mock.Mocker() as m: m.post(f'https://test.com/publicapi/get/report?format=pdf&hash={mock_sha256}', status_code=404) main() assert demisto_mock.call_args[0][0] == {'status': 'not found'} def test_incorrect_sha256(mocker): """ Given: An incorrect sha256. When: internal-wildfire-get-report command is running. Then: Ensure that the command is running as expected. """ mock_sha256 = 'abcdef1234567890abcdef1234567890abcdef1234567890abcdef123456789' # The length is 63 insteadof 64 mocker.patch.object(demisto, 'command', return_value='internal-wildfire-get-report') mocker.patch.object(demisto, 'params', return_value={'server': 'https://test.com/', 'token': '123456'}) mocker.patch.object(demisto, 'args', return_value={'sha256': mock_sha256}) demisto_mock = mocker.patch.object(demisto, 'results') expected_description_error = 'Failed to download report.\nError:\nInvalid hash. Only SHA256 are supported.' main() assert demisto_mock.call_args_list[0].args[0].get('error', {}).get('description') == expected_description_error def test_incorrect_authorization(mocker): """ Given: An incorrect API token. When: test-module command is running. Then: Ensure that the command is running as expected. """ mocker.patch.object(demisto, 'command', return_value='test-module') mocker.patch.object(demisto, 'params', return_value={'server': 'https://test.com/', 'token': 'incorrect api token'}) demisto_mock = mocker.patch.object(demisto, 'results') expected_description_error = 'Authorization Error: make sure API Key is correctly set' url = 'https://test.com/publicapi/get/report' params = '?apikey=incorrect+api+token&format=pdf&hash=dca86121cc7427e375fd24fe5871d727' with requests_mock.Mocker() as m: m.post(url + params, status_code=401) main() assert demisto_mock.call_args_list[0].args[0] == expected_description_error def test_empty_api_token(mocker): """ Given: An empty API token. When: test-module command is running. Then: Ensure that the command is running as expected. """ mocker.patch.object(demisto, 'command', return_value='test-module') mocker.patch.object(demisto, 'params', return_value={'server': 'https://test.com/', 'token': ''}) mocker.patch.object(demisto, 'getLicenseCustomField', return_value=None) demisto_mock = mocker.patch('WildFireReports.return_error') expected_description_error = 'Authorization Error: It\'s seems that the token is empty and you have not a ' \ 'TIM license that is up-to-date, Please fill the token or update your TIM license ' \ 'and try again.' main() assert demisto_mock.call_args_list[0].args[0] == expected_description_error
VirusTotal/content
Packs/Palo_Alto_Networks_WildFire/Integrations/WildFireReports/WildFireReports_test.py
Python
mit
4,906
using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; using uWebshop.Domain; using uWebshop.Domain.Helpers; using uWebshop.Domain.Interfaces; namespace uWebshop.API { [DataContract(Namespace = "")] internal class BasketStore : IStore { private readonly Domain.Store _store; public BasketStore(Domain.Store store) { _store = store; Id = store.Id; Alias = store.Alias; TypeAlias = store.TypeAlias; } public BasketStore(StoreInfo info) : this(info.Store) { Alias = info.Alias; } [DataMember] public int Id { get; set; } [DataMember] public string TypeAlias { get; private set; } [DataMember] public string Culture { get { return _store.Culture; } } [DataMember] public string Alias { get; set; } [DataMember] public string CountryCode { get { return _store.CountryCode; } } [DataMember] public string DefaultCountryCode { get { return _store.DefaultCountryCode; } } [DataMember] public string CurrencyCulture { get { return _store.CountryCode; } } [IgnoreDataMember] public IEnumerable<ICurrency> Currencies { get { return _store.Currencies; } } [IgnoreDataMember] public CultureInfo DefaultCurrencyCultureInfo { get { return _store.DefaultCurrencyCultureInfo; } } [DataMember] public string DefaultCurrencyCultureSymbol { get { return _store.DefaultCurrencyCultureSymbol; } } [IgnoreDataMember] public CultureInfo CultureInfo { get { return _store.CultureInfo; } } [DataMember] public decimal GlobalVat { get { return _store.GlobalVat; } } [DataMember] public bool Testmode { get { return _store.Testmode; } } [DataMember] public string StoreUrlWithoutDomain { get { return _store.StoreUrlWithoutDomain; } } [DataMember] public string EmailAddressFrom { get { return _store.EmailAddressFrom; } } [DataMember] public string EmailAddressFromName { get { return _store.EmailAddressFromName; } } [DataMember] public string EmailAddressTo { get { return _store.EmailAddressTo; } } [DataMember] public string StoreURL { get { return _store.StoreURL; } } public IEnumerable<int> GetConnectedNodes { get { return _store.GetConnectedNodes; } } [IgnoreDataMember] public bool Disabled { get { return _store.Disabled; } } [IgnoreDataMember] public DateTime CreateDate { get { return _store.CreateDate; } } [IgnoreDataMember] public DateTime UpdateDate { get { return _store.UpdateDate; } } [DataMember] public int SortOrder { get { return _store.SortOrder; } } } }
uWebshop/uWebshop-Releases
Core/uWebshop.Domain/API/DataClasses/BasketStore.cs
C#
mit
2,701
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Claims; using Ascon.Pilot.Core; using Ascon.Pilot.Server.Api; using Ascon.Pilot.Server.Api.Contracts; using Ascon.Pilot.Transport; using Microsoft.AspNet.Http; using ISession = Microsoft.AspNet.Http.Features.ISession; namespace Ascon.Pilot.WebClient.Extensions { public static class SessionExt { public static IDictionary<int, MType> GetMetatypes(this ISession session) { return session.GetSessionValues<IDictionary<int, MType>>(SessionKeys.MetaTypes); } /// <summary> /// Set value of type <typeparam name="T">T</typeparam> at session dictionary using protobuf-net /// </summary> /// <typeparam name="T">type of value to set. Must be proto-serializable</typeparam> /// <param name="session">session to add values</param> /// <param name="key">key of value</param> /// <param name="value">value to set</param> public static void SetSessionValues<T>(this ISession session, string key, T value) { using (var bs = new MemoryStream()) { ProtoBuf.Serializer.Serialize(bs, value); session.Set(key, bs.ToArray()); } } /// <summary> /// Deserialize values if type T from session dictionary using protobuf-net /// </summary> /// <typeparam name="T">type of value</typeparam> /// <param name="session">Session where values located</param> /// <param name="key">key of values in dictionary</param> /// <returns></returns> public static T GetSessionValues<T>(this ISession session, string key) { var val = session.Get(key); if (val == null) return default(T); using (var bs = new MemoryStream(val)) { return ProtoBuf.Serializer.Deserialize<T>(bs); } } } public static class HttpContextClientsStorage { private static readonly Dictionary<Guid, HttpPilotClient> ClientsDictionary = new Dictionary<Guid, HttpPilotClient>(); public static HttpPilotClient GetClient(this HttpContext context) { var clientIdString = context.User.FindFirstValue(ClaimTypes.Sid); if (string.IsNullOrEmpty(clientIdString)) return null; var clientId = Guid.Parse(clientIdString); if (ClientsDictionary.ContainsKey(clientId)) { var client = ClientsDictionary[clientId]; if (client.IsClientActive()) return client; } return null; } public static void SetClient(this HttpContext context, HttpPilotClient client, Guid clientId) { ClientsDictionary[clientId] = client; } public static IServerApi GetServerApi(this HttpContext context, IServerCallback callback = null) { if (callback == null) callback = CallbackFactory.Get<IServerCallback>(); var client = context.GetClient(); if (client == null) client = Reconnect(context, callback); return client.GetServerApi(callback); } private static HttpPilotClient Reconnect(HttpContext context, IServerCallback callback) { var client = new HttpPilotClient(); client.Connect(ApplicationConst.PilotServerUrl); var serverApi = client.GetServerApi(callback); var dbName = context.User.FindFirstValue(ClaimTypes.Surname); var login = context.User.FindFirstValue(ClaimTypes.Name); var protectedPassword = context.User.FindFirstValue(ClaimTypes.UserData); var useWindowsAuth = login.Contains("/") || login.Contains("\\"); var dbInfo = serverApi.OpenDatabase(dbName, login, protectedPassword, useWindowsAuth); if (dbInfo == null) throw new TransportException(); var clientIdString = context.User.FindFirstValue(ClaimTypes.Sid); ClientsDictionary[Guid.Parse(clientIdString)] = client; DMetadata dMetadata = serverApi.GetMetadata(dbInfo.MetadataVersion); context.Session.SetSessionValues(SessionKeys.MetaTypes, dMetadata.Types.ToDictionary(x => x.Id, y => y)); return client; } } }
perminov-aleksandr/askon-pilot-client-asp
src/Ascon.Pilot.WebClient/Extensions/ClientsStorage.cs
C#
mit
4,520
package io.swagger.client.api; import io.swagger.client.ApiClient; import io.swagger.client.model.InlineResponse200; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for StoriesApi */ public class StoriesApiTest { private StoriesApi api; @Before public void setup() { api = new ApiClient().createService(StoriesApi.class); } /** * Top Stories * * The Top Stories API provides JSON and JSONP lists of articles and associated images by section. */ @Test public void sectionFormatGetTest() { String section = null; String format = null; String callback = null; // InlineResponse200 response = api.sectionFormatGet(section, format, callback); // TODO: test validations } }
amardeshbd/android-daily-headlines
api-lib/src/test/java/io/swagger/client/api/StoriesApiTest.java
Java
mit
903
require 'calabash-android/operations' INSTALLATION_STATE = { :installed => false } Before do |scenario| $calabashQueryView = self scenario_tags = scenario.source_tag_names if !INSTALLATION_STATE[:installed] uninstall_apps install_app(ENV['TEST_APP_PATH']) install_app(ENV['APP_PATH']) INSTALLATION_STATE[:installed] = true end if scenario_tags.include?('@reinstall') clear_app_data end start_test_server_in_background end After do |scenario| shutdown_test_server end
RuudPuts/CalabashTesting
features/android/support/app_life_cycle_hooks.rb
Ruby
mit
521
/** * @Author: shenyu <SamMFFL> * @Date: 2016/12/08 10:18:06 * @Email: samfec@163.com * @Last modified by: SamMFFL * @Last modified time: 2016/12/13 14:39:33 */ import React, {Component} from 'react'; import { StyleSheet, Text, View, Image, TouchableHighlight, ScrollView, } from 'react-native'; import Header from '../Header'; import Box from '../Box'; import Icon from 'react-native-vector-icons/FontAwesome'; import demoImg from '../imgs/demo.png'; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', flexDirection: 'column' }, scroll: { flex: 1, // borderWidth: 1, marginBottom: 50, }, box: { height: 200, borderTopWidth: 1, borderBottomWidth: 1, borderColor: '#D6DCDF', backgroundColor: '#f5fcff', marginBottom: 10, paddingBottom: 20, }, animateView: { flex: 1, justifyContent: 'center', alignItems: 'center', }, boxBtn: { height: 30, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', } }); export default class setNativePropsDemo extends Component { count = 0; constructor(props) { super(props); this.startAnimationOfSize = this.startAnimationOfSize.bind(this); this.stopAnimationOfSize = this.stopAnimationOfSize.bind(this); this._renderSize = this._renderSize.bind(this); this.animateSizeFunc = this.animateSizeFunc.bind(this); this.state = { width: 50, height: 50, } } _renderSize() { return ( <View style={[styles.animateView,{ opacity:1 }]}> <Image ref="img" source = { demoImg } style={{ width: this.state.width, height: this.state.height, }} /> </View> ); } animateSizeFunc(){ requestAnimationFrame(() =>{ if(this.count<50){ ++this.count; // this.setState({ // width: this.state.width+10 , // height: this.state.height+10 // }); this.refs.img.setNativeProps({ style: { width: this.state.width++, height: this.state.height++, } }); // console.log('count',this.count) this.animateSizeFunc(); } }); } startAnimationOfSize(){ this.setState({ width: 50, height: 50 }); this.count = 0; this.animateSizeFunc(); } stopAnimationOfSize(){ this.setState({ width: 50, height: 50 }); this.refs.img.setNativeProps({ style: { width: 50, height: 50, } }); this.count = 100; setTimeout(()=>{ this.count = 0; },100) } startAnimation(){ var count = 0; var width=50, height=50; while (++count < 10000) { requestAnimationFrame(() =>{ // console.log(12) this.refs.img.setNativeProps({ style: { width: width, height: height, } }); }); width += 0.01; height += 0.01; } // LayoutAnimation.configureNext({ // duration: 700, //持续时间 // create: { // 视图创建 // type: LayoutAnimation.Types.spring, // property: LayoutAnimation.Properties.scaleXY,// opacity、scaleXY // }, // update: { // 视图更新 // type: LayoutAnimation.Types.spring, // }, // }); // this.setState({ // width: this.state.width + 100, // height: this.state.height + 100 // }); } render() { const {navigator, title} = this.props; console.log(1) return ( <View style={styles.container}> <Header title={title} showArrow={Boolean(true)} navigator={navigator} /> <ScrollView vertical={Boolean(true)} directionalLockEnabled={Boolean(true)} showsHorizontalScrollIndicator={Boolean(false)} indicatorStyle="white" style={styles.scroll} > <Box title="放大动画处理" animatedContent={this._renderSize()} playFunc={this.startAnimationOfSize} pauseFunc={this.stopAnimationOfSize} /> </ScrollView> </View> ) } componentDidMount(){ // this.startAnimation(); } }
yeeFlame/animate-for-RN
studyAnimate/containers/examples/setNativePropsDemo.js
JavaScript
mit
5,282
package simpul.core; import simpul.Interfaces; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class EventEmitter implements Interfaces.EventEmitter{ private class RegisteredCallback{ private final Interfaces.EventCallback cb; private final boolean once; private RegisteredCallback(Interfaces.EventCallback cb, boolean once) { this.cb = cb; this.once = once; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RegisteredCallback that = (RegisteredCallback) o; return cb.equals(that.cb); } @Override public int hashCode() { return cb.hashCode(); } } private final Map<String,List<RegisteredCallback>> listeners; public EventEmitter() { listeners = new HashMap<>(); } @Override public <T> void on(String event, Interfaces.EventCallback<T> cb) { addListener(event, cb, false); } private <T> void addListener(String event, Interfaces.EventCallback<T> cb, boolean once) { List<RegisteredCallback> callbacks = listeners.get(event); if (callbacks == null) { callbacks = new ArrayList<>(); listeners.put(event,callbacks); } callbacks.add(new RegisteredCallback(cb,once)); } @Override public <T> void once(String event, Interfaces.EventCallback<T> cb) { addListener(event, cb, true); } @Override public <T> void emit(String event, T data) { List<RegisteredCallback> callbacks = listeners.get(event); if (callbacks == null) { return; } for (RegisteredCallback registeredCallback: callbacks) { if (registeredCallback.once) { //noinspection unchecked removeListener(event,registeredCallback.cb); } //noinspection unchecked registeredCallback.cb.invoke(data); } } @Override public <T> void removeListener(String event, Interfaces.EventCallback<T> cb) { List<RegisteredCallback> callbacks = listeners.get(event); if (callbacks == null) { return; } callbacks.remove(new RegisteredCallback(cb,false)); } @Override public void removeAllListeners(String event) { listeners.remove(event); } @Override public int listeners(String event) { List<RegisteredCallback> callbacks = listeners.get(event); if (callbacks == null) { return 0; } return callbacks.size(); } }
parroit/simpul
src/main/java/simpul/core/EventEmitter.java
Java
mit
2,783
#!/usr/bin/env python2 import argparse import xml.etree.ElementTree as ET import subprocess import os.path as path from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import time OUT_DIR = './_out' HAXE_PATH = 'haxe' def get_main_info(meta_root): server_main, client_main = None, None node = meta_root.find('server_main') if node is not None: server_main = {'src': '', 'class': 'Main', 'main_dir': ''} src = node.attrib['src'] if src is not None: server_main['main_dir'] = path.dirname(src) server_main['src'] = path.relpath(src, server_main['main_dir']) node = meta_root.find('client_main') if node is not None: client_main = {'src': '', 'class': 'Main', 'main_dir': ''} src = node.attrib['src'] if src is not None: client_main['main_dir'] = path.dirname(src) client_main['src'] = path.relpath(src, client_main['main_dir']) return server_main, client_main def build_meta(meta_root): meta_root.append(ET.Element('script', {'src': 'server.lua', 'type': 'server'})) meta_root.append(ET.Element('script', {'src': 'client.lua', 'type': 'client'})) for node in meta_root.findall('server_main'): meta_root.remove(node) for node in meta_root.findall('client_main'): meta_root.remove(node) ET.ElementTree(meta_root).write(path.join(OUT_DIR, 'meta.xml')) def build_resource(): print('Building...') # Parse meta.xml tree = ET.parse('meta.xml') root = tree.getroot() # Get information about entry point server_main, client_main = get_main_info(root) server_out_path = path.join('..', OUT_DIR, 'server.lua') client_out_path = path.join('..', OUT_DIR, 'client.lua') # Invoke the compiler if server_main is not None: ret = subprocess.call([HAXE_PATH, '-main', server_main['class'], '-lua', server_out_path, server_main['src'], '-lib', 'mtasa-typings'], cwd=server_main['main_dir']) if client_main is not None: ret = subprocess.call([HAXE_PATH, '-main', client_main['class'], '-lua', client_out_path, client_main['src'], '-lib', 'mtasa-typings'], cwd=client_main['main_dir']) # Build new meta build_meta(root) if __name__ == '__main__': # Parse args parser = argparse.ArgumentParser(description='haxe-mta build tools') sub_parsers = parser.add_subparsers(help='sub commands') build_parser = sub_parsers.add_parser('build', help='build resource') run_parser = sub_parsers.add_parser('run', help='wait and recompile on changes') build_parser.set_defaults(build_parser=True, run_parser=False) run_parser.set_defaults(run_parser=True, build_parser=False) args = parser.parse_args() # Handle commands if args.build_parser: # Build resource once build_resource() elif args.run_parser: # Build resource again on any change class FileSystemListener(PatternMatchingEventHandler): def __init__(self): super(FileSystemListener, self).__init__(ignore_patterns=['**/_out*']) def on_any_event(self, event): build_resource() event_handler = FileSystemListener() observer = Observer() observer.schedule(event_handler, '.', recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
Jusonex/haxe-mtasa-typings
example/build.py
Python
mit
3,302
<?php /** * Copyright (c) 2017. Puerto Parrot Booklet. Written by Dimitri Mostrey for www.puertoparrot.com * Contact me at admin@puertoparrot.com or dmostrey@yahoo.com */ namespace App\Http\Controllers; use App\Models\City; use App\Models\Province; use App\Models\Service; use DB; /** * Class ApiController * * @package App\Http\Controllers */ class ApiController extends Controller { /** * @return string * @throws \Exception */ public static function Currency() { $data = array(); //$old = DB::table('currencies')->first(); $data['usdphp'] = ApiController::convertCurrency(1, 'USD', 'PHP') ? : $data['usdphp'] = cache('usdphp'); $data['eurphp'] = ApiController::convertCurrency(1, 'EUR', 'PHP') ? : $data['eurphp'] = cache('eurphp'); //empty the database DB::table('currencies')->truncate(); //insert the data DB::table('currencies')->insert($data); cache(['usdphp' => $data['usdphp']], 400); cache(['eurphp' => $data['eurphp']], 400); $message = 'The currency has been successfully added: USDPHP = ' . $data['usdphp'] . ' and EURPHP ' . $data['eurphp']; \Log::info('[ApiController Currency] ' . $message); return $message; /*$message = 'There was a problem adding the currency in the table at ' . date('Y-m-d H:i:s'); \Log::error('[ApiController Currency] ' . $message); return $message;*/ } /** * @param $amount * @param $from * @param $to * * @return string|null */ private static function convertCurrency($amount, $from, $to) { //$url = "https://www.xe.com/currencyconverter/convert/?Amount={$amount}&From={$from}&To={$to}"; $url = "https://themoneyconverter.com/{$from}/{$to}.aspx"; $data = @file_get_contents($url); if ( ! $data) { return null; } //preg_match_all("/<span class='uccResultAmount'>([0-9.]*)<\/span>/", $data, $converted); preg_match_all('/<td id="PHP">([0-9.]*)<\/td>/', $data, $converted); try { $final = $converted[1][0]; } catch (\Exception $e) { return null; } return round($final, 2); } /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function googleCoordsPage() { $provinces = Province::where('id', '=', 1)->orderBy('id')->get(); $cities = City::where('id', '=', 1645)->get(); foreach ($cities as $city) { if ($data = $this->getGoogleCoords($city)) { DB::table('cities')->where('id', $data['city_id'])->update(['lat' => $data['lat'], 'long' => $data['long'], ]); } } return view('google_coords', compact('provinces')); } /** * @param $city * * @return bool */ public function getGoogleCoords($city) { //create the call URL $city_db = $city; //City::where('name', $city)->first(); $google_api = "AIzaSyB-7u1CvRIkmsjcHVVQgilPj6doeIh93oA"; $baseURL = "https://maps.googleapis.com/maps/api/geocode/json?address="; $format = "&key=" . $google_api; $query = "philippines,+" . urlencode($city_db->province->name) . ",+" . urlencode($city_db->name); $callURL = $baseURL . $query . $format; //make the call $session = curl_init($callURL); curl_setopt($session, CURLOPT_URL, $callURL); curl_setopt($session, CURLOPT_BINARYTRANSFER, true); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $json = curl_exec($session); curl_close($session); // Decode JSON response: $coords = json_decode($json, true); if ($coords["status"] == "OK") { $data['lat'] = $coords["results"][0]["geometry"]["location"]["lat"]; $data['long'] = $coords["results"][0]["geometry"]["location"]["lng"]; $data['postcode'] = $coords["results"][0]["address_components"]; $data['city_id'] = $city_db->id; return $data; } else { return false; } } public function blank() { // $services = Service::whereNotNull('icon') ->with(['categories']) ->join('service_category_service', 'services.id', '=', 'service_category_service.service_id') ->join('service_categories', 'service_category_service.service_category_id', '=', 'service_categories.id') ->groupBy('service_categories.name') ->pluck('services.icon', 'service_categories.slug'); //$services['generic'] = 'https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png'; dd($services); /*foreach ($services as $k => $v) { echo "<h2>$k has $v</h2>"; $category = ServiceCategory::where('slug', '=', $k)->first(); if ($category) { if (count($category->services) != 0) { $categories = $category->services->where('icon', 'IS', null); foreach ($categories as $c) { echo $c->id . " " . $c->icon . " => <strong>". $c->title . "</strong><br>\n"; if($k != 'government' && $k != 'education' && $k != 'atm' && $c->title == strtoupper($c->title)) { $c->title = ucwords(strtolower($c->title)); echo $c->title . "<br>"; $c->update(); } } } echo "<br><hr><br>\n\n"; } }*/ /*$category = ServiceCategory::where('slug', '=', 'terminal')->first(); $categories = $category->services->where('icon', 'IS', null); foreach ($categories as $category) { $category->icon = 'https://maps.gstatic.com/mapfiles/place_api/icons/bus-71.png'; $category->update(); echo "<strong>UPDATED</strong> " . $category->id . " " . $category->icon . " => <strong>". $category->title . "</strong><br>\n"; }*/ return view('blank'); } }
Dimimo/Booklet
app/Http/Controllers/ApiController.php
PHP
mit
6,538
package utils.verbos; /** Clase que representa una conjugación verbal * Se ordena por valor completo, pero su igualdad se mira con la conjugación (sin tildes) * @author andoni * */ public class Conjugacion extends SufijoVerbal { // en Conjugacion el modelo genérico pasa a ser ya el infinitivo concreto private String conjugacion = ""; private String conjugacionSinTildes = ""; private String sufijoEnclitico = ""; private float confianza = 0.0F; // Confianza de detección automática del verbo (si procede) /** Constructor por defecto de un sufijo de conjugación no reflexivo * @param pInfinitivo Infinitivo verbal, p ej "amar", "deber", "vivir" ... * @param pTerminacion Terminación verbal (la que se sustituye por el sufijo de conjugación), p ej "ar" "er" "ir" para esos 3 modelos * @param pPersona Persona (1-3) de la conjugación, 0 si no procede * @param pNumeroPlural Singular (false) o plural (true) * @param pForma Forma verbal ("presente", "futuro"..., "participio", "gerundio" ...) * @param pModoSubjuntivo Indicativo (false) o subjuntivo (true) * @param pSufijo Sufijo verbal en minúsculas (con tildes, si procede) [si solo se usan las conjugaciones, puede ser ""] * @param pConjugacion Conjugación verbal en minúsculas (con tildes, si procede) [si solo se usan los sufijos, puede ser ""] * @param pConfianza Confianza (0.0F a 1.0F) de detección automática del verbo (si procede) */ public Conjugacion( String pInfinitivo, String pTerminacion, int pPersona, boolean pNumeroPlural, String pForma, boolean pModoSubjuntivo, String pSufijo, String pConjugacion, float pConfianza ) { super( pInfinitivo, pTerminacion, pPersona, pNumeroPlural, pForma, pModoSubjuntivo, pSufijo ); conjugacion = pConjugacion; conjugacionSinTildes = UtilsVerbos.quitarTildes( pConjugacion ); confianza = pConfianza; } public float getConfianza() { return confianza; } public String getInfinitivo() { // = getModelo() return modelo; } public String getConjugacion() { return conjugacion; } public String getConjugacionSinTildes() { return conjugacionSinTildes; } public String getSufijoEnclitico( ) { return sufijoEnclitico; } public void setConjugacion( String conj ) { conjugacion = conj; conjugacionSinTildes = UtilsVerbos.quitarTildes( conj ); } public void setSufijoEnclitico( String se ) { sufijoEnclitico = se; } public void setConfianza( float conf ) { confianza = conf; } /** Pone la forma verbal de la conjugación, eliminando el resto de los datos (dejándolos a blanco), * preparando este elemento para la búsqueda. * @param pConjugacion forma verbal */ /* Activa internamente el flag de búsqueda para poder encontrar la primera ocurrencia en la estructura */ public void initConjugBusqueda( String pConjugacion ) { conjugacion = pConjugacion; conjugacionSinTildes = UtilsVerbos.quitarTildes( pConjugacion ); flagBusqueda = true; // Estamos buscando este elemento en el Tree modelo = ""; persona = 0; numeroPlural = false; forma = ""; modoSubjuntivo = false; sufijo = ""; sufijoSinTildes = ""; } public int compareTo( SufijoVerbal c2 ) { // Si todo igual se devuelve 0 if (c2 instanceof Conjugacion) { return compareTo( (Conjugacion)c2 ); } return -1; } public int compareTo( Conjugacion c2 ) { // Si todo igual se devuelve 0 if (modelo.equals(c2.modelo) && terminacion==c2.terminacion && persona==c2.persona && numeroPlural==c2.numeroPlural && forma.equals(c2.forma) && modoSubjuntivo==c2.modoSubjuntivo && sufijo.equals(c2.sufijo) && conjugacion.equals(c2.conjugacion)) return 0; // Si alguno está en modo de búsqueda y coinciden las claves se devuelve 0 if (conjugacionSinTildes.equals(c2.conjugacionSinTildes) && (flagBusqueda || c2.flagBusqueda)) return 0; // Si no, -1 o +1 if (conjugacionSinTildes.compareTo( c2.conjugacionSinTildes )<0) return -1; else return +1; } public String showReduc() { return "<" + modelo + ">" + persona + (numeroPlural?"P":"S") + forma.substring(0,4) + (modoSubjuntivo?"Sub":"") + (reflexivo?"reflexivo":""); } public String show( boolean mostrarConfianza ) { return conjugacion + " (<" + modelo + "> (-" + terminacion + ") " + persona + (numeroPlural?"P ":"S ") + forma + (modoSubjuntivo?" subju":" indic") + (reflexivo?" reflexivo":"") + (sufijo.equals("")?"":" -"+sufijo) + ( (sufijoEnclitico.equals(""))?"":(" -" + sufijoEnclitico) ) + (mostrarConfianza?" [confi " + confianza + "]":"") + ")"; } public String toString() { return conjugacionSinTildes; } }
andoni-eguiluz/UD-Prog3-ant
src/utils/verbos/Conjugacion.java
Java
mit
4,580
# -*- coding: utf-8 -*- from google.appengine.api import apiproxy_stub_map from google.appengine.ext import db from django.core.urlresolvers import resolve from django.http import HttpRequest, QueryDict from ragendja.testutils import ModelTestCase from search.core import SearchIndexProperty import base64 class Indexed(db.Model): # Test normal and prefix index one = db.StringProperty() two = db.StringProperty() one_two_index = SearchIndexProperty(('one', 'two')) check = db.BooleanProperty() # Test relation index value = db.StringProperty() value_index = SearchIndexProperty('value', integrate=('one', 'check')) def run_tasks(): stub = apiproxy_stub_map.apiproxy.GetStub('taskqueue') tasks = stub.GetTasks('default') for task in tasks: view, args, kwargs = resolve(task['url']) request = HttpRequest() request.POST = QueryDict(base64.b64decode(task['body'])) view(request) stub.DeleteTask('default', task['name']) class TestIndexed(ModelTestCase): model = Indexed.value_index._relation_index_model def setUp(self): apiproxy_stub_map.apiproxy.GetStub('taskqueue').FlushQueue('default') for i in range(3): Indexed(one=u'OneOne%d' % i).put() for i in range(3): Indexed(one=u'one%d' % i, two='two%d' % i).put() for i in range(3): Indexed(one=(None, u'ÜÄÖ-+!#><|', 'blub')[i], check=bool(i%2), value=u'value%d test-word' % i).put() run_tasks() def test_setup(self): self.assertEqual(len(Indexed.one_two_index.search('one2')), 1) self.assertEqual(len(Indexed.one_two_index.search('two')), 0) self.assertEqual(len(Indexed.one_two_index.search('two1')), 1) self.assertEqual(len(Indexed.value_index.search('word')), 3) self.assertEqual(len(Indexed.value_index.search('test-word')), 3) self.assertEqual(len(Indexed.value_index.search('value0', filters=('check =', False))), 1) self.assertEqual(len(Indexed.value_index.search('value1', filters=('check =', True, 'one =', u'ÜÄÖ-+!#><|'))), 1) self.assertEqual(len(Indexed.value_index.search('value2', filters=('check =', False, 'one =', 'blub'))), 1) def test_change(self): value = Indexed.value_index.search('value0').get() value.value = 'value1 test-word' value.put() value.one = 'shidori' value.value = 'value3 rasengan/shidori' value.put() run_tasks() self.assertEqual(len(Indexed.value_index.search('rasengan')), 1) self.assertEqual(len(Indexed.value_index.search('value3')), 1) value = Indexed.value_index.search('value3').get() value.delete() run_tasks() self.assertEqual(len(Indexed.value_index.search('value3')), 0)
nurey/disclosed
app2/search/tests.py
Python
mit
2,896
const SPRINTER_COUNT = 7; // how many lanes there are, including the player var runners = []; // lineup var runner; // player var laneWidth; // width of each lane var startTime; // beginning of the game function setup() { createCanvas(window.innerWidth, window.innerHeight); /* initialize opponents */ var opponentColor = randomColor(); // color of opponents for (var i = 1; i < SPRINTER_COUNT; i++) { // push opponents runners.push(new Sprinter(random(0.075) + 0.1, opponentColor)); } /* initialize player */ runner = new Sprinter(0, invertColor(opponentColor)); runners.splice(Math.floor(runners.length / 2), 0, runner); /* initialize stopwatch */ startTime = new Date().getTime(); laneWidth = height / runners.length; } function draw() { background(51); handleTrack(); stride(); } /** * handle user input */ function keyPressed() { runner.run(keyCode); } /** * AI for opponents */ function stride() { for (var r = 0; r < runners.length; r++) { // loop through runners if (random() < runners[r].skill) { // calculate the speed of the runner // take a stride // LEFT_ARROW + RIGHT_ARROW = 76, therefore; // 76 - LEFT_ARROW = RIGHT_ARROW & // 76 - RIGHT_ARROW = LEFT_ARROW runners[r].run(76 - runners[r].previousKey); } } } /** * draws & updates runners * draws lanes */ function handleTrack() { for (var r = 0; r < runners.length; r++) { /* draw & update runners */ runners[r].draw(r, laneWidth); runners[r].update(); /* draw lanes */ var y1 = (r / runners.length) * height; // inner line var y2 = (r / runners.length) * height + laneWidth; // outer line stroke("#A14948"); strokeWeight(3); line(0, y1, width, y1); line(0, y2, width, y2); } } /** * returns a random color */ function randomColor() { return color(random(255), random(255), random(255)); } /** * returns an inverted color of the passed col */ function invertColor(col) { var r = 255 - red(col); var g = 255 - green(col); var b = 255 - blue(col); return color(r, g, b); }
Kaelinator/AGAD
Sprinter Game/SprinterGame.js
JavaScript
mit
2,082
<?php if (! defined('BASEPATH')) exit('No direct Script access allowed'); class Prova_model extends CI_Model { /*------------------------------ ATRIBUTOS ------------------------------*/ private $idProva; private $nome; private $introducao; private $inicio; private $termino; private $tentativas; private $objDisciplina; private $objTurma; private $data_exclusao; /*------------------------------ CONSTRUTOR ------------------------------*/ public function __construct() { parent::__construct(); } /*------------------------------ METODOS ------------------------------*/ public function GetidProva() // RETORNA PROVA { return $this->idProva; } public function SetidProva($idProva) // ATRIBUI PROVA { $this->idProva = $idProva; } public function GetNome() // RETORNA NOME { return $this->nome; } public function SetNome($nome) // ATRIBUI NOME { $this->nome = $nome; } public function GetIntroducao() // RETORNA INTRODUCAO { return $this->introducao; } public function SetIntroducao($introducao) // ATRIBUI INTRODUCAO { $this->introducao = $introducao; } public function GetInicio() // RETORNA INICIO DA PROVA { return $this->inicio; } public function SetInicio($inicio) // ATRIBUI INICIO DA PROVA { $this->inicio = $inicio; } public function GetTermino() // RETORNA TERMINO DA PROVA { return $this->termino; } public function SetTermino($termino) // ATRIBUI TERMINO DA PROVA { $this->termino = $termino; } public function GetTentativas() // RETORNA TENTATIVAS DA PROVA { return $this->tentativas; } public function SetTentativas($tentativas) // ATRIBUI TENTATIVAS DA PROVA { $this->tentativas = $tentativas; } /*--- NÃO NECESSARIO public function GetobjDisciplina() { return $this->objDisciplina; } public function SetobjDisciplina($objDisciplina) { $this->objDisciplina = $objDisciplina; } public function GetobjTurma() { return $this->objTurma; } public function SetobjTurma($objTurma) { $this->objTurma = $objTurma; } --- DESCONTINUADO */ public function GetDataExclusao() { return $this->data_exclusao; } public function SetDataExclusao($data_exclusao) { $this->data_exclusao = $data_exclusao; } public function consultar(){ $this->db->select('p.*,d.descricao as disciplina'); $this->db->where('p.data_exclusao',null); $this->db->from('provas p'); $this->db->join('disciplina d','p.disciplina_iddisciplina = d.iddisciplina'); return $this->db->get()->result(); } public function Consultar_Id($id){ $id = addslashes($id); return $this->db->get_where('provas',array('idprovas'=>$id))->row(); } public function ConsultarDisciplinaProva(){ $this->db->select('p.idprovas,p.nome,d.iddisciplina,d.descricao as disciplina'); $this->db->where('p.data_exclusao',null); $this->db->where('p.aplicada',1); $this->db->from('provas p'); $this->db->join('disciplina d','p.disciplina_iddisciplina = d.iddisciplina'); return $this->db->get()->result(); } public function Contagem(){ $this->db->select('idprovas'); $this->db->where('p.data_exclusao',null); $this->db->where('p.aplicada',1); $this->db->from('provas p'); return $this->db->get()->result()-num_rows; } public function Validacao($id,$aluno) { $this->db->where('idprovas', $id); $this->db->from('provas'); $query = $this->db->get(); if ($query->num_rows() == 1) { return true; // RETORNA VERDADEIRO } } public function inserir(){ $object = array( 'idprovas' => $this->GetIdProva(), 'nome' => $this->GetNome(), 'introducao' => $this->GetIntroducao(), 'inicio' => $this->GetInicio(), 'termino' => $this->GetTermino(), 'tentativa' => $this->GetTentativas(), 'turma_idturma' => $this->Turma_model->GetidTurma(), 'disciplina_iddisciplina' => $this->Disciplina_model->GetIdDisciplina(), 'data_exclusao' => null, ); $query = $this->db->insert('provas',$object); if($query){ $this->session->set_flashdata('sucesso','<div class="alert alert-success alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4> <i class="icon fa fa-check"></i> Alerta!</h4> Sua Turma foi cadastrada com sucesso..</div>'); redirect('prova'); } } public function update(){ $object = array( 'idprovas' => $this->GetIdProva(), 'nome' => $this->GetNome(), 'introducao' => $this->GetIntroducao(), 'inicio' => $this->GetInicio(), 'termino' => $this->GetTermino(), 'tentativa' => $this->GetTentativas(), 'turma_idturma' => $this->Turma_model->GetidTurma(), 'disciplina_iddisciplina' => $this->Disciplina_model->GetIdDisciplina(), 'data_exclusao' => null, ); $this->db->where('idprovas', $this->GetIdProva()); if($this->db->update('provas',$object)){ $this->session->set_flashdata('sucesso','<div class="alert alert-success alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4><i class="icon fa fa-check"></i> Alerta!</h4> Seu produto foi Alterado com sucesso..</div>'); redirect('prova'); } } public function aplicar(){ $object = array( 'aplicada' => 1, ); $this->db->where('idprovas', $this->GetIdProva()); if($this->db->update('provas',$object)){ $this->session->set_flashdata('sucesso','<div class="alert alert-success alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4><i class="icon fa fa-check"></i> Alerta!</h4> Seu produto foi Alterado com sucesso..</div>'); redirect('prova'); } } public function excluir(){ $object = array( 'data_exclusao' => $this->GetDataExclusao() ); $this->db->where('idprovas', $this->GetIdProva()); if($this->db->update('provas',$object)){ $this->session->set_flashdata('sucesso','<div class="alert alert-success alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4><i class="icon fa fa-check"></i> Alerta!</h4> Seu produto foi deletado com sucesso..</div>'); redirect('prova'); } } public function Consulta_ProvaDisciplina($iddisciplina){ $this->db->select('*'); $this->db->where('p.data_exclusao',null); $this->db->where('p.aplicada',1); $this->db->where('p.disciplina_iddisciplina',$iddisciplina); $this->db->from('provas p'); $this->db->join('disciplina d', 'p.disciplina_iddisciplina = d.iddisciplina'); return $this->db->get()->result(); } public function Consulta_ProvaDisciplina2($matricula){ $this->db->select('*'); $this->db->from('cursando c'); $this->db->where('c.disciplina_iddisciplina',$matricula); $this->db->where('p.aplicada',1); $this->db->join('aluno a', 'c.Aluno_idAluno = a.idaluno'); $this->db->join('disciplina d', 'c.disciplina_iddisciplina = d.iddisciplina'); $this->db->join('provas p', 'p.disciplina_iddisciplina = d.iddisciplina'); return $this->db->get()->result(); } } ?>
Lasterblade/SGPLTE
application/models/Prova_model.php
PHP
mit
8,474
#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("roxcoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } }
Roxcoin/roxcointor
src/qt/qrcodedialog.cpp
C++
mit
4,343
using System; using Microsoft.Tools.WindowsInstallerXml.Bootstrapper; namespace Shimmer.Client.WiXUi { public interface IWiXEvents { IObservable<DetectBeginEventArgs> DetectBeginObs { get; } IObservable<DetectPackageCompleteEventArgs> DetectPackageCompleteObs { get; } IObservable<DetectRelatedBundleEventArgs> DetectRelatedBundleObs { get; } IObservable<PlanPackageBeginEventArgs> PlanPackageBeginObs { get; } IObservable<PlanCompleteEventArgs> PlanCompleteObs { get; } IObservable<ApplyBeginEventArgs> ApplyBeginObs { get; } IObservable<ApplyCompleteEventArgs> ApplyCompleteObs { get; } IObservable<ResolveSourceEventArgs> ResolveSourceObs { get; } IObservable<ErrorEventArgs> ErrorObs { get; } IObservable<ExecuteMsiMessageEventArgs> ExecuteMsiMessageObs { get; } IObservable<ExecuteProgressEventArgs> ExecuteProgressObs { get; } IObservable<ProgressEventArgs> ProgressObs { get; } IObservable<CacheAcquireBeginEventArgs> CacheAcquireBeginObs { get; } IObservable<CacheCompleteEventArgs> CacheCompleteObs { get; } IEngine Engine { get; } IntPtr MainWindowHwnd { get; } Display DisplayMode { get; } LaunchAction Action { get; } void ShouldQuit(); } }
stefanolson/Squirrel.Windows.MahApps
src/Shimmer.WiXUiClient/IWiXEvents.cs
C#
mit
1,324
/** * Tree View Collapse * @see https://github.com/cpojer/mootools-tree */ export default new Class({ Implements: [Options, Class.Single], options: { animate: false, fadeOpacity: 1, className: 'collapse', selector: 'a.expand', listSelector: 'li', childSelector: 'ul' }, initialize: function(element, options) { this.setOptions(options); element = this.element = document.id(element); return this.check(element) || this.setup(); }, setup: function() { var self = this; this.handler = function(e) { self.toggle(this, e); }; this.mouseover = function() { if (self.hasChildren(this)) { this.getElement(self.options.selector).fade(1); } }; this.mouseout = function() { if (self.hasChildren(this)) { this.getElement(self.options.selector).fade(self.options.fadeOpacity); } }; this.prepare().attach(); }, attach: function() { var element = this.element; element.addEvent('click:relay(' + this.options.selector + ')', this.handler); if (this.options.animate) { element.addEvent('mouseover:relay(' + this.options.listSelector + ')', this.mouseover); element.addEvent('mouseout:relay(' + this.options.listSelector + ')', this.mouseout); } return this; }, detach: function() { this.element.removeEvent('click:relay(' + this.options.selector + ')', this.handler) .removeEvent('mouseover:relay(' + this.options.listSelector + ')', this.mouseover) .removeEvent('mouseout:relay(' + this.options.listSelector + ')', this.mouseout); return this; }, prepare: function() { this.prepares = true; this.element.getElements(this.options.listSelector).each(this.updateElement, this); this.prepares = false; return this; }, updateElement: function(element) { var child = element.getElement(this.options.childSelector); var icon = element.getElement(this.options.selector); if (!this.hasChildren(element)) { if (!this.options.animate || this.prepares) { icon.setStyle('opacity', 0); } else { icon.fade(0); } return; } if (this.options.animate) { icon.fade(this.options.fadeOpacity); } else { icon.setStyle('opacity', this.options.fadeOpacity); } if (this.isCollapsed(child)) { icon.removeClass('collapse'); } else { icon.addClass('collapse'); } }, hasChildren: function(element) { var child = element.getElement(this.options.childSelector); return (child && child.getChildren().length); }, isCollapsed: function(element) { if (!element) { return; } return (element.getStyle('display') == 'none'); }, toggle: function(element, event) { if (event) { event.preventDefault(); } if (!element.match(this.options.listSelector)) { element = element.getParent(this.options.listSelector); } if (this.isCollapsed(element.getElement(this.options.childSelector))) { this.expand(element); } else { this.collapse(element); } return this; }, expand: function(element) { element.getElement(this.options.childSelector).setStyle('display', 'block'); element.getElement(this.options.selector).addClass(this.options.className); return this; }, collapse: function(element) { if (!element.getElement(this.options.childSelector)) { return; } element.getElement(this.options.childSelector).setStyle('display', 'none'); element.getElement(this.options.selector).removeClass(this.options.className); return this; } });
codepolitan/caoutchouc
src/view/tree/utils/collapse.js
JavaScript
mit
3,649
#ifndef ADD_BINARY_HPP_ #define ADD_BINARY_HPP_ #include <string> using namespace std; class AddBinary { public: string addBinary(string a, string b); }; #endif // ADD_BINARY_HPP_
yanzhe-chen/leetcode
include/AddBinary.hpp
C++
mit
188
package org.robolectric.shadows; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.provider.BaseColumns; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.TestRunners; import static org.fest.assertions.api.Assertions.assertThat; @RunWith(TestRunners.WithDefaults.class) public class SQLiteQueryBuilderTest { private static final String TABLE_NAME = "sqlBuilderTest"; private static final String COL_VALUE = "valueCol"; private static final String COL_GROUP = "groupCol"; private SQLiteDatabase database; private SQLiteQueryBuilder builder; private long firstRecordId; @Before public void setUp() throws Exception { database = SQLiteDatabase.create(null); database.execSQL("create table " + TABLE_NAME + " (" + COL_VALUE + " TEXT, " + COL_GROUP + " INTEGER" + ")"); ContentValues values = new ContentValues(); values.put(COL_VALUE, "record1"); values.put(COL_GROUP, 1); firstRecordId = database.insert(TABLE_NAME, null, values); assertThat(firstRecordId).isGreaterThan(0); values.clear(); values.put(COL_VALUE, "record2"); values.put(COL_GROUP, 1); long secondRecordId = database.insert(TABLE_NAME, null, values); assertThat(secondRecordId).isGreaterThan(0).isNotEqualTo(firstRecordId); values.clear(); values.put(COL_VALUE, "won't be selected"); values.put(COL_GROUP, 2); database.insert(TABLE_NAME, null, values); builder = new SQLiteQueryBuilder(); builder.setTables(TABLE_NAME); builder.appendWhere(COL_VALUE + " <> "); builder.appendWhereEscapeString("won't be selected"); } @Test public void shouldBeAbleToMakeQueries() { Cursor cursor = builder.query(database, new String[] {"rowid"}, null, null, null, null, null); assertThat(cursor.getCount()).isEqualTo(2); } @Test public void shouldBeAbleToMakeQueriesWithSelection() { Cursor cursor = builder.query(database, new String[] {"rowid"}, COL_VALUE + "=?", new String[] {"record1"}, null, null, null); assertThat(cursor.getCount()).isEqualTo(1); assertThat(cursor.moveToNext()).isTrue(); assertThat(cursor.getLong(0)).isEqualTo(firstRecordId); } @Test public void shouldBeAbleToMakeQueriesWithGrouping() { Cursor cursor = builder.query(database, new String[] {"rowid"}, null, null, COL_GROUP, null, null); assertThat(cursor.getCount()).isEqualTo(1); } }
qx/FullRobolectricTestSample
src/test/java/org/robolectric/shadows/SQLiteQueryBuilderTest.java
Java
mit
2,586
require 'spec_helper' describe Authorization do let(:client_id) { "12345" } let(:client_secret) { "Y9axRxR9bcvSW2cc0IwoWeq7" } let(:expires_in) { 3600 } let(:access_token) { "75sf4WWbwfr6HYd5URpC6KBk" } subject do described_class end before do stub_requests end describe '#with_authorization' do it "returns a valid authorization" do subject.new(client_id, client_secret).with_authorization do |access_token| expect(access_token).to eq access_token end end it "returns Unauthorized" do expect { subject.new("invalid", client_secret).with_authorization }.to raise_error NotAuthorizedError end end describe '#authorize!' do it "returns a valid authorization" do auth = subject.new(client_id, client_secret).authorize! expect(auth.access_token).to eq access_token expect(auth.expires_in).not_to be_nil end it "returns Unauthorized" do expect { subject.new("invalid", client_secret).authorize! }.to raise_error NotAuthorizedError end end describe '#authorized?' do it "returns TRUE when authorization NOT Expired" do auth = subject.new(client_id, client_secret).authorize! expect(auth.authorized?).to be true end it "returns FALSE when authorization Expired" do auth = subject.new(client_id, client_secret).authorize! allow(Time).to receive(:now).and_return(auth.expires_at + 1) expect(auth.authorized?).to be false end end describe '#to_yaml' do it "serializes and deserializes Authorization" do auth = subject.new(client_id, client_secret).authorize! expect(YAML::load(auth.to_yaml)).to be_instance_of(ExactTargetRest::Authorization) end end private def stub_requests stub_request(:post, ExactTargetRest::AUTH_URL). with( :body => "{\"clientId\":\"#{client_id}\",\"clientSecret\":\"#{client_secret}\"}", :headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type'=>'application/json', 'User-Agent'=>'Faraday v0.9.2'} ). to_return( headers: {"Content-Type"=> "application/json"}, body: %({"accessToken": "#{access_token}", "expiresIn": 3600}), status: 200 ) stub_request(:any, ExactTargetRest::AUTH_URL). with( :body => "{\"clientId\":\"invalid\",\"clientSecret\":\"#{client_secret}\"}", :headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type'=>'application/json', 'User-Agent'=>'Faraday v0.9.2'} ). to_return( headers: {"Content-Type"=> "application/json"}, body: %({"message": "Unauthorized","errorcode": 1,"documentation": ""}), status: 401 ) end end
VAGAScom/exact_target_rest
spec/lib/exact_target_rest/authorization_spec.rb
Ruby
mit
2,830
<?php return array ( 'id' => 'mot_xt882_ver1', 'fallback' => 'generic_android_ver2_3', 'capabilities' => array ( 'uaprof' => 'http://uaprof.motorola.com/phoneconfig/motomb860/Profile/motoxt882.rdf', 'model_name' => 'XT882', 'brand_name' => 'Motorola', 'marketing_name' => 'MOTO XT882', 'physical_screen_height' => '89', 'physical_screen_width' => '50', 'resolution_width' => '540', 'resolution_height' => '960', ), );
cuckata23/wurfl-data
data/mot_xt882_ver1.php
PHP
mit
461
'use strict' const redis = require('redis') const config = require('config-lite').redis const logger = require('./logger.js') Promise.promisifyAll(redis.RedisClient.prototype) let client = redis.createClient(config) client.on('error', (err) => { if (err) { logger.error('connect to redis error, check your redis config', err) process.exit(1) } }) module.exports = client
xiedacon/nodeclub-koa
app/middleware/redis.js
JavaScript
mit
404
/* * This file is part of UltimateCore, licensed under the MIT License (MIT). * * Copyright (c) Bammerbom * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package bammerbom.ultimatecore.sponge.modules.afk; import bammerbom.ultimatecore.sponge.UltimateCore; import bammerbom.ultimatecore.sponge.api.config.defaultconfigs.module.ModuleConfig; import bammerbom.ultimatecore.sponge.api.config.defaultconfigs.module.RawModuleConfig; import bammerbom.ultimatecore.sponge.api.module.Module; import bammerbom.ultimatecore.sponge.modules.afk.api.AfkPermissions; import bammerbom.ultimatecore.sponge.modules.afk.commands.AfkCommand; import bammerbom.ultimatecore.sponge.modules.afk.listeners.AfkDetectionListener; import bammerbom.ultimatecore.sponge.modules.afk.listeners.AfkSwitchListener; import bammerbom.ultimatecore.sponge.modules.afk.runnables.AfkTitleTask; import org.spongepowered.api.Sponge; import org.spongepowered.api.event.game.state.GameInitializationEvent; import org.spongepowered.api.event.game.state.GamePostInitializationEvent; import org.spongepowered.api.event.game.state.GameStoppingEvent; import org.spongepowered.api.text.Text; import java.util.Optional; public class AfkModule implements Module { //TODO "user may not respond" with chat/pm to user ModuleConfig config; @Override public String getIdentifier() { return "afk"; } @Override public Text getDescription() { return Text.of("Management of what happens to idle players."); } @Override public Optional<ModuleConfig> getConfig() { return Optional.of(config); } @Override public void onRegister() { } @Override public void onInit(GameInitializationEvent event) { //Config config = new RawModuleConfig("afk"); //Commands UltimateCore.get().getCommandService().register(new AfkCommand()); //Listeners Sponge.getEventManager().registerListeners(UltimateCore.get(), new AfkSwitchListener()); AfkDetectionListener.start(); //Runnables if (config.get().getNode("title", "enabled").getBoolean(true)) { Sponge.getScheduler().createTaskBuilder().intervalTicks(config.get().getNode("title", "subtitle-refresh").getLong()).name("UC afk title task").execute(new AfkTitleTask()).submit(UltimateCore.get()); } //Register permissions new AfkPermissions(); } @Override public void onPostInit(GamePostInitializationEvent event) { } @Override public void onStop(GameStoppingEvent event) { } }
Bammerbom/UltimateCore
src/main/java/bammerbom/ultimatecore/sponge/modules/afk/AfkModule.java
Java
mit
3,618
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace AssaultBird2454.VPTU.Server.Instances { public class ServerInstance { #region Variables and Objects #region Base Server /// <summary> /// Server class for handeling server communications /// </summary> public Networking.Server.TCP.TCP_Server Server { get; private set; } /// <summary> /// Server_CommandHandeler contains functions for creating and calling command callbacks /// </summary> public Networking.Server.Command_Handeler.Server_CommandHandeler Server_CommandHandeler { get; private set; } public Server.Base_Commands Base_Server_Commands { get; private set; } private object Logger; /// <summary> /// Server_Logger contains functions for server logging /// </summary> public object Server_Logger { get { return Logger; } set { if (value is Class.Logging.I_Logger) { Logger = value; } else { throw new Class.Logging.Invalid_Logger_Class_Exception(); } } } /// <summary> /// Save Manager class, contains Save Data /// </summary> public SaveManager.SaveManager SaveManager { get; private set; } #endregion #region Authentication public List<KeyValuePair<Networking.Server.TCP.TCP_ClientNode, Authentication_Manager.Data.User>> Authenticated_Clients; public bool Authenticate_Client(Networking.Server.TCP.TCP_ClientNode cn, CommandData.Auth.Login Login) { Authenticated_Clients.RemoveAll(x => x.Key == cn); Authentication_Manager.Data.Identity ID = SaveManager.SaveData.Identities.Find(x => x.Key == Login.Client_Key); if (ID != null) { Authentication_Manager.Data.User user = SaveManager.SaveData.Users.Find(x => x.UserID == ID.UserID); Authenticated_Clients.Add(new KeyValuePair<Networking.Server.TCP.TCP_ClientNode, Authentication_Manager.Data.User>(cn, user)); ((Class.Logging.I_Logger)Server_Logger).Log("Client @ " + cn.ID + " Passed authenticated as User " + user.Name + " (" + user.IC_Name + ")", Class.Logging.LoggerLevel.Audit); cn.Send(new CommandData.Auth.Login() { Client_Key = ID.Key, Auth_State = CommandData.Auth.AuthState.Passed, UserData = user }); return true; } else { ((Class.Logging.I_Logger)Server_Logger).Log("Client @ " + cn.ID + " Failed authentication", Class.Logging.LoggerLevel.Audit); cn.Send(new CommandData.Auth.Login() { Client_Key = "", Auth_State = CommandData.Auth.AuthState.Failed }); return false; } } public void DeAuthenticate_Client(Networking.Server.TCP.TCP_ClientNode cn) { Authenticated_Clients.RemoveAll(x => x.Key == cn); ((Class.Logging.I_Logger)Server_Logger).Log("Client @ " + cn.ID + " DeAuthenticated", Class.Logging.LoggerLevel.Audit); cn.Send(new CommandData.Auth.Logout() { Auth_State = CommandData.Auth.AuthState.DeAuthenticated }); } public bool CheckAuthentication_Client(Networking.Server.TCP.TCP_ClientNode cn) { if (Authenticated_Clients.FindAll(x => x.Key == cn).Count >= 1) return true; return false; } #endregion #endregion public ServerInstance(Class.Logging.I_Logger _Logger, string SaveData, int Port = 25444) { #region Logs Server_Logger = _Logger; ((Class.Logging.I_Logger)Server_Logger).Setup(Class.Logging.Logger_Type.Server); #endregion #region SaveManager ((Class.Logging.I_Logger)Server_Logger).Log("Initilizing Save Manager", Class.Logging.LoggerLevel.Debug); SaveManager = new VPTU.SaveManager.SaveManager(SaveData);// Create Manager Object ((Class.Logging.I_Logger)Server_Logger).Log("Loading Save Data", Class.Logging.LoggerLevel.Debug); SaveManager.Load_SaveData();// Load Data #endregion #region Command Handeler ((Class.Logging.I_Logger)Server_Logger).Log("Initilizing Command Handeler", Class.Logging.LoggerLevel.Debug); Server_CommandHandeler = new Networking.Server.Command_Handeler.Server_CommandHandeler(); Server_CommandHandeler.CommandRegistered += Server_CommandHandeler_CommandRegistered; Server_CommandHandeler.CommandUnRegistered += Server_CommandHandeler_CommandUnRegistered; Server_CommandHandeler.RateLimitChanged_Event += Server_CommandHandeler_RateLimitChanged_Event; Server_CommandHandeler.RateLimitHit_Event += Server_CommandHandeler_RateLimitHit_Event; Base_Server_Commands = new Server.Base_Commands(this); ((Class.Logging.I_Logger)Server_Logger).Log("Registering Base Server Commands", Class.Logging.LoggerLevel.Debug); Base_Server_Commands.Register_Commands(Server_CommandHandeler); #endregion #region Networking ((Class.Logging.I_Logger)Server_Logger).Log("Initilizing Base Network", Class.Logging.LoggerLevel.Debug); Server = new Networking.Server.TCP.TCP_Server(IPAddress.Any, Server_CommandHandeler, Port); Server.TCP_AcceptClients_Changed += Server_TCP_AcceptClients_Changed; Server.TCP_ClientState_Changed += Server_TCP_ClientState_Changed; Server.TCP_Data_Error_Event += Server_TCP_Data_Error_Event; Server.TCP_Data_Event += Server_TCP_Data_Event; Server.TCP_ServerState_Changed += Server_TCP_ServerState_Changed; #endregion #region Plugins #endregion Authenticated_Clients = new List<KeyValuePair<Networking.Server.TCP.TCP_ClientNode, Authentication_Manager.Data.User>>(); ((Class.Logging.I_Logger)Server_Logger).Log("Server Ready!", Class.Logging.LoggerLevel.Info); } public void StartServerInstance() { #region Start Server ((Class.Logging.I_Logger)Server_Logger).Log("Starting Base Network", Class.Logging.LoggerLevel.Info); try { Authenticated_Clients = new List<KeyValuePair<Networking.Server.TCP.TCP_ClientNode, Authentication_Manager.Data.User>>(); Server.Start(); ((Class.Logging.I_Logger)Server_Logger).Log("Base Network Started", Class.Logging.LoggerLevel.Info); } catch (Exception e) { ((Class.Logging.I_Logger)Server_Logger).Log("Base Network Failed to Start", Class.Logging.LoggerLevel.Fatil); ((Class.Logging.I_Logger)Server_Logger).Log(e.ToString(), Class.Logging.LoggerLevel.Debug); Authenticated_Clients = new List<KeyValuePair<Networking.Server.TCP.TCP_ClientNode, Authentication_Manager.Data.User>>(); StopServerInstance(); return; } #endregion } public void StopServerInstance() { #region Stop Server ((Class.Logging.I_Logger)Server_Logger).Log("Stopping Base Network", Class.Logging.LoggerLevel.Info); try { Server.Stop(); ((Class.Logging.I_Logger)Server_Logger).Log("Base Network Stopped", Class.Logging.LoggerLevel.Info); } catch (Exception e) { ((Class.Logging.I_Logger)Server_Logger).Log("Base Network Failed to Stop", Class.Logging.LoggerLevel.Fatil); ((Class.Logging.I_Logger)Server_Logger).Log(e.ToString(), Class.Logging.LoggerLevel.Debug); return; } #endregion } #region Event Handelers private void Server_CommandHandeler_CommandUnRegistered(string Command) { ((Class.Logging.I_Logger)Server_Logger).Log("Command Unregistered -> Command: \"" + Command + "\"", Class.Logging.LoggerLevel.Debug); } private void Server_CommandHandeler_CommandRegistered(string Command) { ((Class.Logging.I_Logger)Server_Logger).Log("Command Registered -> Command: \"" + Command + "\"", Class.Logging.LoggerLevel.Debug); } private void Server_CommandHandeler_RateLimitChanged_Event(string Command, bool Enabled, int Limit) { if (Enabled) { ((Class.Logging.I_Logger)Server_Logger).Log("Command Rate Limit -> Command: \"" + Command + "\" Setting: \"" + Limit + " Invokes per 5 minute block per client\"", Class.Logging.LoggerLevel.Debug); } else { ((Class.Logging.I_Logger)Server_Logger).Log("Command Rate Limit -> Command: \"" + Command + "\" Setting: \"No Limit\"", Class.Logging.LoggerLevel.Debug); } } private void Server_CommandHandeler_RateLimitHit_Event(string Name, Networking.Server.TCP.TCP_ClientNode Client) { ((Class.Logging.I_Logger)Server_Logger).Log("Client \"" + Client.ID + "\" hit the rate limit for command \" " + Name + " \"", Class.Logging.LoggerLevel.Warning); } private void Server_TCP_ServerState_Changed(Networking.Data.Server_Status Server_State) { ((Class.Logging.I_Logger)Server_Logger).Log("Base Network is " + Server_State.ToString(), Class.Logging.LoggerLevel.Debug); } private void Server_TCP_Data_Event(string Data, Networking.Server.TCP.TCP_ClientNode Client, Networking.Server.TCP.DataDirection Direction) { if (Direction == Networking.Server.TCP.DataDirection.Recieve) { ((Class.Logging.I_Logger)Server_Logger).Log("Data Recieved from " + Client.ID, Class.Logging.LoggerLevel.Debug); } else if (Direction == Networking.Server.TCP.DataDirection.Send) { ((Class.Logging.I_Logger)Server_Logger).Log("Data Sent to " + Client.ID, Class.Logging.LoggerLevel.Debug); } } private void Server_TCP_Data_Error_Event(Exception ex, Networking.Server.TCP.DataDirection Direction) { ((Class.Logging.I_Logger)Server_Logger).Log("Failed to " + Direction.ToString() + " Data (Base Network)", Class.Logging.LoggerLevel.Error); } private void Server_TCP_ClientState_Changed(Networking.Server.TCP.TCP_ClientNode Client, Networking.Data.Client_ConnectionStatus Client_State) { if (Client_State == Networking.Data.Client_ConnectionStatus.Connected) { ((Class.Logging.I_Logger)Server_Logger).Log("Client Connected (Base Network) Address: " + Client.ID, Class.Logging.LoggerLevel.Info); if (Authenticated_Clients.FindAll(x => x.Key == Client).Count == 0) { Authenticated_Clients.Add(new KeyValuePair<Networking.Server.TCP.TCP_ClientNode, Authentication_Manager.Data.User>(Client, null)); } } else if (Client_State == Networking.Data.Client_ConnectionStatus.Connecting) { ((Class.Logging.I_Logger)Server_Logger).Log("Client Connecting (Base Network) Address: " + Client.ID, Class.Logging.LoggerLevel.Info); if (Authenticated_Clients.FindAll(x => x.Key == Client).Count == 0) { Authenticated_Clients.Add(new KeyValuePair<Networking.Server.TCP.TCP_ClientNode, Authentication_Manager.Data.User>(Client, null)); } } else if (Client_State == Networking.Data.Client_ConnectionStatus.Disconnected) { ((Class.Logging.I_Logger)Server_Logger).Log("Client Disconnected (Base Network) Address: " + Client.ID, Class.Logging.LoggerLevel.Info); Authenticated_Clients.RemoveAll(x => x.Key == Client); } else if (Client_State == Networking.Data.Client_ConnectionStatus.Dropped) { ((Class.Logging.I_Logger)Server_Logger).Log("Client Dropped Connection (Base Network) Address: " + Client.ID, Class.Logging.LoggerLevel.Info); Authenticated_Clients.RemoveAll(x => x.Key == Client); } else if (Client_State == Networking.Data.Client_ConnectionStatus.Encrypted) { ((Class.Logging.I_Logger)Server_Logger).Log("Client Encrypted Network Transmittions (Base Network) Address: " + Client.ID, Class.Logging.LoggerLevel.Info); if (Authenticated_Clients.FindAll(x => x.Key == Client).Count == 0) { Authenticated_Clients.Add(new KeyValuePair<Networking.Server.TCP.TCP_ClientNode, Authentication_Manager.Data.User>(Client, null)); } } } private void Server_TCP_AcceptClients_Changed(bool Accepting_Connections) { if (Accepting_Connections) { ((Class.Logging.I_Logger)Server_Logger).Log("Base Network is Accepting New Connections", Class.Logging.LoggerLevel.Info); } else { ((Class.Logging.I_Logger)Server_Logger).Log("Base Network is Refusing New Connections", Class.Logging.LoggerLevel.Info); } } #endregion } } // ((Class.Logging.I_Logger)Server_Logger).Log("", Class.Logging.LoggerLevel.Info);
AssaultBird2454/Virtual-Pokemon-Tabletop
Virtual Pokemon Tabletop/AssaultBird2454.VPTU/Server/Instances/ServerInstance.cs
C#
mit
13,894