repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
paxhujing/Tumbler.Addin.v2
Tumbler.Addin/Tumbler.Addin.Core/IMessagePoint.cs
351
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tumbler.Addin.Core { /// <summary> /// 表示该对象可以收发消息,但不是宿主、插件和服务。 /// </summary> public interface IMessagePoint : IMessageSource, IMessageTarget { } }
mit
YaniLozanov/Software-University
C#/03. C# OOP/01. C# Advanced/04. Functional Programming Exercises/01. Action Point/Program.cs
337
using System; using System.Linq; namespace _01._Action_Point { class Program { static void Main(string[] args) { Action<string> print = x => Console.WriteLine(x); Console.ReadLine() .Split() .ToList() .ForEach(print); } } }
mit
jaspervdm/pogoprotos-php
src/POGOProtos/Networking/Responses/UseItemCaptureResponse.php
16418
<?php /** * Generated by Protobuf protoc plugin. * * File descriptor : POGOProtos/Networking/Responses/UseItemCaptureResponse.proto */ namespace POGOProtos\Networking\Responses; /** * Protobuf message : POGOProtos.Networking.Responses.UseItemCaptureResponse */ class UseItemCaptureResponse extends \Protobuf\AbstractMessage { /** * @var \Protobuf\UnknownFieldSet */ protected $unknownFieldSet = null; /** * @var \Protobuf\Extension\ExtensionFieldMap */ protected $extensions = null; /** * success optional bool = 1 * * @var bool */ protected $success = null; /** * item_capture_mult optional double = 2 * * @var float */ protected $item_capture_mult = null; /** * item_flee_mult optional double = 3 * * @var float */ protected $item_flee_mult = null; /** * stop_movement optional bool = 4 * * @var bool */ protected $stop_movement = null; /** * stop_attack optional bool = 5 * * @var bool */ protected $stop_attack = null; /** * target_max optional bool = 6 * * @var bool */ protected $target_max = null; /** * target_slow optional bool = 7 * * @var bool */ protected $target_slow = null; /** * Check if 'success' has a value * * @return bool */ public function hasSuccess() { return $this->success !== null; } /** * Get 'success' value * * @return bool */ public function getSuccess() { return $this->success; } /** * Set 'success' value * * @param bool $value */ public function setSuccess($value = null) { $this->success = $value; } /** * Check if 'item_capture_mult' has a value * * @return bool */ public function hasItemCaptureMult() { return $this->item_capture_mult !== null; } /** * Get 'item_capture_mult' value * * @return float */ public function getItemCaptureMult() { return $this->item_capture_mult; } /** * Set 'item_capture_mult' value * * @param float $value */ public function setItemCaptureMult($value = null) { $this->item_capture_mult = $value; } /** * Check if 'item_flee_mult' has a value * * @return bool */ public function hasItemFleeMult() { return $this->item_flee_mult !== null; } /** * Get 'item_flee_mult' value * * @return float */ public function getItemFleeMult() { return $this->item_flee_mult; } /** * Set 'item_flee_mult' value * * @param float $value */ public function setItemFleeMult($value = null) { $this->item_flee_mult = $value; } /** * Check if 'stop_movement' has a value * * @return bool */ public function hasStopMovement() { return $this->stop_movement !== null; } /** * Get 'stop_movement' value * * @return bool */ public function getStopMovement() { return $this->stop_movement; } /** * Set 'stop_movement' value * * @param bool $value */ public function setStopMovement($value = null) { $this->stop_movement = $value; } /** * Check if 'stop_attack' has a value * * @return bool */ public function hasStopAttack() { return $this->stop_attack !== null; } /** * Get 'stop_attack' value * * @return bool */ public function getStopAttack() { return $this->stop_attack; } /** * Set 'stop_attack' value * * @param bool $value */ public function setStopAttack($value = null) { $this->stop_attack = $value; } /** * Check if 'target_max' has a value * * @return bool */ public function hasTargetMax() { return $this->target_max !== null; } /** * Get 'target_max' value * * @return bool */ public function getTargetMax() { return $this->target_max; } /** * Set 'target_max' value * * @param bool $value */ public function setTargetMax($value = null) { $this->target_max = $value; } /** * Check if 'target_slow' has a value * * @return bool */ public function hasTargetSlow() { return $this->target_slow !== null; } /** * Get 'target_slow' value * * @return bool */ public function getTargetSlow() { return $this->target_slow; } /** * Set 'target_slow' value * * @param bool $value */ public function setTargetSlow($value = null) { $this->target_slow = $value; } /** * {@inheritdoc} */ public function extensions() { if ( $this->extensions !== null) { return $this->extensions; } return $this->extensions = new \Protobuf\Extension\ExtensionFieldMap(__CLASS__); } /** * {@inheritdoc} */ public function unknownFieldSet() { return $this->unknownFieldSet; } /** * {@inheritdoc} */ public static function fromStream($stream, \Protobuf\Configuration $configuration = null) { return new self($stream, $configuration); } /** * {@inheritdoc} */ public static function fromArray(array $values) { $message = new self(); $values = array_merge([ 'success' => null, 'item_capture_mult' => null, 'item_flee_mult' => null, 'stop_movement' => null, 'stop_attack' => null, 'target_max' => null, 'target_slow' => null ], $values); $message->setSuccess($values['success']); $message->setItemCaptureMult($values['item_capture_mult']); $message->setItemFleeMult($values['item_flee_mult']); $message->setStopMovement($values['stop_movement']); $message->setStopAttack($values['stop_attack']); $message->setTargetMax($values['target_max']); $message->setTargetSlow($values['target_slow']); return $message; } /** * {@inheritdoc} */ public static function descriptor() { return \google\protobuf\DescriptorProto::fromArray([ 'name' => 'UseItemCaptureResponse', 'field' => [ \google\protobuf\FieldDescriptorProto::fromArray([ 'number' => 1, 'name' => 'success', 'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_BOOL(), 'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL() ]), \google\protobuf\FieldDescriptorProto::fromArray([ 'number' => 2, 'name' => 'item_capture_mult', 'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_DOUBLE(), 'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL() ]), \google\protobuf\FieldDescriptorProto::fromArray([ 'number' => 3, 'name' => 'item_flee_mult', 'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_DOUBLE(), 'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL() ]), \google\protobuf\FieldDescriptorProto::fromArray([ 'number' => 4, 'name' => 'stop_movement', 'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_BOOL(), 'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL() ]), \google\protobuf\FieldDescriptorProto::fromArray([ 'number' => 5, 'name' => 'stop_attack', 'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_BOOL(), 'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL() ]), \google\protobuf\FieldDescriptorProto::fromArray([ 'number' => 6, 'name' => 'target_max', 'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_BOOL(), 'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL() ]), \google\protobuf\FieldDescriptorProto::fromArray([ 'number' => 7, 'name' => 'target_slow', 'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_BOOL(), 'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL() ]), ], ]); } /** * {@inheritdoc} */ public function toStream(\Protobuf\Configuration $configuration = null) { $config = $configuration ?: \Protobuf\Configuration::getInstance(); $context = $config->createWriteContext(); $stream = $context->getStream(); $this->writeTo($context); $stream->seek(0); return $stream; } /** * {@inheritdoc} */ public function writeTo(\Protobuf\WriteContext $context) { $stream = $context->getStream(); $writer = $context->getWriter(); $sizeContext = $context->getComputeSizeContext(); if ($this->success !== null) { $writer->writeVarint($stream, 8); $writer->writeBool($stream, $this->success); } if ($this->item_capture_mult !== null) { $writer->writeVarint($stream, 17); $writer->writeDouble($stream, $this->item_capture_mult); } if ($this->item_flee_mult !== null) { $writer->writeVarint($stream, 25); $writer->writeDouble($stream, $this->item_flee_mult); } if ($this->stop_movement !== null) { $writer->writeVarint($stream, 32); $writer->writeBool($stream, $this->stop_movement); } if ($this->stop_attack !== null) { $writer->writeVarint($stream, 40); $writer->writeBool($stream, $this->stop_attack); } if ($this->target_max !== null) { $writer->writeVarint($stream, 48); $writer->writeBool($stream, $this->target_max); } if ($this->target_slow !== null) { $writer->writeVarint($stream, 56); $writer->writeBool($stream, $this->target_slow); } if ($this->extensions !== null) { $this->extensions->writeTo($context); } return $stream; } /** * {@inheritdoc} */ public function readFrom(\Protobuf\ReadContext $context) { $reader = $context->getReader(); $length = $context->getLength(); $stream = $context->getStream(); $limit = ($length !== null) ? ($stream->tell() + $length) : null; while ($limit === null || $stream->tell() < $limit) { if ($stream->eof()) { break; } $key = $reader->readVarint($stream); $wire = \Protobuf\WireFormat::getTagWireType($key); $tag = \Protobuf\WireFormat::getTagFieldNumber($key); if ($stream->eof()) { break; } if ($tag === 1) { \Protobuf\WireFormat::assertWireType($wire, 8); $this->success = $reader->readBool($stream); continue; } if ($tag === 2) { \Protobuf\WireFormat::assertWireType($wire, 1); $this->item_capture_mult = $reader->readDouble($stream); continue; } if ($tag === 3) { \Protobuf\WireFormat::assertWireType($wire, 1); $this->item_flee_mult = $reader->readDouble($stream); continue; } if ($tag === 4) { \Protobuf\WireFormat::assertWireType($wire, 8); $this->stop_movement = $reader->readBool($stream); continue; } if ($tag === 5) { \Protobuf\WireFormat::assertWireType($wire, 8); $this->stop_attack = $reader->readBool($stream); continue; } if ($tag === 6) { \Protobuf\WireFormat::assertWireType($wire, 8); $this->target_max = $reader->readBool($stream); continue; } if ($tag === 7) { \Protobuf\WireFormat::assertWireType($wire, 8); $this->target_slow = $reader->readBool($stream); continue; } $extensions = $context->getExtensionRegistry(); $extension = $extensions ? $extensions->findByNumber(__CLASS__, $tag) : null; if ($extension !== null) { $this->extensions()->add($extension, $extension->readFrom($context, $wire)); continue; } if ($this->unknownFieldSet === null) { $this->unknownFieldSet = new \Protobuf\UnknownFieldSet(); } $data = $reader->readUnknown($stream, $wire); $unknown = new \Protobuf\Unknown($tag, $wire, $data); $this->unknownFieldSet->add($unknown); } } /** * {@inheritdoc} */ public function serializedSize(\Protobuf\ComputeSizeContext $context) { $calculator = $context->getSizeCalculator(); $size = 0; if ($this->success !== null) { $size += 1; $size += 1; } if ($this->item_capture_mult !== null) { $size += 1; $size += 8; } if ($this->item_flee_mult !== null) { $size += 1; $size += 8; } if ($this->stop_movement !== null) { $size += 1; $size += 1; } if ($this->stop_attack !== null) { $size += 1; $size += 1; } if ($this->target_max !== null) { $size += 1; $size += 1; } if ($this->target_slow !== null) { $size += 1; $size += 1; } if ($this->extensions !== null) { $size += $this->extensions->serializedSize($context); } return $size; } /** * {@inheritdoc} */ public function clear() { $this->success = null; $this->item_capture_mult = null; $this->item_flee_mult = null; $this->stop_movement = null; $this->stop_attack = null; $this->target_max = null; $this->target_slow = null; } /** * {@inheritdoc} */ public function merge(\Protobuf\Message $message) { if ( ! $message instanceof \POGOProtos\Networking\Responses\UseItemCaptureResponse) { throw new \InvalidArgumentException(sprintf('Argument 1 passed to %s must be a %s, %s given', __METHOD__, __CLASS__, get_class($message))); } $this->success = ($message->success !== null) ? $message->success : $this->success; $this->item_capture_mult = ($message->item_capture_mult !== null) ? $message->item_capture_mult : $this->item_capture_mult; $this->item_flee_mult = ($message->item_flee_mult !== null) ? $message->item_flee_mult : $this->item_flee_mult; $this->stop_movement = ($message->stop_movement !== null) ? $message->stop_movement : $this->stop_movement; $this->stop_attack = ($message->stop_attack !== null) ? $message->stop_attack : $this->stop_attack; $this->target_max = ($message->target_max !== null) ? $message->target_max : $this->target_max; $this->target_slow = ($message->target_slow !== null) ? $message->target_slow : $this->target_slow; } }
mit
jtneal/learn-clean-code
src/DesignPatterns/Adapter/Radio.php
565
<?php namespace LearnCleanCode\DesignPatterns\Adapter; /** * Class Radio * @package LearnCleanCode\DesignPatterns\Adapter */ class Radio { /** * @var int */ private $state = 0; /** * Turn On */ public function radioOn() { $this->state = 1; } /** * Turn Off */ public function radioOff() { $this->state = 0; } /** * @return bool */ public function isRadioOn(): bool { return $this->state === 1; } }
mit
mbr/flask-nav
setup.py
741
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='flask-nav', version='0.6.dev1', description='Easily create navigation for Flask applications.', long_description=read('README.rst'), author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/flask-nav', license='MIT', packages=find_packages(exclude=['tests', 'example']), install_requires=['flask', 'visitor', 'dominate'], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ])
mit
dapengchen123/code_v1
reid/models/resnetlstm_btfu.py
3442
from __future__ import absolute_import import torch.nn.functional as F import torch.nn.init as init from torch import nn from torch.autograd import Variable from torchvision.models import resnet18, resnet34, resnet50, resnet101, \ resnet152 from torch import zeros as t_zeros LSTM_hidden = 128 LSTM_layer = 2 def init_states(hidden_sz, batch_sz, layer=1): h_0 = Variable(t_zeros(layer, batch_sz, hidden_sz)) c_0 = Variable(t_zeros(layer, batch_sz, hidden_sz)) return (h_0.cuda(), c_0.cuda()) class ResNetLSTM_btfu(nn.Module): __factory = { 18: resnet18, 34: resnet34, 50: resnet50, 101: resnet101, 152: resnet152, } def __init__(self, depth, pretrained=True, num_features=0, norm=False, dropout=0): super(ResNetLSTM_btfu, self).__init__() self.depth = depth self.pretrained = pretrained # Construct base (pretrained) resnet if depth not in ResNetLSTM_btfu.__factory: raise KeyError("Unsupported depth:". depth) ### At the bottom of CNN network conv0 = nn.Conv2d(2, 64, kernel_size=7, stride=2, padding=3, bias=False) init.kaiming_normal(conv0.weight, mode='fan_out') self.conv0 = conv0 self.base = ResNetLSTM_btfu.__factory[depth](pretrained=pretrained) self.num_features = num_features self.norm = norm self.dropout = dropout self.has_embedding = num_features > 0 ### Append new upper layers out_planes = self.base.fc.in_features if self.has_embedding: self.feat = nn.Linear(out_planes, self.num_features) self.feat_bn = nn.BatchNorm1d(self.num_features) init.kaiming_normal(self.feat.weight, mode='fan_out') init.constant(self.feat.bias, 0) init.constant(self.feat_bn.weight, 1) init.constant(self.feat_bn.bias, 0) else: self.num_features = out_planes if self.dropout > 0: self.drop = nn.Dropout(self.dropout) ### Append LSTM layers self.lstm = nn.LSTM(self.num_features, LSTM_hidden, num_layers=LSTM_layer, batch_first=True) def forward(self, imgs, motions): img_size = imgs.size() motion_size = motions.size() batch_sz = img_size[0] seq_len = img_size[1] imgs = imgs.view(img_size[0] * img_size[1], img_size[2], img_size[3], img_size[4]) motions = motions.view(motion_size[0] * motion_size[1], motion_size[2], motion_size[3], motion_size[4]) motions = motions[:, 1:3] for name, module in self.base._modules.items(): if name == 'conv1': x = module(imgs)+self.conv0(motions) continue if name == 'avgpool': break x = module(x) x = F.avg_pool2d(x, x.size()[2:]) x = x.view(x.size(0), -1) if self.has_embedding: x = self.feat(x) x = self.feat_bn(x) if self.norm: x = x / x.norm(2, 1).expand_as(x) elif self.has_embedding: x = F.relu(x) if self.dropout > 0: x = self.drop(x) ###### LSTM part ######### x = x.view(batch_sz, seq_len, -1) hidden0 = init_states(LSTM_hidden, batch_sz, LSTM_layer) output, _ = self.lstm (x, hidden0) return output[:, -1]
mit
Comp4711Bengals/a2
application/views/League/leagueConf.php
3561
<div class="row"> <div class="text"> <button><a href="/League/layout/leagueConf">Conference</a></button> <button><a href="/League/layout/leagueDiv">Division</a></button> <button><a href="/League/layout/league">League</a></button> <br/> <br/> <h2>NFL Teams - American Football Conference</h2> <table class="table table-bordered tb"> <thead> <tr> <th>LOGO:</th> <th>TEAM NAME</th> <th>CITY:</th> <th>WINS:</th> <th>LOSSES:</th> <th>TIES:</th> <th>PF:</th> <th>PA:</th> <th>NET POINTS:</th> <th>HOME WINS:</th> <th>ROAD WINS:</th> <th>DIVISION WINS:</th> <th>CONF:</th> <th>NON-CONF:</th> <th>STREAK:</th> <th>LAST 5:</th> </tr> </thead> <tbody> {AFC} <tr> <td><img class="logo" src="/assets/images/teamLogos/{logo}"/></td> <td>{id}</td> <td>{city}</td> <td>{win}</td> <td>{loss}</td> <td>{ties}</td> <td>{pf}</td> <td>{pa}</td> <td>{netpts}</td> <td>{homew}</td> <td>{roadw}</td> <td>{divw}</td> <td>{confscore}</td> <td>{nonconfscore}</td> <td>{streak}</td> <td>{last5}</td> </tr> {/AFC} </tbody> </table> <h2>NFL Teams - National Football Conference</h2> <table class="table table-bordered tb"> <thead> <tr> <th>Logo:</th> <th>TEAM NAME</th> <th>CITY:</th> <th>DIVISION:</th> <th>WINS:</th> <th>LOSSES:</th> <th>TIES:</th> <th>PF:</th> <th>PA:</th> <th>NET POINTS:</th> <th>HOME WINS:</th> <th>ROAD WINS:</th> <th>DIVISION WINS:</th> <th>CONF:</th> <th>NON-CONF:</th> <th>STREAK:</th> <th>LAST 5:</th> </tr> </thead> <tbody> {NFC} <tr> <td><img class="logo" src="/assets/images/teamLogos/{logo}"/></td> <td>{id}</td> <td>{city}</td> <td>{division}</td> <td>{win}</td> <td>{loss}</td> <td>{ties}</td> <td>{pf}</td> <td>{pa}</td> <td>{netpts}</td> <td>{homew}</td> <td>{roadw}</td> <td>{divw}</td> <td>{confscore}</td> <td>{nonconfscore}</td> <td>{streak}</td> <td>{last5}</td> </tr> {/NFC} </tbody> </table> </div> </div>
mit
hattonpoint/SendWithUs.Client
SendWithUs.Client.Tests/Unit/DripCampaignDeactivateAllResponseTests.cs
3596
// 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. namespace SendWithUs.Client.Tests.Unit { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Newtonsoft.Json.Linq; using Names = SendWithUs.Client.DripCampaignDeactivateAllResponse.PropertyNames; [TestClass] public class DripCampaignDeactivateAllResponseTests { [TestMethod] public void Populate_NullJson_DoesNotSetProperties() { // Arrange var response = new Mock<DripCampaignDeactivateAllResponse>() { CallBase = true }; var json = null as JObject; // Act response.Object.Populate(json); // Assert response.VerifySet(r => r.Success = It.IsAny<bool>(), Times.Never); response.VerifySet(r => r.Status = It.IsAny<string>(), Times.Never); response.VerifySet(r => r.RecipientAddress = It.IsAny<string>(), Times.Never); response.VerifySet(r => r.UnsubscribedCount = It.IsAny<int>(), Times.Never); } [TestMethod] public void Populate_ValidJson_SetsProperties() { // Arrange var response = new Mock<DripCampaignDeactivateAllResponse>() { CallBase = true }; var success = true; var status = TestHelper.GetUniqueId(); var dripCampaignId = TestHelper.GetUniqueId(); var dripCampaignName = TestHelper.GetUniqueId(); var recipientAddress = TestHelper.GetUniqueId(); var unsubscribedCount = TestHelper.GetRandomInteger(0,1000); var json = new Mock<JObject>(); var details = new Mock<JObject>(); json.Setup(j => j.Value<bool>(Names.Success)).Returns(success); json.Setup(j => j.Value<string>(Names.Status)).Returns(status); json.Setup(j => j.Value<string>(Names.RecipientAddress)).Returns(recipientAddress); json.Setup(j => j.Value<int>(Names.UnsubscribedCount)).Returns(unsubscribedCount); // Act response.Object.Populate(json.Object); // Assert response.VerifySet(r => r.Success = success, Times.Once); response.VerifySet(r => r.Status = status, Times.Once); response.VerifySet(r => r.RecipientAddress = recipientAddress, Times.Once); response.VerifySet(r => r.UnsubscribedCount = unsubscribedCount, Times.Once); } } }
mit
hisune/Echarts-PHP
src/Doc/IDE/SingleAxis/SplitArea/AreaStyle.php
1247
<?php /** * Created by Hisune EchartsPHP AutoGenerate. * @author: Hisune <hi@hisune.com> */ namespace Hisune\EchartsPHP\Doc\IDE\SingleAxis\SplitArea; use Hisune\EchartsPHP\Property; /** * @property array $color Default: '[\'rgba(250,250,250,0.3)\',\'rgba(200,200,200,0.3)\']' * Color of split area. * SplitArea color could also be set in color array, which the split lines would take as their colors in turns. Dark and light colors in turns are used by default. * * @property int $shadowBlur * Size of shadow blur. This attribute should be used along with shadowColor,shadowOffsetX, shadowOffsetY to set shadow to component. * For example: * { * shadowColor: rgba(0, 0, 0, 0.5), * shadowBlur: 10 * } * * @property string $shadowColor * Shadow color. Support same format as color. * * @property int $shadowOffsetX Default: 0 * Offset distance on the horizontal direction of shadow. * * @property int $shadowOffsetY Default: 0 * Offset distance on the vertical direction of shadow. * * @property int $opacity * Opacity of the component. Supports value from 0 to 1, and the component will not be drawn when set to 0. * * {_more_} */ class AreaStyle extends Property {}
mit
lafaiDev/vente-en-ligne
src/Catalogue/CatalogueBundle/Entity/ProduitOption.php
1810
<?php namespace Catalogue\CatalogueBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * ProduitOption * * @ORM\Table() * @ORM\Entity(repositoryClass="Catalogue\CatalogueBundle\Entity\ProduitOptionRepository") */ class ProduitOption { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var float * * @ORM\Column(name="montant", type="float") */ private $montant; /** * @ORM\ManyToOne(targetEntity="Catalogue\CatalogueBundle\Entity\Produit", inversedBy="options") * @ORM\JoinColumn(nullable=false) */ private $produit; /** * @var string * * @ORM\Column(name="nom", type="string", length=255) */ private $options; /** * @param mixed $produit */ public function setProduit($produit) { $this->produit = $produit; } /** * @return mixed */ public function getProduit() { return $this->produit; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set montant * * @param float $montant * * @return ProduitOption */ public function setMontant($montant) { $this->montant = $montant; return $this; } /** * Get montant * * @return float */ public function getMontant() { return $this->montant; } /** * @param mixed $options */ public function setOptions($options) { $this->options = $options; } /** * @return mixed */ public function getOptions() { return $this->options; } }
mit
castlegateit/cgit-static-site-template
index.php
900
<?php $page_info = [ 'title' => 'Static Site Template', 'heading' => 'Static Site Template', 'description' => 'A template for static sites in PHP.', ]; include $_SERVER['DOCUMENT_ROOT'] . '/includes/header.php'; ?> <div class="main" role="main"> <h1>Home</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> <?php include $_SERVER['DOCUMENT_ROOT'] . '/includes/side.php'; include $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';
mit
vdkhai/neatHR
app/views/admin/employeeemergencycontacts/index.blade.php
3062
@extends('admin.layouts.default') {{-- Web site Title --}} @section('title') {{{ $title }}} :: @parent @stop {{-- Content --}} @section('content') <div class="page-header"> <h3> {{{ $title }}} <div class="pull-right"> <a data-toggle="modal" data-target="#modal" id="create" href="#" class="btn btn-small btn-info"><span class="glyphicon glyphicon-plus-sign"></span> {{{ Lang::get('button.create') }}}</a> </div> </h3> </div> <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content" id="replaceableContent"> </div> </div> </div> <table id="employeeemergencycontacts" class="table table-striped table-hover"> <thead> <tr> <th class="col-md-1">{{{ Lang::get('table.status') }}}</th> <th class="col-md-4">{{{ Lang::get('admin/employeeemergencycontacts/table.employeeemergencycontact_title') }}}</th> <th class="col-md-6">{{{ Lang::get('admin/employeeemergencycontacts/table.employeeemergencycontact_detail') }}}</th> <th class="col-md-1">{{{ Lang::get('table.actions') }}}</th> </tr> </thead> <tbody> </tbody> </table> @stop {{-- Scripts --}} @section('scripts') <script type="text/javascript"> var oTable; $(document).ready(function() { oTable = $('#employeeemergencycontacts').dataTable( { "sDom": "<'row'<'col-md-6'l><'col-md-6'f>r>t<'row'<'col-md-6'i><'col-md-6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page" }, "bProcessing": true, "bServerSide": true, "sAjaxSource": "{{ URL::to('admin/employeeemergencycontacts/' . $employee->id . '/data') }}", "fnDrawCallback": function ( oSettings ) { $(".iframe").colorbox({iframe:true, width:"80%", height:"80%"}); } }); }); $(document).ready(function() { // Open modal to create $('#create').click(function(e){ e.preventDefault(); getAjaxContent("{{ URL::to('admin/employeeemergencycontacts/' . $employee->id . '/create') }}"); $('#modal').modal(); }); }); // Open modal to edit function getEdit(url){ getAjaxContent(url); $('#modal').modal(); } function getDelete(url){ ajaxDelete(url); } function getAjaxContent(url){ $.ajax({ url: url, data: '', dataType: 'html', tryCount:0, //current retry count retryLimit:3, //number of retries on fail timeout: 5000, //time before retry on fail success: function(returnedData) { var divContent = $('#replaceableContent'); divContent.html(returnedData); }, error: function(xhr, textStatus, errorThrown) { if (textStatus == 'timeout') { //if error is 'timeout' this.tryCount++; if (this.tryCount < this.retryLimit) { $.ajax(this); return; } } } }); } function ajaxDelete(url){ $.ajax({ url: url, success: function(returnData) { var returnObj = $.parseJSON(returnData); oTable.fnReloadAjax(); return false; }, error: function(){ alert('Delete fail'); return false; } }); } </script> @stop
mit
WebHare/designfiles
wh.compat.base/wh.compat.base.js
46336
/* generated from Designfiles Public by generate_data_designfles */ require ('frameworks.mootools.core'); /*! LOAD: frameworks.mootools.core !*/ /* This file is always included when wh.compat.base is requested. It only contains non-browser stuff, like generic object extensions. All browser stuff, like Element extensions, is located in base-browser.js */ (function() { // Fake some browser objects, if we're called within the context of a Titanium module if (typeof Ti != "undefined") { window = this; document = {}; } if (!window.$wh) window.$wh = {}; $wh.debug = {}; $wh.isHTMLElement = function(node) { return node.nodeType == 1 && typeof node.className == "string"; } String.implement( { /* Return the length of the string in bytes when UTF8-encoded */ getUTF8Length: function() { return unescape(encodeURIComponent(this)).length; } /* encodeAsHTML */ , encodeAsHTML:function() { return this.split('&').join('&amp;').split('<').join('&lt;'); } /* encodeAsValue */ , encodeAsValue: function() { return this.split('"').join('&#34;').split("'").join("&#39;"); } /* decodeFromHtml */ , decodeFromHtml: function() { var str = this.replace(/<br *\/?>/g, "\n"); str = str.replace(/&#(\d+);/g, function(match, dec) { return String.fromCharCode(dec) }); str = str.replace(/&amp;/g, "&"); return str.replace(/&lt;/g, "<"); } }); Date.implement( { /* Calculate the number of full years between this date and another date (the current date if no other date given). Time of day is not taken into consideration. */ getAge: function(otherDate) { // If no 'other date' is given, use current date otherDate = otherDate || new Date(); // Calculate the year difference var years = otherDate.getFullYear() - this.getFullYear(); // If the current month is before the birth month or if the current month is the birth month and the current month day is // before the birth month day, the last year isn't fully over if (otherDate.getMonth() < this.getMonth() || (otherDate.getMonth() == this.getMonth() && otherDate.getDate() < this.getDate())) --years; return years; } }) if(!window.console) //install a fake console to make sure unprotected console.log invocations don't crash IE window.console = {}; ['assert','clear','count','debug','dir','dirxml','error','exception','group','groupCollapsed','groupEnd' ,'info','log','time','timeEnd','timeStamp','profile','profileEnd','trace','warn' ].each(function(node) { if(!window.console[node]) window.console[node] = function() {} }); if(!window.console.table) window.console.table=function(tab) { console.log(tab); } /** @short get the index of the first object within the array which contains the specified value (or one of the specified values if an array is passed) @param value can be a single value or array of values. if an array was specified, a single matching value within the specified array is enough for an object to match. */ Array.prototype.indexByProperty = function(key, value) { var arrlen = this.length; if (value instanceof Array) { for(var idx=0; idx<arrlen; idx++) { if (value.contains( this[idx][key] )) return idx; } } else { for(var idx=0; idx<arrlen; idx++) { if(this[idx][key] === value) return idx; } } return -1; } /** @short get the first object within the array which contains the specified value (or one of the specified values if an array is passed) @param value can be a single value or array of values. if an array was specified, a single matching value within the specified array is enough for an object to match. */ Array.prototype.getByProperty = function(key, value) { var idx = this.indexByProperty(key,value); return idx >= 0 ? this[idx] : null; } /** @short return an array with all the objects in which the specified property contains the value (or one of the values in case an array was given as value) @param value can be a single value, array of values or a function. If an array was specified, a single matching value within the specified array is enough for an object to match. If an function was specified .... */ Array.prototype.filterByProperty = function(key, value) { var arrlen = this.length; var matches = []; if (value instanceof Array) { for(var idx=0; idx<arrlen; idx++) { if (value.contains( this[idx][key] )) matches.push(this[idx]); } } else if (typeof value == "function") { return this.filter(function(obj, idx) { return value(obj[key], idx, obj); }); } else { for(var idx=0; idx<arrlen; idx++) { if(this[idx][key] === value) matches.push(this[idx]); } } return matches; } /* Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing. http://davidwalsh.name/function-debounce */ Function.implement({ debounce: function(wait, immediate) { var timeout, func = this; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } }); $wh.Event = new Class( { bubbles: true , cancelable: true , defaultPrevented: false , target:null , type:null , initEvent:function(type, bubbles, cancelable) { this.type = type; this.bubbles = bubbles; this.cancelable = cancelable; } , stopPropagation: function() { this.bubbles=false; } , preventDefault:function() { this.defaultPrevented=true; } , stop:function() { this.preventDefault(); this.stopPropagation(); } }); // http://www.w3.org/TR/ElementTraversal/ wrappers with IE8&9 support $wh.getFirstElementChild = function(node) { if("firstElementChild" in node) return node.firstElementChild; var child = node.firstChild; while(child && child.nodeType != 1) child = child.nextSibling; return child; } $wh.getLastElementChild = function(node) //IE8&9 don't support this property natively { if("lastElementChild" in node) return node.lastElementChild; var child = node.lastChild; while(child && child.nodeType != 1) child = child.previousSibling; return child; } $wh.getPreviousElementSibling = function(node) { if("previousElementSibling" in node) return node.previousElementSibling; while(node && node.nodeType != 1) node = node.previousSibling; return node; } $wh.getNextElementSibling = function(node) { if("nextElementSibling" in node) return node.nextElementSibling; while(node && node.nodeType != 1) node = node.nextSibling; return node; } $wh.getChildElementCount = function(node) { if("childElementCount" in node) return node.childElementCount; var count=0; var child = node.firstChild; while(child) { if(child.nodeType == 1) ++count; child = child.nextSibling; } return count; } $wh.getActiveElement = function(doc) { try { //activeElement can reportedly throw on IE9 and _definately_ on IE11 return doc.id(doc.activeElement); } catch(e) { return null; } } function getTrackNameForElement(el) { if(el.getAttribute) { //attempt data-whtrack-name && id first var name = el.getAttribute('data-whtrack-name'); if(name) return name; name = el.getAttribute('id'); if(name) return name; //if we have a name, can we combine with a form? name = el.getAttribute('name'); if(name && el.getParent) { var form = el.getParent('form'); if(form) return getTrackNameForElement(form) + ':' + name; } } return el.nodeName.toLowerCase(); } var trackcache = [], trackforwardto=null; $wh.track = function(category, action, label, options) { //wrapper for callbacks function once(fptr) { var invoked=false; return function() { if(invoked) return; invoked=true; fptr(); } } if(typeof label == "number") label = ''+label; else if(typeof label != "string") { if(label.ownerDocument) //it's in a doc, probably a html element; { //the node may override us category = label.getAttribute("data-wh-track-category") || category; action = label.getAttribute("data-wh-track-action") || action; label = label.getAttribute("data-wh-track-label") || getTrackNameForElement(label); } else { console.error("Unrecognized label " , label); label = 'unrecognized label'; } } if(!category || !action) throw new Error("Category & action are required fields"); if(!label) label=''; if(options && options.callback) { options.callback = once(options.callback); options.callback.delay(200); //ensure we invoke it after at most 200ms } if(trackforwardto) { trackforwardto(category, action, label, options); } else { var callback = options ? options.callback : null; if(callback) options.callback = null; trackcache.push([category,action,label,options]); //ADDME: nicer would be to set an event to handle callbacks, and execute them once a tracker has gotten the chance to grab the trackcache.. if(callback) callback(); } } $wh.setDefaultTracker = function(newtracker) { Array.each(trackcache, function(el) { newtracker.apply(null,el) }); trackcache = []; trackforwardto = newtracker; } })(); //end function scope guard require ('frameworks.mootools.core'); /*! LOAD: frameworks.mootools.core AFTER: base.js !*/ (function($) { //mootools wrapper var ispreview = false; $wh.BrowserFeatures = null; $wh.assumecookiepermission = true; $wh.__transform_venderprefix = ''; $wh.__transform_property = ''; JSON.secure = true; //secure the mootools 1.4 JSON implementation. 1.5 doesn't need this //enable onmessage Element.NativeEvents.message = 2; Element.Events.message = { base: 'message', condition: function(event) { //if(event.type == 'message') { if(!event.$message_extended) { event.data = event.event.data; event.source = event.event.source; event.origin = event.event.origin; event.$message_extended = true; } return true; } }; // MooTools 1.4 doesn't register hashchange as native event if (!Element.NativeEvents.hashchange) Element.NativeEvents.hashchange = 1; var whconfigel=document.querySelector('script#wh-config'); if(whconfigel) { $wh.config=Object.merge($wh.config||{}, JSON.parse(whconfigel.textContent)); // Make sure we have obj/site as some sort of object, to prevent crashes on naive 'if ($wh.config.obj.x)' tests' if(!$wh.config.obj) $wh.config.obj={}; if(!$wh.config.site) $wh.config.site={}; } else if(!$wh.config) //no $wh.config is no <webdesign>. don't bother with obj & site, but designfiles still rely on $wh.config itself { $wh.config={}; } //polyfill CustomEvent try //IE11 does not ship with CustomEvent { new window.CustomEvent("test"); } catch(e) { var eventconstructor = function(event, params) { var evt; params = params || { bubbles: false, cancelable: false, detail: undefined }; evt = document.createEvent("CustomEvent"); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; }; eventconstructor.prototype = window.Event.prototype; window.CustomEvent = eventconstructor; } function getAndroidVersion(ua) { var ua = ua || navigator.userAgent; var match = ua.match(/Android\s([0-9\.]*)/); return match ? match[1] : false; }; function initializeWHBaseBrowser() { $wh.BrowserFeatures = { trueopacity: false , pointerevents: false , animations: false , android_positionfixedbroken: Browser.platform == "android" && parseInt(getAndroidVersion(),10) <= 3 //pre-4 is apparently buggy with position:fixed & translations }; if(typeof Browser.platform == "undefined") //mootools 1.4 { // Quick fix for MooTools not recognizing IE11, probably fixed in MooTools 1.5 if (Browser.name === "unknown") { if (navigator.userAgent.toLowerCase().indexOf('trident/7.0') > -1) { Browser.name = 'ie'; Browser.version = '11'; Browser[Browser.name] = true; Browser[Browser.name + parseInt(Browser.version, 10)] = true; } } Browser.platform = Browser.Platform.name; } if(typeof Browser.Platform == "undefined") //moo 1.5 { if(! (Browser.name == "ie" && parseInt(Browser.version) >= 11) ) //do not set 'Browser.ie' on IE11, as mootools 1.5 doesn't do that either, not even in compat mode Browser[Browser.name] = true; Browser[Browser.name + parseInt(Browser.version, 10)] = true; Browser.Platform = {}; Browser.Platform[Browser.platform] = true; } var element = document.createElement('x'); element.style.cssText = 'pointer-events:auto;'; if(element.style.pointerEvents === 'auto') $wh.BrowserFeatures.pointerevents = true; $wh.BrowserFeatures.trueopacity = typeof element.style.opacity !== "undefined"; // Parse debug settings var debugstr=''; var urldebugvar = location.href.match(/[\?&#]wh-debug=([^&#?]*)/); //extract wh-debug var if(urldebugvar) debugstr = decodeURIComponent(urldebugvar[1]).split(',').join('.'); else debugstr = Cookie.read("wh-debug"); var previewvar = location.href.match(/[\?&#]whs-clock=([^&#?]*)/); if(previewvar) { document.documentElement.addClass("wh-preview"); ispreview=true; } if(debugstr) { Array.each(debugstr.split('.'), function(tok) { $wh.debug[tok]=true; }); } Object.each($wh.debug, function(v,k) { document.documentElement.addClass("wh-debug-" + k) }); var transforms = { computed: ['transformProperty', 'transform', 'WebkitTransform', 'MozTransform', 'msTransform'], prefix: ['', '', '-webkit-', '-moz-', '-ms-'] }; var testEl = new Element("div"); transforms.computed.some(function(el, index) { var test = el in testEl.style; if (test) { $wh.__transform_venderprefix = transforms.prefix[index]; $wh.__transform_property = transforms.computed[index]; } return test; }); $wh.BrowserFeatures.animations = "webkitAnimation" in testEl.style || "animation" in testEl.style; // Initialization code to fix some usual HTML5 issues // In IE 7/8, unknown elements are not recognized (i.e. cannot be styled or properly added to the DOM), unless they've been created before (they don't have to be added to the DOM in order to be recognized). if(Browser.ie && Browser.version<9) { var tags = ["abbr","article","aside","audio","canvas","datalist","details","figure","footer","header","hgroup","main","mark","menu","meter","nav","output","progress","section","template","time","video"]; for (var i=0; i<tags.length; ++i) document.createElement(tags[i]); } } //workaround for first rect( parameter not animating Fx.CSS.Parsers.Rect={ parse: function(value){ if (value.substr(0,5)=='rect(') return parseFloat(value.substr(5)); return false; }, compute: Fx.compute, serve: function(value){ return 'rect(' + value + 'px'; } }; Element.implement( { getSelfOrParent: function(selector) { return this.match(selector) ? this : this.getParent(selector); } }); // Internet Explorer still uses an old prefixed name for the node.matches() method // (and just to be nice whe'll also support other old browser.. for now.) // http://caniuse.com/#feat=matchesselector if (!Element.prototype.matches) { var ep = Element.prototype; if (ep.webkitMatchesSelector) // Chrome <34, SF<7.1, iOS<8 ep.matches = ep.webkitMatchesSelector; if (ep.msMatchesSelector) // IE9/10/11 & Edge ep.matches = ep.msMatchesSelector; if (ep.mozMatchesSelector) // FF<34 ep.matches = ep.mozMatchesSelector; } // http://www.nixtu.info/2013/06/how-to-upload-canvas-data-to-server.html $wh.dataURItoBlob = function(dataURI) { // convert base64 to raw binary data held in a string // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this var byteString = atob(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length); var dw = new DataView(ab); for(var i = 0; i < byteString.length; i++) { dw.setUint8(i, byteString.charCodeAt(i)); } // write the ArrayBuffer to a blob, and you're done return new Blob([ ab ], { type: mimeString }); } // canvas.toBlob polyfill if (window.HTMLCanvasElement && !window.HTMLCanvasElement.prototype.toBlob) { window.HTMLCanvasElement.prototype.toBlob = function(callback, type, quality) { callback($wh.dataURItoBlob(this.toDataURL(type, quality))); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////// // // - Auto-redirecting properties to prefixed versions if neccesary // - opacity workaround in which totally transparent elements cannot be clicked/touched // var old_getstyle1 = Element.prototype.getStyle; var old_setstyle1 = Element.prototype.setStyle; Element.implement( { getStyle: function(property) { //console.log('getstyle', retval, Fx.CSS.prototype.parse(retval)); // rename transform properties to include their prefix if needed for the current browser if(["transform","transform-origin"].contains(property)) { if ($wh.__transform_venderprefix != "") return old_getstyle1.apply(this, [$wh.__transform_venderprefix + property]); else return old_getstyle1.apply(this,arguments); } if(property=='-wh-opacity' || property=='wh-opacity') { // FIXME: implement this with pointer-events for iOS? (for better performance) var opacity = old_getstyle1.apply(this,['opacity']); var display = old_getstyle1.apply(this,['display']); return display == "none" ? 0 : opacity; } return old_getstyle1.apply(this,arguments); } , setStyle: function(property, value) { // rename transform properties to include their prefix if needed for the current browser if(["transform","transform-origin"].contains(property)) { if ($wh.__transform_venderprefix != "") return old_setstyle1.apply(this, [$wh.__transform_venderprefix + property, value]); else return old_setstyle1.apply(this,arguments); } if(property=='-wh-opacity' || property=='wh-opacity' ) { if(parseFloat(value)<=0) old_setstyle1.apply(this, ["display","none"]); else old_setstyle1.apply(this, ["display","block"]); return old_setstyle1.apply(this,["opacity",value]); } // NOTE: the wh.animations.timeline handle these properties itself, // so it won't cause the transform property to be updated for each seperate // wh property. if (["wh-left","wh-top","wh-rotate","wh-scale"].contains(property)) { if (!this._wh_pos) // keep these vars in sync with wh.animations.timeline this._wh_pos = { changed: false, left: null, top: null, scale: 1, rotate: 0 }; var wh_pos = this._wh_pos; // NOTE: no need to set changed, because we know whe directly handle the change switch(property) { case "wh-left": wh_pos.left = value; break; case "wh-top": wh_pos.top = value; break; case "wh-scale": wh_pos.scale = value; break; case "wh-rotate": wh_pos.rotate = value; break; } if ($wh.__transform_property == "") { if (wh_pos.left) this.style.left = this._wh_pos.left; if (wh_pos.top) this.style.top = this._wh_pos.top; } else { var transformstr = ""; if (Browser.Platform.ios == true) //(use3dtransforms) transformstr += " translate3D("+(wh_pos.left ? wh_pos.left : 0)+"px,"+(wh_pos.top ? wh_pos.top : 0)+"px,0)"; else// if (usetransforms) transformstr += " translate("+(wh_pos.left ? wh_pos.left : 0)+"px,"+(wh_pos.top ? wh_pos.top : 0)+"px)"; if (wh_pos.rotate != 0) transformstr += " rotate("+wh_pos.rotate+"deg)"; if (wh_pos.scale != 1) transformstr += " scale("+wh_pos.scale.toFixed(5)+")"; // NOTE: we cannot pass the transform through Mootool's setStyles this.style[$wh.__transform_property] = transformstr; //console.log(this, $wh.__transform_property, transformstr); } return; } return old_setstyle1.apply(this,arguments); } }); // NOTE: Safari currently doesn't allow input in <input> elements while in fullscreen mode // keyboard events however still work, although you need to set focus again // ADDME: also help with fullscreenchange events? if (!window.requestFullScreen) { Element.implement( { requestFullScreen: Element.prototype.webkitRequestFullScreen || Element.prototype.mozRequestFullScreen || Element.prototype.msRequestFullscreen || function() {} }); /* { requestFullScreen: function() { if (this.webkitRequestFullScreen) { this.webkitRequestFullscreen();//this.ALLOW_KEYBOARD_INPUT); console.log("okliedoklie"); } else if (this.mozRequestFullScreen) this.mozRequestFullScreen(); else this.msRequestFullScreen(); } }); */ // cancelFullScreen is implemented only on document (not documented in MDN) } if (!document.exitFullscreen) document.exitFullScreen = document.webkitCancelFullScreen || document.mozCancelFullScreen || document.msCancelFullScreen || document.exitFullscreen || function() {} Element.implement( { toggleFullScreen: function() { var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement; // if we aren't in fullscreen or we want to toggle another element to go fullscreen // request full screen on that element if (fullscreenElement != this) this.requestFullScreen(); else document.exitFullScreen(); } }); $wh.getIframeDocument = function(iframe) { // if we try to read contentWindow before the iframe has been inserted into a document, // IE will throw an 'Unspecified error' if (typeof iframe.contentWindow == 'unknown') return null; // contentDocument is supported by NS6, Firefox, Opera, IE8 if (iframe.contentDocument) return iframe.contentDocument; // FF3/SF3.2.1/OP9.64/CHR1 will properly return null (typeof=='object') if not initialized if (iframe.contentWindow == null) return null; //if (iframe.document) // For IE5 // return iframe.document; // if we have a contentwindow we can safely ask for it's document // (IE5.5 and IE6) return iframe.contentWindow.document; }; //we cannot use location.hash safely, as the url http://b-lex.nl/#motoren%25abc will return 'motoren%abc' on FF, and 'motoren%25abc' on Chrome $wh.getCurrentHash = function() { var hashidx = location.href.indexOf('#'); if(hashidx==-1) return ''; return decodeURIComponent(location.href.substr(hashidx+1)); } /*globals HTMLSelectElement*/ /** * @requires polyfill: Array.from {@link https://gist.github.com/4212262} * @requires polyfill: Array.prototype.filter {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter} * @requires polyfill: Object.defineProperty {@link https://github.com/eligrey/Xccessors} * @license MIT, GPL, do whatever you want */ if(!new Element("select").selectedOptions) { function PseudoHTMLCollection(arr) { var i, arrl; for (i = 0, arrl = arr.length; i < arrl; i++) this[i] = arr[i]; try { Object.defineProperty(this, 'length', { get: function () { return arr.length; } }); } catch (e) { // IE does not support accessors on non-DOM objects, so we can't handle dynamic (array-like index) addition to the collection this.length = arr.length; } if (Object.freeze) { // Not present in IE, so don't rely on security aspects Object.freeze(this); } } PseudoHTMLCollection.prototype = { constructor: PseudoHTMLCollection, item: function (i) { return this[i] !== undefined && this[i] !== null ? this[i] : null; }, namedItem: function (name) { var i, thisl; for (i = 0, thisl = this.length; i < thisl; i++) { if (this[i].id === name || this[i].name === name) { return this[i]; } } return null; } }; Object.defineProperty(HTMLSelectElement.prototype, 'selectedOptions', {get: function () { return new PseudoHTMLCollection(Array.from(this.options).filter(function (option) { return option.selected; })); }}); } /* original from http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating Fixed by B-Lex Native support in: - Chrome 17 - IE 10 - FF 4 (incomplete, -moz) - FF 11 (-moz) - Safari unknown when support (supported in Webkit nightlies) - Opera 15 Without prefix in - IE 10 - FF 23 - CHR 24 - SF 6.1 / iOS 7 - OP 15 */ var reqanim_prefix; var reqanim_currentframe = 0; var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { if (typeof( window[vendors[x]+'RequestAnimationFrame'] ) != "function") continue; reqanim_prefix = vendors[x]; // Firefox 4+ has supported for mozRequestAnimationFrame, but didn't return requestId before Firefox 11 window.requestAnimationFrame = function(callback) // 2nd argument is only supported by Webkit(SF/CHR) { var requestId = window[reqanim_prefix+'RequestAnimationFrame'](callback); if (typeof requestId == "undefined") // FIX for FF4 up to FF10 { reqanim_currentframe++; requestId = reqanim_currentframe; } return requestId; } window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) { var anim_fallback_wait = 1000/60 // if the browser doesn't support animationframes, use this as wait window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 1000/60 - (currTime - lastTime)); //100/60 = frame var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; $(window).addEvent("load", function() { if ($wh.assumecookiepermission) $(document).fireEvent("cookiespermitted"); }); /// Safari seems to immediately repeat keydown events when pressing Esc, so we'll cancel subsequent keydown events /// WebKit bug report: https://bugs.webkit.org/show_bug.cgi?id=78206 if (Browser.safari) { (function() { // Should keydown events be cancelled? (We'll allow repeating events after repeatTimeout) var startCancelling = true; // Are keydown events being cancelled? var cancelEvents = false; // Keyboard repeat timeout var repeatTimeout = 500; window.addEventListener("keydown", function(event) { // Check if esc is pressed without modifier keys if (event.keyCode == 27 && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) { if (cancelEvents) { // Cancel this event event.stopPropagation(); event.preventDefault(); } else if (startCancelling) { // Start cancelling events startCancelling = false; cancelEvents = true; // Stop cancelling events after repeatTimeout setTimeout(function() { cancelEvents = false; }, repeatTimeout); } } }, true); window.addEventListener("keyup", function(event) { // Check if esc is pressed without modifier keys if (event.keyCode == 27) { // Stop cancelling events; they may be cancelled upon next esc keydown startCancelling = true; cancelEvents = false; } }, true); })(); } //Fire a layout change event $wh.fireLayoutChangeEvent = function(node, direction) { node=$(node); // FIXME: is there still code listening to these legacy classes?? if($wh.legacyclasses !== false) { node.getParents('.-wh-layoutlistener').fireEvent("-wh-layoutchange", { target:node, direction:'up' }); if(node.hasClass('-wh-layoutlistener')) node.fireEvent("-wh-layoutchange", { target:node, direction:'self' }); node.getElements(".-wh-layoutlistener").fireEvent("-wh-layoutchange", { target:node, direction:'down' }); } var up = !direction || direction == "up"; var down = !direction || direction == "down"; // console.log( up ? "UP":"", down ? "DOWN":"", node); //console.trace(); //console.log("LayoutChange " + (up?"UP":"") + " " + (down?"DOWN":"") + " from", node); if (up) node.getParents(".wh-layoutlistener").fireEvent("wh-layoutchange", { target: node, direction: "up" }); if(node.hasClass("wh-layoutlistener")) node.fireEvent("wh-layoutchange", { target: node, direction:'self' }); if (down) node.getElements(".wh-layoutlistener").fireEvent("wh-layoutchange", { target: node, direction: "down" }); window.fireEvent("wh-layoutchange", { target: node, direction: "down" }) } $wh.getJSONAttribute = function(node, attrname) { var data = node.getAttribute(attrname) || 'null'; if (data.substr(0,1) == '@') { // This is a reference to a variable in window. // It is meant for reuse of settings (for example for RTE or slideshow settings) var path = data.substr(1).split('.'); path.unshift(window); var curr = window; for (var i = 1; i < path.length; ++i) { var pathelt = path[i]; var sub = curr[pathelt]; if (typeof sub == "undefined") throw Error("Cannot find variable '" + pathelt + "' in '" + path.slice(0,i).join(',') + "' when looking up '" + data + "'"); curr = sub; } data = curr; } else data = JSON.parse(data); return data; } $wh.getJSAssetPath = function(scriptname) { var url; var script = $("wh-designfiles-combined-js"); if (script) url = script.getAttribute("src"); if (!url) { var playerscript = $$('script[src*="/' + scriptname + '"]').pick(); if (playerscript) url = playerscript.getAttribute("src"); } if(url) { var urlparts = url.split('?')[0].split('/'); return urlparts.slice(0,urlparts.length-1).join('/')+'/'; } return null; } function generateForm(action, values, method) { var form = new Element("form", { action: action, method: method || "POST", charset: "utf-8" }); if(values instanceof Array) { Array.each(values, function(item) { form.adopt(new Element("input", { type: "hidden", name: item.name, value: item.value })); }); } else Object.each(values, function(value, name) { form.adopt(new Element("input", { type: "hidden", name: name, value: value })); }); return form; } $wh.submitForm = function(action, values, method) { var form = generateForm(action, values, method); $(document.body).adopt(form); form.submit(); } /** get elements matching a selector, matching them from the documentNode (getElement only applies to subelements. use this if you want '#xx span' to match nodes if you start the search at #xx) @param node: if null, match from top. if Element, iterate element and children. if rangestart/rangelimit are set, walk through that range, excluding rangelimit */ $wh.getTopMatchedElements = function(node, selector) { function getSelfAndElements(node,selector) { // NOTE: we convert the static nodelist to a MooTools element list var retval = $$( node.querySelectorAll(selector) ); if (node.matches(selector)) retval.include( node ); return retval; } var elements=[]; if(!node) { // if no start/root node is specified, get all elements within the document which match the selector elements = document.querySelectorAll(selector); } else if($wh.isHTMLElement(node)) { elements = getSelfAndElements($(node), selector); } else if(node.rangestart) { for(var testnode = node.rangestart;testnode&&testnode!=node.rangelimit;testnode=testnode.nextSibling) if($wh.isHTMLElement(testnode)) elements.append( getSelfAndElements($(testnode), selector)); } else if(node.firstChild) //document fragment { for(node = node.firstChild;node;node=node.nextSibling) if(node.getElements) elements.append(getSelfAndElements(node)); } return elements; } //Hook fireEvent so we can integrate our 'wh-after-domready ' ' var saveFireEvent = window.fireEvent; window.fireEvent = function(type, args, delay) { saveFireEvent.apply(this, [type, args, delay]); if(type=="domready" || type=="load") saveFireEvent.apply(this, ["wh-after-" + type, args, delay]); return this; } /// Chain a function after the DOMEvent constructor var domextends = null; $wh.extendDOMEventConstructor = function(func) { if (!domextends) { domextends = []; // Replace the DOMEvent type by our own implementation - copy prototype & keys over from the old DOMEvent var oldDOMEvent = DOMEvent; DOMEvent = new Type('DOMEvent', function() { oldDOMEvent.apply(this, arguments); for (var i = 0; i < domextends.length; ++i) domextends[i].apply(this, arguments); }); DOMEvent.prototype = oldDOMEvent.prototype; Object.keys(oldDOMEvent).each(function(key, value){ DOMEvent[key] = oldDOMEvent[key] }); } domextends.push(func); } $wh.getDocumentLanguage = function() { var htmlnode = document.documentElement; return htmlnode ? htmlnode.getAttribute('lang') || htmlnode.getAttribute('xml:lang') || 'en' : 'en'; } //overhead calculations $wh.getHorizontalOverhead = function(node) { if (typeof window["getComputedStyle"] == "function") { var style = getComputedStyle(node, null); return (style.getPropertyValue("padding-left").toInt() || 0) + (style.getPropertyValue("padding-right").toInt() || 0) + (style.getPropertyValue("border-left-width").toInt() || 0) + (style.getPropertyValue("border-right-width").toInt() || 0); } else if (node["currentStyle"]) { var style = node.currentStyle; return (style.paddingLeft.toInt() || 0) + (style.paddingRight.toInt() || 0) + (style.borderLeftWidth.toInt() || 0) + (style.borderRightWidth.toInt() || 0); } return 0; } $wh.getVerticalOverhead = function(node) { if (typeof window["getComputedStyle"] == "function") { var style = getComputedStyle(node, null); return (style.getPropertyValue("padding-top").toInt() || 0) + (style.getPropertyValue("padding-bottom").toInt() || 0) + (style.getPropertyValue("border-top-width").toInt() || 0) + (style.getPropertyValue("border-bottom-width").toInt() || 0); } else if (node["currentStyle"]) { var style = node.currentStyle; return (style.paddingTop.toInt() || 0) + (style.paddingBottom.toInt() || 0) + (style.borderTopWidth.toInt() || 0) + (style.borderBottomWidth.toInt() || 0); } return 0; } // get the information needed to properly stretch an image // (to fully cover (fit or fill) the available space (outwidth/outheight) with the original size (inwidth/inheight) while keeping the aspect ratio) $wh.getCoverCoordinates = function(inwidth, inheight, outwidth, outheight, fit) { var infx = !(outwidth > 0); var infy = !(outheight > 0); var dx = infx ? 0 : inwidth / outwidth; var dy = infy ? 0 : inheight / outheight; var scale; if(infx) scale=dy; else if(infy) scale=dx; else if(fit) scale = Math.max(dx,dy); else scale = Math.min(dx,dy); return { width: inwidth/scale , height: inheight/scale , top: (outheight - (inheight/scale))/2 , left: (outwidth - (inwidth/scale))/2 }; } $wh.dispatchDomEvent=function(element, eventtype, options) { if(!options) options={}; if(!("cancelable" in options)) //you generally need to think about these two... console.error("You should set 'cancelable' to true or false in a $wh.dispatchDomEvent call"); if(!("bubbles" in options)) console.error("You should set 'bubbles' to true or false in a $wh.dispatchDomEvent call"); //Firefox Bugzilla #329509 - Do not prevent event dispatching even if there is no prescontext or (form) element is disabled //we'll just normalize around Firefox' behaviour - IE might do it too? if(element.disabled) return true; var evt = element.ownerDocument.createEvent(eventtype == "click" ? "MouseEvents" : "HTMLEvents"); evt.initEvent(eventtype, options.bubbles, options.cancelable); if(options.detail) evt.detail = options.detail; if(eventtype=='click' && window.IScroll) evt._constructed = true; //ensure IScroll doesn't blindly cancel our synthetic clicks var result = element.dispatchEvent(evt); return result; } //manually fire 'onchange' events. needed for event simulation and some IE<=8 modernizations $wh.fireHTMLEvent=function(element, type) { //http://stackoverflow.com/questions/2856513/trigger-onchange-event-manually return $wh.dispatchDomEvent(element, type, { bubbles: ["input","change","click"].contains(type), cancelable: true}); } $wh.setTextWithLinefeeds = function(node, message) { Array.each(message.split("\n"), function(line,idx) { if(idx==0) node.set("text",line); else node.adopt(new Element("br")).appendText(line); }); } //A DOM4 customevent. http://www.w3.org/TR/dom/#interface-customevent $wh.CustomEvent = new Class( { Extends: $wh.Event , initialize:function(type, eventInitDict) { this.bubbles = eventInitDict && eventInitDict.bubbles; this.cancelable = eventInitDict && eventInitDict.cancelable; this.detail = (eventInitDict ? eventInitDict.detail : null) || null; this.type = type; } }); $wh.dispatchEvent = function(node, event) { if(!node) throw new Error("null node passed to dispatchEvent"); event.target = node; //one day, we should match this algorithm exactly: http://www.w3.org/TR/dom/#dispatching-events var mywindow = node.ownerDocument.defaultView; var nodetree = [node]; while(node.parentNode) { node = node.parentNode; nodetree.unshift(node); } if(mywindow) nodetree.unshift(mywindow); //ADDME capture phase? but only if the event was declared as native though - addEvent cannot officially capture such events anyway. //bubble! for(var treepos=nodetree.length-1;treepos >= 0;--treepos) { node = $(nodetree[treepos]); if(!node.fireEvent) continue; node.fireEvent(event.type, event); if(!event.bubbles) //stop looping once bubble is broken break; } return !event.defaultPrevented; } /** Change the value of a form element, and fire the correct events as if it were a user change @param element Element to change @param newvalue New value @param norecursecheck Optional. if true, disable recursive change checking */ $wh.changeValue = function(element, newvalue, norecursecheck) { if(element instanceof Array || element instanceof Elements) { Array.each(element, function(node) { $wh.changeValue(node, newvalue) }); return; } element=$(element); if(element.nodeName=='INPUT' && ['radio','checkbox'].contains(element.type)) { if(!!element.checked == !!newvalue) return; element.checked=!!newvalue; } else { if(element.value == newvalue) return; element.value = newvalue; } if(!norecursecheck && $wh.changeValue.changelist.contains(element)) { console.error("Changing element ",element,"to",newvalue," while its onchange is firing"); throw new Error("$wh.changeValue detected recursion on element"); } try { if(!norecursecheck) $wh.changeValue.changelist.push(element); $wh.fireHTMLEvent(element,"input"); $wh.fireHTMLEvent(element,"change"); } finally { if(!norecursecheck) $wh.changeValue.changelist.erase(element); } } $wh.changeValue.changelist = []; /// Always set the cancelBubble flag, so we can detect that stopPropagation was called var stopPropagation = DOMEvent.prototype.stopPropagation; DOMEvent.prototype.stopPropagation = function() { stopPropagation.call(this); if (this.event.stopPropagation) this.event.cancelBubble = true; return this; }; initializeWHBaseBrowser(); function runCompat() { //Firefox redisables buttons that were disabled at refresh, even if they're not disabled in the HTML if (Browser.name == "firefox") $$('button:disabled').set('disabled',null); } $wh.isPreview = function() { return ispreview; } $wh.navigateTo = function(newurl,options) { var debugtype = options ? options.debugtype : null; if(!debugtype && $wh.debug.rdr) debugtype = 'rdr'; if(debugtype) { //ADDME check if we're still in rendering stage, ie when document.write would have no overwriting effect. or can we force overwrite using document open/close ? document.write('<body>[' + debugtype.encodeAsHTML() + '] Must redirect to: <a href="' + newurl.encodeAsValue() + '" id="redirectto">' + newurl.encodeAsHTML() + '</a></body>'); return; } location.href = newurl; } $wh.executeSubmitInstruction = function(instr, options) { if(!instr) throw Error("Unknown instruction received"); options = options || {}; if (!options.nobusylock && instr.type != "postmessage") { if ($wh.createBusyLock) $wh.createBusyLock('reload'); } if (options.iframe) { switch (instr.type) { case "redirect": { options.iframe.src = instr.url; } break; case "form": { // FIXME: Clear iframe if document is not cross-domain accessible var idoc = options.iframe.document || options.iframe.contentDocument || options.iframe.contentWindow.document; var form = generateForm(instr.form.action, instr.form.vars, instr.method); var adopted_form = idoc.adoptNode(form); idoc.body.appendChild(adopted_form); adopted_form.submit(); } break; default: { throw Error("Unknown submit instruction '" + instr.type + "' for iframe received"); } } return; } switch (instr.type) { case "redirect": { $wh.navigateTo(instr.url, { debugtype: options.debugtype }); } break; case "form": { $wh.submitForm(instr.form.action, instr.form.vars, instr.form.method); } break; case "refresh": case "reload": { window.location.reload(); } break; case "postmessage": { parent.postMessage(instr.message, "*"); } break; case "close": { window.close(); } default: { throw Error("Unknown submit instruction '" + instr.type + "' received"); } } } function isInDocument(node) { while (node) { if (node.nodeType == 9) return true; node = node.parentNode; } } /** Signal that a node and its subnodes are about to be removed from the DOM @param node Node that has just been removed */ $wh.fireRemovingFromDOMEvent = function(node) { node = $(node); if (!isInDocument(node)) return; if (node.hasClass("wh-domevents")) node.fireEvent("wh-dom-removing"); node.getElements(".wh-domevents").fireEvent("wh-dom-removing"); } /** Signal that a node and its subnodes have just been added to the DOM @param node Node that has just been added */ $wh.fireAddedToDOMEvent = function(node) { node = $(node); if (!isInDocument(node)) return; if (node.hasClass("wh-domevents")) node.fireEvent("wh-dom-added"); node.getElements(".wh-domevents").fireEvent("wh-dom-added"); } /** Enable saving the scroll state over DOM-removals. Requires correct calls to $wh.fireRemovingFromDOMEvent and $wh.fireAddedToDOMEvent @param node Scrolled node */ $wh.autoSaveScrollState = function(node) { node.addClass("wh-domevents"); node.addEvent("wh-dom-removing", function(e) { node.store("wh-scrollstate", { scrollTop: node.scrollTop, scrollLeft: node.scrollLeft }); }); node.addEvent("wh-dom-added", function(e) { var domstate = node.retrieve("wh-scrollstate"); if (domstate) { node.scrollTop = domstate.scrollTop; node.scrollLeft = domstate.scrollLeft; node.store("wh-scrollstate", null); } }); } $wh.renderConsoleLog = function(logentries) { Array.each(logentries, function(logentry) { console.log(logentry.text + " (" + logentry.caller + ")"); }); } window.addEvent("domready", runCompat); })(document.id); //end mootools wrapper
mit
vlad20012/pushall-api-java
src/main/java/ru/pushall/api/request/NotificationBuilder.java
2868
package ru.pushall.api.request; import ru.pushall.api.response.BroadcastResponse; import ru.pushall.api.response.SelfResponse; import ru.pushall.api.response.UnicastResponse; import java.util.Objects; public class NotificationBuilder<R> { private final RequestType type; private final long id; private final String key; private final long unicastUserId; private String title; private String text; private String icon; private String url; private NotificationHideType hidden = NotificationHideType.NOT_HIDE; private NotificationPriority priority = NotificationPriority.DEFAULT; private int ttl = Integer.MIN_VALUE; private boolean background; private NotificationBuilder(RequestType type, long id, String key, long unicastUserId) { this.type = type; this.id = id; this.key = key; this.unicastUserId = unicastUserId; } public NotificationBuilder<R> setTitle(String title) { this.title = title; return this; } public NotificationBuilder<R> setText(String text) { this.text = text; return this; } public NotificationBuilder<R> setIcon(String icon) { this.icon = icon; return this; } public NotificationBuilder<R> setUrl(String url) { this.url = url; return this; } public NotificationBuilder<R> setHidden(NotificationHideType hidden) { this.hidden = Objects.requireNonNull(hidden); return this; } public NotificationBuilder<R> setPriority(NotificationPriority priority) { this.priority = Objects.requireNonNull(priority); return this; } public NotificationBuilder<R> setTtl(int ttl) { this.ttl = ttl; return this; } public NotificationBuilder<R> setBackground(boolean background) { this.background = background; return this; } @SuppressWarnings("unchecked") public NotificationRequest<R> build() { if(type == RequestType.BROADCAST) return (NotificationRequest<R>) new BroadcastRequest(id, key, title, text, icon, url, hidden, priority, ttl, background); if(type == RequestType.SELF) return (NotificationRequest<R>) new SelfRequest(id, key, title, text, icon, url, hidden, priority, ttl, background); if(type == RequestType.UNICAST) return (NotificationRequest<R>) new UnicastRequest(id, key, title, text, icon, url, hidden, priority, ttl, background, unicastUserId); throw new UnsupportedOperationException(); } public static NotificationBuilder<SelfResponse> forSelf(long selfId, String key) { return new NotificationBuilder<>(RequestType.SELF, selfId, key, 0); } public static NotificationBuilder<BroadcastResponse> forBroadcast(long channelId, String key) { return new NotificationBuilder<>(RequestType.BROADCAST, channelId, key, 0); } public static NotificationBuilder<UnicastResponse> forUnicast(long channelId, String key, long unicastUserId) { return new NotificationBuilder<>(RequestType.UNICAST, channelId, key, unicastUserId); } }
mit
zsgithub3895/common.code
src/com/zs/leetcode/stack/PostorderTraversal.java
1201
package com.zs.leetcode.stack; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Stack; public class PostorderTraversal { public static void main(String[] args) { int[] array = { 12, 8, 18 }; TreeNode root = new TreeNode(array[0]);// 创建二叉树 for (int i = 1; i < array.length; i++) { root.insert(root, array[i]);// 向二叉树中插入数据 } System.out.println(root.val); System.out.println(root.left.val); System.out.println(root.right.val); root = null; System.out.println(postorderTraversal(root)); } public static List<Integer> postorderTraversal(TreeNode root) { List<Integer> list = new LinkedList<Integer>(); Stack<TreeNode> s1 = new Stack<TreeNode>(); Stack<TreeNode> s2 = new Stack<TreeNode>(); TreeNode curr; s1.push(root); while (!s1.isEmpty()) { curr = s1.peek(); if (curr != null) { s1.pop(); s2.push(curr); if (curr.left != null) s1.push(curr.left); if (curr.right != null) s1.push(curr.right); } } while (!s2.isEmpty()) { list.add(s2.pop().val); } return list; } }
mit
tguzik/mybatis-metrics
integration-tests/integration-test-commons/src/main/java/com/tguzik/metrics/mybatis/integrationtests/IntegrationTestVerificationUtil.java
2580
package com.tguzik.metrics.mybatis.integrationtests; import static com.codahale.metrics.MetricRegistry.name; import static org.assertj.core.api.Assertions.assertThat; import com.codahale.metrics.MetricRegistry; /** * The reason why we're bothering with inheritance in these integration tests is that we want to have exactly same * tests for each of MyBatis initialization methods. * * @author Tomasz Guzik <tomek@tguzik.com> */ public class IntegrationTestVerificationUtil { public static void validateSuccessfulOperation( MetricRegistry registry, String baseMetricName ) { validate( registry, baseMetricName, 1, 0 ); } public static void validateFailingOperation( MetricRegistry registry, String baseMetricName ) { validate( registry, baseMetricName, 1, 1 ); } private static void validate( MetricRegistry registry, String base, long expectedInvocations, long expectedFailures ) { // Counters assertThat( registry.getCounters() ).containsKeys( name( base, "totalInvocations" ), name( base, "totalFailures" ) ); assertThat( counterValue( registry, base, "totalInvocations" ) ).isEqualTo( expectedInvocations ); assertThat( counterValue( registry, base, "totalFailures" ) ).isEqualTo( expectedFailures ); // Meters assertThat( registry.getMeters() ).containsKeys( name( base, "invocationsPerSecond" ), name( base, "failuresPerSecond" ) ); assertThat( meterValue( registry, base, "invocationsPerSecond" ) ).isEqualTo( expectedInvocations ); assertThat( meterValue( registry, base, "failuresPerSecond" ) ).isEqualTo( expectedFailures ); // Timers assertThat( registry.getTimers() ).containsKey( name( base, "elapsed" ) ); assertThat( timerCount( registry, base, "elapsed" ) ).isEqualTo( expectedInvocations ); } private static long counterValue( MetricRegistry registry, String baseName, String item ) { return registry.counter( name( baseName, item ) ).getCount(); } private static long meterValue( MetricRegistry registry, String baseName, String item ) { return registry.meter( name( baseName, item ) ).getCount(); } private static long timerCount( MetricRegistry registry, String baseName, String item ) { return registry.timer( name( baseName, item ) ).getCount(); } }
mit
KuangPF/mySport
models/user/userInfo.js
561
/** * Created by ForeverW on 2017/5/9. */ var mongoose=require('mongoose'); mongoose.Promise = global.Promise; /** * 用户模型 */ var userInfoCshema= new mongoose.Schema({ /*用户基本信息*/ username:{type:String}, userActualName:{type:String}, usernameIDNum:{type:String}, usernameEmail:{type:String}, password:{type:String}, booleanLogin:{type:Number}, telephoneNum:{type:Number}, userBirthDay:{type:String}, userNickName:{type:String}, userSignature:{type:String} }); module.exports = userInfoCshema;
mit
emergenzeHack/emergenzeHack.github.io
node_modules/electron-to-chromium/full-versions.js
18771
module.exports = { "10.0.0-nightly.20200325": "83.0.4087.0", "10.0.0-nightly.20200324": "83.0.4087.0", "10.0.0-nightly.20200323": "83.0.4087.0", "10.0.0-nightly.20200320": "83.0.4087.0", "10.0.0-nightly.20200318": "83.0.4087.0", "10.0.0-nightly.20200317": "83.0.4087.0", "10.0.0-nightly.20200316": "83.0.4086.0", "10.0.0-nightly.20200311": "82.0.4083.0", "10.0.0-nightly.20200310": "82.0.4076.0", "10.0.0-nightly.20200309": "82.0.4076.0", "10.0.0-nightly.20200306": "82.0.4076.0", "10.0.0-nightly.20200305": "82.0.4076.0", "10.0.0-nightly.20200304": "82.0.4076.0", "10.0.0-nightly.20200303": "82.0.4050.0", "10.0.0-nightly.20200226": "82.0.4050.0", "10.0.0-nightly.20200223": "82.0.4050.0", "10.0.0-nightly.20200222": "82.0.4050.0", "10.0.0-nightly.20200221": "82.0.4050.0", "10.0.0-nightly.20200218": "82.0.4050.0", "10.0.0-nightly.20200217": "82.0.4050.0", "10.0.0-nightly.20200216": "82.0.4050.0", "10.0.0-nightly.20200211": "82.0.4050.0", "10.0.0-nightly.20200210": "82.0.4050.0", "10.0.0-nightly.20200209": "82.0.4050.0", "9.0.0-nightly.20200121": "81.0.4030.0", "9.0.0-nightly.20200119": "81.0.4030.0", "9.0.0-nightly.20200117": "81.0.3994.0", "9.0.0-nightly.20200116": "81.0.3994.0", "9.0.0-nightly.20200115": "81.0.3994.0", "9.0.0-nightly.20200113": "81.0.3994.0", "9.0.0-nightly.20200111": "81.0.3994.0", "9.0.0-nightly.20200110": "81.0.3994.0", "9.0.0-nightly.20200109": "81.0.3994.0", "9.0.0-nightly.20200108": "81.0.3994.0", "9.0.0-nightly.20200106": "81.0.3994.0", "9.0.0-nightly.20200105": "81.0.3994.0", "9.0.0-nightly.20200104": "81.0.3994.0", "9.0.0-nightly.20200103": "81.0.3994.0", "9.0.0-nightly.20200101": "81.0.3994.0", "9.0.0-nightly.20191231": "81.0.3994.0", "9.0.0-nightly.20191230": "81.0.3994.0", "9.0.0-nightly.20191229": "81.0.3994.0", "9.0.0-nightly.20191228": "81.0.3994.0", "9.0.0-nightly.20191226": "81.0.3994.0", "9.0.0-nightly.20191225": "81.0.3994.0", "9.0.0-nightly.20191224": "81.0.3994.0", "9.0.0-nightly.20191223": "81.0.3994.0", "9.0.0-nightly.20191222": "81.0.3994.0", "9.0.0-nightly.20191221": "81.0.3994.0", "9.0.0-nightly.20191220": "81.0.3994.0", "9.0.0-nightly.20191210": "80.0.3954.0", "9.0.0-nightly.20191204": "80.0.3954.0", "9.0.0-nightly.20191203": "80.0.3954.0", "9.0.0-nightly.20191202": "80.0.3954.0", "9.0.0-nightly.20191201": "80.0.3954.0", "9.0.0-nightly.20191130": "80.0.3954.0", "9.0.0-nightly.20191129": "80.0.3954.0", "9.0.0-nightly.20191124": "80.0.3954.0", "9.0.0-nightly.20191123": "80.0.3954.0", "9.0.0-nightly.20191122": "80.0.3954.0", "9.0.0-nightly.20191121": "80.0.3954.0", "9.0.0-beta.10": "82.0.4085.10", "9.0.0-beta.9": "82.0.4058.2", "9.0.0-beta.7": "82.0.4058.2", "9.0.0-beta.6": "82.0.4058.2", "9.0.0-beta.5": "82.0.4048.0", "9.0.0-beta.4": "82.0.4048.0", "9.0.0-beta.3": "82.0.4048.0", "9.0.0-beta.2": "82.0.4048.0", "9.0.0-beta.1": "82.0.4048.0", "8.2.0": "80.0.3987.158", "8.1.1": "80.0.3987.141", "8.1.0": "80.0.3987.137", "8.0.3": "80.0.3987.134", "8.0.2": "80.0.3987.86", "8.0.1": "80.0.3987.86", "8.0.0": "80.0.3987.86", "8.0.0-nightly.20191105": "80.0.3952.0", "8.0.0-nightly.20191101": "80.0.3952.0", "8.0.0-nightly.20191023": "79.0.3931.0", "8.0.0-nightly.20191021": "79.0.3931.0", "8.0.0-nightly.20191020": "79.0.3931.0", "8.0.0-nightly.20191019": "79.0.3931.0", "8.0.0-nightly.20191017": "79.0.3919.0", "8.0.0-nightly.20191012": "79.0.3919.0", "8.0.0-nightly.20191011": "79.0.3919.0", "8.0.0-nightly.20191009": "79.0.3919.0", "8.0.0-nightly.20191006": "79.0.3919.0", "8.0.0-nightly.20191005": "79.0.3919.0", "8.0.0-nightly.20191004": "79.0.3919.0", "8.0.0-nightly.20191001": "79.0.3919.0", "8.0.0-nightly.20190930": "79.0.3919.0", "8.0.0-nightly.20190929": "79.0.3919.0", "8.0.0-nightly.20190926": "79.0.3919.0", "8.0.0-nightly.20190924": "79.0.3919.0", "8.0.0-nightly.20190923": "79.0.3919.0", "8.0.0-nightly.20190920": "79.0.3915.0", "8.0.0-nightly.20190919": "79.0.3915.0", "8.0.0-nightly.20190917": "78.0.3892.0", "8.0.0-nightly.20190915": "78.0.3892.0", "8.0.0-nightly.20190914": "78.0.3892.0", "8.0.0-nightly.20190913": "78.0.3892.0", "8.0.0-nightly.20190911": "78.0.3892.0", "8.0.0-nightly.20190910": "78.0.3892.0", "8.0.0-nightly.20190909": "78.0.3892.0", "8.0.0-nightly.20190907": "78.0.3892.0", "8.0.0-nightly.20190902": "78.0.3892.0", "8.0.0-nightly.20190901": "78.0.3892.0", "8.0.0-nightly.20190830": "78.0.3892.0", "8.0.0-nightly.20190828": "78.0.3892.0", "8.0.0-nightly.20190827": "78.0.3892.0", "8.0.0-nightly.20190825": "78.0.3892.0", "8.0.0-nightly.20190824": "78.0.3892.0", "8.0.0-nightly.20190820": "78.0.3881.0", "8.0.0-nightly.20190819": "78.0.3881.0", "8.0.0-nightly.20190818": "78.0.3881.0", "8.0.0-nightly.20190817": "78.0.3881.0", "8.0.0-nightly.20190816": "78.0.3881.0", "8.0.0-nightly.20190815": "78.0.3871.0", "8.0.0-nightly.20190814": "78.0.3871.0", "8.0.0-nightly.20190813": "78.0.3871.0", "8.0.0-nightly.20190812": "78.0.3871.0", "8.0.0-nightly.20190811": "78.0.3871.0", "8.0.0-nightly.20190810": "78.0.3871.0", "8.0.0-nightly.20190809": "78.0.3871.0", "8.0.0-nightly.20190808": "78.0.3871.0", "8.0.0-nightly.20190807": "78.0.3871.0", "8.0.0-nightly.20190806": "78.0.3871.0", "8.0.0-nightly.20190803": "78.0.3871.0", "8.0.0-nightly.20190802": "78.0.3866.0", "8.0.0-nightly.20190801": "78.0.3866.0", "8.0.0-beta.9": "80.0.3987.75", "8.0.0-beta.8": "80.0.3987.75", "8.0.0-beta.7": "80.0.3987.59", "8.0.0-beta.6": "80.0.3987.51", "8.0.0-beta.5": "80.0.3987.14", "8.0.0-beta.4": "80.0.3955.0", "8.0.0-beta.3": "80.0.3955.0", "8.0.0-beta.2": "79.0.3931.0", "8.0.0-beta.1": "79.0.3931.0", "7.2.1": "78.0.3904.130", "7.2.0": "78.0.3904.130", "7.1.14": "78.0.3904.130", "7.1.13": "78.0.3904.130", "7.1.12": "78.0.3904.130", "7.1.11": "78.0.3904.130", "7.1.10": "78.0.3904.130", "7.1.9": "78.0.3904.130", "7.1.8": "78.0.3904.130", "7.1.7": "78.0.3904.130", "7.1.6": "78.0.3904.130", "7.1.5": "78.0.3904.130", "7.1.4": "78.0.3904.130", "7.1.3": "78.0.3904.126", "7.1.2": "78.0.3904.113", "7.1.1": "78.0.3904.99", "7.1.0": "78.0.3904.94", "7.0.1": "78.0.3904.92", "7.0.0": "78.0.3905.1", "7.0.0-nightly.20190731": "78.0.3866.0", "7.0.0-nightly.20190730": "78.0.3866.0", "7.0.0-nightly.20190729": "78.0.3866.0", "7.0.0-nightly.20190728": "78.0.3866.0", "7.0.0-nightly.20190727": "78.0.3866.0", "7.0.0-nightly.20190726": "77.0.3864.0", "7.0.0-nightly.20190721": "77.0.3848.0", "7.0.0-nightly.20190720": "77.0.3848.0", "7.0.0-nightly.20190719": "77.0.3848.0", "7.0.0-nightly.20190705": "77.0.3843.0", "7.0.0-nightly.20190704": "77.0.3843.0", "7.0.0-nightly.20190702": "77.0.3815.0", "7.0.0-nightly.20190701": "77.0.3815.0", "7.0.0-nightly.20190630": "77.0.3815.0", "7.0.0-nightly.20190629": "77.0.3815.0", "7.0.0-nightly.20190627": "77.0.3815.0", "7.0.0-nightly.20190624": "77.0.3815.0", "7.0.0-nightly.20190623": "77.0.3815.0", "7.0.0-nightly.20190622": "77.0.3815.0", "7.0.0-nightly.20190619": "77.0.3815.0", "7.0.0-nightly.20190618": "77.0.3815.0", "7.0.0-nightly.20190616": "77.0.3815.0", "7.0.0-nightly.20190615": "77.0.3815.0", "7.0.0-nightly.20190613": "77.0.3815.0", "7.0.0-nightly.20190612": "77.0.3815.0", "7.0.0-nightly.20190611": "77.0.3815.0", "7.0.0-nightly.20190609": "77.0.3815.0", "7.0.0-nightly.20190608": "77.0.3815.0", "7.0.0-nightly.20190607": "77.0.3815.0", "7.0.0-nightly.20190606": "77.0.3815.0", "7.0.0-nightly.20190605": "77.0.3815.0", "7.0.0-nightly.20190604": "77.0.3814.0", "7.0.0-nightly.20190603": "76.0.3806.0", "7.0.0-nightly.20190602": "76.0.3806.0", "7.0.0-nightly.20190531": "76.0.3806.0", "7.0.0-nightly.20190530": "76.0.3806.0", "7.0.0-nightly.20190529": "76.0.3806.0", "7.0.0-nightly.20190521": "76.0.3784.0", "7.0.0-beta.7": "78.0.3905.1", "7.0.0-beta.6": "78.0.3905.1", "7.0.0-beta.5": "78.0.3905.1", "7.0.0-beta.4": "78.0.3896.6", "7.0.0-beta.3": "78.0.3866.0", "7.0.0-beta.2": "78.0.3866.0", "7.0.0-beta.1": "78.0.3866.0", "6.1.9": "76.0.3809.146", "6.1.8": "76.0.3809.146", "6.1.7": "76.0.3809.146", "6.1.6": "76.0.3809.146", "6.1.5": "76.0.3809.146", "6.1.4": "76.0.3809.146", "6.1.3": "76.0.3809.146", "6.1.2": "76.0.3809.146", "6.1.1": "76.0.3809.146", "6.1.0": "76.0.3809.146", "6.0.12": "76.0.3809.146", "6.0.11": "76.0.3809.146", "6.0.10": "76.0.3809.146", "6.0.9": "76.0.3809.146", "6.0.8": "76.0.3809.146", "6.0.7": "76.0.3809.139", "6.0.6": "76.0.3809.138", "6.0.5": "76.0.3809.136", "6.0.4": "76.0.3809.131", "6.0.3": "76.0.3809.126", "6.0.2": "76.0.3809.110", "6.0.1": "76.0.3809.102", "6.0.0": "76.0.3809.88", "6.0.0-nightly.20190311": "74.0.3724.8", "6.0.0-nightly.20190213": "72.0.3626.110", "6.0.0-nightly.20190212": "72.0.3626.107", "6.0.0-beta.15": "76.0.3809.74", "6.0.0-beta.14": "76.0.3809.68", "6.0.0-beta.13": "76.0.3809.60", "6.0.0-beta.12": "76.0.3809.54", "6.0.0-beta.11": "76.0.3809.42", "6.0.0-beta.10": "76.0.3809.37", "6.0.0-beta.9": "76.0.3809.26", "6.0.0-beta.8": "76.0.3809.26", "6.0.0-beta.7": "76.0.3809.22", "6.0.0-beta.6": "76.0.3809.3", "6.0.0-beta.5": "76.0.3805.4", "6.0.0-beta.4": "76.0.3783.1", "6.0.0-beta.3": "76.0.3783.1", "6.0.0-beta.2": "76.0.3783.1", "6.0.0-beta.1": "76.0.3774.1", "5.0.13": "73.0.3683.121", "5.0.12": "73.0.3683.121", "5.0.11": "73.0.3683.121", "5.0.10": "73.0.3683.121", "5.0.9": "73.0.3683.121", "5.0.8": "73.0.3683.121", "5.0.7": "73.0.3683.121", "5.0.6": "73.0.3683.121", "5.0.5": "73.0.3683.121", "5.0.4": "73.0.3683.121", "5.0.3": "73.0.3683.121", "5.0.2": "73.0.3683.121", "5.0.1": "73.0.3683.121", "5.0.0": "73.0.3683.119", "5.0.0-nightly.20190122": "71.0.3578.98", "5.0.0-nightly.20190121": "71.0.3578.98", "5.0.0-nightly.20190107": "70.0.3538.110", "5.0.0-beta.9": "73.0.3683.117", "5.0.0-beta.8": "73.0.3683.104", "5.0.0-beta.7": "73.0.3683.94", "5.0.0-beta.6": "73.0.3683.84", "5.0.0-beta.5": "73.0.3683.61", "5.0.0-beta.4": "73.0.3683.54", "5.0.0-beta.3": "73.0.3683.27", "5.0.0-beta.2": "72.0.3626.52", "5.0.0-beta.1": "72.0.3626.52", "4.2.12": "69.0.3497.128", "4.2.11": "69.0.3497.128", "4.2.10": "69.0.3497.128", "4.2.9": "69.0.3497.128", "4.2.8": "69.0.3497.128", "4.2.7": "69.0.3497.128", "4.2.6": "69.0.3497.128", "4.2.5": "69.0.3497.128", "4.2.4": "69.0.3497.128", "4.2.3": "69.0.3497.128", "4.2.2": "69.0.3497.128", "4.2.1": "69.0.3497.128", "4.2.0": "69.0.3497.128", "4.1.5": "69.0.3497.128", "4.1.4": "69.0.3497.128", "4.1.3": "69.0.3497.128", "4.1.2": "69.0.3497.128", "4.1.1": "69.0.3497.128", "4.1.0": "69.0.3497.128", "4.0.8": "69.0.3497.128", "4.0.7": "69.0.3497.128", "4.0.6": "69.0.3497.106", "4.0.5": "69.0.3497.106", "4.0.4": "69.0.3497.106", "4.0.3": "69.0.3497.106", "4.0.2": "69.0.3497.106", "4.0.1": "69.0.3497.106", "4.0.0": "69.0.3497.106", "4.0.0-nightly.20181010": "69.0.3497.106", "4.0.0-nightly.20181006": "68.0.3440.128", "4.0.0-nightly.20180929": "67.0.3396.99", "4.0.0-nightly.20180821": "66.0.3359.181", "4.0.0-nightly.20180819": "66.0.3359.181", "4.0.0-nightly.20180817": "66.0.3359.181", "4.0.0-beta.11": "69.0.3497.106", "4.0.0-beta.10": "69.0.3497.106", "4.0.0-beta.9": "69.0.3497.106", "4.0.0-beta.8": "69.0.3497.106", "4.0.0-beta.7": "69.0.3497.106", "4.0.0-beta.6": "69.0.3497.106", "4.0.0-beta.5": "69.0.3497.106", "4.0.0-beta.4": "69.0.3497.106", "4.0.0-beta.3": "69.0.3497.106", "4.0.0-beta.2": "69.0.3497.106", "4.0.0-beta.1": "69.0.3497.106", "3.1.13": "66.0.3359.181", "3.1.12": "66.0.3359.181", "3.1.11": "66.0.3359.181", "3.1.10": "66.0.3359.181", "3.1.9": "66.0.3359.181", "3.1.8": "66.0.3359.181", "3.1.7": "66.0.3359.181", "3.1.6": "66.0.3359.181", "3.1.5": "66.0.3359.181", "3.1.4": "66.0.3359.181", "3.1.3": "66.0.3359.181", "3.1.2": "66.0.3359.181", "3.1.1": "66.0.3359.181", "3.1.0": "66.0.3359.181", "3.1.0-beta.5": "66.0.3359.181", "3.1.0-beta.4": "66.0.3359.181", "3.1.0-beta.3": "66.0.3359.181", "3.1.0-beta.2": "66.0.3359.181", "3.1.0-beta.1": "66.0.3359.181", "3.0.16": "66.0.3359.181", "3.0.15": "66.0.3359.181", "3.0.14": "66.0.3359.181", "3.0.13": "66.0.3359.181", "3.0.12": "66.0.3359.181", "3.0.11": "66.0.3359.181", "3.0.10": "66.0.3359.181", "3.0.9": "66.0.3359.181", "3.0.8": "66.0.3359.181", "3.0.7": "66.0.3359.181", "3.0.6": "66.0.3359.181", "3.0.5": "66.0.3359.181", "3.0.4": "66.0.3359.181", "3.0.3": "66.0.3359.181", "3.0.2": "66.0.3359.181", "3.0.1": "66.0.3359.181", "3.0.0": "66.0.3359.181", "3.0.0-nightly.20180904": "66.0.3359.181", "3.0.0-nightly.20180823": "66.0.3359.181", "3.0.0-nightly.20180821": "66.0.3359.181", "3.0.0-nightly.20180818": "66.0.3359.181", "3.0.0-beta.13": "66.0.3359.181", "3.0.0-beta.12": "66.0.3359.181", "3.0.0-beta.11": "66.0.3359.181", "3.0.0-beta.10": "66.0.3359.181", "3.0.0-beta.9": "66.0.3359.181", "3.0.0-beta.8": "66.0.3359.181", "3.0.0-beta.7": "66.0.3359.181", "3.0.0-beta.6": "66.0.3359.181", "3.0.0-beta.5": "66.0.3359.181", "3.0.0-beta.4": "66.0.3359.181", "3.0.0-beta.3": "66.0.3359.181", "3.0.0-beta.2": "66.0.3359.181", "3.0.0-beta.1": "66.0.3359.181", "2.1.0-unsupported.20180809": "61.0.3163.100", "2.0.18": "61.0.3163.100", "2.0.17": "61.0.3163.100", "2.0.16": "61.0.3163.100", "2.0.15": "61.0.3163.100", "2.0.14": "61.0.3163.100", "2.0.13": "61.0.3163.100", "2.0.12": "61.0.3163.100", "2.0.11": "61.0.3163.100", "2.0.10": "61.0.3163.100", "2.0.9": "61.0.3163.100", "2.0.8": "61.0.3163.100", "2.0.8-nightly.20180820": "61.0.3163.100", "2.0.8-nightly.20180819": "61.0.3163.100", "2.0.7": "61.0.3163.100", "2.0.6": "61.0.3163.100", "2.0.5": "61.0.3163.100", "2.0.4": "61.0.3163.100", "2.0.3": "61.0.3163.100", "2.0.2": "61.0.3163.100", "2.0.1": "61.0.3163.100", "2.0.0": "61.0.3163.100", "2.0.0-beta.8": "61.0.3163.100", "2.0.0-beta.7": "61.0.3163.100", "2.0.0-beta.6": "61.0.3163.100", "2.0.0-beta.5": "61.0.3163.100", "2.0.0-beta.4": "61.0.3163.100", "2.0.0-beta.3": "61.0.3163.100", "2.0.0-beta.2": "61.0.3163.100", "2.0.0-beta.1": "61.0.3163.100", "1.8.8": "59.0.3071.115", "1.8.7": "59.0.3071.115", "1.8.6": "59.0.3071.115", "1.8.5": "59.0.3071.115", "1.8.4": "59.0.3071.115", "1.8.3": "59.0.3071.115", "1.8.2": "59.0.3071.115", "1.8.2-beta.5": "59.0.3071.115", "1.8.2-beta.4": "59.0.3071.115", "1.8.2-beta.3": "59.0.3071.115", "1.8.2-beta.2": "59.0.3071.115", "1.8.2-beta.1": "59.0.3071.115", "1.8.1": "59.0.3071.115", "1.8.0": "59.0.3071.115", "1.7.16": "58.0.3029.110", "1.7.15": "58.0.3029.110", "1.7.14": "58.0.3029.110", "1.7.13": "58.0.3029.110", "1.7.12": "58.0.3029.110", "1.7.11": "58.0.3029.110", "1.7.10": "58.0.3029.110", "1.7.9": "58.0.3029.110", "1.7.8": "58.0.3029.110", "1.7.7": "58.0.3029.110", "1.7.6": "58.0.3029.110", "1.7.5": "58.0.3029.110", "1.7.4": "58.0.3029.110", "1.7.3": "58.0.3029.110", "1.7.2": "58.0.3029.110", "1.7.1": "58.0.3029.110", "1.7.0": "58.0.3029.110", "1.6.18": "56.0.2924.87", "1.6.17": "56.0.2924.87", "1.6.16": "56.0.2924.87", "1.6.15": "56.0.2924.87", "1.6.14": "56.0.2924.87", "1.6.13": "56.0.2924.87", "1.6.12": "56.0.2924.87", "1.6.11": "56.0.2924.87", "1.6.10": "56.0.2924.87", "1.6.9": "56.0.2924.87", "1.6.8": "56.0.2924.87", "1.6.7": "56.0.2924.87", "1.6.6": "56.0.2924.87", "1.6.5": "56.0.2924.87", "1.6.4": "56.0.2924.87", "1.6.3": "56.0.2924.87", "1.6.2": "56.0.2924.87", "1.6.1": "56.0.2924.87", "1.6.0": "56.0.2924.87", "1.5.1": "54.0.2840.101", "1.5.0": "54.0.2840.101", "1.4.16": "53.0.2785.143", "1.4.15": "53.0.2785.143", "1.4.14": "53.0.2785.143", "1.4.13": "53.0.2785.143", "1.4.12": "54.0.2840.51", "1.4.11": "53.0.2785.143", "1.4.10": "53.0.2785.143", "1.4.8": "53.0.2785.143", "1.4.7": "53.0.2785.143", "1.4.6": "53.0.2785.143", "1.4.5": "53.0.2785.113", "1.4.4": "53.0.2785.113", "1.4.3": "53.0.2785.113", "1.4.2": "53.0.2785.113", "1.4.1": "53.0.2785.113", "1.4.0": "53.0.2785.113", "1.3.15": "52.0.2743.82", "1.3.14": "52.0.2743.82", "1.3.13": "52.0.2743.82", "1.3.10": "52.0.2743.82", "1.3.9": "52.0.2743.82", "1.3.7": "52.0.2743.82", "1.3.6": "52.0.2743.82", "1.3.5": "52.0.2743.82", "1.3.4": "52.0.2743.82", "1.3.3": "52.0.2743.82", "1.3.2": "52.0.2743.82", "1.3.1": "52.0.2743.82", "1.3.0": "52.0.2743.82", "1.2.8": "51.0.2704.106", "1.2.7": "51.0.2704.106", "1.2.6": "51.0.2704.106", "1.2.5": "51.0.2704.103", "1.2.4": "51.0.2704.103", "1.2.3": "51.0.2704.84", "1.2.2": "51.0.2704.84", "1.2.1": "51.0.2704.63", "1.2.0": "51.0.2704.63", "1.1.3": "50.0.2661.102", "1.1.2": "50.0.2661.102", "1.1.1": "50.0.2661.102", "1.1.0": "50.0.2661.102", "1.0.2": "49.0.2623.75", "1.0.1": "49.0.2623.75", "1.0.0": "49.0.2623.75", "0.37.8": "49.0.2623.75", "0.37.7": "49.0.2623.75", "0.37.6": "49.0.2623.75", "0.37.5": "49.0.2623.75", "0.37.4": "49.0.2623.75", "0.37.3": "49.0.2623.75", "0.37.1": "49.0.2623.75", "0.37.0": "49.0.2623.75", "0.36.12": "47.0.2526.110", "0.36.11": "47.0.2526.110", "0.36.10": "47.0.2526.110", "0.36.9": "47.0.2526.110", "0.36.8": "47.0.2526.110", "0.36.7": "47.0.2526.110", "0.36.6": "47.0.2526.110", "0.36.5": "47.0.2526.110", "0.36.4": "47.0.2526.73", "0.36.3": "47.0.2526.73", "0.36.2": "47.0.2526.73", "0.36.0": "47.0.2526.73", "0.35.5": "45.0.2454.85", "0.35.4": "45.0.2454.85", "0.35.3": "45.0.2454.85", "0.35.2": "45.0.2454.85", "0.35.1": "45.0.2454.85", "0.34.4": "45.0.2454.85", "0.34.3": "45.0.2454.85", "0.34.2": "45.0.2454.85", "0.34.1": "45.0.2454.85", "0.34.0": "45.0.2454.85", "0.33.9": "45.0.2454.85", "0.33.8": "45.0.2454.85", "0.33.7": "45.0.2454.85", "0.33.6": "45.0.2454.85", "0.33.4": "45.0.2454.85", "0.33.3": "45.0.2454.85", "0.33.2": "45.0.2454.85", "0.33.1": "45.0.2454.85", "0.33.0": "45.0.2454.85", "0.32.3": "45.0.2454.85", "0.32.2": "45.0.2454.85", "0.31.2": "45.0.2454.85", "0.31.0": "44.0.2403.125", "0.30.4": "44.0.2403.125", "0.29.2": "43.0.2357.65", "0.29.1": "43.0.2357.65", "0.28.3": "43.0.2357.65", "0.28.2": "43.0.2357.65", "0.28.1": "43.0.2357.65", "0.28.0": "43.0.2357.65", "0.27.3": "43.0.2357.65", "0.27.2": "43.0.2357.65", "0.27.1": "42.0.2311.107", "0.27.0": "42.0.2311.107", "0.26.1": "42.0.2311.107", "0.26.0": "42.0.2311.107", "0.25.3": "42.0.2311.107", "0.25.2": "42.0.2311.107", "0.25.1": "42.0.2311.107", "0.25.0": "42.0.2311.107", "0.24.0": "41.0.2272.76", "0.23.0": "41.0.2272.76", "0.22.3": "41.0.2272.76", "0.22.2": "41.0.2272.76", "0.22.1": "41.0.2272.76", "0.21.3": "41.0.2272.76", "0.21.2": "40.0.2214.91", "0.21.1": "40.0.2214.91", "0.21.0": "40.0.2214.91", "0.20.8": "39.0.2171.65", "0.20.7": "39.0.2171.65", "0.20.6": "39.0.2171.65", "0.20.5": "39.0.2171.65", "0.20.4": "39.0.2171.65", "0.20.3": "39.0.2171.65", "0.20.2": "39.0.2171.65", "0.20.1": "39.0.2171.65", "0.20.0": "39.0.2171.65" };
mit
e-koch/VLA_Lband
14B-088/HI/visualization/yt_viz.py
1794
''' Image rendering with yt's Scene functionality. ''' from spectral_cube import SpectralCube from astropy.io import fits import yt import numpy as np cube = SpectralCube.read("M33_14B-088_HI.clean.image.pbcov_gt_0.5_masked.fits") mask = fits.open("M33_14B-088_HI.clean.image.pbcov_gt_0.5_masked_source_mask.fits")[0] cube = cube.with_mask(mask.data > 0) cube_max = cube.max() ytcube = cube[100:-100].to_yt() ytcube.dataset.periodicity = (True, True, True) sc = yt.create_scene(ytcube.dataset, field='flux') cam = sc.camera source = sc[0] source.log_field = True source.set_use_ghost_zones(True) cam.resolution = [2048, 2048] # Start with the disk face on. cam.rotate(np.pi / 2.) bounds = (np.log10(0.004), np.log10(cube_max.value)) # bounds = (0.001, cube.max().value) tf = yt.ColorTransferFunction(bounds) # def linramp(vals, minval, maxval): # return (vals - vals.min()) / (vals.max() - vals.min()) # tf.map_to_colormap(bounds[0], bounds[1], # colormap='arbre', # scale_func=linramp) nLayer = 10 # tf.add_layers(nLayer, colormap='gist_rainbow', # alpha=np.linspace(0, 1, nLayer)) tf.add_layers(nLayer, w=0.001, colormap='gist_rainbow', alpha=np.logspace(-1.0, -0.2, nLayer)) source.tfh.tf = tf source.tfh.set_log(False) source.tfh.bounds = bounds # save an image at the starting position frame = 0 sc.save('yt_outputs/camera_movement_%04i.png' % frame, sigma_clip=3) frame += 1 # for _ in cam.iter_zoom(1.5, 2): # sc.render() # sc.save('yt_outputs/camera_movement_%04i.png' % frame, # sigma_clip=1) # frame += 1 for _ in cam.iter_rotate(1.9 * np.pi, 20): sc.render() sc.save('yt_outputs/camera_movement_%04i.png' % frame, sigma_clip=1) frame += 1
mit
opbeat/opbeat-react
test/e2e/react/simple.failsafe.js
691
describe('failsafe react-app', function () { // Can't use utils.verifyNoBrowserErrors since console is not available in ie9 it('should have no errors', function (done) { browser .url('/react/index.html') .executeAsync( function (cb) { var errors = [] window.onerror = function (error, url, line) { errors.push(error) console.log(error) } setTimeout(function () { cb(errors) }, 1000) } ).then(function (response) { var errors = response.value expect(errors.length).toBe(0) done() }, function (error) { browser.log(error) }) }) })
mit
ProfilerTeam/Profiler
protected/vendors/Zend/Tool/Project/Context/Interface.php
1135
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Tool * @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * Interface for contexts * * setResource() is an optional method that if the context supports * will be set with the resource at construction time * * @category Zend * @package Zend_Tool * @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Zend_Tool_Project_Context_Interface { public function getName(); }
mit
DLRSP/django-sp
src/socialprofile/migrations/0006_auto_20211030_2242.py
494
# Generated by Django 2.2.19 on 2021-10-30 22:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("socialprofile", "0005_auto_20211030_2237"), ] operations = [ migrations.AlterField( model_name="socialprofile", name="google_language", field=models.CharField( blank=True, max_length=10, null=True, verbose_name="Google Language" ), ), ]
mit
paazmaya/tozan
tests/lib/store-data_test.js
1045
/** * tozan * https://github.com/paazmaya/tozan * Index filesystem by creating metadata database * * Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (https://paazmaya.fi) * Licensed under the MIT license */ import tape from 'tape'; import storeData from '../../lib/store-data.js'; tape('storeData - interface', (test) => { test.plan(2); test.equal(typeof storeData, 'function', 'is a function'); test.equal(storeData.length, 2); }); tape('storeData - empty list not processed', (test) => { test.plan(1); const list = []; const db = {}; const output = storeData(list, db); test.notOk(output); }); tape('storeData - calls all database methods once with one file', (test) => { test.plan(3); const list = ['']; const db = { prepare: function prepare() { test.ok('prepare was called'); return { run: function run() { test.ok('run was called'); } }; } }; const output = storeData(list, db); test.equal(output, db, 'The same db instance returned'); });
mit
lrt/lrt
vendor/gedmo/doctrine-extensions/tests/Gedmo/Mapping/Xml/TimestampableMappingTest.php
2087
<?php namespace Gedmo\Mapping\Xml; use Doctrine\Common\EventManager; use Doctrine\ORM\Mapping\Driver\DriverChain; use Doctrine\ORM\Mapping\Driver\XmlDriver; use Gedmo\Timestampable\TimestampableListener; use Tool\BaseTestCaseOM; /** * These are mapping extension tests * * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com> * @package Gedmo.Mapping * @link http://www.gediminasm.org * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ class TimestampableMappingTest extends BaseTestCaseOM { /** * @var Doctrine\ORM\EntityManager */ private $em; /** * @var Gedmo\Timestampable\TimestampableListener */ private $timestampable; public function setUp() { parent::setUp(); $xmlDriver = new XmlDriver(__DIR__.'/../Driver/Xml'); $chain = new DriverChain; $chain->addDriver($xmlDriver, 'Mapping\Fixture\Xml'); $this->timestampable = new TimestampableListener; $this->evm = new EventManager; $this->evm->addEventSubscriber($this->timestampable); $this->em = $this->getMockSqliteEntityManager(array( 'Mapping\Fixture\Xml\Timestampable', 'Mapping\Fixture\Xml\Status', ), $chain); } public function testTimestampableMetadata() { $meta = $this->em->getClassMetadata('Mapping\Fixture\Xml\Timestampable'); $config = $this->timestampable->getConfiguration($this->em, $meta->name); $this->assertArrayHasKey('create', $config); $this->assertEquals('created', $config['create'][0]); $this->assertArrayHasKey('update', $config); $this->assertEquals('updated', $config['update'][0]); $this->assertArrayHasKey('change', $config); $onChange = $config['change'][0]; $this->assertEquals('published', $onChange['field']); $this->assertEquals('status.title', $onChange['trackedField']); $this->assertEquals('Published', $onChange['value']); } }
mit
ebernhardson/l2r
code/dbn_random_set.py
1338
import numpy as np import pandas as pd import config from utils import table_utils def main(): df = table_utils._read(config.CLICK_DATA) \ .join(table_utils._read(config.RELEVANCE_DATA).set_index(['norm_query', 'hit_title']), on=['norm_query', 'hit_title'], how='inner') dfQ = df['norm_query'].drop_duplicates() queries = dfQ.reindex(np.random.permutation(dfQ.index))[:20] del dfQ condition = np.zeros((len(df)), dtype=bool) for q in queries: condition = condition | (df['norm_query'] == q) dfShort = df[condition] pd.set_option('display.width', 1000) for norm_query, query_group in dfShort.groupby(['norm_query']): hits = [] for title, hit_group in query_group.groupby(['hit_title']): num_clicks = np.sum(hit_group['clicked']) avg_position = np.mean(hit_group['hit_position']) relevance = np.mean(hit_group['relevance']) hits.append((title, num_clicks, avg_position, relevance)) queries = list(query_group['query'].drop_duplicates()) print("Normalized Query: %s" % (norm_query.encode('utf8'))) print("Queries:\n\t%s" % ("\n\t".join(map(lambda x: x.encode('utf8'), queries)))) hitDf = pd.DataFrame(hits, columns=['title', 'num_clicks', 'avg_pos', 'dbn_rel']) print(hitDf.sort_values(['dbn_rel'], ascending=False)) print("\n\n") if __name__ == "__main__": main()
mit
501st-alpha1/php-mcrypt
attributes/default.rb
508
# # Cookbook Name:: php-mcrypt # # Copyright 2014, Michael Beattie # # Licensed under the MIT License. # You may obtain a copy of the License at # # http://opensource.org/licenses/MIT # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #
mit
Azure/azure-sdk-for-java
sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/src/main/java/com/azure/resourcemanager/recoveryservicesbackup/models/AzureVmWorkloadSqlDatabaseProtectedItem.java
7466
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.recoveryservicesbackup.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import java.time.OffsetDateTime; import java.util.List; import java.util.Map; /** Azure VM workload-specific protected item representing SQL Database. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "protectedItemType") @JsonTypeName("AzureVmWorkloadSQLDatabase") @Fluent public final class AzureVmWorkloadSqlDatabaseProtectedItem extends AzureVmWorkloadProtectedItem { @JsonIgnore private final ClientLogger logger = new ClientLogger(AzureVmWorkloadSqlDatabaseProtectedItem.class); /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withFriendlyName(String friendlyName) { super.withFriendlyName(friendlyName); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withServerName(String serverName) { super.withServerName(serverName); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withParentName(String parentName) { super.withParentName(parentName); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withParentType(String parentType) { super.withParentType(parentType); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withProtectionStatus(String protectionStatus) { super.withProtectionStatus(protectionStatus); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withProtectionState(ProtectionState protectionState) { super.withProtectionState(protectionState); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withLastBackupStatus(LastBackupStatus lastBackupStatus) { super.withLastBackupStatus(lastBackupStatus); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withLastBackupTime(OffsetDateTime lastBackupTime) { super.withLastBackupTime(lastBackupTime); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withLastBackupErrorDetail(ErrorDetail lastBackupErrorDetail) { super.withLastBackupErrorDetail(lastBackupErrorDetail); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withProtectedItemDataSourceId(String protectedItemDataSourceId) { super.withProtectedItemDataSourceId(protectedItemDataSourceId); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withProtectedItemHealthStatus( ProtectedItemHealthStatus protectedItemHealthStatus) { super.withProtectedItemHealthStatus(protectedItemHealthStatus); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withExtendedInfo( AzureVmWorkloadProtectedItemExtendedInfo extendedInfo) { super.withExtendedInfo(extendedInfo); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withKpisHealths(Map<String, KpiResourceHealthDetails> kpisHealths) { super.withKpisHealths(kpisHealths); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withBackupManagementType(BackupManagementType backupManagementType) { super.withBackupManagementType(backupManagementType); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withWorkloadType(DataSourceType workloadType) { super.withWorkloadType(workloadType); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withContainerName(String containerName) { super.withContainerName(containerName); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withSourceResourceId(String sourceResourceId) { super.withSourceResourceId(sourceResourceId); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withPolicyId(String policyId) { super.withPolicyId(policyId); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withLastRecoveryPoint(OffsetDateTime lastRecoveryPoint) { super.withLastRecoveryPoint(lastRecoveryPoint); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withBackupSetName(String backupSetName) { super.withBackupSetName(backupSetName); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withCreateMode(CreateMode createMode) { super.withCreateMode(createMode); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withDeferredDeleteTimeInUtc(OffsetDateTime deferredDeleteTimeInUtc) { super.withDeferredDeleteTimeInUtc(deferredDeleteTimeInUtc); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withIsScheduledForDeferredDelete( Boolean isScheduledForDeferredDelete) { super.withIsScheduledForDeferredDelete(isScheduledForDeferredDelete); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withDeferredDeleteTimeRemaining(String deferredDeleteTimeRemaining) { super.withDeferredDeleteTimeRemaining(deferredDeleteTimeRemaining); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withIsDeferredDeleteScheduleUpcoming( Boolean isDeferredDeleteScheduleUpcoming) { super.withIsDeferredDeleteScheduleUpcoming(isDeferredDeleteScheduleUpcoming); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withIsRehydrate(Boolean isRehydrate) { super.withIsRehydrate(isRehydrate); return this; } /** {@inheritDoc} */ @Override public AzureVmWorkloadSqlDatabaseProtectedItem withResourceGuardOperationRequests( List<String> resourceGuardOperationRequests) { super.withResourceGuardOperationRequests(resourceGuardOperationRequests); return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); } }
mit
Bob-Thomas/V100PC-school
Catch/include/reporters/catch_reporter_xml.hpp
9374
/* * Created by Phil on 28/10/2010. * Copyright 2010 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED #define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED #include "catch_reporter_bases.hpp" #include "../internal/catch_capture.hpp" #include "../internal/catch_reporter_registrars.hpp" #include "../internal/catch_xmlwriter.hpp" #include "../internal/catch_timer.h" namespace Catch { class XmlReporter : public StreamingReporterBase { public: XmlReporter(ReporterConfig const &_config) : StreamingReporterBase(_config), m_sectionDepth(0) { m_reporterPrefs.shouldRedirectStdOut = true; } virtual ~XmlReporter() CATCH_OVERRIDE; static std::string getDescription() { return "Reports test results as an XML document"; } public: // StreamingReporterBase virtual void noMatchingTestCases(std::string const &s) CATCH_OVERRIDE { StreamingReporterBase::noMatchingTestCases(s); } virtual void testRunStarting(TestRunInfo const &testInfo) CATCH_OVERRIDE { StreamingReporterBase::testRunStarting(testInfo); m_xml.setStream(stream); m_xml.startElement("Catch"); if (!m_config->name().empty()) m_xml.writeAttribute("name", m_config->name()); } virtual void testGroupStarting(GroupInfo const &groupInfo) CATCH_OVERRIDE { StreamingReporterBase::testGroupStarting(groupInfo); m_xml.startElement("Group") .writeAttribute("name", groupInfo.name); } virtual void testCaseStarting(TestCaseInfo const &testInfo) CATCH_OVERRIDE { StreamingReporterBase::testCaseStarting(testInfo); m_xml.startElement("TestCase").writeAttribute("name", trim(testInfo.name)); if (m_config->showDurations() == ShowDurations::Always) m_testCaseTimer.start(); } virtual void sectionStarting(SectionInfo const &sectionInfo) CATCH_OVERRIDE { StreamingReporterBase::sectionStarting(sectionInfo); if (m_sectionDepth++ > 0) { m_xml.startElement("Section") .writeAttribute("name", trim(sectionInfo.name)) .writeAttribute("description", sectionInfo.description); } } virtual void assertionStarting(AssertionInfo const &) CATCH_OVERRIDE { } virtual bool assertionEnded(AssertionStats const &assertionStats) CATCH_OVERRIDE { const AssertionResult &assertionResult = assertionStats.assertionResult; // Print any info messages in <Info> tags. if (assertionStats.assertionResult.getResultType() != ResultWas::Ok) { for (std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); it != itEnd; ++it) { if (it->type == ResultWas::Info) { m_xml.scopedElement("Info") .writeText(it->message); } else if (it->type == ResultWas::Warning) { m_xml.scopedElement("Warning") .writeText(it->message); } } } // Drop out if result was successful but we're not printing them. if (!m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType())) return true; // Print the expression if there is one. if (assertionResult.hasExpression()) { m_xml.startElement("Expression") .writeAttribute("success", assertionResult.succeeded()) .writeAttribute("type", assertionResult.getTestMacroName()) .writeAttribute("filename", assertionResult.getSourceInfo().file) .writeAttribute("line", assertionResult.getSourceInfo().line); m_xml.scopedElement("Original") .writeText(assertionResult.getExpression()); m_xml.scopedElement("Expanded") .writeText(assertionResult.getExpandedExpression()); } // And... Print a result applicable to each result type. switch (assertionResult.getResultType()) { case ResultWas::ThrewException: m_xml.scopedElement("Exception") .writeAttribute("filename", assertionResult.getSourceInfo().file) .writeAttribute("line", assertionResult.getSourceInfo().line) .writeText(assertionResult.getMessage()); break; case ResultWas::FatalErrorCondition: m_xml.scopedElement("Fatal Error Condition") .writeAttribute("filename", assertionResult.getSourceInfo().file) .writeAttribute("line", assertionResult.getSourceInfo().line) .writeText(assertionResult.getMessage()); break; case ResultWas::Info: m_xml.scopedElement("Info") .writeText(assertionResult.getMessage()); break; case ResultWas::Warning: // Warning will already have been written break; case ResultWas::ExplicitFailure: m_xml.scopedElement("Failure") .writeText(assertionResult.getMessage()); break; default: break; } if (assertionResult.hasExpression()) m_xml.endElement(); return true; } virtual void sectionEnded(SectionStats const &sectionStats) CATCH_OVERRIDE { StreamingReporterBase::sectionEnded(sectionStats); if (--m_sectionDepth > 0) { XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResults"); e.writeAttribute("successes", sectionStats.assertions.passed); e.writeAttribute("failures", sectionStats.assertions.failed); e.writeAttribute("expectedFailures", sectionStats.assertions.failedButOk); if (m_config->showDurations() == ShowDurations::Always) e.writeAttribute("durationInSeconds", sectionStats.durationInSeconds); m_xml.endElement(); } } virtual void testCaseEnded(TestCaseStats const &testCaseStats) CATCH_OVERRIDE { StreamingReporterBase::testCaseEnded(testCaseStats); XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResult"); e.writeAttribute("success", testCaseStats.totals.assertions.allOk()); if (m_config->showDurations() == ShowDurations::Always) e.writeAttribute("durationInSeconds", m_testCaseTimer.getElapsedSeconds()); m_xml.endElement(); } virtual void testGroupEnded(TestGroupStats const &testGroupStats) CATCH_OVERRIDE { StreamingReporterBase::testGroupEnded(testGroupStats); // TODO: Check testGroupStats.aborting and act accordingly. m_xml.scopedElement("OverallResults") .writeAttribute("successes", testGroupStats.totals.assertions.passed) .writeAttribute("failures", testGroupStats.totals.assertions.failed) .writeAttribute("expectedFailures", testGroupStats.totals.assertions.failedButOk); m_xml.endElement(); } virtual void testRunEnded(TestRunStats const &testRunStats) CATCH_OVERRIDE { StreamingReporterBase::testRunEnded(testRunStats); m_xml.scopedElement("OverallResults") .writeAttribute("successes", testRunStats.totals.assertions.passed) .writeAttribute("failures", testRunStats.totals.assertions.failed) .writeAttribute("expectedFailures", testRunStats.totals.assertions.failedButOk); m_xml.endElement(); } private: Timer m_testCaseTimer; XmlWriter m_xml; int m_sectionDepth; }; INTERNAL_CATCH_REGISTER_REPORTER("xml", XmlReporter) } // end namespace Catch #endif // TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED
mit
ucndm/0215-Web-Development-Open-Source
web1.local/Database/links3.php
1721
<?php //HTTP headers header('Content-type: text/html'); //variables $message = new stdClass(); $message->alert = ''; $links = array(); try { //db connection $conn = new PDO('mysql:host=localhost;dbname=links', 'test_user', 'test_user_pw'); //inserting new links if($_SERVER['REQUEST_METHOD'] == 'POST'){ if(array_key_exists('url',$_POST) && array_key_exists('title',$_POST)){ if($_POST['title'] != '' && $_POST['url'] != ''){ $insert = $conn->prepare("INSERT INTO link (url, title) VALUES (:url, :title)"); $insert->bindParam(":url", $_POST['url'], PDO::PARAM_STR, 265); $insert->bindParam(":title", $_POST['title'], PDO::PARAM_STR, 256); if($insert->execute()){ $message->alert = "Link created! ".$conn->lastInsertId(); } }else{ $message->alert = 'You need both title and url'; } } } //collecting links from db $select = $conn->prepare("SELECT * FROM link"); $select->execute(); $links = $select->fetchAll(PDO::FETCH_CLASS, "Link"); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } class Link { public $id; public $url; public $title; function __construct() { } } ?> <!DOCTYPE html> <html> <head> <title>Links</title> </head> <body> <div class="message"><?php echo $message->alert; ?></div> <h1>Links</h1> <ul> <?php foreach($links as $link){ echo "<li><a data-id=\"$link->id\" href=\"$link->url\">$link->title</a></li>"; } ?> </ul> <h2>New link</h2> <form name="postlink" method="post"> <label>URL <input type="url" name="url"/></label> <label>Title <input type="text" name="title"/></label> <input type="submit"/> </form> </body> </html>
mit
typetools/annotation-tools
annotation-file-utilities/tests/issue155/Issue155.java
80
package test; class Issue155 { void foo() { B result[] = new B[2]; } }
mit
JamesBarwell/probabilitydrive.js
example/persistent/script/main.js
1309
(function() { if (!window.localStorage) { console.warn('Sorry, this example needs localStorage support'); return; } // Get ProbabilityDrive and a localStorage data store var probabilitydrive = new window.probabilitydrive; var cache = window.localStorage; // Make it available globally just for playing around with in this example window.pdInstance = probabilitydrive; // Retrieve and set the historical data from the data store var previousData; try { previousData = JSON.parse(cache.getItem('pd-data')); } catch (e) { // swallow the error - don't do this in real life! } log('setData', previousData); probabilitydrive.setData(previousData); // Observe the current path var pathname = window.location.pathname; log('observe', pathname); probabilitydrive.observe(pathname); // Save the updated data back to the data store var updatedData = probabilitydrive.getData('data'); log('getData', updatedData); cache.setItem('pd-data', JSON.stringify(updatedData)); // Make a prediction var prediction = probabilitydrive.determine(); log('prediction', prediction.join(', ')); function log(method, data) { console.log('probabilitydrive.' + method, data); } })();
mit
netrack/openflow
ofp/packet_test.go
2964
package ofp import ( "encoding/gob" "testing" "github.com/netrack/openflow/internal/encodingtest" ) func TestPacketIn(t *testing.T) { tests := []encodingtest.MU{ {ReadWriter: &PacketIn{ Buffer: NoBuffer, Length: 0x38, Reason: PacketInReasonAction, Table: Table(2), Cookie: 0xdeadbeef, Match: Match{MatchTypeXM, []XM{{ Class: XMClassOpenflowBasic, Type: XMTypeInPort, Value: XMValue{0x00, 0x00, 0x00, 0x03}, }}}, Data: []byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x08, 0x06, }, }, Bytes: []byte{ 0xff, 0xff, 0xff, 0xff, // Buffer identifier. 0x00, 0x38, // Total frame length. 0x01, // Packet-in submission reason. 0x02, // Table identifier. 0x00, 0x00, 0x00, 0x00, 0xde, 0xad, 0xbe, 0xef, // Cookie. 0x00, 0x01, // Match type. 0x00, 0x0c, // Match length. // Match. 0x80, 0x00, // OpenFlow basic. 0x00, // Match field + Mask flag. 0x04, // Match field length. 0x00, 0x00, 0x00, 0x03, // Match field value. 0x00, 0x00, 0x00, 0x00, // 4-byte padding. 0x00, 0x00, // 2-byte padding. // Original ethernet frame. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // Destination MAC. 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, // Source MAC. 0x08, 0x06, // Ether-Type }}, } encodingtest.RunMU(t, tests) } func TestPacketOut(t *testing.T) { tests := []encodingtest.MU{ // Test Packet-Out without data (buffer_id required). {ReadWriter: &PacketOut{ Buffer: 0x01, InPort: PortController, Actions: Actions{&ActionGroup{Group: GroupAll}}, }, Bytes: []byte{ 0x00, 0x00, 0x00, 0x01, // Buffer identifier. 0xff, 0xff, 0xff, 0xfd, // Port number. 0x00, 0x08, // Actions list length in bytes. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 6-byte padding. // Actions. 0x00, 0x16, // Action group. 0x00, 0x08, 0xff, 0xff, 0xff, 0xfc, }}, // Test Packet-Out with data (no buffer_id). {ReadWriter: &PacketOut{ Buffer: NoBuffer, InPort: PortController, Actions: Actions{&ActionOutput{Port: PortNo(1)}}, Data: []byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x08, 0x06, }, }, Bytes: []byte{ 0xff, 0xff, 0xff, 0xff, // Buffer identifier (OFP_NO_BUFFER). 0xff, 0xff, 0xff, 0xfd, // Port number (OFPP_CONTROLLER). 0x00, 0x10, // Actions list length in bytes. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 6-byte padding. // Actions. 0x00, 0x00, // Type output. 0x00, 0x10, // Length. 0x00, 0x00, 0x00, 0x01, // Port. 0x00, 0x00, // Max length. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 6-byte padding. // Data with the ethernet frame. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // Destination MAC. 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, // Source MAC. 0x08, 0x06, // Ether-Type }}, } gob.Register(ActionGroup{}) gob.Register(ActionOutput{}) encodingtest.RunMU(t, tests) }
mit
mr-karan/Udacity-FullStack-ND004
Project1/assignments/turtle/turtleproject.py
266
import turtle def draw_shape(): window = turtle.Screen() window.bgcolor("blue") jeff = turtle.Turtle() jeff.color("brown") jeff.shape("classic") jeff.speed(1) for i in range(36): jeff.rt(3) jeff.rt(120) jeff.fd(120) window.exitonclick() draw_shape()
mit
patricepalau/leetcode
src/removedups2/Solution.java
1475
package removedups2; /** * https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ * * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. * * For example * - Given 1->2->3->3->4->4->5, return 1->2->5. * - Given 1->1->1->2->3, return 2->3. */ public class Solution { static class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public ListNode deleteDuplicates(ListNode head) { if (head == null) return null; if (head.next == null) return head; ListNode current = head; ListNode nextNode = null; ListNode prev = null; while (current != null) { nextNode = current.next; boolean removeCurrentNode = false; while (nextNode != null && current.val == nextNode.val) { current.next = nextNode.next; nextNode.next = null; nextNode = current.next; removeCurrentNode = true; } if (removeCurrentNode) { if (prev != null) { prev.next = current.next; current.next = null; current = prev; } else { head = current.next; current.next = null; current = head; prev = null; } } else if (current != null) { prev = current; current = current.next; } } return head; } }
mit
niki-funky/Telerik_Academy
Programming/02.Csharp/02. Arrays/02.Compare2Arrays/02.Compare2Arrays.cs
1478
using System; class Compare2Arrays { //Write a program that reads two arrays from //the console and compares them element by element. static void Main() { //variables //int n = int.Parse(Console.ReadLine()); //int m = int.Parse(Console.ReadLine()); //int[] array1 = new int[n]; //int[] array2 = new int[m]; int[] array1 = { 1, 2, 3, 4 }; int[] array2 = { 1, 3, 5, 4, 7, 8 }; int equalElements = 0; //expressions ////read from console the numbers for first array //for (int i = 0; i < n; i++) //{ // array1[i] = int.Parse(Console.ReadLine()); //} ////read from console the numbers for second array //for (int i = 0; i < m; i++) //{ // array2[i] = int.Parse(Console.ReadLine()); //} for (int i = 0; i < (array1.Length >= array2.Length ? array2.Length : array1.Length); i++) { if (array1[i] == array2[i]) { Console.WriteLine("Elements at index[{0}] from both arrays are equal.", i); equalElements++; } if (array1.Length == array2.Length && equalElements == array2.Length) { Console.WriteLine("Arrays are identical."); } } if (array1.Length != array2.Length) { Console.WriteLine("Arrays are Not identical."); } } }
mit
matortheeternal/zedit
src/javascripts/Views/editValueModal.js
5194
ngapp.controller('editValueModalController', function($scope, $timeout, errorService, hotkeyService) { // variables let opts = $scope.modalOptions, node = opts.targetNode, handle = node.handles[opts.targetIndex], value = node.cells[opts.targetIndex + 1].value, vtLabel = xelib.valueTypes[node.value_type]; xelib.valueTypes.forEach((key, index) => $scope[key] = index); $scope.path = xelib.Path(handle); $scope.vtClass = vtLabel; $scope.valueType = node.value_type; let tryParseColor = function(color) { try { return new Color(color) } catch (e) {} }; // scope functions $scope.applyValue = function() { if ($scope.invalid) return; errorService.try(function() { xelib.SetValue(handle, '', $scope.value); $scope.afterApplyValue(); }); }; $scope.afterApplyValue = function() { let index = opts.targetIndex, record = index === 0 ? opts.record : opts.overrides[index - 1]; $scope.$root.$broadcast('recordUpdated', record); $scope.$emit('closeModal'); }; $scope.setupBytes = function(value) { let isPrintable = function(key) { return key > 33 && key !== 127; }; let bytesToStr = function(bytes) { let a = bytes.map((byte) => { return parseInt(byte, 16); }); return a.reduce(function(str, byte) { let char = isPrintable(byte) ? String.fromCharCode(byte) : '.'; return str + char; }, ''); }; $scope.applyValue = function() { errorService.try(function() { xelib.SetValue(handle, '', $scope.bytes.join(' ')); $scope.afterApplyValue(); }); }; $scope.$watch('bytes', function() { $scope.text = bytesToStr($scope.bytes); }, true); $scope.bytes = value.split(' '); }; $scope.setupNumber = function(value) { $scope.textChanged = function() { let match = /^\-?([0-9]+)(\.[0-9]+)?$/i.exec($scope.value); $scope.invalid = !match; }; $scope.value = value; $scope.textChanged(); }; $scope.setupText = function(value) { const htmlElements = ['DESC - Book Text']; $scope.useHtmlEditor = htmlElements.includes(node.label); $scope.value = value; }; $scope.setupReference = function(value) { $scope.signatures = xelib.GetAllowedSignatures(handle).sort(); $scope.signature = $scope.signatures[0]; $scope.handle = handle; $scope.value = value; }; $scope.setupFlags = function(value) { $scope.applyValue = function() { let activeFlags = $scope.flags.filter((flag) => { return flag.active; }); $scope.value = activeFlags.map((flag) => { return flag.name; }); xelib.SetEnabledFlags(handle, '', $scope.value); $scope.afterApplyValue(); }; // initialize flags $scope.defaultAction = $scope.applyValue; let enabledFlags = value.split(', '); $scope.flags = xelib.GetAllFlags(handle).map(function(flag) { return { name: flag, active: flag !== '' && enabledFlags.includes(flag) } }); }; $scope.setupEnum = function(value) { $scope.options = xelib.GetEnumOptions(handle); $scope.value = value; }; $scope.setupColor = function() { $scope.textChanged = function() { let c = tryParseColor($scope.value); $scope.invalid = !c; if (!$scope.invalid) $scope.color = c.toHex(); }; $scope.applyValue = function() { if ($scope.invalid) return; errorService.try(function() { let c = tryParseColor($scope.value); xelib.SetValue(handle, 'Red', c.getRed().toString()); xelib.SetValue(handle, 'Green', c.getGreen().toString()); xelib.SetValue(handle, 'Blue', c.getBlue().toString()); $scope.afterApplyValue(); }); }; $scope.$watch('color', function() { let c = new Color($scope.color); $scope.value = c.toRGB(); $scope.colorStyle = {'background-color': `${$scope.value}`}; }); // initialize color let red = xelib.GetValueEx(handle, 'Red'), green = xelib.GetValueEx(handle, 'Green'), blue = xelib.GetValueEx(handle, 'Blue'); $scope.value = `rgb(${red}, ${green}, ${blue})`; $scope.textChanged(); }; // initialization hotkeyService.buildOnKeyDown($scope, 'onKeyDown', 'editValueModal'); let setupFunctions = { vtBytes: $scope.setupBytes, vtNumber: $scope.setupNumber, vtReference: $scope.setupReference, vtFlags: $scope.setupFlags, vtEnum: $scope.setupEnum, vtColor: $scope.setupColor, vtText: $scope.setupText }; let defaultSetup = (value) => $scope.value = value; (setupFunctions[vtLabel] || defaultSetup)(value); });
mit
orobogenius/batchdownloaderbot
app/Messages/AddressMessage.php
752
<?php namespace App\Messages; /** * @implements AbstractMessage */ class AddressMessage extends BaseMessage implements AbstractMessage { /** * @var Update */ protected $update; /** * Create a new address message instance. * * @param Update * @return void */ function __construct($update) { parent::__construct(); $this->update = $update; } public function handle() { $this->sendMessage(); } public function sendMessage() { $response = $this->bot->sendMessage([ 'chat_id' => $this->update->message->chat->id, 'text' => 'Enter the base file url' ]); $messageId = $response->getMessageId(); } }
mit
codefornigeria/project-tame-api
src/models/antidote.model.js
599
// antidote-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. module.exports = function (app) { const mongooseClient = app.get('mongooseClient'); const antidote = new mongooseClient.Schema({ name: { type: String}, description: { type: 'String' }, score: { type: Number }, location: { type: mongooseClient.Schema.Types.ObjectId, ref: 'location' }, createdAt: { type: Date, 'default': Date.now }, updatedAt: { type: Date, 'default': Date.now } }); return mongooseClient.model('antidote', antidote); };
mit
asiboro/asiboro.github.io
vsdoc/search--/s_2733.js
107
search_result['2733']=["topic_0000000000000688_methods--.html","MasterBadgesPersonResponseDto Methods",""];
mit
swaggest/go-code-builder
src/Style/Initialisms.php
1339
<?php namespace Swaggest\GoCodeBuilder\Style; class Initialisms { public $values; public function __construct() { $this->values = json_decode('{ "API": true, "ASCII": true, "CPU": true, "CSS": true, "DNS": true, "EOF": true, "HTML": true, "HTTP": true, "HTTPS": true, "ID": true, "IP": true, "JSON": true, "LHS": true, "QPS": true, "RAM": true, "RHS": true, "RPC": true, "SLA": true, "SMTP": true, "SSH": true, "TLS": true, "TTL": true, "UI": true, "UID": true, "URI": true, "URL": true, "UTF8": true, "VM": true, "XML": true, "FK": true }', true); } public function process($goName) { $words = preg_split('/(?=[A-Z])/', $goName); if (false !== $words) { foreach ($words as &$word) { if ($word === strtolower($word)) { // skip lowercase words continue; } $uppercase = strtoupper($word); if (isset($this->values[$uppercase])) { $word = $uppercase; } } $goName = implode('', $words); return $goName; } return ''; } }
mit
wangyanxing/Demi3D
src/addons/K2/K2StaticObj.cpp
1120
/********************************************************************** This source file is a part of Demi3D __ ___ __ __ __ | \|_ |\/|| _)| \ |__/|__| || __)|__/ Copyright (c) 2013-2014 Demi team https://github.com/wangyanxing/Demi3D Released under the MIT License https://github.com/wangyanxing/Demi3D/blob/master/License.txt ***********************************************************************/ #include "K2Pch.h" #include "K2StaticObj.h" #include "K2Clip.h" #include "K2Model.h" #include "CullNode.h" #include "GfxDriver.h" #include "SceneManager.h" namespace Demi { DiK2StaticObj::DiK2StaticObj(DiK2World* world) :DiK2RenderObject(world) { } DiK2StaticObj::~DiK2StaticObj() { } DiK2ModelPtr DiK2StaticObj::LoadModel(const DiString& mdf) { DiSceneManager* sm = Driver->GetSceneManager(); mNode = sm->GetRootNode()->CreateChild(); mModel = make_shared<DiK2Model>(mdf); mModel->GetAnimation()->Play(K2PrefabClip::ANIM_IDLE); mNode->AttachObject(mModel); PostInit(); return mModel; } }
mit
gtamazian/bioformats
bioformats/scripts/gff3_bed12.py
979
#!/usr/bin/env python3 # -*- coding: utf8 -*- # Gaik Tamazian, 2019 # mail (at) gtamazian (dot) com """ Convert a GFF3 file to the BED12 format. The script converts gene records from a GFF3 file to the BED12 format. Each gene transcript is converted to one line in the output file. The converted file is printed to standard output. """ import sys from .. import bed from .. import gff3 assert sys.version_info >= (3, 5), "Python 3.5 or higher required" def gff3_bed12(gff3_fname): """ Convert a GFF3 file to the BED12 format and print to standard output. :param gff3_fname: a GFF3 file name """ for _, transcripts in gff3.iterate_genes(gff3_fname): for k in transcripts: print(bed.print_line(bed.gff3_bed12(k[1], k[0][-1]["ID"]))) def main(args): if len(args) != 2: print("Usage: gff3_bed12 genes.gff3", file=sys.stderr) sys.exit(1) gff3_bed12(args[1]) if __name__ == "__main__": main(sys.argv)
mit
Azure/azure-sdk-for-go
sdk/resourcemanager/changeanalysis/armchangeanalysis/ze_generated_example_operations_client_test.go
1293
//go:build go1.16 // +build go1.16 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. package armchangeanalysis_test import ( "context" "log" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/changeanalysis/armchangeanalysis" ) // x-ms-original-file: specification/changeanalysis/resource-manager/Microsoft.ChangeAnalysis/stable/2021-04-01/examples/OperationsList.json func ExampleOperationsClient_List() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armchangeanalysis.NewOperationsClient(cred, nil) pager := client.List(&armchangeanalysis.OperationsClientListOptions{SkipToken: nil}) for { nextResult := pager.NextPage(ctx) if err := pager.Err(); err != nil { log.Fatalf("failed to advance page: %v", err) } if !nextResult { break } for _, v := range pager.PageResponse().Value { log.Printf("Pager result: %#v\n", v) } } }
mit
foothing/laravel-boilerplate
app/Activation.php
266
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Activation extends Model { public function getCode() { return $this->code; } public function getDates() { return ['created_at', 'updated_at', 'completed_at']; } }
mit
TorchPowered/Thallium
src/main/java/net/minecraft/command/server/CommandBanIp.java
4149
package net.minecraft.command.server; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.CommandSender; import net.minecraft.command.PlayerNotFoundException; import net.minecraft.command.WrongUsageException; import net.minecraft.entity.player.PlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.IPBanEntry; import net.minecraft.util.BlockPos; import net.minecraft.util.IChatComponent; public class CommandBanIp extends CommandBase { public static final Pattern field_147211_a = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); /** * Gets the name of the command */ public String getCommandName() { return "ban-ip"; } /** * Return the required permission level for this command. */ public int getRequiredPermissionLevel() { return 3; } /** * Returns true if the given command sender is allowed to use this command. */ public boolean canCommandSenderUseCommand(CommandSender sender) { return MinecraftServer.getServer().getConfigurationManager().getBannedIPs().isLanServer() && super.canCommandSenderUseCommand(sender); } /** * Gets the usage string for the command. */ public String getCommandUsage(CommandSender sender) { return "commands.banip.usage"; } /** * Callback when the command is invoked */ public void processCommand(CommandSender sender, String[] args) throws CommandException { if (args.length >= 1 && args[0].length() > 1) { IChatComponent ichatcomponent = args.length >= 2 ? getChatComponentFromNthArg(sender, args, 1) : null; Matcher matcher = field_147211_a.matcher(args[0]); if (matcher.matches()) { this.func_147210_a(sender, args[0], ichatcomponent == null ? null : ichatcomponent.getUnformattedText()); } else { PlayerMP entityplayermp = MinecraftServer.getServer().getConfigurationManager().getPlayerByUsername(args[0]); if (entityplayermp == null) { throw new PlayerNotFoundException("commands.banip.invalid", new Object[0]); } this.func_147210_a(sender, entityplayermp.getPlayerIP(), ichatcomponent == null ? null : ichatcomponent.getUnformattedText()); } } else { throw new WrongUsageException("commands.banip.usage", new Object[0]); } } public List<String> addTabCompletionOptions(CommandSender sender, String[] args, BlockPos pos) { return args.length == 1 ? getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()) : null; } protected void func_147210_a(CommandSender p_147210_1_, String p_147210_2_, String p_147210_3_) { IPBanEntry ipbanentry = new IPBanEntry(p_147210_2_, (Date)null, p_147210_1_.getName(), (Date)null, p_147210_3_); MinecraftServer.getServer().getConfigurationManager().getBannedIPs().addEntry(ipbanentry); List<PlayerMP> list = MinecraftServer.getServer().getConfigurationManager().getPlayersMatchingAddress(p_147210_2_); String[] astring = new String[list.size()]; int i = 0; for (PlayerMP entityplayermp : list) { entityplayermp.playerNetServerHandler.kickPlayerFromServer("You have been IP banned."); astring[i++] = entityplayermp.getName(); } if (list.isEmpty()) { notifyOperators(p_147210_1_, this, "commands.banip.success", new Object[] {p_147210_2_}); } else { notifyOperators(p_147210_1_, this, "commands.banip.success.players", new Object[] {p_147210_2_, joinNiceString(astring)}); } } }
mit
vkhorikov/CSharpFunctionalExtensions
CSharpFunctionalExtensions/ValueObject/SimpleValueObject.cs
702
using System; using System.Collections.Generic; namespace CSharpFunctionalExtensions { [Serializable] public abstract class SimpleValueObject<T> : ValueObject { public T Value { get; } protected SimpleValueObject(T value) { Value = value; } protected override IEnumerable<object> GetEqualityComponents() { yield return Value; } public override string ToString() { return Value?.ToString(); } public static implicit operator T(SimpleValueObject<T> valueObject) { return valueObject == null ? default : valueObject.Value; } } }
mit
seanpdoyle/ember-test-helpers
tests/test-module-for-integration-test.js
8859
import Ember from 'ember'; import hasEmberVersion from 'ember-test-helpers/has-ember-version'; import { TestModuleForComponent } from 'ember-test-helpers'; import test from 'tests/test-support/qunit-test'; import qunitModuleFor from 'tests/test-support/qunit-module-for'; import { setResolverRegistry } from 'tests/test-support/resolver'; function moduleForComponent(name, description, callbacks) { var module = new TestModuleForComponent(name, description, callbacks); qunitModuleFor(module); } moduleForComponent('Component Integration Tests', { integration: true, beforeSetup: function() { setResolverRegistry({ 'template:components/my-component': Ember.Handlebars.compile( '<span>{{name}}</span>' ) }); } }); test('it can render a template', function() { this.render("<span>Hello</span>"); equal(this.$('span').text(), 'Hello'); }); if (hasEmberVersion(1,11)) { test('it can render a link-to', function() { this.render("{{link-to 'Hi' 'index'}}"); ok(true, 'it renders without fail'); }); } test('it complains if you try to use bare render', function() { var self = this; throws(function() { self.render(); }, /in a component integration test you must pass a template to `render\(\)`/); }); test('it complains if you try to use subject()', function() { var self = this; throws(function() { self.subject(); }, /component integration tests do not support `subject\(\)`\./); }); test('it can access the full container', function() { this.set('myColor', 'red'); this.render('{{my-component name=myColor}}'); equal(this.$('span').text(), 'red'); this.set('myColor', 'blue'); equal(this.$('span').text(), 'blue'); }); test('it can handle actions', function() { var handlerArg; this.render('<button {{action "didFoo" 42}} />'); this.on('didFoo', function(thing) { handlerArg = thing; }); this.$('button').click(); equal(handlerArg, 42); }); test('it accepts precompiled templates', function() { this.render(Ember.Handlebars.compile("<span>Hello</span>")); equal(this.$('span').text(), 'Hello'); }); test('it supports DOM events', function() { setResolverRegistry({ 'component:my-component': Ember.Component.extend({ value: 0, layout: Ember.Handlebars.compile("<span class='target'>Click to increment!</span><span class='value'>{{value}}</span>"), incrementOnClick: Ember.on('click', function() { this.incrementProperty('value'); }) }) }); this.render('{{my-component}}'); this.$('.target').click(); equal(this.$('.value').text(), '1'); }); test('it supports updating an input', function() { setResolverRegistry({ 'component:my-input': Ember.TextField.extend({ value: null }) }); this.render('{{my-input value=value}}'); this.$('input').val('1').change(); equal(this.get('value'), '1'); }); test('it supports dom triggered focus events', function() { setResolverRegistry({ 'component:my-input': Ember.TextField.extend({ _onInit: Ember.on('init', function() { this.set('value', 'init'); }), focusIn: function() { this.set('value', 'focusin'); }, focusOut: function() { this.set('value', 'focusout'); } }) }); this.render('{{my-input}}'); equal(this.$('input').val(), 'init'); this.$('input').trigger('focusin'); equal(this.$('input').val(), 'focusin'); this.$('input').trigger('focusout'); equal(this.$('input').val(), 'focusout'); }); moduleForComponent('Component Integration Tests: render during setup', { integration: true, beforeSetup: function() { setResolverRegistry({ 'component:my-component': Ember.Component.extend({ value: 0, layout: Ember.Handlebars.compile("<span class='target'>Click to increment!</span><span class='value'>{{value}}</span>"), incrementOnClick: Ember.on('click', function() { this.incrementProperty('value'); }) }) }); }, setup: function() { this.render('{{my-component}}'); } }); test('it has working events', function() { this.$('.target').click(); equal(this.$('.value').text(), '1'); }); moduleForComponent('Component Integration Tests: context', { integration: true, beforeSetup: function() { setResolverRegistry({ 'component:my-component': Ember.Component.extend({ layout: Ember.Handlebars.compile('<span class="foo">{{foo}}</span><span class="bar">{{bar}}</span>') }) }); } }); test('it can set and get properties', function() { this.set('foo', 1); this.render('{{my-component foo=foo}}'); equal(this.get('foo'), '1'); equal(this.$('.foo').text(), '1'); }); test('it can setProperties and getProperties', function() { this.setProperties({ foo: 1, bar: 2 }); this.render('{{my-component foo=foo bar=bar}}'); var properties = this.getProperties('foo', 'bar'); equal(properties.foo, '1'); equal(properties.bar, '2'); equal(this.$('.foo').text(), '1'); equal(this.$('.bar').text(), '2'); }); var origDeprecate; moduleForComponent('Component Integration Tests: implicit views are not deprecated', { integration: true, setup: function () { origDeprecate = Ember.deprecate; Ember.deprecate = function(msg, check) { if (!check) { throw new Error("unexpected deprecation: " + msg); } }; }, teardown: function () { Ember.deprecate = origDeprecate; } }); test('the toplevel view is not deprecated', function () { expect(0); this.register('component:my-toplevel', this.container.lookupFactory('view:toplevel')); this.render("{{my-toplevel}}"); }); moduleForComponent('Component Integration Tests: register and inject', { integration: true }); test('can register a component', function() { this.register('component:x-foo', Ember.Component.extend({ classNames: ['i-am-x-foo'] })); this.render("{{x-foo}}"); equal(this.$('.i-am-x-foo').length, 1, "found i-am-x-foo"); }); test('can register a service', function() { this.register('component:x-foo', Ember.Component.extend({ unicorn: Ember.inject.service(), layout: Ember.Handlebars.compile('<span class="x-foo">{{unicorn.sparkliness}}</span>') })); this.register('service:unicorn', Ember.Component.extend({ sparkliness: 'extreme' })); this.render("{{x-foo}}"); equal(this.$('.x-foo').text().trim(), "extreme"); }); test('can inject a service directly into test context', function() { this.register('component:x-foo', Ember.Component.extend({ unicorn: Ember.inject.service(), layout: Ember.Handlebars.compile('<span class="x-foo">{{unicorn.sparkliness}}</span>') })); this.register('service:unicorn', Ember.Component.extend({ sparkliness: 'extreme' })); this.inject.service('unicorn'); this.render("{{x-foo}}"); equal(this.$('.x-foo').text().trim(), "extreme"); this.set('unicorn.sparkliness', 'amazing'); equal(this.$('.x-foo').text().trim(), "amazing"); }); test('can inject a service directly into test context, with aliased name', function() { this.register('component:x-foo', Ember.Component.extend({ unicorn: Ember.inject.service(), layout: Ember.Handlebars.compile('<span class="x-foo">{{unicorn.sparkliness}}</span>') })); this.register('service:unicorn', Ember.Component.extend({ sparkliness: 'extreme' })); this.inject.service('unicorn', { as: 'hornedBeast' }); this.render("{{x-foo}}"); equal(this.$('.x-foo').text().trim(), "extreme"); this.set('hornedBeast.sparkliness', 'amazing'); equal(this.$('.x-foo').text().trim(), "amazing"); }); moduleForComponent('Component Integration Tests: willDestoryElement', { integration: true, beforeSetup: function() { setResolverRegistry({ 'component:my-component': Ember.Component.extend({ willDestroyElement: function() { var stateIndicatesInDOM = (this._state === 'inDOM'); var actuallyInDOM = Ember.$.contains(document, this.$()[0]); ok((actuallyInDOM === true) && (actuallyInDOM === stateIndicatesInDOM), 'component should still be in the DOM'); } }) }); } }); test('still in DOM in willDestroyElement', function() { expect(1); this.render("{{my-component}}"); }); if (! hasEmberVersion(2,0)) { moduleForComponent('my-component', 'Component Legacy Integration Tests', { integration: 'legacy', beforeSetup: function() { setResolverRegistry({ 'component:my-component': Ember.Component.extend(), 'template:components/my-component': Ember.Handlebars.compile( '<span>{{name}}</span>' ) }); } }); test('it can render components semantically equivalent to v0.4.3', function() { this.subject({ name: 'Charles XII', }); this.render(); equal(this.$('span').text(), 'Charles XII'); }); }
mit
rangermeier/flaskberry
flaskberry/static/player-controls.js
6123
var statusMap = new can.Map({ enabled: false }) statusMap.bind("src", function(ev, newVal, oldVal){ if(newVal) { statusMap.attr("fileName", decodeURI(newVal).split("/").pop()) } else { statusMap.removeAttr("currentTime") statusMap.removeAttr("duration") } }) statusMap.bind("consumers", function(ev, newVal, oldVal){ statusMap.attr("enabled", newVal > 0) }) statusMap.bind("fullscreen", function(ev, newVal, oldVal){ if(newVal === false) { exitFullscreen() } }) /* Mustache helper for localized strings */ Mustache.registerHelper("lbl", function(key){ return lbl[key] }) /* Play/Pause Button */ can.Component.extend({ tag: "button-pause", template: can.view("#button-pause"), scope: statusMap, events: { click: function(){ socket.emit('play', { paused: !statusMap.attr("paused") }) } } }) function enterFullscreen(el) { if (el && !document.fullscreenElement && // alternative standard method !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) { // current working methods if (el.requestFullscreen) { el.requestFullscreen(); } else if (el.msRequestFullscreen) { el.msRequestFullscreen(); } else if (el.mozRequestFullScreen) { el.mozRequestFullScreen(); } else if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } } } function exitFullscreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } /* Fullscreen Button */ can.Component.extend({ tag: "button-fullscreen", template: can.view("#button-fullscreen"), scope: { visible: can.compute(function(){ return statusMap.attr("fullscreen") || !!$("video").length }) }, events: { click: function(){ enterFullscreen($("video").get(0)) socket.emit('update status', { fullscreen: !statusMap.attr("fullscreen") }) } } }) /* Mute Button */ can.Component.extend({ tag: "button-mute", template: can.view("#button-mute"), scope: { iconstate: function(){ var volume = parseFloat(statusMap.attr("volume")) if(statusMap.attr("muted") || !volume) { return "off" } return (volume < 0.5) ? "down" : "up" } }, events: { click: function(ev) { socket.emit('play', { muted: !statusMap.attr("muted") }) } } }) var sliderComponent = can.Component.extend({ tag: "slider", template: can.view("#slider-progress"), events: { getCursorVal: function(el, ev){ var percent = ev.offsetX / el.find(".progress").width() var factor = this.scope.property === "currentTime" ? statusMap.duration : 1 return percent * factor }, click: function(el, ev) { var data = {} data[this.scope.property] = this.getCursorVal(el, ev) socket.emit('play', data) }, mousemove: function(el, ev) { var label = this.scope.formatTooltip(this.getCursorVal(el, ev)) this.element.attr("title", label) } } }) var formatTime = function(timeInSec) { var s = parseInt(timeInSec) var sec = (s % 60)+"" return isNaN(s) ? "" : Math.floor(s/60) + ":" + (sec.length === 2 ? sec : "0"+sec) } /* Time/Duration Slider */ sliderComponent.extend({ tag: "slider-progress", scope: { property: "currentTime", formatTooltip: formatTime, total: can.compute(function(){ return formatTime(statusMap.attr("duration")) }), current: can.compute(function(){ return formatTime(statusMap.attr("currentTime")) }), percent: can.compute(function() { return statusMap.attr("currentTime") ? parseInt((parseFloat(statusMap.attr("currentTime")) * 100) / parseFloat(statusMap.attr("duration"))) : 0 }) } }) /* Volume Slider */ sliderComponent.extend({ tag: "slider-volume", scope: { property: "volume", formatTooltip: function(value){ return parseInt(value * 100) + "%" }, percent: can.compute(function() { return parseFloat(statusMap.attr("volume")) * 100 }) } }) /* Subtitles Menu */ can.Component.extend({ tag: "select-subtitles", template: can.view("#select-subtitles"), scope: { subtitles: [] }, helpers: { isActive: function(opts){ var selected = statusMap.attr("subtitles") if(selected && opts.context.url.split("/").pop() === selected.split("/").pop()) { return opts.fn() } else { return opts.inverse() } } }, events: { "button click": function() { var scope = this.scope if(statusMap.src) { $.getJSON("/movies/subtitles?src="+statusMap.src) .done(function(data){ scope.subtitles.replace(data.subtitles) }) } }, "a click": function(el, ev) { ev.preventDefault() socket.emit("play", { subtitles: el.data("url") }) } } }) /* SocketIO listeners */ if(!window.socket) { socket = io.connect('http://' + document.domain + ':' + location.port + socketNamespace); } socket.on('connect', function() { socket.emit('register controller', {}) }) socket.on('status', function(data){ statusMap.attr(data) })
mit
Hoene84/perzist
jdbc/src/test/java/ch/hoene/perzist/jdbc/db/db2instance/Db2Product.java
763
package ch.hoene.perzist.jdbc.db.db2instance; import ch.hoene.perzist.access.creator.ResultCreator; import ch.hoene.perzist.jdbc.db.Tables; import ch.hoene.perzist.model.Product; import java.sql.ResultSet; import java.sql.SQLException; public class Db2Product implements ResultCreator<Tables.Products, Product, ResultSet> { @Override public Product create(ResultSet resultSet) { try { return new Product( resultSet.getInt(Tables.Products.ID.getName()), resultSet.getString(Tables.Products.DESC.getName()), resultSet.getString(Tables.Products.CATALOG.getName()) ); } catch (SQLException e) { throw new RuntimeException(e); } } }
mit
vulcansteel/autorest
AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyBoolean/IBoolModel.cs
3772
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyBoolean { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// BoolModel operations. /// </summary> public partial interface IBoolModel { /// <summary> /// Get true Boolean value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<bool?>> GetTrueWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set Boolean value true /// </summary> /// <param name='boolBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutTrueWithHttpMessagesAsync(bool? boolBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get false Boolean value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<bool?>> GetFalseWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set Boolean value false /// </summary> /// <param name='boolBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutFalseWithHttpMessagesAsync(bool? boolBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get null Boolean value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<bool?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid Boolean value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<bool?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
mit
pancfab/thaurusbeats
app/cache/dev/assetic/config/8/8e2fb05ed27d4d063aec79c8d60ab62a.php
400
<?php // ShabloThaurusBeatsBundle:Edit:edituserpanel.html.twig return array ( '547e906' => array ( 0 => array ( 0 => 'bundles/thaurus/css/*', ), 1 => array ( ), 2 => array ( 'output' => '_controller/css/547e906.css', 'name' => '547e906', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), );
mit
sarahtrop/dance-index
db/migrate/20170510212444_remove_progression_id_from_contra.rb
139
class RemoveProgressionIdFromContra < ActiveRecord::Migration def change remove_column :contras, :progression_id, :integer end end
mit
ajozwik/akka-smtp-server
akka-smtp/src/main/scala/pl/jozwik/smtp/server/command/HelloCommand.scala
1989
/* * Copyright (c) 2017 Andrzej Jozwik * * 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 pl.jozwik.smtp package server package command import java.net.InetSocketAddress import pl.jozwik.smtp.util.Constants._ object HelloCommand { def handleEhlo(localHostName: String, remote: InetSocketAddress, size: Long): (MailAccumulator, ResponseMessage) = { val welcomeLine = s"$REQUEST_COMPLETE-$localHostName Hello ${remote.getHostName} " + s"[${remote.getAddress.getHostAddress}] pleased to meet you." response(MailAccumulator.withHello, welcomeLine, OK_8_BIT, s"$OK_SIZE $size", OK_PIPELINE) } def handleHelo(localHostName: String, remote: InetSocketAddress): (MailAccumulator, ResponseMessage) = { val welcomeLine = s"$REQUEST_COMPLETE $localHostName Hello ${remote.getHostName} " + s"[${remote.getAddress.getHostAddress}] pleased to meet you." response(MailAccumulator.withHello, welcomeLine) } }
mit
flexelektro/texture-packer
dist/BinPackingAlgorithm.js
3140
"use strict"; var BinPackingAlgorithm = function BinPackingAlgorithm(blocks, w, h) { this.root = { x: 0, y: 0, w: w, h: h }; this.fit = function (blocks) { var n, node, block; for (n = 0; n < blocks.length; n++) { block = blocks[n]; if (node = this.findNode(this.root, block.width, block.height)) { block.fit = this.splitNode(node, block.width, block.height); block.x = block.fit.x; block.y = block.fit.y; } else { this.root = this.growForNode(this.root, block.width, block.height); if (node = this.findNode(this.root, block.width, block.height)) { block.fit = this.splitNode(node, block.width, block.height); block.x = block.fit.x; block.y = block.fit.y; } } } return blocks; }; this.findNode = function (root, w, h) { console.log(root); if (root.used) return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);else if (w <= root.w && h <= root.h) return root;else return null; }; this.splitNode = function (node, w, h) { node.used = true; node.down = { x: node.x, y: node.y + h, w: node.w, h: node.h - h }; node.right = { x: node.x + w, y: node.y, w: node.w - w, h: h }; return node; }; this.growForNode = function (root, w, h) { var canGrowRight = h <= root.h; var canGrowDown = w <= root.w; var shouldGrowRight = canGrowRight && root.w + w <= root.h; var shouldGrowDown = canGrowDown && root.h + h <= root.w; var node = root; if (shouldGrowRight) { return this.growRight(node, w, h); } else if (shouldGrowDown) { return this.growDown(node, w, h); } else if (canGrowRight) { return this.growRight(node, w, h); } else if (canGrowDown) { return this.growDown(node, w, h); } else { return null; } }; this.growRight = function (node, w, h) { var newNode = { "used": true, "x": 0, "y": 0, "w": node.w + w, "h": node.h, "down": node, "right": { "x": node.w + node.x, "y": node.y, "w": w, "h": node.h } }; return newNode; }; this.growDown = function (node, w, h) { var newNode = { "used": true, "x": 0, "y": 0, "w": node.w, "h": node.h + h, "down": { "x": node.x, "y": node.y + node.h, "w": node.w, "h": h }, "right": node }; return newNode; }; var theBlocks = this.fit(blocks); return { "elements": theBlocks, "size": { width: this.root.w, height: this.root.h } }; }; module.exports = BinPackingAlgorithm;
mit
nilbot/furry-sansa
src/github.com/nilbot/note.app/notes/note_test.go
2569
package notes import ( "crypto/sha512" "fmt" "io" "testing" ) func newNoteOrFatal(t *testing.T, content string) *Note { note, err := NewNote(content) if err != nil { t.Fatalf("new note: %v", err) } return note } func TestNewNote(t *testing.T) { content := "copied from campoy/todo" hash := sha512.New() io.WriteString(hash, content) sha512_checksum := fmt.Sprintf("%x", hash.Sum(nil)) note := newNoteOrFatal(t, content) if note.Content != content { t.Errorf("expected content %q, got %q", content, note.Content) } if note.ID != sha512_checksum { t.Errorf("expected checksum %q, got %q", sha512_checksum, note.ID) } } func TestSave(t *testing.T) { content := "test a new note with a single hashtag #test, without linebreaks etc." note := newNoteOrFatal(t, content) man := NewNoteManager() man.Save(note) all := man.AllNotes() if len(all) != 1 { t.Errorf("expected 1 note, got %v", len(all)) } if *all[0] != *note { t.Errorf("expected %v, got %v", note, all[0]) } } func TestParse(t *testing.T) { content := "test a new note with a single hashtag #test, without linebreaks etc." tags := parseTag(content) if len(tags) != 1 { t.Errorf("expected 1 tag, got %v", len(tags)) } if tags[0] != "test" { t.Errorf("expected parsed tag %q, got %q", "test", tags[0]) } } func getNoteWithTagAndSaveInManager(t *testing.T) (*NoteManager, *Note, string, []string) { content := "test a new note with a single hashtag #test, without linebreaks etc." tags := parseTag(content) note := newNoteOrFatal(t, content) man := NewNoteManager() man.Save(note) return man, note, content, tags } func TestSaveWithVerifyingTag(t *testing.T) { content := "test a new note with a single hashtag #test, without linebreaks etc." tag := "test" note := newNoteOrFatal(t, content) man := NewNoteManager() man.Save(note) tags := man.AllTags() if len(tags) != 1 { t.Errorf("expected 1 tag, got %v", len(tags)) } if _, ok := man.NotesWith(tag); !ok { t.Errorf("expected to find tag %q, got nothing", "test") } if val, ok := man.NotesWith(tag); ok { for _, s := range val { if s != note.ID { t.Errorf("expected to find mapping of %q to %q, got %q to %q", "test", note.ID, "test", val) } } } } func TestGetNoteById(t *testing.T) { man, note, content, _ := getNoteWithTagAndSaveInManager(t) if n, ok := man.Find(note.ID); ok { if n.Content != content { t.Errorf("expected matching content, got %q", n.Content) } } if _, ok := man.Find(note.ID); !ok { t.Errorf("expected to find a matching, got nothing") } }
mit
magdkudama/phatic-blog-extension
src/MagdKudama/PhaticBlogExtension/Parser/PostsParser.php
1392
<?php namespace MagdKudama\PhaticBlogExtension\Parser; use MagdKudama\PhaticBlogExtension\Model\Collection\PostCollection; use MagdKudama\PhaticBlogExtension\Model\Post; use Symfony\Component\Finder\SplFileInfo; use Symfony\Component\Yaml\Yaml; use DateTime; class PostsParser extends BaseParser { public function read() { $postsCollection = new PostCollection(); /** @var SplFileInfo $postData */ foreach ($this->getSearchCriteria() as $postData) { $configFile = $postData->getRealpath() . '/config.yml'; $body = $postData->getRealpath() . '/content.html'; $config = Yaml::parse($configFile)['config']; $post = new Post(); $post->setTitle($config['title']); $post->setCreatedAt(DateTime::createFromFormat('Y-m-d H:i:s', $config['created_at'])); $post->setContent(file_get_contents($body)); $post->setKeywords($config['keywords']); $post->setMetaDescription($config['description']); $post->setSlug($postData->getFilename()); $post->setFile($postData); $postsCollection->add($post); } return $postsCollection->orderByDate(); } protected function getSearchCriteria() { return $this->getFinder()->directories()->notName('_*')->in($this->getConfig()->getPostsPath()); } }
mit
Hochfrequenz/aurelia-openui5-bridge
sample/vendor/openui5/sap/ui/unified/CalendarMonthIntervalRenderer-dbg.js
2637
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global'], function(jQuery) { "use strict"; /** * Calendar renderer. * @namespace */ var CalendarMonthIntervalRenderer = { }; /** * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer * @param {sap.ui.unified.CalendarMonthInterval} oCal An object representation of the control that should be rendered */ CalendarMonthIntervalRenderer.render = function(oRm, oCal){ oCal._iMode = 0; // it's rendered always as MonthsRow var sId = oCal.getId(); var sTooltip = oCal.getTooltip_AsString(); var oMonthsRow = oCal.getAggregation("monthsRow"); oRm.write("<div"); oRm.writeControlData(oCal); oRm.addClass("sapUiCal"); oRm.addClass("sapUiCalInt"); oRm.addClass("sapUiCalMonthInt"); if (oCal._getShowItemHeader()) { oRm.addClass("sapUiCalIntHead"); } // This makes the calendar focusable and therefore // the white empty areas can be clicked without closing the calendar // by accident. oRm.writeAttribute("tabindex", "-1"); var rb = sap.ui.getCore().getLibraryResourceBundle("sap.ui.unified"); var mAccProps = {labelledby: {value: "", append: false}}; // render on Month if (oCal._bPoupupMode) { mAccProps["role"] = "dialog"; } oRm.writeAccessibilityState(oCal, mAccProps); if (sTooltip) { oRm.writeAttributeEscaped('title', sTooltip); } var sWidth = oCal.getWidth(); if (sWidth && sWidth != '') { oRm.addStyle("width", sWidth); oRm.writeStyles(); } oRm.writeClasses(); oRm.write(">"); // div element var oHeader = oCal.getAggregation("header"); oRm.renderControl(oHeader); oRm.write("<div id=\"" + sId + "-content\" class=\"sapUiCalContent\">"); oRm.renderControl(oMonthsRow); oRm.write("<div id=\"" + sId + "-contentOver\" class=\"sapUiCalContentOver\" style=\"display:none;\"></div>"); oRm.write("</div>"); oRm.write("<button id=\"" + sId + "-cancel\" class=\"sapUiCalCancel\" tabindex=\"-1\">"); oRm.write(rb.getText("CALENDAR_CANCEL")); oRm.write("</button>"); // dummy element to catch tabbing in from next element oRm.write("<div id=\"" + sId + "-end\" tabindex=\"0\" style=\"width:0;height:0;position:absolute;right:0;bottom:0;\"></div>"); oRm.write("</div>"); }; return CalendarMonthIntervalRenderer; }, /* bExport= */ true);
mit
martyn82/aphajs
src/test/Apha/Projections/Projection.spec.ts
1311
import {expect} from "chai"; import {Projection} from "../../../main/Apha/Projections/Projection"; describe("Projection", () => { describe("copy", () => { it("should copy the projection", () => { const original = new ProjectionSpecProjection("foo", 12, true, new Date()); const copy = original.copy(); expect(copy).to.eql(original); }); it("should be able to override properties", () => { const original = new ProjectionSpecProjection("foo", 12, true, new Date()); const copy = original.copy({_foo: "bar", _baz: Date.parse("2012-12-12 00:00:00")}); expect(copy.foo).to.equal("bar"); expect(copy.bar).to.equal(12); expect(copy.boo).to.equal(true); expect(copy.baz).to.equal(Date.parse("2012-12-12 00:00:00")); }); }); }); class ProjectionSpecProjection extends Projection { constructor(private _foo: string, private _bar: number, private _boo: boolean, private _baz: Date) { super(); } public get foo(): string { return this._foo; } public get bar(): number { return this._bar; } public get boo(): boolean { return this._boo; } public get baz(): Date { return this._baz; } }
mit
ksss/text2svg
lib/text2svg/typography.rb
7203
require 'cgi' require 'freetype' require 'text2svg/option' module Text2svg class OptionError < StandardError end class Typography WHITESPACE = /[[:space:]]/ IDEOGRAPHIC_SPACE = /[\u{3000}]/ NEW_LINE = /[\u{000A}]/ NOTDEF_GLYPH_ID = 0 INTER_CHAR_SPACE_DIV = 50r class << self def build(text, option) if Hash === option option = Option.from_hash(option) end content = path(text, option) svg = %(<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 #{content.width} #{content.height}">\n) svg << "<title>#{CGI.escapeHTML(text.to_s)}</title>\n" svg << content.data svg << "</svg>\n" Content.new(svg, content.width, content.height, content.notdef_indexes) end def path(text, option) if Hash === option option = Option.from_hash(option) end text = String.try_convert(text) return Content.new('', 0, 0, []) if text.nil? || text.empty? option.encoding ||= Encoding::UTF_8 option.text_align ||= :left text.force_encoding(option.encoding).encode!(Encoding::UTF_8) notdef_indexes = [] unless option.font raise OptionError, 'should set `font\' option' end char_sizes = option.char_size.split(',').map(&:to_i) unless char_sizes.length == 4 raise OptionError, 'char-size option should be four integer values' end FreeType::API::Font.open(File.expand_path(option.font)) do |f| f.set_char_size(*char_sizes) lines = [] line = [] lines << line min_hori_bearing_x_by_line = [0] space_width = f.glyph(' '.freeze).char_width text.each_char.with_index do |char, index| if NEW_LINE.match char min_hori_bearing_x_by_line[-1] = min_hori_bearing_x(line) min_hori_bearing_x_by_line << 0 line = [] lines << line next end glyph_id = f.char_index(char) glyph = if glyph_id == 0 notdef_indexes << index f.notdef else f.glyph(char) end if glyph.outline.tags.empty? notdef_indexes << index glyph = f.notdef end glyph.bold if option.bold glyph.italic if option.italic metrics = FreeType::C::FT_Glyph_Metrics.new is_draw = if IDEOGRAPHIC_SPACE.match char metrics[:width] = space_width * 2r metrics[:height] = 0 metrics[:horiBearingX] = space_width * 2r metrics[:horiBearingY] = 0 metrics[:horiAdvance] = space_width * 2r metrics[:vertBearingX] = 0 metrics[:vertBearingY] = 0 metrics[:vertAdvance] = 0 false elsif WHITESPACE.match char metrics[:width] = space_width metrics[:height] = 0 metrics[:horiBearingX] = space_width metrics[:horiBearingY] = 0 metrics[:horiAdvance] = space_width metrics[:vertBearingX] = 0 metrics[:vertBearingY] = 0 metrics[:vertAdvance] = 0 false else FreeType::C::FT_Glyph_Metrics.members.each do |m| metrics[m] = glyph.metrics[m] end true end line << CharSet.new(char, metrics, is_draw, glyph.outline.svg_path_data) end min_hori_bearing_x_by_line[-1] = min_hori_bearing_x(line) inter_char_space = space_width / INTER_CHAR_SPACE_DIV min_hori_bearing_x_all = min_hori_bearing_x_by_line.min width_by_line = lines.map do |line| before_char = nil if line.empty?.! line.map { |cs| width = if cs.equal?(line.last) cs.metrics[:width] + cs.metrics[:horiBearingX] else cs.metrics[:horiAdvance] end w = width + f.kerning_unfitted(before_char, cs.char).x w.tap { before_char = cs.char } }.inject(:+) + (line.length - 1) * inter_char_space - min_hori_bearing_x_all else 0 end end max_width = width_by_line.max y = 0r output = '' output << %(<g #{option.attribute}>\n) if option.attribute lines.zip(width_by_line).each_with_index do |(line, line_width), index| x = 0r y += if index == 0 f.face[:size][:metrics][:ascender] * option.scale else f.line_height * option.scale end before_char = nil case option.text_align.to_sym when :center x += (max_width - line_width) / 2r * option.scale when :right x += (max_width - line_width) * option.scale when :left # nothing else warn 'text_align must be left,right or center' end output << %!<g transform="matrix(1,0,0,1,0,#{y.round})">\n! x -= min_hori_bearing_x_all * option.scale sr = option.scale.rationalize line.each do |cs| x += f.kerning_unfitted(before_char, cs.char).x * option.scale if cs.draw? d = cs.outline2d.map do |cmd, *points| [ cmd, *points.map { |i| i.rationalize * sr }.map do |i| i.denominator == 1 ? i.to_i : i.to_f end, ] end output << %! <path transform="matrix(1,0,0,1,#{x.round},0)" d="#{d.join(' '.freeze)}"/>\n! end x += cs.metrics[:horiAdvance] * option.scale x += inter_char_space * option.scale if cs != line.last before_char = cs.char end output << "</g>\n".freeze end output << "</g>\n".freeze if option.attribute option_width = 0 option_width += (space_width / 1.5 * option.scale) if option.italic Content.new( output, ((max_width + option_width) * option.scale).ceil, (y - f.face[:size][:metrics][:descender] * 1.2 * option.scale).ceil, notdef_indexes, ) end end private def min_hori_bearing_x(line) return 0 if line.empty? point = 0 bearings = line.map do |cs| (cs.metrics[:horiBearingX] + point).tap do point += cs.metrics[:horiAdvance] end end bearings.min end end end CharSet = Struct.new(:char, :metrics, :is_draw, :outline2d) do def draw? is_draw end end Content = Struct.new(:data, :width, :height, :notdef_indexes) do def to_s data end end end
mit
magrumadha/ekuesioner
js/login.js
1662
// Set Message Error Untuk OnLoad function customValidLoad() { i = document.getElementById("username"); j = document.getElementById("password"); checkValidUserName(i); checkValidPassword(j); } function checkValidUserName(input) { if (input.value == "") { input.setCustomValidity("Masukan username"); } else if (input.value.length < 4) { input.setCustomValidity("Minimum input 4 character"); } else { input.setCustomValidity(''); } } function checkValidPassword(input) { if (input.value == "") { input.setCustomValidity("Masukan Password"); } else { input.setCustomValidity(''); } } function loginuser() { // setTimeout(function () { // console.log(document.getElementById("fm-login").checkValidity()); //}, 300); //console.log(document.getElementById("fm-login").checkValidity()); //document.getElementById("fm-login").submit(); //alert("output"); username = gv("username"); password = gv("password"); st_login = "<div class='alert-box notice'><span>Proses: </span>Logging In</div></span>"; st_success = "<div class='alert-box success'><span>Bravo: </span>Login Success</div>"; st_failed = "<div class='alert-box error'><span>Error: </span>Login Failed. Check your username and password</div>"; si("status", st_login); //html = ajaxdata("GET","action.php?action=login&username="+username+"&password="+password); html = ajaxdata("POST", "action.php?action=login", "username=" + username + "&password=" + password); //alert(html); if (html == 'success') { si("status", st_success); var delay = 1000; setTimeout(function() { window.location.href = "home.php"; }, delay); } else { si("status", st_failed); } }
mit
arturictus/hash_map
spec/examples/collections_spec.rb
1649
require 'spec_helper' describe 'Collections' do class Things < HashMap::Base properties :name, :age end class Collections < HashMap::Base collection :things, mapper: Things collection :numbers, mapper: proc { |n| n.to_i } end let(:original) do { things: [ { name: 'one thing', age: 12 }, { name: 'another thing', age: 8 } ], numbers: %w(1 2 3) } end subject { Collections.map(original) } describe ':things' do it { expect(subject[:things]).to match_array original[:things] } end describe ':numbers' do it { expect(subject[:numbers]).to match_array original[:numbers].map(&:to_i) } end describe 'with a single element' do let(:thing) { { name: 'one thing', age: 12 } } let(:original){ { things: thing } } it { expect(subject[:things]).to match_array [ thing ] } end describe 'when is nil' do let(:original){ { things: nil } } it { expect(subject[:things]).to eq [] } end describe 'when does not exist' do let(:original){ { } } it { expect(subject[:things]).to eq [] } end describe 'multiple blocks' do class ComplexCollection < HashMap::Base from_child :things do from_child :inside do to_child :collection do collection :numbers, mapper: proc { |n| n.to_i } end end end end let(:original) do { things: { inside: { numbers: %w(1 2 3) } } } end subject { ComplexCollection.map(original) } it { expect(subject[:collection][:numbers]).to match_array [1, 2, 3] } end end
mit
hackathongi/2015-recomanacio
recommend/index.php
897
<?php $description = htmlspecialchars($_GET["description"]); $reccomender_id = htmlspecialchars($_GET["reccomender_id"]); $job_id = htmlspecialchars($_GET["job_id"]); $application_id = htmlspecialchars($_GET["application_id"]); $url = 'https://api.wallyjobs.com/recommendations' ; $post = array( 'description' => $description, 'reccomender_id' => $reccomender_id, 'job_id' => $job_id, 'application_id' => $application_id ); $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERSION, 3); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $result = curl_exec($ch); curl_close($ch); echo $result; ?>
mit
gdb/doom-py
doom_py/vizdoom_src/src/v_video.cpp
41371
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // $Id:$ // // Copyright (C) 1993-1996 by id Software, Inc. // // This source is available for distribution and/or modification // only under the terms of the DOOM Source Code License as // published by id Software. All rights reserved. // // The source is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License // for more details. // // $Log:$ // // DESCRIPTION: // Functions to draw patches (by post) directly to screen-> // Functions to blit a block to the screen-> // //----------------------------------------------------------------------------- #include <stdio.h> #include "i_system.h" #include "x86.h" #include "i_video.h" #include "r_state.h" #include "doomdef.h" #include "doomdata.h" #include "doomstat.h" #include "c_console.h" #include "hu_stuff.h" #include "m_argv.h" #include "m_bbox.h" #include "m_swap.h" #include "i_video.h" #include "v_video.h" #include "v_text.h" #include "w_wad.h" #include "c_cvars.h" #include "c_dispatch.h" #include "cmdlib.h" #include "gi.h" #include "templates.h" #include "sbar.h" #include "hardware.h" #include "r_data/r_translate.h" #include "f_wipe.h" #include "m_png.h" #include "colormatcher.h" #include "v_palette.h" #include "r_sky.h" #include "r_utility.h" #include "r_renderer.h" #include "menu/menu.h" #include "r_data/voxels.h" FRenderer *Renderer; IMPLEMENT_ABSTRACT_CLASS (DCanvas) IMPLEMENT_ABSTRACT_CLASS (DFrameBuffer) #if defined(_DEBUG) && defined(_M_IX86) #define DBGBREAK { __asm int 3 } #else #define DBGBREAK #endif class DDummyFrameBuffer : public DFrameBuffer { DECLARE_CLASS (DDummyFrameBuffer, DFrameBuffer); public: DDummyFrameBuffer (int width, int height) : DFrameBuffer (0, 0) { Width = width; Height = height; } bool Lock(bool buffered) { DBGBREAK; return false; } void Update() { DBGBREAK; } PalEntry *GetPalette() { DBGBREAK; return NULL; } void GetFlashedPalette(PalEntry palette[256]) { DBGBREAK; } void UpdatePalette() { DBGBREAK; } bool SetGamma(float gamma) { Gamma = gamma; return true; } bool SetFlash(PalEntry rgb, int amount) { DBGBREAK; return false; } void GetFlash(PalEntry &rgb, int &amount) { DBGBREAK; } int GetPageCount() { DBGBREAK; return 0; } bool IsFullscreen() { DBGBREAK; return 0; } #ifdef _WIN32 void PaletteChanged() {} int QueryNewPalette() { return 0; } bool Is8BitMode() { return false; } #endif float Gamma; }; IMPLEMENT_ABSTRACT_CLASS (DDummyFrameBuffer) // SimpleCanvas is not really abstract, but this macro does not // try to generate a CreateNew() function. IMPLEMENT_ABSTRACT_CLASS (DSimpleCanvas) class FPaletteTester : public FTexture { public: FPaletteTester (); const BYTE *GetColumn(unsigned int column, const Span **spans_out); const BYTE *GetPixels(); void Unload(); bool CheckModified(); void SetTranslation(int num); protected: BYTE Pixels[16*16]; int CurTranslation; int WantTranslation; static const Span DummySpan[2]; void MakeTexture(); }; const FTexture::Span FPaletteTester::DummySpan[2] = { { 0, 16 }, { 0, 0 } }; int DisplayWidth, DisplayHeight, DisplayBits; FFont *SmallFont, *SmallFont2, *BigFont, *ConFont, *IntermissionFont; extern "C" { DWORD Col2RGB8[65][256]; DWORD *Col2RGB8_LessPrecision[65]; DWORD Col2RGB8_Inverse[65][256]; ColorTable32k RGB32k; } static DWORD Col2RGB8_2[63][256]; // [RH] The framebuffer is no longer a mere byte array. // There's also only one, not four. DFrameBuffer *screen; CVAR (Int, vid_defwidth, 640, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) CVAR (Int, vid_defheight, 480, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) CVAR (Int, vid_defbits, 8, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) CVAR (Bool, vid_fps, false, 0) CVAR (Bool, ticker, false, 0) CVAR (Int, vid_showpalette, 0, 0) CUSTOM_CVAR (Bool, vid_vsync, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (screen != NULL) { screen->SetVSync (*self); } } CUSTOM_CVAR (Int, vid_refreshrate, 0, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (screen != NULL) { screen->NewRefreshRate(); } } CUSTOM_CVAR (Float, dimamount, -1.f, CVAR_ARCHIVE) { if (self < 0.f && self != -1.f) { self = -1.f; } else if (self > 1.f) { self = 1.f; } } CVAR (Color, dimcolor, 0xffd700, CVAR_ARCHIVE) // [RH] Set true when vid_setmode command has been executed bool setmodeneeded = false; // [RH] Resolution to change to when setmodeneeded is true int NewWidth, NewHeight, NewBits; // // V_MarkRect // void V_MarkRect (int x, int y, int width, int height) { } DCanvas *DCanvas::CanvasChain = NULL; //========================================================================== // // DCanvas Constructor // //========================================================================== DCanvas::DCanvas (int _width, int _height) { // Init member vars Buffer = NULL; LockCount = 0; Width = _width; Height = _height; // Add to list of active canvases Next = CanvasChain; CanvasChain = this; } //========================================================================== // // DCanvas Destructor // //========================================================================== DCanvas::~DCanvas () { // Remove from list of active canvases DCanvas *probe = CanvasChain, **prev; prev = &CanvasChain; probe = CanvasChain; while (probe != NULL) { if (probe == this) { *prev = probe->Next; break; } prev = &probe->Next; probe = probe->Next; } } //========================================================================== // // DCanvas :: IsValid // //========================================================================== bool DCanvas::IsValid () { // A nun-subclassed DCanvas is never valid return false; } //========================================================================== // // DCanvas :: FlatFill // // Fill an area with a texture. If local_origin is false, then the origin // used for the wrapping is (0,0). Otherwise, (left,right) is used. // //========================================================================== void DCanvas::FlatFill (int left, int top, int right, int bottom, FTexture *src, bool local_origin) { int w = src->GetWidth(); int h = src->GetHeight(); // Repeatedly draw the texture, left-to-right, top-to-bottom. for (int y = local_origin ? top : (top / h * h); y < bottom; y += h) { for (int x = local_origin ? left : (left / w * w); x < right; x += w) { DrawTexture (src, x, y, DTA_ClipLeft, left, DTA_ClipRight, right, DTA_ClipTop, top, DTA_ClipBottom, bottom, DTA_TopOffset, 0, DTA_LeftOffset, 0, TAG_DONE); } } } //========================================================================== // // DCanvas :: Dim // // Applies a colored overlay to the entire screen, with the opacity // determined by the dimamount cvar. // //========================================================================== void DCanvas::Dim (PalEntry color) { PalEntry dimmer; float amount; if (dimamount >= 0) { dimmer = PalEntry(dimcolor); amount = dimamount; } else { dimmer = gameinfo.dimcolor; amount = gameinfo.dimamount; } if (gameinfo.gametype == GAME_Hexen && gamestate == GS_DEMOSCREEN) { // On the Hexen title screen, the default dimming is not // enough to make the menus readable. amount = MIN<float> (1.f, amount*2.f); } // Add the cvar's dimming on top of the color passed to the function if (color.a != 0) { float dim[4] = { color.r/255.f, color.g/255.f, color.b/255.f, color.a/255.f }; V_AddBlend (dimmer.r/255.f, dimmer.g/255.f, dimmer.b/255.f, amount, dim); dimmer = PalEntry (BYTE(dim[0]*255), BYTE(dim[1]*255), BYTE(dim[2]*255)); amount = dim[3]; } Dim (dimmer, amount, 0, 0, Width, Height); } //========================================================================== // // DCanvas :: Dim // // Applies a colored overlay to an area of the screen. // //========================================================================== void DCanvas::Dim (PalEntry color, float damount, int x1, int y1, int w, int h) { if (damount == 0.f) return; DWORD *bg2rgb; DWORD fg; int gap; BYTE *spot; int x, y; if (x1 >= Width || y1 >= Height) { return; } if (x1 + w > Width) { w = Width - x1; } if (y1 + h > Height) { h = Height - y1; } if (w <= 0 || h <= 0) { return; } { int amount; amount = (int)(damount * 64); bg2rgb = Col2RGB8[64-amount]; fg = (((color.r * amount) >> 4) << 20) | ((color.g * amount) >> 4) | (((color.b * amount) >> 4) << 10); } spot = Buffer + x1 + y1*Pitch; gap = Pitch - w; for (y = h; y != 0; y--) { for (x = w; x != 0; x--) { DWORD bg; bg = bg2rgb[(*spot)&0xff]; bg = (fg+bg) | 0x1f07c1f; *spot = RGB32k.All[bg&(bg>>15)]; spot++; } spot += gap; } } //========================================================================== // // DCanvas :: GetScreenshotBuffer // // Returns a buffer containing the most recently displayed frame. The // width and height of this buffer are the same as the canvas. // //========================================================================== void DCanvas::GetScreenshotBuffer(const BYTE *&buffer, int &pitch, ESSType &color_type) { Lock(true); buffer = GetBuffer(); pitch = GetPitch(); color_type = SS_PAL; } //========================================================================== // // DCanvas :: ReleaseScreenshotBuffer // // Releases the buffer obtained through GetScreenshotBuffer. These calls // must not be nested. // //========================================================================== void DCanvas::ReleaseScreenshotBuffer() { Unlock(); } //========================================================================== // // V_GetColorFromString // // Passed a string of the form "#RGB", "#RRGGBB", "R G B", or "RR GG BB", // returns a number representing that color. If palette is non-NULL, the // index of the best match in the palette is returned, otherwise the // RRGGBB value is returned directly. // //========================================================================== int V_GetColorFromString (const DWORD *palette, const char *cstr) { int c[3], i, p; char val[3]; val[2] = '\0'; // Check for HTML-style #RRGGBB or #RGB color string if (cstr[0] == '#') { size_t len = strlen (cstr); if (len == 7) { // Extract each eight-bit component into c[]. for (i = 0; i < 3; ++i) { val[0] = cstr[1 + i*2]; val[1] = cstr[2 + i*2]; c[i] = ParseHex (val); } } else if (len == 4) { // Extract each four-bit component into c[], expanding to eight bits. for (i = 0; i < 3; ++i) { val[1] = val[0] = cstr[1 + i]; c[i] = ParseHex (val); } } else { // Bad HTML-style; pretend it's black. c[2] = c[1] = c[0] = 0; } } else { if (strlen(cstr) == 6) { char *p; int color = strtol(cstr, &p, 16); if (*p == 0) { // RRGGBB string c[0] = (color & 0xff0000) >> 16; c[1] = (color & 0xff00) >> 8; c[2] = (color & 0xff); } else goto normal; } else { normal: // Treat it as a space-delimited hexadecimal string for (i = 0; i < 3; ++i) { // Skip leading whitespace while (*cstr <= ' ' && *cstr != '\0') { cstr++; } // Extract a component and convert it to eight-bit for (p = 0; *cstr > ' '; ++p, ++cstr) { if (p < 2) { val[p] = *cstr; } } if (p == 0) { c[i] = 0; } else { if (p == 1) { val[1] = val[0]; } c[i] = ParseHex (val); } } } } if (palette) return ColorMatcher.Pick (c[0], c[1], c[2]); else return MAKERGB(c[0], c[1], c[2]); } //========================================================================== // // V_GetColorStringByName // // Searches for the given color name in x11r6rgb.txt and returns an // HTML-ish "#RRGGBB" string for it if found or the empty string if not. // //========================================================================== FString V_GetColorStringByName (const char *name) { FMemLump rgbNames; char *rgbEnd; char *rgb, *endp; int rgblump; int c[3], step; size_t namelen; if (Wads.GetNumLumps()==0) return FString(); rgblump = Wads.CheckNumForName ("X11R6RGB"); if (rgblump == -1) { Printf ("X11R6RGB lump not found\n"); return FString(); } rgbNames = Wads.ReadLump (rgblump); rgb = (char *)rgbNames.GetMem(); rgbEnd = rgb + Wads.LumpLength (rgblump); step = 0; namelen = strlen (name); while (rgb < rgbEnd) { // Skip white space if (*rgb <= ' ') { do { rgb++; } while (rgb < rgbEnd && *rgb <= ' '); } else if (step == 0 && *rgb == '!') { // skip comment lines do { rgb++; } while (rgb < rgbEnd && *rgb != '\n'); } else if (step < 3) { // collect RGB values c[step++] = strtoul (rgb, &endp, 10); if (endp == rgb) { break; } rgb = endp; } else { // Check color name endp = rgb; // Find the end of the line while (endp < rgbEnd && *endp != '\n') endp++; // Back up over any whitespace while (endp > rgb && *endp <= ' ') endp--; if (endp == rgb) { break; } size_t checklen = ++endp - rgb; if (checklen == namelen && strnicmp (rgb, name, checklen) == 0) { FString descr; descr.Format ("#%02x%02x%02x", c[0], c[1], c[2]); return descr; } rgb = endp; step = 0; } } if (rgb < rgbEnd) { Printf ("X11R6RGB lump is corrupt\n"); } return FString(); } //========================================================================== // // V_GetColor // // Works like V_GetColorFromString(), but also understands X11 color names. // //========================================================================== int V_GetColor (const DWORD *palette, const char *str) { FString string = V_GetColorStringByName (str); int res; if (!string.IsEmpty()) { res = V_GetColorFromString (palette, string); } else { res = V_GetColorFromString (palette, str); } return res; } //========================================================================== // // BuildTransTable // // Build the tables necessary for blending // //========================================================================== static void BuildTransTable (const PalEntry *palette) { int r, g, b; // create the RGB555 lookup table for (r = 0; r < 32; r++) for (g = 0; g < 32; g++) for (b = 0; b < 32; b++) RGB32k.RGB[r][g][b] = ColorMatcher.Pick ((r<<3)|(r>>2), (g<<3)|(g>>2), (b<<3)|(b>>2)); int x, y; // create the swizzled palette for (x = 0; x < 65; x++) for (y = 0; y < 256; y++) Col2RGB8[x][y] = (((palette[y].r*x)>>4)<<20) | ((palette[y].g*x)>>4) | (((palette[y].b*x)>>4)<<10); // create the swizzled palette with the lsb of red and blue forced to 0 // (for green, a 1 is okay since it never gets added into) for (x = 1; x < 64; x++) { Col2RGB8_LessPrecision[x] = Col2RGB8_2[x-1]; for (y = 0; y < 256; y++) { Col2RGB8_2[x-1][y] = Col2RGB8[x][y] & 0x3feffbff; } } Col2RGB8_LessPrecision[0] = Col2RGB8[0]; Col2RGB8_LessPrecision[64] = Col2RGB8[64]; // create the inverse swizzled palette for (x = 0; x < 65; x++) for (y = 0; y < 256; y++) { Col2RGB8_Inverse[x][y] = (((((255-palette[y].r)*x)>>4)<<20) | (((255-palette[y].g)*x)>>4) | ((((255-palette[y].b)*x)>>4)<<10)) & 0x3feffbff; } } //========================================================================== // // DCanvas :: CalcGamma // //========================================================================== void DCanvas::CalcGamma (float gamma, BYTE gammalookup[256]) { // I found this formula on the web at // <http://panda.mostang.com/sane/sane-gamma.html>, // but that page no longer exits. double invgamma = 1.f / gamma; int i; for (i = 0; i < 256; i++) { gammalookup[i] = (BYTE)(255.0 * pow (i / 255.0, invgamma)); } } //========================================================================== // // DSimpleCanvas Constructor // // A simple canvas just holds a buffer in main memory. // //========================================================================== DSimpleCanvas::DSimpleCanvas (int width, int height) : DCanvas (width, height) { // Making the pitch a power of 2 is very bad for performance // Try to maximize the number of cache lines that can be filled // for each column drawing operation by making the pitch slightly // longer than the width. The values used here are all based on // empirical evidence. if (width <= 640) { // For low resolutions, just keep the pitch the same as the width. // Some speedup can be seen using the technique below, but the speedup // is so marginal that I don't consider it worthwhile. Pitch = width; } else { // If we couldn't figure out the CPU's L1 cache line size, assume // it's 32 bytes wide. if (CPU.DataL1LineSize == 0) { CPU.DataL1LineSize = 32; } // The Athlon and P3 have very different caches, apparently. // I am going to generalize the Athlon's performance to all AMD // processors and the P3's to all non-AMD processors. I don't know // how smart that is, but I don't have a vast plethora of // processors to test with. if (CPU.bIsAMD) { Pitch = width + CPU.DataL1LineSize; } else { Pitch = width + MAX(0, CPU.DataL1LineSize - 8); } } MemBuffer = new BYTE[Pitch * height]; memset (MemBuffer, 0, Pitch * height); } //========================================================================== // // DSimpleCanvas Destructor // //========================================================================== DSimpleCanvas::~DSimpleCanvas () { if (MemBuffer != NULL) { delete[] MemBuffer; MemBuffer = NULL; } } //========================================================================== // // DSimpleCanvas :: IsValid // //========================================================================== bool DSimpleCanvas::IsValid () { return (MemBuffer != NULL); } //========================================================================== // // DSimpleCanvas :: Lock // //========================================================================== bool DSimpleCanvas::Lock (bool) { if (LockCount == 0) { Buffer = MemBuffer; } LockCount++; return false; // System surfaces are never lost } //========================================================================== // // DSimpleCanvas :: Unlock // //========================================================================== void DSimpleCanvas::Unlock () { if (--LockCount <= 0) { LockCount = 0; Buffer = NULL; // Enforce buffer access only between Lock/Unlock } } //========================================================================== // // DFrameBuffer Constructor // // A frame buffer canvas is the most common and represents the image that // gets drawn to the screen. // //========================================================================== DFrameBuffer::DFrameBuffer (int width, int height) : DSimpleCanvas (width, height) { LastMS = LastSec = FrameCount = LastCount = LastTic = 0; Accel2D = false; } //========================================================================== // // DFrameBuffer :: DrawRateStuff // // Draws the fps counter, dot ticker, and palette debug. // //========================================================================== void DFrameBuffer::DrawRateStuff () { // Draws frame time and cumulative fps if (vid_fps) { DWORD ms = I_FPSTime(); DWORD howlong = ms - LastMS; if ((signed)howlong >= 0) { char fpsbuff[40]; int chars; int rate_x; chars = mysnprintf (fpsbuff, countof(fpsbuff), "%2u ms (%3u fps)", howlong, LastCount); rate_x = Width - ConFont->StringWidth(&fpsbuff[0]); Clear (rate_x, 0, Width, ConFont->GetHeight(), GPalette.BlackIndex, 0); DrawText (ConFont, CR_WHITE, rate_x, 0, (char *)&fpsbuff[0], TAG_DONE); DWORD thisSec = ms/1000; if (LastSec < thisSec) { LastCount = FrameCount / (thisSec - LastSec); LastSec = thisSec; FrameCount = 0; } FrameCount++; } LastMS = ms; } // draws little dots on the bottom of the screen if (ticker) { int i = I_GetTime(false); int tics = i - LastTic; BYTE *buffer = GetBuffer(); LastTic = i; if (tics > 20) tics = 20; // Buffer can be NULL if we're doing hardware accelerated 2D if (buffer != NULL) { buffer += (GetHeight()-1) * GetPitch(); for (i = 0; i < tics*2; i += 2) buffer[i] = 0xff; for ( ; i < 20*2; i += 2) buffer[i] = 0x00; } else { for (i = 0; i < tics*2; i += 2) Clear(i, Height-1, i+1, Height, 255, 0); for ( ; i < 20*2; i += 2) Clear(i, Height-1, i+1, Height, 0, 0); } } // draws the palette for debugging if (vid_showpalette) { // This used to just write the palette to the display buffer. // With hardware-accelerated 2D, that doesn't work anymore. // Drawing it as a texture does and continues to show how // well the PalTex shader is working. static FPaletteTester palette; palette.SetTranslation(vid_showpalette); DrawTexture(&palette, 0, 0, DTA_DestWidth, 16*7, DTA_DestHeight, 16*7, DTA_Masked, false, TAG_DONE); } } //========================================================================== // // FPaleteTester Constructor // // This is just a 16x16 image with every possible color value. // //========================================================================== FPaletteTester::FPaletteTester() { Width = 16; Height = 16; WidthBits = 4; HeightBits = 4; WidthMask = 15; CurTranslation = 0; WantTranslation = 1; MakeTexture(); } //========================================================================== // // FPaletteTester :: CheckModified // //========================================================================== bool FPaletteTester::CheckModified() { return CurTranslation != WantTranslation; } //========================================================================== // // FPaletteTester :: SetTranslation // //========================================================================== void FPaletteTester::SetTranslation(int num) { if (num >= 1 && num <= 9) { WantTranslation = num; } } //========================================================================== // // FPaletteTester :: Unload // //========================================================================== void FPaletteTester::Unload() { } //========================================================================== // // FPaletteTester :: GetColumn // //========================================================================== const BYTE *FPaletteTester::GetColumn (unsigned int column, const Span **spans_out) { if (CurTranslation != WantTranslation) { MakeTexture(); } column &= 15; if (spans_out != NULL) { *spans_out = DummySpan; } return Pixels + column*16; } //========================================================================== // // FPaletteTester :: GetPixels // //========================================================================== const BYTE *FPaletteTester::GetPixels () { if (CurTranslation != WantTranslation) { MakeTexture(); } return Pixels; } //========================================================================== // // FPaletteTester :: MakeTexture // //========================================================================== void FPaletteTester::MakeTexture() { int i, j, k, t; BYTE *p; t = WantTranslation; p = Pixels; k = 0; for (i = 0; i < 16; ++i) { for (j = 0; j < 16; ++j) { *p++ = (t > 1) ? translationtables[TRANSLATION_Standard][t - 2]->Remap[k] : k; k += 16; } k -= 255; } CurTranslation = t; } //========================================================================== // // DFrameBuffer :: CopyFromBuff // // Copies pixels from main memory to video memory. This is only used by // DDrawFB. // //========================================================================== void DFrameBuffer::CopyFromBuff (BYTE *src, int srcPitch, int width, int height, BYTE *dest) { if (Pitch == width && Pitch == Width && srcPitch == width) { memcpy (dest, src, Width * Height); } else { for (int y = 0; y < height; y++) { memcpy (dest, src, width); dest += Pitch; src += srcPitch; } } } //========================================================================== // // DFrameBuffer :: SetVSync // // Turns vertical sync on and off, if supported. // //========================================================================== void DFrameBuffer::SetVSync (bool vsync) { } //========================================================================== // // DFrameBuffer :: NewRefreshRate // // Sets the fullscreen display to the new refresh rate in vid_refreshrate, // if possible. // //========================================================================== void DFrameBuffer::NewRefreshRate () { } //========================================================================== // // DFrameBuffer :: SetBlendingRect // // Defines the area of the screen containing the 3D view. // //========================================================================== void DFrameBuffer::SetBlendingRect (int x1, int y1, int x2, int y2) { } //========================================================================== // // DFrameBuffer :: Begin2D // // Signal that 3D rendering is complete, and the rest of the operations on // the canvas until Unlock() will be 2D ones. // //========================================================================== bool DFrameBuffer::Begin2D (bool copy3d) { return false; } //========================================================================== // // DFrameBuffer :: DrawBlendingRect // // In hardware 2D modes, the blending rect needs to be drawn separately // from transferring the 3D scene to video memory, because the weapon // sprite is drawn on top of that. // //========================================================================== void DFrameBuffer::DrawBlendingRect() { } //========================================================================== // // DFrameBuffer :: CreateTexture // // Creates a native texture for a game texture, if supported. // //========================================================================== FNativeTexture *DFrameBuffer::CreateTexture(FTexture *gametex, bool wrapping) { return NULL; } //========================================================================== // // DFrameBuffer :: CreatePalette // // Creates a native palette from a remap table, if supported. // //========================================================================== FNativePalette *DFrameBuffer::CreatePalette(FRemapTable *remap) { return NULL; } //========================================================================== // // DFrameBuffer :: WipeStartScreen // // Grabs a copy of the screen currently displayed to serve as the initial // frame of a screen wipe. Also determines which screenwipe will be // performed. // //========================================================================== bool DFrameBuffer::WipeStartScreen(int type) { return wipe_StartScreen(type); } //========================================================================== // // DFrameBuffer :: WipeEndScreen // // Grabs a copy of the most-recently drawn, but not yet displayed, screen // to serve as the final frame of a screen wipe. // //========================================================================== void DFrameBuffer::WipeEndScreen() { wipe_EndScreen(); Unlock(); } //========================================================================== // // DFrameBuffer :: WipeDo // // Draws one frame of a screenwipe. Should be called no more than 35 // times per second. If called less than that, ticks indicates how many // ticks have passed since the last call. // //========================================================================== bool DFrameBuffer::WipeDo(int ticks) { Lock(true); return wipe_ScreenWipe(ticks); } //========================================================================== // // DFrameBuffer :: WipeCleanup // //========================================================================== void DFrameBuffer::WipeCleanup() { wipe_Cleanup(); } //=========================================================================== // // Create texture hitlist // //=========================================================================== void DFrameBuffer::GetHitlist(BYTE *hitlist) { BYTE *spritelist; int i; spritelist = new BYTE[sprites.Size()]; // Precache textures (and sprites). memset (spritelist, 0, sprites.Size()); { AActor *actor; TThinkerIterator<AActor> iterator; while ( (actor = iterator.Next ()) ) spritelist[actor->sprite] = 1; } for (i = (int)(sprites.Size () - 1); i >= 0; i--) { if (spritelist[i]) { int j, k; for (j = 0; j < sprites[i].numframes; j++) { const spriteframe_t *frame = &SpriteFrames[sprites[i].spriteframes + j]; for (k = 0; k < 16; k++) { FTextureID pic = frame->Texture[k]; if (pic.isValid()) { hitlist[pic.GetIndex()] = FTextureManager::HIT_Sprite; } } } } } delete[] spritelist; for (i = numsectors - 1; i >= 0; i--) { hitlist[sectors[i].GetTexture(sector_t::floor).GetIndex()] = hitlist[sectors[i].GetTexture(sector_t::ceiling).GetIndex()] |= FTextureManager::HIT_Flat; } for (i = numsides - 1; i >= 0; i--) { hitlist[sides[i].GetTexture(side_t::top).GetIndex()] = hitlist[sides[i].GetTexture(side_t::mid).GetIndex()] = hitlist[sides[i].GetTexture(side_t::bottom).GetIndex()] |= FTextureManager::HIT_Wall; } // Sky texture is always present. // Note that F_SKY1 is the name used to // indicate a sky floor/ceiling as a flat, // while the sky texture is stored like // a wall texture, with an episode dependant // name. if (sky1texture.isValid()) { hitlist[sky1texture.GetIndex()] |= FTextureManager::HIT_Sky; } if (sky2texture.isValid()) { hitlist[sky2texture.GetIndex()] |= FTextureManager::HIT_Sky; } } //========================================================================== // // DFrameBuffer :: GameRestart // //========================================================================== void DFrameBuffer::GameRestart() { } //=========================================================================== // // // //=========================================================================== FNativePalette::~FNativePalette() { } FNativeTexture::~FNativeTexture() { } bool FNativeTexture::CheckWrapping(bool wrapping) { return true; } CCMD(clean) { Printf ("CleanXfac: %d\nCleanYfac: %d\n", CleanXfac, CleanYfac); } // // V_SetResolution // bool V_DoModeSetup (int width, int height, int bits) { DFrameBuffer *buff = I_SetMode (width, height, screen); int cx1, cx2; if (buff == NULL) { return false; } screen = buff; GC::WriteBarrier(screen); screen->SetGamma (Gamma); // Load fonts now so they can be packed into textures straight away, // if D3DFB is being used for the display. FFont::StaticPreloadFonts(); V_CalcCleanFacs(320, 200, width, height, &CleanXfac, &CleanYfac, &cx1, &cx2); CleanWidth = width / CleanXfac; CleanHeight = height / CleanYfac; assert(CleanWidth >= 320); assert(CleanHeight >= 200); if (width < 800 || width >= 960) { if (cx1 < cx2) { // Special case in which we don't need to scale down. CleanXfac_1 = CleanYfac_1 = cx1; } else { CleanXfac_1 = MAX(CleanXfac - 1, 1); CleanYfac_1 = MAX(CleanYfac - 1, 1); // On larger screens this is not enough so make sure it's at most 3/4 of the screen's width while (CleanXfac_1 * 320 > screen->GetWidth()*3/4 && CleanXfac_1 > 2) { CleanXfac_1--; CleanYfac_1--; } } CleanWidth_1 = width / CleanXfac_1; CleanHeight_1 = height / CleanYfac_1; } else // if the width is between 800 and 960 the ratio between the screensize and CleanXFac-1 becomes too large. { CleanXfac_1 = CleanXfac; CleanYfac_1 = CleanYfac; CleanWidth_1 = CleanWidth; CleanHeight_1 = CleanHeight; } DisplayWidth = width; DisplayHeight = height; DisplayBits = bits; R_OldBlend = ~0; Renderer->OnModeSet(); M_RefreshModesList (); return true; } void V_CalcCleanFacs (int designwidth, int designheight, int realwidth, int realheight, int *cleanx, int *cleany, int *_cx1, int *_cx2) { int ratio; int cwidth; int cheight; int cx1, cy1, cx2, cy2; ratio = CheckRatio(realwidth, realheight); if (ratio & 4) { cwidth = realwidth; cheight = realheight * BaseRatioSizes[ratio][3] / 48; } else { cwidth = realwidth * BaseRatioSizes[ratio][3] / 48; cheight = realheight; } // Use whichever pair of cwidth/cheight or width/height that produces less difference // between CleanXfac and CleanYfac. cx1 = MAX(cwidth / designwidth, 1); cy1 = MAX(cheight / designheight, 1); cx2 = MAX(realwidth / designwidth, 1); cy2 = MAX(realheight / designheight, 1); if (abs(cx1 - cy1) <= abs(cx2 - cy2)) { // e.g. 640x360 looks better with this. *cleanx = cx1; *cleany = cy1; } else { // e.g. 720x480 looks better with this. *cleanx = cx2; *cleany = cy2; } if (*cleanx < *cleany) *cleany = *cleanx; else *cleanx = *cleany; if (_cx1 != NULL) *_cx1 = cx1; if (_cx2 != NULL) *_cx2 = cx2; } bool IVideo::SetResolution (int width, int height, int bits) { int oldwidth, oldheight; int oldbits; if (screen) { oldwidth = SCREENWIDTH; oldheight = SCREENHEIGHT; oldbits = DisplayBits; } else { // Harmless if screen wasn't allocated oldwidth = width; oldheight = height; oldbits = bits; } I_ClosestResolution (&width, &height, bits); if (!I_CheckResolution (width, height, bits)) { // Try specified resolution if (!I_CheckResolution (oldwidth, oldheight, oldbits)) { // Try previous resolution (if any) return false; } else { width = oldwidth; height = oldheight; bits = oldbits; } } return V_DoModeSetup (width, height, bits); } CCMD (vid_setmode) { bool goodmode = false; int width = 0, height = SCREENHEIGHT; int bits = DisplayBits; if (argv.argc() > 1) { width = atoi (argv[1]); if (argv.argc() > 2) { height = atoi (argv[2]); if (argv.argc() > 3) { bits = atoi (argv[3]); } } } if (width && I_CheckResolution (width, height, bits)) { goodmode = true; } if (goodmode) { // The actual change of resolution will take place // near the beginning of D_Display(). if (gamestate != GS_STARTUP) { setmodeneeded = true; NewWidth = width; NewHeight = height; NewBits = bits; } } else if (width) { Printf ("Unknown resolution %d x %d x %d\n", width, height, bits); } else { Printf ("Usage: vid_setmode <width> <height> <mode>\n"); } } // // V_Init // void V_Init (bool restart) { const char *i; int width, height, bits; atterm (V_Shutdown); // [RH] Initialize palette management InitPalette (); if (!restart) { width = height = bits = 0; if ( (i = Args->CheckValue ("-width")) ) width = atoi (i); if ( (i = Args->CheckValue ("-height")) ) height = atoi (i); if ( (i = Args->CheckValue ("-bits")) ) bits = atoi (i); if (width == 0) { if (height == 0) { width = vid_defwidth; height = vid_defheight; } else { width = (height * 8) / 6; } } else if (height == 0) { height = (width * 6) / 8; } if (bits == 0) { bits = vid_defbits; } screen = new DDummyFrameBuffer (width, height); } // Update screen palette when restarting else { PalEntry *palette = screen->GetPalette (); for (int i = 0; i < 256; ++i) *palette++ = GPalette.BaseColors[i]; screen->UpdatePalette(); } BuildTransTable (GPalette.BaseColors); } void V_Init2() { assert (screen->IsKindOf(RUNTIME_CLASS(DDummyFrameBuffer))); int width = screen->GetWidth(); int height = screen->GetHeight(); float gamma = static_cast<DDummyFrameBuffer *>(screen)->Gamma; { DFrameBuffer *s = screen; screen = NULL; s->ObjectFlags |= OF_YesReallyDelete; delete s; } I_InitGraphics(); I_ClosestResolution (&width, &height, 8); if (!Video->SetResolution (width, height, 8)) I_FatalError ("Could not set resolution to %d x %d x %d", width, height, 8); else Printf ("Resolution: %d x %d\n", SCREENWIDTH, SCREENHEIGHT); screen->SetGamma (gamma); Renderer->RemapVoxels(); FBaseCVar::ResetColors (); C_NewModeAdjust(); M_InitVideoModesMenu(); V_SetBorderNeedRefresh(); setsizeneeded = true; } void V_Shutdown() { if (screen) { DFrameBuffer *s = screen; screen = NULL; s->ObjectFlags |= OF_YesReallyDelete; delete s; } V_ClearFonts(); } EXTERN_CVAR (Bool, vid_tft) CUSTOM_CVAR (Bool, vid_nowidescreen, false, CVAR_GLOBALCONFIG|CVAR_ARCHIVE) { setsizeneeded = true; if (StatusBar != NULL) { StatusBar->ScreenSizeChanged(); } } CUSTOM_CVAR (Int, vid_aspect, 0, CVAR_GLOBALCONFIG|CVAR_ARCHIVE) { setsizeneeded = true; if (StatusBar != NULL) { StatusBar->ScreenSizeChanged(); } } // Tries to guess the physical dimensions of the screen based on the // screen's pixel dimensions. Can return: // 0: 4:3 // 1: 16:9 // 2: 16:10 // 3: 17:10 // 4: 5:4 int CheckRatio (int width, int height, int *trueratio) { int fakeratio = -1; int ratio; if ((vid_aspect >= 1) && (vid_aspect <= 5)) { // [SP] User wants to force aspect ratio; let them. fakeratio = int(vid_aspect); if (fakeratio == 3) { fakeratio = 0; } else if (fakeratio == 5) { fakeratio = 3; } } if (vid_nowidescreen) { if (!vid_tft) { fakeratio = 0; } else { fakeratio = (height * 5/4 == width) ? 4 : 0; } } // If the size is approximately 16:9, consider it so. if (abs (height * 16/9 - width) < 10) { ratio = 1; } // Consider 17:10 as well. else if (abs (height * 17/10 - width) < 10) { ratio = 3; } // 16:10 has more variance in the pixel dimensions. Grr. else if (abs (height * 16/10 - width) < 60) { // 320x200 and 640x400 are always 4:3, not 16:10 if ((width == 320 && height == 200) || (width == 640 && height == 400)) { ratio = 0; } else { ratio = 2; } } // Unless vid_tft is set, 1280x1024 is 4:3, not 5:4. else if (height * 5/4 == width && vid_tft) { ratio = 4; } // Assume anything else is 4:3. (Which is probably wrong these days...) else { ratio = 0; } if (trueratio != NULL) { *trueratio = ratio; } return (fakeratio >= 0) ? fakeratio : ratio; } // First column: Base width // Second column: Base height (used for wall visibility multiplier) // Third column: Psprite offset (needed for "tallscreen" modes) // Fourth column: Width or height multiplier // For widescreen aspect ratio x:y ... // base_width = 240 * x / y // multiplier = 320 / base_width // base_height = 200 * multiplier const int BaseRatioSizes[5][4] = { { 960, 600, 0, 48 }, // 4:3 320, 200, multiplied by three { 1280, 450, 0, 48*3/4 }, // 16:9 426.6667, 150, multiplied by three { 1152, 500, 0, 48*5/6 }, // 16:10 386, 166.6667, multiplied by three { 1224, 471, 0, 48*40/51 }, // 17:10 408, 156.8627, multiplied by three { 960, 640, (int)(6.5*FRACUNIT), 48*15/16 } // 5:4 320, 213.3333, multiplied by three }; void IVideo::DumpAdapters () { Printf("Multi-monitor support unavailable.\n"); } CCMD(vid_listadapters) { if (Video != NULL) Video->DumpAdapters(); }
mit
Dyndrilliac/java-custom-api
api/util/sicxe/SICXE_AssemblerProgram.java
65298
/* * Title: SICXE_AssemblerProgram * Author: Matthew Boyette * Date: 3/27/2015 - 4/23/2015 * * The purpose of this class is to provide a feature complete implementation for a two-pass SIC/XE assembler. * * @formatter:off * TODO: Pass 1 - Relative Symbols vs Absolute Symbols * TODO: Pass 1 - USE Directive and Program Blocks * TODO: Pass 1 - CSECT / EXTDEF / EXTREF * TODO: Pass 1 - Macro Processor * TODO: Pass 2 - Output Generated Object Code to Object File * TODO: Pass 2 - Literals * TODO: Pass 2 - USE Directive and Program Blocks * TODO: Pass 2 - CSECT / EXTDEF / EXTREF * TODO: Pass 2 - Macro Processor * @formatter:on */ package api.util.sicxe; import java.util.Collections; import java.util.List; import api.util.Lexer; import api.util.Support; import api.util.datastructures.SeparateChainingSymbolTable; import edu.princeton.cs.introcs.In; import edu.princeton.cs.introcs.Out; import edu.princeton.cs.introcs.StdOut; public class SICXE_AssemblerProgram extends SimpleSymbolTable { // Directive table contains all possible assembler directives. public static final SeparateChainingSymbolTable<String, SICXE_OpCode> DIRECTIVE_TABLE = SICXE_AssemblerProgram.constructDirectiveTable(new SeparateChainingSymbolTable<String, SICXE_OpCode>()); // Output file extensions. public static final String fileExtLst = ".lst"; public static final String fileExtMid = ".mid"; public static final String fileExtObj = ".obj"; // Instruction table contains all possible program instructions. public static final SeparateChainingSymbolTable<String, SICXE_OpCode> INSTRUCTION_TABLE = SICXE_AssemblerProgram.constructInstructionTable(new SeparateChainingSymbolTable<String, SICXE_OpCode>()); // Register table contains all possible registers. public static final SeparateChainingSymbolTable<String, Byte> REGISTER_TABLE = SICXE_AssemblerProgram.constructRegisterTable(new SeparateChainingSymbolTable<String, Byte>()); protected static final String buildLiteralTableString(final SICXE_AssemblerProgram asmProgram) { // This method builds the literal table string for printing. // First get a list of all the keys in the literal table. List<String> literals = asmProgram.getLiteralTable().keysList(); // Sort the keys so the table can be easily searched visually. Collections.sort(literals); // Create an instance of StringBuilder to build the string. StringBuilder sb = new StringBuilder(); // Append the table header. sb.append("Literal Input\t\tHex Value\t\tLength\tAddress\n"); // Loop through the list of keys. for ( String s : literals ) { SICXE_Literal l = SICXE_AssemblerProgram.resolveLiteral(s, asmProgram); // Append a row for each literal. sb.append(String.format("%-17S", l.getInput()) + "\t" + String.format("%-15S", l.getHexValue()) + "\t" + String.format("%-4d", l.getLength()) + "\t" + String.format("%04X", l.getAddress()) + "\n"); } // Return the literal table string. return sb.toString(); } protected static final String buildSymbolTableString(final SICXE_AssemblerProgram asmProgram) { // This method builds the symbol table string for printing. // First get a list of all the keys in the symbol table. List<String> symbols = asmProgram.getSymbolTable().keysList(); // Sort the keys so the table can be easily searched visually. Collections.sort(symbols); // Create an instance of StringBuilder to build the string. StringBuilder sb = new StringBuilder(); // Append the special values tracked by the pass1 algorithm. sb.append("\nStart:\t\t\t\t" + String.format("%04X", asmProgram.getStartVal()) + "\nEnd:\t\t\t\t" + String.format("%04X", asmProgram.getEndVal()) + "\nLocation Counter:\t" + String.format("%04X", asmProgram.getLocCtr()) + "\nProgram Length:\t\t" + String.format("%04X", asmProgram.getPgmLen()) + "\n"); // Append the table header. sb.append("\nTable Location\tLabel\tAddress\tUse\t\tCSect\n"); // Loop through the list of keys. for ( String s : symbols ) { // Append a row for each symbol. sb.append(String.format("%03d %-7d", asmProgram.getSymbolTable().hash(s), 0) + "\t\t" + String.format("%-6S", s) + "\t" + String.format("%04X", asmProgram.getSymbolTable().get(s)) + "\t" + "main" + "\t" + "main" + "\n"); } // Return the symbol table string. return sb.toString(); } protected static final SeparateChainingSymbolTable<String, SICXE_OpCode> constructDirectiveTable(final SeparateChainingSymbolTable<String, SICXE_OpCode> symTable) { // This table contains all of the possible assembler directives. // Pre-sorted in ascending alphabetical order. symTable.put("BASE", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 1)); symTable.put("BYTE", new SICXE_OpCode((byte) 0, (byte) 1, (byte) 1)); symTable.put("CSECT", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 1)); symTable.put("END", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 1)); symTable.put("EQU", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 1)); symTable.put("EXTDEF", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 1)); symTable.put("EXTREF", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 1)); symTable.put("LTORG", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 0)); symTable.put("NOBASE", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 0)); symTable.put("ORG", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 1)); symTable.put("RESB", new SICXE_OpCode((byte) 0xFF, (byte) 1, (byte) 1)); symTable.put("RESW", new SICXE_OpCode((byte) 0xFF, (byte) 3, (byte) 1)); symTable.put("START", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 1)); symTable.put("USE", new SICXE_OpCode((byte) 0, (byte) 0, (byte) 1)); symTable.put("WORD", new SICXE_OpCode((byte) 0, (byte) 3, (byte) 1)); return symTable; } protected static final SeparateChainingSymbolTable<String, SICXE_OpCode> constructInstructionTable(final SeparateChainingSymbolTable<String, SICXE_OpCode> symTable) { // This table contains all of the possible program instructions. // Pre-sorted in ascending alphabetical order. symTable.put("*ADD", new SICXE_OpCode((byte) 0x18, (byte) 3, (byte) 1)); symTable.put("*AND", new SICXE_OpCode((byte) 0x40, (byte) 3, (byte) 1)); symTable.put("*COMP", new SICXE_OpCode((byte) 0x28, (byte) 3, (byte) 1)); symTable.put("*DIV", new SICXE_OpCode((byte) 0x24, (byte) 3, (byte) 1)); symTable.put("*J", new SICXE_OpCode((byte) 0x3C, (byte) 3, (byte) 1)); symTable.put("*JEQ", new SICXE_OpCode((byte) 0x30, (byte) 3, (byte) 1)); symTable.put("*JGT", new SICXE_OpCode((byte) 0x34, (byte) 3, (byte) 1)); symTable.put("*JLT", new SICXE_OpCode((byte) 0x38, (byte) 3, (byte) 1)); symTable.put("*JSUB", new SICXE_OpCode((byte) 0x48, (byte) 3, (byte) 1)); symTable.put("*LDA", new SICXE_OpCode((byte) 0x00, (byte) 3, (byte) 1)); symTable.put("*LDCH", new SICXE_OpCode((byte) 0x50, (byte) 3, (byte) 1)); symTable.put("*LDL", new SICXE_OpCode((byte) 0x08, (byte) 3, (byte) 1)); symTable.put("*LDX", new SICXE_OpCode((byte) 0x04, (byte) 3, (byte) 1)); symTable.put("*MUL", new SICXE_OpCode((byte) 0x20, (byte) 3, (byte) 1)); symTable.put("*OR", new SICXE_OpCode((byte) 0x44, (byte) 3, (byte) 1)); symTable.put("*RD", new SICXE_OpCode((byte) 0xD8, (byte) 3, (byte) 1)); symTable.put("*RSUB", new SICXE_OpCode((byte) 0x4C, (byte) 3, (byte) 0)); symTable.put("*STA", new SICXE_OpCode((byte) 0x0C, (byte) 3, (byte) 1)); symTable.put("*STCH", new SICXE_OpCode((byte) 0x54, (byte) 3, (byte) 1)); symTable.put("*STL", new SICXE_OpCode((byte) 0x14, (byte) 3, (byte) 1)); symTable.put("*STSW", new SICXE_OpCode((byte) 0xE8, (byte) 3, (byte) 1)); symTable.put("*STX", new SICXE_OpCode((byte) 0x10, (byte) 3, (byte) 1)); symTable.put("*SUB", new SICXE_OpCode((byte) 0x1C, (byte) 3, (byte) 1)); symTable.put("*TD", new SICXE_OpCode((byte) 0xE0, (byte) 3, (byte) 1)); symTable.put("*TIX", new SICXE_OpCode((byte) 0x2C, (byte) 3, (byte) 1)); symTable.put("*WD", new SICXE_OpCode((byte) 0xDC, (byte) 3, (byte) 1)); symTable.put("+ADD", new SICXE_OpCode((byte) 0x18, (byte) 4, (byte) 1)); symTable.put("+ADDF", new SICXE_OpCode((byte) 0x58, (byte) 4, (byte) 1)); symTable.put("+AND", new SICXE_OpCode((byte) 0x40, (byte) 4, (byte) 1)); symTable.put("+COMP", new SICXE_OpCode((byte) 0x28, (byte) 4, (byte) 1)); symTable.put("+COMPF", new SICXE_OpCode((byte) 0x88, (byte) 4, (byte) 1)); symTable.put("+DIV", new SICXE_OpCode((byte) 0x24, (byte) 4, (byte) 1)); symTable.put("+DIVF", new SICXE_OpCode((byte) 0x64, (byte) 4, (byte) 1)); symTable.put("+J", new SICXE_OpCode((byte) 0x3C, (byte) 4, (byte) 1)); symTable.put("+JEQ", new SICXE_OpCode((byte) 0x30, (byte) 4, (byte) 1)); symTable.put("+JGT", new SICXE_OpCode((byte) 0x34, (byte) 4, (byte) 1)); symTable.put("+JLT", new SICXE_OpCode((byte) 0x38, (byte) 4, (byte) 1)); symTable.put("+JSUB", new SICXE_OpCode((byte) 0x48, (byte) 4, (byte) 1)); symTable.put("+LDA", new SICXE_OpCode((byte) 0x00, (byte) 4, (byte) 1)); symTable.put("+LDB", new SICXE_OpCode((byte) 0x68, (byte) 4, (byte) 1)); symTable.put("+LDCH", new SICXE_OpCode((byte) 0x50, (byte) 4, (byte) 1)); symTable.put("+LDF", new SICXE_OpCode((byte) 0x70, (byte) 4, (byte) 1)); symTable.put("+LDL", new SICXE_OpCode((byte) 0x08, (byte) 4, (byte) 1)); symTable.put("+LDS", new SICXE_OpCode((byte) 0x6C, (byte) 4, (byte) 1)); symTable.put("+LDT", new SICXE_OpCode((byte) 0x74, (byte) 4, (byte) 1)); symTable.put("+LDX", new SICXE_OpCode((byte) 0x04, (byte) 4, (byte) 1)); symTable.put("+LPS", new SICXE_OpCode((byte) 0xD0, (byte) 4, (byte) 1)); symTable.put("+MUL", new SICXE_OpCode((byte) 0x20, (byte) 4, (byte) 1)); symTable.put("+MULF", new SICXE_OpCode((byte) 0x60, (byte) 4, (byte) 1)); symTable.put("+OR", new SICXE_OpCode((byte) 0x44, (byte) 4, (byte) 1)); symTable.put("+RD", new SICXE_OpCode((byte) 0xD8, (byte) 4, (byte) 1)); symTable.put("+RSUB", new SICXE_OpCode((byte) 0x4C, (byte) 4, (byte) 0)); symTable.put("+SSK", new SICXE_OpCode((byte) 0xEC, (byte) 4, (byte) 1)); symTable.put("+STA", new SICXE_OpCode((byte) 0x0C, (byte) 4, (byte) 1)); symTable.put("+STB", new SICXE_OpCode((byte) 0x78, (byte) 4, (byte) 1)); symTable.put("+STCH", new SICXE_OpCode((byte) 0x54, (byte) 4, (byte) 1)); symTable.put("+STF", new SICXE_OpCode((byte) 0x80, (byte) 4, (byte) 1)); symTable.put("+STI", new SICXE_OpCode((byte) 0xD4, (byte) 4, (byte) 1)); symTable.put("+STL", new SICXE_OpCode((byte) 0x14, (byte) 4, (byte) 1)); symTable.put("+STS", new SICXE_OpCode((byte) 0x7C, (byte) 4, (byte) 1)); symTable.put("+STSW", new SICXE_OpCode((byte) 0xE8, (byte) 4, (byte) 1)); symTable.put("+STT", new SICXE_OpCode((byte) 0x84, (byte) 4, (byte) 1)); symTable.put("+STX", new SICXE_OpCode((byte) 0x10, (byte) 4, (byte) 1)); symTable.put("+SUB", new SICXE_OpCode((byte) 0x1C, (byte) 4, (byte) 1)); symTable.put("+SUBF", new SICXE_OpCode((byte) 0x5C, (byte) 4, (byte) 1)); symTable.put("+TD", new SICXE_OpCode((byte) 0xE0, (byte) 4, (byte) 1)); symTable.put("+TIX", new SICXE_OpCode((byte) 0x2C, (byte) 4, (byte) 1)); symTable.put("+WD", new SICXE_OpCode((byte) 0xDC, (byte) 4, (byte) 1)); symTable.put("ADD", new SICXE_OpCode((byte) 0x18, (byte) 3, (byte) 1)); symTable.put("ADDF", new SICXE_OpCode((byte) 0x58, (byte) 3, (byte) 1)); symTable.put("ADDR", new SICXE_OpCode((byte) 0x90, (byte) 2, (byte) 2)); symTable.put("AND", new SICXE_OpCode((byte) 0x40, (byte) 3, (byte) 1)); symTable.put("CLEAR", new SICXE_OpCode((byte) 0xB4, (byte) 2, (byte) 1)); symTable.put("COMP", new SICXE_OpCode((byte) 0x28, (byte) 3, (byte) 1)); symTable.put("COMPF", new SICXE_OpCode((byte) 0x88, (byte) 3, (byte) 1)); symTable.put("COMPR", new SICXE_OpCode((byte) 0xA0, (byte) 2, (byte) 2)); symTable.put("DIV", new SICXE_OpCode((byte) 0x24, (byte) 3, (byte) 1)); symTable.put("DIVF", new SICXE_OpCode((byte) 0x64, (byte) 3, (byte) 1)); symTable.put("DIVR", new SICXE_OpCode((byte) 0x9C, (byte) 2, (byte) 2)); symTable.put("FIX", new SICXE_OpCode((byte) 0xC4, (byte) 1, (byte) 0)); symTable.put("FLOAT", new SICXE_OpCode((byte) 0xC0, (byte) 1, (byte) 0)); symTable.put("HIO", new SICXE_OpCode((byte) 0xF4, (byte) 1, (byte) 0)); symTable.put("J", new SICXE_OpCode((byte) 0x3C, (byte) 3, (byte) 1)); symTable.put("JEQ", new SICXE_OpCode((byte) 0x30, (byte) 3, (byte) 1)); symTable.put("JGT", new SICXE_OpCode((byte) 0x34, (byte) 3, (byte) 1)); symTable.put("JLT", new SICXE_OpCode((byte) 0x38, (byte) 3, (byte) 1)); symTable.put("JSUB", new SICXE_OpCode((byte) 0x48, (byte) 3, (byte) 1)); symTable.put("LDA", new SICXE_OpCode((byte) 0x00, (byte) 3, (byte) 1)); symTable.put("LDB", new SICXE_OpCode((byte) 0x68, (byte) 3, (byte) 1)); symTable.put("LDCH", new SICXE_OpCode((byte) 0x50, (byte) 3, (byte) 1)); symTable.put("LDF", new SICXE_OpCode((byte) 0x70, (byte) 3, (byte) 1)); symTable.put("LDL", new SICXE_OpCode((byte) 0x08, (byte) 3, (byte) 1)); symTable.put("LDS", new SICXE_OpCode((byte) 0x6C, (byte) 3, (byte) 1)); symTable.put("LDT", new SICXE_OpCode((byte) 0x74, (byte) 3, (byte) 1)); symTable.put("LDX", new SICXE_OpCode((byte) 0x04, (byte) 3, (byte) 1)); symTable.put("LPS", new SICXE_OpCode((byte) 0xD0, (byte) 3, (byte) 1)); symTable.put("MUL", new SICXE_OpCode((byte) 0x20, (byte) 3, (byte) 1)); symTable.put("MULF", new SICXE_OpCode((byte) 0x60, (byte) 3, (byte) 1)); symTable.put("MULR", new SICXE_OpCode((byte) 0x98, (byte) 2, (byte) 2)); symTable.put("NORM", new SICXE_OpCode((byte) 0xC8, (byte) 1, (byte) 0)); symTable.put("OR", new SICXE_OpCode((byte) 0x44, (byte) 3, (byte) 1)); symTable.put("RD", new SICXE_OpCode((byte) 0xD8, (byte) 3, (byte) 1)); symTable.put("RMO", new SICXE_OpCode((byte) 0xAC, (byte) 2, (byte) 2)); symTable.put("RSUB", new SICXE_OpCode((byte) 0x4C, (byte) 3, (byte) 0)); symTable.put("SHIFTL", new SICXE_OpCode((byte) 0xA4, (byte) 2, (byte) 2)); symTable.put("SHIFTR", new SICXE_OpCode((byte) 0xA8, (byte) 2, (byte) 2)); symTable.put("SIO", new SICXE_OpCode((byte) 0xF0, (byte) 1, (byte) 0)); symTable.put("SSK", new SICXE_OpCode((byte) 0xEC, (byte) 3, (byte) 1)); symTable.put("STA", new SICXE_OpCode((byte) 0x0C, (byte) 3, (byte) 1)); symTable.put("STB", new SICXE_OpCode((byte) 0x78, (byte) 3, (byte) 1)); symTable.put("STCH", new SICXE_OpCode((byte) 0x54, (byte) 3, (byte) 1)); symTable.put("STF", new SICXE_OpCode((byte) 0x80, (byte) 3, (byte) 1)); symTable.put("STI", new SICXE_OpCode((byte) 0xD4, (byte) 3, (byte) 1)); symTable.put("STL", new SICXE_OpCode((byte) 0x14, (byte) 3, (byte) 1)); symTable.put("STS", new SICXE_OpCode((byte) 0x7C, (byte) 3, (byte) 1)); symTable.put("STSW", new SICXE_OpCode((byte) 0xE8, (byte) 3, (byte) 1)); symTable.put("STT", new SICXE_OpCode((byte) 0x84, (byte) 3, (byte) 1)); symTable.put("STX", new SICXE_OpCode((byte) 0x10, (byte) 3, (byte) 1)); symTable.put("SUB", new SICXE_OpCode((byte) 0x1C, (byte) 3, (byte) 1)); symTable.put("SUBF", new SICXE_OpCode((byte) 0x5C, (byte) 3, (byte) 1)); symTable.put("SUBR", new SICXE_OpCode((byte) 0x94, (byte) 2, (byte) 2)); symTable.put("SVC", new SICXE_OpCode((byte) 0xB0, (byte) 2, (byte) 1)); symTable.put("TD", new SICXE_OpCode((byte) 0xE0, (byte) 3, (byte) 1)); symTable.put("TIO", new SICXE_OpCode((byte) 0xF8, (byte) 1, (byte) 0)); symTable.put("TIX", new SICXE_OpCode((byte) 0x2C, (byte) 3, (byte) 1)); symTable.put("TIXR", new SICXE_OpCode((byte) 0xB8, (byte) 2, (byte) 1)); symTable.put("WD", new SICXE_OpCode((byte) 0xDC, (byte) 3, (byte) 1)); return symTable; } protected static final SeparateChainingSymbolTable<String, Byte> constructRegisterTable(final SeparateChainingSymbolTable<String, Byte> symTable) { // This table contains all of the possible registers. symTable.put("A", (byte) 0); symTable.put("X", (byte) 1); symTable.put("L", (byte) 2); symTable.put("B", (byte) 3); symTable.put("S", (byte) 4); symTable.put("T", (byte) 5); symTable.put("F", (byte) 6); symTable.put("PC", (byte) 8); symTable.put("SW", (byte) 9); return symTable; } protected static final int evaluateExpression(final String expression, final SICXE_AssemblerProgram asmProgram) { Integer left = null, right = null, result = 0; if ( expression != null ) { String[] parts = expression.split(SICXE_Lexer.SICXE_OPERATORS, 2); String sign = expression.replaceAll("\\w+", ""); if ( expression.matches(Lexer.C_NUMBERS + SICXE_Lexer.SICXE_OPERATORS + Lexer.C_NUMBERS) ) { left = SICXE_AssemblerProgram.resolveOperand(parts[0].trim(), asmProgram); right = SICXE_AssemblerProgram.resolveOperand(parts[1].trim(), asmProgram); } else if ( expression.matches(SICXE_Lexer.SICXE_IDENTIFIERS + SICXE_Lexer.SICXE_OPERATORS + Lexer.C_NUMBERS) ) { left = SICXE_AssemblerProgram.resolveSymbol(parts[0].trim(), asmProgram); right = SICXE_AssemblerProgram.resolveOperand(parts[1].trim(), asmProgram); } else if ( expression.matches(Lexer.C_NUMBERS + SICXE_Lexer.SICXE_OPERATORS + SICXE_Lexer.SICXE_IDENTIFIERS) ) { left = SICXE_AssemblerProgram.resolveOperand(parts[0].trim(), asmProgram); right = SICXE_AssemblerProgram.resolveSymbol(parts[1].trim(), asmProgram); } else { left = SICXE_AssemblerProgram.resolveSymbol(parts[0].trim(), asmProgram); right = SICXE_AssemblerProgram.resolveSymbol(parts[1].trim(), asmProgram); } if ( ( left != null ) && ( right != null ) ) { switch ( sign ) { case "-": result = ( left - right ); break; case "+": result = ( left + right ); break; case "*": result = ( left * right ); break; case "/": result = ( left / right ); break; default: break; } } } return result; } public static final boolean isAssemblerDirective(final String s) { return SICXE_AssemblerProgram.DIRECTIVE_TABLE.contains(s); } public static final boolean isOpCode(final String s) { return ( SICXE_AssemblerProgram.isAssemblerDirective(s) || SICXE_AssemblerProgram.isProgramInstruction(s) ); } public static final boolean isProgramInstruction(final String s) { return SICXE_AssemblerProgram.INSTRUCTION_TABLE.contains(s); } protected static final SICXE_Literal resolveLiteral(final String literal, final SICXE_AssemblerProgram asmProgram) { if ( ( literal != null ) && ( asmProgram.getLiteralTable().contains(literal) ) ) { return asmProgram.getLiteralTable().get(literal); } return null; } protected static final Integer resolveOperand(final String operand, final SICXE_AssemblerProgram asmProgram) { return SICXE_AssemblerProgram.resolveOperand(operand, asmProgram, 10); } protected static final Integer resolveOperand(final String operand, final SICXE_AssemblerProgram asmProgram, final int radix) { Integer result = null; // Handle expressions. if ( operand.matches(SICXE_Lexer.SICXE_IDENTIFIERS + SICXE_Lexer.SICXE_OPERATORS + SICXE_Lexer.SICXE_IDENTIFIERS) ) { result = SICXE_AssemblerProgram.evaluateExpression(operand, asmProgram); } // Handle locCtr reference symbol. if ( operand.equals("*") ) { result = asmProgram.getLocCtr(); } // Handle integer operands. if ( operand.matches(Lexer.C_NUMBERS) ) { if ( Support.isStringParsedAsInteger(operand) ) { result = Integer.parseInt(operand, radix); } else { if ( Support.isStringParsedAsDouble(operand) ) { result = (int) ( Double.parseDouble(operand) ); } } } // Handle symbol references. if ( asmProgram.getSymbolTable().contains(operand) ) { result = SICXE_AssemblerProgram.resolveSymbol(operand, asmProgram); } // Handle literal references. if ( asmProgram.getLiteralTable().contains(operand) ) { result = SICXE_AssemblerProgram.resolveLiteral(operand, asmProgram).getAddress(); } return result; } protected static final Integer resolveSymbol(final String symbol, final SICXE_AssemblerProgram asmProgram) { if ( ( symbol != null ) && ( asmProgram.getSymbolTable().contains(symbol) ) ) { return asmProgram.getSymbolTable().get(symbol); } return null; } private int baseAddress = 0; private int endVal = 0; private String fileName = null; private boolean isBaseFlag = false; private int lineCtr = 0; private SICXE_AssemblerCodeLine[] lines = null; private SeparateChainingSymbolTable<String, SICXE_Literal> literalTable = null; private int locCtr = 0; private boolean pass1Error = false; private boolean pass2Error = false; private int pgmLen = 0; private int startVal = 0; public SICXE_AssemblerProgram(final String fileName) { super(fileName); } // Assign addresses to literals (create literal pools) protected void addressLiterals(final SICXE_AssemblerCodeLine acl, final boolean pass1) { // Create literal pools as appropriate following the LTORG and END directives. if ( pass1 ) { List<String> literals = this.getLiteralTable().keysList(); for ( String literal : literals ) { SICXE_Literal l = SICXE_AssemblerProgram.resolveLiteral(literal, this); if ( l.getAddress() < 0 ) { l.setAddress(this.getLocCtr()); this.setLocCtr(this.getLocCtr() + l.getLength()); } this.getLiteralTable().put(literal, l); } } // Print literal pools to report/listing file as appropriate following the LTORG and END directives. else { // ... } } protected void assembleProgram() { // Try to assemble the program. try { StdOut.println("University of North Florida: SIC/XE Assembler"); StdOut.println("Version Date 4/23/2015"); // Execute the first pass of the SIC/XE assembler. this.pass1(); if ( !this.isPass1Error() ) { // Execute the second pass of the SIC/XE assembler. this.pass2(); if ( this.isPass2Error() ) { StdOut.println("Errors (Pass 2): partial object code generation, but no object file instantiation. " + "Refer to " + this.getFileName() + SICXE_AssemblerProgram.fileExtLst + ".\n"); } else { StdOut.println("Assembler report file: " + this.getFileName() + SICXE_AssemblerProgram.fileExtLst); StdOut.println("\t object file: " + this.getFileName() + SICXE_AssemblerProgram.fileExtObj); StdOut.println("\t middle file: " + this.getFileName() + SICXE_AssemblerProgram.fileExtMid); } } else { StdOut.println("Errors (Pass 1): no object code generated. " + "Refer to " + this.getFileName() + SICXE_AssemblerProgram.fileExtMid + ".\n"); } } catch ( final Exception exception ) { exception.printStackTrace(); System.exit( -2); } } public final int getBaseAddress() { return this.baseAddress; } public final int getEndVal() { return this.endVal; } public final String getFileName() { return this.fileName; } public final int getLineCtr() { return this.lineCtr; } public final SICXE_AssemblerCodeLine[] getLines() { return this.lines; } public final SeparateChainingSymbolTable<String, SICXE_Literal> getLiteralTable() { return this.literalTable; } public final int getLocCtr() { return this.locCtr; } public final int getPgmLen() { return this.pgmLen; } public final int getStartVal() { return this.startVal; } protected void handleBase(final SICXE_AssemblerCodeLine acl) { if ( acl.getOpCode() != null ) { switch ( acl.getOpCode() ) { case "BASE": if ( acl.getOperand() != null ) { Integer baseAddress = SICXE_AssemblerProgram.resolveOperand(acl.getOperand(), this); if ( baseAddress != null ) { this.setBaseAddress(baseAddress); this.setBaseFlag(true); } } break; case "NOBASE": this.setBaseAddress(0); this.setBaseFlag(false); break; default: break; } } } protected void handleLabel(final SICXE_AssemblerCodeLine acl, final Out out) { if ( acl.getLabel() != null ) { if ( this.getSymbolTable().contains(acl.getLabel()) ) { // If the label is already in the symbol table, then trigger a duplicate label error. String errorString = "ERROR: Duplicate label found on line " + acl.getLineNum() + "."; out.println(errorString); this.setPass1Error(true); } else { if ( acl.getOpCode() != null ) { // EQU labels. // [Label] = [Operand] // Associate the label with the value on the same line. // Store them in the symbol table. if ( acl.getOpCode().equals("EQU") ) { if ( acl.getOperand() != null ) { Integer value = SICXE_AssemblerProgram.resolveOperand(acl.getOperand(), this); if ( value != null ) { this.getSymbolTable().put(acl.getLabel(), value); } } } // Regular labels. // [Label] = [locCtr] // Associate the label with the address of the program instruction on the same line. // Store them in the symbol table. else { this.getSymbolTable().put(acl.getLabel(), this.getLocCtr()); } } } } } protected void handleLiteral(final SICXE_AssemblerCodeLine acl, final boolean pass1) { if ( acl.getOperand() != null ) { // Literals - Pass 1 if ( pass1 ) { // Search for literals and add them to the literal table if they aren't already there. if ( acl.getOperand().matches(SICXE_Lexer.SICXE_LITERALS) ) { if ( !this.getLiteralTable().contains(acl.getOperand()) ) { SICXE_Literal literal = new SICXE_Literal(acl.getOperand()); // Differentiate between true literals and literal byte constants with the '=' prefix. if ( literal.isTrueLiteral() ) { this.getLiteralTable().put(acl.getOperand(), literal); } } } } // Literals - Pass 2 else { // ... } } } protected void incrementLocCtr(final SICXE_AssemblerCodeLine acl, final Out out) { if ( acl.getOpCode() != null ) { if ( SICXE_AssemblerProgram.isOpCode(acl.getOpCode()) ) { int incAmount = 0; if ( SICXE_AssemblerProgram.isProgramInstruction(acl.getOpCode()) ) { // If the opCode is a program instruction, then increment locCtr by the instruction's format number. incAmount = SICXE_AssemblerProgram.INSTRUCTION_TABLE.get(acl.getOpCode()).getFormat(); } if ( SICXE_AssemblerProgram.isAssemblerDirective(acl.getOpCode()) ) { /* * @formatter:off * * If the opCode is an assembler directive, then determine if it is a storage directive. * The only assembler directives that increment locCtr are the storage directives BYTE, RESB, RESW, and WORD. * Some assembler storage directives interact with locCtr in other ways, such as LTORG and ORG. * * @formatter:on */ int format = SICXE_AssemblerProgram.DIRECTIVE_TABLE.get(acl.getOpCode()).getFormat(); switch ( acl.getOpCode() ) { case "WORD": // Increment locCtr by 3 incAmount = format; break; case "RESW": // Increment locCtr by [Operand] * 3 if ( acl.getOperand() != null ) { Integer numWords = SICXE_AssemblerProgram.resolveOperand(acl.getOperand(), this); if ( numWords != null ) { incAmount = ( numWords * format ); } } break; case "RESB": // Increment locCtr by [Operand] if ( acl.getOperand() != null ) { incAmount = SICXE_AssemblerProgram.resolveOperand(acl.getOperand(), this); } break; case "ORG": // Set locCtr to [Operand] if ( acl.getOperand() != null ) { this.setLocCtr(SICXE_AssemblerProgram.resolveOperand(acl.getOperand(), this, 16)); } break; case "LTORG": this.addressLiterals(acl, true); break; case "BYTE": // Increment locCtr by the size in bytes of the [Operand] if ( acl.getOperand() != null ) { if ( acl.getOperand().matches(SICXE_Lexer.SICXE_LITERALS) ) { incAmount = ( new SICXE_Literal(acl.getOperand()) ).getLength(); } else { if ( Support.isStringParsedAsByte(acl.getOperand()) ) { incAmount = format; } } } break; default: break; } } this.setLocCtr(this.getLocCtr() + incAmount); } else { // If the opCode is neither a valid program instruction nor a valid assembler directive, // then trigger an unsupported operation code error. String errorString = "ERROR: Unsupported operation code found on line " + acl.getLineNum() + "."; out.println(errorString); this.setPass1Error(true); } } } @Override protected void initialize() { super.initialize(); this.setBaseAddress(0); this.setBaseFlag(false); this.setEndVal(0); this.setFileName(null); this.setLineCtr(0); this.setLines(null); this.setLiteralTable(new SeparateChainingSymbolTable<String, SICXE_Literal>()); this.setLocCtr(0); this.setPass1Error(false); this.setPass2Error(false); this.setPgmLen(0); this.setStartVal(0); } public final boolean isBaseFlag() { return this.isBaseFlag; } public final boolean isPass1Error() { return this.pass1Error; } public final boolean isPass2Error() { return this.pass2Error; } protected void makeObjectCode(final SICXE_AssemblerCodeLine acl, final Out out) { String objectCode = ""; if ( acl.getOpCode() != null ) { if ( acl.getOperand() != null ) { // Handle memory-oriented assembler directives. if ( SICXE_AssemblerProgram.isAssemblerDirective(acl.getOpCode()) ) { switch ( acl.getOpCode() ) { case "BYTE": if ( acl.getOperand().matches(SICXE_Lexer.SICXE_LITERALS) ) { objectCode = ( new SICXE_Literal(acl.getOperand()) ).getHexValue(); } else { if ( Support.isStringParsedAsByte(acl.getOperand()) ) { objectCode = String.format("%02X", Byte.parseByte(acl.getOperand())); } } break; case "WORD": if ( Support.isStringParsedAsInteger(acl.getOperand()) ) { objectCode = String.format("%06X", Integer.parseInt(acl.getOperand())); } if ( objectCode.length() > 6 ) { objectCode = objectCode.substring(2); } break; default: break; } } } // Handle program instructions. if ( SICXE_AssemblerProgram.isProgramInstruction(acl.getOpCode()) ) { SICXE_OpCode opCodeInfo = SICXE_AssemblerProgram.INSTRUCTION_TABLE.get(acl.getOpCode()); String opCode = String.format("%02X", opCodeInfo.getOpCode()); // Divide up the instruction handling code based on the format of the instruction. switch ( opCodeInfo.getFormat() ) { case 1: // Simplest case: just set objectCode to the hex string of the operation code. // FIX, FLOAT, HIO, NORM, SIO, TIO. objectCode = opCode; break; case 2: // Next simplest case: as case 1, but also append the operands. boolean registerError = false; boolean shiftQuantityError = false; boolean interruptError = false; // ADDR, CLEAR, COMPR, DIVR, MULR, RMO, SHIFTL, SHIFTR, SUBR, SVC, TIXR. if ( acl.getOperand() != null ) { int reg1; if ( opCodeInfo.getNumOperands() == 2 ) { String[] operands = acl.getOperand().split(",", 2); if ( operands.length > 1 ) { reg1 = SICXE_AssemblerProgram.REGISTER_TABLE.get(operands[0]); if ( ( reg1 >= 0 ) && ( reg1 <= 9 ) ) { int reg2; switch ( acl.getOpCode() ) { case "SHIFTL": // SHIFTL, SHIFTR. case "SHIFTR": // Here reg2 = n+1 bits to be shifted. reg2 = SICXE_AssemblerProgram.resolveOperand(operands[1], this); if ( ( reg2 >= 1 ) && ( reg2 <= 16 ) ) { objectCode = opCode + reg1 + String.format("%-1X", ( reg2 - 1 )); } else { shiftQuantityError = true; } break; default: // ADDR, COMPR, DIVR, MULR, RMO, SUBR. reg2 = SICXE_AssemblerProgram.REGISTER_TABLE.get(operands[1]); if ( ( reg2 >= 0 ) && ( reg2 <= 9 ) ) { objectCode = opCode + reg1 + reg2; } else { registerError = true; } break; } } else { registerError = true; } } else { registerError = true; } } // CLEAR, SVC, TIXR. else { // SVC. if ( acl.getOpCode().equals("SVC") ) { // Here reg2 = interrupt code. reg1 = SICXE_AssemblerProgram.resolveOperand(acl.getOperand(), this); if ( ( reg1 >= 0 ) && ( reg1 <= 15 ) ) { objectCode = opCode + String.format("%-1X", reg1) + "0"; } else { interruptError = true; } } // CLEAR, TIXR. else { reg1 = SICXE_AssemblerProgram.REGISTER_TABLE.get(acl.getOperand()); if ( ( reg1 >= 0 ) && ( reg1 <= 9 ) ) { objectCode = opCode + reg1 + "0"; } else { registerError = true; } } } } else { registerError = true; } if ( registerError ) { String errorString = "ERROR: Invalid register or no register found in operand on line " + acl.getLineNum() + "."; out.println(errorString); this.setPass2Error(true); } if ( shiftQuantityError ) { String errorString = "ERROR: Invalid shift quantity entered on line " + acl.getLineNum() + "."; out.println(errorString); this.setPass2Error(true); } if ( interruptError ) { String errorString = "ERROR: Invalid interrupt code entered on line " + acl.getLineNum() + "."; out.println(errorString); this.setPass2Error(true); } break; default: // Most complex cases: formats 3 & 4. Must figure out bit flags and displacement. // We will do SIC simple and SIC/XE extended first because they are the simplest. /* * @formatter:off * * Bit Flags: nixbpe * * BaseRelative (n=1, i=1, b=1, p=0) * Direct (n=1, i=1, b=0, p=0) * Extended (b=0, p=0, e=1) * Immediate (n=0, i=1, x=0) * Indexed (both n & i = 0 or 1, x=1) * Indirect (n=1, i=0, x=0) * PCRelative (n=1, i=1, b=0, p=1) * Simple (n=0, i=0, b=0, p=0, e=0) * * @formatter:on */ boolean extended = false; boolean immediate = false; boolean indexed = false; boolean indirect = false; boolean simple = false; switch ( acl.getOpCode().charAt(0) ) { case '+': // SIC/XE Extended Direct (Format 4) extended = true; break; case '*': // SIC Simple Direct (Format 3), all flags = 0 except possibly x (indexed). simple = true; break; default: // SIC/XE Normal (Format 3) break; } if ( acl.getOperand() != null ) { String bitFlags = "", operand = acl.getOperand(); short origin = (short) ( acl.getAddress() + opCodeInfo.getFormat() ); switch ( acl.getOperand().charAt(0) ) { case '#': immediate = true; opCode = String.format("%02X", ( opCodeInfo.getOpCode() + 1 )); break; case '@': indirect = true; opCode = String.format("%02X", ( opCodeInfo.getOpCode() + 2 )); break; default: if ( !simple ) { opCode = String.format("%02X", ( opCodeInfo.getOpCode() + 3 )); } // Indexed addressing cannot be used with immediate or indirect addressing. if ( acl.getOperand().contains(",") ) { indexed = true; operand = operand.substring(0, operand.indexOf(",")); } break; } if ( immediate || indirect ) { operand = operand.substring(1, operand.length()); } // Next simplest case: as case 1, but determine if indexing is in use and then append the target address. if ( simple ) { if ( indexed ) { bitFlags = "8"; } else { bitFlags = "0"; } objectCode = opCode + bitFlags + String.format("%03X", SICXE_AssemblerProgram.resolveOperand(operand, this)); } else // Next simplest case: as case 1, but determine if indexing is in use and then append the target address. { if ( extended ) { if ( indexed ) { bitFlags = "9"; } else { bitFlags = "1"; } objectCode = opCode + bitFlags + String.format("%05X", SICXE_AssemblerProgram.resolveOperand(operand, this)); } else { // This method is already pretty massive. // Handle the remaining toughest cases in a separate method for maintainability. objectCode = this.makeObjectCode_Hard(opCode, operand, origin, indexed); } } } else // Handle RSUB variants. { if ( acl.getOpCode().contains("RSUB") ) { // *RSUB if ( simple ) { objectCode = opCode + "0000"; } else // RSUB, +RSUB { opCode = String.format("%02X", ( opCodeInfo.getOpCode() + 3 )); // +RSUB if ( extended ) { objectCode = opCode + "100000"; } // RSUB else { objectCode = opCode + "0000"; } } } else { String errorString = "ERROR: Missing operand or operand not found in symbol table on line " + acl.getLineNum() + "."; out.println(errorString); this.setPass2Error(true); } } break; } } } acl.setObjectCode(objectCode); } // Finish object code generation for the hardest cases: SIC/XE format 3. protected String makeObjectCode_Hard(final String opCode, final String operand, final short origin, final boolean indexed) { short targetAddress = ( SICXE_AssemblerProgram.resolveOperand(operand, this) ).shortValue(); short baseDisp = (short) ( targetAddress - this.getBaseAddress() ); short pcDisp = (short) ( targetAddress - origin ); String bitFlags = "", displacement = ""; // Operand is a numerical constant, so use Direct addressing mode. if ( Support.isStringParsedAsInteger(operand) ) { // Bit Flags = 8. if ( indexed ) { bitFlags = "8"; displacement = String.format("%03X", targetAddress); if ( ( targetAddress < 0 ) || ( targetAddress > 4095 ) ) { if ( targetAddress > 4095 ) { displacement = String.format("%03X", 4095); } if ( targetAddress < 0 ) { displacement = String.format("%03X", 0); } } } // Bit Flags = 0. else { bitFlags = "0"; displacement = String.format("%03X", targetAddress); if ( ( targetAddress < 0 ) || ( targetAddress > 4095 ) ) { if ( targetAddress > 4095 ) { displacement = String.format("%03X", 4095); } if ( targetAddress < 0 ) { displacement = String.format("%03X", 0); } } } } /* * @formatter:off * * Operand is a memory location, so use PCRelative or BaseRelative addressing mode. * Try PCRelative mode first. Only try to use BaseRelative mode if PCRelative mode won't work. * * PCRelative: TA = (PC) + displacement (-2048 <= displacement <= 2047) * BaseRelative: TA = (B) + displacement (0 <= displacement <= 4095) * * @formatter:on */ else { // Bit Flags = A (PCRelative) or C (BaseRelative). if ( indexed ) { if ( ( pcDisp >= -2048 ) && ( pcDisp <= 2047 ) ) { bitFlags = "A"; displacement = String.format("%03X", pcDisp); if ( displacement.length() > 3 ) { displacement = displacement.substring(1); } } else { if ( this.isBaseFlag() ) { if ( ( baseDisp >= 0 ) && ( baseDisp <= 4095 ) ) { bitFlags = "C"; displacement = String.format("%03X", baseDisp); } } } } // Bit Flags = 2 (PCRelative) or 4 (BaseRelative). else { if ( ( pcDisp >= -2048 ) && ( pcDisp <= 2047 ) ) { bitFlags = "2"; displacement = String.format("%03X", pcDisp); if ( displacement.length() > 3 ) { displacement = displacement.substring(1); } } else { if ( this.isBaseFlag() ) { if ( ( baseDisp >= 0 ) && ( baseDisp <= 4095 ) ) { bitFlags = "4"; displacement = String.format("%03X", baseDisp); } } } } } return ( opCode + bitFlags + displacement ); } // Output generated object code to object file. protected void outputObjectFile() { Out out = new Out(this.getFileName() + SICXE_AssemblerProgram.fileExtObj); SICXE_AssemblerCodeLine acl = null; // Loop through the file line-by-line from the beginning. for ( int i = 0; i < this.getLineCtr(); i++ ) { acl = this.getLines()[i]; if ( acl != null ) { if ( acl.getOpCode() != null ) { // START directive special case. if ( acl.getOpCode().equals("START") ) { out.print(""); continue; } // END directive special case. if ( acl.getOpCode().equals("END") ) { out.print(""); break; } // General case. out.print(""); } } } } protected void pass1() { Out out = new Out(this.getFileName() + SICXE_AssemblerProgram.fileExtMid); SICXE_AssemblerCodeLine acl = null; // Loop through the file line-by-line from the beginning. for ( int i = 0; i < this.getLineCtr(); i++ ) { acl = this.getLines()[i]; if ( acl != null ) { String lineNumString = String.format("%03d", acl.getLineNum()); if ( acl.isFullComment() ) { // Don't process full comments. Just print them to the intermediate file. out.println(lineNumString + ":" + acl.getInput()); } else { // Process START assembler directive, if present. this.processStartDirective(acl); // Set the address for this line of assembly code by copying locCtr. acl.setAddress(this.getLocCtr()); // Print to the intermediate file. out.println(lineNumString + ":" + String.format("%04X", this.getLocCtr()) + "\t" + acl.getInput()); // Handle label, if present. this.handleLabel(acl, out); // Handle literal, if present. this.handleLiteral(acl, true); // Increment locCtr depending on the given opCode. this.incrementLocCtr(acl, out); // Process END assembler directive, if present. if ( this.processEndDirective(acl) ) { break; } } } } // Calculate program length. this.setPgmLen(this.getLocCtr() - this.getStartVal()); // Output the symbol and literal tables as necessary. // If there are no literals in the program, skip the literal table. if ( !this.getLiteralTable().isEmpty() ) { out.println(SICXE_AssemblerProgram.buildSymbolTableString(this)); out.print(SICXE_AssemblerProgram.buildLiteralTableString(this)); } else { out.print(SICXE_AssemblerProgram.buildSymbolTableString(this)); } } protected void pass2() { Out out = new Out(this.getFileName() + SICXE_AssemblerProgram.fileExtLst); SICXE_AssemblerCodeLine acl = null; // Print the listing/report file preamble. out.println("*********************************************"); out.println("University of North Florida: SIC/XE Assembler"); out.println("Version Date 4/23/2015"); out.println(Support.getDateTimeStamp()); out.println("*********************************************"); out.println("ASSEMBLER REPORT"); out.println("----------------"); out.println("\t Loc\tObject Code\tSource Code"); out.println("\t ---\t-----------\t-----------"); // Loop through the file line-by-line from the beginning. for ( int i = 0; i < this.getLineCtr(); i++ ) { acl = this.getLines()[i]; if ( acl != null ) { String lineNumString = String.format("%03d", acl.getLineNum()); if ( acl.isFullComment() ) { // Don't process full comments. Just print them to the listing/report file. out.println(lineNumString + "- " + acl.getInput()); } else { // Handle BASE/NOBASE assembler directives, if present. this.handleBase(acl); // Handle literal, if present. this.handleLiteral(acl, false); // Generate the object byte code for this line of assembly source code. this.makeObjectCode(acl, out); // Print to the listing/report file. out.println(lineNumString + "- " + String.format("%05X", acl.getAddress()) + "\t" + String.format("%-8S", acl.getObjectCode()) + "\t" + acl.getInput()); // Print literal pools as appropriate. this.addressLiterals(acl, false); } } } // If there was an error during pass 2, don't bother generating an object code file. if ( !this.isPass2Error() ) { this.outputObjectFile(); } } protected boolean processEndDirective(final SICXE_AssemblerCodeLine acl) { if ( acl.getOpCode() != null ) { if ( acl.getOpCode().equals("END") ) { if ( acl.getOperand() != null ) { Integer address = SICXE_AssemblerProgram.resolveOperand(acl.getOperand(), this, 16); if ( address != null ) { this.setEndVal(address); } } this.addressLiterals(acl, true); return true; } } return false; } protected void processStartDirective(final SICXE_AssemblerCodeLine acl) { if ( acl.getOpCode() != null ) { if ( acl.getOpCode().equals("START") ) { if ( acl.getOperand() != null ) { Integer address = SICXE_AssemblerProgram.resolveOperand(acl.getOperand(), this, 16); if ( address != null ) { this.setStartVal(address); this.setLocCtr(address); this.setEndVal(address); } } } } } @Override protected void readFile(final String fileName) { // Try to read from the given file. try { // Initialize data input. // If the given file is invalid or inaccessible, an exception is thrown. In inputStream = new In(fileName); // Establish how many lines of text are in the file. this.setLineCtr(Support.countLinesInTextFile(fileName)); this.setLines(new SICXE_AssemblerCodeLine[this.getLineCtr()]); // Read in the file's data line by line and store it for future analysis. for ( int i = 0; ( ( i < this.getLineCtr() ) && ( inputStream.hasNextLine() ) ); i++ ) { String line = inputStream.readLine(); if ( line != null ) { this.getLines()[i] = new SICXE_AssemblerCodeLine(line.toUpperCase(), i + 1, 0); } } this.setFileName(fileName); this.assembleProgram(); } catch ( final Exception exception ) { StdOut.println("Error opening source file."); StdOut.println("Unable to read source code from file " + fileName + " - program aborts."); System.exit( -1); } } protected final void setBaseAddress(final int baseAddress) { this.baseAddress = baseAddress; } protected final void setBaseFlag(final boolean isBaseFlag) { this.isBaseFlag = isBaseFlag; } protected final void setEndVal(final int endVal) { this.endVal = endVal; } protected final void setFileName(final String fileName) { this.fileName = fileName; } protected final void setLineCtr(final int lineCtr) { this.lineCtr = lineCtr; } protected final void setLines(final SICXE_AssemblerCodeLine[] lines) { this.lines = lines; } protected final void setLiteralTable(final SeparateChainingSymbolTable<String, SICXE_Literal> literalTable) { this.literalTable = literalTable; } protected final void setLocCtr(final int locCtr) { this.locCtr = locCtr; } protected final void setPass1Error(final boolean pass1Error) { this.pass1Error = pass1Error; } protected final void setPass2Error(final boolean pass2Error) { this.pass2Error = pass2Error; } protected final void setPgmLen(final int pgmLen) { this.pgmLen = pgmLen; } protected final void setStartVal(final int startVal) { this.startVal = startVal; } }
mit
htmlpdfapi/hpa-ruby
lib/hpa/pdf.rb
106
module Hpa class Pdf def self.create(options={}) Hpa.create(:pdf, options) end end end
mit
luobotang/old-js-dependency-analysis
lib/analyze.js
1133
var esprima = require('esprima') var escope = require('escope') var GlobalVarsInBrowser = require('./global-vars-browser') var helpers = require('./array-helpers') module.exports = analyze /* * @type AnalysisResult * @property {string} file * @property {string[]} defineVars * @property {string[]} requireVars */ /* * @param {string} code - JS src code * @param {string} file - file path * @return {AnalysisResult} */ function analyze(code, file) { var ast = esprima.parse(code) var scopeManager = escope.analyze(ast, {ignoreEval: true}) var globalScope = scopeManager.acquire(ast) var defineVars = (globalScope.variables || []).map(function (v) { return v.name }).sort() var usedVars = (globalScope.through || []).map(function (ref) { return ref.identifier.name }).reduce(helpers.unionByReduce, []).filter(excludeGlobalVars).sort() var requireVars = helpers.diff(defineVars, usedVars)[1] return { file: file, defineVars: defineVars, requireVars: requireVars } } // used in arr.filter() function excludeGlobalVars(value) { return GlobalVarsInBrowser.indexOf(value) === -1 }
mit
seanpue/al340
lessons/textanalysis/Untitled0.py
1100
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import nltk %matplotlib inline # <codecell> import os from nltk.corpus.reader.plaintext import PlaintextCorpusReader corpusdir = 'data/texts/' # Directory of corpus. corpus0 = PlaintextCorpusReader(corpusdir, '.*') corpus = nltk.Text(corpus0.words()) # <codecell> corpus.concordance('girls') # <codecell> corpus.concordance("'", lines=all) # <codecell> len(set(corpus)) # <codecell> len(corpus) # <codecell> corpus.common_contexts(['general']) # <codecell> from nltk.corpus import stopwords stopwords = stopwords.words(‘english’) # <codecell> corpus.dispersion_plot(["women","girls","fire"]) # <codecell> import mpld3 # <codecell> mpld3.enable_notebook() # <codecell> corpus.dispersion_plot(["women","girls","fire"], ) # <codecell> len(corpus) # <codecell> len(set(corpus)) / len(corpus) # <codecell> corpus[0:100] # <codecell> fdist1 = nltk.FreqDist(corpus) # <codecell> fdist1.most_common(50) # <codecell> fdist1.plot(50, cumulative=True) # <codecell> corpus[w.upper() for w in corpus]
mit
Caijiacheng/pig
lib/lib-util/src/main/java/com/mm/util/db/WrapperConn.java
7480
package com.mm.util.db; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; /** * override void close() * @author apple * */ public class WrapperConn implements Connection { Connection conn; public WrapperConn(Connection conn) { this.conn = conn; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return conn.unwrap(iface); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return conn.isWrapperFor(iface); } @Override public Statement createStatement() throws SQLException { return conn.createStatement(); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return conn.prepareStatement(sql); } @Override public CallableStatement prepareCall(String sql) throws SQLException { return conn.prepareCall(sql); } @Override public String nativeSQL(String sql) throws SQLException { return conn.nativeSQL(sql); } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { conn.setAutoCommit(autoCommit); } @Override public boolean getAutoCommit() throws SQLException { return conn.getAutoCommit(); } @Override public void commit() throws SQLException { conn.commit(); } @Override public void rollback() throws SQLException { conn.rollback(); } @Override public void close() throws SQLException { if (!AbsDBHandle.s_conn_share_mode.get()) conn.close(); } @Override public boolean isClosed() throws SQLException { return conn.isClosed(); } @Override public DatabaseMetaData getMetaData() throws SQLException { return conn.getMetaData(); } @Override public void setReadOnly(boolean readOnly) throws SQLException { conn.setReadOnly(readOnly); } @Override public boolean isReadOnly() throws SQLException { return conn.isReadOnly(); } @Override public void setCatalog(String catalog) throws SQLException { conn.setCatalog(catalog); } @Override public String getCatalog() throws SQLException { return conn.getCatalog(); } @Override public void setTransactionIsolation(int level) throws SQLException { conn.setTransactionIsolation(level); } @Override public int getTransactionIsolation() throws SQLException { return conn.getTransactionIsolation(); } @Override public SQLWarning getWarnings() throws SQLException { return conn.getWarnings(); } @Override public void clearWarnings() throws SQLException { conn.clearWarnings(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return conn.createStatement(); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return conn.prepareStatement(sql, resultSetType, resultSetConcurrency); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return conn.prepareCall(sql, resultSetType, resultSetConcurrency); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { return conn.getTypeMap(); } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { conn.setTypeMap(map); } @Override public void setHoldability(int holdability) throws SQLException { conn.setHoldability(holdability); } @Override public int getHoldability() throws SQLException { return conn.getHoldability(); } @Override public Savepoint setSavepoint() throws SQLException { return conn.setSavepoint(); } @Override public Savepoint setSavepoint(String name) throws SQLException { return conn.setSavepoint(name); } @Override public void rollback(Savepoint savepoint) throws SQLException { conn.rollback(savepoint); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { conn.releaseSavepoint(savepoint); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return conn.prepareStatement(sql, autoGeneratedKeys); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return conn.prepareStatement(sql, columnIndexes); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return conn.prepareStatement(sql, columnNames); } @Override public Clob createClob() throws SQLException { return conn.createClob(); } @Override public Blob createBlob() throws SQLException { return conn.createBlob(); } @Override public NClob createNClob() throws SQLException { return conn.createNClob(); } @Override public SQLXML createSQLXML() throws SQLException { return conn.createSQLXML(); } @Override public boolean isValid(int timeout) throws SQLException { return conn.isValid(timeout); } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { conn.setClientInfo(name, value); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { conn.setClientInfo(properties); } @Override public String getClientInfo(String name) throws SQLException { return conn.getClientInfo(name); } @Override public Properties getClientInfo() throws SQLException { return conn.getClientInfo(); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return conn.createArrayOf(typeName, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return conn.createStruct(typeName, attributes); } @Override public void setSchema(String schema) throws SQLException { conn.setSchema(schema); } @Override public String getSchema() throws SQLException { return conn.getSchema(); } @Override public void abort(Executor executor) throws SQLException { conn.abort(executor); } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { conn.setNetworkTimeout(executor, milliseconds); } @Override public int getNetworkTimeout() throws SQLException { return conn.getNetworkTimeout(); } }
mit
rolandjitsu/ionic-app-scripts
src/dev-server/http-server.ts
4589
import * as path from 'path'; import { injectNotificationScript } from './injector'; import { injectLiveReloadScript } from './live-reload'; import * as express from 'express'; import * as fs from 'fs'; import * as url from 'url'; import { ServeConfig, LOGGER_DIR, IONIC_LAB_URL, IOS_PLATFORM_PATH, ANDROID_PLATFORM_PATH } from './serve-config'; import { Logger } from '../logger/logger'; import * as proxyMiddleware from 'proxy-middleware'; import { injectDiagnosticsHtml } from '../logger/logger-diagnostics'; import * as Constants from '../util/constants'; import { getBooleanPropertyValue } from '../util/helpers'; import { getProjectJson, IonicProject } from '../util/ionic-project'; import { LabAppView, ApiCordovaProject, ApiPackageJson } from './lab'; /** * Create HTTP server */ export function createHttpServer(config: ServeConfig): express.Application { const app = express(); app.set('serveConfig', config); app.listen(config.httpPort, config.host, function() { Logger.debug(`listening on ${config.httpPort}`); }); app.get('/', serveIndex); app.use('/', express.static(config.wwwDir)); app.use(`/${LOGGER_DIR}`, express.static(path.join(__dirname, '..', '..', 'bin'), { maxAge: 31536000 })); // Lab routes app.use(IONIC_LAB_URL + '/static', express.static(path.join(__dirname, '..', '..', 'lab', 'static'))); app.get(IONIC_LAB_URL, LabAppView); app.get(IONIC_LAB_URL + '/api/v1/cordova', ApiCordovaProject ); app.get(IONIC_LAB_URL + '/api/v1/app-config', ApiPackageJson); app.get('/cordova.js', servePlatformResource, serveMockCordovaJS); app.get('/cordova_plugins.js', servePlatformResource); app.get('/plugins/*', servePlatformResource); // Fallback route - send to index.html to allow deeplinker to handle path. app.use(serveIndex); if (config.useProxy) { setupProxies(app); } return app; } function setupProxies(app: express.Application) { if (getBooleanPropertyValue(Constants.ENV_READ_CONFIG_JSON)) { getProjectJson().then(function(projectConfig: IonicProject) { for (const proxy of projectConfig.proxies || []) { let opts: any = url.parse(proxy.proxyUrl); if (proxy.proxyNoAgent) { opts.agent = false; } opts.rejectUnauthorized = !(proxy.rejectUnauthorized === false); app.use(proxy.path, proxyMiddleware(opts)); Logger.info('Proxy added:' + proxy.path + ' => ' + url.format(opts)); } }).catch((err: Error) => { Logger.error(`Failed to read the projects ionic.config.json file: ${err.message}`); }); } } /** * http responder for /index.html base entrypoint */ function serveIndex(req: express.Request, res: express.Response) { const config: ServeConfig = req.app.get('serveConfig'); // respond with the index.html file const indexFileName = path.join(config.wwwDir, process.env[Constants.ENV_VAR_HTML_TO_SERVE]); fs.readFile(indexFileName, (err, indexHtml) => { if (config.useLiveReload) { indexHtml = injectLiveReloadScript(indexHtml, req.hostname, config.liveReloadPort); } indexHtml = injectNotificationScript(config.rootDir, indexHtml, config.notifyOnConsoleLog, config.notificationPort); indexHtml = injectDiagnosticsHtml(config.buildDir, indexHtml); res.set('Content-Type', 'text/html'); res.send(indexHtml); }); } /** * http responder for cordova.js file */ function serveMockCordovaJS(req: express.Request, res: express.Response) { res.set('Content-Type', 'application/javascript'); res.send('// mock cordova file during development'); } /** * Middleware to serve platform resources */ function servePlatformResource(req: express.Request, res: express.Response, next: express.NextFunction) { const config: ServeConfig = req.app.get('serveConfig'); const userAgent = req.header('user-agent'); let resourcePath = config.wwwDir; if (!config.isCordovaServe) { return next(); } if (isUserAgentIOS(userAgent)) { resourcePath = path.join(config.rootDir, IOS_PLATFORM_PATH); } else if (isUserAgentAndroid(userAgent)) { resourcePath = path.join(config.rootDir, ANDROID_PLATFORM_PATH); } fs.stat(path.join(resourcePath, req.url), (err, stats) => { if (err) { return next(); } res.sendFile(req.url, { root: resourcePath }); }); } function isUserAgentIOS(ua: string) { ua = ua.toLowerCase(); return (ua.indexOf('iphone') > -1 || ua.indexOf('ipad') > -1 || ua.indexOf('ipod') > -1); } function isUserAgentAndroid(ua: string) { ua = ua.toLowerCase(); return ua.indexOf('android') > -1; }
mit
gtkatakura/furb-desenvolvimento-plataformas-moveis
backend/app/controllers/institutes_controller.rb
1215
class InstitutesController < ApplicationController before_action :authenticate_user! before_action :set_institute, only: [:show, :update, :destroy] # GET /institutes def index @institutes = Institute.all render json: @institutes end # GET /institutes/1 def show render json: @institute end # POST /institutes def create @institute = Institute.new(institute_params) if @institute.save render json: @institute, status: :created, location: @institute else render json: @institute.errors.full_messages, status: :unprocessable_entity end end # PATCH/PUT /institutes/1 def update if @institute.update(institute_params) render json: @institute else render json: @institute.errors.full_messages, status: :unprocessable_entity end end # DELETE /institutes/1 def destroy @institute.destroy end private # Use callbacks to share common setup or constraints between actions. def set_institute @institute = Institute.find(params[:id]) end # Only allow a trusted parameter "white list" through. def institute_params params.require(:institute).permit(:name, :maintainer_id) end end
mit
Xeroeta/nkcgo-webapp
src/Screens/AboutScreen.js
1837
import React, { Component } from 'react'; import appConfig from '../Config/params'; const style = { width: '100%', height: '100%', margin: '0px' } const line1 = "Welcome to the Ultimate Guide to North Kansas City, MO!"; const line2 = "Check-in at dozens of points of interests along our famous mile-and-a-half Pint Path, track your progress among new local discoveries, and win prizes during NKC events!"; const line3 = "This mobile app is your guide to entertainment, events, points of interest and the community of North Kansas City. From restaurants and bars, breweries and distilleries, retail and entertainment venues, parks and community spaces to art installations and historical points of interest, North Kansas City has it all! Keep an eye on this app for future check-in events to earn prizes and badges to your collection!"; const line4 = ""; export default class AboutScreen extends Component { constructor(props) { super(props); this.state = { width: '0', height: '0' }; this.updateWindowDimensions = this.updateWindowDimensions.bind(this); } componentWillMount() { } componentDidMount() { this.updateWindowDimensions(); window.addEventListener('resize', this.updateWindowDimensions); } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); } updateWindowDimensions() { this.setState({ width: window.innerWidth, height: window.innerHeight }); } render() { return ( <div> <p style={styles.aboutText}>{line1} </p> <p style={styles.aboutText}>{line2} </p> <p style={styles.aboutText}>{line3} </p> <p style={styles.aboutText}>{line4} </p> </div> ); } } const styles = { aboutText: { color: '#000', fontSize: 20, fontWeight: 'bold', } };
mit
Telerivet/cloud-script-example
commands/unsubscribe.js
154
var config = require('../config'); var subscribers = project.getOrCreateGroup(config.GROUP_NAME); contact.removeFromGroup(subscribers); contact.save();
mit
integratedfordevelopers/integrated
src/Common/Queue/Exception/UnexpectedTypeException.php
640
<?php /* * This file is part of the Integrated package. * * (c) e-Active B.V. <integrated@e-active.nl> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Integrated\Common\Queue\Exception; /** * @author Jan Sanne Mulder <jansanne@e-active.nl> */ class UnexpectedTypeException extends InvalidArgumentException { public function __construct($value, $expectedType) { parent::__construct(sprintf('Expected argument of type "%s", "%s" given', $expectedType, \is_object($value) ? \get_class($value) : \gettype($value))); } }
mit
robertzml/Aglaia
Aglaia.API/Areas/HelpPage/HelpPageConfigurationExtensions.cs
24076
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Aglaia.API.Areas.HelpPage.ModelDescriptions; using Aglaia.API.Areas.HelpPage.Models; namespace Aglaia.API.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
mit
Quramy/ts-graphql-plugin
src/language-service-plugin/index.ts
41
export * from './plugin-module-factory';
mit
jadu/meteor
src/Package/Migrations/MigrationsCopier.php
1172
<?php namespace Meteor\Package\Migrations; use Meteor\Filesystem\Filesystem; use Meteor\IO\IOInterface; class MigrationsCopier { /** * @var Filesystem */ private $filesystem; /** * @var IOInterface */ private $io; /** * @param Filesystem $filesystem * @param IOInterface $io */ public function __construct(Filesystem $filesystem, IOInterface $io) { $this->filesystem = $filesystem; $this->io = $io; } /** * @param string $workingDir * @param string $tempDir * @param array $config * * @return array */ public function copy($workingDir, $tempDir, array $config) { if (isset($config['migrations'])) { $this->io->text('Adding migrations to the package:'); $migrationDirectory = 'migrations/' . $config['name']; $this->filesystem->copyDirectory( $workingDir . '/' . $config['migrations']['directory'], $tempDir . '/' . $migrationDirectory ); $config['migrations']['directory'] = $migrationDirectory; } return $config; } }
mit
alice1017/gitTools
git-todo.py
11140
#!/usr/bin/env python #coding: utf-8 import os import sys import miniparser from util import core from util import adjust from util import objects from util.git import * from util.color import * from util.objects import Todo from subprocess import Popen, PIPE from StringIO import StringIO from datetime import datetime from sys import exit as kill parser = miniparser.parser( version="0.1.0b", description="You can manage to" \ "What you want to do on your git repository") CACHE_FILE = os.path.join(git_directory(), "gitodo") CACHE_FILE_PATH = os.path.join(os.getcwd(), CACHE_FILE) @parser.default(description="Show all ToDos.") def default(): if os.access(CACHE_FILE_PATH, os.F_OK) != True: print "The repository does not todo initialized yet." print "Please do 'git todo init'" kill(1) # get todo container todo_container = core.load_state(open(CACHE_FILE_PATH,"r")) if len(todo_container) == 0: print "There is not ToDo." kill(1) adjust.output_todolist(todo_container, sortby="status-open") @parser.option( "print", description="this option makes TODO file, and write all tasks.") def printout_file(): if os.access(CACHE_FILE_PATH, os.F_OK) != True: print "The repository does not todo initialized yet." print "Please do 'git todo init'" kill(1) # get todo container todo_container = core.load_state(open(CACHE_FILE_PATH,"r")) if len(todo_container) == 0: print "There is not ToDo." kill(1) if os.access("TODO",os.F_OK): print "The TODO file is already created." confirm = raw_input("Do you sure overwrite tasks? (y/n) >> ") if confirm in ["n", "no"]: print "Sure." return elif confirm in ["y", "yes"]: pass else: print "I can't udnerstand." fp = open("TODO","w") sys.stdout = fp adjust.output_todolist(todo_container, sortby="status-open", nocolor=True) fp.close() sys.stdout = sys.__stdout__ print "Complete." @parser.option( "init", description="prepare for managing todo") def initialize(): # check exist file if os.access(CACHE_FILE_PATH, os.F_OK): print "In this repository, you already initialized." return # create cache file core.save_state([], open(CACHE_FILE_PATH,"w")) @parser.option("new", description="Create new todo, Please write TODO content at argument.") def create(content): if os.access(CACHE_FILE_PATH, os.F_OK) != True: print "The repository does not todo initialized yet." print "Please do 'git todo init'" kill(1) # ------------------------------------------------ # ToDo object # 1. id (str) - git hash-object # 2. content(str) - todo content string # 3. author(str) - the author name that create todo # 4. created_at(datetime) - datetime when open todo # 5. status(str) - open or close # 6. opened_commit(str) - commit hash when created todo # 7. closed_at(datetime) - datetime when close todo # 8. closed_commit(str) - commit hash when closed todo # ------------------------------------------------ # get todo container todo_container = core.load_state(open(CACHE_FILE_PATH,"r")) for n,todo in enumerate(todo_container): if todo.content == content: print "fatal: this ToDo is duplicate." print "Your appending ToDo: %s" % content print "duplicate ToDo: %(index)s %(content)s" % { "index": yellow(n), "content":todo.content} kill(1) todo_info = {} todo_info["hashid"] = make_hash(content) todo_info["content"] = content todo_info["author"] = get_author() todo_info["created_at"] = datetime.now() todo_info["status"] = "OPEN" todo_info["opened_commit"] = adjust.get_latest_commit().commithash todo_info["closed_at"] = None todo_info["closed_commit"] = None todo_obj = Todo(**todo_info) todo_container.append(todo_obj) core.save_state(todo_container, open(CACHE_FILE_PATH,"w")) @parser.option("ls","list", description="Show all todos.") def showall(): if os.access(CACHE_FILE_PATH, os.F_OK) != True: print "The repository does not todo initialized yet." print "Please do 'git todo init'" kill(1) # get todo container todo_container = core.load_state(open(CACHE_FILE_PATH,"r")) if len(todo_container) == 0: print "There is not ToDo." kill(1) adjust.output_todolist(todo_container) @parser.option("info", description="Show more information about todo", argument_types={"index": int}) def todo_information(index): if os.access(CACHE_FILE_PATH, os.F_OK) != True: print "The repository does not todo initialized yet." print "Please do 'git todo init'" kill(1) # get todo container todo_container = core.load_state(open(CACHE_FILE_PATH,"r")) if len(todo_container) == 0: print "There is not ToDo." kill(1) if index > len(todo_container)-1: print "The Index value is over the number of todo." kill(1) todo = todo_container[index] timeformat = core.isoformat.replace("-"," ") print "%s" % yellow("#%d"%index) print "[%s]" % (blue(todo.status) if todo.status == "OPEN" else red(todo.status)), print todo.content print "-"*core.terminal_width() print "Author".ljust(13),":",magenta(todo.author) print "Primary Id".ljust(13),":",todo.hashid print "Created at".ljust(13), ":", todo.created_at.strftime( timeformat) if todo.status == "CLOSED": print "Closed at".ljust(13), ":", todo.closed_at.strftime( timeformat) print "Opened commit", ":", blue(todo.opened_commit) if todo.status == "CLOSED": print "Closed commit", ":", red(todo.closed_commit) print "-"*core.terminal_width() #print get_commit_diff(todo.closed_commit) @parser.option("close", description="Update todo status from OPEN to CLOSE.", argument_types={"index": int}) def close_todo(index): if os.access(CACHE_FILE_PATH, os.F_OK) != True: print "The repository does not todo initialized yet." print "Please do 'git todo init'" kill(1) # get todo container todo_container = core.load_state(open(CACHE_FILE_PATH,"r")) if len(todo_container) == 0: print "There is not ToDo." kill(1) if index > len(todo_container): print "The Index value is over the number of todo." kill(1) # check already closed if todo_container[index].status == "CLOSED": print "This ToDo is already closed." kill(1) # create tag put_tag("ToDo#%d_close" % index, "Closed '%s' ToDo."%todo_container[index].content) # change status todo_container[index].status = "CLOSED" todo_container[index].closed_commit = adjust.get_latest_commit().commithash todo_container[index].closed_at = datetime.now() core.save_state(todo_container, open(CACHE_FILE_PATH,"w")) @parser.option("del", description="delete ToDo", argument_types={"index": int}) def delete(index): if os.access(CACHE_FILE_PATH, os.F_OK) != True: print "The repository does not todo initialized yet." print "Please do 'git todo init'" kill(1) # get todo container todo_container = core.load_state(open(CACHE_FILE_PATH,"r")) if len(todo_container) == 0: print "There is not ToDo." kill(1) if index > len(todo_container): print "The Index value is over the number of todo." kill(1) todo_container.pop(index) core.save_state(todo_container, open(CACHE_FILE_PATH,"w")) @parser.option("log", description="You can show commit log with when your ToDo opened or closed") def show_log(): if os.access(CACHE_FILE_PATH, os.F_OK) != True: print "The repository does not todo initialized yet." print "Please do 'git todo init'" kill(1) todo_container = core.load_state(open(CACHE_FILE_PATH,"r")) commits = adjust.get_commits() pager = get_pager() isoformat = "%a %b %d %H:%M:%S %Y %z" io = StringIO() sys.stdout = io for commit in commits: print yellow("commit: %s" % commit.commithash) opened_commits = ([blue("'"+t.content+"'") for t in todo_container \ if t.opened_commit == commit.commithash]) closed_commits = ([red("'"+t.content+"'") for t in todo_container \ if t.closed_commit == commit.commithash]) if len(opened_commits) != 0: print "Opened ToDo: %s" % ", ".join(opened_commits) if len(closed_commits) != 0: print "Closed ToDo: %s" % ", ".join(closed_commits) if commit.merge_data != None: print "Merge: %s" % " ".join(commit.merge_data) print "Author: %s <%s>" % ( commit.author.name, commit.author.email) else: print "Author: %s <%s>" % ( commit.author.name, commit.author.email) print "Date: %s" % commit.date.strftime(isoformat) print print commit.comment print sys.stdout = sys.__stdout__ if pager == None: print io.getvalue()[:-1] else: proc = Popen(pager.split(" "), stdin=PIPE, stderr=PIPE) proc.communicate(io.getvalue()[:-1]) @parser.option("alldelete", description=yellow("This is Only Development option.")+" You can delete all ToDo data") def alldeelete(): if os.access(CACHE_FILE_PATH, os.F_OK) != True: print "The repository does not todo initialized yet." print "Please do 'git todo init'" kill(1) # save todo container data to backup file fp = open("todo_backup","w") todo_container = core.load_state(open(CACHE_FILE_PATH,"r")) core.save_state(todo_container, fp) # delete cache file if os.access(CACHE_FILE_PATH, os.F_OK): core.shellrun("rm", "%s" % CACHE_FILE_PATH) print "Complete" @parser.option("import", description=yellow("This is Only Development option")+ \ " You can import ToDo data from backup file.") def import_todo(backup_file): if os.access(backup_file, os.F_OK) == False: print "'%s' file is not found." % backup_file kill(1) fp = open(backup_file,"r") todo_container = core.load_state(fp) core.save_state(todo_container, open(CACHE_FILE_PATH,"w")) if __name__ == "__main__": if check_exist_repo() == False: print yellow("There is not git repository!") kill(1) parser.parse()
mit
nailsapp/module-email
webpack.config.js
946
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const path = require('path'); module.exports = { entry: { 'admin': './assets/js/admin.js', 'debugger': './assets/js/debugger.js' }, output: { filename: '[name].min.js', path: path.resolve(__dirname, 'assets/js/') }, module: { rules: [ { test: /\.(css|scss|sass)$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { url: false } }, 'postcss-loader', 'sass-loader' ] }, ] }, plugins: [ new MiniCssExtractPlugin({ filename: '../css/[name].min.css' }), ], mode: 'production' };
mit
ethical-jobs/ethical-jobs-redux
src/assertions.js
6007
import Immutable from 'immutable'; import ImmutableUtils from './immutable'; /** * Asserts a modules "initial" state * * @author Andrew McLagan <andrew@ethicaljobs.com.au> */ function initialState(reducer, expectedState) { return Immutable.is(reducer(undefined), expectedState); } /** * Asserts a modules "cleared" state * @param {object} reducer * @param {function} action * @param {object} initialState * @return {bool} */ function clearedEntities(reducer, action, initialState) { const expected = initialState .set('entities', Immutable.Map()) .set('result', false); return Immutable.is(reducer(undefined, action), expected); } /** * Asserts a modules updated filter state * @param {object} reducer * @param {function} actionCreator * @param {object} initialState * @return {boolean} */ function updatedFilters(reducer, actionCreator, initialState) { let state; state = reducer(undefined, actionCreator({ foo: 'bar' })); state = reducer(state, actionCreator({ bar: 123 })); state = reducer(state, actionCreator({ foo: 10000 })); const expected = initialState.set('filters', Immutable.fromJS({ bar: 123, foo: 10000 })); return Immutable.is(state, expected); } /** * Asserts a modules cleared filter state * @param {object} reducer * @param {function} actionCreator * @param {object} initialState * @return {boolean} */ function clearedFilters(reducer, actionCreator, initialState) { const expected = initialState.set('filters', Immutable.Map()); let state = reducer(initialState.set('filters', Immutable.Map({ foo: 'bar' }))); state = reducer(state, actionCreator()); return Immutable.is(state, expected); } /** * Asserts a modules updated syncFilter state * @param {object} reducer * @param {function} actionCreator * @param {object} initialState * @return {boolean} */ function updatedSyncFilters(reducer, actionCreator, initialState) { let state; state = reducer(undefined, actionCreator({ foo: 'bar' })); state = reducer(state, actionCreator({ bar: 123 })); state = reducer(state, actionCreator({ foo: 10000 })); const expected = initialState.set('syncFilters', Immutable.fromJS({ bar: 123, foo: 10000 })); return Immutable.is(state, expected); } /** * Asserts a modules "search request" state * * @author Andrew McLagan <andrew@ethicaljobs.com.au> */ function searchRequestState(reducer, actionType, initialState) { const expected = ImmutableUtils.mergeSearchRequest(initialState); return Immutable.is(reducer(undefined, { type: `${actionType}_REQUEST` }), expected); } /** * Asserts a modules "request" state * * @author Andrew McLagan <andrew@ethicaljobs.com.au> */ function requestState(reducer, actionTypes = [], initialState) { let passes = true; const expected = ImmutableUtils.mergeRequest(initialState); actionTypes.forEach(type => { if (false === Immutable.is(reducer(undefined, { type }), expected)) { passes = false; } }); return passes; } /** * Asserts a modules "success" state * * @author Andrew McLagan <andrew@ethicaljobs.com.au> */ function successState(reducer, actionTypes = [], initialState, fixture) { let passes = true; const expected = ImmutableUtils.mergeSuccess(initialState, fixture); actionTypes.forEach(type => { const action = { type, payload: fixture }; if (false === Immutable.is(reducer(undefined, action), expected)) { passes = false; } }); return passes; } function archiveSuccessState(reducer, actionType, initialState, archivedEntry) { const action = { type: actionType, payload: archivedEntry }; const expected = ImmutableUtils.archiveSuccess(initialState, archivedEntry); return Immutable.is(reducer(initialState, action), expected); } /** * Asserts a modules "failure" state * * @author Andrew McLagan <andrew@ethicaljobs.com.au> */ function failureState(reducer, actionTypes = [], initialState, fixture) { let passes = true; const expected = ImmutableUtils.mergeFailure(initialState, fixture); actionTypes.forEach(type => { const action = { type, payload: fixture, error: true }; if (false === Immutable.is(reducer(undefined, action), expected)) { passes = false; } }); return passes; } /** * Asserts a modules fetchingSelector * * @author Andrew McLagan <andrew@ethicaljobs.com.au> */ function fetchingSelector(key, selector) { const state = Immutable.fromJS({ entities: { [key]: { fetching: 'foo-bar-bam', }, } }); return Immutable.is('foo-bar-bam', selector(state)); } /** * Asserts a modules filtersSelector * * @author Andrew McLagan <andrew@ethicaljobs.com.au> */ function filtersSelector(key, selector) { const state = Immutable.fromJS({ entities: { [key]: { filters: 'foo-bar-bam', }, } }); return Immutable.is('foo-bar-bam', selector(state)); } /** * Asserts a modules resultSelector * * @author Andrew McLagan <andrew@ethicaljobs.com.au> */ function resultSelector(key, selector) { const state = Immutable.fromJS({ entities: { [key]: { result: 'foo-bar-bam', }, } }); return Immutable.is('foo-bar-bam', selector(state)); } /** * Asserts a modules entities selector * * @author Andrew McLagan <andrew@ethicaljobs.com.au> */ function entitiesSelector(moduleKey, entitiesKey, selector) { const state = Immutable.fromJS({ entities: { [moduleKey]: { entities: { [entitiesKey]: 'foo-bar-bam', }, }, } }); const correctState = Immutable.is('foo-bar-bam', selector(state)); const defaultState = Immutable.is(Immutable.Map(), selector(Immutable.fromJS({}))); return correctState && defaultState; } export default { initialState, clearedEntities, updatedFilters, clearedFilters, updatedSyncFilters, searchRequestState, requestState, successState, archiveSuccessState, failureState, fetchingSelector, filtersSelector, resultSelector, entitiesSelector, };
mit
mbme/cman
spec/repository_spec.rb
4982
require 'spec_helper' describe Cman::Repository do include FakeFS::SpecHelpers before :each do FileUtils.mkdir_p BASE_DIR @repo_name = 'i3' @repo = new @repo_name end def new(name) Cman::Repository.new name end it "exist when it's dir exist and config exists" do FileUtils.mkdir File.join(BASE_DIR, @repo_name) touch @repo.config_path @repo.exist?.should be_true end it "doesn't exist when its dir or config doesn't exist" do @repo.exist?.should be_false FileUtils.mkdir File.join(BASE_DIR, @repo_name) @repo.exist?.should be_false end it 'correctly builds full repo path' do @repo.path.should eq File.join(BASE_DIR, @repo_name) end it 'correctly builds repo config path' do expected_path = File.join( BASE_DIR, @repo_name, Cman::Repository::REPO_CONFIG ) @repo.config_path.should eq expected_path end it 'can be created' do @repo.exist?.should be_false @repo.create @repo.exist?.should be_true # check if config file exist File.file?(@repo.config_path).should be_true end it 'cannot be created if already exist' do @repo.create repo = new @repo_name expect { repo.create }.to raise_error end it 'cannot be created with wrong name' do expect { new '.test' }.to raise_error end it 'cannot be created if dir already exists' do FileUtils.mkdir File.join(BASE_DIR, @repo_name) repo = new @repo_name expect { repo.create }.to raise_error end it 'can be removed if exist' do @repo.create @repo.exist?.should be_true @repo.remove @repo.exist?.should be_false end it "cannot be removed if doesn't exist" do @repo.exist?.should be_false expect { @repo.remove }.to raise_error end it 'can add new file' do @repo.create file_path = '/test/file' touch file_path rec = @repo.add_record file_path rec.repository.should eq @repo rec.id.should eq 0 rec.repo_file.should eq ':test:file' File.file?(file_path).should be_true File.file?(rec.repo_path).should be_true File.file?(@repo.config_path).should be_true end it 'cannot add same file twice' do @repo.create file_path = '/test/file' touch file_path # we can add file first time @repo.add_record(file_path).should_not be_nil # but cannot add it second time expect { @repo.add_record file_path }.to raise_error end it 'cannot add symlink' do @repo.create file_path = '/test/file' touch file_path link = '/test/symlink' FileUtils.symlink file_path, link expect { @repo.add_record(link) }.to raise_error end it 'can add dir with multiple files and dirs' do @repo.create base_dir = '/test/test-dir' f1 = 'dir/other' f1_path = "#{base_dir}/#{f1}" touch f1_path l1 = 'dir/symlink' File.symlink f1_path, "#{base_dir}/#{l1}" f2 = 'file' touch "#{base_dir}/#{f2}" d1 = 'empty-dir' FileUtils.mkdir "#{base_dir}/#{d1}" rec = @repo.add_record base_dir rec.repository.should eq @repo rec.id.should eq 0 Dir.exist?(rec.repo_path).should be_true File.exist?(File.join(@repo.path, rec.repo_file, f1)).should be_true File.exist?(File.join(@repo.path, rec.repo_file, f2)).should be_true # we should skip empty dirs Dir.exist?(File.join(@repo.path, rec.repo_file, d1)).should be_false # we should skip symlinks File.symlink?(File.join(@repo.path, rec.repo_file, l1)).should be_false end it 'can be deserialized from config file' do file_path = '/test/file' touch file_path @repo.create rec1 = @repo.add_record file_path repo = Cman::Repository.read @repo_name repo.size.should eq 1 rec2 = repo.get_record 0 rec1.id.should eq rec2.id rec1.path.should eq rec2.path end it 'can add files with the same name' do name = 'file' path1 = "/test/#{name}" path2 = "/test/1/#{name}" touch "#{path1}/somefile", path2 @repo.create rec1 = @repo.add_record path1 rec2 = @repo.add_record path2 File.exist?(rec2.repo_path).should be_true File.directory?(rec1.repo_path).should be_true end it 'can add hidden file' do @repo.create file_path = '/test/.file' touch file_path rec = @repo.add_record file_path File.file?(rec.repo_path).should be_true end it 'can remove file' do @repo.create file_path1 = '/test/.file' file_path2 = '/test1/file' touch file_path1, file_path2 rec = @repo.add_record file_path1 @repo.add_record file_path2 @repo.size.should eq 2 File.file?(rec.repo_path).should be_true @repo.remove_record rec.id repo = Cman::Repository.read @repo_name repo.size.should eq 1 File.file?(rec.repo_path).should be_false end it 'cannot remove not existing file' do @repo.create expect { @repo.remove_record 1000 }.to raise_error @repo.size.should eq 0 end end
mit
sue445/gitpeach
app/controllers/sessions_controller.rb
736
class SessionsController < ApplicationController def create api_response = Gitlab.session(params[:login], params[:password]) user = User.find_or_create_by(gitlab_user_id: api_response.id) user.username = api_response.username user.private_token = api_response.private_token user.email = api_response.email user.save! session[:user_id] = user.id back_to_path = params[:back_to] ? params[:back_to] : root_path redirect_to back_to_path, notice: "Signed in!" rescue Gitlab::Error::Unauthorized => e redirect_to root_path(back_to: params[:back_to]), alert: "Unauthorized" end def destroy session[:user_id] = nil redirect_to root_path, notice: "Signed Out!" end end
mit
robinleej/billund
packages/billund-framework-core/lib/server/modules/actionbinder.js
7168
'use strict'; const isDev = (process.env.LEGO_ENV === 'development' || process.env.LEGO_ENV === 'dev' || process.env.BILLUND_ENV === 'development' || process.env.BILLUND_ENV === 'dev'); const path = require('path'); const _ = require('lodash'); const legoUtils = require('billund-utils'); const decache = require('decache'); const convert = require('koa-convert'); const gaze = require('gaze'); /* watch变化的文件路径 router实例 */ let watchFiles = []; let routerIns = null; let watched = false; /* url2ActionConfig的数据设计: key: url[String], value: actonConfig { actionPath: [String], // action的路径 action: [GeneratorFunction], // 用以执行的迭代器函数 routerConfig: String // routerConfig路径 } */ let url2ActionConfig = null; let initedConfig = null; /** * 初始化router * * @param {Array} actions - controler层的列表 */ function initRouter() { const url2Path = {}; const router = require('koa-router')(); /** * 向router中注册url & action * * @param {String} url - router的路径 * @param {GeneratorFunction} actionConfig - 执行函数 * @param {String} actionPath - actino路径 */ function registUrlToAction(url, actionConfig, actionPath) { if (!(url && actionConfig && actionConfig.action)) return; if (url2Path[url]) throw new Error(`duplicate define router url: ${url}`); url2Path[url] = true; let staticRc = null; const actionPathDir = path.resolve(actionPath, '../'); if (actionConfig.routerConfig) { staticRc = path.resolve(actionPathDir, actionConfig.routerConfig); } let injector = function* injector(next) { yield next; /* 如果有routerConfig的话 是一个字符串,那么是相对的路径,目前只有这种情况才能解决代码解析的问题 */ if (this.legoConfig) { // 优先判断routerConfigPath if (this.legoConfig.routerConfigPath) { let rcPath = ''; if (path.isAbsolute(this.legoConfig.routerConfigPath)) { rcPath = this.legoConfig.routerConfigPath; } else { rcPath = path.resolve(actionPathDir, this.legoConfig.routerConfigPath); } this.legoConfig.staticRouterConfig = require(rcPath); if (isDev) { collectFileAndChildren(rcPath); } } else if (staticRc) { this.legoConfig.staticRouterConfig = require(staticRc); } } }; let action = actionConfig.action; if (initedConfig && initedConfig.koa2) { injector = convert(injector); action = convert(actionConfig.action); } router.register(url, ['get', 'post'], [injector, action]); /* 如果是dev的话,加入watchFile */ if (isDev) { collectFileAndChildren(actionPath); collectFileAndChildren(staticRc); } } Object.keys(url2ActionConfig).forEach((url) => { const actionConfig = url2ActionConfig[url]; const actionPath = actionConfig.actionPath; registUrlToAction(url, actionConfig, actionPath); }); routerIns = router.routes(); if (!watched) { watchFilesChange(); watched = true; } } /** * 更新widgets信息 */ function updateRouter() { watchFiles.forEach((file) => { decache(file); console.log(`${file} decache.`); }); initRouter(); } /** * watch文件的变更 */ function watchFilesChange() { watchFiles.forEach((file) => { gaze(file, function(err) { if (err) { console.warn(err); console.log(`watch ${file} file fail`); return; } this.on('changed', () => { updateRouter(); }); }); }); } /** * 收集当前文件和它的引用文件 * * @param {String} pathname - 当前文件 */ function collectFileAndChildren(pathname) { if (!pathname) return; // 如果已经监听过,不做收集 if (watched) return; // 因为超过调用上限的问题,不监听node_modules下的变化 if (/\/node_modules\//.test(pathname)) return; const findedIndex = watchFiles.findIndex((filePath) => { return filePath === pathname; }); const isExisted = findedIndex !== -1; if (!isExisted) { const list = [pathname]; let children = []; try { children = require.cache[pathname].children; } catch (e) { children = []; } if (children && children.length) { children.forEach((child) => { const childFindedIndex = watchFiles.findIndex((filePath) => { return filePath === child.filename; }); if (childFindedIndex === -1) { collectFileAndChildren(child.filename); } }); } watchFiles = watchFiles.concat(list); } } /** * 准备action的map * * @param {Object} config - 对应的配置项目 * @return {Object} */ function prepareUrl2ActionConfig(config) { /* 优先判断url2ActionConfig */ let ret = {}; if (config.url2ActionConfig) { ret = Object.assign({}, config.url2ActionConfig); } const storeActionPaths = legoUtils.common.getFilteredFiles(config.actionDir, { nameRegex: config.nameRegex }); (storeActionPaths || []).forEach((action) => { let actionConfig = null; try { actionConfig = require(action); } catch (e) { console.error(e); return true; } // 如果没有要的属性,就过滤掉 if (!(actionConfig && actionConfig.url)) return true; const urls = _.isArray(actionConfig.url) ? actionConfig.url : [actionConfig.url]; urls.forEach((url) => { ret[url] = Object.assign({ actionPath: action }, actionConfig); }); }); return ret; } /** * 绑定对应的action到routers中 * * @param {Object} config - 对应的配置项目,字段如下: * { * actionDir: [String], // action的文件夹名称 * url2ActionConfig: [Object], // action的url与actionConfig的映射 * nameRegex: [Regex|String] // 名称的正则 * fallbackUrl: [String] // 降级的url * } */ function bindActionRouter(config) { if (!(config && (config.actionDir || config.url2ActionConfig))) throw new Error('missing actionDir or url2ActionConfig config in lego framework'); initedConfig = Object.assign({}, config); url2ActionConfig = prepareUrl2ActionConfig(config); initRouter(); } function getRouter() { return routerIns; } module.exports = { getRouter, bindActionRouter };
mit
NuCode1497/TimekeeperWPF
TimekeeperWPF/Calendar/NowMarker.xaml.cs
651
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace TimekeeperWPF.Calendar { /// <summary> /// Interaction logic for NowMarker.xaml /// </summary> public partial class NowMarker : CalendarObject { public NowMarker() { InitializeComponent(); } } }
mit
eaglewangy/advanced-list-adapter
Sample/src/com/example/bindableadaptertest/MockImageLoader.java
298
package com.example.bindableadaptertest; import android.widget.ImageView; import com.peony.listadapter.interfaces.DynamicImageLoader; public class MockImageLoader implements DynamicImageLoader { @Override public void loadImage(String url, ImageView view) { //does nothing! :) } }
mit
j0kaso/ngl
src/viewer/viewer-constants.js
2343
/** * @file Viewer Constants * @author Alexander Rose <alexander.rose@weirdbyte.de> * @private */ import { Debug } from '../globals.js' if (typeof window !== 'undefined' && window.WebGLRenderingContext) { const wrcp = window.WebGLRenderingContext.prototype // wrap WebGL debug function used by three.js and // ignore calls to them when the debug flag is not set const _getShaderParameter = wrcp.getShaderParameter wrcp.getShaderParameter = function getShaderParameter () { if (Debug) { return _getShaderParameter.apply(this, arguments) } else { return true } } const _getShaderInfoLog = wrcp.getShaderInfoLog wrcp.getShaderInfoLog = function getShaderInfoLog () { if (Debug) { return _getShaderInfoLog.apply(this, arguments) } else { return '' } } const _getProgramParameter = wrcp.getProgramParameter wrcp.getProgramParameter = function getProgramParameter (program, pname) { if (Debug || pname !== wrcp.LINK_STATUS) { return _getProgramParameter.apply(this, arguments) } else { return true } } const _getProgramInfoLog = wrcp.getProgramInfoLog wrcp.getProgramInfoLog = function getProgramInfoLog () { if (Debug) { return _getProgramInfoLog.apply(this, arguments) } else { return '' } } } const JitterVectors = [ [ [ 0, 0 ] ], [ [ 4, 4 ], [ -4, -4 ] ], [ [ -2, -6 ], [ 6, -2 ], [ -6, 2 ], [ 2, 6 ] ], [ [ 1, -3 ], [ -1, 3 ], [ 5, 1 ], [ -3, -5 ], [ -5, 5 ], [ -7, -1 ], [ 3, 7 ], [ 7, -7 ] ], [ [ 1, 1 ], [ -1, -3 ], [ -3, 2 ], [ 4, -1 ], [ -5, -2 ], [ 2, 5 ], [ 5, 3 ], [ 3, -5 ], [ -2, 6 ], [ 0, -7 ], [ -4, -6 ], [ -6, 4 ], [ -8, 0 ], [ 7, -4 ], [ 6, 7 ], [ -7, -8 ] ], [ [ -4, -7 ], [ -7, -5 ], [ -3, -5 ], [ -5, -4 ], [ -1, -4 ], [ -2, -2 ], [ -6, -1 ], [ -4, 0 ], [ -7, 1 ], [ -1, 2 ], [ -6, 3 ], [ -3, 3 ], [ -7, 6 ], [ -3, 6 ], [ -5, 7 ], [ -1, 7 ], [ 5, -7 ], [ 1, -6 ], [ 6, -5 ], [ 4, -4 ], [ 2, -3 ], [ 7, -2 ], [ 1, -1 ], [ 4, -1 ], [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ], [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ] ] ] JitterVectors.forEach(offsetList => { offsetList.forEach(offset => { // 0.0625 = 1 / 16 offset[ 0 ] *= 0.0625 offset[ 1 ] *= 0.0625 }) }) export { JitterVectors }
mit
Terricide/ReVision
src/ReVision.Forms/Controls/ListBox.cs
347
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.Windows.Forms { public class ListBox : ListControl { public override string ControlName { get { return "ListBox"; } } } }
mit
ForbesLindesay/monploy-agent
bin/cli.js
957
#!/usr/bin/env node var forever = require('forever'); var request = require('then-request'); var command = process.argv[2]; function start() { // see https://github.com/nodejitsu/forever-monitor for options forever.startDaemon('server.js', { sourceDir: __dirname, cwd: process.cwd(), uid: 'monploy-agent' }); } function stop() { forever.list(null, function (err, processes) { if (err) throw err; if ((processes || []).some(function (proc, index) { if (proc.uid === 'monploy_agent') { forever.stop(index); return true; } else { return false; } })) { setTimeout(stop, 1000); } else { console.log('stopped'); } }); } switch (command) { case 'start': start(); break; case 'stop': stop(); break; case 'list': request('http://localhost:3000/list').done(function (res) { console.dir(JSON.parse(res.getBody())); }); break; }
mit
almostcake/TimetableWebAPI
src/TimetableWebAPI/Extensions/Database.cs
1755
using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using TimetableWebAPI.Infrastructure.Contexts; using TimetableWebAPI.Tests.Data; namespace TimetableWebAPI.Extensions { public static class Database { /// <summary> /// Регистрация зависимостей необходимых для работы с БД /// </summary> /// <param name="services"></param> public static IServiceCollection AddDatabaseDependencies(this IServiceCollection services) { //на всякий случай, добавил sql server, мб надо бует //services.AddEntityFrameworkSqlServer() //.AddDbContext<TimetableContext>(options => options.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TimetableWA;Integrated Security=True")); //Postgresql соединение к бд //services.AddDbContext<TimetableContext>(opt => opt.UseNpgsql(Configuration.GetConnectionString("NpgsqlLocalDb"))); //пока что поюзаем бд в памяти, потестить все дела, все настроить и тд, чтобы выйти сразу на норм бд, и не морочиться с миграциями services.AddDbContext<TimetableContext>(opt => opt.UseInMemoryDatabase()); return services; } public static IApplicationBuilder SeedDatabaseWithTestData(this IApplicationBuilder builder) { builder.ApplicationServices .GetService<TimetableContext>() .EnsureSeedData(); return builder; } } }
mit
johngatti/mozu-java
mozu-java-core/src/main/java/com/mozu/api/clients/platform/developer/DeveloperAdminUserAuthTicketClient.java
7504
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.clients.platform.developer; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; /** <summary> * Use the Authtickets resource to manage authentication tickets for your developer account. * </summary> */ public class DeveloperAdminUserAuthTicketClient { /** * Generate an authentication ticket for a developer account. * <p><pre><code> * MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> mozuClient=CreateDeveloperUserAuthTicketClient( userAuthInfo); * client.setBaseAddress(url); * client.executeRequest(); * DeveloperAdminUserAuthTicket developerAdminUserAuthTicket = client.Result(); * </code></pre></p> * @param userAuthInfo Information required to authenticate a user. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> * @see com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket * @see com.mozu.api.contracts.core.UserAuthInfo */ public static MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> createDeveloperUserAuthTicketClient(com.mozu.api.contracts.core.UserAuthInfo userAuthInfo) throws Exception { return createDeveloperUserAuthTicketClient( userAuthInfo, null, null); } /** * Generate an authentication ticket for a developer account. * <p><pre><code> * MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> mozuClient=CreateDeveloperUserAuthTicketClient( userAuthInfo, developerAccountId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * DeveloperAdminUserAuthTicket developerAdminUserAuthTicket = client.Result(); * </code></pre></p> * @param developerAccountId Unique identifier of the developer account. * @param responseFields Use this field to include those fields which are not included by default. * @param userAuthInfo Information required to authenticate a user. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> * @see com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket * @see com.mozu.api.contracts.core.UserAuthInfo */ public static MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> createDeveloperUserAuthTicketClient(com.mozu.api.contracts.core.UserAuthInfo userAuthInfo, Integer developerAccountId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.platform.developer.DeveloperAdminUserAuthTicketUrl.createDeveloperUserAuthTicketUrl(developerAccountId, responseFields); String verb = "POST"; Class<?> clz = com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket.class; MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> mozuClient = (MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(userAuthInfo); return mozuClient; } /** * Generates a new developer account authentication ticket for the specified tenant by supplying the defined refresh token information. * <p><pre><code> * MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> mozuClient=RefreshDeveloperAuthTicketClient( existingAuthTicket); * client.setBaseAddress(url); * client.executeRequest(); * DeveloperAdminUserAuthTicket developerAdminUserAuthTicket = client.Result(); * </code></pre></p> * @param existingAuthTicket Properties of the authentication ticket to be used in developer account claims with the Mozu API. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> * @see com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket * @see com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket */ public static MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> refreshDeveloperAuthTicketClient(com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket existingAuthTicket) throws Exception { return refreshDeveloperAuthTicketClient( existingAuthTicket, null, null); } /** * Generates a new developer account authentication ticket for the specified tenant by supplying the defined refresh token information. * <p><pre><code> * MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> mozuClient=RefreshDeveloperAuthTicketClient( existingAuthTicket, developerAccountId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * DeveloperAdminUserAuthTicket developerAdminUserAuthTicket = client.Result(); * </code></pre></p> * @param developerAccountId Unique identifier of the developer account. * @param responseFields Use this field to include those fields which are not included by default. * @param existingAuthTicket Properties of the authentication ticket to be used in developer account claims with the Mozu API. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> * @see com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket * @see com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket */ public static MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> refreshDeveloperAuthTicketClient(com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket existingAuthTicket, Integer developerAccountId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.platform.developer.DeveloperAdminUserAuthTicketUrl.refreshDeveloperAuthTicketUrl(developerAccountId, responseFields); String verb = "PUT"; Class<?> clz = com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket.class; MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket> mozuClient = (MozuClient<com.mozu.api.contracts.adminuser.DeveloperAdminUserAuthTicket>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(existingAuthTicket); return mozuClient; } /** * Deletes the authentication ticket for the developer account by supplying the refresh token. * <p><pre><code> * MozuClient mozuClient=DeleteUserAuthTicketClient( refreshToken); * client.setBaseAddress(url); * client.executeRequest(); * </code></pre></p> * @param refreshToken Alphanumeric string used for access tokens. This token refreshes access for accounts by generating a new developer or application account authentication ticket after an access token expires. * @return Mozu.Api.MozuClient */ public static MozuClient deleteUserAuthTicketClient(String refreshToken) throws Exception { MozuUrl url = com.mozu.api.urls.platform.developer.DeveloperAdminUserAuthTicketUrl.deleteUserAuthTicketUrl(refreshToken); String verb = "DELETE"; MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance(); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } }
mit
voxsoftware/vox-core
submodules/vox-core-moment/dist/locale/dv.js
2243
var $mod$368 = core.VW.Ecma2015.Utils.module(require('../moment')); var months = [ 'ޖެނުއަރީ', 'ފެބްރުއަރީ', 'މާރިޗު', 'އޭޕްރީލު', 'މޭ', 'ޖޫން', 'ޖުލައި', 'އޯގަސްޓު', 'ސެޕްޓެމްބަރު', 'އޮކްޓޯބަރު', 'ނޮވެމްބަރު', 'ޑިސެމްބަރު' ], weekdays = [ 'އާދިއްތަ', 'ހޯމަ', 'އަންގާރަ', 'ބުދަ', 'ބުރާސްފަތި', 'ހުކުރު', 'ހޮނިހިރު' ]; exports.default = $mod$368.default.defineLocale('dv', { months: months, monthsShort: months, weekdays: weekdays, weekdaysShort: weekdays, weekdaysMin: 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'D/M/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, meridiemParse: /މކ|މފ/, isPM: function (input) { return 'މފ' === input; }, meridiem: function (hour, minute, isLower) { if (hour < 12) { return 'މކ'; } else { return 'މފ'; } }, calendar: { sameDay: '[މިއަދު] LT', nextDay: '[މާދަމާ] LT', nextWeek: 'dddd LT', lastDay: '[އިއްޔެ] LT', lastWeek: '[ފާއިތުވި] dddd LT', sameElse: 'L' }, relativeTime: { future: 'ތެރޭގައި %s', past: 'ކުރިން %s', s: 'ސިކުންތުކޮޅެއް', m: 'މިނިޓެއް', mm: 'މިނިޓު %d', h: 'ގަޑިއިރެއް', hh: 'ގަޑިއިރު %d', d: 'ދުވަހެއް', dd: 'ދުވަސް %d', M: 'މަހެއް', MM: 'މަސް %d', y: 'އަހަރެއް', yy: 'އަހަރު %d' }, preparse: function (string) { return string.replace(/،/g, ','); }, postformat: function (string) { return string.replace(/,/g, '\u060C'); }, week: { dow: 7, doy: 12 } });
mit
NoaYHM/Augmented-Reality-using-Unity3D
Assets/Scripts/Facebook.cs
331
 using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Facebook : MonoBehaviour { private GameObject FacebookButton; void Start () { } void OnMouseDown(){ // this object was clicked - do something Application.OpenURL("https://www.facebook.com/BoyaKabini"); } }
mit
FernFerret/demobrowser
run.py
379
#!/usr/bin/env python from demobrowser import app, db #db.drop_all() db.create_all() app.debug = app.config.get('DEBUG', False) # This is required. app.secret_key = app.config.get('SECRET_KEY', None) if app.secret_key is None: print "ERROR: SECRET_KEY not found in settings.cfg. Please see README.md for help!" else: app.run(host=app.config.get('ADDRESS', '0.0.0.0'))
mit
sidlors/microservicios
Chapter 1/firstboot/src/test/java/com/sample/firstboot/SampleApplicationTest.java
690
package com.sample.firstboot; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class SampleApplicationTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public SampleApplicationTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( SampleApplicationTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
mit
krishl/restaurant-planner
config/environments/production.rb
3592
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. # config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "restaurant-planner_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
mit
xrstf/libhg
tests/Dummies/Client.php
2969
<?php /* * Copyright (c) 2012, Christoph Mewes, http://www.xrstf.de/ * * This file is released under the terms of the MIT license. You can find the * complete text in the attached LICENSE file or online at: * * http://www.opensource.org/licenses/mit-license.php */ /** * dummy client */ class libhg_Dummies_Client implements libhg_Client_Interface { public $stdin; ///< libhg_Stream_Writable hg -> PHP public $stdout; ///< libhg_Stream_Readable PHP -> hg public $open; ///< boolean public $capabilities = null; ///< array public $options; ///< libhg_Options_Interface public $repo; ///< libhg_Repository_Interface /** * Constructor * * @param libhg_Options_Interface $options * @param libhg_Repository_Interface $repo */ public function __construct(libhg_Options_Interface $options, libhg_Repository_Interface $repo) { $this->reset(); $this->options = $options; $this->repo = $repo; } /** * get options * * @return libhg_Options_Interface */ public function getOptions() { return $this->options; } /** * get capabilities * * @return array */ public function getCapabilities() { return $this->capabilities; } /** * get writable stream * * @return libhg_Stream_Writable */ public function getWritableStream() { return $this->stdin; } /** * get readable stream * * @return libhg_Stream_Readable */ public function getReadableStream() { return $this->stdout; } /** * check is a connection is established * * @return boolean */ public function isConnected() { return $this->open; } /** * get repository * * @return libhg_Repository_Interface */ public function getRepository() { return $this->repo; } /** * reset object * * @return libhg_Client self */ protected function reset() { $this->stdin = null; $this->stdout = null; $this->open = false; $this->process = false; $this->capabilities = array(); return $this; } /** * set repository * * @param libhg_Repository_Interface $repo * @return libhg_Client self */ public function setRepository(libhg_Repository_Interface $repo) { $this->repo = $repo; return $this; } /** * set options * * @param libhg_Options_Interface $options * @return libhg_Client self */ public function setOptions(libhg_Options_Interface $options) { $this->options = $options; return $this; } /** * connect * * @return Dummies_Client self */ public function connect() { if ($this->open) $this->close(); $this->open = true; return $this; } /** * Close connection * * @return boolean */ public function close() { if (!$this->open) return false; $this->reset(); return true; } public function run(libhg_Command_Interface $command, libhg_Repository_Interface $repository = null) { return array($command, $repository); } }
mit
odellus/year_of_code
nested.py
297
#! /usr/bin/env python def solution(A): st = [] for ch in S: if ch == '(': st.append(ch) elif len(st) < 1: return 0 elif st.pop(-1) != '(' or ch != ')': return 0 if len(st) == 0: return 1 else: return 0
mit
LykkeCity/Notary
glue/src/py/example.py
130
# simple python module for testing interop def hello(s): return "hello, " + s + " how are you." def calc(x): return x+2
mit
JohnJosuaPaderon/Scarlet.NET
Scarlet.NetFramework/DbValueConverter.Definitions.NullableByte.cs
436
using System; namespace Scarlet { partial class DbValueConverter { public static byte? ToNullableByte(object value) { return ConversionBase(value, ValueConverter.ToNullableByte); } public static byte? ToNullableByte(object value, IFormatProvider formatProvider) { return ConversionBase(value, formatProvider, ValueConverter.ToNullableByte); } } }
mit
callemall/material-ui
packages/material-ui-icons/src/LocalGasStationRounded.js
600
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19.77 7.23l.01-.01-3.19-3.19c-.29-.29-.77-.29-1.06 0-.29.29-.29.77 0 1.06l1.58 1.58c-1.05.4-1.76 1.47-1.58 2.71.16 1.1 1.1 1.99 2.2 2.11.47.05.88-.03 1.27-.2v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v15c0 .55.45 1 1 1h8c.55 0 1-.45 1-1v-6.5h1.5v4.86c0 1.31.94 2.5 2.24 2.63 1.5.15 2.76-1.02 2.76-2.49V9c0-.69-.28-1.32-.73-1.77zM12 10H6V5h6v5zm6 0c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" /> , 'LocalGasStationRounded');
mit
OSUrobotics/rgbd_numpy
rgbd_numpy/scripts/python_pointclouds.py
3342
#!/usr/bin/env python from sensor_msgs.msg import PointCloud2, PointField, Image import numpy as np import struct import cv from cv_bridge import CvBridge import copy import code # HACK for debugging fmt_full = '' _DATATYPES = {} _DATATYPES[PointField.INT8] = ('b', 1) _DATATYPES[PointField.UINT8] = ('B', 1) _DATATYPES[PointField.INT16] = ('h', 2) _DATATYPES[PointField.UINT16] = ('H', 2) _DATATYPES[PointField.INT32] = ('i', 4) _DATATYPES[PointField.UINT32] = ('I', 4) _DATATYPES[PointField.FLOAT32] = ('f', 4) _DATATYPES[PointField.FLOAT64] = ('d', 8) _NP_TYPES = { np.dtype('uint8') : (PointField.UINT8, 1), np.dtype('int8') : (PointField.INT8, 1), np.dtype('uint16') : (PointField.UINT16, 2), np.dtype('int16') : (PointField.INT16, 2), np.dtype('uint32') : (PointField.UINT32, 4), np.dtype('int32') : (PointField.INT32, 4), np.dtype('float32') : (PointField.FLOAT32,4), np.dtype('float64') : (PointField.FLOAT64,8) } def pointcloud2_to_array(msg): global fmt_full if not fmt_full: fmt = _get_struct_fmt(msg) fmt_full = '>' if msg.is_bigendian else '<' + fmt.strip('<>')*msg.width*msg.height # import pdb; pdb.set_trace() unpacker = struct.Struct(fmt_full) unpacked = np.asarray(unpacker.unpack_from(msg.data)) unpacked = unpacked.reshape(msg.height, msg.width, len(msg.fields)) # Unpack RGB color info _float2rgb_vectorized = np.vectorize(_float2rgb) r, g, b = _float2rgb_vectorized(unpacked[:, :, 3]) z = np.expand_dims(copy.deepcopy(unpacked[:, :, 2]), 2) r = np.expand_dims(r, 2) # insert blank 3rd dimension (for concatenation) g = np.expand_dims(g, 2) b = np.expand_dims(b, 2) unpacked = np.concatenate((unpacked[:, :, 0:3], r, g, b), axis=2) return unpacked def _get_struct_fmt(cloud, field_names=None): fmt = '>' if cloud.is_bigendian else '<' offset = 0 for field in (f for f in sorted(cloud.fields, key=lambda f: f.offset) if field_names is None or f.name in field_names): if offset < field.offset: fmt += 'x' * (field.offset - offset) offset = field.offset if field.datatype not in _DATATYPES: print >> sys.stderr, 'Skipping unknown PointField datatype [%d]' % field.datatype else: datatype_fmt, datatype_length = _DATATYPES[field.datatype] fmt += field.count * datatype_fmt offset += field.count * datatype_length return fmt def _float2rgb(x): rgb = struct.unpack('I', struct.pack('f', x))[0] b = (rgb >> 16) & 0x0000ff; g = (rgb >> 8) & 0x0000ff; r = (rgb) & 0x0000ff; return r,g,b ######### ROS NODE FOR TESTING ################ image_pub = None bridge = CvBridge() def cloud_cb(msg): arr = pointcloud2_to_array(msg) image_np = copy.deepcopy(arr[:, :, 3:].astype('uint8')) image_cv = cv.fromarray(image_np) image_msg = bridge.cv_to_imgmsg(image_cv, encoding='rgb8') image_pub.publish(image_msg) if __name__ == '__main__': import rospy from std_msgs.msg import Empty rospy.init_node('test_pointclouds') image_pub = rospy.Publisher('/camera/depth_registered/points_image', Image) rospy.Subscriber('/camera/depth_registered/points', PointCloud2, cloud_cb) rospy.spin()
mit