repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
GreatWorksCopenhagen/gw-xmascard
src/lib/bower/modernizr@3.2.0/test/browser/src/prefixedCSS.js
1054
/* */ "format global"; describe('prefixedCSS', function() { var ModernizrProto = {_config: {usePrefixes: true}, _q: []}; var prefixedCSS; var cleanup; before(function(done) { define('ModernizrProto', [], function() {return ModernizrProto;}); define('package', [], function() {return {version: 'v9999'};}); var req = requirejs.config({ context: Math.random().toString().slice(2), baseUrl: '../src', paths: {cleanup: '../test/cleanup'} }); req(['cleanup', 'prefixedCSS'], function(_cleanup, _prefixedCSS) { prefixedCSS = _prefixedCSS; cleanup = _cleanup; done(); }); }); it('creates a reference on `ModernizrProto`', function() { expect(prefixedCSS).to.equal(ModernizrProto.prefixedCSS); }); it('returns false on unknown properties', function() { expect(prefixedCSS('fart')).to.equal(false); }); it('returns known values without prefix', function() { expect(prefixedCSS('display')).to.equal('display'); }); after(function() { cleanup(); }); });
gpl-3.0
privamov/accio
accio/java/fr/cnrs/liris/infra/thriftserver/WebhookAuthStrategy.scala
2605
/* * Accio is a platform to launch computer science experiments. * Copyright (C) 2016-2018 Vincent Primault <v.primault@ucl.ac.uk> * * Accio is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Accio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Accio. If not, see <http://www.gnu.org/licenses/>. */ package fr.cnrs.liris.infra.thriftserver import java.nio.file.Path import com.twitter.util.logging.Logging import com.twitter.util.{Duration, Future} import fr.cnrs.liris.infra.webhook.Webhook import fr.cnrs.liris.util.cache.CacheBuilder final class WebhookAuthStrategy(webhook: Webhook[WebhookAuthStrategy.ReviewResponse], cacheTtl: Duration) extends AuthStrategy with Logging { private[this] val cache = CacheBuilder().expireAfterWrite(cacheTtl).build[String, Option[UserInfo]] override def authenticate(credentials: String): Future[Option[UserInfo]] = { cache.get(credentials) match { case Some(res) => Future.value(res) case None => webhook .execute(WebhookAuthStrategy.ReviewRequest(credentials)) .map { review => if (review.authenticated) { Some(review.user.getOrElse(UserInfo(credentials))) } else { None } } .onSuccess { userInfo => // We only cache successful responses. cache.put(credentials, userInfo) } .handle { case e: Throwable => logger.error(s"Error in webhook: ${e.getMessage}") None } } } } object WebhookAuthStrategy { case class ReviewRequest(credentials: String) case class ReviewResponse(authenticated: Boolean, user: Option[UserInfo]) /** * Create a new webhook authentication strategy from a given config file. * * @param path Path to the webhook configuration. * @param cacheTtl Time to live for authentication results. * @throws IllegalArgumentException If the provided path is not a readable file. */ def fromFile(path: Path, cacheTtl: Duration): WebhookAuthStrategy = { new WebhookAuthStrategy(Webhook.fromFile[ReviewResponse](path), cacheTtl) } }
gpl-3.0
PrestaShop/prestonbot
src/AppBundle/PullRequests/Repository.php
4368
<?php namespace AppBundle\PullRequests; use AppBundle\Search\Repository as SearchRepository; use Github\Api\Issue\Comments as KnpCommentsApi; use Github\Exception\RuntimeException; use PrestaShop\Github\Entity\Comment; use PrestaShop\Github\Entity\PullRequest; /** * Get the pull requests according to some filters * As GitHub consider pull requests as specific issues * don't be surprised too much by the produced repository. */ class Repository implements RepositoryInterface { /** * @var SearchRepository */ private $searchRepository; /** * @var KnpCommentsApi */ private $knpCommentsApi; /** * @var string */ private $repositoryOwner; /** * @var string */ private $repositoryName; public function __construct( SearchRepository $searchRepository, KnpCommentsApi $knpCommentsApi, $repositoryOwner, $repositoryName ) { $this->searchRepository = $searchRepository; $this->knpCommentsApi = $knpCommentsApi; $this->repositoryOwner = $repositoryOwner; $this->repositoryName = $repositoryName; } /** * {@inheritdoc} */ public function findAll(string $base = 'develop') { $pullRequests = []; $search = $this->searchRepository->getPullRequests(['base' => $base]); foreach ($search['items'] as $pullRequest) { $pullRequests[] = new PullRequest($pullRequest); } return $pullRequests; } /** * {@inheritdoc} */ public function findAllWithLabel(string $label, string $base = 'develop') { $pullRequests = []; $search = $this->searchRepository->getPullRequests( [ 'label' => $this->parseLabel($label), 'base' => $base, ] ); foreach ($search['items'] as $pullRequest) { $pullRequests[] = new PullRequest($pullRequest); } return $pullRequests; } /** * {@inheritdoc} */ public function getComments(PullRequest $pullRequest) { try { $commentsApi = $this->knpCommentsApi ->all( $this->repositoryOwner, $this->repositoryName, $pullRequest->getNumber() ) ; } catch (RuntimeException $e) { $commentsApi = []; } $comments = []; foreach ($commentsApi as $comment) { $comments[] = new Comment($comment); } return $comments; } /** * {@inheritdoc} */ public function getCommentsFrom(PullRequest $pullRequest, $userLogin) { $comments = $this->getComments($pullRequest); $userComments = []; foreach ($comments as $comment) { if ($userLogin === $comment->getUser()->getLogin()) { $userComments[] = $comment; } } return $userComments; } /** * {@inheritdoc} */ public function getCommentsByExpressionFrom( PullRequest $pullRequest, $expression, $userLogin ) { $userCommentsByExpression = []; $userComments = $this->getCommentsFrom($pullRequest, $userLogin); foreach ($userComments as $userComment) { if (false !== strpos($userComment->getBody(), $expression)) { $userCommentsByExpression[] = $userComment; } } return $userCommentsByExpression; } /** * {@inheritdoc} */ public function removeCommentsIfExists(PullRequest $pullRequest, $pattern, $userLogin) { $comments = $this->getCommentsByExpressionFrom( $pullRequest, $pattern, $userLogin ) ; if (\count($comments) > 0) { foreach ($comments as $comment) { $this->knpCommentsApi->remove( $this->repositoryOwner, $this->repositoryName, $comment->getId() ); } return true; } return false; } /** * @param $label * * @return string */ private function parseLabel(string $label) { return '"'.$label.'"'; } }
gpl-3.0
ericmjonas/pybm3d
pybm3d/__init__.py
90
"""PyBM3D package for image denoising.""" import pybm3d.bm3d as bm3d __all__ = ['bm3d']
gpl-3.0
gausie/croud
public/modules/points/config/points.client.config.js
289
'use strict'; // Configuring the Points module angular.module('points').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', '<i class="fa fa-map-marker"></i> Add a point!', 'createPoint', 'button', undefined, undefined, undefined, -1); } ]);
gpl-3.0
Booksonic-Server/madsonic-main
src/test/java/org/madsonic/domain/TranscodeSchemeTestCase.java
1601
/* This file is part of Madsonic. Madsonic is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Madsonic is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Madsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2009-2016 (C) Sindre Mehus, Martin Karel */ package org.madsonic.domain; import junit.framework.TestCase; import static org.madsonic.domain.TranscodeScheme.*; /** * Unit test of {@link TranscodeScheme}. * * @author Sindre Mehus, Martin Karel */ public class TranscodeSchemeTestCase extends TestCase { /** * Tests {@link TranscodeScheme#strictest}. */ public void testStrictest() { assertSame("Error in strictest().", OFF, OFF.strictest(null)); assertSame("Error in strictest().", OFF, OFF.strictest(OFF)); assertSame("Error in strictest().", MAX_32, OFF.strictest(MAX_32)); assertSame("Error in strictest().", MAX_32, MAX_32.strictest(null)); assertSame("Error in strictest().", MAX_32, MAX_32.strictest(OFF)); assertSame("Error in strictest().", MAX_32, MAX_32.strictest(MAX_64)); assertSame("Error in strictest().", MAX_32, MAX_64.strictest(MAX_32)); } }
gpl-3.0
StanShebs/gdb-doxy-test
gdbserver/search/variables_73.js
12044
var searchData= [ ['s390_5fbreakpoint',['s390_breakpoint',['../linux-s390-low_8c.html#a884b4915122741248c43f95f666f19fd',1,'linux-s390-low.c']]], ['s390_5fregmap',['s390_regmap',['../linux-s390-low_8c.html#a4b484b0afbb9bea8668d65622219ff8d',1,'linux-s390-low.c']]], ['s390_5fregsets',['s390_regsets',['../linux-s390-low_8c.html#abf86629862b0dec06c0caa21a82a6327',1,'linux-s390-low.c']]], ['s390_5fregsets_5finfo',['s390_regsets_info',['../linux-s390-low_8c.html#a0cea42cf872cb78b1cc02063057b38d9',1,'linux-s390-low.c']]], ['s390_5fusrregs_5finfo',['s390_usrregs_info',['../linux-s390-low_8c.html#a027d0dd8b46f783aacee23c5b47902e5',1,'linux-s390-low.c']]], ['sa',['sa',['../unionsocket__addr.html#a323a6c71fd9c959767a229ff1f4d7cdd',1,'socket_addr']]], ['seen_5fstep_5faction_5fflag',['seen_step_action_flag',['../tracepoint_8c.html#a5ac4d310cc9e38d8e2a259e4de5380d7',1,'tracepoint.c']]], ['send',['send',['../structtracepoint__action__ops.html#ad6abbfcabb7d02a11cd0366c580bbe78',1,'tracepoint_action_ops']]], ['server_5fwaiting',['server_waiting',['../server_8c.html#acceea17650beca3630fbde898b3d941e',1,'server_waiting():&#160;server.c'],['../server_8h.html#acceea17650beca3630fbde898b3d941e',1,'server_waiting():&#160;server.c']]], ['set_5fpc',['set_pc',['../structlinux__target__ops.html#a4437f47a5fb6fb64e1ee3e527c8bfe49',1,'linux_target_ops']]], ['set_5frequest',['set_request',['../structlynx__regset__info.html#a50b74ae1c6aa61866582277a4812ff5e',1,'lynx_regset_info']]], ['set_5fthread_5fcontext',['set_thread_context',['../structwin32__target__ops.html#a38da8f5fc455336acc6f3892308e18a3',1,'win32_target_ops']]], ['sh_5fbreakpoint',['sh_breakpoint',['../linux-sh-low_8c.html#a2aef7e44a19bd772b42c4dcbbc8c2c76',1,'linux-sh-low.c']]], ['sh_5fregmap',['sh_regmap',['../linux-sh-low_8c.html#ae430b7f74b230edad36adf9feae7cbdf',1,'linux-sh-low.c']]], ['sh_5fregsets',['sh_regsets',['../linux-sh-low_8c.html#ad3b3a6800fe9140b15dfa8447e73c6fc',1,'linux-sh-low.c']]], ['sh_5fregsets_5finfo',['sh_regsets_info',['../linux-sh-low_8c.html#a1b1eb5670c062aa9f37100a43009f844',1,'linux-sh-low.c']]], ['sh_5fusrregs_5finfo',['sh_usrregs_info',['../linux-sh-low_8c.html#a54872f059980f3b3b1081463dfa65808',1,'linux-sh-low.c']]], ['shlib_5fdisabled',['shlib_disabled',['../structraw__breakpoint.html#a452313e9f57631ed25f880536f6de8e6',1,'raw_breakpoint']]], ['sig',['sig',['../structthread__resume.html#a88bf6ec5d314b6dd090f9eaecf042e30',1,'thread_resume']]], ['siginfo_5ffixup',['siginfo_fixup',['../structlinux__target__ops.html#af501c9c0bccee20297e1eb7d3812fcc0',1,'linux_target_ops']]], ['signal',['signal',['../structpending__signals.html#a975a7d4ece4a96a6d70fa73a974ac099',1,'pending_signals']]], ['signal_5fpid',['signal_pid',['../server_8c.html#a555df195f15b266f5782c83e73d37d5d',1,'server.c']]], ['signals',['signals',['../signals_8c.html#a41d412dc9e329ebb343f9b309330f817',1,'signals.c']]], ['sin',['sin',['../unionsocket__addr.html#a29e9ed4e230b2c3f878d3d65a3ebf7c5',1,'socket_addr']]], ['sin6',['sin6',['../unionsocket__addr.html#a364961b97f7770ca4c603b3b20721e6a',1,'socket_addr']]], ['single_5fstep',['single_step',['../structwin32__target__ops.html#ad710db08d81e5db80197de02c5e7d9d9',1,'win32_target_ops']]], ['size',['size',['../structlynx__regset__info.html#aa902946a5d85eb8edad495a1728f87d4',1,'lynx_regset_info::size()'],['../structxtensa__regtable__t.html#ab98044bb67f5bb8d7433a85d6d95d521',1,'xtensa_regtable_t::size()']]], ['small_5fjump_5finsn',['small_jump_insn',['../linux-x86-low_8c.html#a6f090cdbefba0ade29f8e711827c7a48',1,'linux-x86-low.c']]], ['soft_5finterrupt_5frequested',['soft_interrupt_requested',['../win32-low_8c.html#a30eda9360246069e57881b842866b653',1,'win32-low.c']]], ['source_5fstrings',['source_strings',['../structtracepoint.html#ac7d851eeefb79a991244e88bade3adc0',1,'tracepoint']]], ['sparc_5fbreakpoint',['sparc_breakpoint',['../linux-sparc-low_8c.html#a1631888ea01d4dd576553ed684d695a5',1,'linux-sparc-low.c']]], ['sparc_5fregmap',['sparc_regmap',['../linux-sparc-low_8c.html#a02cd54a836c4cf5ea1c55d75de14c126',1,'linux-sparc-low.c']]], ['sparc_5fregsets',['sparc_regsets',['../linux-sparc-low_8c.html#ade2a927d12341f3866ba8397b28b2ca5',1,'linux-sparc-low.c']]], ['sparc_5fregsets_5finfo',['sparc_regsets_info',['../linux-sparc-low_8c.html#a95090bbd6167c12f0c12b86fa13b4cc9',1,'linux-sparc-low.c']]], ['sparc_5fusrregs_5finfo',['sparc_usrregs_info',['../linux-sparc-low_8c.html#afa0f27e6ee4573f0e06a00ea493fcdc9',1,'linux-sparc-low.c']]], ['spefscr',['spefscr',['../structgdb__evrregset__t.html#a3faf35a031814ce48da6017588fcb544',1,'gdb_evrregset_t']]], ['spu_5ftarget_5fops',['spu_target_ops',['../spu-low_8c.html#a6b8cd2cf25a10c59d16eaa05a29a523b',1,'spu-low.c']]], ['st_5fspace',['st_space',['../structi387__fsave.html#ae296faa64a1bd6eb5de060d85433bcbe',1,'i387_fsave::st_space()'],['../structi387__fxsave.html#a5aecb31adc6a62534e73684483536eb3',1,'i387_fxsave::st_space()'],['../structi387__xsave.html#adf91bd447b4b9a83f82e146963b0e153',1,'i387_xsave::st_space()']]], ['stabilize_5fthreads',['stabilize_threads',['../structtarget__ops.html#aa2a1ea5c7510fbf244a54cf60a494ebc',1,'target_ops']]], ['stabilizing_5fthreads',['stabilizing_threads',['../linux-low_8c.html#a6b63009f233d62cf5d2d853b16e8f460',1,'linux-low.c']]], ['start',['start',['../structtrace__buffer__control.html#a956507669c34bc6bca8d728f798dd108',1,'trace_buffer_control::start()'],['../structipa__trace__buffer__control.html#a6822bfc227dbe9bfaf147cbe5591660f',1,'ipa_trace_buffer_control::start()'],['../structreadonly__region.html#a78fb2f2d5d5c59e091036077bdab1db9',1,'readonly_region::start()']]], ['start_5fnon_5fstop',['start_non_stop',['../structtarget__ops.html#a6f3f8935ea9a90a5c6304902b48a4bb6',1,'target_ops']]], ['status',['status',['../structsimple__pid__list.html#a5f98e2307cd45342913e6bf3d58205a6',1,'simple_pid_list::status()'],['../structvstop__notif.html#a079946dc916ad751fe9828eab67a3b39',1,'vstop_notif::status()']]], ['status_5fpending',['status_pending',['../structlwp__info.html#a9118995c6bc80a31dc55bf592ff8e78c',1,'lwp_info']]], ['status_5fpending_5fp',['status_pending_p',['../structlwp__info.html#a06d72174a98904774838ad065b22dbff',1,'lwp_info']]], ['step_5factions',['step_actions',['../structtracepoint.html#a59760bf566cd491c2956e036476a3922',1,'tracepoint']]], ['step_5factions_5fstr',['step_actions_str',['../structtracepoint.html#adfa335dd0299f9d07d7e98959e342b8c',1,'tracepoint']]], ['step_5fcount',['step_count',['../structtracepoint.html#a8bae4ca63932cb0ceb5c052aaa8bc9c8',1,'tracepoint']]], ['step_5fover_5fbkpt',['step_over_bkpt',['../linux-low_8c.html#a67c86990035c32fe3ac55ff2d862ece7',1,'linux-low.c']]], ['step_5frange_5fend',['step_range_end',['../structlwp__info.html#a870a8c641fe6caec8900030106c8348e',1,'lwp_info::step_range_end()'],['../structthread__resume.html#ae2dc7724c297d70fd8476ace40bde143',1,'thread_resume::step_range_end()']]], ['step_5frange_5fstart',['step_range_start',['../structlwp__info.html#a7419951d035c060630a051aa5a118e05',1,'lwp_info::step_range_start()'],['../structthread__resume.html#a98e6e70ea81aa9e52dabbfea301f493d',1,'thread_resume::step_range_start()']]], ['stepping',['stepping',['../structlwp__info.html#aceb2e5672c59bd6143f7e2a4bfd7de34',1,'lwp_info']]], ['stop_5fexpected',['stop_expected',['../structlwp__info.html#a50c11467a9958321fd5cd9e063d76052',1,'lwp_info']]], ['stop_5fpc',['stop_pc',['../structlwp__info.html#a0a35eb9fff9d87ddf3aec9d0be58a74a',1,'lwp_info']]], ['stop_5ftracing_5fbkpt',['stop_tracing_bkpt',['../tracepoint_8c.html#a4404ea3180cae6f72c08982e06ec257a',1,'tracepoint.c']]], ['stopped',['stopped',['../structlwp__info.html#a8b51de0f6db2790336402296bbda3176',1,'lwp_info']]], ['stopped_5fby_5fwatchpoint',['stopped_by_watchpoint',['../structlinux__target__ops.html#aaec59e3feafe28ef46b54bf5a6017dac',1,'linux_target_ops::stopped_by_watchpoint()'],['../structlwp__info.html#a8c614d4fa52a4d8a1093826d421f7735',1,'lwp_info::stopped_by_watchpoint()'],['../structtarget__ops.html#a2ef66a1b39f75e7b51c2625a59726e70',1,'target_ops::stopped_by_watchpoint()'],['../structwin32__target__ops.html#a3832d795e9edc4d4221db12093546c8e',1,'win32_target_ops::stopped_by_watchpoint()']]], ['stopped_5fdata_5faddress',['stopped_data_address',['../structarch__lwp__info.html#ab37244cb83d70d89fe5b71ec3c5acd4f',1,'arch_lwp_info::stopped_data_address()'],['../structlinux__target__ops.html#a7f634a5ab419a8ceea20a30ed5a9c9b7',1,'linux_target_ops::stopped_data_address()'],['../structlwp__info.html#a760920cc629a065c444e10103dff6f06',1,'lwp_info::stopped_data_address()'],['../structtarget__ops.html#ab0c71085bdbeb081fc5d4e10dc8db70a',1,'target_ops::stopped_data_address()'],['../structwin32__target__ops.html#ac158ab187d2c0f1a2bcdc35debb253b1',1,'win32_target_ops::stopped_data_address()']]], ['stopped_5fpids',['stopped_pids',['../linux-low_8c.html#a5a82e149efcccd1710583f0a41850035',1,'linux-low.c']]], ['stopping_5fthreads',['stopping_threads',['../linux-low_8c.html#a8f7e6248f30ebe7475bc3350c0beb672',1,'linux-low.c']]], ['stopping_5ftracepoint',['stopping_tracepoint',['../tracepoint_8c.html#a254c89801b952af57cfb002c9394cffc',1,'tracepoint.c']]], ['store_5ffunction',['store_function',['../structlynx__regset__info.html#a9badee1ddb900593674fe23a35489c27',1,'lynx_regset_info']]], ['store_5finferior_5fregister',['store_inferior_register',['../structwin32__target__ops.html#a404fea17d1cc4ff8cc4a8655874a022a',1,'win32_target_ops']]], ['store_5fregisters',['store_registers',['../structtarget__ops.html#acef27aba3859abbbad8140a14e8c6f76',1,'target_ops']]], ['str',['str',['../structsource__string.html#ad0fabd61b31acbdaaadeec08605d9e48',1,'source_string']]], ['string',['string',['../structformat__piece.html#ab607ea636f54fedfb05f6bda5d31988e',1,'format_piece::string()'],['../signals_8c.html#ae1adbce218e7a9d09164012443191d24',1,'string():&#160;signals.c']]], ['supply_5fptrace_5fregister',['supply_ptrace_register',['../structlinux__target__ops.html#afacf193bca451d37d04cc996b529441f',1,'linux_target_ops']]], ['supports_5fagent',['supports_agent',['../structtarget__ops.html#ac8039d154f6fd72a25f44da259b0735a',1,'target_ops']]], ['supports_5fbtrace',['supports_btrace',['../structtarget__ops.html#ae5e9e6cbdb5c856eb382249959a126bb',1,'target_ops']]], ['supports_5fdisable_5frandomization',['supports_disable_randomization',['../structtarget__ops.html#add158cd91c0c1c360c607b20c00b7079',1,'target_ops']]], ['supports_5fmulti_5fprocess',['supports_multi_process',['../structtarget__ops.html#ae6b0c51607518aa2c902d9a1f9100e92',1,'target_ops']]], ['supports_5fnon_5fstop',['supports_non_stop',['../structtarget__ops.html#afc1738d66cffff1c52cf427fda805319',1,'target_ops']]], ['supports_5frange_5fstepping',['supports_range_stepping',['../structlinux__target__ops.html#add90141e1aa4b2bc54114a0da4519b9d',1,'linux_target_ops::supports_range_stepping()'],['../structtarget__ops.html#aeee5fac528df0575717cf92486408c7c',1,'target_ops::supports_range_stepping()']]], ['supports_5ftracepoints',['supports_tracepoints',['../structlinux__target__ops.html#a9ea8e6f6e38c8ef063a4241dd52852bc',1,'linux_target_ops::supports_tracepoints()'],['../structtarget__ops.html#a7f9f0f133b5b589bc933787ad7c64d03',1,'target_ops::supports_tracepoints()']]], ['suspended',['suspended',['../structlwp__info.html#a45c2d4f42164dc95dce5ef65944b1649',1,'lwp_info::suspended()'],['../structwin32__thread__info.html#ac724ca37646e1f6a55040aba8ff71f7d',1,'win32_thread_info::suspended()']]], ['symbol_5fcache',['symbol_cache',['../structprocess__info.html#af7df10558808d5b182a0cac4c988ac91',1,'process_info']]], ['symbol_5flist',['symbol_list',['../tracepoint_8c.html#a36885eec82d8f96d7e98326b26f3d43b',1,'symbol_list():&#160;tracepoint.c'],['../agent_8c.html#ae5df653d3ba5a4faaadd29f9fdfd8188',1,'symbol_list():&#160;agent.c']]], ['syscallno',['syscallno',['../structtd__notify.html#a4dff95cb1a8037f49edf4a3fa7665e04',1,'td_notify']]] ];
gpl-3.0
voidALPHA/cgc_viz
Assets/Packages/Plugins/Mono/FileDialog.cs
5289
// Copyright 2017 voidALPHA, Inc. // This file is part of the Haxxis video generation system and is provided // by voidALPHA in support of the Cyber Grand Challenge. // Haxxis is free software: you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software Foundation. // Haxxis is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A // PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with // Haxxis. If not, see <http://www.gnu.org/licenses/>. using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; using Chains; using ChainViews; using UnityEngine; using Application = UnityEngine.Application; #if UNITY_EDITOR using UnityEditor; #endif namespace Packages.Plugins.Mono { public static class FileDialog { //[DllImport( "user32.dll" )] //private static extern void SaveFileDialog(); //[DllImport( "user32.dll" )] //private static extern void OpenFileDialog(); //[DllImport( "user32.dll", EntryPoint = "GetActiveWindow" )] //private static extern IntPtr GetActiveWindow(); //[DllImport( "user32.dll" )] //static extern bool IsZoomed( IntPtr hWnd ); //[DllImport( "user32.dll" )] //private static extern bool ShowWindowAsync( IntPtr hWnd, int nCmdShow ); private static string InitialDirectory { get { var localRootPath = HaxxisPackage.RootPath; var remoteRootPath = Environment.GetEnvironmentVariable( @"CGC_REMOTE_HP_ROOT" ); var finalRootPath = ChainView.Instance.UseLocalPackageStore ? localRootPath : ( remoteRootPath ?? localRootPath ); return Path.GetFullPath( finalRootPath ); } } public static FilePicker.FilePickResult ShowOpenDialog(string title, FilePicker.FileFilter[] filters) { //Debug.Log( "Initial directory is " + InitialDirectory ); //#if UNITY_EDITOR // return EditorUtility.OpenFilePanel( "Open File", InitialDirectory, "json" ); //#else // using ( var diag = new OpenFileDialog() ) // { // diag.Multiselect = false; // diag.Filter = "Json Haxxis Packages (*.json)|*.json|All files (*.*)|*.*"; // diag.InitialDirectory = InitialDirectory; // diag.AutoUpgradeEnabled = true; // // Get window's maximized state // var windowHandle = GetActiveWindow(); // var maximized = IsZoomed( windowHandle ); // var result = diag.ShowDialog( new WindowWrapper { Handle = windowHandle } ); // // Restore window's maximized state // ShowWindowAsync( windowHandle, maximized ? 3 : 1 ); // if ( result == DialogResult.OK ) // { // return diag.FileName; // } // return string.Empty; // } //#endif return FilePicker.ShowOpenDialog(InitialDirectory, title, filters); } public static FilePicker.FilePickResult ShowSaveDialog(string title, FilePicker.FileFilter[] filters) { return ShowSaveDialog( string.Empty, title, filters ); } private class WindowWrapper : IWin32Window { public IntPtr Handle { get; set; } } public static FilePicker.FilePickResult ShowSaveDialog( string filename, string title, FilePicker.FileFilter[] filters ) { // TODO: This should respect the Local/Remote button, even if there is an open package. var pathSansFilename = string.IsNullOrEmpty( filename ) ? InitialDirectory : Path.GetFullPath( filename ); //#if UNITY_EDITOR // var filenameSansPath = Path.GetFileName( filename ); // return EditorUtility.SaveFilePanel( "Save File", pathSansFilename, filenameSansPath, "json" ); //#else // using ( var diag = new SaveFileDialog() ) // { // diag.Filter = "Json Haxxis Packages (*.json)|*.json|All files (*.*)|*.*"; // diag.InitialDirectory = pathSansFilename; // if ( !string.IsNullOrEmpty( filename ) ) // diag.FileName = filename; // // Get window's maximized state // var windowHandle = GetActiveWindow(); // var maximized = IsZoomed( windowHandle ); // var result = diag.ShowDialog( new WindowWrapper { Handle = windowHandle } ); // // Restore window's maximized state // ShowWindowAsync( windowHandle, maximized ? 3 : 1 ); // if ( result == DialogResult.OK ) // { // return diag.FileName; // } // return string.Empty; // } //#endif return FilePicker.ShowSaveDialog(pathSansFilename, title, filters); } } }
gpl-3.0
SpaceGroupUCL/qgisSpaceSyntaxToolkit
esstoolkit/external/networkx/algorithms/centrality/tests/test_closeness_centrality.py
10220
""" Tests for closeness centrality. """ import pytest import networkx as nx from networkx.testing import almost_equal class TestClosenessCentrality: @classmethod def setup_class(cls): cls.K = nx.krackhardt_kite_graph() cls.P3 = nx.path_graph(3) cls.P4 = nx.path_graph(4) cls.K5 = nx.complete_graph(5) cls.C4 = nx.cycle_graph(4) cls.T = nx.balanced_tree(r=2, h=2) cls.Gb = nx.Graph() cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) F = nx.florentine_families_graph() cls.F = F cls.LM = nx.les_miserables_graph() # Create random undirected, unweighted graph for testing incremental version cls.undirected_G = nx.fast_gnp_random_graph(n=100, p=0.6, seed=123) cls.undirected_G_cc = nx.closeness_centrality(cls.undirected_G) def test_wf_improved(self): G = nx.union(self.P4, nx.path_graph([4, 5, 6])) c = nx.closeness_centrality(G) cwf = nx.closeness_centrality(G, wf_improved=False) res = {0: 0.25, 1: 0.375, 2: 0.375, 3: 0.25, 4: 0.222, 5: 0.333, 6: 0.222} wf_res = {0: 0.5, 1: 0.75, 2: 0.75, 3: 0.5, 4: 0.667, 5: 1.0, 6: 0.667} for n in G: assert almost_equal(c[n], res[n], places=3) assert almost_equal(cwf[n], wf_res[n], places=3) def test_digraph(self): G = nx.path_graph(3, create_using=nx.DiGraph()) c = nx.closeness_centrality(G) cr = nx.closeness_centrality(G.reverse()) d = {0: 0.0, 1: 0.500, 2: 0.667} dr = {0: 0.667, 1: 0.500, 2: 0.0} for n in sorted(self.P3): assert almost_equal(c[n], d[n], places=3) assert almost_equal(cr[n], dr[n], places=3) def test_k5_closeness(self): c = nx.closeness_centrality(self.K5) d = {0: 1.000, 1: 1.000, 2: 1.000, 3: 1.000, 4: 1.000} for n in sorted(self.K5): assert almost_equal(c[n], d[n], places=3) def test_p3_closeness(self): c = nx.closeness_centrality(self.P3) d = {0: 0.667, 1: 1.000, 2: 0.667} for n in sorted(self.P3): assert almost_equal(c[n], d[n], places=3) def test_krackhardt_closeness(self): c = nx.closeness_centrality(self.K) d = { 0: 0.529, 1: 0.529, 2: 0.500, 3: 0.600, 4: 0.500, 5: 0.643, 6: 0.643, 7: 0.600, 8: 0.429, 9: 0.310, } for n in sorted(self.K): assert almost_equal(c[n], d[n], places=3) def test_florentine_families_closeness(self): c = nx.closeness_centrality(self.F) d = { "Acciaiuoli": 0.368, "Albizzi": 0.483, "Barbadori": 0.4375, "Bischeri": 0.400, "Castellani": 0.389, "Ginori": 0.333, "Guadagni": 0.467, "Lamberteschi": 0.326, "Medici": 0.560, "Pazzi": 0.286, "Peruzzi": 0.368, "Ridolfi": 0.500, "Salviati": 0.389, "Strozzi": 0.4375, "Tornabuoni": 0.483, } for n in sorted(self.F): assert almost_equal(c[n], d[n], places=3) def test_les_miserables_closeness(self): c = nx.closeness_centrality(self.LM) d = { "Napoleon": 0.302, "Myriel": 0.429, "MlleBaptistine": 0.413, "MmeMagloire": 0.413, "CountessDeLo": 0.302, "Geborand": 0.302, "Champtercier": 0.302, "Cravatte": 0.302, "Count": 0.302, "OldMan": 0.302, "Valjean": 0.644, "Labarre": 0.394, "Marguerite": 0.413, "MmeDeR": 0.394, "Isabeau": 0.394, "Gervais": 0.394, "Listolier": 0.341, "Tholomyes": 0.392, "Fameuil": 0.341, "Blacheville": 0.341, "Favourite": 0.341, "Dahlia": 0.341, "Zephine": 0.341, "Fantine": 0.461, "MmeThenardier": 0.461, "Thenardier": 0.517, "Cosette": 0.478, "Javert": 0.517, "Fauchelevent": 0.402, "Bamatabois": 0.427, "Perpetue": 0.318, "Simplice": 0.418, "Scaufflaire": 0.394, "Woman1": 0.396, "Judge": 0.404, "Champmathieu": 0.404, "Brevet": 0.404, "Chenildieu": 0.404, "Cochepaille": 0.404, "Pontmercy": 0.373, "Boulatruelle": 0.342, "Eponine": 0.396, "Anzelma": 0.352, "Woman2": 0.402, "MotherInnocent": 0.398, "Gribier": 0.288, "MmeBurgon": 0.344, "Jondrette": 0.257, "Gavroche": 0.514, "Gillenormand": 0.442, "Magnon": 0.335, "MlleGillenormand": 0.442, "MmePontmercy": 0.315, "MlleVaubois": 0.308, "LtGillenormand": 0.365, "Marius": 0.531, "BaronessT": 0.352, "Mabeuf": 0.396, "Enjolras": 0.481, "Combeferre": 0.392, "Prouvaire": 0.357, "Feuilly": 0.392, "Courfeyrac": 0.400, "Bahorel": 0.394, "Bossuet": 0.475, "Joly": 0.394, "Grantaire": 0.358, "MotherPlutarch": 0.285, "Gueulemer": 0.463, "Babet": 0.463, "Claquesous": 0.452, "Montparnasse": 0.458, "Toussaint": 0.402, "Child1": 0.342, "Child2": 0.342, "Brujon": 0.380, "MmeHucheloup": 0.353, } for n in sorted(self.LM): assert almost_equal(c[n], d[n], places=3) def test_weighted_closeness(self): edges = [ ("s", "u", 10), ("s", "x", 5), ("u", "v", 1), ("u", "x", 2), ("v", "y", 1), ("x", "u", 3), ("x", "v", 5), ("x", "y", 2), ("y", "s", 7), ("y", "v", 6), ] XG = nx.Graph() XG.add_weighted_edges_from(edges) c = nx.closeness_centrality(XG, distance="weight") d = {"y": 0.200, "x": 0.286, "s": 0.138, "u": 0.235, "v": 0.200} for n in sorted(XG): assert almost_equal(c[n], d[n], places=3) # # Tests for incremental closeness centrality. # @staticmethod def pick_add_edge(g): u = nx.utils.arbitrary_element(g) possible_nodes = set(g.nodes()) neighbors = list(g.neighbors(u)) + [u] possible_nodes.difference_update(neighbors) v = nx.utils.arbitrary_element(possible_nodes) return (u, v) @staticmethod def pick_remove_edge(g): u = nx.utils.arbitrary_element(g) possible_nodes = list(g.neighbors(u)) v = nx.utils.arbitrary_element(possible_nodes) return (u, v) def test_directed_raises(self): with pytest.raises(nx.NetworkXNotImplemented): dir_G = nx.gn_graph(n=5) prev_cc = None edge = self.pick_add_edge(dir_G) insert = True nx.incremental_closeness_centrality(dir_G, edge, prev_cc, insert) def test_wrong_size_prev_cc_raises(self): with pytest.raises(nx.NetworkXError): G = self.undirected_G.copy() edge = self.pick_add_edge(G) insert = True prev_cc = self.undirected_G_cc.copy() prev_cc.pop(0) nx.incremental_closeness_centrality(G, edge, prev_cc, insert) def test_wrong_nodes_prev_cc_raises(self): with pytest.raises(nx.NetworkXError): G = self.undirected_G.copy() edge = self.pick_add_edge(G) insert = True prev_cc = self.undirected_G_cc.copy() num_nodes = len(prev_cc) prev_cc.pop(0) prev_cc[num_nodes] = 0.5 nx.incremental_closeness_centrality(G, edge, prev_cc, insert) def test_zero_centrality(self): G = nx.path_graph(3) prev_cc = nx.closeness_centrality(G) edge = self.pick_remove_edge(G) test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insertion=False) G.remove_edges_from([edge]) real_cc = nx.closeness_centrality(G) shared_items = set(test_cc.items()) & set(real_cc.items()) assert len(shared_items) == len(real_cc) assert 0 in test_cc.values() def test_incremental(self): # Check that incremental and regular give same output G = self.undirected_G.copy() prev_cc = None for i in range(5): if i % 2 == 0: # Remove an edge insert = False edge = self.pick_remove_edge(G) else: # Add an edge insert = True edge = self.pick_add_edge(G) # start = timeit.default_timer() test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insert) # inc_elapsed = (timeit.default_timer() - start) # print(f"incremental time: {inc_elapsed}") if insert: G.add_edges_from([edge]) else: G.remove_edges_from([edge]) # start = timeit.default_timer() real_cc = nx.closeness_centrality(G) # reg_elapsed = (timeit.default_timer() - start) # print(f"regular time: {reg_elapsed}") # Example output: # incremental time: 0.208 # regular time: 0.276 # incremental time: 0.00683 # regular time: 0.260 # incremental time: 0.0224 # regular time: 0.278 # incremental time: 0.00804 # regular time: 0.208 # incremental time: 0.00947 # regular time: 0.188 assert set(test_cc.items()) == set(real_cc.items()) prev_cc = test_cc
gpl-3.0
Antokolos/NLB_Legacy
NLB_Bldr/DialogTriggeredStringConditionProperties.cpp
6213
// DialogTriggeredStringConditionProperties.cpp : implementation file // #include "stdafx.h" #include "NLB_Bldr.h" #include "NLB_BldrDoc.h" #include "MainFrm.h" #include "DialogTriggeredStringConditionProperties.h" #include "CBookVar.h" #include "CStringVar.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDialogTriggeredStringConditionProperties dialog CDialogTriggeredStringConditionProperties::CDialogTriggeredStringConditionProperties(CWnd* pParent /*=NULL*/) : CDialog(CDialogTriggeredStringConditionProperties::IDD, pParent) { //{{AFX_DATA_INIT(CDialogTriggeredStringConditionProperties) //}}AFX_DATA_INIT m_hwndlstConditionsParent = NULL; m_tsc.ConditionPairCur.pBVCondition = NULL; m_tsc.ConditionPairCur.pStrVar = NULL; m_fNeedToDisableAddButton = FALSE; m_fCloseImmediately = FALSE; } void CDialogTriggeredStringConditionProperties::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDialogTriggeredStringConditionProperties) DDX_Control(pDX, IDC_COMBO_VALUE, m_cbbValue); DDX_Control(pDX, IDC_COMBO_CONDITION, m_cbbCondition); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDialogTriggeredStringConditionProperties, CDialog) //{{AFX_MSG_MAP(CDialogTriggeredStringConditionProperties) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDialogTriggeredStringConditionProperties message handlers BOOL CDialogTriggeredStringConditionProperties::OnInitDialog() { int iConditionSel = 0; int iValueSel = 0; int iConditionCount = 0; int iAlreadyExistingConditionCount = 0; int iValueCount = 0; CMainFrame* pMainFrame = (CMainFrame*) AfxGetMainWnd(); CNLB_BldrDoc* pDoc; POSITION pos; int iBookVarsCount; CBookVar* pBookVarCur; int iItemPos; int iStrVarsCount; CStringVar* pStrVarCur; int i, j; S_TS_ConditionPair* pstsc; BOOL fCanInclude; LVITEM lvitem; BOOL fVarLBoxHasItems = FALSE; // Åñëè â ñïèñîê Condition íå áûëî äîáàâëåíî íè îäíîé ïåðåìåííîé, çàêðûâàåì äèàëîã ñðàçó æå, ñêàçàâ, ÷òî îáëîì. CString strTemp; CDialog::OnInitDialog(); m_fNeedToDisableAddButton = FALSE; iAlreadyExistingConditionCount = ::SendMessage(m_hwndlstConditionsParent, LVM_GETITEMCOUNT, 0, 0); if (pMainFrame) { pDoc = (CNLB_BldrDoc*) pMainFrame->GetActiveDocument(); ASSERT_VALID(pDoc); if (pDoc) { pos = pDoc->m_lstBookVars.GetHeadPosition(); iBookVarsCount = pDoc->m_lstBookVars.GetCount(); for (i=0; i<iBookVarsCount; i++) { pBookVarCur = pDoc->m_lstBookVars.GetAt(pos); // Ïðîâåðèì, ìîæåò áûòü, òàêîå óñëîâèå óæå åñòü. Òîãäà íå íàäî äîáàâëÿòü fCanInclude = TRUE; for (j = 0; j < iAlreadyExistingConditionCount; j++) { lvitem.iItem = j; lvitem.iSubItem = 0; lvitem.mask = LVIF_PARAM; if (::SendMessage(m_hwndlstConditionsParent, LVM_GETITEM, 0, (LPARAM) &lvitem)) { pstsc = (S_TS_ConditionPair*) lvitem.lParam; if ((pBookVarCur == pstsc->pBVCondition) && (pBookVarCur != m_tsc.ConditionPairCur.pBVCondition)) { fCanInclude = FALSE; break; } } } if (fCanInclude) { fVarLBoxHasItems = TRUE; //iItemPos = m_cbbCondition.AddString(pBookVarCur->Get_strBookVarName()); // Âìåñòî íåå èñïîëüçóåì InsertString, òàê êàê // Unlike the AddString method, InsertString does not cause a list with the LBS_SORT style to be sorted. // Èëè æå íàäî áûòü óâåðåííûì, ÷òî â ñïèñêå íå ñòîèò ãàëêà àâòîñîðòèðîâêè // -1 îçíà÷àåò "äîáàâèòü â êîíåö" iItemPos = m_cbbCondition.InsertString(-1, pBookVarCur->Get_strBookVarName()); if (iItemPos >= 0) { m_cbbCondition.SetItemDataPtr(iItemPos, pBookVarCur); if (pBookVarCur == m_tsc.ConditionPairCur.pBVCondition) iConditionSel = iConditionCount; iConditionCount++; } } pDoc->m_lstBookVars.GetNext(pos); } pos = pDoc->m_lstStrVars.GetHeadPosition(); iStrVarsCount = pDoc->m_lstStrVars.GetCount(); for (i=0; i<iStrVarsCount; i++) { pStrVarCur = pDoc->m_lstStrVars.GetAt(pos); if (pStrVarCur->m_lstStrVarParameters.GetCount() == 0) // Ïîçâîëÿåòñÿ äîáàâëÿòü òîëüêî ñòðîêè áåç ïàðàìåòðîâ! { if (pStrVarCur->m_lstStrVarDependencies.GetCount() == 0) strTemp = pStrVarCur->Get_strStrVarName(); else strTemp.Format(IDS_STRING_TSVAR_DEPENDENT_STRING_VALUE, pStrVarCur->Get_strStrVarName()); //iItemPos = m_cbbValue.AddString(strTemp); iItemPos = m_cbbValue.InsertString(-1, strTemp); if (iItemPos >= 0) { m_cbbValue.SetItemDataPtr(iItemPos, pStrVarCur); if (pStrVarCur == m_tsc.ConditionPairCur.pStrVar) iValueSel = iValueCount; iValueCount++; } } pDoc->m_lstStrVars.GetNext(pos); } } } m_cbbCondition.SetCurSel(iConditionSel); m_cbbValue.SetCurSel(iValueSel); if ((!fVarLBoxHasItems) || m_fCloseImmediately) { int nRet = IRETCODE_ALL_BOOKVARS_IS_USED; EndDialog(nRet); // This value is returned by DoModal! // Ôàêòè÷åñêè, çàêðûòèå äèàëîãà ïðîèçîéäåò óæå ÏÎÑËÅ âûõîäà èç ýòîé ôóíêöèè, ò.å. ïî ãðàìîòíîìó } if (m_fCloseImmediately) { if (iConditionCount == 0) m_fNeedToDisableAddButton = TRUE; // Ýòîò âàðèàíò - êîãäà îòêðûâàåòñÿ óæå ïîëíîñòüþ çàïîëíåííàÿ ïåðåìåííàÿ, ò.å. íåëüçÿ äîáàâèòü íîâûé ýëåìåíò. À â ñòðî÷êå íèæå äîáàâëÿåìûé ýëåìåíò áóäåò ïîñëåäíèì, ò.å. òîæå íàäî äèçàáëèòü Add } else { if (iConditionCount == 1) m_fNeedToDisableAddButton = TRUE; // Åñëè áîëüøå íåëüçÿ äîáàâèòü íè îäíîãî ýëåìåíòà, íàäî çàïðåòèòü èõ äàëüíåéøåå äîáàâëåíèå } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDialogTriggeredStringConditionProperties::OnOK() { int iItemPos; iItemPos = m_cbbCondition.GetCurSel(); m_tsc.ConditionPairCur.pBVCondition = (CBookVar*) m_cbbCondition.GetItemDataPtr(iItemPos); iItemPos = m_cbbValue.GetCurSel(); m_tsc.ConditionPairCur.pStrVar = (CStringVar*) m_cbbValue.GetItemDataPtr(iItemPos); CDialog::OnOK(); }
gpl-3.0
wh1t3cAt1k/whitemath
whiteMath/WhiteMath/ArithmeticLong/LongArithmeticMethods.cs
29216
using System; using System.Collections.Generic; using System.Linq; using WhiteMath.General; using WhiteStructs.Conditions; using WhiteStructs.Collections; namespace WhiteMath.ArithmeticLong { /// <summary> /// This class provides static methods for various long /// integer calculation purposes. /// </summary> public static class LongIntegerMethods { /// <summary> /// Checks whether the specified long integer number is even. /// </summary> /// <param name="BASE">The base of digits of the <paramref name="operand"/>. If even, the checking takes O(1) time. If odd, the time is O(n).</param> /// <param name="operand">A list which contains the digits of the long integer modulo <paramref name="BASE"/>, starting with the least significant digit.</param> /// <returns>True if the long integer number defined by <paramref name="operand"/> is even, false otherwise.</returns> public static bool IsEven(int BASE, IReadOnlyList<int> operand) { Condition.Validate(BASE > 1).OrArgumentOutOfRangeException(Messages.DigitBaseNeedsToBeBiggerThanOne); Condition.ValidateNotNull(operand, nameof(operand)); Condition.ValidateNotEmpty(operand, Messages.DigitArrayNeedsToHaveAtLeastOneDigit); if (BASE % 2 == 0) { return operand[0] % 2 == 0; } else { // Можно считать, что существует "виртуальная нулевая цифра". // Она четна. // Потом мы как будто накапливаем сумму с произведениями вида // a_i * BASE^i. Так как BASE^i всегда нечетная при нечетном BASE, // то этот член четен, если a_i четно. // На каждом шаге к текущей сумме и текущему члену применяем правило: // Чет + Нечет = Нечет. // Чет + Чет = Чет. // Нечет + Нечет = Чет. bool currentSumEven = true; for (int i = 0; i < operand.Count; ++i) { currentSumEven = (currentSumEven == (operand[i] % 2 == 0)); } return currentSumEven; } } /// <summary> /// Checks whether the specified long integer number is divisible by five. /// </summary> /// <param name="BASE">The base of digits of the <paramref name="operand"/>. If divisible by five, the checking takes O(1) time. If not, the time is O(n).</param> /// <param name="operand">A list which contains the digits of the long integer modulo <paramref name="BASE"/>, starting with the least significant digit.</param> /// <returns>True if the long integer number defined by <paramref name="operand"/> is divisible by five, false otherwise.</returns> public static bool IsDivisibleByFive(int BASE, IReadOnlyList<int> operand) { Condition.Validate(BASE > 1).OrArgumentOutOfRangeException(Messages.DigitBaseNeedsToBeBiggerThanOne); Condition.ValidateNotNull(operand, nameof(operand)); Condition.ValidateNotEmpty(operand, Messages.DigitArrayNeedsToHaveAtLeastOneDigit); if (BASE % 5 == 0) return operand[0] % 5 == 0; else { int lastBaseDigit = BASE % 10; // We work with series of remainders of BASE divided by five. // - int[] remainderSeries; switch (lastBaseDigit) { case 0: case 5: remainderSeries = new int[] { 0 }; break; case 1: case 6: remainderSeries = new int[] { 1 }; break; case 2: case 7: remainderSeries = new int[] { 2, 4, 3, 1 }; break; case 3: case 8: remainderSeries = new int[] { 3, 4, 2, 1 }; break; case 4: case 9: remainderSeries = new int[] { 4, 1 }; break; default: throw new InvalidProgramException(); } int currentRemainder = operand[0] % 5; for (int i = 1; i < operand.Count; ++i) { currentRemainder = (currentRemainder + operand[i] * remainderSeries[(i - 1) % remainderSeries.Length] % 5) % 5; } return (currentRemainder % 5 == 0); } } /// <summary> /// Checks whether one natural long integer number is bigger than another. /// Digit arrays can contain leading zeroes, digits should be of the same /// base for both parameters. Need not specify BASE. /// </summary> /// <param name="one">The first long integer digits array.</param> /// <param name="two">The second long integer digits array.</param> /// <param name="equals">The out argument showing if the second number is actually equal to the first one.</param> /// <returns></returns> public static bool GreaterThan(IReadOnlyList<int> one, IReadOnlyList<int> two, out bool equals) { Condition.ValidateNotNull(one, nameof(one)); Condition.ValidateNotNull(two, nameof(two)); equals = true; int i; int smallerLength = (one.Count < two.Count ? one.Count : two.Count); int biggerLength = (one.Count < two.Count ? two.Count : one.Count); for (i = biggerLength - 1; i >= smallerLength; i--) { // Если первое число длиннее другого, идем с конца, как только не ноль - точно больше. // - if (one.Count == biggerLength && one[i] != 0) { equals = false; return true; } // Если второе число длиннее другого, идем с конца, как только не ноль - точно меньше. // - else if (two.Count == biggerLength && two[i] != 0) { equals = false; return false; } } for (; i >= 0; i--) { if (one[i] > two[i]) { equals = false; return true; } else if (one[i] < two[i]) { equals = false; return false; } } return false; } /// <summary> /// Checks whether the two natural long integers store the same value. /// Digits array can contain leading zeroes, digits should be of the same BASE. (need not specify) /// </summary> public static bool Equals(IReadOnlyList<int> one, IReadOnlyList<int> two) { Condition.ValidateNotNull(one, nameof(one)); Condition.ValidateNotNull(two, nameof(two)); int i; int smallerLength = (one.Count < two.Count ? one.Count : two.Count); int biggerLength = (one.Count < two.Count ? two.Count : one.Count); // Длины чисел не равны, если в большем встретится нечто, что не ноль - числа точно не равны. for (i = biggerLength - 1; i >= smallerLength; i--) if (one.Count == biggerLength && one[i] != 0 || two[i] != 0) return false; // Теперь проверяем поцифирькно for (; i >= 0; i--) if (one[i] != two[i]) return false; return true; } // ------------------------------------- // ---------------- SUM ---------------- // ------------------------------------- /// <summary> /// Returns the sum of several long integer numbers. /// </summary> /// <param name="BASE">The base of digits in numbers (ex.: 10, 100, 1000)</param> /// <param name="sumOperands">An array of sum operands.</param> /// <returns>The digit array containing the sum and NO trailing zeroes.</returns> public static int[] Sum(int BASE, IList<int>[] sumOperands) { Condition.Validate(BASE > 1).OrArgumentOutOfRangeException(Messages.DigitBaseNeedsToBeBiggerThanOne); Condition.ValidateNotNull(sumOperands, nameof(sumOperands)); Condition.Validate(sumOperands.Count() > 1).OrArgumentException(Messages.MoreThanOneOperandRequired); int n = sumOperands.Max(delegate(IList<int> operand) { return operand.Count; }); int m = sumOperands.Length; int[] result = new int[n + (int)Math.Ceiling(Math.Log(m, BASE))]; Sum(BASE, result, sumOperands); return result.Cut(); } /// <summary> /// Calculates the sum of several long integer numbers. /// </summary> /// <remarks> /// WARNING: if the length of the largest operand is N, and there are M operands, /// the result should be safe to store at least N + ceil(log(M, BASE)) digits. Note that no checking /// is performed, thus the operation may result in a loss. /// </remarks> /// <param name="result">The result digits array. Should be safe to store at least N + ceil(log(M, BASE)) digits.</param> /// <param name="BASE">The base of digits in numbers (ex.: 10, 100, 1000)</param> public static void Sum(int BASE, IList<int> result, params IList<int>[] sumOperands) { Condition.Validate(BASE > 1).OrArgumentOutOfRangeException(Messages.DigitBaseNeedsToBeBiggerThanOne); Condition.ValidateNotNull(result, nameof(result)); Condition.ValidateNotNull(sumOperands, nameof(sumOperands)); Condition.Validate(sumOperands.Length > 1).OrArgumentException(Messages.MoreThanOneOperandRequired); int i; long tmp; int carry = 0; for (i = 0; i < result.Count; i++) { tmp = carry; foreach (IList<int> op in sumOperands) if (i < op.Count) tmp += op[i]; result[i] = (int)(tmp % BASE); carry = (int)(tmp / BASE); } } /// <summary> /// Returns the sum of two long integer numbers, each shifted /// left by certain amounts of BASE-based digits. /// </summary> /// <param name="BASE">The base of digits in the numbers.</param> /// <param name="operand1">The digits list of the first number.</param> /// <param name="shift1">A positive amount of digits for the first number to shift left by.</param> /// <param name="operand2">The digits list of the second number.</param> /// <param name="shift2">A positive amount of digits for the second number to shift left by.</param> /// <returns>The digits array of the result containing only significant digits.</returns> public static int[] SumShifted(int BASE, IList<int> operand1, int shift1, IList<int> operand2, int shift2) { Condition .Validate(shift1 >= 0) .OrArgumentOutOfRangeException(Messages.CannotShiftByNegativeNumberOfDigits); Condition .Validate(shift2 >= 0) .OrArgumentOutOfRangeException(Messages.CannotShiftByNegativeNumberOfDigits); Condition.ValidateNotNull(operand1, nameof(operand1)); Condition.ValidateNotNull(operand2, nameof(operand2)); int[] result = new int[Math.Max(operand1.Count + shift1, operand2.Count + shift2) + 1]; SumShifted(BASE, result, operand1, shift1, operand2, shift2); return result.Cut(); } /// <summary> /// Calculates the sum of two long integer numbers, each shifted /// left by certain amounts of BASE-based digits. /// </summary> /// <param name="BASE">The base of digits in the numbers.</param> /// <param name="result">The digits list to store the result. If N = max(operand1.Count + shift1, operand2.Count + shift2), this list should be able to store at least N+1 digits. Otherwise, the result will be cut.</param> /// <param name="operand1">The digits list of the first number.</param> /// <param name="shift1">A positive amount of digits for the first number to shift left by.</param> /// <param name="operand2">The digits list of the second number.</param> /// <param name="shift2">A positive amount of digits for the second number to shift left by.</param> public static void SumShifted(int BASE, IList<int> result, IList<int> operand1, int shift1, IList<int> operand2, int shift2) { Condition .Validate(shift1 >= 0) .OrArgumentOutOfRangeException(Messages.CannotShiftByNegativeNumberOfDigits); Condition .Validate(shift2 >= 0) .OrArgumentOutOfRangeException(Messages.CannotShiftByNegativeNumberOfDigits); Condition.ValidateNotNull(operand1, nameof(operand1)); Condition.ValidateNotNull(operand2, nameof(operand2)); Condition.ValidateNotNull(result, nameof(result)); int i; long tmp; int carry = 0; for (i = 0; i < result.Count; i++) { tmp = carry; if (i - shift1 >= 0 && i - shift1 < operand1.Count) tmp += operand1[i - shift1]; if (i - shift2 >= 0 && i - shift2 < operand2.Count) tmp += operand2[i - shift2]; result[i] = (int)(tmp % BASE); carry = (int)(tmp / BASE); } return; } // --------------------------------------- // ----------- DIFFERENCE ---------------- // --------------------------------------- /// <summary> /// Calculates the difference between two natural long integer numbers. /// WARNING: if the length of the bigger number is N, then the result /// digits array should be able to store N digits as well. /// No checking is performed, thus an <c>IndexOutOfBoundsException</c> can be thrown. /// We assume that number 'one' is greater than number 'two'. /// If, nevertheless, <paramref name="two"/> is bigger than <paramref name="one"/>, the function would return <c>true</c> /// and the result would be equal to (<c>BASE^result.Length - trueResultValue</c>); /// </summary> /// <param name="one"></param> /// <param name="two"></param> /// <param name="result"></param> /// <param name="BASE"></param> public static bool Subtract(int BASE, IList<int> result, IReadOnlyList<int> one, IReadOnlyList<int> two) { Condition.ValidateNotNull(one, nameof(one)); Condition.ValidateNotNull(two, nameof(two)); Condition.ValidateNotNull(result, nameof(result)); // TODO: turn this into a unit test. // Contract.Ensures(Contract.ForAll(result, x => (x >= 0))); int i; int temp; int carry = 0; for (i = 0; i < result.Count; i++) { temp = -carry; if (i < one.Count) temp += one[i]; if (i < two.Count) temp -= two[i]; carry = 0; while (temp < 0) { carry++; temp += BASE; } result[i] = temp; } return (carry != 0); } // --------------------------------------- // ---------------- DIVISION ------------- // --------------------------------------- /// <summary> /// Performs the division (with remainder) of two long integer numbers. /// Returns the quotient containing only significant digits. /// /// The remainder containing only significant digits is passed as an 'out' parameter. /// </summary> /// <param name="BASE">The digit base integers to divide one by another.</param> /// <param name="one">The dividend.</param> /// <param name="two">The divisor.</param> /// <param name="remainder">The reference to store the remainder.</param> /// <returns>The quotient containing only significant digits (no trailing zeroes).</returns> public static IList<int> Divide(int BASE, IReadOnlyList<int> one, IReadOnlyList<int> two, out IList<int> remainder) { Condition.ValidateNotNull(one, nameof(one)); Condition.ValidateNotNull(two, nameof(two)); /* * TODO: make this into a unit test * Contract.Ensures(Contract.Result<IList<int>>() != null); // result's not null Contract.Ensures(Contract.ValueAtReturn<IList<int>>(out remainder) != null); // remainder's not null Contract.Ensures(Contract.ForAll(Contract.Result<IList<int>>(), (x => (x >= 0)))); // the result has positive digits Contract.Ensures(Contract.ForAll(Contract.ValueAtReturn<IList<int>>(out remainder), (x => (x >= 0)))); // the remainder has positive digits */ int[] result = new int[one.CountSignificant() - two.CountSignificant() + 1]; remainder = Divide(BASE, result, one, two).AsReadOnly().Cut(); return result.Cut(); } /// <summary> /// Performs the division (with remainder) of two long integer numbers. /// The method would return the list containing the remainder digits. /// </summary> /// <returns>The list containing the remainder digits.</returns> /// <param name="BASE">The numberic base of the digits, ex. 10 000</param> /// <param name="result">The digits array to store the result. WARNING! Should be able to store AT LEAST one.Count - two.Count + 1 digits.</param> /// <param name="one">The digits array containing the first operand.</param> /// <param name="two">The digits array containing the second operand.</param> public static IList<int> Divide(int BASE, IList<int> result, IReadOnlyList<int> one, IReadOnlyList<int> two) { Condition.ValidateNotNull(one, nameof(one)); Condition.ValidateNotNull(two, nameof(two)); Condition.ValidateNotNull(result, nameof(result)); Condition.Validate(one.All(digit => digit >= 0)).OrArgumentException(Messages.OperandShouldNotContainNegativeDigits); Condition.Validate(two.All(digit => digit >= 0)).OrArgumentException(Messages.OperandShouldNotContainNegativeDigits); /* Contract.Requires(Contract.ForAll(one, x => x >= 0)); // first contains only positive digits Contract.Requires(Contract.ForAll(two, x => x >= 0)); // second contains only positive digits */ /* * TODO: turn this into a unit test Contract.Ensures(Contract.Result<IList<int>>() != null); // remainder's not null Contract.Ensures(Contract.ForAll(Contract.Result<IList<int>>(), x => x >= 0)); // remainder has positive digits Contract.Ensures(Contract.ForAll(result, x => x >= 0)); // quot has positive digits */ // Обнуляем результат result.FillByAssign(0); // ------------------ IList<int> u; IList<int> v; int uShift, vShift, i; long temp, temp1, temp2; int scale; int qGuess, remainder; int borrow, carry; // Check if we need to scale. If yes, alas, // additional memory needs to be allocated. // - scale = BASE / (two[two.CountSignificant() - 1] + 1); if (scale > 1) { u = new int[one.Count + 2]; v = new int[two.Count + 2]; int[] scaleDigitsArray = { scale }; MultiplySimple(BASE, u, one, scaleDigitsArray); MultiplySimple(BASE, v, two, scaleDigitsArray); } else { // The number will be spoiled, so we need to // create a copy. // - u = new int[one.CountSignificant() + 1]; ServiceMethods.Copy(one, 0, u, 0, u.Count - 1); v = new int[two.CountSignificant()]; ServiceMethods.Copy(one, 0, v, 0, v.Count); } int n = v.AsReadOnly().CountSignificant(); int m = u.AsReadOnly().CountSignificant() - n; // Added -1. // - for (vShift = m, uShift = n + vShift; vShift >= 0; --vShift, --uShift) { qGuess = (int)(((long)u[uShift] * BASE + u[uShift - 1]) / v[n - 1]); remainder = (int)(((long)u[uShift] * BASE + u[uShift - 1]) % v[n - 1]); while (remainder < BASE) { temp2 = (long)v[n - 2] * qGuess; temp1 = (long)remainder * BASE + u[uShift - 2]; if ((temp2 > temp1) || (qGuess == BASE)) { --qGuess; remainder += v[n - 1]; } else break; } // Теперь qGuess - правильное частное или на единицу больше q // Вычесть делитель B, умноженный на qGuess из делимого U, // начиная с позиции vJ+i carry = 0; borrow = 0; // Loop over the second number's digits. // - for (i = 0; i < n; i++) { // получить в temp цифру произведения B*qGuess temp1 = (long)v[i] * qGuess + carry; carry = (int)(temp1 / BASE); temp1 -= (long)carry * BASE; // Сразу же вычесть из U temp2 = (long)u[i + vShift] - temp1 + borrow; if (temp2 < 0) { u[i + vShift] = (int)(temp2 + BASE); borrow = -1; } else { u[i + vShift] = (int)temp2; borrow = 0; } } // возможно, умноженое на qGuess число B удлинилось. // Если это так, то после умножения остался // неиспользованный перенос carry. Вычесть и его тоже. temp2 = (long)u[i + vShift] - carry + borrow; if (temp2 < 0) { u[i + vShift] = (int)temp2 + BASE; borrow = -1; } else { u[i + vShift] = (int)temp2; borrow = 0; } // Did the subtraction go normally? // - if (borrow == 0) { // Yes, the quotient guess was correct. // - result[vShift] = qGuess; } else { // No, the last borrow during subtraction is -1, // which means qGuess is 1 larger than the true // quotient. // - result[vShift] = qGuess - 1; // добавить одно, вычтенное сверх необходимого B к U carry = 0; for (i = 0; i < n; i++) { temp = (long)u[i + vShift] + v[i] + carry; if (temp >= BASE) { u[i + vShift] = (int)(temp - BASE); carry = 1; } else { u[i + vShift] = (int)temp; carry = 0; } } u[i + vShift] = u[i + vShift] + carry - BASE; } // Обновим размер U, который после вычитания мог уменьшиться // i = u.Length - 1; // while ((i > 0) && (u[i] == 0)) // u.digits.RemoveAt(i--); } // Return the remainder, also need to scale back. // - int[] remainderDigits = new int[u.Count]; DivideByInteger(BASE, remainderDigits, u.AsReadOnly(), scale); return remainderDigits; } /// <summary> /// Divides the natural long integer number by a natural integer value. /// The method would return an array containing only significant digits of the quotient. /// The integer remainder is passed as an out parameter. /// </summary> /// <param name="BASE">The base of dividend's digits.</param> /// <param name="one">The natural long integer dividend.</param> /// <param name="two">The natural integer divisor.</param> /// <param name="remainder">The reference to store the remainder.</param> /// <returns>An array containing only significant digits of the quotient.</returns> public static int[] DivideByInteger(int BASE, IReadOnlyList<int> one, int two, out int remainder) { Condition.ValidateNotNull(one, nameof(one)); Condition.Validate(two > 0).OrArgumentOutOfRangeException(Messages.DivisorShouldBePositive); int[] result = new int[one.Count]; remainder = DivideByInteger(BASE, result, one, two); return result.Cut(); } /// <summary> /// Divides the natural long integer number by a natural integer value. /// The method would return the remainder of the operation. /// </summary> /// <param name="BASE">The base of the digits in operands.</param> /// <param name="result">The digit array to contain the result. WARNING! Should be safe to store all [one.Count] digits</param> /// <param name="one">The first operand. Should be non-negative.</param> /// <param name="two">The second operand. Should be positive.</param> public static int DivideByInteger(int BASE, IList<int> result, IReadOnlyList<int> one, int two) { Condition.ValidateNotNull(result, nameof(result)); Condition.ValidateNotNull(one, nameof(one)); Condition.Validate(two > 0).OrArgumentOutOfRangeException(Messages.DivisorShouldBePositive); Condition.Validate(one.All(digit => digit >= 0)).OrArgumentException(Messages.OperandShouldNotContainNegativeDigits); int i; long remainder = 0; long temp; for (i = result.Count - 1; i >= one.Count; i--) result[i] = 0; for (; i >= 0; i--) { temp = remainder * BASE + one[i]; result[i] = (int)(temp / two); remainder = temp - (long)result[i] * two; } // the remainder now equals // the overall remainder return (int)remainder; } // -------------------------------- // -------- MULTIPLICATION -------- // -------------------------------- /// <summary> /// Multiplies one natural long integer by another. /// The result digits array must be safe to contain one.Count + two.Count elements. /// </summary> public static void MultiplySimple(int BASE, IList<int> result, IReadOnlyList<int> one, IReadOnlyList<int> two) { Condition.ValidateNotNull(result, nameof(result)); Condition.ValidateNotNull(one, nameof(one)); Condition.ValidateNotNull(two, nameof(two)); Condition.Validate(one.All(digit => digit >= 0)).OrArgumentException(Messages.OperandShouldNotContainNegativeDigits); Condition.Validate(two.All(digit => digit >= 0)).OrArgumentException(Messages.OperandShouldNotContainNegativeDigits); result.FillByAssign(0); int i, j; long shift; // перенос long temp; // временный результат for (i = 0; i < one.Count; i++) { shift = 0; for (j = 0; j < two.Count; j++) { temp = shift + (long)one[i] * two[j] + result[i + j]; shift = temp / BASE; result[i + j] = (int)(temp - shift * BASE); } result[i + j] = (int)shift; } } } }
gpl-3.0
Moony22/Compact_Crafting
src/main/java/moony/compactcrafting/worldgenerators/WorldGeneratorCNR.java
1130
package moony.compactcrafting.worldgenerators; import java.util.Random; import moony.compactcrafting.CCMain; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; import cpw.mods.fml.common.IWorldGenerator; public class WorldGeneratorCNR implements IWorldGenerator { public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { switch (world.provider.dimensionId) { case -1: generateNether(world, random, chunkX*16, chunkZ*16); case 0: generateSurface(world, random, chunkX*16, chunkZ*16); } } private void generateSurface(World world, Random random, int blockX, int blockZ) { } private void generateNether(World world, Random random, int blockX, int blockZ) { int Xcoord = blockX + random.nextInt(16); int Ycoord = random.nextInt(60); int Zcoord = blockZ + random.nextInt(16); (new WorldGenMinableNether(CCMain.CompactNetherrack, random.nextInt(20))).generate(world, random, Xcoord, Ycoord, Zcoord); } }
gpl-3.0
aristide/playSMS
web/plugin/feature/simplerate/simplerate.php
7078
<?php /** * This file is part of playSMS. * * playSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * playSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with playSMS. If not, see <http://www.gnu.org/licenses/>. */ defined('_SECURE_') or die('Forbidden'); if (!auth_isadmin()) { auth_block(); } switch (_OP_) { case "simplerate_list": $content = _dialog() . " <h2>" . _('Manage SMS rate') . "</h2> <p>" . _button('index.php?app=main&inc=feature_simplerate&op=simplerate_add', _('Add rate')) . " <div class=table-responsive> <table class=playsms-table-list> <thead><tr> <th width='50%'>" . _('Destination') . "</th> <th width='20%'>" . _('Prefix') . "</th> <th width='20%'>" . _('Rate') . "</th> <th width='10%'>" . _('Action') . "</th> </tr></thead> <tbody>"; $i = 0; $db_query = "SELECT * FROM " . _DB_PREF_ . "_featureSimplerate ORDER BY dst"; $db_result = dba_query($db_query); while ($db_row = dba_fetch_array($db_result)) { $action = "<a href=\"" . _u('index.php?app=main&inc=feature_simplerate&op=simplerate_edit&rateid=' . $db_row['id']) . "\">" . $icon_config['edit'] . "</a>"; $action .= "<a href=\"javascript: ConfirmURL('" . _('Are you sure you want to delete rate ?') . " (" . _('destination') . ": " . $db_row['dst'] . ", " . _('prefix') . ": " . $db_row['prefix'] . ")','" . _u('index.php?app=main&inc=feature_simplerate&op=simplerate_del&rateid=' . $db_row['id']) . "')\">" . $icon_config['delete'] . "</a>"; $i++; $content .= " <tr> <td>" . $db_row['dst'] . "</td> <td>" . $db_row['prefix'] . "</td> <td>" . $db_row['rate'] . "</td> <td>$action</td> </tr>"; } $content .= " </tbody></table> </div> " . _button('index.php?app=main&inc=feature_simplerate&op=simplerate_add', _('Add rate')); _p($content); break; case "simplerate_del": $rateid = $_REQUEST['rateid']; $dst = simplerate_getdst($rateid); $prefix = simplerate_getprefix($rateid); $_SESSION['dialog']['info'][] = _('Fail to delete rate') . " (" . _('destination') . ": $dst, " . _('prefix') . ": $prefix)"; $db_query = "DELETE FROM " . _DB_PREF_ . "_featureSimplerate WHERE id='$rateid'"; if (@dba_affected_rows($db_query)) { $_SESSION['dialog']['info'][] = _('Rate has been deleted') . " (" . _('destination') . ": $dst, " . _('prefix') . ": $prefix)"; } header("Location: " . _u('index.php?app=main&inc=feature_simplerate&op=simplerate_list')); exit(); break; case "simplerate_edit": $rateid = $_REQUEST['rateid']; $dst = simplerate_getdst($rateid); $prefix = simplerate_getprefix($rateid); $rate = simplerate_getbyid($rateid); $content = _dialog() . " <h2>" . _('Manage SMS rate') . "</h2> <h3>" . _('Edit rate') . "</h3> <form action='index.php?app=main&inc=feature_simplerate&op=simplerate_edit_save' method='post'> " . _CSRF_FORM_ . " <input type='hidden' name='rateid' value=\"$rateid\"> <table class=playsms-table> <tr> <td class=label-sizer>" . _('Destination') . "</td><td><input type='text' maxlength='30' name='up_dst' value=\"$dst\"></td> </tr> <tr> <td>" . _('Prefix') . "</td><td><input type='text' maxlength=10 name='up_prefix' value=\"$prefix\"></td> </tr> <tr> <td>" . _('Rate') . "</td><td><input type='text' maxlength=14 name='up_rate' value=\"$rate\"></td> </tr> </table> <p><input type='submit' class='button' value='" . _('Save') . "'></p> </form> " . _back('index.php?app=main&inc=feature_simplerate&op=simplerate_list'); _p($content); break; case "simplerate_edit_save": $rateid = $_POST['rateid']; $up_dst = $_POST['up_dst']; $up_prefix = $_POST['up_prefix']; $up_prefix = preg_replace('/[^0-9.]*/', '', $up_prefix); $up_rate = $_POST['up_rate']; $_SESSION['dialog']['info'][] = _('No changes made!'); if ($rateid && $up_dst && ($up_prefix >= 0) && ($up_rate >= 0)) { $db_query = "UPDATE " . _DB_PREF_ . "_featureSimplerate SET c_timestamp='" . time() . "',dst='$up_dst',prefix='$up_prefix',rate='$up_rate' WHERE id='$rateid'"; if (@dba_affected_rows($db_query)) { $_SESSION['dialog']['info'][] = _('Rate has been saved') . " (" . _('destination') . ": $up_dst, " . _('prefix') . ": $up_prefix)"; } else { $_SESSION['dialog']['info'][] = _('Fail to save rate') . " (" . _('destination') . ": $up_dst, " . _('prefix') . ": $up_prefix)"; } } else { $_SESSION['dialog']['info'][] = _('You must fill all fields'); } header("Location: " . _u('index.php?app=main&inc=feature_simplerate&op=simplerate_edit&rateid=' . $rateid)); exit(); break; case "simplerate_add": $content = _dialog() . " <h2>" . _('Manage SMS rate') . "</h2> <h3>" . _('Add rate') . "</h3> <form action='index.php?app=main&inc=feature_simplerate&op=simplerate_add_yes' method='post'> " . _CSRF_FORM_ . " <table class=playsms-table> <tr> <td class=label-sizer>" . _('Destination') . "</td><td><input type='text' maxlength='30' name='add_dst' value=\"$add_dst\"></td> </tr> <tr> <td>" . _('Prefix') . "</td><td><input type='text' maxlength=10 name='add_prefix' value=\"$add_prefix\"></td> </tr> <tr> <td>" . _('Rate') . "</td><td><input type='text' maxlength=14 name='add_rate' value=\"$add_rate\"></td> </tr> </table> <input type='submit' class='button' value='" . _('Save') . "'> </form> " . _back('index.php?app=main&inc=feature_simplerate&op=simplerate_list'); _p($content); break; case "simplerate_add_yes": $add_dst = $_POST['add_dst']; $add_prefix = $_POST['add_prefix']; $add_prefix = preg_replace('/[^0-9.]*/', '', $add_prefix); $add_rate = $_POST['add_rate']; if ($add_dst && ($add_prefix >= 0) && ($add_rate >= 0)) { $db_query = "SELECT * FROM " . _DB_PREF_ . "_featureSimplerate WHERE prefix='$add_prefix'"; $db_result = dba_query($db_query); if ($db_row = dba_fetch_array($db_result)) { $_SESSION['dialog']['info'][] = _('Rate already exists') . " (" . _('destination') . ": " . $db_row['dst'] . ", " . _('prefix') . ": " . $db_row['prefix'] . ")"; } else { $db_query = " INSERT INTO " . _DB_PREF_ . "_featureSimplerate (dst,prefix,rate) VALUES ('$add_dst','$add_prefix','$add_rate')"; if ($new_uid = @dba_insert_id($db_query)) { $_SESSION['dialog']['info'][] = _('Rate has been added') . " (" . _('destination') . ": $add_dst, " . _('prefix') . ": $add_prefix)"; } } } else { $_SESSION['dialog']['info'][] = _('You must fill all fields'); } header("Location: " . _u('index.php?app=main&inc=feature_simplerate&op=simplerate_add')); exit(); break; }
gpl-3.0
c-pari22/dressme
dressme/dressme/wsgi.py
392
""" WSGI config for dressme project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dressme.settings") application = get_wsgi_application()
gpl-3.0
manuelp/todo-events
src/main/java/com/github/manuelp/todoEvents/listView/UpdateTodo.java
1317
package com.github.manuelp.todoEvents.listView; import com.github.manuelp.todoEvents.events.TodoUpdated; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.skife.jdbi.v2.DBI; import rx.Observer; import java.sql.Timestamp; import java.time.LocalDateTime; public class UpdateTodo implements Observer<TodoUpdated> { private static final Logger logger = LogManager.getLogger(UpdateTodo.class); private DBI dbi; public UpdateTodo(DBI dbi) { this.dbi = dbi; } @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(TodoUpdated todoUpdated) { logger.debug("Processing: " + todoUpdated.toString()); dbi.withHandle(h -> { h.createStatement("UPDATE list_view SET title=:title,notes=:notes,updated=:updated WHERE id=:id").bind("id", todoUpdated .getId()) .bind("title", todoUpdated.getTitle()).bind("notes", todoUpdated.getNotes()).bind("updated", Timestamp.valueOf( LocalDateTime.now())).execute(); return null; }); } }
mpl-2.0
paragonie/halite
test/unit/FileTest.php
31508
<?php declare(strict_types=1); use ParagonIE\Halite\File; use ParagonIE\Halite\KeyFactory; use ParagonIE\Halite\Stream\{ MutableFile, ReadOnlyFile, WeakReadOnlyFile }; use ParagonIE\Halite\Symmetric\EncryptionKey; use ParagonIE\Halite\Util; use ParagonIE\Halite\Alerts as CryptoException; use ParagonIE\HiddenString\HiddenString; use PHPUnit\Framework\TestCase; final class FileTest extends TestCase { public function setUp(): void { chmod(__DIR__.'/tmp/', 0777); if (!\extension_loaded('sodium')) { $this->markTestSkipped('Libsodium not installed'); } } /** * @throws CryptoException\InvalidKey * @throws SodiumException */ public function testAsymmetricEncrypt() { touch(__DIR__.'/tmp/paragon_avatar.a-encrypted.png'); chmod(__DIR__.'/tmp/paragon_avatar.a-encrypted.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.a-encrypted-aad.png'); chmod(__DIR__.'/tmp/paragon_avatar.a-encrypted-aad.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.a-decrypted.png'); chmod(__DIR__.'/tmp/paragon_avatar.a-decrypted.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.a-decrypted-aad.png'); chmod(__DIR__.'/tmp/paragon_avatar.a-decrypted-aad.png', 0777); $alice = KeyFactory::generateEncryptionKeyPair(); $aliceSecret = $alice->getSecretKey(); $alicePublic = $alice->getPublicKey(); $bob = KeyFactory::generateEncryptionKeyPair(); $bobSecret = $bob->getSecretKey(); $bobPublic = $bob->getPublicKey(); File::asymmetricEncrypt( __DIR__.'/tmp/paragon_avatar.png', __DIR__.'/tmp/paragon_avatar.a-encrypted.png', $bobPublic, $aliceSecret ); File::asymmetricDecrypt( __DIR__.'/tmp/paragon_avatar.a-encrypted.png', __DIR__.'/tmp/paragon_avatar.a-decrypted.png', $bobSecret, $alicePublic ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.a-decrypted.png') ); // Now with AAD: $aad = 'Halite v5 test'; File::asymmetricEncrypt( __DIR__.'/tmp/paragon_avatar.png', __DIR__.'/tmp/paragon_avatar.a-encrypted-aad.png', $bobPublic, $aliceSecret, $aad ); try { File::asymmetricDecrypt( __DIR__.'/tmp/paragon_avatar.a-encrypted-aad.png', __DIR__.'/tmp/paragon_avatar.a-decrypted-aad.png', $bobSecret, $alicePublic ); } catch (CryptoException\HaliteAlert $ex) { $this->assertSame( 'Invalid message authentication code', $ex->getMessage() ); } File::asymmetricDecrypt( __DIR__.'/tmp/paragon_avatar.a-encrypted-aad.png', __DIR__.'/tmp/paragon_avatar.a-decrypted-aad.png', $bobSecret, $alicePublic, $aad ); unlink(__DIR__.'/tmp/paragon_avatar.a-encrypted.png'); unlink(__DIR__.'/tmp/paragon_avatar.a-decrypted.png'); unlink(__DIR__.'/tmp/paragon_avatar.a-encrypted-aad.png'); unlink(__DIR__.'/tmp/paragon_avatar.a-decrypted-aad.png'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws TypeError */ public function testEncrypt() { touch(__DIR__.'/tmp/paragon_avatar.encrypted.png'); chmod(__DIR__.'/tmp/paragon_avatar.encrypted.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.decrypted.png'); chmod(__DIR__.'/tmp/paragon_avatar.decrypted.png', 0777); $key = new EncryptionKey( new HiddenString(\str_repeat('B', 32)) ); File::encrypt( __DIR__.'/tmp/paragon_avatar.png', __DIR__.'/tmp/paragon_avatar.encrypted.png', $key ); File::decrypt( __DIR__.'/tmp/paragon_avatar.encrypted.png', __DIR__.'/tmp/paragon_avatar.decrypted.png', $key ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.decrypted.png') ); unlink(__DIR__.'/tmp/paragon_avatar.encrypted.png'); unlink(__DIR__.'/tmp/paragon_avatar.decrypted.png'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws TypeError */ public function testEncryptWithAAD() { touch(__DIR__.'/tmp/paragon_avatar.encrypted-aad.png'); chmod(__DIR__.'/tmp/paragon_avatar.encrypted-aad.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.decrypted-aad.png'); chmod(__DIR__.'/tmp/paragon_avatar.decrypted-aad.png', 0777); $key = new EncryptionKey( new HiddenString(\str_repeat('B', 32)) ); $aad = "Additional associated data"; File::encrypt( __DIR__.'/tmp/paragon_avatar.png', __DIR__.'/tmp/paragon_avatar.encrypted-aad.png', $key, $aad ); try { File::decrypt( __DIR__.'/tmp/paragon_avatar.encrypted-aad.png', __DIR__.'/tmp/paragon_avatar.decrypted-aad.png', $key ); } catch (CryptoException\HaliteAlert $ex) { $this->assertSame( 'Invalid message authentication code', $ex->getMessage() ); } File::decrypt( __DIR__.'/tmp/paragon_avatar.encrypted-aad.png', __DIR__.'/tmp/paragon_avatar.decrypted-aad.png', $key, $aad ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.decrypted-aad.png') ); unlink(__DIR__.'/tmp/paragon_avatar.encrypted-aad.png'); unlink(__DIR__.'/tmp/paragon_avatar.decrypted-aad.png'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws TypeError */ public function testEncryptEmpty() { file_put_contents(__DIR__.'/tmp/empty.txt', ''); chmod(__DIR__.'/tmp/empty.txt', 0777); touch(__DIR__.'/tmp/empty.encrypted.txt'); chmod(__DIR__.'/tmp/empty.encrypted.txt', 0777); touch(__DIR__.'/tmp/empty.decrypted.txt'); chmod(__DIR__.'/tmp/empty.decrypted.txt', 0777); $key = new EncryptionKey( new HiddenString(\str_repeat('B', 32)) ); File::encrypt( __DIR__.'/tmp/empty.txt', __DIR__.'/tmp/empty.encrypted.txt', $key ); File::decrypt( __DIR__.'/tmp/empty.encrypted.txt', __DIR__.'/tmp/empty.decrypted.txt', $key ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/empty.txt'), hash_file('sha256', __DIR__.'/tmp/empty.decrypted.txt') ); unlink(__DIR__.'/tmp/empty.txt'); unlink(__DIR__.'/tmp/empty.encrypted.txt'); unlink(__DIR__.'/tmp/empty.decrypted.txt'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws Exception * @throws TypeError */ public function testEncryptFail() { touch(__DIR__.'/tmp/paragon_avatar.encrypt_fail.png'); chmod(__DIR__.'/tmp/paragon_avatar.encrypt_fail.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.decrypt_fail.png'); chmod(__DIR__.'/tmp/paragon_avatar.decrypt_fail.png', 0777); $key = new EncryptionKey( new HiddenString(\str_repeat('B', 32)) ); File::encrypt( __DIR__.'/tmp/paragon_avatar.png', __DIR__.'/tmp/paragon_avatar.encrypt_fail.png', $key ); $fp = fopen(__DIR__.'/tmp/paragon_avatar.encrypt_fail.png', 'ab'); fwrite($fp, random_bytes(1)); fclose($fp); try { File::decrypt( __DIR__.'/tmp/paragon_avatar.encrypt_fail.png', __DIR__.'/tmp/paragon_avatar.decrypt_fail.png', $key ); $this->fail( 'This should have thrown an InvalidMessage exception!' ); } catch (CryptoException\InvalidMessage $e) { $this->assertTrue($e instanceof CryptoException\InvalidMessage); unlink(__DIR__.'/tmp/paragon_avatar.encrypt_fail.png'); unlink(__DIR__.'/tmp/paragon_avatar.decrypt_fail.png'); } } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidType * @throws TypeError */ public function testEncryptSmallFail() { touch(__DIR__.'/tmp/empty.encrypted.txt'); chmod(__DIR__.'/tmp/empty.encrypted.txt', 0777); touch(__DIR__.'/tmp/empty.decrypted.txt'); chmod(__DIR__.'/tmp/empty.decrypted.txt', 0777); $msg = 'Input file is too small to have been encrypted by Halite.'; $key = new EncryptionKey( new HiddenString(str_repeat('B', 32)) ); file_put_contents( __DIR__.'/tmp/empty.encrypted.txt', '' ); try { File::decrypt( __DIR__ . '/tmp/empty.encrypted.txt', __DIR__ . '/tmp/empty.decrypted.txt', $key ); $this->fail("This should scream bloody murder"); } catch (CryptoException\InvalidMessage $e) { $this->assertSame($msg, $e->getMessage()); } file_put_contents( __DIR__.'/tmp/empty.encrypted.txt', "\x31\x41\x04\x00\x01" ); try { File::decrypt( __DIR__ . '/tmp/empty.encrypted.txt', __DIR__ . '/tmp/empty.decrypted.txt', $key ); $this->fail("This should scream bloody murder"); } catch (CryptoException\InvalidMessage $e) { $this->assertSame($msg, $e->getMessage()); } file_put_contents( __DIR__.'/tmp/empty.encrypted.txt', "\x31\x41\x04\x00" . \str_repeat("\x00", 87) ); try { File::decrypt( __DIR__ . '/tmp/empty.encrypted.txt', __DIR__ . '/tmp/empty.decrypted.txt', $key ); $this->fail("This should scream bloody murder"); } catch (CryptoException\InvalidMessage $e) { $this->assertSame($msg, $e->getMessage()); } unlink(__DIR__.'/tmp/empty.encrypted.txt'); unlink(__DIR__.'/tmp/empty.decrypted.txt'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws TypeError */ public function testEncryptVarious() { touch(__DIR__.'/tmp/paragon_avatar.encrypted.png'); chmod(__DIR__.'/tmp/paragon_avatar.encrypted.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.decrypted.png'); chmod(__DIR__.'/tmp/paragon_avatar.decrypted.png', 0777); $key = new EncryptionKey( new HiddenString(\str_repeat('B', 32)) ); File::encrypt( new ReadOnlyFile(__DIR__.'/tmp/paragon_avatar.png'), new MutableFile(__DIR__.'/tmp/paragon_avatar.encrypted.png'), $key ); File::decrypt( new ReadOnlyFile(__DIR__.'/tmp/paragon_avatar.encrypted.png'), new MutableFile(__DIR__.'/tmp/paragon_avatar.decrypted.png'), $key ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.decrypted.png') ); File::encrypt( new WeakReadOnlyFile(__DIR__.'/tmp/paragon_avatar.png'), new MutableFile(__DIR__.'/tmp/paragon_avatar.encrypted.png'), $key ); File::decrypt( new WeakReadOnlyFile(__DIR__.'/tmp/paragon_avatar.encrypted.png'), new MutableFile(__DIR__.'/tmp/paragon_avatar.decrypted.png'), $key ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.decrypted.png') ); unlink(__DIR__.'/tmp/paragon_avatar.encrypted.png'); unlink(__DIR__.'/tmp/paragon_avatar.decrypted.png'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws Exception * @throws TypeError */ public function testSeal() { touch(__DIR__.'/tmp/paragon_avatar.sealed.png'); chmod(__DIR__.'/tmp/paragon_avatar.sealed.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.opened.png'); chmod(__DIR__.'/tmp/paragon_avatar.opened.png', 0777); $keypair = KeyFactory::generateEncryptionKeyPair(); $secretkey = $keypair->getSecretKey(); $publickey = $keypair->getPublicKey(); File::seal( __DIR__.'/tmp/paragon_avatar.png', __DIR__.'/tmp/paragon_avatar.sealed.png', $publickey ); File::unseal( __DIR__.'/tmp/paragon_avatar.sealed.png', __DIR__.'/tmp/paragon_avatar.opened.png', $secretkey ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.opened.png') ); // New: Additional Associated Data tests $aad = "Additional associated data"; File::seal( __DIR__.'/tmp/paragon_avatar.png', __DIR__.'/tmp/paragon_avatar.sealed-aad.png', $publickey, $aad ); try { File::unseal( __DIR__.'/tmp/paragon_avatar.sealed-aad.png', __DIR__.'/tmp/paragon_avatar.opened-aad.png', $secretkey ); } catch (CryptoException\HaliteAlert $ex) { $this->assertSame( 'Invalid message authentication code', $ex->getMessage() ); } File::unseal( __DIR__.'/tmp/paragon_avatar.sealed-aad.png', __DIR__.'/tmp/paragon_avatar.opened-aad.png', $secretkey, $aad ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.opened-aad.png') ); unlink(__DIR__.'/tmp/paragon_avatar.sealed.png'); unlink(__DIR__.'/tmp/paragon_avatar.opened.png'); unlink(__DIR__.'/tmp/paragon_avatar.sealed-aad.png'); unlink(__DIR__.'/tmp/paragon_avatar.opened-aad.png'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws Exception * @throws TypeError */ public function testSealFromStreamWrapper() { require_once __DIR__ . '/RemoteStream.php'; stream_register_wrapper('haliteTest', RemoteStream::class); touch(__DIR__.'/tmp/paragon_avatar.sealed.png'); chmod(__DIR__.'/tmp/paragon_avatar.sealed.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.opened.png'); chmod(__DIR__.'/tmp/paragon_avatar.opened.png', 0777); $keypair = KeyFactory::generateEncryptionKeyPair(); $secretkey = $keypair->getSecretKey(); $publickey = $keypair->getPublicKey(); $file = new ReadOnlyFile(fopen('haliteTest://paragon_avatar.png', 'rb')); File::seal( $file, __DIR__.'/tmp/paragon_avatar.sealed.png', $publickey ); File::unseal( __DIR__.'/tmp/paragon_avatar.sealed.png', __DIR__.'/tmp/paragon_avatar.opened.png', $secretkey ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.opened.png') ); unlink(__DIR__.'/tmp/paragon_avatar.sealed.png'); unlink(__DIR__.'/tmp/paragon_avatar.opened.png'); $this->assertEquals($file->getHash(), (new ReadOnlyFile(__DIR__.'/tmp/paragon_avatar.png'))->getHash()); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws Exception * @throws TypeError */ public function testSealEmpty() { file_put_contents(__DIR__.'/tmp/empty.txt', ''); chmod(__DIR__.'/tmp/empty.txt', 0777); touch(__DIR__.'/tmp/empty.sealed.txt'); chmod(__DIR__.'/tmp/empty.sealed.txt', 0777); touch(__DIR__.'/tmp/empty.unsealed.txt'); chmod(__DIR__.'/tmp/empty.unsealed.txt', 0777); $keypair = KeyFactory::generateEncryptionKeyPair(); $secretkey = $keypair->getSecretKey(); $publickey = $keypair->getPublicKey(); File::seal( __DIR__.'/tmp/empty.txt', __DIR__.'/tmp/empty.sealed.txt', $publickey ); File::unseal( __DIR__.'/tmp/empty.sealed.txt', __DIR__.'/tmp/empty.unsealed.txt', $secretkey ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/empty.txt'), hash_file('sha256', __DIR__.'/tmp/empty.unsealed.txt') ); unlink(__DIR__.'/tmp/empty.txt'); unlink(__DIR__.'/tmp/empty.sealed.txt'); unlink(__DIR__.'/tmp/empty.unsealed.txt'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws Exception * @throws TypeError */ public function testSealFail() { touch(__DIR__.'/tmp/paragon_avatar.seal_fail.png'); chmod(__DIR__.'/tmp/paragon_avatar.seal_fail.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.open_fail.png'); chmod(__DIR__.'/tmp/paragon_avatar.open_fail.png', 0777); $keypair = KeyFactory::generateEncryptionKeyPair(); $secretkey = $keypair->getSecretKey(); $publickey = $keypair->getPublicKey(); File::seal( __DIR__.'/tmp/paragon_avatar.png', __DIR__.'/tmp/paragon_avatar.seal_fail.png', $publickey ); $fp = fopen(__DIR__.'/tmp/paragon_avatar.seal_fail.png', 'ab'); fwrite($fp, random_bytes(1)); fclose($fp); try { File::unseal( __DIR__.'/tmp/paragon_avatar.seal_fail.png', __DIR__.'/tmp/paragon_avatar.open_fail.png', $secretkey ); $this->fail( 'This should have thrown an InvalidMessage exception!' ); } catch (CryptoException\InvalidMessage $e) { $this->assertTrue($e instanceof CryptoException\InvalidMessage); unlink(__DIR__.'/tmp/paragon_avatar.seal_fail.png'); unlink(__DIR__.'/tmp/paragon_avatar.open_fail.png'); } } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidType * @throws TypeError */ public function testSealSmallFail() { touch(__DIR__.'/tmp/empty.sealed.txt'); chmod(__DIR__.'/tmp/empty.sealed.txt', 0777); touch(__DIR__.'/tmp/empty.unsealed.txt'); chmod(__DIR__.'/tmp/empty.unsealed.txt', 0777); $msg = 'Input file is too small to have been encrypted by Halite.'; $keypair = KeyFactory::generateEncryptionKeyPair(); $secretkey = $keypair->getSecretKey(); file_put_contents(__DIR__.'/tmp/empty.sealed.txt', ''); try { File::unseal( __DIR__.'/tmp/empty.sealed.txt', __DIR__.'/tmp/empty.unsealed.txt', $secretkey ); $this->fail("This should scream bloody murder"); } catch (CryptoException\InvalidMessage $e) { $this->assertSame($msg, $e->getMessage()); } file_put_contents( __DIR__.'/tmp/empty.sealed.txt', "\x31\x41\x04\x00" . \str_repeat("\x00", 95) ); try { File::unseal( __DIR__.'/tmp/empty.sealed.txt', __DIR__.'/tmp/empty.unsealed.txt', $secretkey ); $this->fail("This should scream bloody murder"); } catch (CryptoException\InvalidMessage $e) { $this->assertSame($msg, $e->getMessage()); } unlink(__DIR__.'/tmp/empty.sealed.txt'); unlink(__DIR__.'/tmp/empty.unsealed.txt'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\FileModified * @throws CryptoException\InvalidDigestLength * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws Exception * @throws TypeError */ public function testSealVarious() { touch(__DIR__.'/tmp/paragon_avatar.sealed.png'); chmod(__DIR__.'/tmp/paragon_avatar.sealed.png', 0777); touch(__DIR__.'/tmp/paragon_avatar.opened.png'); chmod(__DIR__.'/tmp/paragon_avatar.opened.png', 0777); $keypair = KeyFactory::generateEncryptionKeyPair(); $secretkey = $keypair->getSecretKey(); $publickey = $keypair->getPublicKey(); File::seal( new ReadOnlyFile(__DIR__.'/tmp/paragon_avatar.png'), new MutableFile(__DIR__.'/tmp/paragon_avatar.sealed.png'), $publickey ); File::unseal( new ReadOnlyFile(__DIR__.'/tmp/paragon_avatar.sealed.png'), new MutableFile(__DIR__.'/tmp/paragon_avatar.opened.png'), $secretkey ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.opened.png') ); File::seal( new WeakReadOnlyFile(__DIR__.'/tmp/paragon_avatar.png'), new MutableFile(__DIR__.'/tmp/paragon_avatar.sealed.png'), $publickey ); File::unseal( new WeakReadOnlyFile(__DIR__.'/tmp/paragon_avatar.sealed.png'), new MutableFile(__DIR__.'/tmp/paragon_avatar.opened.png'), $secretkey ); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash_file('sha256', __DIR__.'/tmp/paragon_avatar.opened.png') ); unlink(__DIR__.'/tmp/paragon_avatar.sealed.png'); unlink(__DIR__.'/tmp/paragon_avatar.opened.png'); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidSignature * @throws CryptoException\InvalidType * @throws TypeError */ public function testSign() { $keypair = KeyFactory::generateSignatureKeyPair(); $secretkey = $keypair->getSecretKey(); $publickey = $keypair->getPublicKey(); $signature = File::sign( __DIR__.'/tmp/paragon_avatar.png', $secretkey ); $this->assertTrue( File::verify( __DIR__.'/tmp/paragon_avatar.png', $publickey, $signature ) ); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidSignature * @throws CryptoException\InvalidType * @throws TypeError */ public function testSignVarious() { $keypair = KeyFactory::generateSignatureKeyPair(); $secretkey = $keypair->getSecretKey(); $publickey = $keypair->getPublicKey(); $inputFile = new ReadOnlyFile(__DIR__.'/tmp/paragon_avatar.png'); $signature = File::sign( $inputFile, $secretkey ); $this->assertTrue( File::verify( $inputFile, $publickey, $signature ) ); $mutable = new WeakReadOnlyFile(__DIR__.'/tmp/paragon_avatar.png'); $signature = File::sign( $mutable, $secretkey ); $this->assertTrue( File::verify( $mutable, $publickey, $signature ) ); } /** * @throws CryptoException\CannotPerformOperation * @throws CryptoException\FileAccessDenied * @throws CryptoException\FileError * @throws CryptoException\InvalidKey * @throws CryptoException\InvalidMessage * @throws CryptoException\InvalidType * @throws Exception * @throws TypeError */ public function testChecksum() { $csum = File::checksum(__DIR__.'/tmp/paragon_avatar.png', null, false); $this->assertSame( $csum, "09f9f74a0e742d057ca08394db4c2e444be88c0c94fe9a914c3d3758c7eccafb". "8dd286e3d6bc37f353e76c0c5aa2036d978ca28ffaccfa59f5dc1f076c5517a0" ); $data = random_bytes(32); file_put_contents(__DIR__.'/tmp/garbage.dat', $data); $hash = Util::raw_hash($data, 64); $file = File::checksum(__DIR__.'/tmp/garbage.dat', null, true); $this->assertSame( $hash, $file ); $this->assertSame( $hash, File::checksum(new ReadOnlyFile(__DIR__.'/tmp/garbage.dat'), null, true) ); $this->assertSame( $hash, File::checksum(new WeakReadOnlyFile(__DIR__.'/tmp/garbage.dat'), null, true) ); // No exceptions: File::checksum(__DIR__.'/tmp/garbage.dat', KeyFactory::generateAuthenticationKey(), true); File::checksum(__DIR__.'/tmp/garbage.dat', KeyFactory::generateSignatureKeyPair()->getPublicKey(), true); try { File::checksum(__DIR__.'/tmp/garbage.dat', KeyFactory::generateEncryptionKey()); $this->fail('Invalid type was accepted.'); } catch (CryptoException\InvalidKey $ex) { } unlink(__DIR__.'/tmp/garbage.dat'); } public function testNonExistingOutputFile() { file_put_contents(__DIR__.'/tmp/empty116.txt', ''); if (\is_file(__DIR__ . '/tmp/empty116.encrypted.txt')) { \unlink(__DIR__ . '/tmp/empty116.encrypted.txt'); \clearstatcache(); } $key = new EncryptionKey( new HiddenString(\str_repeat('B', 32)) ); File::encrypt( __DIR__.'/tmp/empty116.txt', __DIR__.'/tmp/empty116.encrypted.txt', $key ); $this->assertTrue(\file_exists(__DIR__.'/tmp/empty116.encrypted.txt')); } public function testOutputToOutputbuffer() { $stream = fopen('php://output', 'wb'); touch(__DIR__.'/tmp/paragon_avatar.encrypted.png'); chmod(__DIR__.'/tmp/paragon_avatar.encrypted.png', 0777); $key = new EncryptionKey( new HiddenString(\str_repeat('B', 32)) ); File::encrypt( __DIR__.'/tmp/paragon_avatar.png', __DIR__.'/tmp/paragon_avatar.encrypted.png', $key ); ob_start(); File::decrypt( __DIR__.'/tmp/paragon_avatar.encrypted.png', new MutableFile($stream), $key ); $contents = ob_get_clean(); $this->assertSame( hash_file('sha256', __DIR__.'/tmp/paragon_avatar.png'), hash('sha256', $contents) ); unlink(__DIR__.'/tmp/paragon_avatar.encrypted.png'); } }
mpl-2.0
oracle/terraform-provider-baremetal
vendor/github.com/oracle/oci-go-sdk/v46/email/list_suppressions_request_response.go
7730
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. package email import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) // ListSuppressionsRequest wrapper for the ListSuppressions operation // // See also // // Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/email/ListSuppressions.go.html to see an example of how to use ListSuppressionsRequest. type ListSuppressionsRequest struct { // The OCID for the compartment. CompartmentId *string `mandatory:"true" contributesTo:"query" name:"compartmentId"` // The request ID for tracing from the system OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` // The email address of the suppression. EmailAddress *string `mandatory:"false" contributesTo:"query" name:"emailAddress"` // Search for suppressions that were created within a specific date range, // using this parameter to specify the earliest creation date for the // returned list (inclusive). Specifying this parameter without the // corresponding `timeCreatedLessThan` parameter will retrieve suppressions created from the // given `timeCreatedGreaterThanOrEqualTo` to the current time, in "YYYY-MM-ddThh:mmZ" format with a // Z offset, as defined by RFC 3339. // **Example:** 2016-12-19T16:39:57.600Z TimeCreatedGreaterThanOrEqualTo *common.SDKTime `mandatory:"false" contributesTo:"query" name:"timeCreatedGreaterThanOrEqualTo"` // Search for suppressions that were created within a specific date range, // using this parameter to specify the latest creation date for the returned // list (exclusive). Specifying this parameter without the corresponding // `timeCreatedGreaterThanOrEqualTo` parameter will retrieve all suppressions created before the // specified end date, in "YYYY-MM-ddThh:mmZ" format with a Z offset, as // defined by RFC 3339. // **Example:** 2016-12-19T16:39:57.600Z TimeCreatedLessThan *common.SDKTime `mandatory:"false" contributesTo:"query" name:"timeCreatedLessThan"` // For list pagination. The value of the opc-next-page response header from the previous "List" call. // For important details about how pagination works, // see List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine). Page *string `mandatory:"false" contributesTo:"query" name:"page"` // For list pagination. The maximum number of results per page, or items to return in a // paginated "List" call. `1` is the minimum, `1000` is the maximum. For important details about // how pagination works, see List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine). Limit *int `mandatory:"false" contributesTo:"query" name:"limit"` // The field to sort by. The `TIMECREATED` value returns the list in in // descending order by default. The `EMAILADDRESS` value returns the list in // ascending order by default. Use the `SortOrderQueryParam` to change the // direction of the returned list of items. SortBy ListSuppressionsSortByEnum `mandatory:"false" contributesTo:"query" name:"sortBy" omitEmpty:"true"` // The sort order to use, either ascending or descending order. SortOrder ListSuppressionsSortOrderEnum `mandatory:"false" contributesTo:"query" name:"sortOrder" omitEmpty:"true"` // Metadata about the request. This information will not be transmitted to the service, but // represents information that the SDK will consume to drive retry behavior. RequestMetadata common.RequestMetadata } func (request ListSuppressionsRequest) String() string { return common.PointerString(request) } // HTTPRequest implements the OCIRequest interface func (request ListSuppressionsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders) } // BinaryRequestBody implements the OCIRequest interface func (request ListSuppressionsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } // RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy. func (request ListSuppressionsRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy } // ListSuppressionsResponse wrapper for the ListSuppressions operation type ListSuppressionsResponse struct { // The underlying http response RawResponse *http.Response // A list of []SuppressionSummary instances Items []SuppressionSummary `presentIn:"body"` // Unique Oracle-assigned identifier for the request. If you need to contact // Oracle about a particular request, please provide the request ID. OpcRequestId *string `presentIn:"header" name:"opc-request-id"` // For list pagination. When this header appears in the response, additional pages of results remain. // For important details about how pagination works, see List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine). OpcNextPage *string `presentIn:"header" name:"opc-next-page"` // For list pagination. When this header appears in the response, previous pages of results remain. // For important details about how pagination works, see List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine). OpcPrevPage *string `presentIn:"header" name:"opc-prev-page"` } func (response ListSuppressionsResponse) String() string { return common.PointerString(response) } // HTTPResponse implements the OCIResponse interface func (response ListSuppressionsResponse) HTTPResponse() *http.Response { return response.RawResponse } // ListSuppressionsSortByEnum Enum with underlying type: string type ListSuppressionsSortByEnum string // Set of constants representing the allowable values for ListSuppressionsSortByEnum const ( ListSuppressionsSortByTimecreated ListSuppressionsSortByEnum = "TIMECREATED" ListSuppressionsSortByEmailaddress ListSuppressionsSortByEnum = "EMAILADDRESS" ) var mappingListSuppressionsSortBy = map[string]ListSuppressionsSortByEnum{ "TIMECREATED": ListSuppressionsSortByTimecreated, "EMAILADDRESS": ListSuppressionsSortByEmailaddress, } // GetListSuppressionsSortByEnumValues Enumerates the set of values for ListSuppressionsSortByEnum func GetListSuppressionsSortByEnumValues() []ListSuppressionsSortByEnum { values := make([]ListSuppressionsSortByEnum, 0) for _, v := range mappingListSuppressionsSortBy { values = append(values, v) } return values } // ListSuppressionsSortOrderEnum Enum with underlying type: string type ListSuppressionsSortOrderEnum string // Set of constants representing the allowable values for ListSuppressionsSortOrderEnum const ( ListSuppressionsSortOrderAsc ListSuppressionsSortOrderEnum = "ASC" ListSuppressionsSortOrderDesc ListSuppressionsSortOrderEnum = "DESC" ) var mappingListSuppressionsSortOrder = map[string]ListSuppressionsSortOrderEnum{ "ASC": ListSuppressionsSortOrderAsc, "DESC": ListSuppressionsSortOrderDesc, } // GetListSuppressionsSortOrderEnumValues Enumerates the set of values for ListSuppressionsSortOrderEnum func GetListSuppressionsSortOrderEnumValues() []ListSuppressionsSortOrderEnum { values := make([]ListSuppressionsSortOrderEnum, 0) for _, v := range mappingListSuppressionsSortOrder { values = append(values, v) } return values }
mpl-2.0
servinglynk/hmis-lynk-open-source
hmis-service-v2014/src/main/java/com/servinglynk/hmis/warehouse/service/converter/VeteranInfoConverter.java
6348
package com.servinglynk.hmis.warehouse.service.converter; import com.servinglynk.hmis.warehouse.core.model.VeteranInfo; import com.servinglynk.hmis.warehouse.enums.VeteranInfoAfghanistanOefEnum; import com.servinglynk.hmis.warehouse.enums.VeteranInfoDesertStormEnum; import com.servinglynk.hmis.warehouse.enums.VeteranInfoDischargeStatusEnum; import com.servinglynk.hmis.warehouse.enums.VeteranInfoIraqOifEnum; import com.servinglynk.hmis.warehouse.enums.VeteranInfoIraqOndEnum; import com.servinglynk.hmis.warehouse.enums.VeteranInfoKoreanWarEnum; import com.servinglynk.hmis.warehouse.enums.VeteranInfoMilitaryBranchEnum; import com.servinglynk.hmis.warehouse.enums.VeteranInfoOtherTheaterEnum; import com.servinglynk.hmis.warehouse.enums.VeteranInfoVietnamWarEnum; import com.servinglynk.hmis.warehouse.enums.VeteranInfoWorldWar2Enum; public class VeteranInfoConverter extends BaseConverter { public static com.servinglynk.hmis.warehouse.model.v2014.VeteranInfo modelToEntity (VeteranInfo model ,com.servinglynk.hmis.warehouse.model.v2014.VeteranInfo entity) { if(entity==null) entity = new com.servinglynk.hmis.warehouse.model.v2014.VeteranInfo(); /* entity.setAfghanistanOef(VeteranInfoAfghanistanOefEnum.valueOf(model.getAfghanistanOef())); entity.setDesertStorm(VeteranInfoDesertStormEnum.valueOf(model.getDesertStorm())); entity.setIraqOif(VeteranInfoIraqOifEnum.valueOf(model.getIraqOif())); entity.setIraqOnd(VeteranInfoIraqOndEnum.valueOf(model.getIraqOnd())); entity.setKoreanWar(VeteranInfoKoreanWarEnum.valueOf(model.getKoreanWar())); entity.setMilitaryBranch(VeteranInfoMilitaryBranchEnum.valueOf(model.getMilitaryBranch())); entity.setOtherTheater(VeteranInfoOtherTheaterEnum.valueOf(model.getOtherTheater())); entity.setVietnamWar(VeteranInfoVietnamWarEnum.valueOf(model.getVietnamWar())); entity.setWorldWar2(VeteranInfoWorldWar2Enum.valueOf(model.getWorldWar2())); entity.setYearEntrdService(model.getYearEntrdService()); entity.setYearSeperated(model.getYearSeperated());*/ if(model.getYearEntrdService()!=null) entity.setYearEntrdService(model.getYearEntrdService()); if(model.getYearSeperated()!=null) entity.setYearSeperated(model.getYearSeperated()); if(model.getWorldWar2()!=null) entity.setWorldWar2(VeteranInfoWorldWar2Enum.lookupEnum(model.getWorldWar2().toString())); if(model.getKoreanWar()!=null) entity.setKoreanWar(VeteranInfoKoreanWarEnum.lookupEnum(model.getKoreanWar().toString())); if(model.getVietnamWar()!=null) entity.setVietnamWar(VeteranInfoVietnamWarEnum.lookupEnum(model.getVietnamWar().toString())); if(model.getDesertStorm()!=null) entity.setDesertStorm(VeteranInfoDesertStormEnum.lookupEnum(model.getDesertStorm().toString())); if(model.getAfghanistanOef()!=null) entity.setAfghanistanOef(VeteranInfoAfghanistanOefEnum.lookupEnum(model.getAfghanistanOef().toString())); if(model.getIraqOif()!=null) entity.setIraqOif(VeteranInfoIraqOifEnum.lookupEnum(model.getIraqOif().toString())); if(model.getIraqOnd()!=null) entity.setIraqOnd(VeteranInfoIraqOndEnum.lookupEnum(model.getIraqOnd().toString())); if(model.getOtherTheater()!=null) entity.setOtherTheater(VeteranInfoOtherTheaterEnum.lookupEnum(model.getOtherTheater().toString())); if(model.getMilitaryBranch()!=null) entity.setMilitaryBranch(VeteranInfoMilitaryBranchEnum.lookupEnum(model.getMilitaryBranch().toString())); if(model.getDischargeStatus()!=null) entity.setDischargeStatus(VeteranInfoDischargeStatusEnum.lookupEnum(model.getDischargeStatus().toString())); copyBeanProperties(entity, model); return entity; } public static VeteranInfo entityToModel (com.servinglynk.hmis.warehouse.model.v2014.VeteranInfo entity) { /* VeteranInfo veteranInfo= new VeteranInfo(); veteranInfo.setAfghanistanOef(entity.getAfghanistanOef().name()); veteranInfo.setDesertStorm(entity.getDesertStorm().name()); veteranInfo.setIraqOif(entity.getIraqOif().name()); veteranInfo.setIraqOnd(entity.getIraqOnd().name()); veteranInfo.setKoreanWar(entity.getKoreanWar().name()); veteranInfo.setMilitaryBranch(entity.getMilitaryBranch().name()); veteranInfo.setOtherTheater(entity.getOtherTheater().name()); veteranInfo.setVietnamWar(entity.getVietnamWar().name()); veteranInfo.setWorldWar2(entity.getWorldWar2().name()); veteranInfo.setYearEntrdService(entity.getYearEntrdService()); veteranInfo.setYearSeperated(entity.getYearSeperated()); veteranInfo.setVeteranInfoId(entity.getId()); return veteranInfo;*/ VeteranInfo model = new VeteranInfo(); if(entity.getId()!=null) model.setVeteranInfoId(entity.getId()); if(entity.getYearEntrdService()!=null) model.setYearEntrdService(entity.getYearEntrdService()); if(entity.getYearSeperated()!=null) model.setYearSeperated(entity.getYearSeperated()); if(entity.getWorldWar2()!=null) model.setWorldWar2(Integer.parseInt(entity.getWorldWar2().getValue())); if(entity.getKoreanWar()!=null) model.setKoreanWar(Integer.parseInt(entity.getKoreanWar().getValue())); if(entity.getVietnamWar()!=null) model.setVietnamWar(Integer.parseInt(entity.getVietnamWar().getValue())); if(entity.getDesertStorm()!=null) model.setDesertStorm(Integer.parseInt(entity.getDesertStorm().getValue())); if(entity.getAfghanistanOef()!=null) model.setAfghanistanOef(Integer.parseInt(entity.getAfghanistanOef().getValue())); if(entity.getIraqOif()!=null) model.setIraqOif(Integer.parseInt(entity.getIraqOif().getValue())); if(entity.getIraqOnd()!=null) model.setIraqOnd(Integer.parseInt(entity.getIraqOnd().getValue())); if(entity.getOtherTheater()!=null) model.setOtherTheater(Integer.parseInt(entity.getOtherTheater().getValue())); if(entity.getMilitaryBranch()!=null) model.setMilitaryBranch(Integer.parseInt(entity.getMilitaryBranch().getValue())); if(entity.getDischargeStatus()!=null) model.setDischargeStatus(Integer.parseInt(entity.getDischargeStatus().getValue())); return model; } }
mpl-2.0
oracle/terraform-provider-baremetal
vendor/github.com/oracle/oci-go-sdk/v46/goldengate/stop_deployment_details.go
1605
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // GoldenGate API // // Use the Oracle Cloud Infrastructure GoldenGate APIs to perform data replication operations. // package goldengate import ( "encoding/json" "github.com/oracle/oci-go-sdk/v46/common" ) // StopDeploymentDetails The information about the Stop for a Deployment. type StopDeploymentDetails interface { } type stopdeploymentdetails struct { JsonData []byte Type string `json:"type"` } // UnmarshalJSON unmarshals json func (m *stopdeploymentdetails) UnmarshalJSON(data []byte) error { m.JsonData = data type Unmarshalerstopdeploymentdetails stopdeploymentdetails s := struct { Model Unmarshalerstopdeploymentdetails }{} err := json.Unmarshal(data, &s.Model) if err != nil { return err } m.Type = s.Model.Type return err } // UnmarshalPolymorphicJSON unmarshals polymorphic json func (m *stopdeploymentdetails) UnmarshalPolymorphicJSON(data []byte) (interface{}, error) { if data == nil || string(data) == "null" { return nil, nil } var err error switch m.Type { case "DEFAULT": mm := DefaultStopDeploymentDetails{} err = json.Unmarshal(data, &mm) return mm, err default: return *m, nil } } func (m stopdeploymentdetails) String() string { return common.PointerString(m) }
mpl-2.0
nisun/tel
Libraries/Telehire.Core/Infrastructure/Fake/FakeHttpSessionState.cs
1630
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; using System.Web.SessionState; namespace Telehire.Core.Infrastructure.Fake { public class FakeHttpSessionState : HttpSessionStateBase { private readonly SessionStateItemCollection _sessionItems; public FakeHttpSessionState(SessionStateItemCollection sessionItems) { _sessionItems = sessionItems; } public override int Count { get { return _sessionItems.Count; } } public override NameObjectCollectionBase.KeysCollection Keys { get { return _sessionItems.Keys; } } public override object this[string name] { get { return _sessionItems[name]; } set { _sessionItems[name] = value; } } public bool Exists(string key) { return _sessionItems[key] != null; } public override object this[int index] { get { return _sessionItems[index]; } set { _sessionItems[index] = value; } } public override void Add(string name, object value) { _sessionItems[name] = value; } public override IEnumerator GetEnumerator() { return _sessionItems.GetEnumerator(); } public override void Remove(string name) { _sessionItems.Remove(name); } } }
mpl-2.0
Ninir/terraform-provider-aws
aws/resource_aws_dms_endpoint_test.go
19588
package aws import ( "fmt" "testing" "github.com/aws/aws-sdk-go/aws" dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccAwsDmsEndpointBasic(t *testing.T) { resourceName := "aws_dms_endpoint.dms_endpoint" randId := acctest.RandString(8) + "-basic" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: dmsEndpointDestroy, Steps: []resource.TestStep{ { Config: dmsEndpointBasicConfig(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"password"}, }, { Config: dmsEndpointBasicConfigUpdate(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "database_name", "tf-test-dms-db-updated"), resource.TestCheckResourceAttr(resourceName, "extra_connection_attributes", "extra"), resource.TestCheckResourceAttr(resourceName, "password", "tftestupdate"), resource.TestCheckResourceAttr(resourceName, "port", "3303"), resource.TestCheckResourceAttr(resourceName, "ssl_mode", "none"), resource.TestCheckResourceAttr(resourceName, "server_name", "tftestupdate"), resource.TestCheckResourceAttr(resourceName, "username", "tftestupdate"), ), }, }, }) } func TestAccAwsDmsEndpointS3(t *testing.T) { resourceName := "aws_dms_endpoint.dms_endpoint" randId := acctest.RandString(8) + "-s3" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: dmsEndpointDestroy, Steps: []resource.TestStep{ { Config: dmsEndpointS3Config(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "s3_settings.#", "1"), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.external_table_definition", ""), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.csv_row_delimiter", "\\n"), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.csv_delimiter", ","), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.bucket_folder", ""), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.bucket_name", "bucket_name"), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.compression_type", "NONE"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"password"}, }, { Config: dmsEndpointS3ConfigUpdate(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "extra_connection_attributes", "key=value;"), resource.TestCheckResourceAttr(resourceName, "s3_settings.#", "1"), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.external_table_definition", "new-external_table_definition"), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.csv_row_delimiter", "\\r"), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.csv_delimiter", "."), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.bucket_folder", "new-bucket_folder"), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.bucket_name", "new-bucket_name"), resource.TestCheckResourceAttr(resourceName, "s3_settings.0.compression_type", "GZIP"), ), }, }, }) } func TestAccAwsDmsEndpointDynamoDb(t *testing.T) { resourceName := "aws_dms_endpoint.dms_endpoint" randId := acctest.RandString(8) + "-dynamodb" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: dmsEndpointDestroy, Steps: []resource.TestStep{ { Config: dmsEndpointDynamoDbConfig(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"password"}, }, { Config: dmsEndpointDynamoDbConfigUpdate(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), ), }, }, }) } func TestAccAwsDmsEndpointMongoDb(t *testing.T) { resourceName := "aws_dms_endpoint.dms_endpoint" randId := acctest.RandString(8) + "-mongodb" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: dmsEndpointDestroy, Steps: []resource.TestStep{ { Config: dmsEndpointMongoDbConfig(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"password"}, }, { Config: dmsEndpointMongoDbConfigUpdate(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "server_name", "tftest-new-server_name"), resource.TestCheckResourceAttr(resourceName, "port", "27018"), resource.TestCheckResourceAttr(resourceName, "username", "tftest-new-username"), resource.TestCheckResourceAttr(resourceName, "password", "tftest-new-password"), resource.TestCheckResourceAttr(resourceName, "database_name", "tftest-new-database_name"), resource.TestCheckResourceAttr(resourceName, "ssl_mode", "require"), resource.TestCheckResourceAttr(resourceName, "extra_connection_attributes", "key=value;"), resource.TestCheckResourceAttr(resourceName, "mongodb_settings.#", "1"), resource.TestCheckResourceAttr(resourceName, "mongodb_settings.0.auth_mechanism", "scram-sha-1"), resource.TestCheckResourceAttr(resourceName, "mongodb_settings.0.nesting_level", "one"), resource.TestCheckResourceAttr(resourceName, "mongodb_settings.0.extract_doc_id", "true"), resource.TestCheckResourceAttr(resourceName, "mongodb_settings.0.docs_to_investigate", "1001"), ), }, }, }) } func TestAccAwsDmsEndpointDocDB(t *testing.T) { resourceName := "aws_dms_endpoint.dms_endpoint" randId := acctest.RandString(8) + "-docdb" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: dmsEndpointDestroy, Steps: []resource.TestStep{ { Config: dmsEndpointDocDBConfig(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "endpoint_arn"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"password"}, }, { Config: dmsEndpointDocDBConfigUpdate(randId), Check: resource.ComposeTestCheckFunc( checkDmsEndpointExists(resourceName), resource.TestCheckResourceAttr(resourceName, "database_name", "tf-test-dms-db-updated"), resource.TestCheckResourceAttr(resourceName, "extra_connection_attributes", "extra"), resource.TestCheckResourceAttr(resourceName, "password", "tftestupdate"), resource.TestCheckResourceAttr(resourceName, "port", "27019"), resource.TestCheckResourceAttr(resourceName, "ssl_mode", "none"), resource.TestCheckResourceAttr(resourceName, "server_name", "tftestupdate"), resource.TestCheckResourceAttr(resourceName, "username", "tftestupdate"), ), }, }, }) } func dmsEndpointDestroy(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "aws_dms_endpoint" { continue } err := checkDmsEndpointExists(rs.Primary.ID) if err == nil { return fmt.Errorf("Found an endpoint that was not destroyed: %s", rs.Primary.ID) } } return nil } func checkDmsEndpointExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("No ID is set") } conn := testAccProvider.Meta().(*AWSClient).dmsconn resp, err := conn.DescribeEndpoints(&dms.DescribeEndpointsInput{ Filters: []*dms.Filter{ { Name: aws.String("endpoint-id"), Values: []*string{aws.String(rs.Primary.ID)}, }, }, }) if err != nil { return fmt.Errorf("DMS endpoint error: %v", err) } if resp.Endpoints == nil { return fmt.Errorf("DMS endpoint not found") } return nil } } func dmsEndpointBasicConfig(randId string) string { return fmt.Sprintf(` resource "aws_dms_endpoint" "dms_endpoint" { database_name = "tf-test-dms-db" endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "source" engine_name = "aurora" extra_connection_attributes = "" password = "tftest" port = 3306 server_name = "tftest" ssl_mode = "none" tags = { Name = "tf-test-dms-endpoint-%[1]s" Update = "to-update" Remove = "to-remove" } username = "tftest" } `, randId) } func dmsEndpointBasicConfigUpdate(randId string) string { return fmt.Sprintf(` resource "aws_dms_endpoint" "dms_endpoint" { database_name = "tf-test-dms-db-updated" endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "source" engine_name = "aurora" extra_connection_attributes = "extra" password = "tftestupdate" port = 3303 server_name = "tftestupdate" ssl_mode = "none" tags = { Name = "tf-test-dms-endpoint-%[1]s" Update = "updated" Add = "added" } username = "tftestupdate" } `, randId) } func dmsEndpointDynamoDbConfig(randId string) string { return fmt.Sprintf(` resource "aws_dms_endpoint" "dms_endpoint" { endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "target" engine_name = "dynamodb" service_access_role = "${aws_iam_role.iam_role.arn}" ssl_mode = "none" tags = { Name = "tf-test-dynamodb-endpoint-%[1]s" Update = "to-update" Remove = "to-remove" } depends_on = ["aws_iam_role_policy.dms_dynamodb_access"] } resource "aws_iam_role" "iam_role" { name = "tf-test-iam-dynamodb-role-%[1]s" assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "dms.amazonaws.com" }, "Effect": "Allow" } ] } EOF } resource "aws_iam_role_policy" "dms_dynamodb_access" { name = "tf-test-iam-dynamodb-role-policy-%[1]s" role = "${aws_iam_role.iam_role.name}" policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "dynamodb:PutItem", "dynamodb:CreateTable", "dynamodb:DescribeTable", "dynamodb:DeleteTable", "dynamodb:DeleteItem", "dynamodb:ListTables" ], "Resource": "*" } ] } EOF } `, randId) } func dmsEndpointDynamoDbConfigUpdate(randId string) string { return fmt.Sprintf(` resource "aws_dms_endpoint" "dms_endpoint" { endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "target" engine_name = "dynamodb" service_access_role = "${aws_iam_role.iam_role.arn}" ssl_mode = "none" tags = { Name = "tf-test-dynamodb-endpoint-%[1]s" Update = "updated" Add = "added" } } resource "aws_iam_role" "iam_role" { name = "tf-test-iam-dynamodb-role-%[1]s" assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "dms.amazonaws.com" }, "Effect": "Allow" } ] } EOF } resource "aws_iam_role_policy" "dms_dynamodb_access" { name = "tf-test-iam-dynamodb-role-policy-%[1]s" role = "${aws_iam_role.iam_role.name}" policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "dynamodb:PutItem", "dynamodb:CreateTable", "dynamodb:DescribeTable", "dynamodb:DeleteTable", "dynamodb:DeleteItem", "dynamodb:ListTables" ], "Resource": "*" } ] } EOF } `, randId) } func dmsEndpointS3Config(randId string) string { return fmt.Sprintf(` resource "aws_dms_endpoint" "dms_endpoint" { endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "target" engine_name = "s3" ssl_mode = "none" extra_connection_attributes = "" tags = { Name = "tf-test-s3-endpoint-%[1]s" Update = "to-update" Remove = "to-remove" } s3_settings { service_access_role_arn = "${aws_iam_role.iam_role.arn}" bucket_name = "bucket_name" } depends_on = ["aws_iam_role_policy.dms_s3_access"] } resource "aws_iam_role" "iam_role" { name = "tf-test-iam-s3-role-%[1]s" assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "dms.amazonaws.com" }, "Effect": "Allow" } ] } EOF } resource "aws_iam_role_policy" "dms_s3_access" { name = "tf-test-iam-s3-role-policy-%[1]s" role = "${aws_iam_role.iam_role.name}" policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:CreateBucket", "s3:ListBucket", "s3:DeleteBucket", "s3:GetBucketLocation", "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:GetObjectVersion", "s3:GetBucketPolicy", "s3:PutBucketPolicy", "s3:DeleteBucketPolicy" ], "Resource": "*" } ] } EOF } `, randId) } func dmsEndpointS3ConfigUpdate(randId string) string { return fmt.Sprintf(` resource "aws_dms_endpoint" "dms_endpoint" { endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "target" engine_name = "s3" ssl_mode = "none" extra_connection_attributes = "key=value;" tags = { Name = "tf-test-s3-endpoint-%[1]s" Update = "updated" Add = "added" } s3_settings { service_access_role_arn = "${aws_iam_role.iam_role.arn}" external_table_definition = "new-external_table_definition" csv_row_delimiter = "\\r" csv_delimiter = "." bucket_folder = "new-bucket_folder" bucket_name = "new-bucket_name" compression_type = "GZIP" } } resource "aws_iam_role" "iam_role" { name = "tf-test-iam-s3-role-%[1]s" assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "dms.amazonaws.com" }, "Effect": "Allow" } ] } EOF } resource "aws_iam_role_policy" "dms_s3_access" { name = "tf-test-iam-s3-role-policy-%[1]s" role = "${aws_iam_role.iam_role.name}" policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:CreateBucket", "s3:ListBucket", "s3:DeleteBucket", "s3:GetBucketLocation", "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:GetObjectVersion", "s3:GetBucketPolicy", "s3:PutBucketPolicy", "s3:DeleteBucketPolicy" ], "Resource": "*" } ] } EOF } `, randId) } func dmsEndpointMongoDbConfig(randId string) string { return fmt.Sprintf(` data "aws_kms_alias" "dms" { name = "alias/aws/dms" } resource "aws_dms_endpoint" "dms_endpoint" { endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "source" engine_name = "mongodb" server_name = "tftest" port = 27017 username = "tftest" password = "tftest" database_name = "tftest" ssl_mode = "none" extra_connection_attributes = "" kms_key_arn = "${data.aws_kms_alias.dms.target_key_arn}" tags = { Name = "tf-test-dms-endpoint-%[1]s" Update = "to-update" Remove = "to-remove" } mongodb_settings { auth_type = "password" auth_mechanism = "default" nesting_level = "none" extract_doc_id = "false" docs_to_investigate = "1000" auth_source = "admin" } } `, randId) } func dmsEndpointMongoDbConfigUpdate(randId string) string { return fmt.Sprintf(` data "aws_kms_alias" "dms" { name = "alias/aws/dms" } resource "aws_dms_endpoint" "dms_endpoint" { endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "source" engine_name = "mongodb" server_name = "tftest-new-server_name" port = 27018 username = "tftest-new-username" password = "tftest-new-password" database_name = "tftest-new-database_name" ssl_mode = "require" extra_connection_attributes = "key=value;" kms_key_arn = "${data.aws_kms_alias.dms.target_key_arn}" tags = { Name = "tf-test-dms-endpoint-%[1]s" Update = "updated" Add = "added" } mongodb_settings { auth_mechanism = "scram-sha-1" nesting_level = "one" extract_doc_id = "true" docs_to_investigate = "1001" } } `, randId) } func dmsEndpointDocDBConfig(randId string) string { return fmt.Sprintf(` resource "aws_dms_endpoint" "dms_endpoint" { database_name = "tf-test-dms-db" endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "target" engine_name = "docdb" extra_connection_attributes = "" password = "tftest" port = 27017 server_name = "tftest" ssl_mode = "none" tags = { Name = "tf-test-dms-endpoint-%[1]s" Update = "to-update" Remove = "to-remove" } username = "tftest" } `, randId) } func dmsEndpointDocDBConfigUpdate(randId string) string { return fmt.Sprintf(` resource "aws_dms_endpoint" "dms_endpoint" { database_name = "tf-test-dms-db-updated" endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "target" engine_name = "docdb" extra_connection_attributes = "extra" password = "tftestupdate" port = 27019 server_name = "tftestupdate" ssl_mode = "none" tags = { Name = "tf-test-dms-endpoint-%[1]s" Update = "updated" Add = "added" } username = "tftestupdate" } `, randId) }
mpl-2.0
CoderLine/alphaTab
src/rendering/BarRendererBase.ts
18514
import { Bar } from '@src/model/Bar'; import { Beat } from '@src/model/Beat'; import { Note } from '@src/model/Note'; import { SimileMark } from '@src/model/SimileMark'; import { Voice } from '@src/model/Voice'; import { ICanvas } from '@src/platform/ICanvas'; import { BeatXPosition } from '@src/rendering/BeatXPosition'; import { BeatContainerGlyph } from '@src/rendering/glyphs/BeatContainerGlyph'; import { BeatGlyphBase } from '@src/rendering/glyphs/BeatGlyphBase'; import { Glyph } from '@src/rendering/glyphs/Glyph'; import { LeftToRightLayoutingGlyphGroup } from '@src/rendering/glyphs/LeftToRightLayoutingGlyphGroup'; import { MusicFontSymbol } from '@src/model/MusicFontSymbol'; import { VoiceContainerGlyph } from '@src/rendering/glyphs/VoiceContainerGlyph'; import { ScoreRenderer } from '@src/rendering/ScoreRenderer'; import { BarLayoutingInfo } from '@src/rendering/staves/BarLayoutingInfo'; import { RenderStaff } from '@src/rendering/staves/RenderStaff'; import { BarBounds } from '@src/rendering/utils/BarBounds'; import { BarHelpers } from '@src/rendering/utils/BarHelpers'; import { Bounds } from '@src/rendering/utils/Bounds'; import { MasterBarBounds } from '@src/rendering/utils/MasterBarBounds'; import { RenderingResources } from '@src/RenderingResources'; import { Settings } from '@src/Settings'; import { BeatOnNoteGlyphBase } from '@src/rendering/glyphs/BeatOnNoteGlyphBase'; import { BeamingHelper } from '@src/rendering/utils/BeamingHelper'; /** * Lists the different position modes for {@link BarRendererBase.getNoteY} */ export enum NoteYPosition { /** * Gets the note y-position on top of the note stem or tab number. */ TopWithStem, /** * Gets the note y-position on top of the note head or tab number. */ Top, /** * Gets the note y-position on the center of the note head or tab number. */ Center, /** * Gets the note y-position on the bottom of the note head or tab number. */ Bottom, /** * Gets the note y-position on the bottom of the note stem or tab number. */ BottomWithStem } /** * Lists the different position modes for {@link BarRendererBase.getNoteX} */ export enum NoteXPosition { /** * Gets the note x-position on left of the note head or tab number. */ Left, /** * Gets the note x-position on the center of the note head or tab number. */ Center, /** * Gets the note x-position on the right of the note head or tab number. */ Right } /** * This is the base public class for creating blocks which can render bars. */ export class BarRendererBase { public static readonly LineSpacing: number = 8; public static readonly StemWidth: number = 0.12 /*bravura stemThickness */ * BarRendererBase.LineSpacing; public static readonly StaffLineThickness: number = 0.13 /*bravura staffLineThickness */ * BarRendererBase.LineSpacing; public static readonly BeamThickness: number = 0.5 /*bravura beamThickness */ * BarRendererBase.LineSpacing; public static readonly BeamSpacing: number = 0.25 /*bravura beamSpacing */ * BarRendererBase.LineSpacing; private _preBeatGlyphs: LeftToRightLayoutingGlyphGroup = new LeftToRightLayoutingGlyphGroup(); private _voiceContainers: Map<number, VoiceContainerGlyph> = new Map(); private _postBeatGlyphs: LeftToRightLayoutingGlyphGroup = new LeftToRightLayoutingGlyphGroup(); public get nextRenderer(): BarRendererBase | null { if (!this.bar || !this.bar.nextBar) { return null; } return this.scoreRenderer.layout!.getRendererForBar(this.staff.staveId, this.bar.nextBar); } public get previousRenderer(): BarRendererBase | null { if (!this.bar || !this.bar.previousBar) { return null; } return this.scoreRenderer.layout!.getRendererForBar(this.staff.staveId, this.bar.previousBar); } public scoreRenderer: ScoreRenderer; public staff!: RenderStaff; public layoutingInfo!: BarLayoutingInfo; public bar: Bar; public x: number = 0; public y: number = 0; public width: number = 0; public height: number = 0; public index: number = 0; public topOverflow: number = 0; public bottomOverflow: number = 0; public helpers!: BarHelpers; /** * Gets or sets whether this renderer is linked to the next one * by some glyphs like a vibrato effect */ public isLinkedToPrevious: boolean = false; /** * Gets or sets whether this renderer can wrap to the next line * or it needs to stay connected to the previous one. * (e.g. when having double bar repeats we must not separate the 2 bars) */ public canWrap: boolean = true; public constructor(renderer: ScoreRenderer, bar: Bar) { this.scoreRenderer = renderer; this.bar = bar; if (bar) { this.helpers = new BarHelpers(this); } } public get middleYPosition(): number { return 0; } public registerOverflowTop(topOverflow: number): void { if (topOverflow > this.topOverflow) { this.topOverflow = topOverflow; } } public registerOverflowBottom(bottomOverflow: number): void { if (bottomOverflow > this.bottomOverflow) { this.bottomOverflow = bottomOverflow; } } public scaleToWidth(width: number): void { // preBeat and postBeat glyphs do not get resized let containerWidth: number = width - this._preBeatGlyphs.width - this._postBeatGlyphs.width; for (const container of this._voiceContainers.values()) { container.scaleToWidth(containerWidth); } this._postBeatGlyphs.x = this._preBeatGlyphs.x + this._preBeatGlyphs.width + containerWidth; this.width = width; } public get resources(): RenderingResources { return this.settings.display.resources; } public get settings(): Settings { return this.scoreRenderer.settings; } public get scale(): number { return this.settings.display.scale; } private _wasFirstOfLine: boolean = false; public get isFirstOfLine(): boolean { return this.index === 0; } public get isLast(): boolean { return !this.bar || this.bar.index === this.scoreRenderer.layout!.lastBarIndex; } public registerLayoutingInfo(): void { let info: BarLayoutingInfo = this.layoutingInfo; let preSize: number = this._preBeatGlyphs.width; if (info.preBeatSize < preSize) { info.preBeatSize = preSize; } for (const container of this._voiceContainers.values()) { container.registerLayoutingInfo(info); } let postSize: number = this._postBeatGlyphs.width; if (info.postBeatSize < postSize) { info.postBeatSize = postSize; } } private _appliedLayoutingInfo: number = 0; public applyLayoutingInfo(): boolean { if (this._appliedLayoutingInfo >= this.layoutingInfo.version) { return false; } this._appliedLayoutingInfo = this.layoutingInfo.version; // if we need additional space in the preBeat group we simply // add a new spacer this._preBeatGlyphs.width = this.layoutingInfo.preBeatSize; // on beat glyphs we apply the glyph spacing let voiceEnd: number = this._preBeatGlyphs.x + this._preBeatGlyphs.width; for (const c of this._voiceContainers.values()) { c.x = this._preBeatGlyphs.x + this._preBeatGlyphs.width; c.applyLayoutingInfo(this.layoutingInfo); let newEnd: number = c.x + c.width; if (voiceEnd < newEnd) { voiceEnd = newEnd; } } // on the post glyphs we add the spacing before all other glyphs this._postBeatGlyphs.x = Math.floor(voiceEnd); this._postBeatGlyphs.width = this.layoutingInfo.postBeatSize; this.width = Math.ceil(this._postBeatGlyphs.x + this._postBeatGlyphs.width); return true; } public isFinalized: boolean = false; public finalizeRenderer(): void { this.isFinalized = true; } /** * Gets the top padding for the main content of the renderer. * Can be used to specify where i.E. the score lines of the notation start. * @returns */ public topPadding: number = 0; /** * Gets the bottom padding for the main content of the renderer. * Can be used to specify where i.E. the score lines of the notation end. */ public bottomPadding: number = 0; public doLayout(): void { if (!this.bar) { return; } this.helpers.initialize(); this._preBeatGlyphs = new LeftToRightLayoutingGlyphGroup(); this._preBeatGlyphs.renderer = this; this._voiceContainers.clear(); this._postBeatGlyphs = new LeftToRightLayoutingGlyphGroup(); this._postBeatGlyphs.renderer = this; for (let i: number = 0; i < this.bar.voices.length; i++) { let voice: Voice = this.bar.voices[i]; if (this.hasVoiceContainer(voice)) { let c: VoiceContainerGlyph = new VoiceContainerGlyph(0, 0, voice); c.renderer = this; this._voiceContainers.set(this.bar.voices[i].index, c); } } if (this.bar.simileMark === SimileMark.SecondOfDouble) { this.canWrap = false; } this.createPreBeatGlyphs(); this.createBeatGlyphs(); this.createPostBeatGlyphs(); this.updateSizes(); // finish up all helpers for (const v of this.helpers.beamHelpers) { for (const h of v) { h.finish(); } } } protected hasVoiceContainer(voice: Voice): boolean { return !voice.isEmpty || voice.index === 0; } protected updateSizes(): void { this.staff.registerStaffTop(this.topPadding); this.staff.registerStaffBottom(this.height - this.bottomPadding); let voiceContainers: Map<number, VoiceContainerGlyph> = this._voiceContainers; let beatGlyphsStart: number = this.beatGlyphsStart; let postBeatStart: number = beatGlyphsStart; for (const c of voiceContainers.values()) { c.x = beatGlyphsStart; c.doLayout(); let x: number = c.x + c.width; if (postBeatStart < x) { postBeatStart = x; } } this._postBeatGlyphs.x = Math.floor(postBeatStart); this.width = Math.ceil(this._postBeatGlyphs.x + this._postBeatGlyphs.width); this.height += this.layoutingInfo.height * this.scale; } protected addPreBeatGlyph(g: Glyph): void { g.renderer = this; this._preBeatGlyphs.addGlyph(g); } protected addBeatGlyph(g: BeatContainerGlyph): void { g.renderer = this; g.preNotes.renderer = this; g.onNotes.renderer = this; g.onNotes.beamingHelper = this.helpers.beamHelperLookup[g.beat.voice.index].get(g.beat.index)!; this.getVoiceContainer(g.beat.voice)!.addGlyph(g); } protected getVoiceContainer(voice: Voice): VoiceContainerGlyph | undefined { return this._voiceContainers.has(voice.index) ? this._voiceContainers.get(voice.index) : undefined; } public getBeatContainer(beat: Beat): BeatContainerGlyph | undefined { return this.getVoiceContainer(beat.voice)?.beatGlyphs?.[beat.index]; } public getPreNotesGlyphForBeat(beat: Beat): BeatGlyphBase | undefined { return this.getBeatContainer(beat)?.preNotes; } public getOnNotesGlyphForBeat(beat: Beat): BeatOnNoteGlyphBase | undefined { return this.getBeatContainer(beat)?.onNotes; } public paint(cx: number, cy: number, canvas: ICanvas): void { this.paintBackground(cx, cy, canvas); canvas.color = this.resources.mainGlyphColor; this._preBeatGlyphs.paint(cx + this.x, cy + this.y, canvas); for (const c of this._voiceContainers.values()) { canvas.color = c.voice.index === 0 ? this.resources.mainGlyphColor : this.resources.secondaryGlyphColor; c.paint(cx + this.x, cy + this.y, canvas); } canvas.color = this.resources.mainGlyphColor; this._postBeatGlyphs.paint(cx + this.x, cy + this.y, canvas); } protected paintBackground(cx: number, cy: number, canvas: ICanvas): void { this.layoutingInfo.paint( cx + this.x + this._preBeatGlyphs.x + this._preBeatGlyphs.width, cy + this.y + this.height, canvas ); // canvas.color = Color.random(); // canvas.fillRect(cx + this.x + this._preBeatGlyphs.x, cy + this.y, this._preBeatGlyphs.width, this.height); } public buildBoundingsLookup(masterBarBounds: MasterBarBounds, cx: number, cy: number): void { let barBounds: BarBounds = new BarBounds(); barBounds.bar = this.bar; barBounds.visualBounds = new Bounds(); barBounds.visualBounds.x = cx + this.x; barBounds.visualBounds.y = cy + this.y + this.topPadding; barBounds.visualBounds.w = this.width; barBounds.visualBounds.h = this.height - this.topPadding - this.bottomPadding; barBounds.realBounds = new Bounds(); barBounds.realBounds.x = cx + this.x; barBounds.realBounds.y = cy + this.y; barBounds.realBounds.w = this.width; barBounds.realBounds.h = this.height; masterBarBounds.addBar(barBounds); for (const [index, c] of this._voiceContainers) { let isEmptyBar: boolean = this.bar.isEmpty && index === 0; if (!c.voice.isEmpty || isEmptyBar) { for (let i: number = 0, j: number = c.beatGlyphs.length; i < j; i++) { let bc: BeatContainerGlyph = c.beatGlyphs[i]; bc.buildBoundingsLookup(barBounds, cx + this.x + c.x, cy + this.y + c.y, isEmptyBar); } } } } protected addPostBeatGlyph(g: Glyph): void { this._postBeatGlyphs.addGlyph(g); } protected createPreBeatGlyphs(): void { this._wasFirstOfLine = this.isFirstOfLine; } protected createBeatGlyphs(): void { for (let v: number = 0; v < this.bar.voices.length; v++) { let voice: Voice = this.bar.voices[v]; if (this.hasVoiceContainer(voice)) { this.createVoiceGlyphs(this.bar.voices[v]); } } } protected createVoiceGlyphs(v: Voice): void { // filled in subclasses } protected createPostBeatGlyphs(): void { // filled in subclasses } public get beatGlyphsStart(): number { return this._preBeatGlyphs.x + this._preBeatGlyphs.width; } public get postBeatGlyphsStart(): number { return this._postBeatGlyphs.x; } public getBeatX(beat: Beat, requestedPosition: BeatXPosition = BeatXPosition.PreNotes): number { let container = this.getBeatContainer(beat); if (container) { switch (requestedPosition) { case BeatXPosition.PreNotes: return container.voiceContainer.x + container.x; case BeatXPosition.OnNotes: return container.voiceContainer.x + container.x + container.onNotes.x; case BeatXPosition.MiddleNotes: return container.voiceContainer.x + container.x + container.onTimeX; case BeatXPosition.Stem: const offset = container.onNotes.beamingHelper ? container.onNotes.beamingHelper.getBeatLineX(beat) : container.onNotes.x + container.onNotes.width / 2; return container.voiceContainer.x + offset; case BeatXPosition.PostNotes: return container.voiceContainer.x + container.x + container.onNotes.x + container.onNotes.width; case BeatXPosition.EndBeat: return container.voiceContainer.x + container.x + container.width; } } return 0; } public getNoteX(note: Note, requestedPosition: NoteXPosition): number { let container = this.getBeatContainer(note.beat); if (container) { return ( container.voiceContainer.x + container.x + container.onNotes.x + container.onNotes.getNoteX(note, requestedPosition) ); } return 0; } public getNoteY(note: Note, requestedPosition: NoteYPosition): number { let beat = this.getOnNotesGlyphForBeat(note.beat); if (beat) { return beat.getNoteY(note, requestedPosition); } return NaN; } public reLayout(): void { // there are some glyphs which are shown only for renderers at the line start, so we simply recreate them // but we only need to recreate them for the renderers that were the first of the line or are now the first of the line if ((this._wasFirstOfLine && !this.isFirstOfLine) || (!this._wasFirstOfLine && this.isFirstOfLine)) { this._preBeatGlyphs = new LeftToRightLayoutingGlyphGroup(); this._preBeatGlyphs.renderer = this; this.createPreBeatGlyphs(); } this.updateSizes(); this.registerLayoutingInfo(); } protected paintSimileMark(cx: number, cy: number, canvas: ICanvas): void { switch (this.bar.simileMark) { case SimileMark.Simple: canvas.fillMusicFontSymbol( cx + this.x + (this.width - 20 * this.scale) / 2, cy + this.y + this.height / 2, 1, MusicFontSymbol.Repeat1Bar, false ); break; case SimileMark.SecondOfDouble: canvas.fillMusicFontSymbol( cx + this.x - (28 * this.scale) / 2, cy + this.y + this.height / 2, 1, MusicFontSymbol.Repeat2Bars, false ); break; } } public completeBeamingHelper(helper: BeamingHelper) { // nothing by default } }
mpl-2.0
walac/taskcluster-worker
plugins/artifacts/artifacts_test.go
2778
package artifacts import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "github.com/taskcluster/slugid-go/slugid" "github.com/taskcluster/taskcluster-client-go/tcqueue" "github.com/taskcluster/taskcluster-worker/plugins/plugintest" "github.com/taskcluster/taskcluster-worker/runtime/client" ) type artifactTestCase struct { plugintest.Case Artifacts []string } func (a artifactTestCase) Test() { taskID := slugid.Nice() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client.") })) defer ts.Close() s3resp, _ := json.Marshal(tcqueue.S3ArtifactResponse{ PutURL: ts.URL, }) resp := tcqueue.PostArtifactResponse(s3resp) mockedQueue := &client.MockQueue{} for _, path := range a.Artifacts { mockedQueue.On( "CreateArtifact", taskID, "0", path, client.PostS3ArtifactRequest, ).Return(&resp, nil) } a.Case.QueueMock = mockedQueue a.Case.TaskID = taskID a.Case.Test() mockedQueue.AssertExpectations(a.Case.TestStruct) } func TestArtifactsNone(t *testing.T) { artifactTestCase{ Case: plugintest.Case{ Payload: `{ "delay": 0, "function": "true", "argument": "whatever" }`, Plugin: "artifacts", PluginConfig: `{}`, TestStruct: t, PluginSuccess: true, EngineSuccess: true, }, }.Test() } func TestArtifactsEmpty(t *testing.T) { artifactTestCase{ Case: plugintest.Case{ Payload: `{ "delay": 0, "function": "true", "argument": "whatever", "artifacts": [] }`, Plugin: "artifacts", PluginConfig: `{}`, TestStruct: t, PluginSuccess: true, EngineSuccess: true, }, }.Test() } func TestArtifactsFile(t *testing.T) { artifactTestCase{ Artifacts: []string{"public/blah.txt"}, Case: plugintest.Case{ Payload: `{ "delay": 0, "function": "write-files", "argument": "/artifacts/blah.txt", "artifacts": [ { "type": "file", "path": "/artifacts/blah.txt", "name": "public/blah.txt" } ] }`, Plugin: "artifacts", PluginConfig: `{}`, TestStruct: t, PluginSuccess: true, EngineSuccess: true, }, }.Test() } func TestArtifactsDirectory(t *testing.T) { artifactTestCase{ Artifacts: []string{"public/blah.txt", "public/foo.txt", "public/bar.json"}, Case: plugintest.Case{ Payload: `{ "delay": 0, "function": "write-files", "argument": "/artifacts/blah.txt /artifacts/foo.txt /artifacts/bar.json", "artifacts": [ { "type": "directory", "path": "/artifacts", "name": "public" } ] }`, Plugin: "artifacts", PluginConfig: `{}`, TestStruct: t, PluginSuccess: true, EngineSuccess: true, }, }.Test() }
mpl-2.0
JustBru00/RenamePlugin
src/com/gmail/justbru00/epic/rename/utils/v3/MaterialPermManager.java
1591
package com.gmail.justbru00.epic.rename.utils.v3; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.gmail.justbru00.epic.rename.enums.v3.EpicRenameCommands; public class MaterialPermManager { public static final String MATERIAL_PERM = "epicrename.{CMD}.material.{MATERIAL}"; /** * Checks if the player has permission for the material provided. * @param erc The command that is being performed. * @param toCheck The {@link ItemStack} to check the material of. * @param p The player that we are checking permissions for. * @return True if the player has permission. False if the player doesn't have permission. */ public static boolean checkPerms(EpicRenameCommands erc, ItemStack toCheck, Player p) { // New Permission Checks String newPerm = MATERIAL_PERM.replace("{CMD}", EpicRenameCommands.getStringName(erc)).replace("{MATERIAL}", toCheck.getType().toString()); String allNewPerm = MATERIAL_PERM.replace("{CMD}", EpicRenameCommands.getStringName(erc)).replace("{MATERIAL}", "*"); //Debug.send("[MaterialPermManager] NewPerm: " + newPerm + " allNewPerm: " + allNewPerm); if (p.hasPermission(allNewPerm)) { Debug.send("[MaterialPermManager] The player has permission. Perm: " + allNewPerm); return true; } if (p.hasPermission(newPerm)) { Debug.send("[MaterialPermManager] The player has permission. Perm: " + newPerm); return true; } Debug.send("[MaterialPermManager] The player doesn't have any of the correct material permissions."); return false; } }
mpl-2.0
testdouble/axe-matchers
lib/axe/api/options.rb
497
require 'forwardable' require 'axe/api/rules' module Axe module API class Options extend Forwardable def_delegators :@rules, :according_to, :checking, :checking_only, :skipping def_delegator :@custom, :merge!, :with_options def initialize @rules = Rules.new @custom = {} end def to_hash @rules.to_hash.merge(@custom) end def to_json to_hash.to_json end alias :to_s :to_json end end end
mpl-2.0
denigma/drugage
app/js/src/main/scala/org/denigma/drugage/FrontEnd.scala
2107
package org.denigma.drugage import org.denigma.binding.binders.{GeneralBinder, NavigationBinding} import org.denigma.binding.extensions._ import org.denigma.binding.views.BindableView import org.denigma.controls.login.{AjaxSession, LoginView} import org.denigma.drugage.views.{SidebarView, MenuView} import org.querki.jquery._ import org.scalajs.dom import org.scalajs.dom.raw.HTMLElement import org.semantic.SidebarConfig import org.semantic.ui._ import scala.collection.immutable.Map import scala.scalajs.js.annotation.JSExport @JSExport("FrontEnd") object FrontEnd extends BindableView with scalajs.js.JSApp { override def name: String = "main" lazy val elem: HTMLElement = dom.document.body override val params: Map[String, Any] = Map.empty val sidebarParams = SidebarConfig.exclusive(false).dimPage(false).closable(false).useLegacy(false) val session = new AjaxSession() /** * Register views */ override lazy val injector = defaultInjector.register("menu") { case (el, args) => new MenuView(el, args).withBinders(menu=>List(new GeneralBinder(menu), new NavigationBinding(menu))) } .register("sidebar"){ case (el, args) => new SidebarView(el, args).withBinder(new GeneralBinder(_)) } .register("login"){ case (el, args) => new LoginView(el, session, args).withBinder(new GeneralBinder(_)) } this.withBinder(new GeneralBinder(_)) @JSExport def main(): Unit = { this.bindView(this.viewElement) this.login("guest") // TODO: change it when session mechanism will work well } @JSExport def login(username: String): Unit = session.setUsername(username) @JSExport protected def showLeftSidebar() = { $(".left.sidebar").sidebar(sidebarParams).show() } @JSExport def load(content: String, into: String): Unit = { dom.document.getElementById(into).innerHTML = content } @JSExport def moveInto(from: String, into: String): Unit = { for { ins <- sq.byId(from) intoElement <- sq.byId(into) } { this.loadElementInto(intoElement, ins.innerHTML) ins.parentNode.removeChild(ins) } } }
mpl-2.0
Bertware/bukkitgui2
bukkitgui2/MinecraftServers/Servers/JsonApi2Server.cs
1867
// JsonApi2Server.cs in bukkitgui2/bukkitgui2 // Created 2014/09/05 // // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // // ©Bertware, visit http://bertware.net using System; using System.IO; using System.Windows.Forms; using Net.Bertware.Bukkitgui2.AddOn.Starter; using Net.Bertware.Bukkitgui2.Core.FileLocation; using Net.Bertware.Bukkitgui2.MinecraftServers.Tools; using Net.Bertware.Bukkitgui2.Properties; namespace Net.Bertware.Bukkitgui2.MinecraftServers.Servers { internal class JsonApi2Server : MinecraftServerBase { public JsonApi2Server() { Name = "JsonApi API v2"; Logo = Resources.jsonapi_logo; Site = "http://mcjsonapi.com/"; HasCustomAssembly = true; CustomAssembly = ""; // will be set in preparelaunch SupportsPlugins = false; //disable plugin manager on this one HasCustomSettingsControl = true; CustomSettingsControl = new JsonApi2CredentialsSettingsControl(); IsLocal = false; } public override void PrepareLaunch() { // Extract the assembly CustomAssembly = Fl.SafeLocation(RequestFile.Temp) + "connector.exe"; using (FileStream fs = File.Create(CustomAssembly)) { fs.Write(Resources.JsonApiConnector, 0, Resources.JsonApiConnector.Length); } } public override string GetLaunchParameters(string defaultParameters = "") { Control control = Starter.GetCustomSettingsControl(); if (!(control is JsonApi2CredentialsSettingsControl)) throw new Exception("Couldn't retrieve parameters"); JsonApi2CredentialsSettingsControl cred = (JsonApi2CredentialsSettingsControl) control; return "-u=" + cred.Username + " -p=" + cred.Password + " -host=" + cred.Host + " -port=" + cred.Port + " -filter"; } } }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
addon-sdk/source/lib/sdk/ui/sidebar.js
10346
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; module.metadata = { 'stability': 'experimental', 'engines': { 'Firefox': '*' } }; const { Class } = require('../core/heritage'); const { merge } = require('../util/object'); const { Disposable } = require('../core/disposable'); const { off, emit, setListeners } = require('../event/core'); const { EventTarget } = require('../event/target'); const { URL } = require('../url'); const { add, remove, has, clear, iterator } = require('../lang/weak-set'); const { id: addonID, data } = require('../self'); const { WindowTracker } = require('../deprecated/window-utils'); const { isShowing } = require('./sidebar/utils'); const { isBrowser, getMostRecentBrowserWindow, windows, isWindowPrivate } = require('../window/utils'); const { ns } = require('../core/namespace'); const { remove: removeFromArray } = require('../util/array'); const { show, hide, toggle } = require('./sidebar/actions'); const { Worker } = require('../deprecated/sync-worker'); const { contract: sidebarContract } = require('./sidebar/contract'); const { create, dispose, updateTitle, updateURL, isSidebarShowing, showSidebar, hideSidebar } = require('./sidebar/view'); const { defer } = require('../core/promise'); const { models, views, viewsFor, modelFor } = require('./sidebar/namespace'); const { isLocalURL } = require('../url'); const { ensure } = require('../system/unload'); const { identify } = require('./id'); const { uuid } = require('../util/uuid'); const { viewFor } = require('../view/core'); const resolveURL = (url) => url ? data.url(url) : url; const sidebarNS = ns(); const WEB_PANEL_BROWSER_ID = 'web-panels-browser'; var sidebars = {}; const Sidebar = Class({ implements: [ Disposable ], extends: EventTarget, setup: function(options) { // inital validation for the model information let model = sidebarContract(options); // save the model information models.set(this, model); // generate an id if one was not provided model.id = model.id || addonID + '-' + uuid(); // further validation for the title and url validateTitleAndURLCombo({}, this.title, this.url); const self = this; const internals = sidebarNS(self); const windowNS = internals.windowNS = ns(); // see bug https://bugzilla.mozilla.org/show_bug.cgi?id=886148 ensure(this, 'destroy'); setListeners(this, options); let bars = []; internals.tracker = WindowTracker({ onTrack: function(window) { if (!isBrowser(window)) return; let sidebar = window.document.getElementById('sidebar'); let sidebarBox = window.document.getElementById('sidebar-box'); let bar = create(window, { id: self.id, title: self.title, sidebarurl: self.url }); bars.push(bar); windowNS(window).bar = bar; bar.addEventListener('command', function() { if (isSidebarShowing(window, self)) { hideSidebar(window, self).catch(() => {}); return; } showSidebar(window, self); }); function onSidebarLoad() { // check if the sidebar is ready let isReady = sidebar.docShell && sidebar.contentDocument; if (!isReady) return; // check if it is a web panel let panelBrowser = sidebar.contentDocument.getElementById(WEB_PANEL_BROWSER_ID); if (!panelBrowser) { bar.removeAttribute('checked'); return; } let sbTitle = window.document.getElementById('sidebar-title'); function onWebPanelSidebarCreated() { if (panelBrowser.contentWindow.location != resolveURL(model.url) || sbTitle.value != model.title) { return; } let worker = windowNS(window).worker = Worker({ window: panelBrowser.contentWindow, injectInDocument: true }); function onWebPanelSidebarUnload() { windowNS(window).onWebPanelSidebarUnload = null; // uncheck the associated menuitem bar.setAttribute('checked', 'false'); emit(self, 'hide', {}); emit(self, 'detach', worker); windowNS(window).worker = null; } windowNS(window).onWebPanelSidebarUnload = onWebPanelSidebarUnload; panelBrowser.contentWindow.addEventListener('unload', onWebPanelSidebarUnload, true); // check the associated menuitem bar.setAttribute('checked', 'true'); function onWebPanelSidebarReady() { panelBrowser.contentWindow.removeEventListener('DOMContentLoaded', onWebPanelSidebarReady); windowNS(window).onWebPanelSidebarReady = null; emit(self, 'ready', worker); } windowNS(window).onWebPanelSidebarReady = onWebPanelSidebarReady; panelBrowser.contentWindow.addEventListener('DOMContentLoaded', onWebPanelSidebarReady); function onWebPanelSidebarLoad() { panelBrowser.contentWindow.removeEventListener('load', onWebPanelSidebarLoad, true); windowNS(window).onWebPanelSidebarLoad = null; // TODO: decide if returning worker is acceptable.. //emit(self, 'show', { worker: worker }); emit(self, 'show', {}); } windowNS(window).onWebPanelSidebarLoad = onWebPanelSidebarLoad; panelBrowser.contentWindow.addEventListener('load', onWebPanelSidebarLoad, true); emit(self, 'attach', worker); } windowNS(window).onWebPanelSidebarCreated = onWebPanelSidebarCreated; panelBrowser.addEventListener('DOMWindowCreated', onWebPanelSidebarCreated, true); } windowNS(window).onSidebarLoad = onSidebarLoad; sidebar.addEventListener('load', onSidebarLoad, true); // removed properly }, onUntrack: function(window) { if (!isBrowser(window)) return; // hide the sidebar if it is showing hideSidebar(window, self).catch(() => {}); // kill the menu item let { bar } = windowNS(window); if (bar) { removeFromArray(viewsFor(self), bar); dispose(bar); } // kill listeners let sidebar = window.document.getElementById('sidebar'); if (windowNS(window).onSidebarLoad) { sidebar && sidebar.removeEventListener('load', windowNS(window).onSidebarLoad, true) windowNS(window).onSidebarLoad = null; } let panelBrowser = sidebar && sidebar.contentDocument.getElementById(WEB_PANEL_BROWSER_ID); if (windowNS(window).onWebPanelSidebarCreated) { panelBrowser && panelBrowser.removeEventListener('DOMWindowCreated', windowNS(window).onWebPanelSidebarCreated, true); windowNS(window).onWebPanelSidebarCreated = null; } if (windowNS(window).onWebPanelSidebarReady) { panelBrowser && panelBrowser.contentWindow.removeEventListener('DOMContentLoaded', windowNS(window).onWebPanelSidebarReady); windowNS(window).onWebPanelSidebarReady = null; } if (windowNS(window).onWebPanelSidebarLoad) { panelBrowser && panelBrowser.contentWindow.removeEventListener('load', windowNS(window).onWebPanelSidebarLoad, true); windowNS(window).onWebPanelSidebarLoad = null; } if (windowNS(window).onWebPanelSidebarUnload) { panelBrowser && panelBrowser.contentWindow.removeEventListener('unload', windowNS(window).onWebPanelSidebarUnload, true); windowNS(window).onWebPanelSidebarUnload(); } } }); views.set(this, bars); add(sidebars, this); }, get id() { return (modelFor(this) || {}).id; }, get title() { return (modelFor(this) || {}).title; }, set title(v) { // destroyed? if (!modelFor(this)) return; // validation if (typeof v != 'string') throw Error('title must be a string'); validateTitleAndURLCombo(this, v, this.url); // do update updateTitle(this, v); return modelFor(this).title = v; }, get url() { return (modelFor(this) || {}).url; }, set url(v) { // destroyed? if (!modelFor(this)) return; // validation if (!isLocalURL(v)) throw Error('the url must be a valid local url'); validateTitleAndURLCombo(this, this.title, v); // do update updateURL(this, v); modelFor(this).url = v; }, show: function(window) { return showSidebar(viewFor(window), this); }, hide: function(window) { return hideSidebar(viewFor(window), this); }, dispose: function() { const internals = sidebarNS(this); off(this); remove(sidebars, this); // stop tracking windows if (internals.tracker) { internals.tracker.unload(); } internals.tracker = null; internals.windowNS = null; views.delete(this); models.delete(this); } }); exports.Sidebar = Sidebar; function validateTitleAndURLCombo(sidebar, title, url) { url = resolveURL(url); if (sidebar.title == title && sidebar.url == url) { return false; } for (let window of windows(null, { includePrivate: true })) { let sidebar = window.document.querySelector('menuitem[sidebarurl="' + url + '"][label="' + title + '"]'); if (sidebar) { throw Error('The provided title and url combination is invalid (already used).'); } } return false; } isShowing.define(Sidebar, isSidebarShowing.bind(null, null)); show.define(Sidebar, showSidebar.bind(null, null)); hide.define(Sidebar, hideSidebar.bind(null, null)); identify.define(Sidebar, function(sidebar) { return sidebar.id; }); function toggleSidebar(window, sidebar) { // TODO: make sure this is not private window = window || getMostRecentBrowserWindow(); if (isSidebarShowing(window, sidebar)) { return hideSidebar(window, sidebar); } return showSidebar(window, sidebar); } toggle.define(Sidebar, toggleSidebar.bind(null, null));
mpl-2.0
gabyx/ExecutionGraph
include/executionGraph/common/Log.hpp
3710
//! ======================================================================================== //! ExecutionGraph //! Copyright (C) 2014 by Gabriel Nützi <gnuetzi (at) gmail (døt) com> //! //! @date Mon Jan 08 2018 //! @author Gabriel Nützi, <gnuetzi (at) gmail (døt) com> //! //! This Source Code Form is subject to the terms of the Mozilla Public //! License, v. 2.0. If a copy of the MPL was not distributed with this //! file, You can obtain one at http://mozilla.org/MPL/2.0/. //! ======================================================================================== #pragma once #include <iostream> #include <fmt/format.h> #include "executionGraph/config/Config.hpp" #ifndef EXECGRAPH_FORCE_MSGLOG_LEVEL # error "EXECGRAPH_FORCE_MSGLOG_LEVEL needs to be defined!" #endif #define EXECGRAPH_LOGLEVEL_TRACE 0 #define EXECGRAPH_LOGLEVEL_DEBUG 1 #define EXECGRAPH_LOGLEVEL_INFO 2 #define EXECGRAPH_LOGLEVEL_WARN 3 #define EXECGRAPH_LOGLEVEL_ERROR 4 #define EXECGRAPH_LOGLEVEL_FATAL 5 // To Concat EXECGRAPH_LOGLEVEL_ and EXECGRAPH_FORCE_MSGLOG_LEVEL #define CONCATT(L) EXECGRAPH_LOGLEVEL_##L // x and y will not be expanded, just pasted #define CONCAT(L) CONCATT(L) // x and y will be expanded before the call to STEP2 #define EXECGRAPH_LOGLEVEL_CURRENT CONCAT(EXECGRAPH_FORCE_MSGLOG_LEVEL) #define EXECGRAPH_LOGMSG(LEVEL, ...) \ if(CONCAT(LEVEL) <= EXECGRAPH_LOGLEVEL_CURRENT) \ { \ std::cerr << fmt::format(__VA_ARGS__) << std::endl; \ } #define EXECGRAPH_LOGMSG_LEVEL(LEVEL, ...) \ if(CONCAT(LEVEL) <= EXECGRAPH_LOGLEVEL_CURRENT) \ { \ std::cerr << "[" #LEVEL "] " << fmt::format(__VA_ARGS__) << std::endl; \ } #define EXECGRAPH_LOGMSG_CONT_LEVEL(LEVEL, ...) \ if(CONCAT(LEVEL) <= EXECGRAPH_LOGLEVEL_CURRENT) \ { \ std::cerr << "[" #LEVEL "] " << fmt::format(__VA_ARGS__); \ } // Undefine all log macros #define EXECGRAPH_LOG_TRACE(...) #define EXECGRAPH_LOG_TRACE_CONT(...) #define EXECGRAPH_LOG_DEBUG(...) #define EXECGRAPH_LOG_INFO(...) #define EXECGRAPH_LOG_WARN(...) #define EXECGRAPH_LOG_ERROR(...) #define EXECGRAPH_LOG_FATAL(...) // Define only those which are active! #if EXECGRAPH_LOGLEVEL_CURRENT <= EXECGRAPH_LOGLEVEL_TRACE # undef EXECGRAPH_LOG_TRACE # define EXECGRAPH_LOG_TRACE(...) EXECGRAPH_LOGMSG_LEVEL(TRACE, __VA_ARGS__) # undef EXECGRAPH_LOG_TRACE_CONT # define EXECGRAPH_LOG_TRACE_CONT(...) EXECGRAPH_LOGMSG_CONT_LEVEL(TRACE, __VA_ARGS__) #endif #if EXECGRAPH_LOGLEVEL_CURRENT <= EXECGRAPH_LOGLEVEL_DEBUG # undef EXECGRAPH_LOG_DEBUG # define EXECGRAPH_LOG_DEBUG(...) EXECGRAPH_LOGMSG_LEVEL(DEBUG, __VA_ARGS__) #endif #if EXECGRAPH_LOGLEVEL_CURRENT <= EXECGRAPH_LOGLEVEL_INFO # undef EXECGRAPH_LOG_INFO # define EXECGRAPH_LOG_INFO(...) EXECGRAPH_LOGMSG_LEVEL(INFO, __VA_ARGS__) #endif #if EXECGRAPH_LOGLEVEL_CURRENT <= EXECGRAPH_LOGLEVEL_WARN # undef EXECGRAPH_LOG_WARN # define EXECGRAPH_LOG_WARN(...) EXECGRAPH_LOGMSG_LEVEL(WARN, __VA_ARGS__) #endif #if EXECGRAPH_LOGLEVEL_CURRENT <= EXECGRAPH_LOGLEVEL_ERROR # undef EXECGRAPH_LOG_ERROR # define EXECGRAPH_LOG_ERROR(...) EXECGRAPH_LOGMSG_LEVEL(ERROR, __VA_ARGS__) #endif #if EXECGRAPH_LOGLEVEL_CURRENT <= EXECGRAPH_LOGLEVEL_FATAL # undef EXECGRAPH_LOG_FATAL # define EXECGRAPH_LOG_FATAL(...) EXECGRAPH_LOGMSG_LEVEL(FATAL, __VA_ARGS__) #endif #undef CONCAT1 #undef CONCAT2
mpl-2.0
SingleSO/singleso
views/admin/settings.php
6561
<?php /** * @var yiiwebView $this * @var yii\bootstrap\ActiveForm $form * @var app\models\admin\SettingsForm $model */ use yii\helpers\Html; use yii\bootstrap\ActiveForm; use yii\captcha\Captcha; $this->title = 'Settings'; ?> <?= $this->render('_alert') ?> <div class="row"> <div class="col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2"> <h1><?= Html::encode($this->title) ?></h1> <?php $form = ActiveForm::begin(['id' => 'admin-settings']); ?> <div class="panel panel-default"> <div class="panel-heading"> <h2 class="panel-title">Application Settings</h2> </div> <div class="panel-body"> <?= $form->field($model, 'application_admin_email') ?> <?= $form->field($model, 'application_home_url') ?> <?= $form->field($model, 'application_name') ?> <?= $form->field($model, 'application_copyright') ?> <p>Use <code>{{year}}</code> for the current year.</p> <?= $form->field($model, 'application_theme') ->radioList($model->themes()) ?> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h2 class="panel-title">User Settings</h2> </div> <div class="panel-body"> <div class="form-group"> <label class="control-label">Registration Settings</label> <?= $form->field($model, 'user_registration_enabled') ->checkbox() ?> <?= $form->field($model, 'user_registration_confirmation') ->checkbox() ?> <?= $form->field($model, 'user_registration_unconfirmed_login') ->checkbox() ?> <?= $form->field($model, 'user_registration_password_recovery') ->checkbox() ?> </div> <?= $form->field($model, 'user_registration_confirm_time') ->label('User Registration Confirm Time (Default: <code>' . $model->defaultValue('user_registration_confirm_time') . '</code>)') ?> <p>Time is in seconds.</p> <?= $form->field($model, 'user_registration_recover_time') ->label('User Registration Recover Time (Default: <code>' . $model->defaultValue('user_registration_recover_time') . '</code>)') ?> <p>Time is in seconds.</p> <?= $form->field($model, 'user_login_remember_time') ->label('User Login Remember Time (Default: <code>' . $model->defaultValue('user_login_remember_time') . '</code>)') ?> <p>Time is in seconds.</p> <?= $form->field($model, 'user_name_length_max') ->label('User Name Max Length (Default: <code>' . $model->defaultValue('user_name_length_max') . '</code>)') ?> <?= $form->field($model, 'user_name_length_min') ->label('User Name Min Length (Default: <code>' . $model->defaultValue('user_name_length_min') . '</code>)') ?> <?= $form->field($model, 'user_email_length_max') ->label('Email Max Length (Default: <code>' . $model->defaultValue('user_email_length_max') . '</code>)') ?> <?= $form->field($model, 'user_name_blacklist', ['enableAjaxValidation' => true]) ->textarea(['value' => implode("\n", $model->user_name_blacklist), 'rows' => 10]) ?> <p>Prevents users from using a name. Admins are not restricted by the blacklist. One blacklist entry per-line. Supports string matching and regular expressions. String matching is case-insensitive, regex must include <code>i</code> flag for case-insensitive matching. Regular expressions must use <code>/</code> as delimiter, other lines are treated as plain strings.</p> <p>Regex Examples:</p> <ul> <li><code>/^exactname$/</code> (Exactly "exactname")</li> <li><code>/caseinsensitivename/i</code> (Contains "caseinsensitivename" of any letter casing.)</li> </ul> <?= $form->field($model, 'user_profile_fields') ->checkboxList($model->profileFields()) ?> <?= $form->field($model, 'user_profile_fields_all') ->checkbox() ?> <p>Check the all option to include all fields, or select individual fields.</p> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h2 class="panel-title">OAuth 2 Settings</h2> </div> <div class="panel-body"> <?= $form->field($model, 'oauth2_code_expire') ->label('Code Expire Time (Default: <code>' . $model->defaultValue('oauth2_code_expire') . '</code>)') ?> <?= $form->field($model, 'oauth2_token_expire') ->label('Token Expire Time (Default: <code>' . $model->defaultValue('oauth2_token_expire') . '</code>)') ?> <p>These settings set the time in seconds that OAuth 2 codes and tokens last before expiration. Use negative value to never expire.</p> <?= $form->field($model, 'oauth2_endpoint') ->textinput(['readonly' => true]) ->label('OAuth 2 Endpoint') ?> <?= $form->field($model, 'oauth2_loginurl') ->textinput(['readonly' => true]) ->label('OAuth 2 Login') ?> <?= $form->field($model, 'oauth2_registerurl') ->textinput(['readonly' => true]) ->label('OAuth 2 Register') ?> <?= $form->field($model, 'oauth2_logouturl') ->textinput(['readonly' => true]) ->label('OAuth 2 Logout') ?> <?= $form->field($model, 'oauth2_domain_global_cookie_name') ->textinput(['readonly' => true]) ->label('Domain Global Cookie Name') ?> <p>Domain global cookie is the name of a cookie set global for the domain to check if logged in.</p> <p>Set by config files like other cookie names. If empty then cookie is disabled.</p> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h2 class="panel-title">Pages</h2> </div> <div class="panel-body"> <p>Page contents support Markdown and HTML. Empty the page content to remove the page.</p> <?= $form->field($model, 'page_about_content') ->textarea(['rows' => 10]) ->label('About Page Content') ?> <?= $form->field($model, 'page_contact_content') ->textarea(['rows' => 10]) ->label('Contact Page Content') ?> <?= $form->field($model, 'page_contact_submitted') ->label('Contact Page Form Submitted Message') ?> <?= $form->field($model, 'page_links') ->textarea(['rows' => 10]) ->label('Links to Add to Nav Menu') ?> <p>A list of links with title and URL pairs. Title on one line, URL on another.</p> </div> </div> <div class="form-group"> <?= Html::submitButton('Submit', [ 'class' => 'btn btn-primary', 'name' => 'contact-button' ]) ?> </div> <?php ActiveForm::end(); ?> </div> </div>
mpl-2.0
marcelohenrique/jsc
src/misc/dwr/bean/Contato.java
1078
package misc.dwr.bean; public class Contato { private int id; private String nome; private String endereco; private String telefone; private long timestamp; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public Contato() { timestamp = System.currentTimeMillis(); } public Contato(int i, String n, String e, String t) { this(); id = i; nome = n; endereco = e; telefone = t; } public String imprimir() { return "id: " + id + "\tnome: " + nome + "\tendereco: " + endereco + "\ttelefone: " + telefone; } }
mpl-2.0
tmhorne/celtx
security/manager/pki/src/nsPKIModule.cpp
3605
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Terry Hayes <thayes@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "nsIModule.h" #include "nsIGenericFactory.h" #include "nsNSSDialogs.h" #include "nsPKIParamBlock.h" #include "nsASN1Tree.h" #include "nsFormSigningDialog.h" NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsNSSDialogs, Init) NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsPKIParamBlock, Init) NS_GENERIC_FACTORY_CONSTRUCTOR(nsNSSASN1Tree) NS_GENERIC_FACTORY_CONSTRUCTOR(nsFormSigningDialog) #define NSS_DIALOGS_DESCRIPTION "PSM Dialog Impl" static const nsModuleComponentInfo components[] = { { NSS_DIALOGS_DESCRIPTION, NS_NSSDIALOGS_CID, NS_TOKENPASSWORDSDIALOG_CONTRACTID, nsNSSDialogsConstructor }, { NSS_DIALOGS_DESCRIPTION, NS_NSSDIALOGS_CID, NS_CERTIFICATEDIALOGS_CONTRACTID, nsNSSDialogsConstructor }, { NSS_DIALOGS_DESCRIPTION, NS_NSSDIALOGS_CID, NS_CLIENTAUTHDIALOGS_CONTRACTID, nsNSSDialogsConstructor }, { NSS_DIALOGS_DESCRIPTION, NS_NSSDIALOGS_CID, NS_CERTPICKDIALOGS_CONTRACTID, nsNSSDialogsConstructor }, { NSS_DIALOGS_DESCRIPTION, NS_NSSDIALOGS_CID, NS_TOKENDIALOGS_CONTRACTID, nsNSSDialogsConstructor }, { NSS_DIALOGS_DESCRIPTION, NS_NSSDIALOGS_CID, NS_DOMCRYPTODIALOGS_CONTRACTID, nsNSSDialogsConstructor }, { NSS_DIALOGS_DESCRIPTION, NS_NSSDIALOGS_CID, NS_GENERATINGKEYPAIRINFODIALOGS_CONTRACTID, nsNSSDialogsConstructor }, { "ASN1 Tree", NS_NSSASN1OUTINER_CID, NS_ASN1TREE_CONTRACTID, nsNSSASN1TreeConstructor }, { "PKI Parm Block", NS_PKIPARAMBLOCK_CID, NS_PKIPARAMBLOCK_CONTRACTID, nsPKIParamBlockConstructor }, { "Form Signing Dialog", NS_FORMSIGNINGDIALOG_CID, NS_FORMSIGNINGDIALOG_CONTRACTID, nsFormSigningDialogConstructor } }; NS_IMPL_NSGETMODULE(PKI, components)
mpl-2.0
ellipsonic/thebuggenige_app
vendor/realityking/pchart/Example19.php
1491
<?php /* Example19 : Error reporting */ // Standard inclusions include("src/pData.php"); include("src/pChart.php"); // Dataset definition $DataSet = new pData; $DataSet->AddPoint(array(10,4,3,2,3,3,2,1,0,7,4,3,2,3,3,5,1,0,7),"Serie1"); $DataSet->AddPoint(array(1,4,2,6,2,3,0,1,-5,1,2,4,5,2,1,0,6,4,30),"Serie2"); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie(); $DataSet->SetXAxisName("Samples"); $DataSet->SetYAxisName("Temperature"); $DataSet->SetSerieName("January","Serie1"); // Initialise the graph $Test = new pChart(700,230); $Test->reportWarnings("GD"); $Test->setFontProperties("Fonts/tahoma.ttf",8); $Test->setGraphArea(60,30,585,185); $Test->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240); $Test->drawRoundedRectangle(5,5,695,225,5,230,230,230); $Test->drawGraphArea(255,255,255,TRUE); $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2); $Test->drawGrid(4,TRUE,230,230,230,50); // Draw the 0 line $Test->setFontProperties("Fonts/tahoma.ttf",6); $Test->drawTreshold(0,143,55,72,TRUE,TRUE); // Draw the cubic curve graph $Test->drawCubicCurve($DataSet->GetData(),$DataSet->GetDataDescription()); // Finish the graph $Test->setFontProperties("Fonts/tahoma.ttf",8); $Test->drawLegend(600,30,$DataSet->GetDataDescription(),255,255,255); $Test->setFontProperties("Fonts/tahoma.ttf",10); $Test->drawTitle(50,22,"Example 19",50,50,50,585); $Test->Render("example19.png");
mpl-2.0
blitzagency/rich
demos/src/static/js/app/demos/auto-layout-demo/views/content.js
319
define(function (require, exports, module) { var rich = require('rich'); var utils = require('app/utils'); var RectangleView = require('app/shared/views/rectangle-view').RectangleView; var Content = RectangleView.extend({ autoLayoutTransition: { duration: 500 }, }); exports.Content = Content; });
mpl-2.0
fiji-flo/servo
components/style_derive/to_animated_zero.rs
2423
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use animate::{AnimationVariantAttrs, AnimationFieldAttrs}; use cg; use quote; use syn; use synstructure; pub fn derive(input: syn::DeriveInput) -> quote::Tokens { let name = &input.ident; let trait_path = parse_quote!(values::animated::ToAnimatedZero); let (impl_generics, ty_generics, mut where_clause) = cg::trait_parts(&input, &trait_path); let s = synstructure::Structure::new(&input); let to_body = s.each_variant(|variant| { let attrs = cg::parse_variant_attrs::<AnimationVariantAttrs>(&variant.ast()); if attrs.error { return Some(quote! { Err(()) }); } let (mapped, mapped_bindings) = cg::value(variant, "mapped"); let bindings_pairs = variant.bindings().into_iter().zip(mapped_bindings); let mut computations = quote!(); computations.append_all(bindings_pairs.map(|(binding, mapped_binding)| { let field_attrs = cg::parse_field_attrs::<AnimationFieldAttrs>(&binding.ast()); if field_attrs.constant { if cg::is_parameterized(&binding.ast().ty, &where_clause.params, None) { where_clause.add_predicate(cg::where_predicate( binding.ast().ty.clone(), &parse_quote!(std::clone::Clone), None, )); } quote! { let #mapped_binding = ::std::clone::Clone::clone(#binding); } } else { where_clause.add_trait_bound(&binding.ast().ty); quote! { let #mapped_binding = ::values::animated::ToAnimatedZero::to_animated_zero(#binding)?; } } })); computations.append_all(quote! { Ok(#mapped) }); Some(computations) }); quote! { impl #impl_generics ::values::animated::ToAnimatedZero for #name #ty_generics #where_clause { #[allow(unused_variables)] #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { match *self { #to_body } } } } }
mpl-2.0
logicmonitor/k8s-argus
vendor/github.com/logicmonitor/lm-sdk-go/models/n_map_netscan.go
17318
// Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "bytes" "context" "encoding/json" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // NMapNetscan n map netscan // // swagger:model NMapNetscan type NMapNetscan struct { collectorField *int32 collectorDescriptionField string collectorGroupField int32 collectorGroupNameField string creatorField string descriptionField string duplicateField *ExcludeDuplicateIps groupField string idField int32 ignoreSystemIPsDuplicatesField bool nameField *string nextStartField string nextStartEpochField int64 nsgIdField int32 scheduleField *RestSchedule versionField int32 // The credentials to be used for the scan // Example: 2 Credentials *NMapNetscanPolicyCredential `json:"credentials,omitempty"` // Information related to including / excluding discovered devices in / from monitoring Ddr *NMapDDR `json:"ddr,omitempty"` // The subnet to exclude from scanning from nmap scans // Example: 10.35.41.1-10.35.41.254 Exclude string `json:"exclude,omitempty"` // The ports that should be used in the Netscan // Required: true Ports *NetscanPorts `json:"ports"` // The subnet to scan for nmap scans // Example: 10.35.41.1-10.35.41.254 // Required: true Subnet *string `json:"subnet"` } // Collector gets the collector of this subtype func (m *NMapNetscan) Collector() *int32 { return m.collectorField } // SetCollector sets the collector of this subtype func (m *NMapNetscan) SetCollector(val *int32) { m.collectorField = val } // CollectorDescription gets the collector description of this subtype func (m *NMapNetscan) CollectorDescription() string { return m.collectorDescriptionField } // SetCollectorDescription sets the collector description of this subtype func (m *NMapNetscan) SetCollectorDescription(val string) { m.collectorDescriptionField = val } // CollectorGroup gets the collector group of this subtype func (m *NMapNetscan) CollectorGroup() int32 { return m.collectorGroupField } // SetCollectorGroup sets the collector group of this subtype func (m *NMapNetscan) SetCollectorGroup(val int32) { m.collectorGroupField = val } // CollectorGroupName gets the collector group name of this subtype func (m *NMapNetscan) CollectorGroupName() string { return m.collectorGroupNameField } // SetCollectorGroupName sets the collector group name of this subtype func (m *NMapNetscan) SetCollectorGroupName(val string) { m.collectorGroupNameField = val } // Creator gets the creator of this subtype func (m *NMapNetscan) Creator() string { return m.creatorField } // SetCreator sets the creator of this subtype func (m *NMapNetscan) SetCreator(val string) { m.creatorField = val } // Description gets the description of this subtype func (m *NMapNetscan) Description() string { return m.descriptionField } // SetDescription sets the description of this subtype func (m *NMapNetscan) SetDescription(val string) { m.descriptionField = val } // Duplicate gets the duplicate of this subtype func (m *NMapNetscan) Duplicate() *ExcludeDuplicateIps { return m.duplicateField } // SetDuplicate sets the duplicate of this subtype func (m *NMapNetscan) SetDuplicate(val *ExcludeDuplicateIps) { m.duplicateField = val } // Group gets the group of this subtype func (m *NMapNetscan) Group() string { return m.groupField } // SetGroup sets the group of this subtype func (m *NMapNetscan) SetGroup(val string) { m.groupField = val } // ID gets the id of this subtype func (m *NMapNetscan) ID() int32 { return m.idField } // SetID sets the id of this subtype func (m *NMapNetscan) SetID(val int32) { m.idField = val } // IgnoreSystemIPsDuplicates gets the ignore system i ps duplicates of this subtype func (m *NMapNetscan) IgnoreSystemIPsDuplicates() bool { return m.ignoreSystemIPsDuplicatesField } // SetIgnoreSystemIPsDuplicates sets the ignore system i ps duplicates of this subtype func (m *NMapNetscan) SetIgnoreSystemIPsDuplicates(val bool) { m.ignoreSystemIPsDuplicatesField = val } // Method gets the method of this subtype func (m *NMapNetscan) Method() string { return "nmap" } // SetMethod sets the method of this subtype func (m *NMapNetscan) SetMethod(val string) { } // Name gets the name of this subtype func (m *NMapNetscan) Name() *string { return m.nameField } // SetName sets the name of this subtype func (m *NMapNetscan) SetName(val *string) { m.nameField = val } // NextStart gets the next start of this subtype func (m *NMapNetscan) NextStart() string { return m.nextStartField } // SetNextStart sets the next start of this subtype func (m *NMapNetscan) SetNextStart(val string) { m.nextStartField = val } // NextStartEpoch gets the next start epoch of this subtype func (m *NMapNetscan) NextStartEpoch() int64 { return m.nextStartEpochField } // SetNextStartEpoch sets the next start epoch of this subtype func (m *NMapNetscan) SetNextStartEpoch(val int64) { m.nextStartEpochField = val } // NsgID gets the nsg Id of this subtype func (m *NMapNetscan) NsgID() int32 { return m.nsgIdField } // SetNsgID sets the nsg Id of this subtype func (m *NMapNetscan) SetNsgID(val int32) { m.nsgIdField = val } // Schedule gets the schedule of this subtype func (m *NMapNetscan) Schedule() *RestSchedule { return m.scheduleField } // SetSchedule sets the schedule of this subtype func (m *NMapNetscan) SetSchedule(val *RestSchedule) { m.scheduleField = val } // Version gets the version of this subtype func (m *NMapNetscan) Version() int32 { return m.versionField } // SetVersion sets the version of this subtype func (m *NMapNetscan) SetVersion(val int32) { m.versionField = val } // UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure func (m *NMapNetscan) UnmarshalJSON(raw []byte) error { var data struct { // The credentials to be used for the scan // Example: 2 Credentials *NMapNetscanPolicyCredential `json:"credentials,omitempty"` // Information related to including / excluding discovered devices in / from monitoring Ddr *NMapDDR `json:"ddr,omitempty"` // The subnet to exclude from scanning from nmap scans // Example: 10.35.41.1-10.35.41.254 Exclude string `json:"exclude,omitempty"` // The ports that should be used in the Netscan // Required: true Ports *NetscanPorts `json:"ports"` // The subnet to scan for nmap scans // Example: 10.35.41.1-10.35.41.254 // Required: true Subnet *string `json:"subnet"` } buf := bytes.NewBuffer(raw) dec := json.NewDecoder(buf) dec.UseNumber() if err := dec.Decode(&data); err != nil { return err } var base struct { /* Just the base type fields. Used for unmashalling polymorphic types.*/ Collector *int32 `json:"collector"` CollectorDescription string `json:"collectorDescription,omitempty"` CollectorGroup int32 `json:"collectorGroup,omitempty"` CollectorGroupName string `json:"collectorGroupName,omitempty"` Creator string `json:"creator,omitempty"` Description string `json:"description,omitempty"` Duplicate *ExcludeDuplicateIps `json:"duplicate"` Group string `json:"group,omitempty"` ID int32 `json:"id,omitempty"` IgnoreSystemIPsDuplicates bool `json:"ignoreSystemIPsDuplicates,omitempty"` Method string `json:"method"` Name *string `json:"name"` NextStart string `json:"nextStart,omitempty"` NextStartEpoch int64 `json:"nextStartEpoch,omitempty"` NsgID int32 `json:"nsgId,omitempty"` Schedule *RestSchedule `json:"schedule,omitempty"` Version int32 `json:"version,omitempty"` } buf = bytes.NewBuffer(raw) dec = json.NewDecoder(buf) dec.UseNumber() if err := dec.Decode(&base); err != nil { return err } var result NMapNetscan result.collectorField = base.Collector result.collectorDescriptionField = base.CollectorDescription result.collectorGroupField = base.CollectorGroup result.collectorGroupNameField = base.CollectorGroupName result.creatorField = base.Creator result.descriptionField = base.Description result.duplicateField = base.Duplicate result.groupField = base.Group result.idField = base.ID result.ignoreSystemIPsDuplicatesField = base.IgnoreSystemIPsDuplicates if base.Method != result.Method() { /* Not the type we're looking for. */ return errors.New(422, "invalid method value: %q", base.Method) } result.nameField = base.Name result.nextStartField = base.NextStart result.nextStartEpochField = base.NextStartEpoch result.nsgIdField = base.NsgID result.scheduleField = base.Schedule result.versionField = base.Version result.Credentials = data.Credentials result.Ddr = data.Ddr result.Exclude = data.Exclude result.Ports = data.Ports result.Subnet = data.Subnet *m = result return nil } // MarshalJSON marshals this object with a polymorphic type to a JSON structure func (m NMapNetscan) MarshalJSON() ([]byte, error) { var b1, b2, b3 []byte var err error b1, err = json.Marshal(struct { // The credentials to be used for the scan // Example: 2 Credentials *NMapNetscanPolicyCredential `json:"credentials,omitempty"` // Information related to including / excluding discovered devices in / from monitoring Ddr *NMapDDR `json:"ddr,omitempty"` // The subnet to exclude from scanning from nmap scans // Example: 10.35.41.1-10.35.41.254 Exclude string `json:"exclude,omitempty"` // The ports that should be used in the Netscan // Required: true Ports *NetscanPorts `json:"ports"` // The subnet to scan for nmap scans // Example: 10.35.41.1-10.35.41.254 // Required: true Subnet *string `json:"subnet"` }{ Credentials: m.Credentials, Ddr: m.Ddr, Exclude: m.Exclude, Ports: m.Ports, Subnet: m.Subnet, }) if err != nil { return nil, err } b2, err = json.Marshal(struct { Collector *int32 `json:"collector"` CollectorDescription string `json:"collectorDescription,omitempty"` CollectorGroup int32 `json:"collectorGroup,omitempty"` CollectorGroupName string `json:"collectorGroupName,omitempty"` Creator string `json:"creator,omitempty"` Description string `json:"description,omitempty"` Duplicate *ExcludeDuplicateIps `json:"duplicate"` Group string `json:"group,omitempty"` ID int32 `json:"id,omitempty"` IgnoreSystemIPsDuplicates bool `json:"ignoreSystemIPsDuplicates,omitempty"` Method string `json:"method"` Name *string `json:"name"` NextStart string `json:"nextStart,omitempty"` NextStartEpoch int64 `json:"nextStartEpoch,omitempty"` NsgID int32 `json:"nsgId,omitempty"` Schedule *RestSchedule `json:"schedule,omitempty"` Version int32 `json:"version,omitempty"` }{ Collector: m.Collector(), CollectorDescription: m.CollectorDescription(), CollectorGroup: m.CollectorGroup(), CollectorGroupName: m.CollectorGroupName(), Creator: m.Creator(), Description: m.Description(), Duplicate: m.Duplicate(), Group: m.Group(), ID: m.ID(), IgnoreSystemIPsDuplicates: m.IgnoreSystemIPsDuplicates(), Method: m.Method(), Name: m.Name(), NextStart: m.NextStart(), NextStartEpoch: m.NextStartEpoch(), NsgID: m.NsgID(), Schedule: m.Schedule(), Version: m.Version(), }) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } // Validate validates this n map netscan func (m *NMapNetscan) Validate(formats strfmt.Registry) error { var res []error if err := m.validateCollector(formats); err != nil { res = append(res, err) } if err := m.validateDuplicate(formats); err != nil { res = append(res, err) } if err := m.validateName(formats); err != nil { res = append(res, err) } if err := m.validateSchedule(formats); err != nil { res = append(res, err) } if err := m.validateCredentials(formats); err != nil { res = append(res, err) } if err := m.validateDdr(formats); err != nil { res = append(res, err) } if err := m.validatePorts(formats); err != nil { res = append(res, err) } if err := m.validateSubnet(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *NMapNetscan) validateCollector(formats strfmt.Registry) error { if err := validate.Required("collector", "body", m.Collector()); err != nil { return err } return nil } func (m *NMapNetscan) validateDuplicate(formats strfmt.Registry) error { if err := validate.Required("duplicate", "body", m.Duplicate()); err != nil { return err } if m.Duplicate() != nil { if err := m.Duplicate().Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("duplicate") } return err } } return nil } func (m *NMapNetscan) validateName(formats strfmt.Registry) error { if err := validate.Required("name", "body", m.Name()); err != nil { return err } return nil } func (m *NMapNetscan) validateSchedule(formats strfmt.Registry) error { if swag.IsZero(m.Schedule()) { // not required return nil } if m.Schedule() != nil { if err := m.Schedule().Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("schedule") } return err } } return nil } func (m *NMapNetscan) validateCredentials(formats strfmt.Registry) error { if swag.IsZero(m.Credentials) { // not required return nil } if m.Credentials != nil { if err := m.Credentials.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("credentials") } return err } } return nil } func (m *NMapNetscan) validateDdr(formats strfmt.Registry) error { if swag.IsZero(m.Ddr) { // not required return nil } if m.Ddr != nil { if err := m.Ddr.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("ddr") } return err } } return nil } func (m *NMapNetscan) validatePorts(formats strfmt.Registry) error { if err := validate.Required("ports", "body", m.Ports); err != nil { return err } if m.Ports != nil { if err := m.Ports.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("ports") } return err } } return nil } func (m *NMapNetscan) validateSubnet(formats strfmt.Registry) error { if err := validate.Required("subnet", "body", m.Subnet); err != nil { return err } return nil } // ContextValidate validate this n map netscan based on the context it is used func (m *NMapNetscan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateDuplicate(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateSchedule(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateCredentials(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateDdr(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidatePorts(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *NMapNetscan) contextValidateDuplicate(ctx context.Context, formats strfmt.Registry) error { if m.Duplicate() != nil { if err := m.Duplicate().ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("duplicate") } return err } } return nil } func (m *NMapNetscan) contextValidateSchedule(ctx context.Context, formats strfmt.Registry) error { if m.Schedule() != nil { if err := m.Schedule().ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("schedule") } return err } } return nil } func (m *NMapNetscan) contextValidateCredentials(ctx context.Context, formats strfmt.Registry) error { if m.Credentials != nil { if err := m.Credentials.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("credentials") } return err } } return nil } func (m *NMapNetscan) contextValidateDdr(ctx context.Context, formats strfmt.Registry) error { if m.Ddr != nil { if err := m.Ddr.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("ddr") } return err } } return nil } func (m *NMapNetscan) contextValidatePorts(ctx context.Context, formats strfmt.Registry) error { if m.Ports != nil { if err := m.Ports.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("ports") } return err } } return nil } // MarshalBinary interface implementation func (m *NMapNetscan) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *NMapNetscan) UnmarshalBinary(b []byte) error { var res NMapNetscan if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
mpl-2.0
dimy93/sports-cubed-android
osmdroid-android/src/main/java/org/osmdroid/tileprovider/BitmapPool.java
1498
package org.osmdroid.tileprovider; import java.util.LinkedList; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; public class BitmapPool { final LinkedList<Bitmap> mPool = new LinkedList<Bitmap>(); private static BitmapPool sInstance; public static BitmapPool getInstance() { if (sInstance == null) sInstance = new BitmapPool(); return sInstance; } public void returnDrawableToPool(ReusableBitmapDrawable drawable) { Bitmap b = drawable.tryRecycle(); if (b != null && b.isMutable()) synchronized (mPool) { mPool.addLast(b); } } public void applyReusableOptions(BitmapFactory.Options bitmapOptions) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { Bitmap pooledBitmap = obtainBitmapFromPool(); bitmapOptions.inBitmap = pooledBitmap; bitmapOptions.inSampleSize = 1; bitmapOptions.inMutable = true; } } public Bitmap obtainBitmapFromPool() { final Bitmap b; synchronized (mPool) { if (mPool.size() == 0) return null; else b = mPool.removeFirst(); } return b; } public Bitmap obtainSizedBitmapFromPool(int width, int height) { synchronized (mPool) { if (mPool.size() == 0) return null; else { for (Bitmap bitmap : mPool) if (bitmap.getWidth() == width && bitmap.getHeight() == height) { mPool.remove(bitmap); return bitmap; } } } return null; } }
mpl-2.0
rhelmer/socorro-webapp
crashstats/api/tests/test_views.py
70979
import datetime import json import re from django.contrib.auth.models import User, Permission from django.core.urlresolvers import reverse from django.conf import settings import mock from nose.tools import eq_, ok_ from waffle import Switch from crashstats.base.tests.testbase import TestCase from crashstats.crashstats.tests.test_views import ( BaseTestViews, Response, ) from crashstats.supersearch.tests.test_views import ( SUPERSEARCH_FIELDS_MOCKED_RESULTS ) from crashstats.tokens.models import Token class TestDedentLeft(TestCase): def test_dedent_left(self): from crashstats.api.views import dedent_left eq_(dedent_left('Hello', 2), 'Hello') eq_(dedent_left(' Hello', 2), ' Hello') eq_(dedent_left(' Hello ', 2), ' Hello ') text = """Line 1 Line 2 Line 3 """.rstrip() # because this code right above is indented with 2 * 4 spaces eq_(dedent_left(text, 8), 'Line 1\nLine 2\nLine 3') class TestDocumentationViews(BaseTestViews): @staticmethod def setUpClass(): TestDocumentationViews.switch = Switch.objects.create( name='app_api_all', active=True, ) @staticmethod def tearDownClass(): TestDocumentationViews.switch.delete() @mock.patch('requests.get') def test_documentation_home_page(self, rget): def mocked_get(url, params, **options): if '/supersearch/fields' in url: return Response(SUPERSEARCH_FIELDS_MOCKED_RESULTS) rget.side_effect = mocked_get url = reverse('api:documentation') response = self.client.get(url) eq_(response.status_code, 200) from crashstats.api import views for each in views.BLACKLIST: ok_(each not in response.content) class TestViews(BaseTestViews): @staticmethod def setUpClass(): TestViews.switch = Switch.objects.create( name='app_api_all', active=True, ) @staticmethod def tearDownClass(): TestViews.switch.delete() def setUp(self): super(TestViews, self).setUp() self._middleware_classes = settings.MIDDLEWARE_CLASSES settings.MIDDLEWARE_CLASSES += ( 'crashstats.crashstats.middleware.SetRemoteAddrFromForwardedFor', ) def tearDown(self): super(TestViews, self).tearDown() settings.MIDDLEWARE_CLASSES = self._middleware_classes def test_invalid_url(self): url = reverse('api:model_wrapper', args=('BlaBLabla',)) response = self.client.get(url) eq_(response.status_code, 404) @mock.patch('requests.get') def test_CrashesPerAdu(self, rget): def mocked_get(url, params, **options): if 'crashes/daily' in url: return Response(""" { "hits": { "WaterWolf:19.0": { "2012-10-08": { "product": "WaterWolf", "adu": 30000, "crash_hadu": 71.099999999999994, "version": "19.0", "report_count": 2133, "date": "2012-10-08" }, "2012-10-02": { "product": "WaterWolf", "adu": 30000, "crash_hadu": 77.299999999999997, "version": "19.0", "report_count": 2319, "date": "2012-10-02" } } } } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('CrashesPerAdu',)) response = self.client.get(url, { 'product': 'WaterWolf', 'versions': ['10.0', '11.1'], }) eq_(response.status_code, 200) eq_(response['Content-Type'], 'application/json; charset=UTF-8') dump = json.loads(response.content) ok_(dump['hits']) # miss one of the required fields response = self.client.get(url, { # note! no 'product' 'versions': ['10.0', '11.1'], }) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['product']) ok_('versions' not in dump['errors']) @mock.patch('requests.get') def test_CORS(self, rget): """any use of model_wrapper should return a CORS header""" def mocked_get(url, params, **options): return Response(""" { "breakpad_revision": "1139", "hits": [ { "date_oldest_job_queued": null, "date_recently_completed": null, "processors_count": 1, "avg_wait_sec": 0.0, "waiting_job_count": 0, "date_created": "2013-04-01T21:40:01+00:00", "id": 463859, "avg_process_sec": 0.0 } ], "total": 12, "socorro_revision": "9cfa4de" } """) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('Status',)) response = self.client.get(url) eq_(response.status_code, 200) eq_(response['Access-Control-Allow-Origin'], '*') @mock.patch('requests.get') def test_CrashesPerAdu_too_much(self, rget): def mocked_get(url, params, **options): if 'crashes/daily' in url: return Response(""" { "hits": { "WaterWolf:19.0": { "2012-10-08": { "product": "WaterWolf", "adu": 30000, "crash_hadu": 71.099999999999994, "version": "19.0", "report_count": 2133, "date": "2012-10-08" }, "2012-10-02": { "product": "WaterWolf", "adu": 30000, "crash_hadu": 77.299999999999997, "version": "19.0", "report_count": 2319, "date": "2012-10-02" } } } } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('CrashesPerAdu',)) response = self.client.get(url, { 'product': 'WaterWolf', 'versions': ['10.0', '11.1'], }) eq_(response.status_code, 200) eq_(response['Content-Type'], 'application/json; charset=UTF-8') for i in range(5): response = self.client.get(url, { 'product': 'WaterWolf', 'versions': ['10.0', '11.1'], }) # should still be ok eq_(response.status_code, 200) rate_limit = settings.API_RATE_LIMIT rate_limit_times = int(re.findall('\d+', rate_limit)[0]) for i in range(rate_limit_times + 1): response = self.client.get(url, { 'product': 'WaterWolf', 'versions': ['10.0', '11.1'], }) eq_(response.status_code, 429) eq_(response.content, 'Too Many Requests') @mock.patch('requests.get') def test_CrashesPerAdu_different_date_parameters(self, rget): def mocked_get(url, params, **options): if 'crashes/daily' in url: # note that the test below sends in a string as # '2012-1-1' which is valid but lacks the leading # zeros. Because the date is converted to a datetime.date # object and serialized back we'll get it here in this # full format. ok_('from_date' in params) eq_('2012-01-01', params['from_date']) return Response(""" { "hits": { "WaterWolf:19.0": { "2012-10-08": { "product": "WaterWolf", "adu": 30000, "crash_hadu": 71.099999999999994, "version": "19.0", "report_count": 2133, "date": "2012-10-08" }, "2012-10-02": { "product": "WaterWolf", "adu": 30000, "crash_hadu": 77.299999999999997, "version": "19.0", "report_count": 2319, "date": "2012-10-02" } } } } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('CrashesPerAdu',)) response = self.client.get(url, { 'product': 'WaterWolf', 'versions': ['10.0', '11.1'], 'from_date': '2012-01-xx', # invalid format }) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['from_date']) response = self.client.get(url, { 'product': 'WaterWolf', 'versions': ['10.0', '11.1'], 'from_date': '2012-02-32', # invalid numbers }) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['from_date']) response = self.client.get(url, { 'product': 'WaterWolf', 'versions': ['10.0', '11.1'], 'from_date': '2012-1-1', }) eq_(response.status_code, 200) @mock.patch('requests.get') def test_CurrentVersions(self, rget): url = reverse('api:model_wrapper', args=('CurrentVersions',)) response = self.client.get(url) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(isinstance(dump, list)) first = dump[0] ok_('product' in first) @mock.patch('requests.get') def test_CurrentProducts(self, rget): url = reverse('api:model_wrapper', args=('CurrentProducts',)) response = self.client.get(url) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['products']) ok_(dump['total']) @mock.patch('requests.get') def test_ProductsVersions(self, rget): url = reverse('api:model_wrapper', args=('ProductsVersions',)) response = self.client.get(url) eq_(response.status_code, 200) dump = json.loads(response.content) ok_('WaterWolf' in dump) ok_('NightTrain' in dump) versions = dump['WaterWolf'] version = versions[0] ok_('product' in version) ok_('version' in version) ok_('throttle' in version) ok_('start_date' in version) ok_('end_date' in version) ok_('featured' in version) ok_('release' in version) def test_Platforms(self): # note: this gets mocked out in the setUp url = reverse('api:model_wrapper', args=('Platforms',)) response = self.client.get(url) eq_(response.status_code, 200) dump = json.loads(response.content) # see the setUp for this fixture eq_(dump[0], {'code': 'win', 'name': 'Windows'}) @mock.patch('requests.get') def test_TCBS(self, rget): def mocked_get(url, params, **options): if 'crashes/signatures' in url: # because it defaults to insert a `limit` we should see # that somewhere in the URL ok_('limit' in params) ok_('os' not in params) return Response(u""" {"crashes": [ { "count": 188, "mac_count": 66, "content_count": 0, "first_report": "2012-06-21", "startup_percent": 0.0, "currentRank": 0, "previousRank": 1, "first_report_exact": "2012-06-21T21:28:08", "versions": "2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1", "percentOfTotal": 0.24258064516128999, "win_count": 56, "changeInPercentOfTotal": 0.011139597126354983, "linux_count": 66, "hang_count": 0, "signature": "FakeSignature1 \u7684 Japanese", "versions_count": 8, "changeInRank": 1, "plugin_count": 0, "previousPercentOfTotal": 0.23144104803493501, "is_gc_count": 10 } ], "totalPercentage": 0, "start_date": "2012-05-10", "end_date": "2012-05-24", "totalNumberOfCrashes": 0} """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('TCBS',)) response = self.client.get(url, { 'product': 'WaterWolf', 'version': '19.0a2', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['crashes']) crash = dump['crashes'][0] eq_(crash['is_gc_count'], 10) @mock.patch('requests.get') def test_TCBS_with_optional_parameters(self, rget): def mocked_get(url, params, **options): if 'crashes/signatures' in url: ok_('limit' in params) eq_(100, params['limit']) ok_('os' in params) eq_('OSX', params['os']) ok_('end_date' in params) eq_('2013-01-01', params['end_date']) return Response(u""" {"crashes": [ { "count": 188, "mac_count": 66, "content_count": 0, "first_report": "2012-06-21", "startup_percent": 0.0, "currentRank": 0, "previousRank": 1, "first_report_exact": "2012-06-21T21:28:08", "versions": "2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1", "percentOfTotal": 0.24258064516128999, "win_count": 56, "changeInPercentOfTotal": 0.011139597126354983, "linux_count": 66, "hang_count": 0, "signature": "FakeSignature1 \u7684 Japanese", "versions_count": 8, "changeInRank": 1, "plugin_count": 0, "previousPercentOfTotal": 0.23144104803493501, "is_gc_count": 10 } ], "totalPercentage": 0, "start_date": "2012-05-10", "end_date": "2012-05-24", "totalNumberOfCrashes": 0} """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('TCBS',)) data = { 'product': 'WaterWolf', 'version': '19.0a2', 'limit': 'xxx', 'duration': 'yyy', 'end_date': 'zzz', 'os': 'OSX', } response = self.client.get(url, data) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['limit']) ok_(dump['errors']['duration']) ok_(dump['errors']['end_date']) data['limit'] = '100' data['duration'] = '1' data['end_date'] = '2013-1-1' response = self.client.get(url, data) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['crashes']) @mock.patch('requests.get') def test_ReportList(self, rget): url = reverse('api:model_wrapper', args=('ReportList',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['signature']) def mocked_get(url, params, **options): if 'report/list/' in url: ok_('signature' in params) eq_('one & two', params['signature']) return Response(""" { "hits": [ { "user_comments": null, "address": "0xdeadbeef", "url": "http://p0rn.com" }, { "user_comments": null, "address": "0xdeadbeef", "url": "" } ], "total": 2 } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, { 'signature': 'one & two', }) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['start_date']) ok_(dump['errors']['end_date']) now = datetime.datetime.utcnow() yesterday = now - datetime.timedelta(days=1) fmt = lambda x: x.strftime('%Y-%m-%d %H:%M:%S') params = { 'signature': 'one & two', 'start_date': fmt(yesterday), 'end_date': fmt(now), } response = self.client.get(url, params) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['total']) # the 'url' key is filtered out hit = dump['hits'][0] ok_('user_comments' in hit) ok_('address' in hit) ok_('url' not in hit) # but sign in and it'll be different... user = self._login() response = self.client.get(url, params) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['total']) # the 'url' key is filtered out hit = dump['hits'][0] ok_('user_comments' in hit) ok_('address' in hit) ok_('url' not in hit) # ...but not until you have the PII permission self._add_permission(user, 'view_pii') response = self.client.get(url, params) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['total']) # the 'url' key is filtered out hit = dump['hits'][0] ok_('user_comments' in hit) ok_('address' in hit) ok_('url' in hit) # no longer filtered out @mock.patch('requests.get') def test_ReportList_with_auth_token(self, rget): url = reverse('api:model_wrapper', args=('ReportList',)) def mocked_get(url, params, **options): if 'report/list' in url: ok_('signature' in params) eq_('one & two', params['signature']) return Response(""" { "hits": [ { "user_comments": null, "address": "0xdeadbeef", "url": "http://p0rn.com" }, { "user_comments": null, "address": "0xdeadbeef", "url": "" } ], "total": 2 } """) raise NotImplementedError(url) rget.side_effect = mocked_get # make a user that has the "view_pii" permission user = User.objects.create(username='test') self._add_permission(user, 'view_pii') self._add_permission(user, 'view_exploitability') view_exploitability_perm = Permission.objects.get( codename='view_exploitability' ) # but make a token that only has the 'view_exploitability' # permission associated with it token = Token.objects.create( user=user, notes="Only exploitability token" ) token.permissions.add(view_exploitability_perm) now = datetime.datetime.utcnow() yesterday = now - datetime.timedelta(days=1) fmt = lambda x: x.strftime('%Y-%m-%d %H:%M:%S') params = { 'signature': 'one & two', 'start_date': fmt(yesterday), 'end_date': fmt(now), } response = self.client.get(url, params, HTTP_AUTH_TOKEN=token.key) eq_(response.status_code, 200) dump = json.loads(response.content) eq_(dump['total'], 2) hit = dump['hits'][0] ok_('user_comments' in hit) ok_('address' in hit) # the token provided, is NOT associated with the PII permission ok_('url' not in hit) # make a different token and attach the PII permission to it token = Token.objects.create( user=user, notes="Only PII token" ) view_pii_perm = Permission.objects.get( codename='view_pii' ) token.permissions.add(view_pii_perm) response = self.client.get(url, params, HTTP_AUTH_TOKEN=token.key) eq_(response.status_code, 200) dump = json.loads(response.content) eq_(dump['total'], 2) hit = dump['hits'][0] ok_('user_comments' in hit) ok_('address' in hit) ok_('url' in hit) @mock.patch('requests.get') def test_ReportList_with_optional_parameters(self, rget): url = reverse('api:model_wrapper', args=('ReportList',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['signature']) def mocked_get(url, params, **options): if 'report/list/' in url: ok_('products' in params) eq_(['WaterWolf', 'NightTrain'], params['products']) ok_('versions' in params) eq_(['11', '12'], params['versions']) ok_('build_ids' in params) eq_('XYZ', params['build_ids']) ok_('signature' in params) eq_('one & two', params['signature']) ok_('os' in params) eq_(['OSX', 'WINDOWS'], params['os']) ok_('from' in params) eq_('2012-01-01T00:00:00+00:00', params['from']) ok_('to' in params) eq_('2013-01-01T00:00:00+00:00', params['to']) return Response(""" { "hits": [ { "user_comments": null, "address": "0xdeadbeef" }, { "user_comments": null, "address": "0xdeadbeef" } ], "total": 2 } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, { 'signature': 'one & two', 'products': ['WaterWolf', 'NightTrain'], 'versions': ['11', '12'], 'os': ['OSX', 'WINDOWS'], 'range_value': '100', 'start_date': '2012-1-1', 'end_date': '2013-1-1', 'build_ids': 'XYZ', 'reasons': 'Anger', 'release_channels': 'noideawhatthisdoes', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['total']) @mock.patch('requests.get') def test_ProcessedCrash(self, rget): url = reverse('api:model_wrapper', args=('ProcessedCrash',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['crash_id']) def mocked_get(url, params, **options): assert '/crash_data' in url, url if 'datatype' in params and params['datatype'] == 'processed': return Response(""" { "client_crash_date": "2012-06-11T06:08:45", "dump": "%s", "signature": "FakeSignature1", "user_comments": null, "uptime": 14693, "release_channel": "nightly", "uuid": "11cb72f5-eb28-41e1-a8e4-849982120611", "flash_version": "[blank]", "hangid": null, "distributor_version": null, "truncated": true, "process_type": null, "id": 383569625, "os_version": "10.6.8 10K549", "version": "5.0a1", "build": "20120609030536", "ReleaseChannel": "nightly", "addons_checked": null, "product": "WaterWolf", "os_name": "Mac OS X", "last_crash": 371342, "date_processed": "2012-06-11T06:08:44", "cpu_name": "amd64", "reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS", "address": "0x8", "completeddatetime": "2012-06-11T06:08:57", "success": true, "upload_file_minidump_browser": "a crash", "upload_file_minidump_flash1": "a crash", "upload_file_minidump_flash2": "a crash", "upload_file_minidump_plugin": "a crash" } """ % dump) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, { 'crash_id': '123', }) eq_(response.status_code, 200, response.content) dump = json.loads(response.content) eq_(dump['uuid'], u'11cb72f5-eb28-41e1-a8e4-849982120611') ok_('upload_file_minidump_flash2' in dump) ok_('url' not in dump) @mock.patch('requests.get') def test_UnredactedCrash(self, rget): url = reverse('api:model_wrapper', args=('UnredactedCrash',)) response = self.client.get(url) # because we don't have the sufficient permissions yet to use it eq_(response.status_code, 403) user = User.objects.create(username='test') self._add_permission(user, 'view_pii') self._add_permission(user, 'view_exploitability') view_pii_perm = Permission.objects.get( codename='view_pii' ) token = Token.objects.create( user=user, notes="Only PII token" ) view_exploitability_perm = Permission.objects.get( codename='view_exploitability' ) token.permissions.add(view_pii_perm) token.permissions.add(view_exploitability_perm) response = self.client.get(url, HTTP_AUTH_TOKEN=token.key) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['crash_id']) def mocked_get(url, params, **options): assert '/crash_data/' in url if 'datatype' in params and params['datatype'] == 'unredacted': return Response(""" { "client_crash_date": "2012-06-11T06:08:45", "dump": "%s", "signature": "FakeSignature1", "user_comments": null, "uptime": 14693, "release_channel": "nightly", "uuid": "11cb72f5-eb28-41e1-a8e4-849982120611", "flash_version": "[blank]", "hangid": null, "distributor_version": null, "truncated": true, "process_type": null, "id": 383569625, "os_version": "10.6.8 10K549", "version": "5.0a1", "build": "20120609030536", "ReleaseChannel": "nightly", "addons_checked": null, "product": "WaterWolf", "os_name": "Mac OS X", "last_crash": 371342, "date_processed": "2012-06-11T06:08:44", "cpu_name": "amd64", "reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS", "address": "0x8", "completeddatetime": "2012-06-11T06:08:57", "success": true, "upload_file_minidump_browser": "a crash", "upload_file_minidump_flash1": "a crash", "upload_file_minidump_flash2": "a crash", "upload_file_minidump_plugin": "a crash", "exploitability": "Unknown Exploitability" } """ % dump) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, { 'crash_id': '123', }) eq_(response.status_code, 200) dump = json.loads(response.content) eq_(dump['uuid'], u'11cb72f5-eb28-41e1-a8e4-849982120611') ok_('upload_file_minidump_flash2' in dump) ok_('exploitability' in dump) @mock.patch('requests.get') def test_RawCrash(self, rget): def mocked_get(url, params, **options): assert '/crash_data' in url if 'uuid' in params and params['uuid'] == 'abc123': return Response(""" { "InstallTime": "1366691881", "AdapterVendorID": "0x8086", "Theme": "classic/1.0", "Version": "23.0a1", "id": "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}", "Vendor": "Mozilla", "EMCheckCompatibility": "true", "Throttleable": "0", "URL": "http://system.gaiamobile.org:8080/", "version": "23.0a1", "AdapterDeviceID": "0x 46", "ReleaseChannel": "nightly", "submitted_timestamp": "2013-04-29T16:42:28.961187+00:00", "buildid": "20130422105838", "timestamp": 1367253748.9612169, "Notes": "AdapterVendorID: 0x8086, AdapterDeviceID: ...", "CrashTime": "1366703112", "FramePoisonBase": "7ffffffff0dea000", "FramePoisonSize": "4096", "StartupTime": "1366702830", "Add-ons": "activities%40gaiamobile.org:0.1,alarms%40gaiam...", "BuildID": "20130422105838", "SecondsSinceLastCrash": "23484", "ProductName": "WaterWolf", "legacy_processing": 0, "ProductID": "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}", "AsyncShutdownTimeout": 12345, "BIOS_Manufacturer": "abc123", "Comments": "I visited http://p0rn.com and mail@email.com", "upload_file_minidump_browser": "a crash", "upload_file_minidump_flash1": "a crash", "upload_file_minidump_flash2": "a crash", "upload_file_minidump_plugin": "a crash" } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('RawCrash',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['crash_id']) response = self.client.get(url, { 'crash_id': 'abc123' }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_('id' in dump) ok_('URL' not in dump) # right? ok_('AsyncShutdownTimeout' in dump) ok_('BIOS_Manufacturer' in dump) ok_('upload_file_minidump_browser' in dump) ok_('upload_file_minidump_flash1' in dump) ok_('upload_file_minidump_flash2' in dump) ok_('upload_file_minidump_plugin' in dump) # `Comments` is scrubbed ok_('I visited' in dump['Comments']) ok_('http://p0rn.com' not in dump['Comments']) ok_('mail@email.com' not in dump['Comments']) @mock.patch('requests.get') def test_RawCrash_binary_blob(self, rget): def mocked_get(url, params, **options): assert '/crash_data' in url if 'uuid' in params and params['uuid'] == 'abc': return Response('\xe0') raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('RawCrash',)) response = self.client.get(url, { 'crash_id': 'abc', 'format': 'raw' }) # because we don't have permission eq_(response.status_code, 403) url = reverse('api:model_wrapper', args=('RawCrash',)) response = self.client.get(url, { 'crash_id': 'abc', 'format': 'wrong' # note }) # invalid format eq_(response.status_code, 400) user = self._login() self._add_permission(user, 'view_pii') response = self.client.get(url, { 'crash_id': 'abc', 'format': 'raw' }) # still don't have the right permission eq_(response.status_code, 403) self._add_permission(user, 'view_rawdump') response = self.client.get(url, { 'crash_id': 'abc', 'format': 'raw' }) # finally! eq_(response.status_code, 200) eq_(response['Content-Disposition'], 'attachment; filename="abc.dmp"') eq_(response['Content-Type'], 'application/octet-stream') @mock.patch('requests.get') def test_CommentsBySignature(self, rget): url = reverse('api:model_wrapper', args=('CommentsBySignature',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['signature']) def mocked_get(url, params, **options): sample_user_comment = ( "This comment contains an " "email@address.com and it also contains " "https://url.com/path?thing=bob" ) hits = { "hits": [{ "user_comments": sample_user_comment, "date_processed": "2012-08-21T11:17:28-07:00", "email": "some@emailaddress.com", "uuid": "469bde48-0e8f-3586-d486-b98810120830" }], "total": 1 } if 'crashes/comments' in url: return Response(hits) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, { 'signature': 'one & two', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['total']) hit = dump['hits'][0] ok_('date_processed' in hit) ok_('uuid' in hit) ok_('user_comments' in hit) ok_('email@address.com' not in hit['user_comments']) ok_('https://url.com/path?thing=bob' not in hit['user_comments']) ok_('email' not in hit) user = self._login() self._add_permission(user, 'view_pii') response = self.client.get(url, { 'signature': 'one & two', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['total']) hit = dump['hits'][0] ok_('date_processed' in hit) ok_('uuid' in hit) ok_('user_comments' in hit) # following is the difference of being signed in and having permissions ok_('email@address.com' in hit['user_comments']) ok_('https://url.com/path?thing=bob' in hit['user_comments']) eq_(hit['email'], 'some@emailaddress.com') @mock.patch('requests.get') def test_CrashPairsByCrashId(self, rget): url = reverse('api:model_wrapper', args=('CrashPairsByCrashId',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['uuid']) ok_(dump['errors']['hang_id']) def mocked_get(url, params, **options): return Response(""" { "hits": [{"guess": "work"}], "total": 1 } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, { 'uuid': '123', 'hang_id': '987' }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['total']) @mock.patch('requests.get') def test_Search(self, rget): def mocked_get(url, params, **options): assert 'search/signatures' in url if 'products' in params and 'WaterWolf' in params['products']: ok_('for' in params) eq_('ABC123', params['for']) ok_('products' in params) eq_(['WaterWolf', 'NightTrain'], params['products']) ok_('versions' in params) eq_(['19.0', '18.0'], params['versions']) ok_('os' in params) eq_(['OSX', 'Win95'], params['os']) return Response("""{ "hits": [ { "count": 586, "signature": "nsASDOMWindowEnumerator::GetNext()", "numcontent": 0, "is_windows": 586, "is_linux": 0, "numplugin": 56, "is_mac": 0, "numhang": 0 }, { "count": 13, "signature": "mySignatureIsCool", "numcontent": 0, "is_windows": 10, "is_linux": 2, "numplugin": 0, "is_mac": 1, "numhang": 0 }, { "count": 2, "signature": "mineIsCoolerThanYours", "numcontent": 0, "is_windows": 0, "is_linux": 0, "numplugin": 0, "is_mac": 2, "numhang": 2 }, { "count": 2, "signature": null, "numcontent": 0, "is_windows": 0, "is_linux": 0, "numplugin": 0, "is_mac": 2, "numhang": 2 } ], "total": 4 } """) else: return Response(""" {"hits": [ { "count": 586, "signature": "nsASDOMWindowEnumerator::GetNext()", "numcontent": 0, "is_windows": 586, "is_linux": 0, "numplugin": 0, "is_mac": 0, "numhang": 0 }], "total": 1 } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('Search',)) response = self.client.get(url, { 'terms': 'ABC123', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) eq_(dump['total'], 1) response = self.client.get(url, { 'terms': 'ABC123', 'products': ['WaterWolf', 'NightTrain'], 'versions': ['19.0', '18.0'], 'os': ['OSX', 'Win95'], 'start_date': '2012-1-1 23:00:00', 'end_date': '2013-1-1 23:00:00', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) eq_(dump['total'], 4) @mock.patch('requests.post') def test_Bugs(self, rpost): url = reverse('api:model_wrapper', args=('Bugs',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['signatures']) def mocked_post(**options): assert '/bugs/' in options['url'], options['url'] return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) rpost.side_effect = mocked_post response = self.client.get(url, { 'signatures': 'one & two', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) @mock.patch('requests.post') def test_SignaturesForBugs(self, rpost): url = reverse('api:model_wrapper', args=('SignaturesByBugs',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['bug_ids']) def mocked_post(**options): assert '/bugs/' in options['url'], options['url'] return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) rpost.side_effect = mocked_post response = self.client.get(url, { 'bug_ids': '123456789', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) @mock.patch('requests.get') def test_SignatureTrend(self, rget): def mocked_get(url, params, **options): if 'crashes/signature_history' in url: ok_('product' in params) eq_('WaterWolf', params['product']) ok_('version' in params) eq_('19.0', params['version']) ok_('end_date' in params) eq_('2013-01-01', params['end_date']) ok_('start_date' in params) eq_('2012-01-01', params['start_date']) ok_('signature' in params) eq_('one & two', params['signature']) return Response(""" { "hits": [ { "count": 1, "date": "2012-06-06", "percent_of_total": 100 } ], "total": 1 } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('SignatureTrend',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['product']) ok_(dump['errors']['version']) ok_(dump['errors']['signature']) ok_(dump['errors']['end_date']) ok_(dump['errors']['start_date']) response = self.client.get(url, { 'product': 'WaterWolf', 'version': '19.0', 'signature': 'one & two', 'end_date': '2013-1-1', 'start_date': '2012-1-1', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['total']) @mock.patch('requests.get') def test_SignatureSummary(self, rget): def mocked_get(url, params, **options): if 'signaturesummary' in url: ok_('report_types' in params) ok_('uptime' in params['report_types']) ok_('signature' in params) eq_('one & two', params['signature']) ok_('start_date' in params) eq_('2012-01-01', params['start_date']) ok_('end_date' in params) eq_('2013-01-01', params['end_date']) return Response({ "reports": { "uptime": [ { "version_string": "12.0", "percentage": "48.440", "report_count": 52311, "product_name": "WaterWolf", "category": "XXX" }, { "version_string": "13.0b4", "percentage": "9.244", "report_count": 9983, "product_name": "WaterWolf", "category": "YYY" } ] } }) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('SignatureSummary',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['start_date']) ok_(dump['errors']['end_date']) ok_(dump['errors']['report_types']) ok_(dump['errors']['signature']) response = self.client.get(url, { 'report_types': ['uptime'], 'signature': 'one & two', 'start_date': '2012-1-1', 'end_date': '2013-1-1', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['reports']) eq_(len(dump['reports']['uptime']), 2) @mock.patch('requests.get') def test_Status(self, rget): def mocked_get(url, params, **options): if '/server_status' in url: return Response(""" { "breakpad_revision": "1139", "hits": [ { "date_oldest_job_queued": null, "date_recently_completed": null, "processors_count": 1, "avg_wait_sec": 0.0, "waiting_job_count": 0, "date_created": "2013-04-01T21:40:01+00:00", "id": 463859, "avg_process_sec": 0.0 } ], "total": 12, "socorro_revision": "9cfa4de" } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('Status',)) response = self.client.get(url) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['socorro_revision']) @mock.patch('requests.get') def test_CrontabberState(self, rget): def mocked_get(url, params, **options): if '/crontabber_state' in url: return Response(""" { "state": { "automatic-emails": { "next_run": "2013-04-01T22:20:01+00:00", "first_run": "2013-03-15T16:25:01+00:00", "depends_on": [], "last_run": "2013-04-01T21:20:01+00:00", "last_success": "2013-04-01T20:25:01+00:00", "error_count": 0, "last_error": {} }, "ftpscraper": { "next_run": "2013-04-01T22:20:09+00:00", "first_run": "2013-03-07T07:05:51+00:00", "depends_on": [], "last_run": "2013-04-01T21:20:09+00:00", "last_success": "2013-04-01T21:05:51+00:00", "error_count": 0, "last_error": {} } } } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('CrontabberState',)) response = self.client.get(url) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['state']) @mock.patch('requests.get') def test_DailyBuilds(self, rget): def mocked_get(url, params, **options): if '/products/builds' in url: return Response(""" [ { "product": "WaterWolf", "repository": "dev", "buildid": 20120625000001, "beta_number": null, "platform": "Mac OS X", "version": "19.0", "date": "2012-06-25", "build_type": "Nightly" }, { "product": "WaterWolf", "repository": "dev", "buildid": 20120625000003, "beta_number": null, "platform": "BeOS", "version": "5.0a1", "date": "2012-06-25", "build_type": "Beta" } ] """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('DailyBuilds',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['product']) response = self.client.get(url, { 'product': 'WaterWolf', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump) ok_(dump[0]['buildid']) @mock.patch('requests.get') def test_CrashTrends(self, rget): def mocked_get(url, params, **options): if '/crashtrends' in url: ok_('product' in params) eq_('WaterWolf', params['product']) ok_('version' in params) eq_('5.0', params['version']) ok_('start_date' in params) eq_('2012-01-01', params['start_date']) ok_('end_date' in params) eq_('2013-01-01', params['end_date']) return Response(""" { "crashtrends": [ { "sort": "1", "default_version": "5.0a1", "release_name": "waterwolf", "rapid_release_version": "5.0", "product_name": "WaterWolf" }], "total": "1" } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('CrashTrends',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['product']) ok_(dump['errors']['version']) ok_(dump['errors']['start_date']) ok_(dump['errors']['end_date']) response = self.client.get(url, { 'product': 'WaterWolf', 'version': '5.0', 'start_date': '2012-1-1', 'end_date': '2013-1-1', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['crashtrends']) ok_(dump['total']) @mock.patch('requests.get') def test_SignatureURLs(self, rget): def mocked_get(url, params, **options): if '/signatureurls' in url: ok_('products' in params) eq_(['WaterWolf', 'NightTrain'], params['products']) ok_('start_date' in params) eq_('2012-01-01T10:00:00+00:00', params['start_date']) ok_('end_date' in params) eq_('2013-01-01T10:00:00+00:00', params['end_date']) return Response("""{ "hits": [ {"url": "http://farm.ville", "crash_count":123}, {"url": "http://other.crap", "crash_count": 1} ], "total": 2 } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('SignatureURLs',)) response = self.client.get(url) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['products']) ok_(dump['errors']['signature']) ok_(dump['errors']['start_date']) ok_(dump['errors']['end_date']) response = self.client.get(url, { 'products': ['WaterWolf', 'NightTrain'], 'versions': ['WaterWolf:14.0', 'NightTrain:15.0'], 'start_date': '2012-1-1 10:00:0', 'end_date': '2013-1-1 10:00:0', 'signature': 'one & two', }) eq_(response.status_code, 200) dump = json.loads(response.content) ok_(dump['hits']) ok_(dump['total']) @mock.patch('requests.get') def test_carry_mware_error_codes(self, rget): # used so we can count, outside the mocked function, # how many times the `requests.get` is called attempts = [] def mocked_get(url, params, **options): attempts.append(url) # The middleware will return JSON encoded errors. # These will be carried through to the end user here def wrap_error(msg): return json.dumps({'error': {'message': msg}}) if len(attempts) == 1: return Response( wrap_error('Not found Stuff'), status_code=400 ) if len(attempts) == 2: return Response( wrap_error('Forbidden Stuff'), status_code=403 ) if len(attempts) == 3: return Response( wrap_error('Bad Stuff'), status_code=500 ) if len(attempts) == 4: return Response( wrap_error('Someone elses Bad Stuff'), status_code=502 ) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('CrontabberState',)) response = self.client.get(url) eq_(response.status_code, 400) eq_(response['content-type'], 'application/json; charset=UTF-8') error = json.loads(response.content)['error'] eq_(error['message'], 'Not found Stuff') # second attempt response = self.client.get(url) eq_(response.status_code, 403) eq_(response['content-type'], 'application/json; charset=UTF-8') error = json.loads(response.content)['error'] eq_(error['message'], 'Forbidden Stuff') # third attempt response = self.client.get(url) eq_(response.status_code, 424) eq_(response['content-type'], 'text/plain') # forth attempt response = self.client.get(url) eq_(response.status_code, 424) eq_(response['content-type'], 'text/plain') @mock.patch('requests.get') def test_Correlations(self, rget): def mocked_get(url, params, **options): assert '/correlations' in url ok_('report_type' in params) eq_('core-counts', params['report_type']) return Response(""" { "reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS", "count": 13, "load": "36% (4/11) vs. 26% (47/180) amd64 with 2 cores" } """) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('Correlations',)) response = self.client.get(url) dump = json.loads(response.content) ok_(dump['errors']['product']) ok_(dump['errors']['platform']) ok_(dump['errors']['version']) ok_(dump['errors']['report_type']) ok_(dump['errors']['signature']) response = self.client.get(url, { 'platform': 'Windows NT', 'product': 'WaterWolf', 'version': '1.0', 'report_type': 'core-counts', 'signature': 'one & two', }) eq_(response.status_code, 200) dump = json.loads(response.content) eq_(dump['count'], 13) eq_(dump['reason'], 'EXC_BAD_ACCESS / KERN_INVALID_ADDRESS') ok_(dump['load']) @mock.patch('requests.get') def test_CorrelationsSignatures(self, rget): def mocked_get(url, params, **options): assert '/correlations/signatures' in url return Response(""" { "hits": ["FakeSignature1", "FakeSignature2"], "total": 2 } """) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('CorrelationsSignatures',)) response = self.client.get(url) dump = json.loads(response.content) ok_(dump['errors']['product']) ok_(dump['errors']['version']) ok_(dump['errors']['report_type']) response = self.client.get(url, { 'platforms': 'Windows NT+Mac OS OX', 'product': 'WaterWolf', 'version': '1.0', 'report_type': 'core-counts', }) eq_(response.status_code, 200) dump = json.loads(response.content) eq_(dump['hits'], [u'FakeSignature1', u'FakeSignature2']) eq_(dump['total'], 2) def test_Field(self): url = reverse('api:model_wrapper', args=('Field',)) response = self.client.get(url) eq_(response.status_code, 404) @mock.patch('requests.get') def test_Correlations_returning_nothing(self, rget): def mocked_get(url, params, **options): assert '/correlations' in url ok_('report_type' in params) eq_('core-counts', params['report_type']) # 'null' is a perfectly valid JSON response return Response('null') rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('Correlations',)) response = self.client.get(url, { 'platform': 'Windows NT', 'product': 'WaterWolf', 'version': '1.0', 'report_type': 'core-counts', 'signature': 'one & two', }) eq_(response.status_code, 200) dump = json.loads(response.content) eq_(dump, None) @mock.patch('requests.get') def test_CrashesByExploitability(self, rget): sample_response = [ { "signature": "FakeSignature", "report_date": "2013-06-06", "null_count": 0, "none_count": 1, "low_count": 2, "medium_count": 3, "high_count": 4 } ] def mocked_get(url, params, **options): assert '/crashes/exploitability' in url return Response(sample_response) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('CrashesByExploitability',)) response = self.client.get(url, { 'page': 1, 'batch': 10 }) eq_(response.status_code, 403) user = self._login() response = self.client.get(url, { 'page': 1, 'batch': 10 }) eq_(response.status_code, 403) self._add_permission(user, 'view_exploitability') response = self.client.get(url, { 'page': 1, 'batch': 10 }) eq_(response.status_code, 200) dump = json.loads(response.content) eq_(dump, sample_response) # now that we have the permission, let's see about causing a 400 error response = self.client.get(url, {}) eq_(response.status_code, 400) dump = json.loads(response.content) ok_(dump['errors']['batch']) @mock.patch('requests.get') def test_CrashesByExploitability_with_auth_token(self, rget): sample_response = [ { "signature": "FakeSignature", "report_date": "2013-06-06", "null_count": 0, "none_count": 1, "low_count": 2, "medium_count": 3, "high_count": 4 } ] def mocked_get(url, params, **options): assert '/crashes/exploitability' in url return Response(sample_response) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('CrashesByExploitability',)) params = { 'page': 1, 'batch': 10 } response = self.client.get(url, params, HTTP_AUTH_TOKEN='somecrap') eq_(response.status_code, 403) user = User.objects.create(username='test') self._add_permission(user, 'view_pii') self._add_permission(user, 'view_exploitability') view_pii_perm = Permission.objects.get( codename='view_pii' ) # but make a token that only has the 'view_pii' # permission associated with it token = Token.objects.create( user=user, notes="Only PII token" ) token.permissions.add(view_pii_perm) response = self.client.get(url, params, HTTP_AUTH_TOKEN=token.key) eq_(response.status_code, 403) # now make a token for the exploitability permission view_exploitability_perm = Permission.objects.get( codename='view_exploitability' ) token = Token.objects.create( user=user, notes="Only exploitability token" ) token.permissions.add(view_exploitability_perm) response = self.client.get(url, params, HTTP_AUTH_TOKEN=token.key) eq_(response.status_code, 200) @mock.patch('requests.get') def test_hit_or_not_hit_ratelimit(self, rget): def mocked_get(url, params, **options): if '/crontabber_state' in url: return Response(""" { "state": { "automatic-emails": { "next_run": "2013-04-01T22:20:01+00:00", "first_run": "2013-03-15T16:25:01+00:00", "depends_on": [], "last_run": "2013-04-01T21:20:01+00:00", "last_success": "2013-04-01T20:25:01+00:00", "error_count": 0, "last_error": {} }, "ftpscraper": { "next_run": "2013-04-01T22:20:09+00:00", "first_run": "2013-03-07T07:05:51+00:00", "depends_on": [], "last_run": "2013-04-01T21:20:09+00:00", "last_success": "2013-04-01T21:05:51+00:00", "error_count": 0, "last_error": {} } } } """) raise NotImplementedError(url) rget.side_effect = mocked_get # doesn't matter much which model we use url = reverse('api:model_wrapper', args=('CrontabberState',)) response = self.client.get(url) eq_(response.status_code, 200) # the rate limit is currently 10/min so it's easy to hit the limit for __ in range(10): response = self.client.get(url) eq_(response.status_code, 429) # but it'll work if you use a different X-Forwarded-For IP response = self.client.get(url, HTTP_X_FORWARDED_FOR='11.11.11.11') eq_(response.status_code, 200) user = User.objects.create(username='test') token = Token.objects.create( user=user, notes="Just for avoiding rate limit" ) response = self.client.get(url, HTTP_AUTH_TOKEN=token.key) eq_(response.status_code, 200) for __ in range(10): response = self.client.get(url) eq_(response.status_code, 200) @mock.patch('requests.get') def test_SuperSearch(self, rget): def mocked_get(url, params, **options): if '/supersearch/fields' in url: return Response(SUPERSEARCH_FIELDS_MOCKED_RESULTS) if '/supersearch' in url: ok_('exploitability' not in params) if 'product' in params: eq_(params['product'], ['WaterWolf', 'NightTrain']) return Response({ 'hits': [ { 'signature': 'abcdef', 'product': 'WaterWolf', 'version': '1.0', 'email': 'thebig@lebowski.net', 'exploitability': 'high', 'url': 'http://embarassing.website.com', 'user_comments': 'hey I am thebig@lebowski.net', } ], 'facets': { 'signature': [] }, 'total': 0 }) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('SuperSearch',)) response = self.client.get(url) eq_(response.status_code, 200) res = json.loads(response.content) ok_(res['hits']) ok_(res['facets']) # Verify forbidden fields are not exposed. ok_('email' not in res['hits']) ok_('exploitability' not in res['hits']) ok_('url' not in res['hits']) # Verify user comments are scrubbed. ok_('thebig@lebowski.net' not in res['hits'][0]['user_comments']) # Verify it's not possible to use restricted parameters. response = self.client.get(url, {'exploitability': 'high'}) eq_(response.status_code, 200) # Verify values can be lists. response = self.client.get(url, { 'product': ['WaterWolf', 'NightTrain'] }) eq_(response.status_code, 200) @mock.patch('requests.get') def test_SuperSearchUnredacted(self, rget): def mocked_get(url, params, **options): if '/supersearch/fields' in url: return Response(SUPERSEARCH_FIELDS_MOCKED_RESULTS) if '/supersearch' in url: ok_('exploitability' in params) if 'product' in params: eq_(params['product'], ['WaterWolf', 'NightTrain']) return Response({ 'hits': [ { 'signature': 'abcdef', 'product': 'WaterWolf', 'version': '1.0', 'email': 'thebig@lebowski.net', 'exploitability': 'high', 'url': 'http://embarassing.website.com', 'user_comments': 'hey I am thebig@lebowski.net', } ], 'facets': { 'signature': [] }, 'total': 0 }) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('api:model_wrapper', args=('SuperSearchUnredacted',)) response = self.client.get(url, {'exploitability': 'high'}) eq_(response.status_code, 403) # Log in to get permissions. user = self._login() self._add_permission(user, 'view_pii') self._add_permission(user, 'view_exploitability') response = self.client.get(url, {'exploitability': 'high'}) eq_(response.status_code, 200) res = json.loads(response.content) ok_(res['hits']) ok_(res['facets']) # Verify forbidden fields are exposed. ok_('email' in res['hits'][0]) ok_('exploitability' in res['hits'][0]) ok_('url' in res['hits'][0]) # Verify user comments are not scrubbed. ok_('thebig@lebowski.net' in res['hits'][0]['user_comments']) # Verify values can be lists. response = self.client.get(url, { 'exploitability': 'high', 'product': ['WaterWolf', 'NightTrain'] }) eq_(response.status_code, 200)
mpl-2.0
kovaloid/infoarchive-sip-sdk
core/src/test/java/com/opentext/ia/sdk/dto/WhenFetchingJobInstance.java
779
/* * Copyright (c) 2016-2017 by OpenText Corporation. All Rights Reserved. */ package com.opentext.ia.sdk.dto; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; public class WhenFetchingJobInstance { private static final String STATUS = "SCHEDULED"; private final JobInstance instance = new JobInstance(); @Test public void fetchDefaultStatus() { assertEquals("Job Instance Default Format", "SUCCESS", instance.getStatus()); } @Test public void fetchStatus() { instance.setStatus(STATUS); assertEquals("Reception Format", STATUS, instance.getStatus()); } @Test public void invokeJobInstances() { JobInstances defs = new JobInstances(); assertNotNull(defs); } }
mpl-2.0
CODEiverse/Open-Source-Tools
Microsoft/CommandLineTools/CLBCStaticDataToUpdateInsertSqlData/Properties/AssemblyInfo.cs
1578
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CLBCStaticDataToUpdateInsertSqlData")] [assembly: AssemblyDescription("Moves static data (from a spec doc set) into a sql data base created to match the structure")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CODEiverse.com")] [assembly: AssemblyProduct("CLBCStaticDataToUpdateInsertSqlData")] [assembly: AssemblyCopyright("Copyright © CODEiverse.com, EJ Alexandra 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e6d39f19-741e-4fa6-abab-07d29c95ae03")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("16.11.30")] [assembly: AssemblyFileVersion("16.11.30")]
mpl-2.0
akissa/baruwa-go
api/client.go
6199
// BaruwaAPI Golang bindings for Baruwa REST API // Copyright (C) 2019 Andrew Colin Kissa <andrew@topdog.za.net> // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at http://mozilla.org/MPL/2.0/. package api import ( "bytes" "crypto/tls" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "strings" ) // Client represents the Baruwa API client type Client struct { BaseURL *url.URL UserAgent string client *http.Client token string } // Options represents optional settings and flags that can be passed to New type Options struct { // HTTP client for communication with the Baruwa API HTTPClient *http.Client // User agent for HTTP client UserAgent string } // TokenResponse is for API response for the /oauth2/token endpoint type TokenResponse struct { RefreshToken string `json:"refresh_token"` Token string `json:"access_token"` Type string `json:"token_type"` Scope string `json:"score"` ExpiresIn expirationTime `json:"expires_in"` } // ErrorResponse https://www.baruwa.com/docs/api/#errors type ErrorResponse struct { Response *http.Response `json:"-"` Message string `json:"error,omitempty"` Code int `json:"code,omitempty"` } // Error method implementation for ErrorResponse struct func (r *ErrorResponse) Error() string { return fmt.Sprintf("%v %v: %d %s", r.Response.Request.Method, r.Response.Request.URL, r.Code, r.Message) } func (c *Client) newRequest(method, path string, opts *ListOptions, body io.Reader) (req *http.Request, err error) { var k, p string var q url.Values var u, nu, rel *url.URL if rel, err = url.ParseRequestURI(path); err != nil { return } u = c.BaseURL.ResolveReference(rel) if method == http.MethodGet && opts != nil && opts.Page != "" { if nu, err = url.Parse(opts.Page); err == nil { if strings.HasPrefix(nu.String(), u.String()) { q = nu.Query() if len(q) >= 1 { for k = range q { if k != "page" { q.Del(k) } } if p = q.Get("page"); p != "" { u.RawQuery = q.Encode() } } } } } if req, err = http.NewRequest(method, u.String(), body); err != nil { return } req.Header.Set("Accept", "application/json") req.Header.Set("User-Agent", c.UserAgent) if req.Method == http.MethodPost || req.Method == http.MethodPut { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } return } func (c *Client) get(path string, opts *ListOptions, data interface{}) (err error) { var req *http.Request if req, err = c.newRequest(http.MethodGet, apiPath(path), opts, nil); err != nil { return } err = c.doWithOAuth(req, data) return } func (c *Client) post(p string, v url.Values, data interface{}) (err error) { var req *http.Request // fmt.Println(v.Encode()) if req, err = c.newRequest(http.MethodPost, apiPath(p), nil, strings.NewReader(v.Encode())); err != nil { return } err = c.doWithOAuth(req, data) return } func (c *Client) put(p string, v url.Values, data interface{}) (err error) { var req *http.Request // fmt.Println(v.Encode()) if req, err = c.newRequest(http.MethodPut, apiPath(p), nil, strings.NewReader(v.Encode())); err != nil { return } err = c.doWithOAuth(req, data) return } func (c *Client) delete(p string, v url.Values) (err error) { var req *http.Request if v == nil { if req, err = c.newRequest(http.MethodDelete, apiPath(p), nil, nil); err != nil { return } } else { if req, err = c.newRequest(http.MethodDelete, apiPath(p), nil, strings.NewReader(v.Encode())); err != nil { return } } err = c.doWithOAuth(req, nil) return } // GetAccessToken returns a token func (c *Client) GetAccessToken(clientID, secret string) (token *TokenResponse, err error) { var req *http.Request var buf *bytes.Buffer if clientID == "" { err = fmt.Errorf(clientIDError) return } if secret == "" { err = fmt.Errorf(clientSecretError) return } buf = bytes.NewBuffer([]byte("grant_type=password")) if req, err = c.newRequest(http.MethodPost, apiPath("oauth2/token"), nil, buf); err != nil { return } req.Header.Set("Content-type", "application/x-www-form-urlencoded") req.SetBasicAuth(clientID, secret) token = &TokenResponse{} err = c.do(req, token) return } func (c *Client) doWithOAuth(req *http.Request, data interface{}) (err error) { req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token)) err = c.do(req, data) return } func (c *Client) do(req *http.Request, v interface{}) (err error) { var data []byte var errResp *ErrorResponse var resp *http.Response if resp, err = c.client.Do(req); err != nil { return } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { errResp = &ErrorResponse{Response: resp} errResp.Code = resp.StatusCode errResp.Message = resp.Status data, err = ioutil.ReadAll(resp.Body) if err == nil && len(data) > 0 { json.Unmarshal(data, errResp) err = errResp } else { err = errResp } return } if v == nil { return } err = json.NewDecoder(resp.Body).Decode(v) return } func apiPath(p string) string { return fmt.Sprintf("/api/%s/%s", APIVersion, p) } // New creates a new Baruwa API client.Options are optional and can be nil. func New(endpoint, token string, options *Options) (c *Client, err error) { var ua string var baseurl *url.URL var client *http.Client var transport *http.Transport if endpoint == "" { err = fmt.Errorf(endpointError) return } ua = fmt.Sprintf("baruwa-go/%s", Version) transport = &http.Transport{ TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper), } client = http.DefaultClient client.Transport = transport if baseurl, err = url.Parse(endpoint); err != nil { return } if options != nil { if options.HTTPClient != nil { client = options.HTTPClient } if options.UserAgent != "" { ua = options.UserAgent } } c = &Client{ BaseURL: baseurl, UserAgent: ua, client: client, token: token, } return }
mpl-2.0
DiamondLovesYou/rust-ppapi
src/libhelper/builtin_defines.hpp
10946
#define _GNU_SOURCE 1 #define _ILP32 1 #define __ATOMIC_ACQUIRE 2 #define __ATOMIC_ACQ_REL 4 #define __ATOMIC_CONSUME 1 #define __ATOMIC_RELAXED 0 #define __ATOMIC_RELEASE 3 #define __ATOMIC_SEQ_CST 5 #define __BIGGEST_ALIGNMENT__ 8 #define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ #define __CHAR16_TYPE__ unsigned short #define __CHAR32_TYPE__ unsigned int #define __CHAR_BIT__ 8 #define __CONSTANT_CFSTRINGS__ 1 #define __DBL_DECIMAL_DIG__ 17 #define __DBL_DENORM_MIN__ 4.9406564584124654e-324 #define __DBL_DIG__ 15 #define __DBL_EPSILON__ 2.2204460492503131e-16 #define __DBL_HAS_DENORM__ 1 #define __DBL_HAS_INFINITY__ 1 #define __DBL_HAS_QUIET_NAN__ 1 #define __DBL_MANT_DIG__ 53 #define __DBL_MAX_10_EXP__ 308 #define __DBL_MAX_EXP__ 1024 #define __DBL_MAX__ 1.7976931348623157e+308 #define __DBL_MIN_10_EXP__ (-307) #define __DBL_MIN_EXP__ (-1021) #define __DBL_MIN__ 2.2250738585072014e-308 #define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__ #define __DEPRECATED 1 #define __ELF__ 1 #define __EXCEPTIONS 1 #define __FINITE_MATH_ONLY__ 0 #define __FLT_DECIMAL_DIG__ 9 #define __FLT_DENORM_MIN__ 1.40129846e-45F #define __FLT_DIG__ 6 #define __FLT_EPSILON__ 1.19209290e-7F #define __FLT_EVAL_METHOD__ 0 #define __FLT_HAS_DENORM__ 1 #define __FLT_HAS_INFINITY__ 1 #define __FLT_HAS_QUIET_NAN__ 1 #define __FLT_MANT_DIG__ 24 #define __FLT_MAX_10_EXP__ 38 #define __FLT_MAX_EXP__ 128 #define __FLT_MAX__ 3.40282347e+38F #define __FLT_MIN_10_EXP__ (-37) #define __FLT_MIN_EXP__ (-125) #define __FLT_MIN__ 1.17549435e-38F #define __FLT_RADIX__ 2 #define __GCC_ATOMIC_BOOL_LOCK_FREE 1 #define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 1 #define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 1 #define __GCC_ATOMIC_CHAR_LOCK_FREE 1 #define __GCC_ATOMIC_INT_LOCK_FREE 1 #define __GCC_ATOMIC_LLONG_LOCK_FREE 1 #define __GCC_ATOMIC_LONG_LOCK_FREE 1 #define __GCC_ATOMIC_POINTER_LOCK_FREE 1 #define __GCC_ATOMIC_SHORT_LOCK_FREE 1 #define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1 #define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 1 #define __GNUC_GNU_INLINE__ 1 #define __GNUC_MINOR__ 2 #define __GNUC_PATCHLEVEL__ 1 #define __GNUC__ 4 #define __GNUG__ 4 #define __GXX_ABI_VERSION 1002 #define __GXX_EXPERIMENTAL_CXX0X__ 1 #define __GXX_RTTI 1 #define __GXX_WEAK__ 1 #define __ILP32__ 1 #define __INT16_C_SUFFIX__ #define __INT16_FMTd__ "hd" #define __INT16_FMTi__ "hi" #define __INT16_MAX__ 32767 #define __INT16_TYPE__ short #define __INT32_C_SUFFIX__ #define __INT32_FMTd__ "d" #define __INT32_FMTi__ "i" #define __INT32_MAX__ 2147483647 #define __INT32_TYPE__ int #define __INT64_C_SUFFIX__ LL #define __INT64_FMTd__ "lld" #define __INT64_FMTi__ "lli" #define __INT64_MAX__ 9223372036854775807LL #define __INT64_TYPE__ long long int #define __INT8_C_SUFFIX__ #define __INT8_FMTd__ "hhd" #define __INT8_FMTi__ "hhi" #define __INT8_MAX__ 127 #define __INT8_TYPE__ signed char #define __INTMAX_C_SUFFIX__ LL #define __INTMAX_FMTd__ "lld" #define __INTMAX_FMTi__ "lli" #define __INTMAX_MAX__ 9223372036854775807LL #define __INTMAX_TYPE__ long long int #define __INTMAX_WIDTH__ 64 #define __INTPTR_FMTd__ "d" #define __INTPTR_FMTi__ "i" #define __INTPTR_MAX__ 2147483647 #define __INTPTR_TYPE__ int #define __INTPTR_WIDTH__ 32 #define __INT_FAST16_FMTd__ "hd" #define __INT_FAST16_FMTi__ "hi" #define __INT_FAST16_MAX__ 32767 #define __INT_FAST16_TYPE__ short #define __INT_FAST32_FMTd__ "d" #define __INT_FAST32_FMTi__ "i" #define __INT_FAST32_MAX__ 2147483647 #define __INT_FAST32_TYPE__ int #define __INT_FAST64_FMTd__ "lld" #define __INT_FAST64_FMTi__ "lli" #define __INT_FAST64_MAX__ 9223372036854775807LL #define __INT_FAST64_TYPE__ long long int #define __INT_FAST8_FMTd__ "hhd" #define __INT_FAST8_FMTi__ "hhi" #define __INT_FAST8_MAX__ 127 #define __INT_FAST8_TYPE__ signed char #define __INT_LEAST16_FMTd__ "hd" #define __INT_LEAST16_FMTi__ "hi" #define __INT_LEAST16_MAX__ 32767 #define __INT_LEAST16_TYPE__ short #define __INT_LEAST32_FMTd__ "d" #define __INT_LEAST32_FMTi__ "i" #define __INT_LEAST32_MAX__ 2147483647 #define __INT_LEAST32_TYPE__ int #define __INT_LEAST64_FMTd__ "lld" #define __INT_LEAST64_FMTi__ "lli" #define __INT_LEAST64_MAX__ 9223372036854775807LL #define __INT_LEAST64_TYPE__ long long int #define __INT_LEAST8_FMTd__ "hhd" #define __INT_LEAST8_FMTi__ "hhi" #define __INT_LEAST8_MAX__ 127 #define __INT_LEAST8_TYPE__ signed char #define __INT_MAX__ 2147483647 #define __LDBL_DECIMAL_DIG__ 17 #define __LDBL_DENORM_MIN__ 4.9406564584124654e-324L #define __LDBL_DIG__ 15 #define __LDBL_EPSILON__ 2.2204460492503131e-16L #define __LDBL_HAS_DENORM__ 1 #define __LDBL_HAS_INFINITY__ 1 #define __LDBL_HAS_QUIET_NAN__ 1 #define __LDBL_MANT_DIG__ 53 #define __LDBL_MAX_10_EXP__ 308 #define __LDBL_MAX_EXP__ 1024 #define __LDBL_MAX__ 1.7976931348623157e+308L #define __LDBL_MIN_10_EXP__ (-307) #define __LDBL_MIN_EXP__ (-1021) #define __LDBL_MIN__ 2.2250738585072014e-308L #define __LITTLE_ENDIAN__ 1 #define __LONG_LONG_MAX__ 9223372036854775807LL #define __LONG_MAX__ 2147483647L #define __NO_INLINE__ 1 #define __ORDER_BIG_ENDIAN__ 4321 #define __ORDER_LITTLE_ENDIAN__ 1234 #define __ORDER_PDP_ENDIAN__ 3412 #define __POINTER_WIDTH__ 32 #define __PRAGMA_REDEFINE_EXTNAME 1 #define __PTRDIFF_FMTd__ "d" #define __PTRDIFF_FMTi__ "i" #define __PTRDIFF_MAX__ 2147483647 #define __PTRDIFF_TYPE__ int #define __PTRDIFF_WIDTH__ 32 #define __SCHAR_MAX__ 127 #define __SHRT_MAX__ 32767 #define __SIG_ATOMIC_MAX__ 2147483647 #define __SIG_ATOMIC_WIDTH__ 32 #define __SIZEOF_DOUBLE__ 8 #define __SIZEOF_FLOAT__ 4 #define __SIZEOF_INT__ 4 #define __SIZEOF_LONG_DOUBLE__ 8 #define __SIZEOF_LONG_LONG__ 8 #define __SIZEOF_LONG__ 4 #define __SIZEOF_POINTER__ 4 #define __SIZEOF_PTRDIFF_T__ 4 #define __SIZEOF_SHORT__ 2 #define __SIZEOF_SIZE_T__ 4 #define __SIZEOF_WCHAR_T__ 4 #define __SIZEOF_WINT_T__ 4 #define __SIZE_FMTX__ "X" #define __SIZE_FMTo__ "o" #define __SIZE_FMTu__ "u" #define __SIZE_FMTx__ "x" #define __SIZE_MAX__ 4294967295U #define __SIZE_TYPE__ unsigned int #define __SIZE_WIDTH__ 32 #define __STDC_HOSTED__ 1 #define __STDC_UTF_16__ 1 #define __STDC_UTF_32__ 1 #define __STDC__ 1 #define __STRICT_ANSI__ 1 #define __UINT16_C_SUFFIX__ #define __UINT16_FMTX__ "hX" #define __UINT16_FMTo__ "ho" #define __UINT16_FMTu__ "hu" #define __UINT16_FMTx__ "hx" #define __UINT16_MAX__ 65535 #define __UINT16_TYPE__ unsigned short #define __UINT32_C_SUFFIX__ U #define __UINT32_FMTX__ "X" #define __UINT32_FMTo__ "o" #define __UINT32_FMTu__ "u" #define __UINT32_FMTx__ "x" #define __UINT32_MAX__ 4294967295U #define __UINT32_TYPE__ unsigned int #define __UINT64_C_SUFFIX__ ULL #define __UINT64_FMTX__ "llX" #define __UINT64_FMTo__ "llo" #define __UINT64_FMTu__ "llu" #define __UINT64_FMTx__ "llx" #define __UINT64_MAX__ 18446744073709551615ULL #define __UINT64_TYPE__ long long unsigned int #define __UINT8_C_SUFFIX__ #define __UINT8_FMTX__ "hhX" #define __UINT8_FMTo__ "hho" #define __UINT8_FMTu__ "hhu" #define __UINT8_FMTx__ "hhx" #define __UINT8_MAX__ 255 #define __UINT8_TYPE__ unsigned char #define __UINTMAX_C_SUFFIX__ ULL #define __UINTMAX_FMTX__ "llX" #define __UINTMAX_FMTo__ "llo" #define __UINTMAX_FMTu__ "llu" #define __UINTMAX_FMTx__ "llx" #define __UINTMAX_MAX__ 18446744073709551615ULL #define __UINTMAX_TYPE__ long long unsigned int #define __UINTMAX_WIDTH__ 64 #define __UINTPTR_FMTX__ "X" #define __UINTPTR_FMTo__ "o" #define __UINTPTR_FMTu__ "u" #define __UINTPTR_FMTx__ "x" #define __UINTPTR_MAX__ 4294967295U #define __UINTPTR_TYPE__ unsigned int #define __UINTPTR_WIDTH__ 32 #define __UINT_FAST16_FMTX__ "hX" #define __UINT_FAST16_FMTo__ "ho" #define __UINT_FAST16_FMTu__ "hu" #define __UINT_FAST16_FMTx__ "hx" #define __UINT_FAST16_MAX__ 65535 #define __UINT_FAST16_TYPE__ unsigned short #define __UINT_FAST32_FMTX__ "X" #define __UINT_FAST32_FMTo__ "o" #define __UINT_FAST32_FMTu__ "u" #define __UINT_FAST32_FMTx__ "x" #define __UINT_FAST32_MAX__ 4294967295U #define __UINT_FAST32_TYPE__ unsigned int #define __UINT_FAST64_FMTX__ "llX" #define __UINT_FAST64_FMTo__ "llo" #define __UINT_FAST64_FMTu__ "llu" #define __UINT_FAST64_FMTx__ "llx" #define __UINT_FAST64_MAX__ 18446744073709551615ULL #define __UINT_FAST64_TYPE__ long long unsigned int #define __UINT_FAST8_FMTX__ "hhX" #define __UINT_FAST8_FMTo__ "hho" #define __UINT_FAST8_FMTu__ "hhu" #define __UINT_FAST8_FMTx__ "hhx" #define __UINT_FAST8_MAX__ 255 #define __UINT_FAST8_TYPE__ unsigned char #define __UINT_LEAST16_FMTX__ "hX" #define __UINT_LEAST16_FMTo__ "ho" #define __UINT_LEAST16_FMTu__ "hu" #define __UINT_LEAST16_FMTx__ "hx" #define __UINT_LEAST16_MAX__ 65535 #define __UINT_LEAST16_TYPE__ unsigned short #define __UINT_LEAST32_FMTX__ "X" #define __UINT_LEAST32_FMTo__ "o" #define __UINT_LEAST32_FMTu__ "u" #define __UINT_LEAST32_FMTx__ "x" #define __UINT_LEAST32_MAX__ 4294967295U #define __UINT_LEAST32_TYPE__ unsigned int #define __UINT_LEAST64_FMTX__ "llX" #define __UINT_LEAST64_FMTo__ "llo" #define __UINT_LEAST64_FMTu__ "llu" #define __UINT_LEAST64_FMTx__ "llx" #define __UINT_LEAST64_MAX__ 18446744073709551615ULL #define __UINT_LEAST64_TYPE__ long long unsigned int #define __UINT_LEAST8_FMTX__ "hhX" #define __UINT_LEAST8_FMTo__ "hho" #define __UINT_LEAST8_FMTu__ "hhu" #define __UINT_LEAST8_FMTx__ "hhx" #define __UINT_LEAST8_MAX__ 255 #define __UINT_LEAST8_TYPE__ unsigned char #define __USER_LABEL_PREFIX__ #define __VERSION__ "4.2.1 Compatible Clang 3.7.0 (https://chromium.googlesource.com/a/native_client/pnacl-clang.git 0895c9a2aedd33371c6cb8703d5fe8bb4493169b) (https://chromium.googlesource.com/a/native_client/pnacl-llvm.git 58b8aae0d0105ffa0042d6e44f50f06f618cb754)" #define __WCHAR_MAX__ 2147483647 #define __WCHAR_TYPE__ int #define __WCHAR_WIDTH__ 32 #define __WINT_TYPE__ int #define __WINT_WIDTH__ 32 #define __clang__ 1 #define __clang_major__ 3 #define __clang_minor__ 7 #define __clang_patchlevel__ 0 #define __clang_version__ "3.7.0 (https://chromium.googlesource.com/a/native_client/pnacl-clang.git 0895c9a2aedd33371c6cb8703d5fe8bb4493169b) (https://chromium.googlesource.com/a/native_client/pnacl-llvm.git 58b8aae0d0105ffa0042d6e44f50f06f618cb754)" #define __cplusplus 201103L #define __cpp_alias_templates 200704 #define __cpp_attributes 200809 #define __cpp_constexpr 200704 #define __cpp_decltype 200707 #define __cpp_delegating_constructors 200604 #define __cpp_exceptions 199711 #define __cpp_inheriting_constructors 200802 #define __cpp_initializer_lists 200806 #define __cpp_lambdas 200907 #define __cpp_nsdmi 200809 #define __cpp_range_based_for 200907 #define __cpp_raw_strings 200710 #define __cpp_ref_qualifiers 200710 #define __cpp_rtti 199711 #define __cpp_rvalue_references 200610 #define __cpp_static_assert 200410 #define __cpp_unicode_characters 200704 #define __cpp_unicode_literals 200710 #define __cpp_user_defined_literals 200809 #define __cpp_variadic_templates 200704 #define __le32__ 1 #define __llvm__ 1 #define __native_client__ 1 #define __pnacl__ 1 #define __private_extern__ extern #define __unix 1 #define __unix__ 1
mpl-2.0
shavac/gexpect
pty/terminal.go
1710
package pty import "os" type Terminal struct { Pty *os.File Tty *os.File Recorder []*os.File Log *os.File oldState State } func (t *Terminal) Write(b []byte) (n int, err error) { return t.Pty.Write(b) } func (t *Terminal) Read(b []byte) (n int, err error) { n, err = t.Pty.Read(b) for _, r := range t.Recorder { if n, err := r.Write(b); err != nil { return n, err } } return n, err } func (t *Terminal) SetWinSize(x, y int) error { return SetWinSize(t.Pty, uint16(x), uint16(y)) } func (t *Terminal) GetWinSize() (x, y int, err error) { return GetWinSize(t.Pty) } func (t *Terminal) ResetWinSize() error { if x, y, err := t.GetWinSize(); err != nil { return err } else { return t.SetWinSize(x, y) } } func (t *Terminal) SetRaw() (err error) { if oldState, err := Tcgetattr(t.Pty); err != nil { return err } else { t.oldState = *oldState } return SetRaw(t.Pty) } func (t *Terminal) SetCBreak() (err error) { if oldState, err := Tcgetattr(t.Pty); err != nil { return err } else { t.oldState = *oldState } return SetCBreak(t.Pty) } func (t *Terminal) Restore() (err error) { return Tcsetattr(t.Pty, &t.oldState) } func (t *Terminal) SendIntr() (err error) { c, err := GetControlChar(t.Pty, "CTRL-C") _, err = t.Write([]byte{c}) return } func (t *Terminal) SendEOF() (err error) { c, err := GetControlChar(t.Pty, "EOF") _, err = t.Write([]byte{c}) return } func (t *Terminal) Close() (err error) { stdout.Reset() for _, r := range t.Recorder { r.Close() } err = t.Tty.Close() err = t.Pty.Close() return } func NewTerminal() (term *Terminal, err error) { pty, tty, err := Open() term = &Terminal{Pty: pty, Tty: tty} return }
mpl-2.0
hashicorp/vault
command/token_lookup.go
3079
package command import ( "fmt" "strings" "github.com/hashicorp/vault/api" "github.com/mitchellh/cli" "github.com/posener/complete" ) var ( _ cli.Command = (*TokenLookupCommand)(nil) _ cli.CommandAutocomplete = (*TokenLookupCommand)(nil) ) type TokenLookupCommand struct { *BaseCommand flagAccessor bool } func (c *TokenLookupCommand) Synopsis() string { return "Display information about a token" } func (c *TokenLookupCommand) Help() string { helpText := ` Usage: vault token lookup [options] [TOKEN | ACCESSOR] Displays information about a token or accessor. If a TOKEN is not provided, the locally authenticated token is used. Get information about the locally authenticated token (this uses the /auth/token/lookup-self endpoint and permission): $ vault token lookup Get information about a particular token (this uses the /auth/token/lookup endpoint and permission): $ vault token lookup 96ddf4bc-d217-f3ba-f9bd-017055595017 Get information about a token via its accessor: $ vault token lookup -accessor 9793c9b3-e04a-46f3-e7b8-748d7da248da For a full list of examples, please see the documentation. ` + c.Flags().Help() return strings.TrimSpace(helpText) } func (c *TokenLookupCommand) Flags() *FlagSets { set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) f := set.NewFlagSet("Command Options") f.BoolVar(&BoolVar{ Name: "accessor", Target: &c.flagAccessor, Default: false, EnvVar: "", Completion: complete.PredictNothing, Usage: "Treat the argument as an accessor instead of a token. When " + "this option is selected, the output will NOT include the token.", }) return set } func (c *TokenLookupCommand) AutocompleteArgs() complete.Predictor { return c.PredictVaultFiles() } func (c *TokenLookupCommand) AutocompleteFlags() complete.Flags { return c.Flags().Completions() } func (c *TokenLookupCommand) Run(args []string) int { f := c.Flags() if err := f.Parse(args); err != nil { c.UI.Error(err.Error()) return 1 } token := "" args = f.Args() switch { case c.flagAccessor && len(args) < 1: c.UI.Error(fmt.Sprintf("Not enough arguments with -accessor (expected 1, got %d)", len(args))) return 1 case c.flagAccessor && len(args) > 1: c.UI.Error(fmt.Sprintf("Too many arguments with -accessor (expected 1, got %d)", len(args))) return 1 case len(args) == 0: // Use the local token case len(args) == 1: token = strings.TrimSpace(args[0]) case len(args) > 1: c.UI.Error(fmt.Sprintf("Too many arguments (expected 0-1, got %d)", len(args))) return 1 } client, err := c.Client() if err != nil { c.UI.Error(err.Error()) return 2 } var secret *api.Secret switch { case token == "": secret, err = client.Auth().Token().LookupSelf() case c.flagAccessor: secret, err = client.Auth().Token().LookupAccessor(token) default: secret, err = client.Auth().Token().Lookup(token) } if err != nil { c.UI.Error(fmt.Sprintf("Error looking up token: %s", err)) return 2 } return OutputSecret(c.UI, secret) }
mpl-2.0
jembi/openhim-mediator-engine-java
src/test/java/org/openhim/mediator/engine/CoreResponseTest.java
4991
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.openhim.mediator.engine; import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.TimeZone; import static org.junit.Assert.*; public class CoreResponseTest { @Test public void testParse() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); format.setTimeZone(TimeZone.getTimeZone("GMT+2")); InputStream in = CoreResponseTest.class.getClassLoader().getResourceAsStream("core-response.json"); String json = IOUtils.toString(in); CoreResponse response = CoreResponse.parse(json); assertEquals("urn:mediator:test-mediator", response.getUrn()); assertEquals("Successful", response.getStatus()); assertEquals(new Integer(200), response.getResponse().getStatus()); assertEquals("text/plain", response.getResponse().getHeaders().get("Content-Type")); assertEquals("a test response", response.getResponse().getBody()); assertEquals("2015-01-15 14:51", format.format(response.getResponse().getTimestamp())); assertEquals(2, response.getOrchestrations().size()); assertEquals("orch1", response.getOrchestrations().get(0).getName()); assertEquals("someserver", response.getOrchestrations().get(0).getRequest().getHost()); assertEquals("8080", response.getOrchestrations().get(0).getRequest().getPort()); assertEquals("/orch1", response.getOrchestrations().get(0).getRequest().getPath()); assertEquals("orchestration 1", response.getOrchestrations().get(0).getRequest().getBody()); assertEquals("POST", response.getOrchestrations().get(0).getRequest().getMethod()); assertEquals("2015-01-15 14:51", format.format(response.getOrchestrations().get(0).getRequest().getTimestamp())); assertEquals(new Integer(201), response.getOrchestrations().get(0).getResponse().getStatus()); assertEquals("text/plain", response.getOrchestrations().get(0).getResponse().getHeaders().get("Content-Type")); assertEquals("created", response.getOrchestrations().get(0).getResponse().getBody()); assertEquals("2015-01-15 14:51", format.format(response.getOrchestrations().get(0).getResponse().getTimestamp())); assertEquals("orch2", response.getOrchestrations().get(1).getName()); assertNull(response.getOrchestrations().get(1).getRequest().getHost()); assertNull(response.getOrchestrations().get(1).getRequest().getPort()); assertEquals("/orch2", response.getOrchestrations().get(1).getRequest().getPath()); assertNull(response.getOrchestrations().get(1).getRequest().getBody()); assertEquals("GET", response.getOrchestrations().get(1).getRequest().getMethod()); assertEquals("2015-01-15 14:51", format.format(response.getOrchestrations().get(1).getRequest().getTimestamp())); assertEquals(new Integer(200), response.getOrchestrations().get(1).getResponse().getStatus()); assertEquals("text/xml", response.getOrchestrations().get(1).getResponse().getHeaders().get("Content-Type")); assertEquals("<data>test orchestration 2</data>", response.getOrchestrations().get(1).getResponse().getBody()); assertEquals("2015-01-15 14:51", format.format(response.getOrchestrations().get(1).getResponse().getTimestamp())); assertEquals(2, response.getProperties().size()); assertEquals("val1", response.getProperties().get("pro1")); assertEquals("val2", response.getProperties().get("pro2")); } @Test public void testDateformats() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); format.setTimeZone(TimeZone.getTimeZone("GMT+2")); InputStream in = CoreResponseTest.class.getClassLoader().getResourceAsStream("core-response-multiple-dates.json"); String json = IOUtils.toString(in); CoreResponse response = CoreResponse.parse(json); assertEquals("Should parse ISO8601 in UTC", "2015-01-15 14:51", format.format(response.getResponse().getTimestamp())); assertEquals("Should parse ISO8601 in GMT+2", "2015-01-15 14:51", format.format(response.getOrchestrations().get(0).getRequest().getTimestamp())); assertEquals("Should parse timestamp in milliseconds", "2015-01-15 14:51", format.format(response.getOrchestrations().get(0).getResponse().getTimestamp())); } @Test public void testParse_BadContent() throws Exception { String json = "bad content!"; try { CoreResponse.parse(json); fail("Failed to throw JsonSyntaxException"); } catch (CoreResponse.ParseException ex) { //expected } } }
mpl-2.0
AlexanderOMara/mozilla-add-on-tutorials
native-dev-panel/lib/panel-model.js
644
'use strict'; // A model class to handle communication with the debuggee. function PanelModel(debuggee) { this._debuggee = debuggee; this._debuggee.start(); } exports.PanelModel = PanelModel; PanelModel.prototype = { constructor: PanelModel, dispose: function() { this._debuggee = null; }, listTabs: function() { // An example debuggee message and response. return new Promise((resolve) => { // Not pretty, but it gets the job done. this._debuggee.onmessage = (e) => { this._debuggee.onmessage = null; resolve(e.data); }; this._debuggee.postMessage({ 'to': 'root', 'type': 'listTabs' }); }); } };
mpl-2.0
openMF/self-service-app
app/src/main/java/org/mifos/mobile/presenters/BeneficiaryApplicationPresenter.java
6045
package org.mifos.mobile.presenters; import android.content.Context; import android.view.View; import org.mifos.mobile.R; import org.mifos.mobile.api.DataManager; import org.mifos.mobile.injection.ApplicationContext; import org.mifos.mobile.models.beneficiary.BeneficiaryPayload; import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload; import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate; import org.mifos.mobile.presenters.base.BasePresenter; import org.mifos.mobile.ui.views.BeneficiaryApplicationView; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; import okhttp3.ResponseBody; /** * Created by dilpreet on 16/6/17. */ public class BeneficiaryApplicationPresenter extends BasePresenter<BeneficiaryApplicationView> { private DataManager dataManager; private CompositeDisposable compositeDisposable; /** * Initialises the LoginPresenter by automatically injecting an instance of * {@link DataManager} and {@link Context}. * * @param dataManager DataManager class that provides access to the data * via the API. * @param context Context of the view attached to the presenter. In this case * it is that of an {@link androidx.appcompat.app.AppCompatActivity} */ @Inject public BeneficiaryApplicationPresenter(DataManager dataManager, @ApplicationContext Context context) { super(context); this.dataManager = dataManager; compositeDisposable = new CompositeDisposable(); } @Override public void detachView() { super.detachView(); compositeDisposable.clear(); } /** * Loads BeneficiaryTemplate from the server and notifies the view to display it. And in case of * any error during fetching the required details it notifies the view. */ public void loadBeneficiaryTemplate() { checkViewAttached(); getMvpView().setVisibility(View.GONE); getMvpView().showProgress(); compositeDisposable.add(dataManager.getBeneficiaryTemplate() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribeWith(new DisposableObserver<BeneficiaryTemplate>() { @Override public void onComplete() { getMvpView().setVisibility(View.VISIBLE); } @Override public void onError(Throwable e) { getMvpView().hideProgress(); getMvpView().showError(context .getString(R.string.error_fetching_beneficiary_template)); } @Override public void onNext(BeneficiaryTemplate beneficiaryTemplate) { getMvpView().hideProgress(); getMvpView().showBeneficiaryTemplate(beneficiaryTemplate); } })); } /** * Used to create a Beneficiary and notifies the view after successful creation of Beneficiary. * And in case of any error during creation, it notifies the view. * * @param payload {@link BeneficiaryPayload} used for creating a Beneficiary. */ public void createBeneficiary(BeneficiaryPayload payload) { checkViewAttached(); getMvpView().showProgress(); compositeDisposable.add(dataManager.createBeneficiary(payload) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribeWith(new DisposableObserver<ResponseBody>() { @Override public void onComplete() { } @Override public void onError(Throwable e) { getMvpView().hideProgress(); getMvpView().showError(context .getString(R.string.error_creating_beneficiary)); } @Override public void onNext(ResponseBody responseBody) { getMvpView().hideProgress(); getMvpView().showBeneficiaryCreatedSuccessfully(); } })); } /** * Update a Beneficiary with provided {@code beneficiaryId} and notifies the view after * successful updation of Beneficiary. And in case of any error during updation, it notifies the * view. * * @param beneficiaryId Id of Beneficiary which you want to update * @param payload {@link BeneficiaryPayload} used for updation a Beneficiary. */ public void updateBeneficiary(long beneficiaryId, BeneficiaryUpdatePayload payload) { checkViewAttached(); getMvpView().showProgress(); compositeDisposable.add(dataManager.updateBeneficiary(beneficiaryId, payload) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribeWith(new DisposableObserver<ResponseBody>() { @Override public void onComplete() { } @Override public void onError(Throwable e) { getMvpView().hideProgress(); getMvpView().showError(context .getString(R.string.error_updating_beneficiary)); } @Override public void onNext(ResponseBody responseBody) { getMvpView().hideProgress(); getMvpView().showBeneficiaryUpdatedSuccessfully(); } })); } }
mpl-2.0
jfschwarz/jsxgettext
lib/cli.js
2696
#!/usr/bin/env node var fs = require('fs'); var path = require('path'); var jsxgettext = require('./jsxgettext'); var opts = require("nomnom") .script('jsxgettext') .option('output', { abbr: 'o', metavar: 'FILE', default: 'messages.po', help: 'write output to specified file' }) .option('output-dir', { abbr: 'p', metavar: 'DIR', help: 'output files will be placed in directory DIR' }) .option('version', { abbr: 'v', flag: true, help: 'print version and exit', callback: function() { return require('../package.json').version; } }) .option('input', { position: 0, required: true, list: true, help: 'input files' }) .option('keyword', { abbr: 'k', metavar: 'WORD', help: 'additional keyword to be looked for as gettext alias' }) .option('plural', { abbr: 'n', metavar: 'WORD', help: 'additional keyword to be looked for as ngettext alias' }) .option('join-existing', { abbr: 'j', flag: true, help: 'join messages with existing file' }) .option('language', { abbr: 'L', metavar: 'NAME', default: 'JavaScript', help: 'recognise the specified language (JavaScript, Babel, EJS, Jinja, Jade, Handlebars)' }) .parse(); function main () { var files = opts.input; var sources = {}; if (files[0] === '-') { var data = ''; process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { data += chunk; }); process.stdin.on('end', function () { gen({'stdin': data}); }); } else { files.forEach(function (filename) { sources[filename] = fs.readFileSync(filename, "utf8"); }); gen(sources); } } function gen (sources) { var result; if (opts.language.toUpperCase() === 'EJS') { result = jsxgettext.generateFromEJS(sources, opts); } else if (opts.language.toUpperCase() === 'JINJA') { result = jsxgettext.generateFromJinja(sources, opts); } else if (opts.language.toUpperCase() === 'JADE') { result = jsxgettext.generateFromJade(sources, opts); } else if (opts.language.toUpperCase() === 'HANDLEBARS') { result = jsxgettext.generateFromHandlebars(sources, opts); } else if (opts.language.toUpperCase() === 'BABEL') { result = jsxgettext.generateFromBabel(sources, opts); } else { result = jsxgettext.generate(sources, opts); } if (opts.output === '-') { console.log(result); } else { fs.writeFileSync(path.resolve(path.join(opts['output-dir'] || '', opts.output)), result, "utf8"); } } main();
mpl-2.0
miracle-as/kitos
Core.DomainModel/ItSystem/AccessType.cs
581
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.DomainModel.ItSystem { public class AccessType : Entity, ISystemModule { public AccessType() { this.ItSystemUsages = new List<ItSystemUsage.ItSystemUsage>(); } public string Name { get; set; } public int ItSystemId { get; set; } public virtual ItSystem ItSystem { get; set; } public virtual ICollection<ItSystemUsage.ItSystemUsage> ItSystemUsages { get; set; } } }
mpl-2.0
Jumoo/Taskily
TaskilyWeb/Scripts/public/taskily.js
2332
/* taskily.js */ var Taskily = function (pickNo) { var tskly = {}; closebtn = '<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>'; var pickTotal = pickNo; tskly.updatePickerBar = function () { var pickedCount = $('.picked').length; if (pickedCount == 1) { $('#pickCount').text(pickedCount + " item"); } else { $('#pickCount').text(pickedCount + " items"); } var picklist = ''; $.each($('.picked'), function (i, picked) { picklist = picklist + '<span class="label label-info picker-item" data-taskid="' + $(picked).attr("data-id") + '"><span class="nowrap">' + $(picked).attr("data-name") + closebtn + '</span></span>'; }); $("#pickList").html(picklist); if (pickedCount == pickTotal) { $('#pickError').text(''); $(".task-btn-clear").hide(); $('.task-btn-pick').fadeIn(); $('.picker-bar').animate({ backgroundColor: '#dfd' }, 200); } else { $(".task-btn-pick").hide(); $(".task-btn-clear").fadeIn(); if (pickedCount > pickTotal) { $('#pickError').html("please pick only <strong>" + pickTotal + "</strong> items."); $('.picker-bar').animate({ backgroundColor: '#fdd' }, 200); } else { $('#pickError').html("pick <strong>" + pickTotal + "</strong> items"); $('.picker-bar').animate({ backgroundColor: '#ddd' }, 200); } } var cb = this.clearCallback; $('.picker-item').on('closed.bs.alert', function () { clearbtn(this, cb); }); }; function clearbtn(item, cb) { var tId = $(item).attr("data-taskId"); $('input[id=r_' + tId + ']').attr('checked', false); $('#lbl_' + tId).removeClass('picked'); cb(); }; tskly.clearCallback = function () { taskily.updatePickerBar(); }; tskly.clear = function () { $('.picked').removeClass('picked'); $('input:checked').attr('checked', false); taskily.updatePickerBar(); }; return tskly; }
mpl-2.0
cj3kim/commonly-famous
math/Utilities.js
1076
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Owner: mark@famo.us * @license MPL 2.0 * @copyright Famous Industries, Inc. 2014 */ /** * A few static methods. * * @class Utilities * @static */ var Utilities = {}; /** * Constrain input to range. * * @method clamp * @param {Number} value input * @param {Array.Number} range [min, max] * @static */ Utilities.clamp = function clamp(value, range) { return Math.max(Math.min(value, range[1]), range[0]); }; /** * Euclidean length of numerical array. * * @method length * @param {Array.Number} array array of numbers * @static */ Utilities.length = function length(array) { var distanceSquared = 0; for (var i = 0; i < array.length; i++) { distanceSquared += array[i] * array[i]; } return Math.sqrt(distanceSquared); }; module.exports = Utilities;
mpl-2.0
shkim/ServerCore
samples/timer/timer.cpp
1951
/* ServerCore Sample, Timer With timer, the server can periodically send data to the client regardless of the client's request. */ #include "timer.h" IServerCore* g_pCore; class TimerServerModule : public IServerModule { virtual bool Create(IServerCore* pCore) { g_pCore = pCore; pCore->RegisterClientListener(Client::Creator); return true; } virtual void Destroy() { } }; SC_SERVERMODULE_ENTRY(TimerServerModule) ////////////////////////////////////////////////////////////////////////////// #ifndef _WIN32 DWORD GetTickCount() { struct timeval curr; gettimeofday(&curr, NULL); return (curr.tv_sec * 1000) + (curr.tv_usec / 1000); } #endif bool Client::OnConnect(ITcpSocket* pSocket, int nErrorCode) { m_pSocket = pSocket; m_dwPrevTick = GetTickCount(); m_nTimerCount = 0; g_pCore->SetTimer(this, rand(), 1000, true); return true; } void Client::OnDisconnect() { g_pCore->ClearTimer(this); } void Client::OnRelease() { m_pSocket = NULL; } void Client::OnFinalDestruct() { delete this; } unsigned int Client::OnReceive(char* pBuffer, unsigned int nLength) { m_pSocket->Send(pBuffer, nLength); return nLength; } void Client::OnTimer(int nTimerID) { char buff[256]; DWORD curTick = GetTickCount(); StringCchPrintfA(buff, 256, "OnTimer(id=%d): %d ticks #%d\r\n", nTimerID, curTick - m_dwPrevTick, ++m_nTimerCount); m_dwPrevTick = curTick; SC_ASSERT(m_pSocket); m_pSocket->Send(buff, (int) strlen(buff)+1); }
mpl-2.0
lorgan3/GG2server
objects/Hitboxes/Point.cs
788
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GG2server.objects.Hitboxes { public struct Point { public float x1; public float y1; /// <summary> /// Defines a point. /// </summary> /// <param name="x1">point x.</param> /// <param name="y1">point y.</param> public Point(float x1, float y1) { this.x1 = x1; this.y1 = y1; } /// <summary> /// Move to this point. /// </summary> /// <param name="x">point x.</param> /// <param name="y">point y.</param> public void move(float x, float y) { this.x1 = x; this.y1 = y; } } }
mpl-2.0
rhelmer/socorro-lib
socorro/unittest/external/elasticsearch/test_search.py
20182
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import datetime import mock from nose.plugins.attrib import attr from nose.tools import eq_, ok_ from .unittestbase import ElasticSearchTestCase from socorro.external.elasticsearch import crashstorage from socorro.external.elasticsearch.search import Search from socorro.lib import util, datetimeutil from socorro.unittest.testbase import TestCase from .test_supersearch import ( SUPERSEARCH_FIELDS ) # Remove debugging noise during development # import logging # logging.getLogger('pyelasticsearch').setLevel(logging.ERROR) # logging.getLogger('elasticutils').setLevel(logging.ERROR) # logging.getLogger('requests.packages.urllib3.connectionpool')\ # .setLevel(logging.ERROR) #============================================================================== class TestElasticSearchSearch(TestCase): """Test Search class implemented with ElasticSearch. """ #-------------------------------------------------------------------------- def get_dummy_context(self): """ Create a dummy config object to use when testing. """ context = util.DotDict() context.elasticSearchHostname = "" context.elasticSearchPort = 9200 context.platforms = ( { "id": "windows", "name": "Windows NT" }, { "id": "linux", "name": "Linux" } ) return context #-------------------------------------------------------------------------- def test_get_signatures_list(self): """ Test Search.get_signatures() """ context = self.get_dummy_context() facets = { "signatures": { "terms": [ { "term": "hang", "count": 145 }, { "term": "js", "count": 7 }, { "term": "ws", "count": 4 } ] } } size = 3 expected = ["hang", "js", "ws"] signatures = Search.get_signatures_list( facets, size, context.platforms ) res_signs = [] for sign in signatures: ok_(sign["signature"] in expected) res_signs.append(sign["signature"]) for sign in expected: ok_(sign in res_signs) #-------------------------------------------------------------------------- def test_get_counts(self): """ Test Search.get_counts() """ context = self.get_dummy_context() signatures = [ { "signature": "hang", "count": 12 }, { "signature": "js", "count": 4 } ] count_sign = { "hang": { "terms": [ { "term": "windows", "count": 3 }, { "term": "linux", "count": 4 } ] }, "js": { "terms": [ { "term": "windows", "count": 2 } ] }, "hang_hang": { "count": 0 }, "js_hang": { "count": 0 }, "hang_plugin": { "count": 0 }, "js_plugin": { "count": 0 }, "hang_content": { "count": 0 }, "js_content": { "count": 0 } } res = Search.get_counts( signatures, count_sign, 0, 2, context.platforms ) ok_(type(res) is list) for sign in res: ok_("signature" in sign) ok_("count" in sign) ok_("is_windows" in sign) ok_("numhang" in sign) ok_("numplugin" in sign) ok_("numcontent" in sign) ok_("is_linux" in res[0]) ok_(not "is_linux" in res[1]) #============================================================================== @attr(integration='elasticsearch') class IntegrationElasticsearchSearch(ElasticSearchTestCase): """Test search with an elasticsearch database containing fake data. """ def setUp(self): super(IntegrationElasticsearchSearch, self).setUp() config = self.get_config_context() self.api = Search(config=config) self.storage = crashstorage.ElasticSearchCrashStorage(config) # clear the indices cache so the index is created on every test self.storage.indices_cache = set() # Create the supersearch fields. self.storage.es.bulk_index( index=config.webapi.elasticsearch_default_index, doc_type='supersearch_fields', docs=SUPERSEARCH_FIELDS.values(), id_field='name', refresh=True, ) now = datetimeutil.utc_now() yesterday = now - datetime.timedelta(days=1) yesterday = datetimeutil.date_to_string(yesterday) last_month = now - datetime.timedelta(weeks=4) last_month = datetimeutil.date_to_string(last_month) # insert data into elasticsearch default_crash_report = { 'uuid': 100, 'signature': 'js::break_your_browser', 'date_processed': yesterday, 'product': 'WaterWolf', 'version': '1.0', 'release_channel': 'release', 'os_name': 'Linux', 'build': '1234567890', 'reason': 'MOZALLOC_WENT_WRONG', 'hangid': None, 'process_type': None, } self.storage.save_processed(default_crash_report) self.storage.save_processed( dict(default_crash_report, uuid=1, product='EarthRaccoon') ) self.storage.save_processed( dict(default_crash_report, uuid=2, version='2.0') ) self.storage.save_processed( dict(default_crash_report, uuid=3, release_channel='aurora') ) self.storage.save_processed( dict(default_crash_report, uuid=4, os_name='Windows NT') ) self.storage.save_processed( dict(default_crash_report, uuid=5, build='0987654321') ) self.storage.save_processed( dict(default_crash_report, uuid=6, reason='VERY_BAD_EXCEPTION') ) self.storage.save_processed( dict(default_crash_report, uuid=7, hangid='12') ) self.storage.save_processed( dict(default_crash_report, uuid=8, process_type='plugin') ) self.storage.save_processed( dict(default_crash_report, uuid=9, signature='my_bad') ) self.storage.save_processed( dict( default_crash_report, uuid=10, date_processed=last_month, signature='my_little_signature', ) ) # for plugin terms test self.storage.save_processed( dict( default_crash_report, uuid=11, product='PluginSoft', process_type='plugin', PluginFilename='carly.dll', PluginName='Hey I just met you', PluginVersion='1.2', ) ) self.storage.save_processed( dict( default_crash_report, uuid=12, product='PluginSoft', process_type='plugin', PluginFilename='hey.dll', PluginName='Hey Plugin', PluginVersion='10.7.0.2a', ) ) self.storage.save_processed( dict( default_crash_report, uuid=13, product='EarlyOwl', version='11.0b1', release_channel='beta', ) ) self.storage.save_processed( dict( default_crash_report, uuid=14, product='EarlyOwl', version='11.0b2', release_channel='beta', ) ) # As indexing is asynchronous, we need to force elasticsearch to # make the newly created content searchable before we run the tests self.storage.es.refresh() def tearDown(self): # clear the test index config = self.get_config_context() self.storage.es.delete_index(config.webapi.elasticsearch_index) self.storage.es.delete_index(config.webapi.elasticsearch_default_index) @mock.patch('socorro.external.elasticsearch.search.Util') def test_search_single_filters(self, mock_psql_util): # verify results show expected numbers # test no filter, get all results params = {} res = self.api.get() eq_(res['total'], 2) eq_( res['hits'][0]['signature'], 'js::break_your_browser' ) eq_( res['hits'][1]['signature'], 'my_bad' ) eq_(res['hits'][0]['is_linux'], 12) eq_(res['hits'][0]['is_windows'], 1) eq_(res['hits'][0]['is_mac'], 0) # test product params = { 'products': 'EarthRaccoon' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test version params = { 'versions': 'WaterWolf:2.0' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test release_channel params = { 'release_channels': 'aurora' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test os_name params = { 'os': 'Windows' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test short os_name params = { 'os': 'win' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test build params = { 'build_ids': '0987654321' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test reason params = { 'reasons': 'VERY_BAD_EXCEPTION' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test hangid params = { 'report_type': 'hang' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test process_type params = { 'report_process': 'plugin' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 3) # test signature params = { 'terms': 'my_bad' } res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) @mock.patch('socorro.external.elasticsearch.search.Util') def test_search_combined_filters(self, mock_psql_util): # get the first, default crash report params = { 'terms': 'js::break_your_browser', 'search_mode': 'is_exactly', 'products': 'WaterWolf', 'versions': 'WaterWolf:1.0', 'release_channels': 'release', 'os': 'Linux', 'build_ids': '1234567890', 'reasons': 'MOZALLOC_WENT_WRONG', 'report_type': 'crash', 'report_process': 'browser', } res = self.api.get(**params) eq_(res['total'], 1) eq_( res['hits'][0]['signature'], 'js::break_your_browser' ) eq_(res['hits'][0]['is_linux'], 1) eq_(res['hits'][0]['is_windows'], 0) eq_(res['hits'][0]['is_mac'], 0) # get the crash report from last month now = datetimeutil.utc_now() three_weeks_ago = now - datetime.timedelta(weeks=3) three_weeks_ago = datetimeutil.date_to_string(three_weeks_ago) five_weeks_ago = now - datetime.timedelta(weeks=5) five_weeks_ago = datetimeutil.date_to_string(five_weeks_ago) params = { 'from_date': five_weeks_ago, 'to_date': three_weeks_ago, } res = self.api.get(**params) eq_(res['total'], 1) eq_( res['hits'][0]['signature'], 'my_little_signature' ) eq_(res['hits'][0]['is_linux'], 1) eq_(res['hits'][0]['is_windows'], 0) eq_(res['hits'][0]['is_mac'], 0) @mock.patch('socorro.external.elasticsearch.search.Util') def test_search_no_results(self, mock_psql_util): # unexisting signature params = { 'terms': 'callMeMaybe()', } res = self.api.get(**params) eq_(res['total'], 0) # unexisting product params = { 'products': 'WindBear', } res = self.api.get(**params) eq_(res['total'], 0) @mock.patch('socorro.external.elasticsearch.search.Util') def test_search_plugin_terms(self, mock_psql_util): base_params = { 'products': 'PluginSoft', 'report_process': 'plugin', } # test 'is_exactly' mode base_params['plugin_search_mode'] = 'is_exactly' # get all results with filename being exactly 'carly.dll' # expect 1 signature with 1 crash params = dict( base_params, plugin_terms='carly.dll', plugin_in='filename', ) res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # get all results with name being exactly 'Hey Plugin' # expect 1 signature with 1 crash params = dict( base_params, plugin_terms='Hey Plugin', plugin_in='name', ) res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test 'contains' mode base_params['plugin_search_mode'] = 'contains' # get all results with filename containing '.dll' # expect 1 signature with 2 crashes params = dict( base_params, plugin_terms='.dll', plugin_in='filename', ) res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 2) # get all results with name containing 'Hey' # expect 1 signature with 2 crashes params = dict( base_params, plugin_terms='Hey', plugin_in='name', ) res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 2) # get all results with name containing 'Plugin' # expect 1 signature with 1 crash params = dict( base_params, plugin_terms='Plugin', plugin_in='name', ) res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # test 'starts_with' mode base_params['plugin_search_mode'] = 'starts_with' # get all results with filename starting with 'car' # expect 1 signature with 1 crash params = dict( base_params, plugin_terms='car', plugin_in='filename', ) res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # get all results with name starting with 'Hey' # expect 1 signature with 2 crashes params = dict( base_params, plugin_terms='Hey', plugin_in='name', ) res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 2) # test 'default' mode base_params['plugin_search_mode'] = 'default' # get all results with name containing the word 'hey' # expect 1 signature with 2 crashes params = dict( base_params, plugin_terms='hey', plugin_in='name', ) res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 2) # get all results with name containing the word 'you' # expect 1 signature with 1 crash params = dict( base_params, plugin_terms='you', plugin_in='name', ) res = self.api.get(**params) eq_(res['total'], 1) eq_(res['hits'][0]['count'], 1) # Test return values res = self.api.get(**base_params) eq_(res['total'], 1) ok_('pluginname' in res['hits'][0]) ok_('pluginfilename' in res['hits'][0]) ok_('pluginversion' in res['hits'][0]) params = dict( base_params, plugin_search_mode='is_exactly', plugin_terms='carly.dll', plugin_in='filename', ) res = self.api.get(**params) eq_(res['total'], 1) hit = res['hits'][0] eq_(hit['pluginname'], 'Hey I just met you') eq_(hit['pluginfilename'], 'carly.dll') eq_(hit['pluginversion'], '1.2') @mock.patch('socorro.external.elasticsearch.search.Util') def test_search_versions(self, mock_psql_util): mock_psql_util.return_value.versions_info.return_value = { 'EarlyOwl:11.0b1': { 'product_version_id': 1, 'product_name': 'EarlyOwl', 'version_string': '11.0b1', 'major_version': '11.0b1', 'release_channel': 'Beta', 'build_id': [1234567890], 'is_rapid_beta': False, 'is_from_rapid_beta': True, 'from_beta_version': 'EarlyOwl:11.0b', }, 'EarlyOwl:11.0b2': { 'product_version_id': 2, 'product_name': 'EarlyOwl', 'version_string': '11.0b2', 'major_version': '11.0b1', 'release_channel': 'Beta', 'build_id': [1234567890], 'is_rapid_beta': False, 'is_from_rapid_beta': True, 'from_beta_version': 'EarlyOwl:11.0b', }, 'EarlyOwl:11.0b': { 'product_version_id': 3, 'product_name': 'EarlyOwl', 'version_string': '11.0b', 'major_version': '11.0', 'release_channel': 'Beta', 'build_id': None, 'is_rapid_beta': True, 'is_from_rapid_beta': True, 'from_beta_version': 'EarlyOwl:11.0b', } } # Get all from the different beta versions params = dict( versions=['EarlyOwl:11.0b1', 'EarlyOwl:11.0b2'], ) res1 = self.api.get(**params) eq_(res1['total'], 1) # Get all from the rapid beta alias params = dict( versions='EarlyOwl:11.0b', ) res2 = self.api.get(**params) eq_(res2['total'], 1) # The results should be identical eq_(res1, res2)
mpl-2.0
ArtMares/PQStudio
Builder/plastiq/include/widgets/PlastiQQGraphicsWidget/plastiqqgraphicswidget.cpp
56286
#include "plastiqmethod.h" #include "plastiqqgraphicswidget.h" #include "widgets/PlastiQQGraphicsObject/plastiqqgraphicsobject.h" #include "widgets/PlastiQQGraphicsLayoutItem/plastiqqgraphicslayoutitem.h" #include <QGraphicsWidget> #include <QFont> #include <QGraphicsLayout> #include <QPainter> #include <QStyleOptionGraphicsItem> #include <QWidget> #include <QPalette> #include <QRectF> #include <QSizeF> #include <QStyle> #include <QString> #include <QEvent> #include <QCloseEvent> #include <QHideEvent> #include <QStyleOption> #include <QGraphicsSceneMoveEvent> #include <QGraphicsSceneResizeEvent> #include <QShowEvent> #include <QPointF> #include <QFocusEvent> #include <QGraphicsSceneHoverEvent> #include <QVariant> QHash<QByteArray, PlastiQMethod> PlastiQQGraphicsWidget::plastiqConstructors = { { "QGraphicsWidget()", { "QGraphicsWidget", "", "QGraphicsWidget*", 0, PlastiQMethod::Public, PlastiQMethod::Constructor } }, { "QGraphicsWidget(QGraphicsItem*)", { "QGraphicsWidget", "QGraphicsItem*", "QGraphicsWidget*", 1, PlastiQMethod::Public, PlastiQMethod::Constructor } }, { "QGraphicsWidget(QGraphicsItem*,enum)", { "QGraphicsWidget", "QGraphicsItem*,Qt::WindowFlags", "QGraphicsWidget*", 2, PlastiQMethod::Public, PlastiQMethod::Constructor } }, }; QHash<QByteArray, PlastiQMethod> PlastiQQGraphicsWidget::plastiqMethods = { { "addAction(QAction*)", { "addAction", "QAction*", "void", 0, PlastiQMethod::Public, PlastiQMethod::Method } }, { "adjustSize()", { "adjustSize", "", "void", 1, PlastiQMethod::Public, PlastiQMethod::Method } }, { "autoFillBackground()", { "autoFillBackground", "", "bool", 2, PlastiQMethod::Public, PlastiQMethod::Method } }, { "focusPolicy()", { "focusPolicy", "", "Qt::FocusPolicy", 3, PlastiQMethod::Public, PlastiQMethod::Method } }, { "focusWidget()", { "focusWidget", "", "QGraphicsWidget*", 4, PlastiQMethod::Public, PlastiQMethod::Method } }, { "font()", { "font", "", "QFont", 5, PlastiQMethod::Public, PlastiQMethod::Method } }, { "getWindowFrameMargins(qreal*,qreal*,qreal*,qreal*)", { "getWindowFrameMargins", "qreal*,qreal*,qreal*,qreal*", "void", 6, PlastiQMethod::Public, PlastiQMethod::Method } }, { "grabShortcut(QKeySequence&)", { "grabShortcut", "QKeySequence&", "int", 7, PlastiQMethod::Public, PlastiQMethod::Method } }, { "grabShortcut(QKeySequence&,enum)", { "grabShortcut", "QKeySequence&,Qt::ShortcutContext", "int", 8, PlastiQMethod::Public, PlastiQMethod::Method } }, { "insertAction(QAction*,QAction*)", { "insertAction", "QAction*,QAction*", "void", 9, PlastiQMethod::Public, PlastiQMethod::Method } }, { "isActiveWindow()", { "isActiveWindow", "", "bool", 10, PlastiQMethod::Public, PlastiQMethod::Method } }, { "layout()", { "layout", "", "QGraphicsLayout*", 11, PlastiQMethod::Public, PlastiQMethod::Method } }, { "layoutDirection()", { "layoutDirection", "", "Qt::LayoutDirection", 12, PlastiQMethod::Public, PlastiQMethod::Method } }, { "paintWindowFrame(QPainter*,const QStyleOptionGraphicsItem*)", { "paintWindowFrame", "QPainter*,QStyleOptionGraphicsItem*", "void", 13, PlastiQMethod::Public, PlastiQMethod::Method } }, { "paintWindowFrame(QPainter*,const QStyleOptionGraphicsItem*,QWidget*)", { "paintWindowFrame", "QPainter*,QStyleOptionGraphicsItem*,QWidget*", "void", 14, PlastiQMethod::Public, PlastiQMethod::Method } }, { "palette()", { "palette", "", "QPalette", 15, PlastiQMethod::Public, PlastiQMethod::Method } }, { "rect()", { "rect", "", "QRectF", 16, PlastiQMethod::Public, PlastiQMethod::Method } }, { "releaseShortcut(int)", { "releaseShortcut", "int", "void", 17, PlastiQMethod::Public, PlastiQMethod::Method } }, { "removeAction(QAction*)", { "removeAction", "QAction*", "void", 18, PlastiQMethod::Public, PlastiQMethod::Method } }, { "resize(QSizeF&)", { "resize", "QSizeF&", "void", 19, PlastiQMethod::Public, PlastiQMethod::Method } }, { "resize(double,double)", { "resize", "qreal,qreal", "void", 20, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setAttribute(enum)", { "setAttribute", "Qt::WidgetAttribute", "void", 21, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setAttribute(enum,bool)", { "setAttribute", "Qt::WidgetAttribute,bool", "void", 22, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setAutoFillBackground(bool)", { "setAutoFillBackground", "bool", "void", 23, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setContentsMargins(double,double,double,double)", { "setContentsMargins", "qreal,qreal,qreal,qreal", "void", 24, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setFocusPolicy(enum)", { "setFocusPolicy", "Qt::FocusPolicy", "void", 25, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setFont(QFont&)", { "setFont", "QFont&", "void", 26, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setGeometry(double,double,double,double)", { "setGeometry", "qreal,qreal,qreal,qreal", "void", 27, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setLayout(QGraphicsLayout*)", { "setLayout", "QGraphicsLayout*", "void", 28, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setLayoutDirection(enum)", { "setLayoutDirection", "Qt::LayoutDirection", "void", 29, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setPalette(QPalette&)", { "setPalette", "QPalette&", "void", 30, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setShortcutAutoRepeat(int)", { "setShortcutAutoRepeat", "int", "void", 31, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setShortcutAutoRepeat(int,bool)", { "setShortcutAutoRepeat", "int,bool", "void", 32, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setShortcutEnabled(int)", { "setShortcutEnabled", "int", "void", 33, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setShortcutEnabled(int,bool)", { "setShortcutEnabled", "int,bool", "void", 34, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setStyle(QStyle*)", { "setStyle", "QStyle*", "void", 35, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setWindowFlags(enum)", { "setWindowFlags", "Qt::WindowFlags", "void", 36, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setWindowFrameMargins(double,double,double,double)", { "setWindowFrameMargins", "qreal,qreal,qreal,qreal", "void", 37, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setWindowTitle(QString)", { "setWindowTitle", "QString&", "void", 38, PlastiQMethod::Public, PlastiQMethod::Method } }, { "size()", { "size", "", "QSizeF", 39, PlastiQMethod::Public, PlastiQMethod::Method } }, { "style()", { "style", "", "QStyle*", 40, PlastiQMethod::Public, PlastiQMethod::Method } }, { "testAttribute(enum)", { "testAttribute", "Qt::WidgetAttribute", "bool", 41, PlastiQMethod::Public, PlastiQMethod::Method } }, { "unsetLayoutDirection()", { "unsetLayoutDirection", "", "void", 42, PlastiQMethod::Public, PlastiQMethod::Method } }, { "unsetWindowFrameMargins()", { "unsetWindowFrameMargins", "", "void", 43, PlastiQMethod::Public, PlastiQMethod::Method } }, { "windowFlags()", { "windowFlags", "", "Qt::WindowFlags", 44, PlastiQMethod::Public, PlastiQMethod::Method } }, { "windowFrameGeometry()", { "windowFrameGeometry", "", "QRectF", 45, PlastiQMethod::Public, PlastiQMethod::Method } }, { "windowFrameRect()", { "windowFrameRect", "", "QRectF", 46, PlastiQMethod::Public, PlastiQMethod::Method } }, { "windowTitle()", { "windowTitle", "", "QString", 47, PlastiQMethod::Public, PlastiQMethod::Method } }, { "windowType()", { "windowType", "", "Qt::WindowType", 48, PlastiQMethod::Public, PlastiQMethod::Method } }, { "setTabOrder(QGraphicsWidget*,QGraphicsWidget*)", { "setTabOrder", "QGraphicsWidget*,QGraphicsWidget*", "void", 49, PlastiQMethod::StaticPublic, PlastiQMethod::Method } }, { "changeEvent(QEvent*)", { "changeEvent", "QEvent*", "void", 50, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "closeEvent(QCloseEvent*)", { "closeEvent", "QCloseEvent*", "void", 51, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "focusNextPrevChild(bool)", { "focusNextPrevChild", "bool", "bool", 52, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "grabKeyboardEvent(QEvent*)", { "grabKeyboardEvent", "QEvent*", "void", 53, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "grabMouseEvent(QEvent*)", { "grabMouseEvent", "QEvent*", "void", 54, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "hideEvent(QHideEvent*)", { "hideEvent", "QHideEvent*", "void", 55, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "initStyleOption(QStyleOption*)", { "initStyleOption", "QStyleOption*", "void", 56, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "moveEvent(QGraphicsSceneMoveEvent*)", { "moveEvent", "QGraphicsSceneMoveEvent*", "void", 57, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "polishEvent()", { "polishEvent", "", "void", 58, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "resizeEvent(QGraphicsSceneResizeEvent*)", { "resizeEvent", "QGraphicsSceneResizeEvent*", "void", 59, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "showEvent(QShowEvent*)", { "showEvent", "QShowEvent*", "void", 60, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "ungrabKeyboardEvent(QEvent*)", { "ungrabKeyboardEvent", "QEvent*", "void", 61, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "ungrabMouseEvent(QEvent*)", { "ungrabMouseEvent", "QEvent*", "void", 62, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "windowFrameEvent(QEvent*)", { "windowFrameEvent", "QEvent*", "bool", 63, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "windowFrameSectionAt(QPointF&)", { "windowFrameSectionAt", "QPointF&", "Qt::WindowFrameSection", 64, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "event(QEvent*)", { "event", "QEvent*", "bool", 65, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "focusInEvent(QFocusEvent*)", { "focusInEvent", "QFocusEvent*", "void", 66, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "focusOutEvent(QFocusEvent*)", { "focusOutEvent", "QFocusEvent*", "void", 67, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "hoverLeaveEvent(QGraphicsSceneHoverEvent*)", { "hoverLeaveEvent", "QGraphicsSceneHoverEvent*", "void", 68, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "hoverMoveEvent(QGraphicsSceneHoverEvent*)", { "hoverMoveEvent", "QGraphicsSceneHoverEvent*", "void", 69, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "itemChange(GraphicsItemChange,QVariant)", { "itemChange", "GraphicsItemChange,QVariant&", "QVariant", 70, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "sceneEvent(QEvent*)", { "sceneEvent", "QEvent*", "bool", 71, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "sizeHint(enum)", { "sizeHint", "Qt::SizeHint", "QSizeF", 72, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "sizeHint(enum,QSizeF&)", { "sizeHint", "Qt::SizeHint,QSizeF&", "QSizeF", 73, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "updateGeometry()", { "updateGeometry", "", "void", 74, PlastiQMethod::VirtualProtected, PlastiQMethod::Method } }, { "close()", { "close", "", "bool", 75, PlastiQMethod::Public, PlastiQMethod::Slot } }, }; QHash<QByteArray, PlastiQMethod> PlastiQQGraphicsWidget::plastiqSignals = { { "geometryChanged()", { "geometryChanged", "", "void", 0, PlastiQMethod::Public, PlastiQMethod::Signal } }, }; QHash<QByteArray, PlastiQProperty> PlastiQQGraphicsWidget::plastiqProperties = { { "autoFillBackground", { "autoFillBackground", "bool", "setAutoFillBackground", "autoFillBackground" } }, { "focusPolicy", { "focusPolicy", "long", "setFocusPolicy", "focusPolicy" } }, { "font", { "font", "QFont", "setFont", "font" } }, { "geometry", { "geometry", "QRectF", "setGeometry", "" } }, { "layout", { "layout", "QGraphicsLayout*", "setLayout", "layout" } }, { "layoutDirection", { "layoutDirection", "long", "setLayoutDirection", "layoutDirection" } }, { "maximumSize", { "maximumSize", "QSizeF", "", "" } }, { "minimumSize", { "minimumSize", "QSizeF", "", "" } }, { "palette", { "palette", "QPalette", "setPalette", "palette" } }, { "preferredSize", { "preferredSize", "QSizeF", "", "" } }, { "size", { "size", "QSizeF", "resize", "size" } }, { "sizePolicy", { "sizePolicy", "QSizePolicy", "", "" } }, { "windowFlags", { "windowFlags", "long", "setWindowFlags", "windowFlags" } }, { "windowTitle", { "windowTitle", "QString", "setWindowTitle", "windowTitle" } }, }; QHash<QByteArray, long> PlastiQQGraphicsWidget::plastiqConstants = { }; QVector<PlastiQMetaObject*> PlastiQQGraphicsWidget::plastiqInherits = { &PlastiQQGraphicsObject::plastiq_static_metaObject, &PlastiQQGraphicsLayoutItem::plastiq_static_metaObject }; const PlastiQ::ObjectType PlastiQQGraphicsWidget::plastiq_static_objectType = PlastiQ::IsQObject; PlastiQMetaObject PlastiQQGraphicsWidget::plastiq_static_metaObject = { { &PlastiQQGraphicsObject::plastiq_static_metaObject, &plastiqInherits, "QGraphicsWidget", &plastiq_static_objectType, &plastiqConstructors, &plastiqMethods, &plastiqSignals, &plastiqProperties, &plastiqConstants, plastiq_static_metacall } }; const PlastiQMetaObject *PlastiQQGraphicsWidget::plastiq_metaObject() const { return &plastiq_static_metaObject; } class PlastiQQGraphicsWidgetWrapper : public QGraphicsWidget { public: VirtualMethodList *virtualMethodList; PQObjectWrapper *pqObjectWPtr; explicit PlastiQQGraphicsWidgetWrapper(QGraphicsItem *parent = Q_NULLPTR, Qt::WindowFlags wFlags = Qt::WindowFlags()) : QGraphicsWidget(parent,wFlags), virtualMethodList(Q_NULLPTR), pqObjectWPtr(Q_NULLPTR) {} void paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) override { static const QByteArray methodSignature = QByteArrayLiteral("void paintWindowFrame(QPainter*,const QStyleOptionGraphicsItem*,QWidget*=)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[4]; stack[1].s_voidp = reinterpret_cast<void*>(painter); stack[1].name = QByteArrayLiteral("QPainter"); stack[1].type = PlastiQ::QtObjectStar; stack[2].s_voidp = reinterpret_cast<void*>(const_cast<QStyleOptionGraphicsItem*>(option)); stack[2].name = QByteArrayLiteral("QStyleOptionGraphicsItem"); stack[2].type = PlastiQ::QtObjectStar; stack[3].s_voidp = reinterpret_cast<void*>(widget); stack[3].name = QByteArrayLiteral("QWidget"); stack[3].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::paintWindowFrame(painter,option,widget); } void PlastiQParentCall_paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) { return QGraphicsWidget::paintWindowFrame(painter,option,widget); } void changeEvent(QEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void changeEvent(QEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::changeEvent(event); } void PlastiQParentCall_changeEvent(QEvent *event) { return QGraphicsWidget::changeEvent(event); } void closeEvent(QCloseEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void closeEvent(QCloseEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QCloseEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::closeEvent(event); } void PlastiQParentCall_closeEvent(QCloseEvent *event) { return QGraphicsWidget::closeEvent(event); } bool focusNextPrevChild(bool next) override { static const QByteArray methodSignature = QByteArrayLiteral("bool focusNextPrevChild(bool)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_bool = next; stack[1].name = QByteArrayLiteral("bool"); stack[1].type = PlastiQ::Bool; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); bool _r = stack[0].s_bool; delete [] stack; return _r; } else return QGraphicsWidget::focusNextPrevChild(next); } bool PlastiQParentCall_focusNextPrevChild(bool next) { return QGraphicsWidget::focusNextPrevChild(next); } void grabKeyboardEvent(QEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void grabKeyboardEvent(QEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::grabKeyboardEvent(event); } void PlastiQParentCall_grabKeyboardEvent(QEvent *event) { return QGraphicsWidget::grabKeyboardEvent(event); } void grabMouseEvent(QEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void grabMouseEvent(QEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::grabMouseEvent(event); } void PlastiQParentCall_grabMouseEvent(QEvent *event) { return QGraphicsWidget::grabMouseEvent(event); } void hideEvent(QHideEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void hideEvent(QHideEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QHideEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::hideEvent(event); } void PlastiQParentCall_hideEvent(QHideEvent *event) { return QGraphicsWidget::hideEvent(event); } void initStyleOption(QStyleOption *option) const override { static const QByteArray methodSignature = QByteArrayLiteral("void initStyleOption(QStyleOption*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(option); stack[1].name = QByteArrayLiteral("QStyleOption"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::initStyleOption(option); } void PlastiQParentCall_initStyleOption(QStyleOption *option) const { return QGraphicsWidget::initStyleOption(option); } void moveEvent(QGraphicsSceneMoveEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void moveEvent(QGraphicsSceneMoveEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QGraphicsSceneMoveEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::moveEvent(event); } void PlastiQParentCall_moveEvent(QGraphicsSceneMoveEvent *event) { return QGraphicsWidget::moveEvent(event); } void polishEvent() override { static const QByteArray methodSignature = QByteArrayLiteral("void polishEvent()"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[1]; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::polishEvent(); } void PlastiQParentCall_polishEvent() { return QGraphicsWidget::polishEvent(); } void resizeEvent(QGraphicsSceneResizeEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void resizeEvent(QGraphicsSceneResizeEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QGraphicsSceneResizeEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::resizeEvent(event); } void PlastiQParentCall_resizeEvent(QGraphicsSceneResizeEvent *event) { return QGraphicsWidget::resizeEvent(event); } void showEvent(QShowEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void showEvent(QShowEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QShowEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::showEvent(event); } void PlastiQParentCall_showEvent(QShowEvent *event) { return QGraphicsWidget::showEvent(event); } void ungrabKeyboardEvent(QEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void ungrabKeyboardEvent(QEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::ungrabKeyboardEvent(event); } void PlastiQParentCall_ungrabKeyboardEvent(QEvent *event) { return QGraphicsWidget::ungrabKeyboardEvent(event); } void ungrabMouseEvent(QEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void ungrabMouseEvent(QEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::ungrabMouseEvent(event); } void PlastiQParentCall_ungrabMouseEvent(QEvent *event) { return QGraphicsWidget::ungrabMouseEvent(event); } bool windowFrameEvent(QEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("bool windowFrameEvent(QEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); bool _r = stack[0].s_bool; delete [] stack; return _r; } else return QGraphicsWidget::windowFrameEvent(event); } bool PlastiQParentCall_windowFrameEvent(QEvent *event) { return QGraphicsWidget::windowFrameEvent(event); } Qt::WindowFrameSection windowFrameSectionAt(const QPointF &pos) const override { static const QByteArray methodSignature = QByteArrayLiteral("Qt::WindowFrameSection windowFrameSectionAt(const QPointF&)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = new QPointF(pos) /* COPY OBJECT */; stack[1].name = QByteArrayLiteral("QPointF"); stack[1].type = PlastiQ::QtObject; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); Qt::WindowFrameSection _r = Qt::WindowFrameSection(stack[0].s_int64); delete [] stack; return _r; } else return QGraphicsWidget::windowFrameSectionAt(pos); } Qt::WindowFrameSection PlastiQParentCall_windowFrameSectionAt(const QPointF &pos) const { return QGraphicsWidget::windowFrameSectionAt(pos); } bool event(QEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("bool event(QEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); bool _r = stack[0].s_bool; delete [] stack; return _r; } else return QGraphicsWidget::event(event); } bool PlastiQParentCall_event(QEvent *event) { return QGraphicsWidget::event(event); } void focusInEvent(QFocusEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void focusInEvent(QFocusEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QFocusEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::focusInEvent(event); } void PlastiQParentCall_focusInEvent(QFocusEvent *event) { return QGraphicsWidget::focusInEvent(event); } void focusOutEvent(QFocusEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void focusOutEvent(QFocusEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QFocusEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::focusOutEvent(event); } void PlastiQParentCall_focusOutEvent(QFocusEvent *event) { return QGraphicsWidget::focusOutEvent(event); } void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void hoverLeaveEvent(QGraphicsSceneHoverEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QGraphicsSceneHoverEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::hoverLeaveEvent(event); } void PlastiQParentCall_hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { return QGraphicsWidget::hoverLeaveEvent(event); } void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("void hoverMoveEvent(QGraphicsSceneHoverEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QGraphicsSceneHoverEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::hoverMoveEvent(event); } void PlastiQParentCall_hoverMoveEvent(QGraphicsSceneHoverEvent *event) { return QGraphicsWidget::hoverMoveEvent(event); } bool sceneEvent(QEvent *event) override { static const QByteArray methodSignature = QByteArrayLiteral("bool sceneEvent(QEvent*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = reinterpret_cast<void*>(event); stack[1].name = QByteArrayLiteral("QEvent"); stack[1].type = PlastiQ::QtObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); bool _r = stack[0].s_bool; delete [] stack; return _r; } else return QGraphicsWidget::sceneEvent(event); } bool PlastiQParentCall_sceneEvent(QEvent *event) { return QGraphicsWidget::sceneEvent(event); } QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const override { static const QByteArray methodSignature = QByteArrayLiteral("QSizeF sizeHint(Qt::SizeHint,const QSizeF&=)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[3]; stack[1].s_int64 = which; stack[1].name = QByteArrayLiteral("Qt::SizeHint"); stack[1].type = PlastiQ::Enum; stack[2].s_voidp = new QSizeF(constraint) /* COPY OBJECT */; stack[2].name = QByteArrayLiteral("QSizeF"); stack[2].type = PlastiQ::QtObject; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); QSizeF _r = QSizeF(*reinterpret_cast<QSizeF*>(stack[0].s_voidp)); delete [] stack; return _r; } else return QGraphicsWidget::sizeHint(which,constraint); } QSizeF PlastiQParentCall_sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const { return QGraphicsWidget::sizeHint(which,constraint); } void updateGeometry() override { static const QByteArray methodSignature = QByteArrayLiteral("void updateGeometry()"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[1]; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::updateGeometry(); } void PlastiQParentCall_updateGeometry() { return QGraphicsWidget::updateGeometry(); } void getContentsMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const override { static const QByteArray methodSignature = QByteArrayLiteral("void getContentsMargins(qreal*,qreal*,qreal*,qreal*)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[5]; stack[1].s_voidp = reinterpret_cast<void*>(left); stack[1].name = QByteArrayLiteral("qreal"); stack[1].type = PlastiQ::ObjectStar; stack[2].s_voidp = reinterpret_cast<void*>(top); stack[2].name = QByteArrayLiteral("qreal"); stack[2].type = PlastiQ::ObjectStar; stack[3].s_voidp = reinterpret_cast<void*>(right); stack[3].name = QByteArrayLiteral("qreal"); stack[3].type = PlastiQ::ObjectStar; stack[4].s_voidp = reinterpret_cast<void*>(bottom); stack[4].name = QByteArrayLiteral("qreal"); stack[4].type = PlastiQ::ObjectStar; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::getContentsMargins(left,top,right,bottom); } void PlastiQParentCall_getContentsMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const { return QGraphicsWidget::getContentsMargins(left,top,right,bottom); } void setGeometry(const QRectF &rect) override { static const QByteArray methodSignature = QByteArrayLiteral("void setGeometry(const QRectF&)"); if (virtualMethodList->contains(methodSignature)) { PMOGStack stack = new PMOGStackItem[2]; stack[1].s_voidp = new QRectF(rect) /* COPY OBJECT */; stack[1].name = QByteArrayLiteral("QRectF"); stack[1].type = PlastiQ::QtObject; virtualMethodList->value(methodSignature).call(pqObjectWPtr, stack); delete [] stack; } else return QGraphicsWidget::setGeometry(rect); } void PlastiQParentCall_setGeometry(const QRectF &rect) { return QGraphicsWidget::setGeometry(rect); } }; void PlastiQQGraphicsWidget::plastiq_static_metacall(PlastiQObject *object, PlastiQMetaObject::Call call, int id, const PMOGStack &stack) { if(call == PlastiQMetaObject::CreateInstance) { PlastiQQGraphicsWidgetWrapper *o = Q_NULLPTR; switch(id) { case 0: o = new PlastiQQGraphicsWidgetWrapper(); break; case 1: o = new PlastiQQGraphicsWidgetWrapper(reinterpret_cast<QGraphicsItem*>(stack[1].s_voidp)); break; case 2: o = new PlastiQQGraphicsWidgetWrapper(reinterpret_cast<QGraphicsItem*>(stack[1].s_voidp), Qt::WindowFlags(stack[2].s_int64)); break; default: ; } o->virtualMethodList = reinterpret_cast<VirtualMethodList*>(stack[0].s_voidp); o->pqObjectWPtr = stack[0].s_pqobject; PlastiQQGraphicsWidget *p = new PlastiQQGraphicsWidget(); p->plastiq_setData(reinterpret_cast<void*>(o), p); PlastiQObject *po = static_cast<PlastiQObject*>(p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = po; } else if(call == PlastiQMetaObject::CreateDataInstance) { PlastiQQGraphicsWidget *p = new PlastiQQGraphicsWidget(); p->plastiq_setData(stack[1].s_voidp, p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = p; } else if(call == PlastiQMetaObject::InvokeMethod || call == PlastiQMetaObject::InvokeStaticMember) { if(id >= 76) { id -= 76; PlastiQQGraphicsObject::plastiq_static_metaObject.d.static_metacall(object, call, id, stack); return; } bool sc = call == PlastiQMetaObject::InvokeStaticMember; bool isWrapper = sc ? false : object->isWrapper(); QGraphicsWidget *o = sc ? Q_NULLPTR : reinterpret_cast<QGraphicsWidget*>(object->plastiq_data()); switch(id) { case 0: o->addAction(reinterpret_cast<QAction*>(stack[1].s_voidp)); stack[0].type = PlastiQ::Void; break; case 1: o->adjustSize(); stack[0].type = PlastiQ::Void; break; case 2: { bool _r = o->autoFillBackground(); stack[0].s_bool = _r; stack[0].type = PlastiQ::Bool; } break; case 3: { qint64 _r = o->focusPolicy(); // HACK for Qt::FocusPolicy stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break; case 4: { QGraphicsWidget* _r = o->focusWidget(); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].type = PlastiQ::QObjectStar; stack[0].name = "QGraphicsWidget"; } break; case 5: { /* COPY OBJECT */ QFont *_r = new QFont(o->font()); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QFont"; stack[0].type = PlastiQ::QtObject; } break; case 6: o->getWindowFrameMargins(reinterpret_cast<qreal*>(stack[1].s_voidp), reinterpret_cast<qreal*>(stack[2].s_voidp), reinterpret_cast<qreal*>(stack[3].s_voidp), reinterpret_cast<qreal*>(stack[4].s_voidp)); stack[0].type = PlastiQ::Void; break; case 7: { int _r = o->grabShortcut((*reinterpret_cast< QKeySequence(*) >(stack[1].s_voidp))); stack[0].s_int = _r; stack[0].type = PlastiQ::Int; } break; case 8: { int _r = o->grabShortcut((*reinterpret_cast< QKeySequence(*) >(stack[1].s_voidp)), Qt::ShortcutContext(stack[2].s_int64)); stack[0].s_int = _r; stack[0].type = PlastiQ::Int; } break; case 9: o->insertAction(reinterpret_cast<QAction*>(stack[1].s_voidp), reinterpret_cast<QAction*>(stack[2].s_voidp)); stack[0].type = PlastiQ::Void; break; case 10: { bool _r = o->isActiveWindow(); stack[0].s_bool = _r; stack[0].type = PlastiQ::Bool; } break; case 11: { QGraphicsLayout* _r = o->layout(); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].type = PlastiQ::QtObjectStar; stack[0].name = "QGraphicsLayout"; } break; case 12: { qint64 _r = o->layoutDirection(); // HACK for Qt::LayoutDirection stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break; case 13: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_paintWindowFrame(reinterpret_cast<QPainter*>(stack[1].s_voidp), reinterpret_cast<const QStyleOptionGraphicsItem*>(stack[2].s_voidp)); else o->paintWindowFrame(reinterpret_cast<QPainter*>(stack[1].s_voidp), reinterpret_cast<const QStyleOptionGraphicsItem*>(stack[2].s_voidp)); stack[0].type = PlastiQ::Void; break; case 14: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_paintWindowFrame(reinterpret_cast<QPainter*>(stack[1].s_voidp), reinterpret_cast<const QStyleOptionGraphicsItem*>(stack[2].s_voidp), reinterpret_cast<QWidget*>(stack[3].s_voidp)); else o->paintWindowFrame(reinterpret_cast<QPainter*>(stack[1].s_voidp), reinterpret_cast<const QStyleOptionGraphicsItem*>(stack[2].s_voidp), reinterpret_cast<QWidget*>(stack[3].s_voidp)); stack[0].type = PlastiQ::Void; break; case 15: { /* COPY OBJECT */ QPalette *_r = new QPalette(o->palette()); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QPalette"; stack[0].type = PlastiQ::QtObject; } break; case 16: { /* COPY OBJECT */ QRectF *_r = new QRectF(o->rect()); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QRectF"; stack[0].type = PlastiQ::QtObject; } break; case 17: o->releaseShortcut(stack[1].s_int); stack[0].type = PlastiQ::Void; break; case 18: o->removeAction(reinterpret_cast<QAction*>(stack[1].s_voidp)); stack[0].type = PlastiQ::Void; break; case 19: o->resize((*reinterpret_cast< QSizeF(*) >(stack[1].s_voidp))); stack[0].type = PlastiQ::Void; break; case 20: o->resize(stack[1].s_double, stack[2].s_double); stack[0].type = PlastiQ::Void; break; case 21: o->setAttribute(Qt::WidgetAttribute(stack[1].s_int64)); stack[0].type = PlastiQ::Void; break; case 22: o->setAttribute(Qt::WidgetAttribute(stack[1].s_int64), stack[2].s_bool); stack[0].type = PlastiQ::Void; break; case 23: o->setAutoFillBackground(stack[1].s_bool); stack[0].type = PlastiQ::Void; break; case 24: o->setContentsMargins(stack[1].s_double, stack[2].s_double, stack[3].s_double, stack[4].s_double); stack[0].type = PlastiQ::Void; break; case 25: o->setFocusPolicy(Qt::FocusPolicy(stack[1].s_int64)); stack[0].type = PlastiQ::Void; break; case 26: o->setFont((*reinterpret_cast< QFont(*) >(stack[1].s_voidp))); stack[0].type = PlastiQ::Void; break; case 27: o->setGeometry(stack[1].s_double, stack[2].s_double, stack[3].s_double, stack[4].s_double); stack[0].type = PlastiQ::Void; break; case 28: o->setLayout(reinterpret_cast<QGraphicsLayout*>(stack[1].s_voidp)); stack[0].type = PlastiQ::Void; break; case 29: o->setLayoutDirection(Qt::LayoutDirection(stack[1].s_int64)); stack[0].type = PlastiQ::Void; break; case 30: o->setPalette((*reinterpret_cast< QPalette(*) >(stack[1].s_voidp))); stack[0].type = PlastiQ::Void; break; case 31: o->setShortcutAutoRepeat(stack[1].s_int); stack[0].type = PlastiQ::Void; break; case 32: o->setShortcutAutoRepeat(stack[1].s_int, stack[2].s_bool); stack[0].type = PlastiQ::Void; break; case 33: o->setShortcutEnabled(stack[1].s_int); stack[0].type = PlastiQ::Void; break; case 34: o->setShortcutEnabled(stack[1].s_int, stack[2].s_bool); stack[0].type = PlastiQ::Void; break; case 35: o->setStyle(reinterpret_cast<QStyle*>(stack[1].s_voidp)); stack[0].type = PlastiQ::Void; break; case 36: o->setWindowFlags(Qt::WindowFlags(stack[1].s_int64)); stack[0].type = PlastiQ::Void; break; case 37: o->setWindowFrameMargins(stack[1].s_double, stack[2].s_double, stack[3].s_double, stack[4].s_double); stack[0].type = PlastiQ::Void; break; case 38: o->setWindowTitle(stack[1].s_string); stack[0].type = PlastiQ::Void; break; case 39: { /* COPY OBJECT */ QSizeF *_r = new QSizeF(o->size()); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QSizeF"; stack[0].type = PlastiQ::QtObject; } break; case 40: { QStyle* _r = o->style(); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].type = PlastiQ::QObjectStar; stack[0].name = "QStyle"; } break; case 41: { bool _r = o->testAttribute(Qt::WidgetAttribute(stack[1].s_int64)); stack[0].s_bool = _r; stack[0].type = PlastiQ::Bool; } break; case 42: o->unsetLayoutDirection(); stack[0].type = PlastiQ::Void; break; case 43: o->unsetWindowFrameMargins(); stack[0].type = PlastiQ::Void; break; case 44: { qint64 _r = o->windowFlags(); // HACK for Qt::WindowFlags stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break; case 45: { /* COPY OBJECT */ QRectF *_r = new QRectF(o->windowFrameGeometry()); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QRectF"; stack[0].type = PlastiQ::QtObject; } break; case 46: { /* COPY OBJECT */ QRectF *_r = new QRectF(o->windowFrameRect()); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QRectF"; stack[0].type = PlastiQ::QtObject; } break; case 47: { QString _r = o->windowTitle(); stack[0].s_string = _r; stack[0].type = PlastiQ::String; } break; case 48: { qint64 _r = o->windowType(); // HACK for Qt::WindowType stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break; case 49: if(sc) { QGraphicsWidget::setTabOrder(reinterpret_cast<QGraphicsWidget*>(stack[1].s_voidp), reinterpret_cast<QGraphicsWidget*>(stack[2].s_voidp)); } else { o->setTabOrder(reinterpret_cast<QGraphicsWidget*>(stack[1].s_voidp), reinterpret_cast<QGraphicsWidget*>(stack[2].s_voidp)); } stack[0].type = PlastiQ::Void; break; case 50: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_changeEvent(reinterpret_cast<QEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 51: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_closeEvent(reinterpret_cast<QCloseEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 52: { bool _r; if (isWrapper) _r = ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_focusNextPrevChild(stack[1].s_bool); else { stack[0].type = PlastiQ::Error; return; } stack[0].s_bool = _r; stack[0].type = PlastiQ::Bool; } break; case 53: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_grabKeyboardEvent(reinterpret_cast<QEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 54: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_grabMouseEvent(reinterpret_cast<QEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 55: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_hideEvent(reinterpret_cast<QHideEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 56: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_initStyleOption(reinterpret_cast<QStyleOption*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 57: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_moveEvent(reinterpret_cast<QGraphicsSceneMoveEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 58: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_polishEvent(); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 59: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_resizeEvent(reinterpret_cast<QGraphicsSceneResizeEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 60: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_showEvent(reinterpret_cast<QShowEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 61: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_ungrabKeyboardEvent(reinterpret_cast<QEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 62: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_ungrabMouseEvent(reinterpret_cast<QEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 63: { bool _r; if (isWrapper) _r = ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_windowFrameEvent(reinterpret_cast<QEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].s_bool = _r; stack[0].type = PlastiQ::Bool; } break; case 64: { qint64 _r; if (isWrapper) _r = ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_windowFrameSectionAt((*reinterpret_cast< QPointF(*) >(stack[1].s_voidp))); else { stack[0].type = PlastiQ::Error; return; } stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break; case 65: { bool _r; if (isWrapper) _r = ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_event(reinterpret_cast<QEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].s_bool = _r; stack[0].type = PlastiQ::Bool; } break; case 66: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_focusInEvent(reinterpret_cast<QFocusEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 67: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_focusOutEvent(reinterpret_cast<QFocusEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 68: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_hoverLeaveEvent(reinterpret_cast<QGraphicsSceneHoverEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 69: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_hoverMoveEvent(reinterpret_cast<QGraphicsSceneHoverEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 70: /* o->itemChange(UNSUPPORTED_TYPE_GraphicsItemChange, stack[2].s_variant) | ret: `QVariant` */ break; case 71: { bool _r; if (isWrapper) _r = ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_sceneEvent(reinterpret_cast<QEvent*>(stack[1].s_voidp)); else { stack[0].type = PlastiQ::Error; return; } stack[0].s_bool = _r; stack[0].type = PlastiQ::Bool; } break; case 72: { /* COPY OBJECT */ QSizeF *_r; if (isWrapper) _r = new QSizeF(((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_sizeHint(Qt::SizeHint(stack[1].s_int64))); else { stack[0].type = PlastiQ::Error; return; } reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QSizeF"; stack[0].type = PlastiQ::QtObject; } break; case 73: { /* COPY OBJECT */ QSizeF *_r; if (isWrapper) _r = new QSizeF(((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_sizeHint(Qt::SizeHint(stack[1].s_int64), (*reinterpret_cast< QSizeF(*) >(stack[2].s_voidp)))); else { stack[0].type = PlastiQ::Error; return; } reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QSizeF"; stack[0].type = PlastiQ::QtObject; } break; case 74: if (isWrapper) ((PlastiQQGraphicsWidgetWrapper*)o)->PlastiQParentCall_updateGeometry(); else { stack[0].type = PlastiQ::Error; return; } stack[0].type = PlastiQ::Void; break; case 75: { bool _r = o->close(); stack[0].s_bool = _r; stack[0].type = PlastiQ::Bool; } break; default: ; } } else if(call == PlastiQMetaObject::CreateConnection) { if(id >= 1) { id -= 1; PlastiQQGraphicsObject::plastiq_static_metaObject.d.static_metacall(object, call, id, stack); return; } QGraphicsWidget *o = reinterpret_cast<QGraphicsWidget*>(object->plastiq_data()); PQObjectWrapper *sender = reinterpret_cast<PQObjectWrapper *>(stack[1].s_voidp); PQObjectWrapper *receiver = reinterpret_cast<PQObjectWrapper *>(stack[2].s_voidp); QByteArray slot = stack[3].s_bytearray; switch(id) { case 0: QObject::connect(o, &QGraphicsWidget::geometryChanged, [=]() { PMOGStack cstack = new PMOGStackItem[0]; PlastiQ_activate(sender, "geometryChanged", receiver, slot.constData(), 0, cstack); delete [] cstack; cstack = 0; }); break; default: ; } } else if(call == PlastiQMetaObject::ToQObject) { QGraphicsWidget *o = reinterpret_cast<QGraphicsWidget*>(object->plastiq_data()); QObject *qo = qobject_cast<QObject*>(o); *reinterpret_cast<QObject**>(stack[0].s_voidpp) = qo; } else if(call == PlastiQMetaObject::HaveParent) { QGraphicsWidget *o = reinterpret_cast<QGraphicsWidget*>(object->plastiq_data()); stack[0].s_bool = o->parent() != Q_NULLPTR; } else if(call == PlastiQMetaObject::DownCast) { QByteArray className = stack[1].s_bytearray; QGraphicsWidget *o = reinterpret_cast<QGraphicsWidget*>(object->plastiq_data()); if(className == "QGraphicsObject") { stack[0].s_voidp = static_cast<QGraphicsObject*>(o); } else if(className == "QGraphicsLayoutItem") { stack[0].s_voidp = static_cast<QGraphicsLayoutItem*>(o); } else { stack[0].s_voidp = Q_NULLPTR; stack[0].name = "Q_NULLPTR"; } } } PlastiQQGraphicsWidget::~PlastiQQGraphicsWidget() { QGraphicsWidget* o = reinterpret_cast<QGraphicsWidget*>(plastiq_data()); if(o != Q_NULLPTR) { delete o; } o = Q_NULLPTR; plastiq_setData(Q_NULLPTR, Q_NULLPTR); }
mpl-2.0
itesla/ipst-core
iidm/iidm-impl/src/main/java/eu/itesla_project/iidm/network/impl/ShuntCompensatorAdderImpl.java
2402
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.iidm.network.impl; import eu.itesla_project.iidm.network.ShuntCompensatorAdder; /** * * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ class ShuntCompensatorAdderImpl extends AbstractInjectionAdder<ShuntCompensatorAdderImpl> implements ShuntCompensatorAdder { private final VoltageLevelExt voltageLevel; private float bPerSection; private int maximumSectionCount; private int currentSectionCount; ShuntCompensatorAdderImpl(VoltageLevelExt voltageLevel) { this.voltageLevel = voltageLevel; } @Override protected NetworkImpl getNetwork() { return voltageLevel.getNetwork(); } @Override protected String getTypeDescription() { return "Shunt compensator"; } @Override public ShuntCompensatorAdder setbPerSection(float bPerSection) { this.bPerSection = bPerSection; return this; } @Override public ShuntCompensatorAdder setMaximumSectionCount(int maximumSectionCount) { this.maximumSectionCount = maximumSectionCount; return this; } @Override public ShuntCompensatorAdder setCurrentSectionCount(int currentSectionCount) { this.currentSectionCount = currentSectionCount; return this; } @Override public ShuntCompensatorImpl add() { String id = checkAndGetUniqueId(); TerminalExt terminal = checkAndGetTerminal(id); ValidationUtil.checkbPerSection(this, bPerSection); ValidationUtil.checkSections(this, currentSectionCount, maximumSectionCount); ShuntCompensatorImpl shunt = new ShuntCompensatorImpl(getNetwork().getRef(), id, getName(), bPerSection, maximumSectionCount, currentSectionCount); shunt.addTerminal(terminal); voltageLevel.attach(terminal, false); getNetwork().getObjectStore().checkAndAdd(shunt); getNetwork().getListeners().notifyCreation(shunt); return shunt; } }
mpl-2.0
lucksus/PJob
src/PJobFile/PJobResultFile.cpp
809
#include "PJobResultFile.h" PJobResultFile::PJobResultFile(void) { m_type = PJobResultFile::SINGLE_VALUE; } QString PJobResultFile::filename() const{ return m_filename; } void PJobResultFile::setFilename(QString filename){ m_filename = filename; } QList<PJobResult> PJobResultFile::results() const{ return m_results; } void PJobResultFile::addResult(PJobResult r){ m_results.append(r); } void PJobResultFile::removeResult(QString resultName){ QList<PJobResult>::iterator it; for(it = m_results.begin();it != m_results.end(); ++it) if(it->name() == resultName){ m_results.erase(it); return; } } PJobResultFile::Type PJobResultFile::type() const{ return m_type; } void PJobResultFile::setType(PJobResultFile::Type type){ m_type = type; }
mpl-2.0
PawelGutkowski/openmrs-module-webservices.rest
omod-1.9/src/main/java/org/openmrs/module/webservices/rest/web/v1_0/resource/openmrs1_9/CustomDatatypeHandlerResource1_9.java
3563
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.webservices.rest.web.v1_0.resource.openmrs1_9; import org.openmrs.module.webservices.rest.web.RequestContext; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.annotation.SubResource; import org.openmrs.module.webservices.rest.web.representation.Representation; import org.openmrs.module.webservices.rest.web.resource.api.PageableResult; import org.openmrs.module.webservices.rest.web.resource.impl.DelegatingResourceDescription; import org.openmrs.module.webservices.rest.web.resource.impl.DelegatingSubResource; import org.openmrs.module.webservices.rest.web.resource.impl.NeedsPaging; import org.openmrs.module.webservices.rest.web.response.ResourceDoesNotSupportOperationException; import org.openmrs.module.webservices.rest.web.response.ResponseException; @SubResource(parent = CustomDatatypeResource1_9.class, path = "handlers", supportedClass = CustomDatatypeHandlerRepresentation.class, supportedOpenmrsVersions = { "1.9.*", "1.10.*", "1.11.*", "1.12.*", "2.0.*", "2.1.*" }) public class CustomDatatypeHandlerResource1_9 extends DelegatingSubResource<CustomDatatypeHandlerRepresentation, CustomDatatypeRepresentation, CustomDatatypeResource1_9> { @Override public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("handlerClassname"); description.addProperty("display", "textToDisplay"); description.addSelfLink(); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); return description; } @Override public CustomDatatypeHandlerRepresentation newDelegate() { return new CustomDatatypeHandlerRepresentation(); } @Override public CustomDatatypeHandlerRepresentation save(CustomDatatypeHandlerRepresentation delegate) { throw new ResourceDoesNotSupportOperationException(); } @Override public CustomDatatypeRepresentation getParent(CustomDatatypeHandlerRepresentation instance) { return instance.getParent(); } @Override public void setParent(CustomDatatypeHandlerRepresentation instance, CustomDatatypeRepresentation parent) { throw new ResourceDoesNotSupportOperationException(); } @Override public PageableResult doGetAll(CustomDatatypeRepresentation parent, RequestContext context) throws ResponseException { return new NeedsPaging<CustomDatatypeHandlerRepresentation>(parent.getHandlers(), context); } @Override public CustomDatatypeHandlerRepresentation getByUniqueId(String uniqueId) { throw new ResourceDoesNotSupportOperationException(); } @Override protected void delete(CustomDatatypeHandlerRepresentation delegate, String reason, RequestContext context) throws ResponseException { throw new ResourceDoesNotSupportOperationException(); } @Override public void purge(CustomDatatypeHandlerRepresentation delegate, RequestContext context) throws ResponseException { throw new ResourceDoesNotSupportOperationException(); } }
mpl-2.0
finjin/finjin-common
cpp/library/src/MemorySize.cpp
7623
//Copyright (c) 2017 Finjin // //This file is part of Finjin Common (finjin-common). // //Finjin Common is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // //This Source Code Form is subject to the terms of the Mozilla Public //License, v. 2.0. If a copy of the MPL was not distributed with this //file, You can obtain one at http://mozilla.org/MPL/2.0/. //Includes---------------------------------------------------------------------- #include "FinjinPrecompiled.hpp" #include "finjin/common/MemorySize.hpp" #include "finjin/common/Convert.hpp" using namespace Finjin::Common; //Macros------------------------------------------------------------------------ #define PARSE_MEMORY_SIZE(unitName, generatorFunction) \ { \ auto doubleString = s; \ doubleString.pop_back(unitName); \ \ double doubleValue; \ Convert::ToNumber(doubleValue, doubleString, error); \ if (error) \ FINJIN_SET_ERROR(error, FINJIN_FORMAT_ERROR_MESSAGE("Failed to parse double %1% size from '%2%'.", unitName, doubleString)); \ else \ sizeValue = generatorFunction(doubleValue); \ } //Local functions--------------------------------------------------------------- static uint64_t Bytes(double value) { return RoundToUInt64(value); } static uint64_t Kilobytes(double value) { return RoundToUInt64(MemorySize::KILOBYTE * value); } static uint64_t Megabytes(double value) { return RoundToUInt64(MemorySize::MEGABYTE * value); } static uint64_t Gigabytes(double value) { return RoundToUInt64(MemorySize::GIGABYTE * value); } static uint64_t Kibibytes(double value) { return RoundToUInt64(MemorySize::KIBIBYTE * value); } static uint64_t Mebibytes(double value) { return RoundToUInt64(MemorySize::MEBIBYTE * value); } static uint64_t Gibibytes(double value) { return RoundToUInt64(MemorySize::GIBIBYTE * value); } template <typename T, typename StringType> void ParseMemorySize(T& sizeValue, const StringType& s, Error& error) { FINJIN_ERROR_METHOD_START(error); if (s.empty()) FINJIN_SET_ERROR(error, "Failed to parse empty memory size."); else if (s.StartsWith("-")) FINJIN_SET_ERROR(error, FINJIN_FORMAT_ERROR_MESSAGE("Failed to parse non-negative memory size. Negative specifier in '%1%'.", s)); else if (s.EndsWith("kilobytes")) PARSE_MEMORY_SIZE("kilobytes", Kilobytes) else if (s.EndsWith("kilobyte")) PARSE_MEMORY_SIZE("kilobyte", Kilobytes) else if (s.EndsWith("megabytes")) PARSE_MEMORY_SIZE("megabytes", Megabytes) else if (s.EndsWith("megabyte")) PARSE_MEMORY_SIZE("megabyte", Megabytes) else if (s.EndsWith("gigabytes")) PARSE_MEMORY_SIZE("gigabytes", Gigabytes) else if (s.EndsWith("gigabyte")) PARSE_MEMORY_SIZE("gigabyte", Gigabytes) else if (s.EndsWith("kibibytes")) PARSE_MEMORY_SIZE("kibibytes", Kibibytes) else if (s.EndsWith("kibibyte")) PARSE_MEMORY_SIZE("kibibyte", Kibibytes) else if (s.EndsWith("mebibytes")) PARSE_MEMORY_SIZE("mebibytes", Mebibytes) else if (s.EndsWith("mebibyte")) PARSE_MEMORY_SIZE("mebibyte", Mebibytes) else if (s.EndsWith("gibibytes")) PARSE_MEMORY_SIZE("gibibytes", Gibibytes) else if (s.EndsWith("gibibyte")) PARSE_MEMORY_SIZE("gibibyte", Gibibytes) else if (s.EndsWith("bytes")) PARSE_MEMORY_SIZE("bytes", Bytes) else if (s.EndsWith("byte")) PARSE_MEMORY_SIZE("byte", Bytes) else if (s.EndsWith("KB")) PARSE_MEMORY_SIZE("KB", Kilobytes) else if (s.EndsWith("kB")) PARSE_MEMORY_SIZE("kB", Kilobytes) else if (s.EndsWith("MB")) PARSE_MEMORY_SIZE("MB", Megabytes) else if (s.EndsWith("mB")) PARSE_MEMORY_SIZE("mB", Megabytes) else if (s.EndsWith("GB")) PARSE_MEMORY_SIZE("GB", Gigabytes) else if (s.EndsWith("gB")) PARSE_MEMORY_SIZE("gB", Gigabytes) else if (s.EndsWith("KiB")) PARSE_MEMORY_SIZE("KiB", Kibibytes) else if (s.EndsWith("MiB")) PARSE_MEMORY_SIZE("MiB", Mebibytes) else if (s.EndsWith("GiB")) PARSE_MEMORY_SIZE("GiB", Gibibytes) else if (s.EndsWith("B") || s.IsDigits()) PARSE_MEMORY_SIZE("B", Bytes) else FINJIN_SET_ERROR(error, FINJIN_FORMAT_ERROR_MESSAGE("Failed to parse non-negative memory size. Unrecognized or unspecified memory size unit in '%1%'.", s)); } //Implementation---------------------------------------------------------------- uint32_t MemorySize::Parse32(const Utf8StringView& stringValue, uint32_t defaultValue) { FINJIN_DECLARE_ERROR(error); uint32_t parsed; Parse(parsed, stringValue, error); return error ? defaultValue : parsed; } uint64_t MemorySize::Parse64(const Utf8StringView& stringValue, uint64_t defaultValue) { FINJIN_DECLARE_ERROR(error); uint64_t parsed; Parse(parsed, stringValue, error); return error ? defaultValue : parsed; } void MemorySize::Parse(uint32_t& sizeValue, const Utf8StringView& stringValue, Error& error) { FINJIN_ERROR_METHOD_START(error); uint64_t sizeValue64; ParseMemorySize(sizeValue64, stringValue, error); if (error) { FINJIN_SET_ERROR_NO_MESSAGE(error); return; } if (sizeValue64 > std::numeric_limits<uint32_t>::max()) { FINJIN_SET_ERROR(error, FINJIN_FORMAT_ERROR_MESSAGE("'%1%' could not be converted to a 32-bit memory size. The value should be within [0 - %2%]", stringValue, std::numeric_limits<uint32_t>::max())); return; } sizeValue = static_cast<uint32_t>(sizeValue64); } void MemorySize::Parse(uint64_t& sizeValue, const Utf8StringView& stringValue, Error& error) { FINJIN_ERROR_METHOD_START(error); ParseMemorySize(sizeValue, stringValue, error); if (error) FINJIN_SET_ERROR_NO_MESSAGE(error); } #if FINJIN_TARGET_PLATFORM_IS_APPLE void MemorySize::Parse(size_t& sizeValue, const Utf8StringView& stringValue, Error& error) { FINJIN_ERROR_METHOD_START(error); ParseMemorySize(sizeValue, stringValue, error); if (error) FINJIN_SET_ERROR_NO_MESSAGE(error); } #endif Utf8String MemorySize::ToString(uint64_t bytes, uint64_t base) { if (base != KILOBYTE && base != KIBIBYTE) base = KILOBYTE; auto gb = bytes / (base * base * base); bytes -= gb * (base * base * base); auto mb = bytes / (base * base); bytes -= mb * (base * base); auto kb = bytes / base; bytes -= kb * base; Utf8String result; if (gb > 0) { result = Convert::ToString(gb); auto fractional = RoundToInt(10.0 * static_cast<double>(mb) / static_cast<double>(base * base)); if (fractional > 0) { result += "."; result += Convert::ToString(fractional); } result += base == KILOBYTE ? "GB" : "GiB"; } else if (mb > 0) { result = Convert::ToString(mb); auto fractional = RoundToInt(10.0 * static_cast<double>(kb) / static_cast<double>(base)); if (fractional > 0) { result += "."; result += Convert::ToString(fractional); } result += base == KILOBYTE ? "MB" : "MiB"; } else if (kb > 0) { result = Convert::ToString(kb); result += base == KILOBYTE ? "KB" : "KiB"; } else { result = Convert::ToString(bytes); result += "B"; } return result; }
mpl-2.0
lundjordan/services
src/codecoverage/bot/code_coverage_bot/codecov.py
7319
# -*- coding: utf-8 -*- import json import os import tempfile from datetime import datetime from datetime import timedelta import hglib import requests from cli_common.log import get_logger from cli_common.taskcluster import get_service from cli_common.utils import ThreadPoolExecutorResult from code_coverage_bot import chunk_mapping from code_coverage_bot import grcov from code_coverage_bot import suite_reports from code_coverage_bot import taskcluster from code_coverage_bot import uploader from code_coverage_bot.artifacts import ArtifactsHandler from code_coverage_bot.github import GitHubUtils from code_coverage_bot.notifier import Notifier from code_coverage_bot.phabricator import PhabricatorUploader from code_coverage_bot.secrets import secrets from code_coverage_bot.zero_coverage import ZeroCov logger = get_logger(__name__) class CodeCov(object): def __init__(self, revision, cache_root, client_id, access_token): # List of test-suite, sorted alphabetically. # This way, the index of a suite in the array should be stable enough. self.suites = [ 'web-platform-tests', ] self.cache_root = cache_root assert os.path.isdir(cache_root), 'Cache root {} is not a dir.'.format(cache_root) self.repo_dir = os.path.join(cache_root, 'mozilla-central') temp_dir = tempfile.mkdtemp() self.artifacts_dir = os.path.join(temp_dir, 'ccov-artifacts') self.ccov_reports_dir = os.path.join(temp_dir, 'code-coverage-reports') self.client_id = client_id self.access_token = access_token self.index_service = get_service('index', client_id, access_token) self.githubUtils = GitHubUtils(cache_root, client_id, access_token) if revision is None: # Retrieve revision of latest codecov build self.github_revision = uploader.get_latest_codecov() self.revision = self.githubUtils.git_to_mercurial(self.github_revision) self.from_pulse = False else: self.github_revision = None self.revision = revision self.from_pulse = True self.notifier = Notifier(self.repo_dir, revision, client_id, access_token) logger.info('Mercurial revision', revision=self.revision) task_ids = { 'linux': taskcluster.get_task('mozilla-central', self.revision, 'linux'), 'windows': taskcluster.get_task('mozilla-central', self.revision, 'win'), 'android-test': taskcluster.get_task('mozilla-central', self.revision, 'android-test'), 'android-emulator': taskcluster.get_task('mozilla-central', self.revision, 'android-emulator'), } self.artifactsHandler = ArtifactsHandler(task_ids, self.artifacts_dir) def clone_mozilla_central(self, revision): shared_dir = self.repo_dir + '-shared' cmd = hglib.util.cmdbuilder('robustcheckout', 'https://hg.mozilla.org/mozilla-central', self.repo_dir, purge=True, sharebase=shared_dir, revision=revision, networkattempts=7) cmd.insert(0, hglib.HGPATH) proc = hglib.util.popen(cmd) out, err = proc.communicate() if proc.returncode: raise hglib.error.CommandError(cmd, proc.returncode, out, err) logger.info('mozilla-central cloned') def go(self): if self.from_pulse: commit_sha = self.githubUtils.mercurial_to_git(self.revision) try: uploader.get_codecov(commit_sha) logger.warn('Build was already injested') return except requests.exceptions.HTTPError: pass with ThreadPoolExecutorResult(max_workers=2) as executor: # Thread 1 - Download coverage artifacts. executor.submit(self.artifactsHandler.download_all) # Thread 2 - Clone mozilla-central. executor.submit(self.clone_mozilla_central, self.revision) if self.from_pulse: self.githubUtils.update_geckodev_repo() logger.info('GitHub revision', revision=commit_sha) self.githubUtils.post_github_status(commit_sha) r = requests.get('https://hg.mozilla.org/mozilla-central/json-rev/%s' % self.revision) r.raise_for_status() push_id = r.json()['pushid'] output = grcov.report( self.artifactsHandler.get(), source_dir=self.repo_dir, service_number=push_id, commit_sha=commit_sha, token=secrets[secrets.COVERALLS_TOKEN] ) logger.info('Report generated successfully') with ThreadPoolExecutorResult(max_workers=2) as executor: executor.submit(uploader.coveralls, output) executor.submit(uploader.codecov, output, commit_sha) logger.info('Upload changeset coverage data to Phabricator') phabricatorUploader = PhabricatorUploader(self.repo_dir, self.revision) phabricatorUploader.upload(json.loads(output)) logger.info('Waiting for build to be ingested by Codecov...') # Wait until the build has been ingested by Codecov. if uploader.codecov_wait(commit_sha): logger.info('Build ingested by codecov.io') self.notifier.notify() else: logger.error('codecov.io took too much time to ingest data.') else: logger.info('Generating suite reports') os.makedirs(self.ccov_reports_dir, exist_ok=True) suite_reports.generate(self.suites, self.artifactsHandler, self.ccov_reports_dir, self.repo_dir) logger.info('Generating zero coverage reports') zc = ZeroCov(self.repo_dir) zc.generate(self.artifactsHandler.get(), self.revision, self.github_revision) logger.info('Generating chunk mapping') chunk_mapping.generate(self.repo_dir, self.revision, self.artifactsHandler) # Index the task in the TaskCluster index at the given revision and as "latest". # Given that all tasks have the same rank, the latest task that finishes will # overwrite the "latest" entry. namespaces = [ 'project.releng.services.project.{}.code_coverage_bot.{}'.format(secrets[secrets.APP_CHANNEL], self.revision), 'project.releng.services.project.{}.code_coverage_bot.latest'.format(secrets[secrets.APP_CHANNEL]), ] for namespace in namespaces: self.index_service.insertTask( namespace, { 'taskId': os.environ['TASK_ID'], 'rank': 0, 'data': {}, 'expires': (datetime.utcnow() + timedelta(180)).strftime('%Y-%m-%dT%H:%M:%S.%fZ'), } ) os.chdir(self.ccov_reports_dir) self.githubUtils.update_codecoveragereports_repo()
mpl-2.0
DISTORTEC/distortos
include/distortos/SignalsReceiver.hpp
1735
/** * \file * \brief SignalsReceiver class header * * \author Copyright (C) 2015-2019 Kamil Szczygiel https://distortec.com https://freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_SIGNALSRECEIVER_HPP_ #define INCLUDE_DISTORTOS_SIGNALSRECEIVER_HPP_ #include "distortos/distortosConfiguration.h" #if DISTORTOS_SIGNALS_ENABLE == 1 #include "distortos/internal/synchronization/SignalsReceiverControlBlock.hpp" namespace distortos { namespace internal { class ThreadControlBlock; } // namespace internal /// SignalsReceiver class is a container for internal::SignalsReceiverControlBlock class SignalsReceiver { friend internal::ThreadControlBlock; public: /** * \brief SignalsReceiver's constructor * * \param [in] signalInformationQueueWrapper is a pointer to SignalInformationQueueWrapper for this receiver, * nullptr to disable queuing of signals for this receiver * \param [in] signalsCatcher is a pointer to SignalsCatcher for this receiver, nullptr if this receiver cannot * catch/handle signals */ explicit SignalsReceiver(SignalInformationQueueWrapper* const signalInformationQueueWrapper, SignalsCatcher* const signalsCatcher) : signalsReceiverControlBlock_{signalInformationQueueWrapper, signalsCatcher} { } private: /// contained internal::SignalsReceiverControlBlock object internal::SignalsReceiverControlBlock signalsReceiverControlBlock_; }; } // namespace distortos #endif // DISTORTOS_SIGNALS_ENABLE == 1 #endif // INCLUDE_DISTORTOS_SIGNALSRECEIVER_HPP_
mpl-2.0
C6H2Cl2/YukariLib
src/main/java/c6h2cl2/YukariLib/ASM/YukariLibClassTransformer.java
1131
package c6h2cl2.YukariLib.ASM; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraftforge.fml.relauncher.FMLLaunchHandler; import java.util.LinkedList; import java.util.List; /** * @author C6H2Cl2 */ public class YukariLibClassTransformer implements IClassTransformer { private final List<String> TARGETS = new LinkedList<>(); public YukariLibClassTransformer() { TARGETS.add("net.minecraft.client.renderer.block.model.ModelBakery"); } @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (FMLLaunchHandler.side().isServer() || !isAccept(transformedName)) return basicClass; ClassReader cr = new ClassReader(basicClass); ClassWriter cw = new ClassWriter(cr, 0); createBuiltinModelSetter(cw, transformedName); return cw.toByteArray(); } private void createBuiltinModelSetter(ClassWriter cw, String className){ } private boolean isAccept(String name) { return TARGETS.contains(name); } }
mpl-2.0
Cempl/http-server-ws
ws_server/sources/VShared/FBL/publ/Algorithms/FBL_Algs_Table.cpp
9517
/**********************************************************************************************/ /* FBL_Algs_Table.cpp */ /* */ /* Copyright Paradigma, 1998-2017 */ /* All Rights Reserved. */ /**********************************************************************************************/ #include <VShared/FBL/publ/Headers/StdAfx.h> #include <VShared/FBL/publ/Algorithms/FBL_Algs_Table.h> #include <VShared/FBL/publ/Properties/FBL_FieldProperties.h> /**********************************************************************************************/ FBL_Begin_Namespace /**********************************************************************************************/ I_Field_Ptr CreateNumericField( I_Table_Ptr inTable, const String& inName, VALUE_TYPE inType, vuint16 inFlags, const String& inMethod ) { I_PropertyContainer_Ptr props; //if( inMethod != NULL && *inMethod != 0 ) if( inMethod.isEmpty() == false ) { props = new PropertyContainer(); props->Add( new Prop_MethodSql( inMethod ) ); } I_Field_Ptr pField = inTable->CreateField( inName, inType, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateFloatField( I_Table_Ptr inTable, const String& inName, vuint16 inFlags, const String& inMethod, vuint16 inPrecision, vuint16 inScale ) { I_PropertyContainer_Ptr props = new PropertyContainer(); if( inPrecision ) props->Add( new Prop_Precision( inPrecision ) ); if( inScale ) props->Add( new Prop_Scale( inScale ) ); if( inMethod.isEmpty() == false ) props->Add( new Prop_MethodSql( inMethod ) ); I_Field_Ptr pField = inTable->CreateField( inName, kTypeFloat, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateDoubleField( I_Table_Ptr inTable, const String& inName, vuint16 inFlags, const String& inMethod, vuint16 inPrecision, vuint16 inScale ) { I_PropertyContainer_Ptr props = new PropertyContainer(); if( inPrecision ) props->Add( new Prop_Precision( inPrecision ) ); if( inScale ) props->Add( new Prop_Scale( inScale ) ); if( inMethod.isEmpty() == false ) props->Add( new Prop_MethodSql( inMethod ) ); I_Field_Ptr pField = inTable->CreateField( inName, kTypeDouble, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateStringField( I_Table_Ptr inTable, const String& inName, vuint32 inMaxLength, vuint16 inFlags, const String& inMethod ) { I_PropertyContainer_Ptr props = new PropertyContainer(); props->Add( new Prop_MaxLen(inMaxLength) ); if( inMethod.isEmpty() == false ) props->Add( new Prop_MethodSql( inMethod ) ); // --------------- I_Field_Ptr pField = inTable->CreateField( inName, kTypeString, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateVarCharField( I_Table_Ptr inTable, const String& inName, vuint32 inMaxLength, vuint16 inFlags, const String& inMethod ) { I_PropertyContainer_Ptr props = new PropertyContainer(); props->Add( new Prop_MaxLen(inMaxLength) ); if( inMethod.isEmpty() == false ) props->Add( new Prop_MethodSql( inMethod ) ); // --------------- I_Field_Ptr pField = inTable->CreateField( inName, kTypeVarChar, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateVarBinaryField( I_Table_Ptr inTable, const String& inName, vuint32 inMaxLength, vuint16 inFlags, const String& inMethod ) { I_PropertyContainer_Ptr props = new PropertyContainer(); props->Add( new Prop_MaxLen(inMaxLength) ); if( inMethod.isEmpty() == false ) props->Add( new Prop_MethodSql( inMethod ) ); // --------------- I_Field_Ptr pField = inTable->CreateField( inName, kTypeVarBinary, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateBLOBField( I_Table_Ptr inTable, const String& inName, vuint32 inSegmentSize, vuint16 inFlags ) { I_PropertyContainer_Ptr props = new PropertyContainer(); props->Add( new Prop_SegmentSize(inSegmentSize) ); // --------------- I_Field_Ptr pField = inTable->CreateField( inName, kTypeBLOB, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateTextField( I_Table_Ptr inTable, const String& inName, vuint32 inSegmentSize, vuint16 inFlags, const String& inMethod ) { I_PropertyContainer_Ptr props = new PropertyContainer(); props->Add( new Prop_SegmentSize(inSegmentSize) ); if( inMethod.isEmpty() == false ) props->Add( new Prop_MethodSql( inMethod ) ); // --------------- I_Field_Ptr pField = inTable->CreateField( inName, kTypeText, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreatePictureField( I_Table_Ptr inTable, const String& inName, vuint32 inSegmentSize, vuint16 inFlags ) { I_PropertyContainer_Ptr props = new PropertyContainer(); props->Add( new Prop_SegmentSize(inSegmentSize) ); // --------------- I_Field_Ptr pField = inTable->CreateField( inName, kTypePicture, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateObjectPtr( I_Table_Ptr inTable, const String& inName, I_Table_Ptr inTarget, EOnDeletion inOnDeletion, vuint16 inFlags, const String& inLinkName ) { I_PropertyContainer_Ptr props = new PropertyContainer(); props->Add( new Prop_Target(inTarget) ); props->Add( new Prop_OnDeletion(inOnDeletion) ); if( inLinkName.isEmpty() == false ) props->Add( new Prop_LinkName( inLinkName ) ); // --------------- I_Field_Ptr pField = inTable->CreateField( inName, kTypeObjectPtr, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateEnumField( I_Table_Ptr inTable, const String& inName, I_Type_Enumerated_Ptr inpType, vuint16 inFlags ) { I_PropertyContainer_Ptr props = new PropertyContainer(); props->Add( new Prop_EnumType(inpType) ); // --------------- I_Field_Ptr pField; switch( inpType->get_MaxIdentCount() ) { case ENUM_8_IDENT_COUNT: { pField = inTable->CreateField( inName, kTypeEnum8, inFlags, props ); } break; case ENUM_16_IDENT_COUNT: { pField = inTable->CreateField( inName, kTypeEnum16, inFlags, props ); } break; default: { FBL_Throw( xFeatureError( ERR_FEATURE_NOT_SUPPORTED, "Not enum8 or enum16" ) ); } } return pField; } /**********************************************************************************************/ I_Field_Ptr CreateMoneyField( I_Table_Ptr inTable, const String& inName, vuint16 inFlags, const String& inMethod ) { I_PropertyContainer_Ptr props = new PropertyContainer(); if( inMethod.isEmpty() == false ) props->Add( new Prop_MethodSql( inMethod ) ); I_Field_Ptr pField = inTable->CreateField( inName, kTypeMoney, inFlags, props ); return pField; } /**********************************************************************************************/ I_Field_Ptr CreateVariantField( I_Table_Ptr inTable, const String& inName, vuint16 inFlags ) { I_Field_Ptr pField = inTable->CreateField( inName, kTypeVariant, inFlags ); return pField; } /**********************************************************************************************/ ArrayOfValues_Ptr GetNotBLOBValues( I_Table_Ptr inTable ) { FBL_CHECK( inTable ); ArrayOfValues_Ptr result; vuint16 fldCount = inTable->get_FieldCount(); if( fldCount ) result = new ArrayOfValues(); for( vuint16 i = 1; i <= fldCount; ++i ) { I_Field_Ptr pField = inTable->get_Field( i ); I_Value_Ptr pValue; switch( pField->get_Type() ) { case kTypeBLOB: case kTypePicture: { ; } break; default: { // IS: 25.02.2008 // http://valentina-db.com/bt/view.php?id=3048 //pValue = pField->get_Value(forAdd); pValue = fbl_const_cast( pField->get_Value() ); FBL_CHECK(pValue); } break; } result->AddItem( pValue ); } return result; } /**********************************************************************************************/ ArrayOfSerializable_Ptr GetSerializables( ArrayOfValues_Ptr inpValues ) { FBL_CHECK( inpValues ); ArrayOfSerializable_Ptr result; vuint32 valCount = inpValues->get_Count(); if( valCount ) result = new ArrayOfSerializable(); for( vuint32 i = 1; i <= valCount; ++i ) { I_Value_Ptr pValue = inpValues->get_ItemAt( i ); I_Serializable_Ptr pSerial = (pValue) ? QI(pValue, I_Serializable) : nullptr; result->AddItem( pSerial ); } return result; } /**********************************************************************************************/ FBL_End_Namespace
mpl-2.0
NetlifeBackupSolutions/Winium.StoreApps
Winium/Winium.StoreApps.Common/Properties/AssemblyInfo.cs
1051
#region using System.Reflection; using System.Resources; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Winium.StoreApps.Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Winium.StoreApps.Common")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.6.2.*")] [assembly: AssemblyFileVersionAttribute("1.6.2.0")]
mpl-2.0
das-praktische-schreinerlein/your-all-in-one
yaio-app-core/src/main/java/de/yaio/app/core/datadomain/DataDomain.java
2855
/** * software for projectmanagement and documentation * * @FeatureDomain Collaboration * @author Michael Schreiner <michael.schreiner@your-it-fellow.de> * @category collaboration * @copyright Copyright (c) 2014, Michael Schreiner * @license http://mozilla.org/MPL/2.0/ Mozilla Public License 2.0 * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package de.yaio.app.core.datadomain; import de.yaio.app.core.node.BaseNode; import de.yaio.app.core.nodeservice.BaseNodeService; import de.yaio.app.core.nodeservice.NodeService; import javax.validation.ConstraintViolation; import java.util.Map; import java.util.Set; /** * interface for DataDomains of the Node * * @FeatureDomain DataDefinition * @package de.yaio.core.datadomain * @author Michael Schreiner <michael.schreiner@your-it-fellow.de> * @category collaboration * @copyright Copyright (c) 2014, Michael Schreiner * @license http://mozilla.org/MPL/2.0/ Mozilla Public License 2.0 */ public interface DataDomain { int CONST_ORDER = 1; // because of Spring roo with Node Set<BaseNode> getChildNodes(); BaseNode getParentNode(); void setParentNode(DataDomain parentNode); // hirarchy-functions void setParentNodeOnly(DataDomain parentNode); Map<String, DataDomain> getChildNodesByNameMap(); String getIdForChildByNameMap(); void addChildNode(DataDomain childNode); boolean hasChildNode(DataDomain childNode); Integer getSortPos(); void setSortPos(Integer sortPos); // basefields Integer getEbene(); void setEbene(Integer ebene); String getName(); void setName(String name); // servies BaseNodeService getBaseNodeService(); /** * validates the node against the declared validation rules * @return set of violations */ Set<ConstraintViolation<BaseNode>> validateMe(); /** * recalc the WFData of the node, upadtes memberfields of dataDomain PlanChildrenSum+IstChildrenSum * @param recursionDirection direction for recursivly recalc CONST_RECURSE_DIRECTION_* */ void recalcData(NodeService.RecalcRecurseDirection recursionDirection); String getNameForLogger(); /** * @return the {@link BaseNode#flgForceUpdate} */ boolean isFlgForceUpdate(); /** * @param flgForceUpdate the {@link BaseNode#flgForceUpdate} to set */ void setFlgForceUpdate(boolean flgForceUpdate); }
mpl-2.0
Orange-OpenSource/ocara
app/src/test/java/com/orange/ocara/ui/presenter/TutorialDisplayPresenterCompleteOnboardingTest.java
2398
package com.orange.ocara.ui.presenter; import com.orange.ocara.business.interactor.UseCase; import com.orange.ocara.business.interactor.UseCaseHandler; import org.junit.Test; import static com.orange.ocara.business.interactor.ChangeOnboardingStepTask.ChangeOnboardingStepRequest; import static com.orange.ocara.business.interactor.ChangeOnboardingStepTask.ChangeOnboardingStepResponse; import static com.orange.ocara.business.interactor.CompleteOnboardingTask.CompleteOnboardingRequest; import static com.orange.ocara.business.interactor.CompleteOnboardingTask.CompleteOnboardingResponse; import static com.orange.ocara.business.interactor.LoadOnboardingItemsTask.LoadOnboardingItemsRequest; import static com.orange.ocara.business.interactor.LoadOnboardingItemsTask.LoadOnboardingItemsResponse; import static com.orange.ocara.business.interactor.SkipOnboardingTask.SkipOnboardingRequest; import static com.orange.ocara.business.interactor.SkipOnboardingTask.SkipOnboardingResponse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** see {@link TutorialDisplayPresenter#completeOnboarding(UseCase.UseCaseCallback)} */ public class TutorialDisplayPresenterCompleteOnboardingTest { private TutorialDisplayPresenter subject; @Test public void shouldDelegateTaskExecutionToHandler() { // given UseCaseHandler useCaseHandler = mock(UseCaseHandler.class); UseCase<CompleteOnboardingRequest, CompleteOnboardingResponse> completeUseCase = mock(UseCase.class); UseCase<LoadOnboardingItemsRequest, LoadOnboardingItemsResponse> loadUseCase = mock(UseCase.class); UseCase<SkipOnboardingRequest, SkipOnboardingResponse> skipUseCase = mock(UseCase.class); UseCase<ChangeOnboardingStepRequest, ChangeOnboardingStepResponse> changeStepUseCase = mock(UseCase.class); subject = new TutorialDisplayPresenter(useCaseHandler, completeUseCase, loadUseCase, skipUseCase, changeStepUseCase); UseCase.UseCaseCallback<CompleteOnboardingResponse> inputCallback = mock(UseCase.UseCaseCallback.class); // when subject.completeOnboarding(inputCallback); // then verify(useCaseHandler).execute(eq(completeUseCase), any(CompleteOnboardingRequest.class), eq(inputCallback)); } }
mpl-2.0
jixiuf/go_spider
core/scheduler/scheduler_queue.go
1451
// Copyright 2014 Hu Cong. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package scheduler import ( "container/list" "crypto/md5" "github.com/jixiuf/go_spider/core/common/request" "sync" //"fmt" ) type QueueScheduler struct { locker *sync.Mutex rm bool rmKey map[[md5.Size]byte]*list.Element queue *list.List } func NewQueueScheduler(rmDuplicate bool) *QueueScheduler { queue := list.New() rmKey := make(map[[md5.Size]byte]*list.Element) locker := new(sync.Mutex) return &QueueScheduler{rm: rmDuplicate, queue: queue, rmKey: rmKey, locker: locker} } func (this *QueueScheduler) Push(requ *request.Request) { this.locker.Lock() var key [md5.Size]byte if this.rm { key = md5.Sum([]byte(requ.GetUrl())) if _, ok := this.rmKey[key]; ok { this.locker.Unlock() return } } e := this.queue.PushBack(requ) if this.rm { this.rmKey[key] = e } this.locker.Unlock() } func (this *QueueScheduler) Poll() *request.Request { this.locker.Lock() if this.queue.Len() <= 0 { this.locker.Unlock() return nil } e := this.queue.Front() requ := e.Value.(*request.Request) key := md5.Sum([]byte(requ.GetUrl())) this.queue.Remove(e) if this.rm { delete(this.rmKey, key) } this.locker.Unlock() return requ } func (this *QueueScheduler) Count() int { this.locker.Lock() len := this.queue.Len() this.locker.Unlock() return len }
mpl-2.0
fromonesrc/terraform
terraform/context_apply_test.go
86572
package terraform import ( "fmt" "os" "reflect" "sort" "strings" "sync" "sync/atomic" "testing" "time" "github.com/hashicorp/terraform/config/module" ) func TestContext2Apply(t *testing.T) { m := testModule(t, "apply-good") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if len(mod.Resources) < 2 { t.Fatalf("bad: %#v", mod.Resources) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_providerAlias(t *testing.T) { m := testModule(t, "apply-provider-alias") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if len(mod.Resources) < 2 { t.Fatalf("bad: %#v", mod.Resources) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProviderAliasStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } // GH-2870 func TestContext2Apply_providerWarning(t *testing.T) { m := testModule(t, "apply-provider-warning") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn p.ValidateFn = func(c *ResourceConfig) (ws []string, es []error) { ws = append(ws, "Just a warning") return } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(` aws_instance.foo: ID = foo `) if actual != expected { t.Fatalf("got: \n%s\n\nexpected:\n%s", actual, expected) } if !p.ConfigureCalled { t.Fatalf("provider Configure() was never called!") } } func TestContext2Apply_emptyModule(t *testing.T) { m := testModule(t, "apply-empty-module") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) actual = strings.Replace(actual, " ", "", -1) expected := strings.TrimSpace(testTerraformApplyEmptyModuleStr) if actual != expected { t.Fatalf("bad: \n%s\nexpect:\n%s", actual, expected) } } func TestContext2Apply_createBeforeDestroy(t *testing.T) { m := testModule(t, "apply-good-create-before") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "require_new": "abc", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, }) if p, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } else { t.Logf(p.String()) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if len(mod.Resources) != 1 { t.Fatalf("bad: %s", state) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyCreateBeforeStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_createBeforeDestroyUpdate(t *testing.T) { m := testModule(t, "apply-good-create-before-update") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "foo": "bar", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, }) if p, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } else { t.Logf(p.String()) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if len(mod.Resources) != 1 { t.Fatalf("bad: %s", state) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyCreateBeforeUpdateStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_destroyComputed(t *testing.T) { m := testModule(t, "apply-destroy-computed") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "foo", Attributes: map[string]string{ "output": "value", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, Destroy: true, }) if p, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } else { t.Logf(p.String()) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } } // https://github.com/hashicorp/terraform/pull/5096 func TestContext2Apply_destroySkipsCBD(t *testing.T) { // Config contains CBD resource depending on non-CBD resource, which triggers // a cycle if they are both replaced, but should _not_ trigger a cycle when // just doing a `terraform destroy`. m := testModule(t, "apply-destroy-cbd") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "foo", }, }, "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "foo", }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, Destroy: true, }) if p, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } else { t.Logf(p.String()) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } } // https://github.com/hashicorp/terraform/issues/2892 func TestContext2Apply_destroyCrossProviders(t *testing.T) { m := testModule(t, "apply-destroy-cross-providers") p_aws := testProvider("aws") p_aws.ApplyFn = testApplyFn p_aws.DiffFn = testDiffFn p_tf := testProvider("terraform") p_tf.ApplyFn = testApplyFn p_tf.DiffFn = testDiffFn providers := map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p_aws), "terraform": testProviderFuncFixed(p_tf), } // Bug only appears from time to time, // so we run this test multiple times // to check for the race-condition for i := 0; i <= 10; i++ { ctx := getContextForApply_destroyCrossProviders( t, m, providers) if p, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } else { t.Logf(p.String()) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } } } func getContextForApply_destroyCrossProviders( t *testing.T, m *module.Tree, providers map[string]ResourceProviderFactory) *Context { state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "terraform_remote_state.shared": &ResourceState{ Type: "terraform_remote_state", Primary: &InstanceState{ ID: "remote-2652591293", Attributes: map[string]string{ "output.env_name": "test", }, }, }, }, }, &ModuleState{ Path: []string{"root", "example"}, Resources: map[string]*ResourceState{ "aws_vpc.bar": &ResourceState{ Type: "aws_vpc", Primary: &InstanceState{ ID: "vpc-aaabbb12", Attributes: map[string]string{ "value": "test", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: providers, State: state, Destroy: true, }) return ctx } func TestContext2Apply_minimal(t *testing.T) { m := testModule(t, "apply-minimal") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyMinimalStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_badDiff(t *testing.T) { m := testModule(t, "apply-good") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } p.DiffFn = func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error) { return &InstanceDiff{ Attributes: map[string]*ResourceAttrDiff{ "newp": nil, }, }, nil } if _, err := ctx.Apply(); err == nil { t.Fatal("should error") } } func TestContext2Apply_cancel(t *testing.T) { stopped := false m := testModule(t, "apply-cancel") p := testProvider("aws") ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) p.ApplyFn = func(*InstanceInfo, *InstanceState, *InstanceDiff) (*InstanceState, error) { if !stopped { stopped = true go ctx.Stop() for { if ctx.sh.Stopped() { break } } } return &InstanceState{ ID: "foo", Attributes: map[string]string{ "num": "2", }, }, nil } p.DiffFn = func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error) { return &InstanceDiff{ Attributes: map[string]*ResourceAttrDiff{ "num": &ResourceAttrDiff{ New: "bar", }, }, }, nil } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } // Start the Apply in a goroutine stateCh := make(chan *State) go func() { state, err := ctx.Apply() if err != nil { panic(err) } stateCh <- state }() state := <-stateCh mod := state.RootModule() if len(mod.Resources) != 1 { t.Fatalf("bad: %s", state.String()) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyCancelStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_compute(t *testing.T) { m := testModule(t, "apply-compute") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } ctx.variables = map[string]string{"value": "1"} state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyComputeStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_countDecrease(t *testing.T) { m := testModule(t, "apply-count-dec") p := testProvider("aws") p.DiffFn = testDiffFn s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo.0": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "foo": "foo", "type": "aws_instance", }, }, }, "aws_instance.foo.1": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "foo": "foo", "type": "aws_instance", }, }, }, "aws_instance.foo.2": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "foo": "foo", "type": "aws_instance", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyCountDecStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_countDecreaseToOne(t *testing.T) { m := testModule(t, "apply-count-dec-one") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo.0": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "foo": "foo", "type": "aws_instance", }, }, }, "aws_instance.foo.1": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, "aws_instance.foo.2": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyCountDecToOneStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } // https://github.com/PeoplePerHour/terraform/pull/11 // // This tests a case where both a "resource" and "resource.0" are in // the state file, which apparently is a reasonable backwards compatibility // concern found in the above 3rd party repo. func TestContext2Apply_countDecreaseToOneCorrupted(t *testing.T) { m := testModule(t, "apply-count-dec-one") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "foo": "foo", "type": "aws_instance", }, }, }, "aws_instance.foo.0": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "baz", Attributes: map[string]string{ "type": "aws_instance", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) if p, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } else { testStringMatch(t, p, testTerraformApplyCountDecToOneCorruptedPlanStr) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyCountDecToOneCorruptedStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_countTainted(t *testing.T) { m := testModule(t, "apply-count-tainted") p := testProvider("aws") p.DiffFn = testDiffFn s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo.0": &ResourceState{ Type: "aws_instance", Tainted: []*InstanceState{ &InstanceState{ ID: "bar", Attributes: map[string]string{ "foo": "foo", "type": "aws_instance", }, }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyCountTaintedStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_countVariable(t *testing.T) { m := testModule(t, "apply-count-variable") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyCountVariableStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_mapVariableOverride(t *testing.T) { m := testModule(t, "apply-map-var-override") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Variables: map[string]string{ "images.us-west-2": "overridden", }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(` aws_instance.bar: ID = foo ami = overridden type = aws_instance aws_instance.foo: ID = foo ami = image-1234 type = aws_instance `) if actual != expected { t.Fatalf("got: \n%s\nexpected: \n%s", actual, expected) } } func TestContext2Apply_module(t *testing.T) { m := testModule(t, "apply-module") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyModuleStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_moduleDestroyOrder(t *testing.T) { m := testModule(t, "apply-module-destroy-order") p := testProvider("aws") p.DiffFn = testDiffFn // Create a custom apply function to track the order they were destroyed var order []string var orderLock sync.Mutex p.ApplyFn = func( info *InstanceInfo, is *InstanceState, id *InstanceDiff) (*InstanceState, error) { orderLock.Lock() defer orderLock.Unlock() order = append(order, is.ID) return nil, nil } state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.b": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "b", }, }, }, }, &ModuleState{ Path: []string{"root", "child"}, Resources: map[string]*ResourceState{ "aws_instance.a": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "a", }, }, }, Outputs: map[string]string{ "a_output": "a", }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, Destroy: true, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } expected := []string{"b", "a"} if !reflect.DeepEqual(order, expected) { t.Fatalf("bad: %#v", order) } { actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyModuleDestroyOrderStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } } func TestContext2Apply_moduleOrphanProvider(t *testing.T) { m := testModule(t, "apply-module-orphan-provider-inherit") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn p.ConfigureFn = func(c *ResourceConfig) error { if _, ok := c.Get("value"); !ok { return fmt.Errorf("value is not found") } return nil } // Create a state with an orphan module state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: []string{"root", "child"}, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, State: state, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } } // This tests an issue where all the providers in a module but not // in the root weren't being added to the root properly. In this test // case: aws is explicitly added to root, but "test" should be added to. // With the bug, it wasn't. func TestContext2Apply_moduleOnlyProvider(t *testing.T) { m := testModule(t, "apply-module-only-provider") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pTest := testProvider("test") pTest.ApplyFn = testApplyFn pTest.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), "test": testProviderFuncFixed(pTest), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyModuleOnlyProviderStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_moduleProviderAlias(t *testing.T) { m := testModule(t, "apply-module-provider-alias") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyModuleProviderAliasStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_moduleProviderAliasTargets(t *testing.T) { m := testModule(t, "apply-module-provider-alias") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Targets: []string{"no.thing"}, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(` <no state> `) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_moduleProviderCloseNested(t *testing.T) { m := testModule(t, "apply-module-provider-close-nested") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: &State{ Modules: []*ModuleState{ &ModuleState{ Path: []string{"root", "child", "subchild"}, Resources: map[string]*ResourceState{ "aws_instance.foo": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, }, }, }, }, Destroy: true, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } } func TestContext2Apply_moduleVarResourceCount(t *testing.T) { m := testModule(t, "apply-module-var-resource-count") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Variables: map[string]string{ "count": "2", }, Destroy: true, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } ctx = testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Variables: map[string]string{ "count": "5", }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } } // GH-819 func TestContext2Apply_moduleBool(t *testing.T) { m := testModule(t, "apply-module-bool") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyModuleBoolStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_multiProvider(t *testing.T) { m := testModule(t, "apply-multi-provider") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pDO := testProvider("do") pDO.ApplyFn = testApplyFn pDO.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), "do": testProviderFuncFixed(pDO), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if len(mod.Resources) < 2 { t.Fatalf("bad: %#v", mod.Resources) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyMultiProviderStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_multiVar(t *testing.T) { m := testModule(t, "apply-multi-var") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn // First, apply with a count of 3 ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Variables: map[string]string{ "count": "3", }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := state.RootModule().Outputs["output"] expected := "bar0,bar1,bar2" if actual != expected { t.Fatalf("bad: \n%s", actual) } // Apply again, reduce the count to 1 { ctx := testContext2(t, &ContextOpts{ Module: m, State: state, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Variables: map[string]string{ "count": "1", }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := state.RootModule().Outputs["output"] expected := "bar0" if actual != expected { t.Fatalf("bad: \n%s", actual) } } } func TestContext2Apply_nilDiff(t *testing.T) { m := testModule(t, "apply-good") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } p.DiffFn = func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error) { return nil, nil } if _, err := ctx.Apply(); err == nil { t.Fatal("should error") } } func TestContext2Apply_outputOrphan(t *testing.T) { m := testModule(t, "apply-output-orphan") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Outputs: map[string]string{ "foo": "bar", "bar": "baz", }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyOutputOrphanStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_providerComputedVar(t *testing.T) { m := testModule(t, "apply-provider-computed") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pTest := testProvider("test") pTest.ApplyFn = testApplyFn pTest.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), "test": testProviderFuncFixed(pTest), }, }) p.ConfigureFn = func(c *ResourceConfig) error { if c.IsComputed("value") { return fmt.Errorf("value is computed") } v, ok := c.Get("value") if !ok { return fmt.Errorf("value is not found") } if v != "yes" { return fmt.Errorf("value is not 'yes': %v", v) } return nil } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } } func TestContext2Apply_Provisioner_compute(t *testing.T) { m := testModule(t, "apply-provisioner-compute") p := testProvider("aws") pr := testProvisioner() p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pr.ApplyFn = func(rs *InstanceState, c *ResourceConfig) error { val, ok := c.Config["foo"] if !ok || val != "computed_dynamical" { t.Fatalf("bad value for foo: %v %#v", val, c) } return nil } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, Variables: map[string]string{ "value": "1", }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } // Verify apply was invoked if !pr.ApplyCalled { t.Fatalf("provisioner not invoked") } } func TestContext2Apply_provisionerCreateFail(t *testing.T) { m := testModule(t, "apply-provisioner-fail-create") p := testProvider("aws") pr := testProvisioner() p.DiffFn = testDiffFn p.ApplyFn = func( info *InstanceInfo, is *InstanceState, id *InstanceDiff) (*InstanceState, error) { is.ID = "foo" return is, fmt.Errorf("error") } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err == nil { t.Fatal("should error") } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerFailCreateStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_provisionerCreateFailNoId(t *testing.T) { m := testModule(t, "apply-provisioner-fail-create") p := testProvider("aws") pr := testProvisioner() p.DiffFn = testDiffFn p.ApplyFn = func( info *InstanceInfo, is *InstanceState, id *InstanceDiff) (*InstanceState, error) { return nil, fmt.Errorf("error") } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err == nil { t.Fatal("should error") } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerFailCreateNoIdStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_provisionerFail(t *testing.T) { m := testModule(t, "apply-provisioner-fail") p := testProvider("aws") pr := testProvisioner() p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pr.ApplyFn = func(*InstanceState, *ResourceConfig) error { return fmt.Errorf("EXPLOSION") } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, Variables: map[string]string{ "value": "1", }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err == nil { t.Fatal("should error") } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerFailStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_provisionerFail_createBeforeDestroy(t *testing.T) { m := testModule(t, "apply-provisioner-fail-create-before") p := testProvider("aws") pr := testProvisioner() p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pr.ApplyFn = func(*InstanceState, *ResourceConfig) error { return fmt.Errorf("EXPLOSION") } state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "require_new": "abc", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, State: state, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err == nil { t.Fatal("should error") } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerFailCreateBeforeDestroyStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_error_createBeforeDestroy(t *testing.T) { m := testModule(t, "apply-error-create-before") p := testProvider("aws") state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "require_new": "abc", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, }) p.ApplyFn = func(info *InstanceInfo, is *InstanceState, id *InstanceDiff) (*InstanceState, error) { return nil, fmt.Errorf("error") } p.DiffFn = testDiffFn if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err == nil { t.Fatal("should have error") } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyErrorCreateBeforeDestroyStr) if actual != expected { t.Fatalf("bad: \n%s\n\nExpected:\n\n%s", actual, expected) } } func TestContext2Apply_errorDestroy_createBeforeDestroy(t *testing.T) { m := testModule(t, "apply-error-create-before") p := testProvider("aws") state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "require_new": "abc", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, }) p.ApplyFn = func(info *InstanceInfo, is *InstanceState, id *InstanceDiff) (*InstanceState, error) { // Fail the destroy! if id.Destroy { return is, fmt.Errorf("error") } // Create should work is = &InstanceState{ ID: "foo", } return is, nil } p.DiffFn = testDiffFn if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err == nil { t.Fatal("should have error") } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyErrorDestroyCreateBeforeDestroyStr) if actual != expected { t.Fatalf("bad: actual:\n%s\n\nexpected:\n%s", actual, expected) } } func TestContext2Apply_multiDepose_createBeforeDestroy(t *testing.T) { m := testModule(t, "apply-multi-depose-create-before-destroy") p := testProvider("aws") p.DiffFn = testDiffFn ps := map[string]ResourceProviderFactory{"aws": testProviderFuncFixed(p)} state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.web": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ID: "foo"}, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: ps, State: state, }) createdInstanceId := "bar" // Create works createFunc := func(is *InstanceState) (*InstanceState, error) { return &InstanceState{ID: createdInstanceId}, nil } // Destroy starts broken destroyFunc := func(is *InstanceState) (*InstanceState, error) { return is, fmt.Errorf("destroy failed") } p.ApplyFn = func(info *InstanceInfo, is *InstanceState, id *InstanceDiff) (*InstanceState, error) { if id.Destroy { return destroyFunc(is) } else { return createFunc(is) } } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } // Destroy is broken, so even though CBD successfully replaces the instance, // we'll have to save the Deposed instance to destroy later state, err := ctx.Apply() if err == nil { t.Fatal("should have error") } checkStateString(t, state, ` aws_instance.web: (1 deposed) ID = bar Deposed ID 1 = foo `) createdInstanceId = "baz" ctx = testContext2(t, &ContextOpts{ Module: m, Providers: ps, State: state, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } // We're replacing the primary instance once again. Destroy is _still_ // broken, so the Deposed list gets longer state, err = ctx.Apply() if err == nil { t.Fatal("should have error") } checkStateString(t, state, ` aws_instance.web: (2 deposed) ID = baz Deposed ID 1 = foo Deposed ID 2 = bar `) // Destroy partially fixed! destroyFunc = func(is *InstanceState) (*InstanceState, error) { if is.ID == "foo" || is.ID == "baz" { return nil, nil } else { return is, fmt.Errorf("destroy partially failed") } } createdInstanceId = "qux" if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err = ctx.Apply() // Expect error because 1/2 of Deposed destroys failed if err == nil { t.Fatal("should have error") } // foo and baz are now gone, bar sticks around checkStateString(t, state, ` aws_instance.web: (1 deposed) ID = qux Deposed ID 1 = bar `) // Destroy working fully! destroyFunc = func(is *InstanceState) (*InstanceState, error) { return nil, nil } createdInstanceId = "quux" if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err = ctx.Apply() if err != nil { t.Fatal("should not have error:", err) } // And finally the state is clean checkStateString(t, state, ` aws_instance.web: ID = quux `) } func TestContext2Apply_provisionerResourceRef(t *testing.T) { m := testModule(t, "apply-provisioner-resource-ref") p := testProvider("aws") pr := testProvisioner() p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pr.ApplyFn = func(rs *InstanceState, c *ResourceConfig) error { val, ok := c.Config["foo"] if !ok || val != "2" { t.Fatalf("bad value for foo: %v %#v", val, c) } return nil } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerResourceRefStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } // Verify apply was invoked if !pr.ApplyCalled { t.Fatalf("provisioner not invoked") } } func TestContext2Apply_provisionerSelfRef(t *testing.T) { m := testModule(t, "apply-provisioner-self-ref") p := testProvider("aws") pr := testProvisioner() p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pr.ApplyFn = func(rs *InstanceState, c *ResourceConfig) error { val, ok := c.Config["command"] if !ok || val != "bar" { t.Fatalf("bad value for command: %v %#v", val, c) } return nil } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerSelfRefStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } // Verify apply was invoked if !pr.ApplyCalled { t.Fatalf("provisioner not invoked") } } func TestContext2Apply_provisionerMultiSelfRef(t *testing.T) { var lock sync.Mutex commands := make([]string, 0, 5) m := testModule(t, "apply-provisioner-multi-self-ref") p := testProvider("aws") pr := testProvisioner() p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pr.ApplyFn = func(rs *InstanceState, c *ResourceConfig) error { lock.Lock() defer lock.Unlock() val, ok := c.Config["command"] if !ok { t.Fatalf("bad value for command: %v %#v", val, c) } commands = append(commands, val.(string)) return nil } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerMultiSelfRefStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } // Verify apply was invoked if !pr.ApplyCalled { t.Fatalf("provisioner not invoked") } // Verify our result sort.Strings(commands) expectedCommands := []string{"number 0", "number 1", "number 2"} if !reflect.DeepEqual(commands, expectedCommands) { t.Fatalf("bad: %#v", commands) } } // Provisioner should NOT run on a diff, only create func TestContext2Apply_Provisioner_Diff(t *testing.T) { m := testModule(t, "apply-provisioner-diff") p := testProvider("aws") pr := testProvisioner() p.ApplyFn = testApplyFn p.DiffFn = testDiffFn pr.ApplyFn = func(rs *InstanceState, c *ResourceConfig) error { return nil } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerDiffStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } // Verify apply was invoked if !pr.ApplyCalled { t.Fatalf("provisioner not invoked") } pr.ApplyCalled = false // Change the state to force a diff mod := state.RootModule() mod.Resources["aws_instance.bar"].Primary.Attributes["foo"] = "baz" // Re-create context with state ctx = testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, State: state, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state2, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual = strings.TrimSpace(state2.String()) if actual != expected { t.Fatalf("bad: \n%s", actual) } // Verify apply was NOT invoked if pr.ApplyCalled { t.Fatalf("provisioner invoked") } } func TestContext2Apply_outputDiffVars(t *testing.T) { m := testModule(t, "apply-good") p := testProvider("aws") s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.baz": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) p.ApplyFn = func(info *InstanceInfo, s *InstanceState, d *InstanceDiff) (*InstanceState, error) { for k, ad := range d.Attributes { if ad.NewComputed { return nil, fmt.Errorf("%s: computed", k) } } result := s.MergeDiff(d) result.ID = "foo" return result, nil } p.DiffFn = func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error) { return &InstanceDiff{ Attributes: map[string]*ResourceAttrDiff{ "foo": &ResourceAttrDiff{ NewComputed: true, Type: DiffAttrOutput, }, "bar": &ResourceAttrDiff{ New: "baz", }, }, }, nil } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } } func TestContext2Apply_Provisioner_ConnInfo(t *testing.T) { m := testModule(t, "apply-provisioner-conninfo") p := testProvider("aws") pr := testProvisioner() p.ApplyFn = func(info *InstanceInfo, s *InstanceState, d *InstanceDiff) (*InstanceState, error) { if s.Ephemeral.ConnInfo == nil { t.Fatalf("ConnInfo not initialized") } result, _ := testApplyFn(info, s, d) result.Ephemeral.ConnInfo = map[string]string{ "type": "ssh", "host": "127.0.0.1", "port": "22", } return result, nil } p.DiffFn = testDiffFn pr.ApplyFn = func(rs *InstanceState, c *ResourceConfig) error { conn := rs.Ephemeral.ConnInfo if conn["type"] != "telnet" { t.Fatalf("Bad: %#v", conn) } if conn["host"] != "127.0.0.1" { t.Fatalf("Bad: %#v", conn) } if conn["port"] != "2222" { t.Fatalf("Bad: %#v", conn) } if conn["user"] != "superuser" { t.Fatalf("Bad: %#v", conn) } if conn["pass"] != "test" { t.Fatalf("Bad: %#v", conn) } return nil } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, Variables: map[string]string{ "value": "1", "pass": "test", }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyProvisionerStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } // Verify apply was invoked if !pr.ApplyCalled { t.Fatalf("provisioner not invoked") } } func TestContext2Apply_destroy(t *testing.T) { m := testModule(t, "apply-destroy") h := new(HookRecordApplyOrder) p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Hooks: []Hook{h}, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) // First plan and apply a create operation if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } // Next, plan and apply a destroy operation h.Active = true ctx = testContext2(t, &ContextOpts{ Destroy: true, State: state, Module: m, Hooks: []Hook{h}, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err = ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } // Test that things were destroyed actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyDestroyStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } // Test that things were destroyed _in the right order_ expected2 := []string{"aws_instance.bar", "aws_instance.foo"} actual2 := h.IDs if !reflect.DeepEqual(actual2, expected2) { t.Fatalf("expected: %#v\n\ngot:%#v", expected2, actual2) } } func TestContext2Apply_destroyNestedModule(t *testing.T) { m := testModule(t, "apply-destroy-nested-module") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: []string{"root", "child", "subchild"}, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) // First plan and apply a create operation if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } // Test that things were destroyed actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyDestroyNestedModuleStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_destroyDeeplyNestedModule(t *testing.T) { m := testModule(t, "apply-destroy-deeply-nested-module") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: []string{"root", "child", "subchild", "subsubchild"}, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) // First plan and apply a create operation if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } // Test that things were destroyed actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(` module.child.subchild.subsubchild: <no state> `) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_destroyOutputs(t *testing.T) { m := testModule(t, "apply-destroy-outputs") h := new(HookRecordApplyOrder) p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Hooks: []Hook{h}, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) // First plan and apply a create operation if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } // Next, plan and apply a destroy operation h.Active = true ctx = testContext2(t, &ContextOpts{ Destroy: true, State: state, Module: m, Hooks: []Hook{h}, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err = ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if len(mod.Resources) > 0 { t.Fatalf("bad: %#v", mod) } } func TestContext2Apply_destroyOrphan(t *testing.T) { m := testModule(t, "apply-error") p := testProvider("aws") s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.baz": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) p.ApplyFn = func(info *InstanceInfo, s *InstanceState, d *InstanceDiff) (*InstanceState, error) { if d.Destroy { return nil, nil } result := s.MergeDiff(d) result.ID = "foo" return result, nil } p.DiffFn = func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error) { return &InstanceDiff{ Attributes: map[string]*ResourceAttrDiff{ "num": &ResourceAttrDiff{ New: "bar", }, }, }, nil } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if _, ok := mod.Resources["aws_instance.baz"]; ok { t.Fatalf("bad: %#v", mod.Resources) } } func TestContext2Apply_destroyTaintedProvisioner(t *testing.T) { m := testModule(t, "apply-destroy-provisioner") p := testProvider("aws") pr := testProvisioner() p.ApplyFn = testApplyFn p.DiffFn = testDiffFn called := false pr.ApplyFn = func(rs *InstanceState, c *ResourceConfig) error { called = true return nil } s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo": &ResourceState{ Type: "aws_instance", Tainted: []*InstanceState{ &InstanceState{ ID: "bar", Attributes: map[string]string{ "id": "bar", }, }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Provisioners: map[string]ResourceProvisionerFactory{ "shell": testProvisionerFuncFixed(pr), }, State: s, Destroy: true, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } if called { t.Fatal("provisioner should not be called") } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace("<no state>") if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_error(t *testing.T) { errored := false m := testModule(t, "apply-error") p := testProvider("aws") ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) p.ApplyFn = func(*InstanceInfo, *InstanceState, *InstanceDiff) (*InstanceState, error) { if errored { state := &InstanceState{ ID: "bar", } return state, fmt.Errorf("error") } errored = true return &InstanceState{ ID: "foo", Attributes: map[string]string{ "num": "2", }, }, nil } p.DiffFn = func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error) { return &InstanceDiff{ Attributes: map[string]*ResourceAttrDiff{ "num": &ResourceAttrDiff{ New: "bar", }, }, }, nil } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err == nil { t.Fatal("should have error") } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyErrorStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_errorPartial(t *testing.T) { errored := false m := testModule(t, "apply-error") p := testProvider("aws") s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) p.ApplyFn = func(info *InstanceInfo, s *InstanceState, d *InstanceDiff) (*InstanceState, error) { if errored { return s, fmt.Errorf("error") } errored = true return &InstanceState{ ID: "foo", Attributes: map[string]string{ "num": "2", }, }, nil } p.DiffFn = func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error) { return &InstanceDiff{ Attributes: map[string]*ResourceAttrDiff{ "num": &ResourceAttrDiff{ New: "bar", }, }, }, nil } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err == nil { t.Fatal("should have error") } mod := state.RootModule() if len(mod.Resources) != 2 { t.Fatalf("bad: %#v", mod.Resources) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyErrorPartialStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_hook(t *testing.T) { m := testModule(t, "apply-good") h := new(MockHook) p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Hooks: []Hook{h}, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } if !h.PreApplyCalled { t.Fatal("should be called") } if !h.PostApplyCalled { t.Fatal("should be called") } if !h.PostStateUpdateCalled { t.Fatalf("should call post state update") } } func TestContext2Apply_hookOrphan(t *testing.T) { m := testModule(t, "apply-blank") h := new(MockHook) p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, State: state, Hooks: []Hook{h}, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } if _, err := ctx.Apply(); err != nil { t.Fatalf("err: %s", err) } if !h.PreApplyCalled { t.Fatal("should be called") } if !h.PostApplyCalled { t.Fatal("should be called") } if !h.PostStateUpdateCalled { t.Fatalf("should call post state update") } } func TestContext2Apply_idAttr(t *testing.T) { m := testModule(t, "apply-idattr") p := testProvider("aws") ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) p.ApplyFn = func(info *InstanceInfo, s *InstanceState, d *InstanceDiff) (*InstanceState, error) { result := s.MergeDiff(d) result.ID = "foo" result.Attributes = map[string]string{ "id": "bar", } return result, nil } p.DiffFn = func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error) { return &InstanceDiff{ Attributes: map[string]*ResourceAttrDiff{ "num": &ResourceAttrDiff{ New: "bar", }, }, }, nil } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() rs, ok := mod.Resources["aws_instance.foo"] if !ok { t.Fatal("not in state") } if rs.Primary.ID != "foo" { t.Fatalf("bad: %#v", rs.Primary.ID) } if rs.Primary.Attributes["id"] != "foo" { t.Fatalf("bad: %#v", rs.Primary.Attributes) } } func TestContext2Apply_output(t *testing.T) { m := testModule(t, "apply-output") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyOutputStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_outputInvalid(t *testing.T) { m := testModule(t, "apply-output-invalid") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) _, err := ctx.Plan() if err == nil { t.Fatalf("err: %s", err) } if !strings.Contains(err.Error(), "is not a string") { t.Fatalf("err: %s", err) } } func TestContext2Apply_outputAdd(t *testing.T) { m1 := testModule(t, "apply-output-add-before") p1 := testProvider("aws") p1.ApplyFn = testApplyFn p1.DiffFn = testDiffFn ctx1 := testContext2(t, &ContextOpts{ Module: m1, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p1), }, }) if _, err := ctx1.Plan(); err != nil { t.Fatalf("err: %s", err) } state1, err := ctx1.Apply() if err != nil { t.Fatalf("err: %s", err) } m2 := testModule(t, "apply-output-add-after") p2 := testProvider("aws") p2.ApplyFn = testApplyFn p2.DiffFn = testDiffFn ctx2 := testContext2(t, &ContextOpts{ Module: m2, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p2), }, State: state1, }) if _, err := ctx2.Plan(); err != nil { t.Fatalf("err: %s", err) } state2, err := ctx2.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state2.String()) expected := strings.TrimSpace(testTerraformApplyOutputAddStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_outputList(t *testing.T) { m := testModule(t, "apply-output-list") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyOutputListStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_outputMulti(t *testing.T) { m := testModule(t, "apply-output-multi") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyOutputMultiStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_outputMultiIndex(t *testing.T) { m := testModule(t, "apply-output-multi-index") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyOutputMultiIndexStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_taint(t *testing.T) { m := testModule(t, "apply-taint") p := testProvider("aws") // destroyCount tests against regression of // https://github.com/hashicorp/terraform/issues/1056 var destroyCount = int32(0) var once sync.Once simulateProviderDelay := func() { time.Sleep(10 * time.Millisecond) } p.ApplyFn = func(info *InstanceInfo, s *InstanceState, d *InstanceDiff) (*InstanceState, error) { once.Do(simulateProviderDelay) if d.Destroy { atomic.AddInt32(&destroyCount, 1) } return testApplyFn(info, s, d) } p.DiffFn = testDiffFn s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.bar": &ResourceState{ Type: "aws_instance", Tainted: []*InstanceState{ &InstanceState{ ID: "baz", Attributes: map[string]string{ "num": "2", "type": "aws_instance", }, }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyTaintStr) if actual != expected { t.Fatalf("bad:\n%s", actual) } if destroyCount != 1 { t.Fatalf("Expected 1 destroy, got %d", destroyCount) } } func TestContext2Apply_taintDep(t *testing.T) { m := testModule(t, "apply-taint-dep") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo": &ResourceState{ Type: "aws_instance", Tainted: []*InstanceState{ &InstanceState{ ID: "baz", Attributes: map[string]string{ "num": "2", "type": "aws_instance", }, }, }, }, "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "foo": "baz", "num": "2", "type": "aws_instance", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) if p, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } else { t.Logf("plan: %s", p) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyTaintDepStr) if actual != expected { t.Fatalf("bad:\n%s", actual) } } func TestContext2Apply_taintDepRequiresNew(t *testing.T) { m := testModule(t, "apply-taint-dep-requires-new") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn s := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo": &ResourceState{ Type: "aws_instance", Tainted: []*InstanceState{ &InstanceState{ ID: "baz", Attributes: map[string]string{ "num": "2", "type": "aws_instance", }, }, }, }, "aws_instance.bar": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "foo": "baz", "num": "2", "type": "aws_instance", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: s, }) if p, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } else { t.Logf("plan: %s", p) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyTaintDepRequireNewStr) if actual != expected { t.Fatalf("bad:\n%s", actual) } } func TestContext2Apply_targeted(t *testing.T) { m := testModule(t, "apply-targeted") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Targets: []string{"aws_instance.foo"}, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if len(mod.Resources) != 1 { t.Fatalf("expected 1 resource, got: %#v", mod.Resources) } checkStateString(t, state, ` aws_instance.foo: ID = foo num = 2 type = aws_instance `) } func TestContext2Apply_targetedCount(t *testing.T) { m := testModule(t, "apply-targeted-count") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Targets: []string{"aws_instance.foo"}, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } checkStateString(t, state, ` aws_instance.foo.0: ID = foo aws_instance.foo.1: ID = foo aws_instance.foo.2: ID = foo `) } func TestContext2Apply_targetedCountIndex(t *testing.T) { m := testModule(t, "apply-targeted-count") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Targets: []string{"aws_instance.foo[1]"}, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } checkStateString(t, state, ` aws_instance.foo.1: ID = foo `) } func TestContext2Apply_targetedDestroy(t *testing.T) { m := testModule(t, "apply-targeted") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo": resourceState("aws_instance", "i-bcd345"), "aws_instance.bar": resourceState("aws_instance", "i-abc123"), }, }, }, }, Targets: []string{"aws_instance.foo"}, Destroy: true, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if len(mod.Resources) != 1 { t.Fatalf("expected 1 resource, got: %#v", mod.Resources) } checkStateString(t, state, ` aws_instance.bar: ID = i-abc123 `) } // https://github.com/hashicorp/terraform/issues/4462 func TestContext2Apply_targetedDestroyModule(t *testing.T) { m := testModule(t, "apply-targeted-module") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo": resourceState("aws_instance", "i-bcd345"), "aws_instance.bar": resourceState("aws_instance", "i-abc123"), }, }, &ModuleState{ Path: []string{"root", "child"}, Resources: map[string]*ResourceState{ "aws_instance.foo": resourceState("aws_instance", "i-bcd345"), "aws_instance.bar": resourceState("aws_instance", "i-abc123"), }, }, }, }, Targets: []string{"module.child.aws_instance.foo"}, Destroy: true, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } checkStateString(t, state, ` aws_instance.bar: ID = i-abc123 aws_instance.foo: ID = i-bcd345 module.child: aws_instance.bar: ID = i-abc123 `) } func TestContext2Apply_targetedDestroyCountIndex(t *testing.T) { m := testModule(t, "apply-targeted-count") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.foo.0": resourceState("aws_instance", "i-bcd345"), "aws_instance.foo.1": resourceState("aws_instance", "i-bcd345"), "aws_instance.foo.2": resourceState("aws_instance", "i-bcd345"), "aws_instance.bar.0": resourceState("aws_instance", "i-abc123"), "aws_instance.bar.1": resourceState("aws_instance", "i-abc123"), "aws_instance.bar.2": resourceState("aws_instance", "i-abc123"), }, }, }, }, Targets: []string{ "aws_instance.foo[2]", "aws_instance.bar[1]", }, Destroy: true, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } checkStateString(t, state, ` aws_instance.bar.0: ID = i-abc123 aws_instance.bar.2: ID = i-abc123 aws_instance.foo.0: ID = i-bcd345 aws_instance.foo.1: ID = i-bcd345 `) } func TestContext2Apply_targetedModule(t *testing.T) { m := testModule(t, "apply-targeted-module") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Targets: []string{"module.child"}, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.ModuleByPath([]string{"root", "child"}) if mod == nil { t.Fatalf("no child module found in the state!\n\n%#v", state) } if len(mod.Resources) != 2 { t.Fatalf("expected 2 resources, got: %#v", mod.Resources) } checkStateString(t, state, ` <no state> module.child: aws_instance.bar: ID = foo num = 2 type = aws_instance aws_instance.foo: ID = foo num = 2 type = aws_instance `) } // GH-1858 func TestContext2Apply_targetedModuleDep(t *testing.T) { m := testModule(t, "apply-targeted-module-dep") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Targets: []string{"aws_instance.foo"}, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } checkStateString(t, state, ` aws_instance.foo: ID = foo foo = foo type = aws_instance Dependencies: module.child module.child: aws_instance.mod: ID = foo Outputs: output = foo `) } func TestContext2Apply_targetedModuleResource(t *testing.T) { m := testModule(t, "apply-targeted-module-resource") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Targets: []string{"module.child.aws_instance.foo"}, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.ModuleByPath([]string{"root", "child"}) if len(mod.Resources) != 1 { t.Fatalf("expected 1 resource, got: %#v", mod.Resources) } checkStateString(t, state, ` <no state> module.child: aws_instance.foo: ID = foo num = 2 type = aws_instance `) } func TestContext2Apply_unknownAttribute(t *testing.T) { m := testModule(t, "apply-unknown") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err == nil { t.Fatal("should error") } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyUnknownAttrStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_unknownAttributeInterpolate(t *testing.T) { m := testModule(t, "apply-unknown-interpolate") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) if _, err := ctx.Plan(); err == nil { t.Fatal("should error") } } func TestContext2Apply_vars(t *testing.T) { m := testModule(t, "apply-vars") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, Variables: map[string]string{ "foo": "us-west-2", "amis.us-east-1": "override", }, }) w, e := ctx.Validate() if len(w) > 0 { t.Fatalf("bad: %#v", w) } if len(e) > 0 { t.Fatalf("bad: %s", e) } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyVarsStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_varsEnv(t *testing.T) { // Set the env var old := tempEnv(t, "TF_VAR_ami", "baz") defer os.Setenv("TF_VAR_ami", old) m := testModule(t, "apply-vars-env") p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn ctx := testContext2(t, &ContextOpts{ Module: m, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, }) w, e := ctx.Validate() if len(w) > 0 { t.Fatalf("bad: %#v", w) } if len(e) > 0 { t.Fatalf("bad: %s", e) } if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyVarsEnvStr) if actual != expected { t.Fatalf("bad: \n%s", actual) } } func TestContext2Apply_createBefore_depends(t *testing.T) { m := testModule(t, "apply-depends-create-before") h := new(HookRecordApplyOrder) p := testProvider("aws") p.ApplyFn = testApplyFn p.DiffFn = testDiffFn state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.web": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "require_new": "ami-old", }, }, }, "aws_instance.lb": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "baz", Attributes: map[string]string{ "instance": "bar", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Hooks: []Hook{h}, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } h.Active = true state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } mod := state.RootModule() if len(mod.Resources) < 2 { t.Fatalf("bad: %#v", mod.Resources) } actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testTerraformApplyDependsCreateBeforeStr) if actual != expected { t.Fatalf("bad: \n%s\n%s", actual, expected) } // Test that things were managed _in the right order_ order := h.States diffs := h.Diffs if order[0].ID != "" || diffs[0].Destroy { t.Fatalf("should create new instance first: %#v", order) } if order[1].ID != "baz" { t.Fatalf("update must happen after create: %#v", order) } if order[2].ID != "bar" || !diffs[2].Destroy { t.Fatalf("destroy must happen after update: %#v", order) } } func TestContext2Apply_singleDestroy(t *testing.T) { m := testModule(t, "apply-depends-create-before") h := new(HookRecordApplyOrder) p := testProvider("aws") invokeCount := 0 p.ApplyFn = func(info *InstanceInfo, s *InstanceState, d *InstanceDiff) (*InstanceState, error) { invokeCount++ switch invokeCount { case 1: if d.Destroy { t.Fatalf("should not destroy") } if s.ID != "" { t.Fatalf("should not have ID") } case 2: if d.Destroy { t.Fatalf("should not destroy") } if s.ID != "baz" { t.Fatalf("should have id") } case 3: if !d.Destroy { t.Fatalf("should destroy") } if s.ID == "" { t.Fatalf("should have ID") } default: t.Fatalf("bad invoke count %d", invokeCount) } return testApplyFn(info, s, d) } p.DiffFn = testDiffFn state := &State{ Modules: []*ModuleState{ &ModuleState{ Path: rootModulePath, Resources: map[string]*ResourceState{ "aws_instance.web": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "bar", Attributes: map[string]string{ "require_new": "ami-old", }, }, }, "aws_instance.lb": &ResourceState{ Type: "aws_instance", Primary: &InstanceState{ ID: "baz", Attributes: map[string]string{ "instance": "bar", }, }, }, }, }, }, } ctx := testContext2(t, &ContextOpts{ Module: m, Hooks: []Hook{h}, Providers: map[string]ResourceProviderFactory{ "aws": testProviderFuncFixed(p), }, State: state, }) if _, err := ctx.Plan(); err != nil { t.Fatalf("err: %s", err) } h.Active = true state, err := ctx.Apply() if err != nil { t.Fatalf("err: %s", err) } if invokeCount != 3 { t.Fatalf("bad: %d", invokeCount) } }
mpl-2.0
sunjay/turtle
examples/star.rs
265
use turtle::Turtle; fn main() { let mut turtle = Turtle::new(); turtle.right(90.0); turtle.set_pen_size(4.0); turtle.set_pen_color("yellow"); for _ in 0..5 { turtle.forward(300.0); turtle.right(180.0 - (180.0 / 5.0)); } }
mpl-2.0
ufal/udpipe
src/model/pipeline.cpp
3079
// This file is part of UDPipe <http://github.com/ufal/udpipe/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "pipeline.h" #include "sentence/input_format.h" #include "sentence/output_format.h" #include "unilib/utf8.h" #include "utils/getwhole.h" namespace ufal { namespace udpipe { const string pipeline::DEFAULT; const string pipeline::NONE = "none"; pipeline::pipeline(const model* m, const string& input, const string& tagger, const string& parser, const string& output) : immediate(false) { set_model(m); set_input(input); set_tagger(tagger); set_parser(parser); set_output(output); } void pipeline::set_model(const model* m) { this->m = m; } void pipeline::set_input(const string& input) { tokenizer.clear(); if (input.empty()) { this->input = "conllu"; } else if (input == "tokenize" || input == "tokenizer") { this->input = "tokenizer"; } else if (input.compare(0, 10, "tokenizer=") == 0) { this->input = "tokenizer"; tokenizer.assign(input, 10, string::npos); } else { this->input = input; } } void pipeline::set_tagger(const string& tagger) { this->tagger = tagger; } void pipeline::set_parser(const string& parser) { this->parser = parser; } void pipeline::set_output(const string& output) { this->output = output.empty() ? "conllu" : output; } void pipeline::set_immediate(bool immediate) { this->immediate = immediate; } void pipeline::set_document_id(const string& document_id) { this->document_id = document_id; } bool pipeline::process(istream& is, ostream& os, string& error) const { error.clear(); sentence s; unique_ptr<input_format> reader; if (input == "tokenizer") { reader.reset(m->new_tokenizer(tokenizer)); if (!reader) return error.assign("The model does not have a tokenizer!"), false; } else { reader.reset(input_format::new_input_format(input)); if (!reader) return error.assign("The requested input format '").append(input).append("' does not exist!"), false; } reader->reset_document(document_id); unique_ptr<output_format> writer(output_format::new_output_format(output)); if (!writer) return error.assign("The requested output format '").append(output).append("' does not exist!"), false; string block; while (immediate ? reader->read_block(is, block) : bool(getwhole(is, block))) { reader->set_text(block); while (reader->next_sentence(s, error)) { if (tagger != NONE) if (!m->tag(s, tagger, error)) return false; if (parser != NONE) if (!m->parse(s, parser, error)) return false; writer->write_sentence(s, os); } if (!error.empty()) return false; } writer->finish_document(os); return true; } } // namespace udpipe } // namespace ufal
mpl-2.0
milescrabill/reaper_fork
securityGroup.go
613
package main import ( "github.com/aws/aws-sdk-go/service/ec2" ) type SecurityGroups []*SecurityGroup type SecurityGroup struct { AWSResource } func NewSecurityGroup(region string, sg *ec2.SecurityGroup) *SecurityGroup { s := SecurityGroup{ AWSResource{ ID: *sg.GroupID, Name: *sg.GroupName, Region: region, Description: *sg.Description, VPCID: *sg.VPCID, OwnerID: *sg.OwnerID, Tags: make(map[string]string), }, } for _, tag := range sg.Tags { s.Tags[*tag.Key] = *tag.Value } s.ReaperState = ParseState(s.Tags[reaper_tag]) return &s }
mpl-2.0
geek/joyent-portal
packages/my-joy-instances/src/components/create-instance/__tests__/title.ui.js
1034
import React from 'react'; import { toMatchImageSnapshot } from 'jest-image-snapshot'; import screenshot from 'react-screenshot-renderer'; import { NameIcon } from 'joyent-ui-toolkit'; import Title from '../title'; import Theme from '@mocks/theme'; expect.extend({ toMatchImageSnapshot }); it('<Title />', async () => { expect( await screenshot( <Theme ss> <Title /> </Theme> ) ).toMatchImageSnapshot(); }); it('<Title label="Test"/>', async () => { expect( await screenshot( <Theme ss> <Title label="Test" /> </Theme> ) ).toMatchImageSnapshot(); }); it('<Title icon="NameIcon"/>', async () => { expect( await screenshot( <Theme ss> <Title icon={<NameIcon />} /> </Theme> ) ).toMatchImageSnapshot(); }); it('<Title icon="Test" label="Instance name"/>', async () => { expect( await screenshot( <Theme ss> <Title icon={<NameIcon />} label="Instance name" /> </Theme> ) ).toMatchImageSnapshot(); });
mpl-2.0
communityshare/communityshare
community_share/__init__.py
3968
import os import logging import sys from functools import wraps from typing import Any, Callable from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.ext.declarative import declarative_base from community_share.config import load_app_config from community_share.crypt import CryptHelper Base = declarative_base() logger = logging.getLogger(__name__) def create_file_logger(path): os.makedirs(os.path.dirname(path), exist_ok=True) return logging.FileHandler(path) def create_stdout_logger(): return logging.StreamHandler(stream=sys.stdout) def setup_logging(level, directory): if directory == 'STDOUT': handler = create_stdout_logger() else: handler = create_file_logger(os.path.join(directory, 'community_share.log')) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) for package in {'__main__', 'community_share'}: module_logger = logging.getLogger(package) module_logger.addHandler(handler) module_logger.setLevel(level) class Store(object): def __init__(self): pass def set_config(self, config): logger.info('Creating database engine with {0}'.format(config.DB_CONNECTION)) self._engine = create_engine(config.DB_CONNECTION) self._session = scoped_session(sessionmaker(bind=self._engine)) @property def engine(self): return self._engine @property def session(self): return self._session store = Store() def with_store(f: Callable[..., Any]) -> Callable[..., Any]: """Provides the SqlAlchemy store to a function Use this instead of importing `communityshare.store` directly in order to make testing easy **Example** This creates a new in-memory store for testing .. sourcecode Python class Store(): engine = create_engine('sqlite:///:memory:') Session = sessionmaker(bind=engine) session = Session() normally_wrapped_function(store=Store()) :param f: function to wrap :return: new function with `store` param injected """ @wraps(f) def wrapped(*args, **kwargs): actual_store = kwargs.pop('store', store) return f(*args, store=actual_store, **kwargs) return wrapped class Config(object): NAMES = { 'APP_ENV', # 'development' or 'production' # Database 'DB_CONNECTION', # Email 'MAILER_TYPE', # Can be 'MAILGUN' or 'DUMMY' or 'QUEUE' 'MAILGUN_API_KEY', 'MAILGUN_DOMAIN', 'DONOTREPLY_EMAIL_ADDRESS', 'SUPPORT_EMAIL_ADDRESS', 'BUG_EMAIL_ADDRESS', 'ABUSE_EMAIL_ADDRESS', 'ADMIN_EMAIL_ADDRESSES', 'NOTIFY_EMAIL_ADDRESS', # Location 'BASEURL', # Logging 'LOGGING_LEVEL', 'LOGGING_LOCATION', # S3 bucket 'S3_BUCKETNAME', 'S3_KEY', 'S3_USERNAME', 'UPLOAD_LOCATION', # Cryptography 'ENCRYPTION_KEY', # SSL 'SSL', 'WEBPACK_ASSETS_URL', 'WEBPACK_MANIFEST_PATH', } def load_config(self, filename): data = load_app_config(self.NAMES, filename) if set(data.keys()) != self.NAMES: missing_keys = self.NAMES - set(data.keys()) invalid_keys = set(data.keys()) - self.NAMES sys.exit( 'Invalid configuration found:\n\tmissing keys: {}\n\tinvalid keys: {}' .format(missing_keys, invalid_keys) ) for key, value in data.items(): setattr(self, key, value) setup_logging(self.LOGGING_LEVEL, self.LOGGING_LOCATION) logger.info('Setup logging with level {0}'.format(self.LOGGING_LEVEL)) store.set_config(self) self.crypt_helper = CryptHelper(config.ENCRYPTION_KEY) config = Config()
mpl-2.0
sideci-sample/sideci-sample-devdocs
lib/docs/scrapers/chai.rb
617
module Docs class Chai < UrlScraper self.name = 'Chai' self.type = 'chai' self.version = '1.10.0' self.base_url = 'http://chaijs.com' self.root_path = '/api/' self.initial_paths = %w(/guide/installation/) html_filters.push 'chai/entries', 'chai/clean_html' options[:container] = '#content' options[:trailing_slash] = true options[:only_patterns] = [/\A\/guide/, /\A\/api/] options[:skip] = %w(/api/test/ /guide/ /guide/resources/) options[:attribution] = <<-HTML &copy; 2011&ndash;2014 Jake Luer<br> Licensed under the MIT License. HTML end end
mpl-2.0
oracle/terraform-provider-baremetal
vendor/github.com/oracle/oci-go-sdk/v46/core/change_cross_connect_compartment_details.go
1342
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Core Services API // // API covering the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm), // Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and // Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services. Use this API // to manage resources such as virtual cloud networks (VCNs), compute instances, and // block storage volumes. // package core import ( "github.com/oracle/oci-go-sdk/v46/common" ) // ChangeCrossConnectCompartmentDetails The configuration details for the move operation. type ChangeCrossConnectCompartmentDetails struct { // The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment to move the // cross-connect to. CompartmentId *string `mandatory:"true" json:"compartmentId"` } func (m ChangeCrossConnectCompartmentDetails) String() string { return common.PointerString(m) }
mpl-2.0
deanhiller/channelmanager2
input/javasrc/org/playorm/nio/api/libs/PacketProcessor.java
487
package org.playorm.nio.api.libs; import java.io.IOException; import java.nio.ByteBuffer; public interface PacketProcessor { public ByteBuffer processOutgoing(ByteBuffer b); /** * processIncoming reads from the ByteBuffer * @param true if we passed data to downstream listener, false if not * @return * @throws IOException */ public boolean incomingData(ByteBuffer b, Object passthrough) throws IOException; public void setPacketListener(PacketListener l); }
mpl-2.0
openWMail/openWMail
src/scenes/mailboxes/src/ui/Mailbox/Google/GoogleMailboxMeetTab.js
2312
const React = require('react') const MailboxTabSleepable = require('../MailboxTabSleepable') const Mailbox = require('shared/Models/Mailbox/Mailbox') const { settingsStore } = require('../../../stores/settings') const URL = window.nativeRequire('url') const REF = 'mailbox_tab' module.exports = React.createClass({ /* **************************************************************************/ // Class /* **************************************************************************/ displayName: 'GoogleMailboxMeetTab', propTypes: { mailboxId: React.PropTypes.string.isRequired }, /* **************************************************************************/ // Component lifecylce /* **************************************************************************/ componentDidMount () { settingsStore.listen(this.settingsChanged) }, componentWillUnmount () { settingsStore.unlisten(this.settingsChanged) }, /* **************************************************************************/ // Data lifecylce /* **************************************************************************/ getInitialState () { const settingsState = settingsStore.getState() return { os: settingsState.os } }, settingsChanged (settingsState) { this.setState({ os: settingsState.os }) }, /* **************************************************************************/ // Browser Events /* **************************************************************************/ /** * Opens a new url in the correct way * @param url: the url to open */ handleOpenNewWindow (url) { const purl = URL.parse(url, true) if (purl.host === 'meet.google.com') { this.setState({ browserSrc: url }) } }, /* **************************************************************************/ // Rendering /* **************************************************************************/ render () { const { mailboxId } = this.props return ( <MailboxTabSleepable ref={REF} src={this.state.browserSrc} preload='../platform/webviewInjection/googleService' mailboxId={mailboxId} service={Mailbox.SERVICES.MEET} newWindow={(evt) => { this.handleOpenNewWindow(evt.url) }} /> ) } })
mpl-2.0
Aris-t2/ClassicThemeRestorer
xpi/defaults/preferences/options.js
19299
// tab settings pref("extensions.classicthemerestorer.tabs","tabs_squared"); pref("extensions.classicthemerestorer.tabsontop",'unset'); pref("extensions.classicthemerestorer.ctabheightcb",false); pref("extensions.classicthemerestorer.ctabheight",28); pref("extensions.classicthemerestorer.square_edges",false); pref("extensions.classicthemerestorer.ctabfontsizecb",false); pref("extensions.classicthemerestorer.ctabfontsize",12); pref("extensions.classicthemerestorer.ctabmwidth",100); pref("extensions.classicthemerestorer.ctabwidth",210); pref("extensions.classicthemerestorer.emptyfavico_t",'emptyfavico_t_none'); pref("extensions.classicthemerestorer.noemptypticon",false); pref("extensions.classicthemerestorer.closetab","closetab_default"); pref("extensions.classicthemerestorer.closetabhfl",false); pref("extensions.classicthemerestorer.closeonleft",false); pref("extensions.classicthemerestorer.closetabbig",false); pref("extensions.classicthemerestorer.closeicon",'closeicon_default'); pref("extensions.classicthemerestorer.tttitlebar",false); pref("extensions.classicthemerestorer.tttitlebar_c",false); pref("extensions.classicthemerestorer.ttoverflow",'ttoverfl_def'); pref("extensions.classicthemerestorer.tabtitlepos",'tabtitlepos_default'); //Appbutton settings pref("extensions.classicthemerestorer.appbutton",'appbutton_v1'); pref("extensions.classicthemerestorer.appbuttonc",'appbuttonc_orange'); pref("extensions.classicthemerestorer.appbuttonct",false); pref("extensions.classicthemerestorer.altabico",'altabico_white'); pref("extensions.classicthemerestorer.appbutmhi",false); pref("extensions.classicthemerestorer.appbutbdl",false); pref("extensions.classicthemerestorer.dblclclosefx",false); pref("extensions.classicthemerestorer.appbclmmenus",true); pref("extensions.classicthemerestorer.appbautocol",false); pref("extensions.classicthemerestorer.appbuttontxt",''); pref("extensions.classicthemerestorer.cappbutc1",'#00FF00'); pref("extensions.classicthemerestorer.cappbutc2",'#007700'); pref("extensions.classicthemerestorer.cappbutpc1",'#CC33CC'); pref("extensions.classicthemerestorer.cappbutpc2",'#993399'); //General UI pref("extensions.classicthemerestorer.smallnavbut",false); pref("extensions.classicthemerestorer.bf_space",false); pref("extensions.classicthemerestorer.backforward",false); pref("extensions.classicthemerestorer.hide_bf_popup",false); pref("extensions.classicthemerestorer.hide_bf_pitem",false); pref("extensions.classicthemerestorer.nbcompact",false); pref("extensions.classicthemerestorer.statusbar",true); pref("extensions.classicthemerestorer.noconicons",false); pref("extensions.classicthemerestorer.altoptions",'options_alt'); pref("extensions.classicthemerestorer.aboutpages",false); pref("extensions.classicthemerestorer.svgfilters",false); pref("extensions.classicthemerestorer.combrelstop",false); pref("extensions.classicthemerestorer.activndicat",false); pref("extensions.classicthemerestorer.nbisizedelay",0); pref("extensions.classicthemerestorer.findbar","findbar_default"); pref("extensions.classicthemerestorer.findb_hide_ws",false); pref("extensions.classicthemerestorer.findb_widthcb",false); pref("extensions.classicthemerestorer.findb_widthva",170); pref("extensions.classicthemerestorer.nbisizedelay",0); pref("extensions.classicthemerestorer.nav_txt_ico","icons"); pref("extensions.classicthemerestorer.iat_notf_vt",false); pref("extensions.classicthemerestorer.wincontrols",false); pref("extensions.classicthemerestorer.puibuttonsep",'puib_nosep'); pref("extensions.classicthemerestorer.oldtoplevimg",false); pref("extensions.classicthemerestorer.oldtoplevimg2",false); pref("extensions.classicthemerestorer.altdlprogbar",false); pref("extensions.classicthemerestorer.altalertbox",false); pref("extensions.classicthemerestorer.emptyfavico_g",'emptyfavico_g_def'); pref("extensions.classicthemerestorer.panelmenucol",false); pref("extensions.classicthemerestorer.cpanelmenus",false); pref("extensions.classicthemerestorer.hidezoomres",false); pref("extensions.classicthemerestorer.alt_newtabp",false); pref("extensions.classicthemerestorer.nosnippets",false); pref("extensions.classicthemerestorer.ctroldsearch",false); pref("extensions.classicthemerestorer.ctroldsearchc",false); pref("extensions.classicthemerestorer.ctrosearchct",0); pref("extensions.classicthemerestorer.ctroldsearchr",false); pref("extensions.classicthemerestorer.ctrosearchrt",0); pref("extensions.classicthemerestorer.osearch_meoit",false); pref("extensions.classicthemerestorer.osearch_meoit2",true); pref("extensions.classicthemerestorer.search_ant",true); pref("extensions.classicthemerestorer.search_abl",true); pref("extensions.classicthemerestorer.search_aho",true); pref("extensions.classicthemerestorer.osearch_dm",false); pref("extensions.classicthemerestorer.osearch_iwidth",true); pref("extensions.classicthemerestorer.osearch_cwidth",false); pref("extensions.classicthemerestorer.os_spsize_minw",200); pref("extensions.classicthemerestorer.os_spsize_maxw",200); pref("extensions.classicthemerestorer.searchbardark",false); pref("extensions.classicthemerestorer.addonversion",true); pref("extensions.classicthemerestorer.alt_addonsm",true); pref("extensions.classicthemerestorer.am_nowarning",false); pref("extensions.classicthemerestorer.am_compact",false); pref("extensions.classicthemerestorer.am_compact2",true); pref("extensions.classicthemerestorer.am_highlight",true); pref("extensions.classicthemerestorer.am_buticons",false); pref("extensions.classicthemerestorer.am_hovshowb",false); pref("extensions.classicthemerestorer.alt_addonsp",false); pref("extensions.classicthemerestorer.am_showrecup",false); pref("extensions.classicthemerestorer.hideeditbm",false); pref("extensions.classicthemerestorer.oldplacesbut",false); pref("extensions.classicthemerestorer.bmbutpanelm",false); pref("extensions.classicthemerestorer.bmbunsortbm",false); pref("extensions.classicthemerestorer.bmbunsortbm2",true); pref("extensions.classicthemerestorer.bmbutnotb",false); pref("extensions.classicthemerestorer.bmbviewbmtb",false); pref("extensions.classicthemerestorer.bmbviewbmsb",false); pref("extensions.classicthemerestorer.bmbnounsort",false); pref("extensions.classicthemerestorer.bmbutnotext",false); pref("extensions.classicthemerestorer.bmbutclpopup",false); pref("extensions.classicthemerestorer.skipprintpr",false); pref("extensions.classicthemerestorer.tbconmenu",false); pref("extensions.classicthemerestorer.noresizerxp",false); pref("extensions.classicthemerestorer.pmhidelabels",false); pref("extensions.classicthemerestorer.menupopupscr",false); pref("extensions.classicthemerestorer.hideprivmask",false); pref("extensions.classicthemerestorer.urlresults",false); pref("extensions.classicthemerestorer.cresultshcb",false); pref("extensions.classicthemerestorer.cresultsh",400); pref("extensions.classicthemerestorer.tabmokcolor",false); pref("extensions.classicthemerestorer.tabmokcolor2",false); pref("extensions.classicthemerestorer.tabmokcolor3",false); pref("extensions.classicthemerestorer.tabmokcolor4",false); pref("extensions.classicthemerestorer.invicomenubar",false); pref("extensions.classicthemerestorer.invicotabsbar",false); pref("extensions.classicthemerestorer.inviconavbar",false); pref("extensions.classicthemerestorer.invicoextrabar",false); pref("extensions.classicthemerestorer.invicobookbar",false); pref("extensions.classicthemerestorer.invicoaddonbar",false); pref("extensions.classicthemerestorer.closeicong",'closeicong_default'); pref("extensions.classicthemerestorer.athrobberurl",""); pref("extensions.classicthemerestorer.anewtaburlcb",false); pref("extensions.classicthemerestorer.anewtaburl","about:newtab"); pref("extensions.classicthemerestorer.anewtaburlpcb",false); pref("extensions.classicthemerestorer.anewtaburlp","about:privatebrowsing"); pref("extensions.classicthemerestorer.anewtaburlpf",false); pref("extensions.classicthemerestorer.tabseparator","tabsep_default"); // Urlbar pref("extensions.classicthemerestorer.starinurl",false); pref("extensions.classicthemerestorer.feedinurl",false); pref("extensions.classicthemerestorer.hideurelstop",false); pref("extensions.classicthemerestorer.hideurelstop2",false); pref("extensions.classicthemerestorer.hideurlgo",false); pref("extensions.classicthemerestorer.hideurlsrg",false); pref("extensions.classicthemerestorer.hideprbutton",false); pref("extensions.classicthemerestorer.urlbardropm",false); pref("extensions.classicthemerestorer.urlbardropm2",false); pref("extensions.classicthemerestorer.altreaderico",false); pref("extensions.classicthemerestorer.hideurlzoom",false); pref("extensions.classicthemerestorer.urlbardark",false); pref("extensions.classicthemerestorer.altautocompl",false); pref("extensions.classicthemerestorer.autocompl_it",false); pref("extensions.classicthemerestorer.autocompl_it2",false); pref("extensions.classicthemerestorer.autocompl_hlb",false); pref("extensions.classicthemerestorer.autocompl_hlu",false); pref("extensions.classicthemerestorer.autocompl_hli",false); pref("extensions.classicthemerestorer.autocompl_hln",false); pref("extensions.classicthemerestorer.autocompl_sep",false); pref("extensions.classicthemerestorer.autocompl_not",false); pref("extensions.classicthemerestorer.autocompl_rhl",false); pref("extensions.classicthemerestorer.ib_nohovcolor",false); pref("extensions.classicthemerestorer.ib_graycolor",false); pref("extensions.classicthemerestorer.verifiedcolors",false); pref("extensions.classicthemerestorer.ibinfoico",false); pref("extensions.classicthemerestorer.ibinfoico2",false); pref("extensions.classicthemerestorer.iblabels",false); pref("extensions.classicthemerestorer.faviconurl",false); pref("extensions.classicthemerestorer.padlock","padlock_default"); pref("extensions.classicthemerestorer.padlockex",true); pref("extensions.classicthemerestorer.icopageinfo",false); pref("extensions.classicthemerestorer.extraurlkeycb",false); pref("extensions.classicthemerestorer.extraurltarget",'tab'); pref("extensions.classicthemerestorer.locsearchbw10",false); pref("extensions.classicthemerestorer.lb_width",false); pref("extensions.classicthemerestorer.lbsize_minw",200); pref("extensions.classicthemerestorer.lbsize_maxw",4000); pref("extensions.classicthemerestorer.sb_width",false); pref("extensions.classicthemerestorer.sbsize_minw",200); pref("extensions.classicthemerestorer.sbsize_maxw",4000); pref("extensions.classicthemerestorer.lb_roundness",false); pref("extensions.classicthemerestorer.lbradius_left",0); pref("extensions.classicthemerestorer.lbradius_right",0); pref("extensions.classicthemerestorer.sb_roundness",false); pref("extensions.classicthemerestorer.sbradius_left",0); pref("extensions.classicthemerestorer.sbradius_right",0); pref("extensions.classicthemerestorer.lbfontsizecb",false); pref("extensions.classicthemerestorer.lbfontsize",12); pref("extensions.classicthemerestorer.sbfontsizecb",false); pref("extensions.classicthemerestorer.sbfontsize",12); // Toolbar settings pref("extensions.classicthemerestorer.aerocolors",false); pref("extensions.classicthemerestorer.aerocolorsg",false); pref("extensions.classicthemerestorer.transpttbw10",false); pref("extensions.classicthemerestorer.transpttbew10",false); pref("extensions.classicthemerestorer.transptcw10",false); pref("extensions.classicthemerestorer.nbiconsize",'small'); pref("extensions.classicthemerestorer.nobookbarbg",false); pref("extensions.classicthemerestorer.bookbarfs",false); pref("extensions.classicthemerestorer.hidenavbar",false); pref("extensions.classicthemerestorer.nonavbarbg",false); pref("extensions.classicthemerestorer.nonavborder",false); pref("extensions.classicthemerestorer.nonavtbborder",false); pref("extensions.classicthemerestorer.toptb_oldpad",false); pref("extensions.classicthemerestorer.hidesbclose",false); pref("extensions.classicthemerestorer.comp_sbheader",false); pref("extensions.classicthemerestorer.hidesidebardm",false); pref("extensions.classicthemerestorer.notextshadow",false); pref("extensions.classicthemerestorer.chevronfix",false); pref("extensions.classicthemerestorer.tbsep_winc",false); pref("extensions.classicthemerestorer.dblclnewtab",false); pref("extensions.classicthemerestorer.hidetbwot",false); pref("extensions.classicthemerestorer.hidetbwote",true); pref("extensions.classicthemerestorer.hidetbwote2",true); pref("extensions.classicthemerestorer.notabfog",false); pref("extensions.classicthemerestorer.notabbg",false); pref("extensions.classicthemerestorer.hightabpososx",false); pref("extensions.classicthemerestorer.showalltabsb",false); pref("extensions.classicthemerestorer.alttabstb",false); pref("extensions.classicthemerestorer.alttabstb2",true); pref("extensions.classicthemerestorer.altmenubar",false); pref("extensions.classicthemerestorer.altmbarpos",'altmbarpos0'); pref("extensions.classicthemerestorer.menubarfs",false); pref("extensions.classicthemerestorer.menubarnofog",false); pref("extensions.classicthemerestorer.closeabarbut",false); pref("extensions.classicthemerestorer.highaddonsbar",false); pref("extensions.classicthemerestorer.lessaddonsbar",false); pref("extensions.classicthemerestorer.addonbarfs",false); pref("extensions.classicthemerestorer.noaddonbarbg",false); pref("extensions.classicthemerestorer.am_extrabars",1); pref("extensions.classicthemerestorer.mbarposition","toolbar-menubar"); pref("extensions.classicthemerestorer.mbarpositionl","toolbar-menubar"); pref("extensions.classicthemerestorer.mbarforceleft",false); pref("extensions.classicthemerestorer.mbarforceright",false); pref("extensions.classicthemerestorer.navbarpad",false); pref("extensions.classicthemerestorer.navbarpad_l",3); pref("extensions.classicthemerestorer.navbarpad_r",3); pref("extensions.classicthemerestorer.navbarmar_l",0); pref("extensions.classicthemerestorer.navbarmar_r",0); // Animation pref("extensions.classicthemerestorer.tabthrobber","throbber_default"); pref("extensions.classicthemerestorer.bmanimation",true); pref("extensions.classicthemerestorer.pananimation",true); pref("extensions.classicthemerestorer.fsaduration",true); pref("extensions.classicthemerestorer.html5warning",true); // CTR area pref("extensions.classicthemerestorer.toolsitem",true); pref("extensions.classicthemerestorer.appmenuitem",true); pref("extensions.classicthemerestorer.contextitem",false); pref("extensions.classicthemerestorer.puictrbutton",false); pref("extensions.classicthemerestorer.cuibuttons",true); pref("extensions.classicthemerestorer.nodevtheme2",false); pref("extensions.classicthemerestorer.restartapp",true); pref("extensions.classicthemerestorer.restartapp2",false); pref("extensions.classicthemerestorer.showfx57pcomp",false); pref("extensions.classicthemerestorer.ctrnewinv",true); pref("extensions.classicthemerestorer.contextfind",false); pref("extensions.classicthemerestorer.pw_actidx_c",1); pref("extensions.classicthemerestorer.pw_actidx_t",0); pref("extensions.classicthemerestorer.pw_actidx_tc",0); pref("extensions.classicthemerestorer.pw_actidx_g",0); pref("extensions.classicthemerestorer.pw_actidx_tb",0); pref("extensions.classicthemerestorer.pw_actidx_lb",0); pref("extensions.classicthemerestorer.pw_actidx_sb",0); // Advanced pref("extensions.classicthemerestorer.oldfontgfx",false); // Tab color settings pref("extensions.classicthemerestorer.tabcolor_def",false); pref("extensions.classicthemerestorer.tabcolor_act",false); pref("extensions.classicthemerestorer.tabcolor_pen",false); pref("extensions.classicthemerestorer.tabcolor_unr",false); pref("extensions.classicthemerestorer.tabcolor_hov",false); pref("extensions.classicthemerestorer.ntabcolor_def",false); pref("extensions.classicthemerestorer.ntabcolor_hov",false); pref("extensions.classicthemerestorer.ctab1",'#00FF00'); pref("extensions.classicthemerestorer.ctab2",'#007700'); pref("extensions.classicthemerestorer.ctabhov1",'#FFFFBB'); pref("extensions.classicthemerestorer.ctabhov2",'#FFFF00'); pref("extensions.classicthemerestorer.ctabact1",'#FF8800'); pref("extensions.classicthemerestorer.ctabact2",'#FF0000'); pref("extensions.classicthemerestorer.ctabpen1",'#00FF00'); pref("extensions.classicthemerestorer.ctabpen2",'#007700'); pref("extensions.classicthemerestorer.ctabunr1",'#00FF00'); pref("extensions.classicthemerestorer.ctabunr2",'#007700'); pref("extensions.classicthemerestorer.cntab1",'#00FF00'); pref("extensions.classicthemerestorer.cntab2",'#007700'); pref("extensions.classicthemerestorer.cntabhov1",'#FFFFBB'); pref("extensions.classicthemerestorer.cntabhov2",'#FFFF00'); pref("extensions.classicthemerestorer.tabtextc_def",false); pref("extensions.classicthemerestorer.tabtextc_act",false); pref("extensions.classicthemerestorer.tabtextc_pen",false); pref("extensions.classicthemerestorer.tabtextc_unr",false); pref("extensions.classicthemerestorer.tabtextc_hov",false); pref("extensions.classicthemerestorer.ctabt",'#000000'); pref("extensions.classicthemerestorer.ctabhovt",'#000000'); pref("extensions.classicthemerestorer.ctabactt",'#000000'); pref("extensions.classicthemerestorer.ctabpent",'#000000'); pref("extensions.classicthemerestorer.ctabunrt",'#000000'); pref("extensions.classicthemerestorer.tabtextsh_def",false); pref("extensions.classicthemerestorer.tabtextsh_act",false); pref("extensions.classicthemerestorer.tabtextsh_pen",false); pref("extensions.classicthemerestorer.tabtextsh_unr",false); pref("extensions.classicthemerestorer.tabtextsh_hov",false); pref("extensions.classicthemerestorer.ctabtsh",'#FFFFFF'); pref("extensions.classicthemerestorer.ctabhovtsh",'#FFFFFF'); pref("extensions.classicthemerestorer.ctabacttsh",'#FFFFFF'); pref("extensions.classicthemerestorer.ctabpentsh",'#FFFFFF'); pref("extensions.classicthemerestorer.ctabunrtsh",'#FFFFFF'); pref("extensions.classicthemerestorer.tabfbold_def",false); pref("extensions.classicthemerestorer.tabfbold_act",false); pref("extensions.classicthemerestorer.tabfbold_pen",false); pref("extensions.classicthemerestorer.tabfbold_unr",false); pref("extensions.classicthemerestorer.tabfbold_hov",false); pref("extensions.classicthemerestorer.tabfita_def",false); pref("extensions.classicthemerestorer.tabfita_act",false); pref("extensions.classicthemerestorer.tabfita_pen",false); pref("extensions.classicthemerestorer.tabfita_unr",false); pref("extensions.classicthemerestorer.tabfita_hov",false); pref("extensions.classicthemerestorer.tablowopa_pen",false); pref("extensions.classicthemerestorer.tablowopa_unr",false); pref("extensions.classicthemerestorer.tabc_act_tb",false); pref("extensions.classicthemerestorer.tabc_hov_unr",false); pref("extensions.classicthemerestorer.tabc_hov_unl",false); pref("extensions.classicthemerestorer.optionsrem",true); pref("extensions.classicthemerestorer.aboutprefs",'category-general'); pref("extensions.classicthemerestorer.aboutprefsInd",0); pref("extensions.classicthemerestorer.aboutprefsww",850); pref("extensions.classicthemerestorer.aboutprefswh",670); // css override pref("extensions.classicthemerestorer.cssoverride",false); pref("extensions.classicthemerestorer.cssoverridec",''); // first run/reset preference pref("extensions.classicthemerestorer.ctrreset",true); // other pref("extensions.classicthemerestorer.cstatextlb",false);
mpl-2.0
mcarton/rust-herbie-lint
tests/compile-fail/no-db/test.rs
165
#![feature(plugin)] //~ERROR: Could not initialize Herbie-Lint #![plugin(herbie_lint)] #![allow(unused_variables)] #![deny(herbie)] fn main() { let a = 42.; }
mpl-2.0
Helioviewer-Project/JHelioviewer-SWHV
src/org/helioviewer/jhv/timelines/Timelines.java
2344
package org.helioviewer.jhv.timelines; import java.util.ArrayList; import java.util.List; import javax.swing.JComponent; import org.helioviewer.jhv.events.JHVRelatedEvents; import org.helioviewer.jhv.gui.JHVFrame; import org.helioviewer.jhv.gui.interfaces.MainContentPanelPlugin; import org.helioviewer.jhv.layers.Movie; import org.helioviewer.jhv.timelines.chart.PlotPanel; import org.helioviewer.jhv.timelines.draw.DrawController; import org.helioviewer.jhv.timelines.radio.RadioData; import org.helioviewer.jhv.timelines.gui.TimelineDialog; import org.helioviewer.jhv.timelines.selector.TimelinePanel; import org.json.JSONObject; public class Timelines implements MainContentPanelPlugin { private static final TimelineLayers layers = new TimelineLayers(); public static final DrawController dc = new DrawController(); // sucks public static final TimelineDialog td = new TimelineDialog(); private final List<JComponent> pluginPanes = new ArrayList<>(); private final PlotPanel plotOne = new PlotPanel(); private static final TimelinePanel timelinePanel = new TimelinePanel(layers); public Timelines() { layers.add(new RadioData(null)); } public static TimelineLayers getLayers() { return layers; } public void installTimelines() { pluginPanes.add(plotOne); JHVFrame.getLeftContentPane().add("Timeline Layers", timelinePanel, true); JHVFrame.getLeftContentPane().revalidate(); JHVFrame.getMainContentPanel().addPlugin(this); Movie.addTimeListener(dc); JHVRelatedEvents.addHighlightListener(dc); } public void uninstallTimelines() { JHVRelatedEvents.removeHighlightListener(dc); Movie.removeTimeListener(dc); JHVFrame.getMainContentPanel().removePlugin(this); JHVFrame.getLeftContentPane().remove(timelinePanel); JHVFrame.getLeftContentPane().revalidate(); pluginPanes.remove(plotOne); } @Override public String getTabName() { return "Timelines"; } @Override public List<JComponent> getVisualInterfaces() { return pluginPanes; } public static void saveState(JSONObject jo) { DrawController.saveState(jo); } public static void loadState(JSONObject jo) { DrawController.loadState(jo); } }
mpl-2.0
ranjib/nomad
api/allocations.go
2978
package api import ( "sort" "time" ) // Allocations is used to query the alloc-related endpoints. type Allocations struct { client *Client } // Allocations returns a handle on the allocs endpoints. func (c *Client) Allocations() *Allocations { return &Allocations{client: c} } // List returns a list of all of the allocations. func (a *Allocations) List(q *QueryOptions) ([]*AllocationListStub, *QueryMeta, error) { var resp []*AllocationListStub qm, err := a.client.query("/v1/allocations", &resp, q) if err != nil { return nil, nil, err } sort.Sort(AllocIndexSort(resp)) return resp, qm, nil } func (a *Allocations) PrefixList(prefix string) ([]*AllocationListStub, *QueryMeta, error) { return a.List(&QueryOptions{Prefix: prefix}) } // Info is used to retrieve a single allocation. func (a *Allocations) Info(allocID string, q *QueryOptions) (*Allocation, *QueryMeta, error) { var resp Allocation qm, err := a.client.query("/v1/allocation/"+allocID, &resp, q) if err != nil { return nil, nil, err } return &resp, qm, nil } // Allocation is used for serialization of allocations. type Allocation struct { ID string EvalID string Name string NodeID string JobID string Job *Job TaskGroup string Resources *Resources TaskResources map[string]*Resources Services map[string]string Metrics *AllocationMetric DesiredStatus string DesiredDescription string ClientStatus string ClientDescription string TaskStates map[string]*TaskState CreateIndex uint64 ModifyIndex uint64 CreateTime int64 } // AllocationMetric is used to deserialize allocation metrics. type AllocationMetric struct { NodesEvaluated int NodesFiltered int NodesAvailable map[string]int ClassFiltered map[string]int ConstraintFiltered map[string]int NodesExhausted int ClassExhausted map[string]int DimensionExhausted map[string]int Scores map[string]float64 AllocationTime time.Duration CoalescedFailures int } // AllocationListStub is used to return a subset of an allocation // during list operations. type AllocationListStub struct { ID string EvalID string Name string NodeID string JobID string TaskGroup string DesiredStatus string DesiredDescription string ClientStatus string ClientDescription string TaskStates map[string]*TaskState CreateIndex uint64 ModifyIndex uint64 CreateTime int64 } // AllocIndexSort reverse sorts allocs by CreateIndex. type AllocIndexSort []*AllocationListStub func (a AllocIndexSort) Len() int { return len(a) } func (a AllocIndexSort) Less(i, j int) bool { return a[i].CreateIndex > a[j].CreateIndex } func (a AllocIndexSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
mpl-2.0
dominictassio/galactic
tmp/cache/mustache/__Mustache_9364d51abd17b3b61f965ffbbb181505.php
4210
<?php class __Mustache_9364d51abd17b3b61f965ffbbb181505 extends Mustache_Template { public function renderInternal(Mustache_Context $context, $indent = '') { $buffer = ''; $newContext = array(); $buffer .= $indent . '<!doctype html> '; $buffer .= $indent . '<html lang="en"> '; $buffer .= $indent . '<head> '; $buffer .= $indent . ' <meta charset="utf-8"> '; $buffer .= $indent . ' <meta http-equiv="X-UA-Compatible" content="IE=edge"> '; $buffer .= $indent . ' <meta name="viewport" content="width=device-width, initial-scale=1"> '; $buffer .= $indent . ' '; $buffer .= $indent . ' <title>Galactic</title> '; $buffer .= $indent . ' '; $buffer .= $indent . ' <link href="assets/css/bootstrap.min.css" rel="stylesheet"> '; $buffer .= $indent . ' '; $buffer .= $indent . ' <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> '; $buffer .= $indent . ' <!--[if lt IE 9]> '; $buffer .= $indent . ' <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> '; $buffer .= $indent . ' <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> '; $buffer .= $indent . ' <![endif]--> '; $buffer .= $indent . ' '; $buffer .= $indent . ' '; $buffer .= $indent . '</head> '; $buffer .= $indent . '<body> '; $buffer .= $indent . ' '; $buffer .= $indent . ' <nav class="navbar navbar-inverse navbar-fixed-top"> '; $buffer .= $indent . ' <div class="container"> '; $buffer .= $indent . ' <div class="navbar-header"> '; $buffer .= $indent . ' <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> '; $buffer .= $indent . ' <span class="sr-only">Toggle navigation</span> '; $buffer .= $indent . ' <span class="icon-bar"></span> '; $buffer .= $indent . ' <span class="icon-bar"></span> '; $buffer .= $indent . ' <span class="icon-bar"></span> '; $buffer .= $indent . ' </button> '; $buffer .= $indent . ' <a class="navbar-brand" href="#">Project name</a> '; $buffer .= $indent . ' </div> '; $buffer .= $indent . ' <div id="navbar" class="collapse navbar-collapse"> '; $buffer .= $indent . ' <ul class="nav navbar-nav"> '; $buffer .= $indent . ' <li class="active"><a href="#">Home</a></li> '; $buffer .= $indent . ' <li><a href="#about">About</a></li> '; $buffer .= $indent . ' <li><a href="#contact">Contact</a></li> '; $buffer .= $indent . ' </ul> '; $buffer .= $indent . ' </div><!--/.nav-collapse --> '; $buffer .= $indent . ' </div> '; $buffer .= $indent . ' </nav> '; $buffer .= $indent . ' '; $buffer .= $indent . ' <div class="container"> '; $buffer .= $indent . ' '; $buffer .= $indent . ' <div class="starter-template"> '; $buffer .= $indent . ' <h1>Bootstrap starter template</h1> '; $buffer .= $indent . ' <p class="lead">'; $value = $this->resolveValue($context->find('welcome'), $context, $indent); $buffer .= htmlspecialchars($value, 2, 'UTF-8'); $buffer .= '</p> '; $buffer .= $indent . ' </div> '; $buffer .= $indent . ' '; $buffer .= $indent . ' </div> '; $buffer .= $indent . ' '; $buffer .= $indent . ' <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> '; $buffer .= $indent . ' <script src="assets/js/bootstrap.min.js"></script> '; $buffer .= $indent . '</body> '; $buffer .= $indent . '</html>'; return $buffer; } }
mpl-2.0
okriuchykhin/scinote-web
app/controllers/search_controller.rb
10031
class SearchController < ApplicationController include IconsHelper before_action :load_vars, only: :index def index redirect_to new_search_path unless @search_query @search_id = params[:search_id] ? params[:search_id] : generate_search_id count_search_results search_projects if @search_category == :projects search_experiments if @search_category == :experiments search_modules if @search_category == :modules search_results if @search_category == :results search_tags if @search_category == :tags search_reports if @search_category == :reports search_protocols if @search_category == :protocols search_steps if @search_category == :steps search_checklists if @search_category == :checklists if @search_category == :repositories && params[:repository] search_repository end search_assets if @search_category == :assets search_tables if @search_category == :tables search_comments if @search_category == :comments @search_pages = (@search_count.to_f / Constants::SEARCH_LIMIT.to_f).ceil @start_page = @search_page - 2 @start_page = 1 if @start_page < 1 @end_page = @start_page + 4 if @end_page > @search_pages @end_page = @search_pages @start_page = @end_page - 4 @start_page = 1 if @start_page < 1 end end def new end private def load_vars query = (params.fetch(:q) { '' }).strip @search_category = params[:category] || '' @search_category = @search_category.to_sym @search_page = params[:page].to_i || 1 @search_case = params[:match_case] == 'true' @search_whole_word = params[:whole_word] == 'true' @search_whole_phrase = params[:whole_phrase] == 'true' @display_query = query if @search_whole_phrase || query.count(' ').zero? if query.length < Constants::NAME_MIN_LENGTH flash[:error] = t('general.query.length_too_short', min_length: Constants::NAME_MIN_LENGTH) redirect_back(fallback_location: root_path) elsif query.length > Constants::TEXT_MAX_LENGTH flash[:error] = t('general.query.length_too_long', max_length: Constants::TEXT_MAX_LENGTH) redirect_back(fallback_location: root_path) else @search_query = query end else # splits the search query to validate all entries splited_query = query.split @search_query = '' splited_query.each_with_index do |w, i| if w.length >= Constants::NAME_MIN_LENGTH && w.length <= Constants::TEXT_MAX_LENGTH @search_query += "#{splited_query[i]} " end end if @search_query.empty? flash[:error] = t('general.query.wrong_query', min_length: Constants::NAME_MIN_LENGTH, max_length: Constants::TEXT_MAX_LENGTH) redirect_back(fallback_location: root_path) else @search_query.strip! end end @search_page = 1 if @search_page < 1 end protected def generate_search_id SecureRandom.urlsafe_base64(32) end def search_by_name(model) model.search(current_user, true, @search_query, @search_page, nil, match_case: @search_case, whole_word: @search_whole_word, whole_phrase: @search_whole_phrase) end def count_by_name(model) model.search(current_user, true, @search_query, Constants::SEARCH_NO_LIMIT, nil, match_case: @search_case, whole_word: @search_whole_word, whole_phrase: @search_whole_phrase).size end def count_by_repository @repository_search_count = Rails.cache.fetch("#{@search_id}/repository_search_count", expires_in: 5.minutes) do search_count = {} search_results = Repository.search(current_user, @search_query, Constants::SEARCH_NO_LIMIT, nil, match_case: @search_case, whole_word: @search_whole_word, whole_phrase: @search_whole_phrase) current_user.teams.includes(:repositories).each do |team| team_results = {} team_results[:team] = team team_results[:count] = 0 team_results[:repositories] = {} Repository.accessible_by_teams(team).each do |repository| repository_results = {} repository_results[:id] = repository.id repository_results[:repository] = repository repository_results[:count] = 0 search_results.each do |result| repository_results[:count] += result.counter if repository.id == result.id end team_results[:repositories][repository.name] = repository_results team_results[:count] += repository_results[:count] end search_count[team.name] = team_results end search_count end count_total = 0 @repository_search_count.each_value do |team_results| count_total += team_results[:count] end count_total end def current_repository_search_count @repository_search_count.each_value do |counter| res = counter[:repositories].values.detect do |rep| rep[:id] == @repository.id end return res[:count] if res && res[:count] end end def count_search_results @project_search_count = fetch_cached_count Project @experiment_search_count = fetch_cached_count Experiment @module_search_count = fetch_cached_count MyModule @result_search_count = fetch_cached_count Result @tag_search_count = fetch_cached_count Tag @report_search_count = fetch_cached_count Report @protocol_search_count = fetch_cached_count Protocol @step_search_count = fetch_cached_count Step @checklist_search_count = fetch_cached_count Checklist @repository_search_count_total = count_by_repository @asset_search_count = fetch_cached_count Asset @table_search_count = fetch_cached_count Table @comment_search_count = fetch_cached_count Comment @search_results_count = @project_search_count @search_results_count += @experiment_search_count @search_results_count += @module_search_count @search_results_count += @result_search_count @search_results_count += @tag_search_count @search_results_count += @report_search_count @search_results_count += @protocol_search_count @search_results_count += @step_search_count @search_results_count += @checklist_search_count @search_results_count += @repository_search_count_total @search_results_count += @asset_search_count @search_results_count += @table_search_count @search_results_count += @comment_search_count end def fetch_cached_count(type) exp = 5.minutes Rails.cache.fetch( "#{@search_id}/#{type.name.underscore}_search_count", expires_in: exp ) do count_by_name type end end def search_projects @project_results = [] @project_results = search_by_name(Project) if @project_search_count > 0 @search_count = @project_search_count end def search_experiments @experiment_results = [] if @experiment_search_count > 0 @experiment_results = search_by_name(Experiment) end @search_count = @experiment_search_count end def search_modules @module_results = [] @module_results = search_by_name(MyModule) if @module_search_count > 0 @search_count = @module_search_count end def search_results @result_results = [] @result_results = search_by_name(Result) if @result_search_count > 0 @search_count = @result_search_count end def search_tags @tag_results = [] @tag_results = search_by_name(Tag) if @tag_search_count > 0 @search_count = @tag_search_count end def search_reports @report_results = [] @report_results = search_by_name(Report) if @report_search_count > 0 @search_count = @report_search_count end def search_protocols @protocol_results = [] @protocol_results = search_by_name(Protocol) if @protocol_search_count > 0 @search_count = @protocol_search_count end def search_steps @step_results = [] @step_results = search_by_name(Step) if @step_search_count > 0 @search_count = @step_search_count end def search_checklists @checklist_results = [] if @checklist_search_count > 0 @checklist_results = search_by_name(Checklist) end @search_count = @checklist_search_count end def search_repository @repository = Repository.find_by_id(params[:repository]) unless current_user.teams.include?(@repository.team) || @repository.private_shared_with?(current_user.teams) render_403 end @repository_results = [] if @repository_search_count_total > 0 @repository_results = Repository.search(current_user, @search_query, @search_page, @repository, match_case: @search_case, whole_word: @search_whole_word, whole_phrase: @search_whole_phrase) end @search_count = current_repository_search_count end def search_assets @asset_results = [] @asset_results = search_by_name(Asset) if @asset_search_count > 0 @search_count = @asset_search_count end def search_tables @table_results = [] @table_results = search_by_name(Table) if @table_search_count > 0 @search_count = @table_search_count end def search_comments @comment_results = [] @comment_results = search_by_name(Comment) if @comment_search_count > 0 @search_count = @comment_search_count end end
mpl-2.0
Yukarumya/Yukarum-Redfoxes
dom/media/directshow/DirectShowDecoder.cpp
1461
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et cindent: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "DirectShowDecoder.h" #include "DirectShowReader.h" #include "DirectShowUtils.h" #include "MediaContainerType.h" #include "MediaDecoderStateMachine.h" #include "mozilla/Preferences.h" #include "mozilla/WindowsVersion.h" namespace mozilla { MediaDecoderStateMachine* DirectShowDecoder::CreateStateMachine() { return new MediaDecoderStateMachine(this, new DirectShowReader(this)); } /* static */ bool DirectShowDecoder::GetSupportedCodecs(const MediaContainerType& aType, MediaCodecs* aOutCodecs) { if (!IsEnabled()) { return false; } if (aType.Type() == MEDIAMIMETYPE("audio/mpeg") || aType.Type() == MEDIAMIMETYPE("audio/mp3")) { if (aOutCodecs) { *aOutCodecs = MediaCodecs("mp3"); } return true; } return false; } /* static */ bool DirectShowDecoder::IsEnabled() { return CanDecodeMP3UsingDirectShow() && Preferences::GetBool("media.directshow.enabled"); } DirectShowDecoder::DirectShowDecoder(MediaDecoderOwner* aOwner) : MediaDecoder(aOwner) { } DirectShowDecoder::~DirectShowDecoder() = default; } // namespace mozilla
mpl-2.0
numericillustration/sdc-imgapi
test/channels.public-test.js
28127
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2014, Joyent, Inc. */ /* * Test channels handling. * * We do this as a "public-test" rather than a "dc-test" * because practically speaking it is updates.joyent.com (a mode=private, * functionally equiv to mode=public) that has channels support and never the * mode=dc IMGAPI in SDC installations. */ var p = console.log; var format = require('util').format; var assert = require('assert-plus'); var fs = require('fs'); var once = require('once'); var imgapi = require('sdc-clients').IMGAPI; // node-tap API if (require.cache[__dirname + '/tap4nodeunit.js']) delete require.cache[__dirname + '/tap4nodeunit.js']; var tap4nodeunit = require('./tap4nodeunit.js'); var after = tap4nodeunit.after; var before = tap4nodeunit.before; var test = tap4nodeunit.test; //---- globals var tmpDownloadFile = '/var/tmp/imgapi-channels-test-download'; // The name of the event on a write stream indicating it is done. var nodeVer = process.versions.node.split('.').map(Number); var writeStreamFinishEvent = 'finish'; if (nodeVer[0] === 0 && nodeVer[1] <= 8) { writeStreamFinishEvent = 'close'; } //---- support stuff function mergeObjs(a, b) { assert.object(a, 'a'); assert.object(b, 'b'); var obj = {}; Object.keys(a).forEach(function (key) { obj[key] = a[key]; }); Object.keys(b).forEach(function (key) { obj[key] = b[key]; }); return obj; } //---- tests before(function (next) { var opts = { url: process.env.IMGAPI_URL, agent: false }; if (process.env.IMGAPI_PASSWORD) { opts.user = process.env.IMGAPI_USER; opts.password = process.env.IMGAPI_PASSWORD; } else if (process.env.IMGAPI_URL === 'https://images.joyent.com') { assert.fail('Do not run the channels tests against images.jo.'); } else { assert.fail('What no auth info!?'); } this.clients = { 'nochan': imgapi.createClient(opts), 'star': imgapi.createClient(mergeObjs(opts, {channel: '*'})), 'bogus': imgapi.createClient(mergeObjs(opts, {channel: 'bogus'})), 'dev': imgapi.createClient(mergeObjs(opts, {channel: 'dev'})), 'staging': imgapi.createClient(mergeObjs(opts, {channel: 'staging'})), 'release': imgapi.createClient(mergeObjs(opts, {channel: 'release'})) }; next(); }); test('ListChannels', function (t) { this.clients.nochan.listChannels({}, function (err, channels) { t.ifError(err, 'ListChannels err: ', err); t.ok(channels, 'channels'); t.equal(channels.length, 3, 'channels.length'); t.equal( channels.filter(function (ch) { return ch.default; })[0].name, 'dev'); t.end(); }); }); test('ListImages with implied dev channel has indevchan', function (t) { this.clients.nochan.listImages(function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'indevchan'; }) .length, 1); t.end(); }); }); test('ListImages with implied dev channel has no innochan', function (t) { this.clients.nochan.listImages(function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'innochan'; }) .length, 0); t.end(); }); }); test('ListImages with implied dev channel has no instagingchan', function (t) { this.clients.nochan.listImages(function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'instagingchan'; }) .length, 0); t.end(); }); }); test('ListImages with dev channel has indevchan', function (t) { this.clients.dev.listImages(function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'indevchan'; }) .length, 1); t.end(); }); }); test('ListImages with dev channel has no innochan', function (t) { this.clients.dev.listImages(function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'innochan'; }) .length, 0); t.end(); }); }); test('ListImages with dev channel has no instagingchan', function (t) { this.clients.dev.listImages(function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'instagingchan'; }) .length, 0); t.end(); }); }); test('ListImages with staging channel has no indevchan', function (t) { this.clients.staging.listImages(function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'indevchan'; }) .length, 0); t.end(); }); }); test('ListImages with staging channel has instagingchan', function (t) { this.clients.staging.listImages(function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'instagingchan'; }) .length, 1); t.end(); }); }); test('ListImages with channel=* has no innochan', function (t) { this.clients.star.listImages(function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'innochan'; }) .length, 0); t.end(); }); }); test('ListImages with channel=* has indevchan and instagingchan', function (t) { this.clients.star.listImages({channel: '*'}, function (err, images) { t.ifError(err); t.equal( images .filter(function (img) { return img.name === 'indevchan'; }) .length, 1); t.equal( images .filter(function (img) { return img.name === 'instagingchan'; }) .length, 1); t.end(); }); }); test('ListImages with bogus channel errors', function (t) { this.clients.bogus.listImages({channel: 'bogus'}, function (err, images) { t.ok(err); t.equal(err.body.code, 'ValidationFailed'); t.equal(err.body.errors[0].field, 'channel'); t.end(); }); }); test('GetImage with implied dev channel can get indevchan', function (t) { this.clients.nochan.getImage('8ba6d20f-6013-f944-9d69-929ebdef45a2', {}, function (err, image) { t.ifError(err); t.ok(image); t.equal(image.uuid, '8ba6d20f-6013-f944-9d69-929ebdef45a2'); t.ok(image.channels.indexOf('dev') !== -1); t.end(); }); }); test('GetImage with implied dev channel cannot get innochan', function (t) { this.clients.nochan.getImage('c58161c0-2547-11e2-a75e-9fdca1940570', {}, function (err, image) { t.ok(err); t.equal(err.body.code, 'ResourceNotFound'); t.end(); }); }); test('GetImage with implied dev channel cannot get instagingchan', function (t) { this.clients.nochan.getImage('3e6ebb8c-bb37-9245-ba5d-43d172461be6', {}, function (err, image) { t.ok(err); if (err) { t.equal(err.body.code, 'ResourceNotFound'); } t.end(); }); }); test('GetImage with dev channel can get indevchan', function (t) { this.clients.dev.getImage('8ba6d20f-6013-f944-9d69-929ebdef45a2', function (err, image) { t.ifError(err); t.ok(image); t.equal(image.uuid, '8ba6d20f-6013-f944-9d69-929ebdef45a2'); t.ok(image.channels.indexOf('dev') !== -1); t.end(); }); }); test('GetImage with dev channel cannot get innochan', function (t) { this.clients.dev.getImage('c58161c0-2547-11e2-a75e-9fdca1940570', function (err, image) { t.ok(err); t.equal(err.body.code, 'ResourceNotFound'); t.end(); }); }); test('GetImage with dev channel cannot get instagingchan', function (t) { this.clients.dev.getImage('3e6ebb8c-bb37-9245-ba5d-43d172461be6', function (err, image) { t.ok(err); if (err) { t.equal(err.body.code, 'ResourceNotFound'); } t.end(); }); }); test('GetImage with staging channel can get instagingchan', function (t) { this.clients.staging.getImage('3e6ebb8c-bb37-9245-ba5d-43d172461be6', function (err, image) { t.ifError(err); t.ok(image); t.equal(image.uuid, '3e6ebb8c-bb37-9245-ba5d-43d172461be6'); t.ok(image.channels.indexOf('staging') !== -1); t.end(); }); }); test('GetImage with staging channel cannot get innochan', function (t) { this.clients.staging.getImage('c58161c0-2547-11e2-a75e-9fdca1940570', function (err, image) { t.ok(err); t.equal(err.body.code, 'ResourceNotFound'); t.end(); }); }); test('GetImage with staging channel cannot get indevchan', function (t) { this.clients.staging.getImage('8ba6d20f-6013-f944-9d69-929ebdef45a2', function (err, image) { t.ok(err); if (err) { t.equal(err.body.code, 'ResourceNotFound'); } t.end(); }); }); test('GetImage with bogus channel gets error', function (t) { this.clients.bogus.getImage('3e6ebb8c-bb37-9245-ba5d-43d172461be6', function (err, image) { t.plan(3); t.ok(err); if (err) { t.equal(err.body.code, 'ValidationFailed'); t.equal(err.body.errors[0].field, 'channel'); } t.end(); }); }); test('GetImageFile with implied dev channel can get indevchan', function (t) { this.clients.nochan.getImageFile('8ba6d20f-6013-f944-9d69-929ebdef45a2', tmpDownloadFile, function (err, res) { t.ifError(err); t.equal(res.statusCode, 200); t.equal(fs.readFileSync(tmpDownloadFile), 'file'); t.end(); }); }); test('GetImageFile with implied dev channel cannot get innochan', function (t) { this.clients.nochan.getImageFile('c58161c0-2547-11e2-a75e-9fdca1940570', tmpDownloadFile, function (err, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('GetImageFile with implied dev channel cannot get instagingchan', function (t) { this.clients.nochan.getImageFile('3e6ebb8c-bb37-9245-ba5d-43d172461be6', tmpDownloadFile, function (err, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('GetImageFile with dev channel can get indevchan', function (t) { this.clients.dev.getImageFile('8ba6d20f-6013-f944-9d69-929ebdef45a2', tmpDownloadFile, undefined, function (err, res) { t.ifError(err); t.equal(res.statusCode, 200); t.equal(fs.readFileSync(tmpDownloadFile), 'file'); t.end(); }); }); test('GetImageFile with dev channel cannot get innochan', function (t) { this.clients.dev.getImageFile('c58161c0-2547-11e2-a75e-9fdca1940570', tmpDownloadFile, undefined, function (err, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('GetImageFile with dev channel cannot get instagingchan', function (t) { this.clients.dev.getImageFile('3e6ebb8c-bb37-9245-ba5d-43d172461be6', tmpDownloadFile, undefined, function (err, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('GetImageFile with staging channel can get instagingchan', function (t) { this.clients.staging.getImageFile('3e6ebb8c-bb37-9245-ba5d-43d172461be6', tmpDownloadFile, undefined, function (err, res) { t.ifError(err); t.equal(res.statusCode, 200); t.equal(fs.readFileSync(tmpDownloadFile), 'file'); t.end(); }); }); test('GetImageFile with staging channel cannot get innochan', function (t) { this.clients.staging.getImageFile('c58161c0-2547-11e2-a75e-9fdca1940570', tmpDownloadFile, undefined, function (err, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('GetImageFile with staging channel cannot get indevchan', function (t) { this.clients.staging.getImageFile('8ba6d20f-6013-f944-9d69-929ebdef45a2', tmpDownloadFile, undefined, function (err, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('GetImageFile with bogus channel gets error', function (t) { this.clients.bogus.getImageFile('3e6ebb8c-bb37-9245-ba5d-43d172461be6', tmpDownloadFile, undefined, function (err, res) { t.plan(2); t.ok(err); if (err) t.equal(err.body.code, 'ValidationFailed'); t.end(); }); }); test('GetImageFile (stream) with staging channel can get instagingchan', function (t) { this.clients.staging.getImageFileStream( '3e6ebb8c-bb37-9245-ba5d-43d172461be6', undefined, function (err, stream) { t.ifError(err); t.ok(stream); function finish_(err2) { t.ifError(err2); if (!err2) t.equal(fs.readFileSync(tmpDownloadFile), 'file'); t.end(); } var finish = once(finish_); var out = stream.pipe(fs.createWriteStream(tmpDownloadFile)); out.on(writeStreamFinishEvent, finish); stream.on('error', finish); stream.resume(); }); }); test('GetImageFile (stream) with staging channel cannot get innochan', function (t) { this.clients.staging.getImageFileStream( 'c58161c0-2547-11e2-a75e-9fdca1940570', undefined, function (err, stream) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(stream.statusCode, 404); t.end(); }); }); test('GetImageFile (stream) with staging channel cannot get indevchan', function (t) { this.clients.staging.getImageFileStream( '8ba6d20f-6013-f944-9d69-929ebdef45a2', undefined, function (err, stream) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(stream.statusCode, 404); t.end(); }); }); test('GetImageIcon with implied dev channel can get indevchan', function (t) { this.clients.dev.getImageIcon('8ba6d20f-6013-f944-9d69-929ebdef45a2', tmpDownloadFile, function (err, res) { t.ifError(err); t.equal(res.statusCode, 200); t.equal(fs.readFileSync(tmpDownloadFile), 'icon'); t.end(); }); }); test('GetImageIcon with implied dev channel cannot get instagingchan', function (t) { this.clients.dev.getImageIcon('3e6ebb8c-bb37-9245-ba5d-43d172461be6', tmpDownloadFile, function (err, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('GetImageIcon with dev channel can get indevchan', function (t) { this.clients.dev.getImageIcon('8ba6d20f-6013-f944-9d69-929ebdef45a2', tmpDownloadFile, undefined, function (err, res) { t.ifError(err); t.equal(res.statusCode, 200); t.equal(fs.readFileSync(tmpDownloadFile), 'icon'); t.end(); }); }); test('GetImageIcon with dev channel cannot get instagingchan', function (t) { this.clients.dev.getImageIcon('3e6ebb8c-bb37-9245-ba5d-43d172461be6', tmpDownloadFile, undefined, function (err, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('GetImageIcon with staging channel can get instagingchan', function (t) { this.clients.staging.getImageIcon('3e6ebb8c-bb37-9245-ba5d-43d172461be6', tmpDownloadFile, undefined, function (err, res) { t.ifError(err); t.equal(res.statusCode, 200); t.equal(fs.readFileSync(tmpDownloadFile), 'icon'); t.end(); }); }); test('GetImageIcon (stream) with staging channel can get instagingchan', function (t) { this.clients.staging.getImageIconStream( '3e6ebb8c-bb37-9245-ba5d-43d172461be6', undefined, function (err, stream) { t.ifError(err); if (!err) { t.ok(stream); function finish_(err2) { t.ifError(err2); if (!err2) t.equal(fs.readFileSync(tmpDownloadFile), 'icon'); t.end(); } var finish = once(finish_); var out = stream.pipe(fs.createWriteStream(tmpDownloadFile)); out.on(writeStreamFinishEvent, finish); stream.on('error', finish); stream.resume(); } else { t.end(); } }); }); test('GetImageIcon (stream) with staging channel cannot get innochan', function (t) { this.clients.staging.getImageIconStream( 'c58161c0-2547-11e2-a75e-9fdca1940570', undefined, function (err, stream) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(stream.statusCode, 404); t.end(); }); }); test('GetImageIcon (stream) with staging channel cannot get indevchan', function (t) { this.clients.staging.getImageIconStream( '8ba6d20f-6013-f944-9d69-929ebdef45a2', undefined, function (err, stream) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(stream.statusCode, 404); t.end(); }); }); //---- UpdateImage (and many the endpoints in the same chain) test('UpdateImage with staging channel can get instagingchan', function (t) { this.clients.staging.updateImage( '3e6ebb8c-bb37-9245-ba5d-43d172461be6', {tags: {foo: 'bar'}}, function (err, img, res) { t.ifError(err); t.equal(res.statusCode, 200); t.ok(img); t.ok(img.channels.indexOf('staging') !== -1); t.equal(img.tags.foo, 'bar'); t.end(); }); }); test('UpdateImage with staging channel cannot get indevchan', function (t) { this.clients.staging.updateImage( '8ba6d20f-6013-f944-9d69-929ebdef45a2', {tags: {foo: 'bar'}}, function (err, img, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); //---- CreateImage // Ensure the set channel gets assigned. test('CreateImage with implicit default channel', function (t) { var data = { name: 'my-CreateImage-staging-test', version: '1.0.0', os: 'other', type: 'other', owner: '639e90cd-71ec-c449-bc7a-2446651cce7c', public: true }; this.clients.nochan.createImage(data, function (err, img, res) { t.ifError(err); t.equal(res.statusCode, 200); t.ok(img); t.ok(img.channels.indexOf('dev') !== -1); t.equal(img.state, 'unactivated'); t.end(); }); }); test('CreateImage with release channel', function (t) { var data = { name: 'my-CreateImage-staging-test', version: '1.0.0', os: 'other', type: 'other', owner: '639e90cd-71ec-c449-bc7a-2446651cce7c', public: true }; this.clients.release.createImage(data, function (err, img, res) { t.ifError(err); t.equal(res.statusCode, 200); t.ok(img); t.ok(img.channels[0], 'release'); t.equal(img.state, 'unactivated'); t.end(); }); }); //---- AddImageAcl/RemoveImageAcl test('AddImageAcl with staging channel can get instagingchan', function (t) { this.clients.staging.addImageAcl('3e6ebb8c-bb37-9245-ba5d-43d172461be6', ['aa1c57aa-1451-11e4-a20c-13e606e498d1'], undefined, function (err, img, res) { t.ifError(err); t.ok(img); t.ok(img.channels.indexOf('staging') !== -1); t.equal(res.statusCode, 200); t.end(); }); }); test('AddImageAcl with staging channel cannot get indevchan', function (t) { this.clients.staging.addImageAcl('8ba6d20f-6013-f944-9d69-929ebdef45a2', ['aa1c57aa-1451-11e4-a20c-13e606e498d1'], undefined, function (err, img, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('RemoveImageAcl with staging channel can get instagingchan', function (t) { this.clients.staging.removeImageAcl('3e6ebb8c-bb37-9245-ba5d-43d172461be6', ['aa1c57aa-1451-11e4-a20c-13e606e498d1'], undefined, function (err, img, res) { t.ifError(err); t.ok(img); t.ok(img.channels.indexOf('staging') !== -1); t.equal(res.statusCode, 200); t.end(); }); }); test('RemoveImageAcl with staging channel cannot get indevchan', function (t) { this.clients.staging.removeImageAcl('8ba6d20f-6013-f944-9d69-929ebdef45a2', ['aa1c57aa-1451-11e4-a20c-13e606e498d1'], undefined, function (err, img, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); //---- ChannelAddImage test('ChannelAddImage instagingchan to bogus channel', function (t) { var addOpts = { uuid: '3e6ebb8c-bb37-9245-ba5d-43d172461be6', channel: 'bogus' }; this.clients.staging.channelAddImage(addOpts, function (err, img, res) { t.ok(err); if (err) t.equal(err.body.code, 'ValidationFailed'); t.equal(res.statusCode, 422); t.end(); }); }); test('ChannelAddImage unknown image to release channel', function (t) { var addOpts = { uuid: '3e6ebb8c-bb37-9245-ba5d-999999999999', channel: 'release' }; this.clients.staging.channelAddImage(addOpts, function (err, img, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('ChannelAddImage instagingchan image to release channel (using dev chan)', function (t) { var addOpts = { uuid: '3e6ebb8c-bb37-9245-ba5d-43d172461be6', channel: 'release' }; this.clients.dev.channelAddImage(addOpts, function (err, img, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); test('ChannelAddImage instagingchan to release channel', function (t) { var addOpts = { uuid: '3e6ebb8c-bb37-9245-ba5d-43d172461be6', channel: 'release' }; this.clients.staging.channelAddImage(addOpts, function (err, img, res) { t.ifError(err); t.ok(img); t.ok(img.channels.indexOf('staging') !== -1); t.ok(img.channels.indexOf('release') !== -1); t.equal(res.statusCode, 200); t.end(); }); }); test('ListImages in release channel to assert have new one', function (t) { var uuid = '3e6ebb8c-bb37-9245-ba5d-43d172461be6'; this.clients.release.listImages(function (err, images) { t.ifError(err); t.equal( images.filter(function (img) { return img.uuid === uuid; }).length, 1); t.end(); }); }); test('DeleteImage instagingchan to remove from release channel', function (t) { this.clients.release.deleteImage('3e6ebb8c-bb37-9245-ba5d-43d172461be6', undefined, function (err, res) { t.ifError(err); t.equal(res.statusCode, 204); t.end(); }); }); test('ListImages in release channel to assert removed', function (t) { var uuid = '3e6ebb8c-bb37-9245-ba5d-43d172461be6'; this.clients.release.listImages(function (err, images) { t.ifError(err); t.equal( images.filter(function (img) { return img.uuid === uuid; }).length, 0); t.end(); }); }); test('ListImages in staging channel to assert still there', function (t) { var uuid = '3e6ebb8c-bb37-9245-ba5d-43d172461be6'; this.clients.staging.listImages(function (err, images) { t.ifError(err); t.equal( images.filter(function (img) { return img.uuid === uuid; }).length, 1); t.end(); }); }); //---- DeleteImageIcon test('DeleteImageIcon with staging channel can get instagingchan', function (t) { this.clients.staging.deleteImageIcon('3e6ebb8c-bb37-9245-ba5d-43d172461be6', undefined, function (err, img, res) { t.ifError(err); t.ok(img); t.ok(img.channels.indexOf('staging') !== -1); t.equal(res.statusCode, 200); t.end(); }); }); test('DeleteImageIcon with staging channel cannot get indevchan', function (t) { this.clients.staging.deleteImageIcon('8ba6d20f-6013-f944-9d69-929ebdef45a2', undefined, function (err, img, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); //---- DeleteImage test('DeleteImage (ch=staging) can get instagingchan', function (t) { this.clients.staging.deleteImage('3e6ebb8c-bb37-9245-ba5d-43d172461be6', undefined, function (err, res) { t.ifError(err); t.equal(res.statusCode, 204); t.end(); }); }); test('ListImages (ch=*) shows instagingchan is really gone', function (t) { this.clients.star.listImages(function (err, imgs) { t.ifError(err); t.equal( imgs.filter(function (img) { return img.name === 'instagingchan'; } ).length, 0); t.end(); }); }); test('DeleteImage (ch=staging) cannot get indevchan', function (t) { this.clients.staging.deleteImage('8ba6d20f-6013-f944-9d69-929ebdef45a2', undefined, function (err, res) { t.ok(err); if (err) t.equal(err.body.code, 'ResourceNotFound'); t.equal(res.statusCode, 404); t.end(); }); }); //---- DeleteImage with ?force_all_channels works as expected test('DeleteImage (ch=dev) with ?force_all_channels fully deletes inmultichan', function (t) { var uuid = '4e6ebb8c-bb37-9245-ba5d-43d172461be6'; var delOpts = { forceAllChannels: true }; this.clients.dev.deleteImage(uuid, delOpts, function (err, res) { t.ifError(err); t.equal(res.statusCode, 204); t.end(); }); }); test('ListImages (ch=*) shows inmultichan is really gone', function (t) { this.clients.star.listImages(function (err, imgs) { t.ifError(err); t.equal( imgs.filter(function (img) { return img.name === 'inmultichan'; } ).length, 0); t.end(); }); });
mpl-2.0
biosistemika/scinote-web
app/controllers/api/v1/project_comments_controller.rb
1094
# frozen_string_literal: true module Api module V1 class ProjectCommentsController < BaseController before_action :load_team before_action :load_project before_action :check_read_permissions before_action :load_project_comment, only: :show def index project_comments = @project.project_comments .page(params.dig(:page, :number)) .per(params.dig(:page, :size)) render jsonapi: project_comments, each_serializer: CommentSerializer, hide_project: true end def show render jsonapi: @project_comment, serializer: CommentSerializer, hide_project: true, include: :user end private def check_read_permissions raise PermissionError.new(Project, :read_comments) unless can_read_project_comments?(@project) end def load_project_comment @project_comment = @project.project_comments.find(params.require(:id)) end end end end
mpl-2.0
Yukarumya/Yukarum-Redfoxes
devtools/client/debugger/test/mochitest/browser_dbg_breakpoints-eval.js
1517
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ /* vim: set ft=javascript ts=2 et sw=2 tw=80: */ /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ /** * Test setting breakpoints on an eval script */ const TAB_URL = EXAMPLE_URL + "doc_script-eval.html"; function test() { let options = { source: EXAMPLE_URL + "code_script-eval.js", line: 1 }; initDebugger(TAB_URL, options).then(([aTab,, aPanel]) => { const gTab = aTab; const gPanel = aPanel; const gDebugger = gPanel.panelWin; const gSources = gDebugger.DebuggerView.Sources; const actions = bindActionCreators(gPanel); Task.spawn(function* () { let newSource = waitForDebuggerEvents(gPanel, gDebugger.EVENTS.NEW_SOURCE); callInTab(gTab, "evalSourceWithSourceURL"); yield newSource; // Wait for it to be added to the UI yield waitForTick(); const newSourceActor = getSourceActor(gSources, EXAMPLE_URL + "bar.js"); yield actions.addBreakpoint({ actor: newSourceActor, line: 2 }); yield ensureThreadClientState(gPanel, "resumed"); const paused = waitForThreadEvents(gPanel, "paused"); callInTab(gTab, "bar"); let frame = (yield paused).frame; is(frame.where.source.actor, newSourceActor, "Should have broken on the eval'ed source"); is(frame.where.line, 2, "Should break on line 2"); yield resumeDebuggerThenCloseAndFinish(gPanel); }); }); }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
devtools/client/inspector/markup/test/browser_markup_css_completion_style_attribute_01.js
3278
/* vim: set ts=2 et sw=2 tw=80: */ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ /* import-globals-from helper_style_attr_test_runner.js */ "use strict"; // Test CSS state is correctly determined and the corresponding suggestions are // displayed. i.e. CSS property suggestions are shown when cursor is like: // ```style="di|"``` where | is the cursor; And CSS value suggestion is // displayed when the cursor is like: ```style="display:n|"``` properly. No // suggestions should ever appear when the attribute is not a style attribute. // The correctness and cycling of the suggestions is covered in the ruleview // tests. loadHelperScript("helper_style_attr_test_runner.js"); const TEST_URL = URL_ROOT + "doc_markup_edit.html"; // test data format : // [ // what key to press, // expected input box value after keypress, // expected input.selectionStart, // expected input.selectionEnd, // is popup expected to be open ? // ] const TEST_DATA = [ ["s", "s", 1, 1, false], ["t", "st", 2, 2, false], ["y", "sty", 3, 3, false], ["l", "styl", 4, 4, false], ["e", "style", 5, 5, false], ["=", "style=", 6, 6, false], ["\"", "style=\"", 7, 7, false], ["d", "style=\"display", 8, 14, true], ["VK_TAB", "style=\"display", 14, 14, true], ["VK_TAB", "style=\"dominant-baseline", 24, 24, true], ["VK_TAB", "style=\"direction", 16, 16, true], ["click_1", "style=\"display", 14, 14, false], [":", "style=\"display:block", 15, 20, true], ["n", "style=\"display:none", 16, 19, false], ["VK_BACK_SPACE", "style=\"display:n", 16, 16, false], ["VK_BACK_SPACE", "style=\"display:", 15, 15, false], [" ", "style=\"display: block", 16, 21, true], [" ", "style=\"display: block", 17, 22, true], ["i", "style=\"display: inherit", 18, 24, true], ["VK_RIGHT", "style=\"display: inherit", 24, 24, false], [";", "style=\"display: inherit;", 25, 25, false], [" ", "style=\"display: inherit; ", 26, 26, false], [" ", "style=\"display: inherit; ", 27, 27, false], ["VK_LEFT", "style=\"display: inherit; ", 26, 26, false], ["c", "style=\"display: inherit; color ", 27, 31, true], ["VK_RIGHT", "style=\"display: inherit; color ", 31, 31, false], [" ", "style=\"display: inherit; color ", 32, 32, false], ["c", "style=\"display: inherit; color c ", 33, 33, false], ["VK_BACK_SPACE", "style=\"display: inherit; color ", 32, 32, false], [":", "style=\"display: inherit; color :aliceblue ", 33, 42, true], ["c", "style=\"display: inherit; color :cadetblue ", 34, 42, true], ["VK_DOWN", "style=\"display: inherit; color :chartreuse ", 34, 43, true], ["VK_RIGHT", "style=\"display: inherit; color :chartreuse ", 43, 43, false], [" ", "style=\"display: inherit; color :chartreuse aliceblue ", 44, 53, true], ["!", "style=\"display: inherit; color :chartreuse !important; ", 45, 55, false], ["VK_RIGHT", "style=\"display: inherit; color :chartreuse !important; ", 55, 55, false], ["VK_RETURN", "style=\"display: inherit; color :chartreuse !important;\"", -1, -1, false] ]; add_task(function* () { let {inspector} = yield openInspectorForURL(TEST_URL); yield runStyleAttributeAutocompleteTests(inspector, TEST_DATA); });
mpl-2.0
biosistemika/scinote-web
spec/controllers/invitations_controller_spec.rb
1147
# frozen_string_literal: true require 'rails_helper' describe Users::InvitationsController, type: :controller do login_user let(:user) { subject.current_user } let!(:team) { create :team, created_by: user } let!(:user_team) { create :user_team, :admin, user: user, team: team } describe 'POST invite_users' do let(:invited_user) { create :user } let(:team) { create :team } let(:params) do { team_ids: [team.id], emails: [invited_user.email], role: 'guest' } end let(:action) { post :invite_users, params: params, format: :json } context 'when inviting existing user not in the team' do it 'calls create activity for inviting user' do expect(Activities::CreateActivityService) .to(receive(:call) .with(hash_including(activity_type: :invite_user_to_team))) action end it 'adds activity in DB' do expect { action } .to(change { Activity.count }) end it 'adds user_team record in DB' do expect { action } .to(change { UserTeam.count }) end end end end
mpl-2.0
Yukarumya/Yukarum-Redfoxes
uriloader/exthandler/tests/mochitest/handlerApps.js
4306
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // handlerApp.xhtml grabs this for verification purposes via window.opener var testURI = "webcal://127.0.0.1/rheeeeet.html"; const Cc = SpecialPowers.Cc; function test() { // set up the web handler object var webHandler = Cc["@mozilla.org/uriloader/web-handler-app;1"]. createInstance(SpecialPowers.Ci.nsIWebHandlerApp); webHandler.name = "Test Web Handler App"; webHandler.uriTemplate = "http://mochi.test:8888/tests/uriloader/exthandler/tests/mochitest/" + "handlerApp.xhtml?uri=%s"; // set up the uri to test with var ioService = Cc["@mozilla.org/network/io-service;1"]. getService(SpecialPowers.Ci.nsIIOService); var uri = ioService.newURI(testURI); // create a window, and launch the handler in it var newWindow = window.open("", "handlerWindow", "height=300,width=300"); var windowContext = SpecialPowers.wrap(newWindow).QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor). getInterface(SpecialPowers.Ci.nsIWebNavigation). QueryInterface(SpecialPowers.Ci.nsIDocShell); webHandler.launchWithURI(uri, windowContext); // if we get this far without an exception, we've at least partly passed // (remaining check in handlerApp.xhtml) ok(true, "webHandler launchWithURI (existing window/tab) started"); // make the web browser launch in its own window/tab webHandler.launchWithURI(uri); // if we get this far without an exception, we've passed ok(true, "webHandler launchWithURI (new window/tab) test started"); // set up the local handler object var localHandler = Cc["@mozilla.org/uriloader/local-handler-app;1"]. createInstance(SpecialPowers.Ci.nsILocalHandlerApp); localHandler.name = "Test Local Handler App"; // get a local app that we know will be there and do something sane var osString = Cc["@mozilla.org/xre/app-info;1"]. getService(SpecialPowers.Ci.nsIXULRuntime).OS; var dirSvc = Cc["@mozilla.org/file/directory_service;1"]. getService(SpecialPowers.Ci.nsIDirectoryServiceProvider); if (osString == "WINNT") { var windowsDir = dirSvc.getFile("WinD", {}); var exe = windowsDir.clone().QueryInterface(SpecialPowers.Ci.nsILocalFile); exe.appendRelativePath("SYSTEM32\\HOSTNAME.EXE"); } else if (osString == "Darwin") { var localAppsDir = dirSvc.getFile("LocApp", {}); exe = localAppsDir.clone(); exe.append("iCal.app"); // lingers after the tests finish, but this seems // seems better than explicitly killing it, since // developers who run the tests locally may well // information in their running copy of iCal if (navigator.userAgent.match(/ SeaMonkey\//)) { // SeaMonkey tinderboxes don't like to have iCal lingering (and focused) // on next test suite run(s). todo(false, "On SeaMonkey, testing OS X as generic Unix. (Bug 749872)"); // assume a generic UNIX variant exe = Cc["@mozilla.org/file/local;1"]. createInstance(SpecialPowers.Ci.nsILocalFile); exe.initWithPath("/bin/echo"); } } else { // assume a generic UNIX variant exe = Cc["@mozilla.org/file/local;1"]. createInstance(SpecialPowers.Ci.nsILocalFile); exe.initWithPath("/bin/echo"); } localHandler.executable = exe; localHandler.launchWithURI(ioService.newURI(testURI)); // if we get this far without an exception, we've passed ok(true, "localHandler launchWithURI test"); // if we ever decide that killing iCal is the right thing to do, change // the if statement below from "NOTDarwin" to "Darwin" if (osString == "NOTDarwin") { var killall = Cc["@mozilla.org/file/local;1"]. createInstance(SpecialPowers.Ci.nsILocalFile); killall.initWithPath("/usr/bin/killall"); var process = Cc["@mozilla.org/process/util;1"]. createInstance(SpecialPowers.Ci.nsIProcess); process.init(killall); var args = ['iCal']; process.run(false, args, args.length); } SimpleTest.waitForExplicitFinish(); } test();
mpl-2.0
grafana/grafana
packages/grafana-e2e/test/cypress/integration/0.cli.ts
78
describe('CLI', () => { it('compiles this file and runs it', () => {}); });
agpl-3.0
hongtaolee/crm
app/controllers/opportunities_controller.rb
11968
# Fat Free CRM # Copyright (C) 2008-2011 by Michael Dvorkin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #------------------------------------------------------------------------------ class OpportunitiesController < ApplicationController before_filter :require_user before_filter :set_current_tab, :only => [ :index, :show ] before_filter :load_settings before_filter :get_data_for_sidebar, :only => :index before_filter :set_params, :only => [:index, :redraw, :filter] after_filter :update_recently_viewed, :only => :show # GET /opportunities # GET /opportunities.json # GET /opportunities.xml #---------------------------------------------------------------------------- def index @opportunities = get_opportunities(:page => params[:page]) respond_to do |format| format.html # index.html.haml format.js # index.js.rjs format.json { render :json => @opportunities } format.xml { render :xml => @opportunities } format.xls { send_data @opportunities.to_xls, :type => :xls } format.csv { send_data @opportunities.to_csv, :type => :csv } format.rss { render "shared/index.rss.builder" } format.atom { render "shared/index.atom.builder" } end end # GET /opportunities/1 # GET /opportunities/1.json # GET /opportunities/1.xml HTML #---------------------------------------------------------------------------- def show @opportunity = Opportunity.my.find(params[:id]) respond_to do |format| format.html do @comment = Comment.new @timeline = timeline(@opportunity) end format.json { render :json => @opportunity } format.xml { render :xml => @opportunity } end rescue ActiveRecord::RecordNotFound respond_to_not_found(:html, :json, :xml) end # GET /opportunities/new # GET /opportunities/new.json # GET /opportunities/new.xml AJAX #---------------------------------------------------------------------------- def new @opportunity = Opportunity.new(:user => @current_user, :stage => "prospecting", :access => Setting.default_access) @users = User.except(@current_user) @account = Account.new(:user => @current_user) @accounts = Account.my.order("name") if params[:related] model, id = params[:related].split("_") instance_variable_set("@#{model}", model.classify.constantize.my.find(id)) end respond_to do |format| format.js # new.js.rjs format.json { render :json => @opportunity } format.xml { render :xml => @opportunity } end rescue ActiveRecord::RecordNotFound # Kicks in if related asset was not found. respond_to_related_not_found(model, :js) if model end # GET /opportunities/1/edit AJAX #---------------------------------------------------------------------------- def edit @opportunity = Opportunity.my.find(params[:id]) @users = User.except(@current_user) @account = @opportunity.account || Account.new(:user => @current_user) @accounts = Account.my.order("name") if params[:previous].to_s =~ /(\d+)\z/ @previous = Opportunity.my.find($1) end rescue ActiveRecord::RecordNotFound @previous ||= $1.to_i respond_to_not_found(:js) unless @opportunity end # POST /opportunities # POST /opportunities.json # POST /opportunities.xml AJAX #---------------------------------------------------------------------------- def create @opportunity = Opportunity.new(params[:opportunity]) respond_to do |format| if @opportunity.save_with_account_and_permissions(params) if called_from_index_page? @opportunities = get_opportunities get_data_for_sidebar elsif called_from_landing_page?(:accounts) get_data_for_sidebar(:account) elsif called_from_landing_page?(:campaigns) get_data_for_sidebar(:campaign) end format.js # create.js.rjs format.json { render :json => @opportunity, :status => :created, :location => @opportunity } format.xml { render :xml => @opportunity, :status => :created, :location => @opportunity } else @users = User.except(@current_user) @accounts = Account.my.order("name") unless params[:account][:id].blank? @account = Account.find(params[:account][:id]) else if request.referer =~ /\/accounts\/(.+)$/ @account = Account.find($1) # related account else @account = Account.new(:user => @current_user) end end @contact = Contact.find(params[:contact]) unless params[:contact].blank? @campaign = Campaign.find(params[:campaign]) unless params[:campaign].blank? format.js # create.js.rjs format.json { render :json => @opportunity.errors, :status => :unprocessable_entity } format.xml { render :xml => @opportunity.errors, :status => :unprocessable_entity } end end end # PUT /opportunities/1 # PUT /opportunities/1.json # PUT /opportunities/1.xml AJAX #---------------------------------------------------------------------------- def update @opportunity = Opportunity.my.find(params[:id]) respond_to do |format| if @opportunity.update_with_account_and_permissions(params) if called_from_index_page? get_data_for_sidebar elsif called_from_landing_page?(:accounts) get_data_for_sidebar(:account) elsif called_from_landing_page?(:campaigns) get_data_for_sidebar(:campaign) end format.js format.json { head :ok } format.xml { head :ok } else @users = User.except(@current_user) @accounts = Account.my.order("name") if @opportunity.account @account = Account.find(@opportunity.account.id) else @account = Account.new(:user => @current_user) end format.js format.json { render :json => @opportunity.errors, :status => :unprocessable_entity } format.xml { render :xml => @opportunity.errors, :status => :unprocessable_entity } end end rescue ActiveRecord::RecordNotFound respond_to_not_found(:js, :json, :xml) end # DELETE /opportunities/1 # DELETE /opportunities/1.json # DELETE /opportunities/1.xml HTML and AJAX #---------------------------------------------------------------------------- def destroy @opportunity = Opportunity.my.find(params[:id]) if called_from_landing_page?(:accounts) @account = @opportunity.account # Reload related account if any. elsif called_from_landing_page?(:campaigns) @campaign = @opportunity.campaign # Reload related campaign if any. end @opportunity.destroy if @opportunity respond_to do |format| format.html { respond_to_destroy(:html) } format.js { respond_to_destroy(:ajax) } format.json { head :ok } format.xml { head :ok } end rescue ActiveRecord::RecordNotFound respond_to_not_found(:html, :js, :json, :xml) end # PUT /opportunities/1/attach # PUT /opportunities/1/attach.xml AJAX #---------------------------------------------------------------------------- # Handled by ApplicationController :attach # POST /opportunities/1/discard # POST /opportunities/1/discard.xml AJAX #---------------------------------------------------------------------------- # Handled by ApplicationController :discard # POST /opportunities/auto_complete/query AJAX #---------------------------------------------------------------------------- # Handled by ApplicationController :auto_complete # GET /opportunities/options AJAX #---------------------------------------------------------------------------- def options unless params[:cancel].true? @per_page = @current_user.pref[:opportunities_per_page] || Opportunity.per_page @outline = @current_user.pref[:opportunities_outline] || Opportunity.outline @sort_by = @current_user.pref[:opportunities_sort_by] || Opportunity.sort_by end end # GET /opportunities/contacts AJAX #---------------------------------------------------------------------------- def contacts @opportunity = Opportunity.my.find(params[:id]) end # POST /opportunities/redraw AJAX #---------------------------------------------------------------------------- def redraw @opportunities = get_opportunities(:page => 1) render :index end # POST /opportunities/filter AJAX #---------------------------------------------------------------------------- def filter @opportunities = get_opportunities(:page => 1) render :index end private #---------------------------------------------------------------------------- def get_opportunities(options = {}) get_list_of_records(Opportunity, options.merge!(:filter => :filter_by_opportunity_stage)) end #---------------------------------------------------------------------------- def respond_to_destroy(method) if method == :ajax if called_from_index_page? get_data_for_sidebar @opportunities = get_opportunities if @opportunities.blank? @opportunities = get_opportunities(:page => current_page - 1) if current_page > 1 render :index and return end else # Called from related asset. self.current_page = 1 end # At this point render destroy.js.rjs else self.current_page = 1 flash[:notice] = t(:msg_asset_deleted, @opportunity.name) redirect_to opportunities_path end end #---------------------------------------------------------------------------- def get_data_for_sidebar(related = false) if related instance_variable_set("@#{related}", @opportunity.send(related)) if called_from_landing_page?(related.to_s.pluralize) else @opportunity_stage_total = { :all => Opportunity.my.count, :other => 0 } @stage.each do |value, key| @opportunity_stage_total[key] = Opportunity.my.where(:stage => key.to_s).count @opportunity_stage_total[:other] -= @opportunity_stage_total[key] end @opportunity_stage_total[:other] += @opportunity_stage_total[:all] end end #---------------------------------------------------------------------------- def load_settings @stage = Setting.unroll(:opportunity_stage) end def set_params @current_user.pref[:opportunities_per_page] = params[:per_page] if params[:per_page] @current_user.pref[:opportunities_outline] = params[:outline] if params[:outline] @current_user.pref[:opportunities_sort_by] = Opportunity::sort_by_map[params[:sort_by]] if params[:sort_by] session[:filter_by_opportunity_stage] = params[:stage] if params[:stage] end end
agpl-3.0
rohitdatta/pepper
migrations/versions/5fe2987ca442_.py
1005
"""empty message Revision ID: 5fe2987ca442 Revises: 87a51f844ed4 Create Date: 2016-07-18 23:52:38.165444 """ # revision identifiers, used by Alembic. revision = '5fe2987ca442' down_revision = '87a51f844ed4' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('role', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) op.create_table('user_roles', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id') ) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('user_roles') op.drop_table('role') ### end Alembic commands ###
agpl-3.0
afshinnj/php-mvc
vendor/framework/widgets/ckeditor/Ckfinder.php
148
<?php /** * */ class Ckfinder { public static function view(){ include_once 'CkfinderView.php'; } public static function load(){} }
agpl-3.0
PRX/www.prx.org
src/common/angular-player-hater.js
11855
(function(){ 'use strict'; var module = angular.module('ngPlayerHater', []); module.factory('globalSoundManager', function ($window) { return $window.soundManager; }); var soundManager2Provider = { $get: getSoundManager, options: { url: '/assets', flashVersion: 9, preferFlash: false, debugMode: false } }; function wrapper(promise) { return function wrap(functionName) { return function () { var args = Array.prototype.slice.call(arguments); return promise.then(function (obj) { return obj[functionName].apply(obj, args); }); }; }; } getSoundManager.$inject = ['$q', '$timeout', 'globalSoundManager']; function getSoundManager($q, $timeout, globalSoundManager) { var deferred = $q.defer(), onReady, wrap = wrapper(deferred.promise), options = soundManager2Provider.options; function resolvePromise() { $timeout(function () { deferred.resolve(globalSoundManager); if (angular.isFunction(onReady)) { onReady.call(null); } }); if ($timeout.flush) { $timeout.flush(); } } resolvePromise._shim = true; if (typeof options.onready !== 'undefined' && !options.onready._shim) { onReady = options.onready; } else { onReady = undefined; } options.onready = resolvePromise; globalSoundManager.setup(options); return { createSound: wrap('createSound'), canPlayLink: wrap('canPlayLink'), canPlayMIME: wrap('canPlayMIME'), canPlayURL: wrap('canPlayURL'), mute: wrap('mute'), pauseAll: wrap('pauseAll'), resumeAll: wrap('resumeAll'), stopAll: wrap('stopAll'), unmute: wrap('unmute') }; } module.provider('soundManager', soundManager2Provider); SoundFactory.$inject = ['soundManager', '$timeout', '$q']; function SoundFactory(soundManager, $timeout, $q) { var id = 0; function Sound(url, options) { if (!angular.isDefined(url)) { throw new Error("URL is required."); } if (angular.isObject(url)) { angular.extend(this, url); url = url.url; } options = options || {}; angular.extend(options, generateCallbacks(this, options.onchange)); options.url = url; this.id3 = {}; this.id = id++; this.sound = function () { if (!this.$sound) { this.$sound = soundManager.createSound(options); } return this.$sound; }; this.$ld = $q.defer(); } Sound.prototype.playing = false; Sound.prototype.loading = false; Sound.prototype.error = false; Sound.prototype.paused = true; var proxies = ('destruct load mute pause resume setPan setPosition ' + 'setVolume stop toogleMute play togglePause unload unmute').split(' '); angular.forEach(proxies, function (proxy) { Sound.prototype[proxy] = makePromisedProxy(proxy); }); var play = Sound.prototype.play; Sound.prototype.play = function () { this.loading = true; return play.apply(this, [].slice.call(arguments)); }; var load = Sound.prototype.load; Sound.prototype.load = function () { var self = this; return load.apply(this, arguments).then(function () { return self.$lp || self.$ld.promise; }); }; var unload = Sound.prototype.destruct; Sound.prototype.unload = function () { this.$lp = undefined; this.$ld = $q.defer(); this.playing = false; this.loading = false; this.error = false; this.paused = true; if (this.$sound) { var self = this; return unload.apply(this, arguments).then(function () { self.$sound = undefined; }); } return $q.when(); }; var setPosition = Sound.prototype.setPosition; Sound.prototype.setPosition = function (position) { this.position = position; var self = this; if (this.$sound) { this.$sound = this.$sound.then(function (sound) { return sound.setPosition(position); }); return this.$sound; } else { var origSound = this.sound; this.sound = function () { return origSound.call(this).then(function (sound) { self.sound = origSound; return setPosition.call(self, position).then(function () { return sound; }); }); }; return $q.when(); } }; function SoundList (urls, options) { var firstSound, opts = (options || {}), subOpts = angular.copy(opts), self = this; this.segments = []; angular.forEach((urls || []).reverse(), function (url) { (function (sound) { subOpts.onfinish = function () { if (angular.isDefined(sound)) { self.$behind += self.$current.duration; self.$current = sound; this.setPosition(0); this.unload(); sound.play(); } else { self.$behind = 0; self.$current = self.$first; self.$current.setPosition(0); self.$current.paused = true; angular.extend(self, self.$first); if (opts.onfinish) { opts.onfinish.call(this); } } }; subOpts.onchange = function () { if (self.$current == this) { angular.extend(self, this); if (!this.position) { self.position = 0; } self.position = (self.position || 0) + self.$behind; } }; firstSound = new Sound(url, angular.copy(subOpts)); firstSound.$next = sound; firstSound.$digest = subOpts.onchange; self.segments.unshift(firstSound.duration); })(firstSound); }); this.$behind = 0; this.$current = this.$first = firstSound; this.length = urls.length; angular.extend(self, this.$current); } angular.forEach(proxies, function (proxy) { SoundList.prototype[proxy] = function () { return this.$current[proxy].apply(this.$current, [].slice.call(arguments)); }; }); SoundList.prototype.playing = false; SoundList.prototype.loading = false; SoundList.prototype.error = false; SoundList.prototype.paused = true; SoundList.prototype.setPosition = function (position) { if (Math.round(this.$behind / 1000) <= Math.round(position / 1000) && this.$behind + this.$current.duration > position) { var result = this.$current.setPosition(Math.max(position - this.$behind, 0)); this.$current.$digest(); return result; } else if (this.position < position) { // we're seeking to the future return this.$searchSeek(position); } else { // start our search at the beginning return this.$searchSeek(position, this.$first, 0); } }; /** * A recursive search forward through the playlist to find out * which sound contains the timecode requested and where in the sound it * occurs. * * This method is called by `setPosition(int position)` after it has been * determined that a simple seek within the active sound is not possible. * * Parameters: * position (int): the position to seek to, in msec. * sound (sound, optional): the sound to start the search from. Defaults * to the currently active sound. * behind: (int, optional): the number of `msec` that all sounds prior to the * passed sound consume. Should be passed when sound is. Defaults to the * running total we have calculated for the currently active sound. * * Returns a promise which resolves to the sound. **/ SoundList.prototype.$searchSeek = function (position, sound, behind) { sound = sound || this.$current; behind = angular.isDefined(behind) ? behind : this.$behind; // We set $current to an empty object so that continued changes // do not impact the playlist (i.e. state changing from playing to paused, // or no longer being in the 'loading' state.) var tmp = this.$current; this.$current = {}; tmp.setPosition(0); tmp.unload(); this.loading = !this.paused; // don't show a loading indicator for paused sounds. return this.$searchSeek_(position, sound, behind); }; // The recursive bit of the $searchSeek method - does not include // setup. SoundList.prototype.$searchSeek_ = function (position, sound, behind) { if (Math.round(sound.duration / 1000) + Math.round(behind / 1000) <= Math.round(position / 1000)) { var recur = angular.bind(this, this.$searchSeek_, position, sound.$next, behind + sound.duration); sound.setPosition(0); sound.unload(); if (sound.$next.duration) { // Already loaded, or pre-populated. return recur(); } else { // Need to load the sound in order to know its duration. return sound.$next.load().then(recur); } } else { // base case, we found the right sound! var setReturn = sound.setPosition(Math.max(position - behind, 0)); this.$current = sound; this.$behind = behind; if (!this.paused) { // If we were not paused before, resume playback. return sound.play(); } else { sound.$digest(); return setReturn; } } }; return { create: function (url, options) { return new Sound(url, options); }, createList: function (urls, options) { return new SoundList(urls, options); } }; function asyncDigest(fun) { return function () { var self = this; $timeout(function () { fun.call(self); }); }; } function generateCallbacks(sound, onchange) { onchange = onchange || angular.noop; return { onload: asyncDigest(function () { /* istanbul ignore else */ if (this.readyState === 1) { sound.loading = true; sound.error = false; } else if (this.readyState === 2) { sound.error = true; sound.loading = false; } else if (this.readyState === 3) { sound.loading = false; sound.error = false; sound.duration = this.duration; } if (this.readyState > 1 && !sound.$lp) { sound.$lp = sound.$ld.promise; sound.$ld.resolve(sound); } onchange.call(sound); }), onpause: asyncDigest(function () { sound.paused = true; sound.playing = false; onchange.call(sound); }), onplay: asyncDigest(function () { sound.paused = false; onchange.call(sound); }), onresume: asyncDigest(function () { sound.paused = false; onchange.call(sound); }), onid3: asyncDigest(function () { angular.copy(this.id3, sound.id3); onchange.call(sound); }), whileloading: asyncDigest(function () { sound.duration = this.durationEstimate; onchange.call(sound); }), whileplaying: asyncDigest(function () { sound.loading = false; sound.position = this.position; onchange.call(sound); }) }; } function makePromisedProxy (property) { return function () { var args = [].slice.call(arguments); return this.sound().then(function (sound) { return sound[property].apply(sound, args); }); }; } } module.factory('smSound', SoundFactory); })();
agpl-3.0
admpub/nging
vendor/github.com/andybalholm/brotli/static_dict.go
17114
package brotli import "encoding/binary" /* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Class to model the static dictionary. */ const maxStaticDictionaryMatchLen = 37 const kInvalidMatch uint32 = 0xFFFFFFF /* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ func hash(data []byte) uint32 { var h uint32 = binary.LittleEndian.Uint32(data) * kDictHashMul32 /* The higher bits contain more mixture from the multiplication, so we take our results from there. */ return h >> uint(32-kDictNumBits) } func addMatch(distance uint, len uint, len_code uint, matches []uint32) { var match uint32 = uint32((distance << 5) + len_code) matches[len] = brotli_min_uint32_t(matches[len], match) } func dictMatchLength(dict *dictionary, data []byte, id uint, len uint, maxlen uint) uint { var offset uint = uint(dict.offsets_by_length[len]) + len*id return findMatchLengthWithLimit(dict.data[offset:], data, brotli_min_size_t(uint(len), maxlen)) } func isMatch(d *dictionary, w dictWord, data []byte, max_length uint) bool { if uint(w.len) > max_length { return false } else { var offset uint = uint(d.offsets_by_length[w.len]) + uint(w.len)*uint(w.idx) var dict []byte = d.data[offset:] if w.transform == 0 { /* Match against base dictionary word. */ return findMatchLengthWithLimit(dict, data, uint(w.len)) == uint(w.len) } else if w.transform == 10 { /* Match against uppercase first transform. Note that there are only ASCII uppercase words in the lookup table. */ return dict[0] >= 'a' && dict[0] <= 'z' && (dict[0]^32) == data[0] && findMatchLengthWithLimit(dict[1:], data[1:], uint(w.len)-1) == uint(w.len-1) } else { /* Match against uppercase all transform. Note that there are only ASCII uppercase words in the lookup table. */ var i uint for i = 0; i < uint(w.len); i++ { if dict[i] >= 'a' && dict[i] <= 'z' { if (dict[i] ^ 32) != data[i] { return false } } else { if dict[i] != data[i] { return false } } } return true } } } func findAllStaticDictionaryMatches(dict *encoderDictionary, data []byte, min_length uint, max_length uint, matches []uint32) bool { var has_found_match bool = false { var offset uint = uint(dict.buckets[hash(data)]) var end bool = offset == 0 for !end { w := dict.dict_words[offset] offset++ var l uint = uint(w.len) & 0x1F var n uint = uint(1) << dict.words.size_bits_by_length[l] var id uint = uint(w.idx) end = !(w.len&0x80 == 0) w.len = byte(l) if w.transform == 0 { var matchlen uint = dictMatchLength(dict.words, data, id, l, max_length) var s []byte var minlen uint var maxlen uint var len uint /* Transform "" + BROTLI_TRANSFORM_IDENTITY + "" */ if matchlen == l { addMatch(id, l, l, matches) has_found_match = true } /* Transforms "" + BROTLI_TRANSFORM_OMIT_LAST_1 + "" and "" + BROTLI_TRANSFORM_OMIT_LAST_1 + "ing " */ if matchlen >= l-1 { addMatch(id+12*n, l-1, l, matches) if l+2 < max_length && data[l-1] == 'i' && data[l] == 'n' && data[l+1] == 'g' && data[l+2] == ' ' { addMatch(id+49*n, l+3, l, matches) } has_found_match = true } /* Transform "" + BROTLI_TRANSFORM_OMIT_LAST_# + "" (# = 2 .. 9) */ minlen = min_length if l > 9 { minlen = brotli_max_size_t(minlen, l-9) } maxlen = brotli_min_size_t(matchlen, l-2) for len = minlen; len <= maxlen; len++ { var cut uint = l - len var transform_id uint = (cut << 2) + uint((dict.cutoffTransforms>>(cut*6))&0x3F) addMatch(id+transform_id*n, uint(len), l, matches) has_found_match = true } if matchlen < l || l+6 >= max_length { continue } s = data[l:] /* Transforms "" + BROTLI_TRANSFORM_IDENTITY + <suffix> */ if s[0] == ' ' { addMatch(id+n, l+1, l, matches) if s[1] == 'a' { if s[2] == ' ' { addMatch(id+28*n, l+3, l, matches) } else if s[2] == 's' { if s[3] == ' ' { addMatch(id+46*n, l+4, l, matches) } } else if s[2] == 't' { if s[3] == ' ' { addMatch(id+60*n, l+4, l, matches) } } else if s[2] == 'n' { if s[3] == 'd' && s[4] == ' ' { addMatch(id+10*n, l+5, l, matches) } } } else if s[1] == 'b' { if s[2] == 'y' && s[3] == ' ' { addMatch(id+38*n, l+4, l, matches) } } else if s[1] == 'i' { if s[2] == 'n' { if s[3] == ' ' { addMatch(id+16*n, l+4, l, matches) } } else if s[2] == 's' { if s[3] == ' ' { addMatch(id+47*n, l+4, l, matches) } } } else if s[1] == 'f' { if s[2] == 'o' { if s[3] == 'r' && s[4] == ' ' { addMatch(id+25*n, l+5, l, matches) } } else if s[2] == 'r' { if s[3] == 'o' && s[4] == 'm' && s[5] == ' ' { addMatch(id+37*n, l+6, l, matches) } } } else if s[1] == 'o' { if s[2] == 'f' { if s[3] == ' ' { addMatch(id+8*n, l+4, l, matches) } } else if s[2] == 'n' { if s[3] == ' ' { addMatch(id+45*n, l+4, l, matches) } } } else if s[1] == 'n' { if s[2] == 'o' && s[3] == 't' && s[4] == ' ' { addMatch(id+80*n, l+5, l, matches) } } else if s[1] == 't' { if s[2] == 'h' { if s[3] == 'e' { if s[4] == ' ' { addMatch(id+5*n, l+5, l, matches) } } else if s[3] == 'a' { if s[4] == 't' && s[5] == ' ' { addMatch(id+29*n, l+6, l, matches) } } } else if s[2] == 'o' { if s[3] == ' ' { addMatch(id+17*n, l+4, l, matches) } } } else if s[1] == 'w' { if s[2] == 'i' && s[3] == 't' && s[4] == 'h' && s[5] == ' ' { addMatch(id+35*n, l+6, l, matches) } } } else if s[0] == '"' { addMatch(id+19*n, l+1, l, matches) if s[1] == '>' { addMatch(id+21*n, l+2, l, matches) } } else if s[0] == '.' { addMatch(id+20*n, l+1, l, matches) if s[1] == ' ' { addMatch(id+31*n, l+2, l, matches) if s[2] == 'T' && s[3] == 'h' { if s[4] == 'e' { if s[5] == ' ' { addMatch(id+43*n, l+6, l, matches) } } else if s[4] == 'i' { if s[5] == 's' && s[6] == ' ' { addMatch(id+75*n, l+7, l, matches) } } } } } else if s[0] == ',' { addMatch(id+76*n, l+1, l, matches) if s[1] == ' ' { addMatch(id+14*n, l+2, l, matches) } } else if s[0] == '\n' { addMatch(id+22*n, l+1, l, matches) if s[1] == '\t' { addMatch(id+50*n, l+2, l, matches) } } else if s[0] == ']' { addMatch(id+24*n, l+1, l, matches) } else if s[0] == '\'' { addMatch(id+36*n, l+1, l, matches) } else if s[0] == ':' { addMatch(id+51*n, l+1, l, matches) } else if s[0] == '(' { addMatch(id+57*n, l+1, l, matches) } else if s[0] == '=' { if s[1] == '"' { addMatch(id+70*n, l+2, l, matches) } else if s[1] == '\'' { addMatch(id+86*n, l+2, l, matches) } } else if s[0] == 'a' { if s[1] == 'l' && s[2] == ' ' { addMatch(id+84*n, l+3, l, matches) } } else if s[0] == 'e' { if s[1] == 'd' { if s[2] == ' ' { addMatch(id+53*n, l+3, l, matches) } } else if s[1] == 'r' { if s[2] == ' ' { addMatch(id+82*n, l+3, l, matches) } } else if s[1] == 's' { if s[2] == 't' && s[3] == ' ' { addMatch(id+95*n, l+4, l, matches) } } } else if s[0] == 'f' { if s[1] == 'u' && s[2] == 'l' && s[3] == ' ' { addMatch(id+90*n, l+4, l, matches) } } else if s[0] == 'i' { if s[1] == 'v' { if s[2] == 'e' && s[3] == ' ' { addMatch(id+92*n, l+4, l, matches) } } else if s[1] == 'z' { if s[2] == 'e' && s[3] == ' ' { addMatch(id+100*n, l+4, l, matches) } } } else if s[0] == 'l' { if s[1] == 'e' { if s[2] == 's' && s[3] == 's' && s[4] == ' ' { addMatch(id+93*n, l+5, l, matches) } } else if s[1] == 'y' { if s[2] == ' ' { addMatch(id+61*n, l+3, l, matches) } } } else if s[0] == 'o' { if s[1] == 'u' && s[2] == 's' && s[3] == ' ' { addMatch(id+106*n, l+4, l, matches) } } } else { var is_all_caps bool = (w.transform != transformUppercaseFirst) /* Set is_all_caps=0 for BROTLI_TRANSFORM_UPPERCASE_FIRST and is_all_caps=1 otherwise (BROTLI_TRANSFORM_UPPERCASE_ALL) transform. */ var s []byte if !isMatch(dict.words, w, data, max_length) { continue } /* Transform "" + kUppercase{First,All} + "" */ var tmp int if is_all_caps { tmp = 44 } else { tmp = 9 } addMatch(id+uint(tmp)*n, l, l, matches) has_found_match = true if l+1 >= max_length { continue } /* Transforms "" + kUppercase{First,All} + <suffix> */ s = data[l:] if s[0] == ' ' { var tmp int if is_all_caps { tmp = 68 } else { tmp = 4 } addMatch(id+uint(tmp)*n, l+1, l, matches) } else if s[0] == '"' { var tmp int if is_all_caps { tmp = 87 } else { tmp = 66 } addMatch(id+uint(tmp)*n, l+1, l, matches) if s[1] == '>' { var tmp int if is_all_caps { tmp = 97 } else { tmp = 69 } addMatch(id+uint(tmp)*n, l+2, l, matches) } } else if s[0] == '.' { var tmp int if is_all_caps { tmp = 101 } else { tmp = 79 } addMatch(id+uint(tmp)*n, l+1, l, matches) if s[1] == ' ' { var tmp int if is_all_caps { tmp = 114 } else { tmp = 88 } addMatch(id+uint(tmp)*n, l+2, l, matches) } } else if s[0] == ',' { var tmp int if is_all_caps { tmp = 112 } else { tmp = 99 } addMatch(id+uint(tmp)*n, l+1, l, matches) if s[1] == ' ' { var tmp int if is_all_caps { tmp = 107 } else { tmp = 58 } addMatch(id+uint(tmp)*n, l+2, l, matches) } } else if s[0] == '\'' { var tmp int if is_all_caps { tmp = 94 } else { tmp = 74 } addMatch(id+uint(tmp)*n, l+1, l, matches) } else if s[0] == '(' { var tmp int if is_all_caps { tmp = 113 } else { tmp = 78 } addMatch(id+uint(tmp)*n, l+1, l, matches) } else if s[0] == '=' { if s[1] == '"' { var tmp int if is_all_caps { tmp = 105 } else { tmp = 104 } addMatch(id+uint(tmp)*n, l+2, l, matches) } else if s[1] == '\'' { var tmp int if is_all_caps { tmp = 116 } else { tmp = 108 } addMatch(id+uint(tmp)*n, l+2, l, matches) } } } } } /* Transforms with prefixes " " and "." */ if max_length >= 5 && (data[0] == ' ' || data[0] == '.') { var is_space bool = (data[0] == ' ') var offset uint = uint(dict.buckets[hash(data[1:])]) var end bool = offset == 0 for !end { w := dict.dict_words[offset] offset++ var l uint = uint(w.len) & 0x1F var n uint = uint(1) << dict.words.size_bits_by_length[l] var id uint = uint(w.idx) end = !(w.len&0x80 == 0) w.len = byte(l) if w.transform == 0 { var s []byte if !isMatch(dict.words, w, data[1:], max_length-1) { continue } /* Transforms " " + BROTLI_TRANSFORM_IDENTITY + "" and "." + BROTLI_TRANSFORM_IDENTITY + "" */ var tmp int if is_space { tmp = 6 } else { tmp = 32 } addMatch(id+uint(tmp)*n, l+1, l, matches) has_found_match = true if l+2 >= max_length { continue } /* Transforms " " + BROTLI_TRANSFORM_IDENTITY + <suffix> and "." + BROTLI_TRANSFORM_IDENTITY + <suffix> */ s = data[l+1:] if s[0] == ' ' { var tmp int if is_space { tmp = 2 } else { tmp = 77 } addMatch(id+uint(tmp)*n, l+2, l, matches) } else if s[0] == '(' { var tmp int if is_space { tmp = 89 } else { tmp = 67 } addMatch(id+uint(tmp)*n, l+2, l, matches) } else if is_space { if s[0] == ',' { addMatch(id+103*n, l+2, l, matches) if s[1] == ' ' { addMatch(id+33*n, l+3, l, matches) } } else if s[0] == '.' { addMatch(id+71*n, l+2, l, matches) if s[1] == ' ' { addMatch(id+52*n, l+3, l, matches) } } else if s[0] == '=' { if s[1] == '"' { addMatch(id+81*n, l+3, l, matches) } else if s[1] == '\'' { addMatch(id+98*n, l+3, l, matches) } } } } else if is_space { var is_all_caps bool = (w.transform != transformUppercaseFirst) /* Set is_all_caps=0 for BROTLI_TRANSFORM_UPPERCASE_FIRST and is_all_caps=1 otherwise (BROTLI_TRANSFORM_UPPERCASE_ALL) transform. */ var s []byte if !isMatch(dict.words, w, data[1:], max_length-1) { continue } /* Transforms " " + kUppercase{First,All} + "" */ var tmp int if is_all_caps { tmp = 85 } else { tmp = 30 } addMatch(id+uint(tmp)*n, l+1, l, matches) has_found_match = true if l+2 >= max_length { continue } /* Transforms " " + kUppercase{First,All} + <suffix> */ s = data[l+1:] if s[0] == ' ' { var tmp int if is_all_caps { tmp = 83 } else { tmp = 15 } addMatch(id+uint(tmp)*n, l+2, l, matches) } else if s[0] == ',' { if !is_all_caps { addMatch(id+109*n, l+2, l, matches) } if s[1] == ' ' { var tmp int if is_all_caps { tmp = 111 } else { tmp = 65 } addMatch(id+uint(tmp)*n, l+3, l, matches) } } else if s[0] == '.' { var tmp int if is_all_caps { tmp = 115 } else { tmp = 96 } addMatch(id+uint(tmp)*n, l+2, l, matches) if s[1] == ' ' { var tmp int if is_all_caps { tmp = 117 } else { tmp = 91 } addMatch(id+uint(tmp)*n, l+3, l, matches) } } else if s[0] == '=' { if s[1] == '"' { var tmp int if is_all_caps { tmp = 110 } else { tmp = 118 } addMatch(id+uint(tmp)*n, l+3, l, matches) } else if s[1] == '\'' { var tmp int if is_all_caps { tmp = 119 } else { tmp = 120 } addMatch(id+uint(tmp)*n, l+3, l, matches) } } } } } if max_length >= 6 { /* Transforms with prefixes "e ", "s ", ", " and "\xC2\xA0" */ if (data[1] == ' ' && (data[0] == 'e' || data[0] == 's' || data[0] == ',')) || (data[0] == 0xC2 && data[1] == 0xA0) { var offset uint = uint(dict.buckets[hash(data[2:])]) var end bool = offset == 0 for !end { w := dict.dict_words[offset] offset++ var l uint = uint(w.len) & 0x1F var n uint = uint(1) << dict.words.size_bits_by_length[l] var id uint = uint(w.idx) end = !(w.len&0x80 == 0) w.len = byte(l) if w.transform == 0 && isMatch(dict.words, w, data[2:], max_length-2) { if data[0] == 0xC2 { addMatch(id+102*n, l+2, l, matches) has_found_match = true } else if l+2 < max_length && data[l+2] == ' ' { var t uint = 13 if data[0] == 'e' { t = 18 } else if data[0] == 's' { t = 7 } addMatch(id+t*n, l+3, l, matches) has_found_match = true } } } } } if max_length >= 9 { /* Transforms with prefixes " the " and ".com/" */ if (data[0] == ' ' && data[1] == 't' && data[2] == 'h' && data[3] == 'e' && data[4] == ' ') || (data[0] == '.' && data[1] == 'c' && data[2] == 'o' && data[3] == 'm' && data[4] == '/') { var offset uint = uint(dict.buckets[hash(data[5:])]) var end bool = offset == 0 for !end { w := dict.dict_words[offset] offset++ var l uint = uint(w.len) & 0x1F var n uint = uint(1) << dict.words.size_bits_by_length[l] var id uint = uint(w.idx) end = !(w.len&0x80 == 0) w.len = byte(l) if w.transform == 0 && isMatch(dict.words, w, data[5:], max_length-5) { var tmp int if data[0] == ' ' { tmp = 41 } else { tmp = 72 } addMatch(id+uint(tmp)*n, l+5, l, matches) has_found_match = true if l+5 < max_length { var s []byte = data[l+5:] if data[0] == ' ' { if l+8 < max_length && s[0] == ' ' && s[1] == 'o' && s[2] == 'f' && s[3] == ' ' { addMatch(id+62*n, l+9, l, matches) if l+12 < max_length && s[4] == 't' && s[5] == 'h' && s[6] == 'e' && s[7] == ' ' { addMatch(id+73*n, l+13, l, matches) } } } } } } } } return has_found_match }
agpl-3.0
steromano87/Gawain
common/php/classes/controllers/Authentication.php
3794
<?php /** * Gawain * Copyright (C) 2016 Stefano Romanò (rumix87 (at) gmail (dot) com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace Gawain\Classes\Controllers; use Gawain\Abstracts\Controllers\GawainController; use Gawain\Functions\StringFunctions; use Identicon\Identicon; class Authentication extends GawainController { private $sessionMapper; private $userMapper; public function __construct($obj_Spot) { parent::__construct($obj_Spot); $this->sessionMapper = $this->spot->mapper('Gawain\Classes\Entities\Session'); $this->userMapper = $this->spot->mapper('Gawain\Classes\Entities\User'); } public function login($str_Username, $str_HashedPassword, $str_ClientHost = null) { $arr_Result = $this->userMapper->credentialsCheck($str_Username, $str_HashedPassword, 3); if ($arr_Result['result']) { $date_SessionEnd = new \DateTime(); $str_SessionID = $this->sessionMapper->insert( array( 'sessionID' => StringFunctions\generateSessionID(), 'userName' => $str_Username, 'sessionStart' => new \DateTime(), 'sessionEnd' => $date_SessionEnd->add(new \DateInterval('PT1H')), 'clientHost' => $str_ClientHost, '_createdBy' => $str_Username ) ); if ($str_SessionID) { return $str_SessionID; } else { return false; } } else { return false; } } public function logout($str_SessionID) { $this->sessionMapper->expire($str_SessionID); } public function isValidSession($str_SessionID) { return $this->sessionMapper->isValid($str_SessionID); } public function getUserFromSession($str_SessionID) { $obj_Session = $this->sessionMapper->get($str_SessionID); return $obj_Session ? $obj_Session->userName : null; } public function getNamedUserFromSession($str_SessionID) { $str_UserName = $this->getUserFromSession($str_SessionID); return is_null($str_UserName) ? null : $this->userMapper->get($this->getUserFromSession($str_SessionID)) ->fullName; } public function getUserImage($str_SessionID) { $obj_Identicon = new Identicon(); $str_UserName = $this->getUserFromSession($str_SessionID); $obj_UserImage = is_null($str_UserName)? null : $this->userMapper->get($this->getUserFromSession ($str_SessionID))->miniature; if (is_null($obj_UserImage)) { return is_null($str_UserName) ? null : $obj_Identicon->getImageDataUri($str_UserName); } else { return $obj_UserImage; } } public function setDomain($str_SessionID, $int_DomainID) { $obj_Session = $this->sessionMapper->get($str_SessionID); $obj_Session->_domainID = $int_DomainID; $obj_Session->_lastModifiedBy = $this->getUserFromSession($str_SessionID); $this->sessionMapper->update($obj_Session); } }
agpl-3.0
TiarkRompf/lancet
src/main/scala/lancet/core/Core_TIR_Opt.scala
17387
/* * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/agpl.html. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package lancet.core trait Core_TIR_Opt extends Base_TIR_Opt with Core_TIR { def liftConst[T:TypeRep](x:T): Rep[T] = Static(x) // byte/char/short conversion override def byteToInt(x: Rep[Byte]): Rep[Int] = eval(x) match { case Const(x) => x.toInt case _ => super.byteToInt(x) } override def charToInt(x: Rep[Char]): Rep[Int] = eval(x) match { case Const(x) => x.toInt case _ => super.charToInt(x) } override def shortToInt(x: Rep[Short]): Rep[Int] = eval(x) match { case Const(x) => x.toInt case _ => super.shortToInt(x) } // int conversion override def intToByte(x: Rep[Int]): Rep[Byte] = eval(x) match { case Const(x) => x.toByte case _ => super.intToByte(x) } override def intToChar(x: Rep[Int]): Rep[Char] = eval(x) match { case Const(x) => x.toChar case _ => super.intToChar(x) } override def intToShort(x: Rep[Int]): Rep[Short] = eval(x) match { case Const(x) => x.toShort case _ => super.intToShort(x) } override def intToInt(x: Rep[Int]): Rep[Int] = x override def intToLong(x: Rep[Int]): Rep[Long] = eval(x) match { case Const(x) => x.toLong case _ => super.intToLong(x) } override def intToFloat(x: Rep[Int]): Rep[Float] = eval(x) match { case Const(x) => x.toFloat case _ => super.intToFloat(x) } override def intToDouble(x: Rep[Int]): Rep[Double] = eval(x) match { case Const(x) => x.toDouble case _ => super.intToDouble(x) } // int arithmetic override def intNegate(x: Rep[Int]): Rep[Int] = eval(x) match { case Const(x) => -x case _ => super.intNegate(x) } override def intPlus(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x + y case (Const(0), _) => y case (_, Const(0)) => x case _ => super.intPlus(x,y) } override def intMinus(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x - y case (Const(0), _) => intNegate(y) case (_, Const(0)) => x case _ => super.intMinus(x,y) } override def intTimes(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x * y case (Const(0), _) => 0 case (_, Const(0)) => 0 case (Const(1), _) => y case (_, Const(1)) => x case (Const(-1), _) => intNegate(y) case (_, Const(-1)) => intNegate(x) case _ => super.intTimes(x,y) } override def intDiv(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x / y case _ => super.intDiv(x,y) } override def intMod(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x % y case _ => super.intMod(x,y) } override def intAnd(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x & y case _ => super.intAnd(x,y) } override def intOr(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x | y case _ => super.intOr(x,y) } override def intXor(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x ^ y case _ => super.intXor(x,y) } override def intShiftLeft(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x << y case _ => super.intShiftLeft(x,y) } override def intShiftRight(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x >> y case _ => super.intShiftRight(x,y) } override def intShiftRightUnsigned(x: Rep[Int], y: Rep[Int]): Rep[Int] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x >>> y case _ => super.intShiftRightUnsigned(x,y) } override def intLess(x: Rep[Int], y: Rep[Int]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x < y case _ => super.intLess(x,y) } override def intLessEqual(x: Rep[Int], y: Rep[Int]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x <= y case _ => super.intLessEqual(x,y) } override def intGreater(x: Rep[Int], y: Rep[Int]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x > y case _ => super.intGreater(x,y) } override def intGreaterEqual(x: Rep[Int], y: Rep[Int]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x >= y case _ => super.intGreaterEqual(x,y) } override def intEqual(x: Rep[Int], y: Rep[Int]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x == y case _ => super.intEqual(x,y) } override def intNotEqual(x: Rep[Int], y: Rep[Int]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x != y case _ => super.intNotEqual(x,y) } // long conversion override def longToByte(x: Rep[Long]): Rep[Byte] = eval(x) match { case Const(x) => x.toByte case _ => super.longToByte(x) } override def longToChar(x: Rep[Long]): Rep[Char] = eval(x) match { case Const(x) => x.toChar case _ => super.longToChar(x) } override def longToShort(x: Rep[Long]): Rep[Short] = eval(x) match { case Const(x) => x.toShort case _ => super.longToShort(x) } override def longToInt(x: Rep[Long]): Rep[Int] = eval(x) match { case Const(x) => x.toInt case _ => super.longToInt(x) } override def longToLong(x: Rep[Long]): Rep[Long] = x override def longToFloat(x: Rep[Long]): Rep[Float] = eval(x) match { case Const(x) => x.toFloat case _ => super.longToFloat(x) } override def longToDouble(x: Rep[Long]): Rep[Double] = eval(x) match { case Const(x) => x.toDouble case _ => super.longToDouble(x) } // long arithmetic override def longNegate(x: Rep[Long]): Rep[Long] = eval(x) match { case Const(x) => -x case _ => super.longNegate(x) } override def longPlus(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x + y case (Const(0), _) => y case (_, Const(0)) => x case _ => super.longPlus(x,y) } override def longMinus(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x - y case (Const(0), _) => longNegate(y) case (_, Const(0)) => x case _ => super.longMinus(x,y) } override def longTimes(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x * y case (Const(0), _) => 0 case (_, Const(0)) => 0 case (Const(1), _) => y case (_, Const(1)) => x case (Const(-1), _) => longNegate(y) case (_, Const(-1)) => longNegate(x) case _ => super.longTimes(x,y) } override def longDiv(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x / y case _ => super.longDiv(x,y) } override def longMod(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x % y case _ => super.longMod(x,y) } override def longAnd(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x & y case _ => super.longAnd(x,y) } override def longOr(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x | y case _ => super.longOr(x,y) } override def longXor(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x ^ y case _ => super.longXor(x,y) } override def longShiftLeft(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x << y case _ => super.longShiftLeft(x,y) } override def longShiftRight(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x >> y case _ => super.longShiftRight(x,y) } override def longShiftRightUnsigned(x: Rep[Long], y: Rep[Long]): Rep[Long] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x >>> y case _ => super.longShiftRightUnsigned(x,y) } override def longLess(x: Rep[Long], y: Rep[Long]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x < y case _ => super.longLess(x,y) } override def longLessEqual(x: Rep[Long], y: Rep[Long]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x <= y case _ => super.longLessEqual(x,y) } override def longGreater(x: Rep[Long], y: Rep[Long]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x > y case _ => super.longGreater(x,y) } override def longGreaterEqual(x: Rep[Long], y: Rep[Long]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x >= y case _ => super.longGreaterEqual(x,y) } override def longEqual(x: Rep[Long], y: Rep[Long]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x == y case _ => super.longEqual(x,y) } override def longNotEqual(x: Rep[Long], y: Rep[Long]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x != y case _ => super.longNotEqual(x,y) } // float conversion override def floatToByte(x: Rep[Float]): Rep[Byte] = eval(x) match { case Const(x) => x.toByte case _ => super.floatToByte(x) } override def floatToChar(x: Rep[Float]): Rep[Char] = eval(x) match { case Const(x) => x.toChar case _ => super.floatToChar(x) } override def floatToShort(x: Rep[Float]): Rep[Short] = eval(x) match { case Const(x) => x.toShort case _ => super.floatToShort(x) } override def floatToInt(x: Rep[Float]): Rep[Int] = eval(x) match { case Const(x) => x.toInt case _ => super.floatToInt(x) } override def floatToLong(x: Rep[Float]): Rep[Long] = eval(x) match { case Const(x) => x.toLong case _ => super.floatToLong(x) } override def floatToFloat(x: Rep[Float]): Rep[Float] = x override def floatToDouble(x: Rep[Float]): Rep[Double] = eval(x) match { case Const(x) => x.toDouble case _ => super.floatToDouble(x) } // float arithmetic override def floatNegate(x: Rep[Float]): Rep[Float] = eval(x) match { case Const(x) => -x case _ => super.floatNegate(x) } override def floatPlus(x: Rep[Float], y: Rep[Float]): Rep[Float] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x + y case _ => super.floatPlus(x,y) } override def floatMinus(x: Rep[Float], y: Rep[Float]): Rep[Float] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x - y case _ => super.floatMinus(x,y) } override def floatTimes(x: Rep[Float], y: Rep[Float]): Rep[Float] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x * y case _ => super.floatTimes(x,y) } override def floatDiv(x: Rep[Float], y: Rep[Float]): Rep[Float] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x / y case _ => super.floatDiv(x,y) } override def floatMod(x: Rep[Float], y: Rep[Float]): Rep[Float] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x % y case _ => super.floatMod(x,y) } override def floatLess(x: Rep[Float], y: Rep[Float]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x < y case _ => super.floatLess(x,y) } override def floatLessEqual(x: Rep[Float], y: Rep[Float]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x <= y case _ => super.floatLessEqual(x,y) } override def floatGreater(x: Rep[Float], y: Rep[Float]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x > y case _ => super.floatGreater(x,y) } override def floatGreaterEqual(x: Rep[Float], y: Rep[Float]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x >= y case _ => super.floatGreaterEqual(x,y) } override def floatEqual(x: Rep[Float], y: Rep[Float]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x == y case _ => super.floatEqual(x,y) } override def floatNotEqual(x: Rep[Float], y: Rep[Float]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x != y case _ => super.floatNotEqual(x,y) } // double conversion override def doubleToByte(x: Rep[Double]): Rep[Byte] = eval(x) match { case Const(x) => x.toByte case _ => super.doubleToByte(x) } override def doubleToChar(x: Rep[Double]): Rep[Char] = eval(x) match { case Const(x) => x.toChar case _ => super.doubleToChar(x) } override def doubleToShort(x: Rep[Double]): Rep[Short] = eval(x) match { case Const(x) => x.toShort case _ => super.doubleToShort(x) } override def doubleToInt(x: Rep[Double]): Rep[Int] = eval(x) match { case Const(x) => x.toInt case _ => super.doubleToInt(x) } override def doubleToLong(x: Rep[Double]): Rep[Long] = eval(x) match { case Const(x) => x.toLong case _ => super.doubleToLong(x) } override def doubleToFloat(x: Rep[Double]): Rep[Float] = eval(x) match { case Const(x) => x.toFloat case _ => super.doubleToFloat(x) } override def doubleToDouble(x: Rep[Double]): Rep[Double] = x // double arithmetic override def doubleNegate(x: Rep[Double]): Rep[Double] = eval(x) match { case Const(x) => -x case _ => super.doubleNegate(x) } override def doublePlus(x: Rep[Double], y: Rep[Double]): Rep[Double] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x + y case _ => super.doublePlus(x,y) } override def doubleMinus(x: Rep[Double], y: Rep[Double]): Rep[Double] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x - y case _ => super.doubleMinus(x,y) } override def doubleTimes(x: Rep[Double], y: Rep[Double]): Rep[Double] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x * y case _ => super.doubleTimes(x,y) } override def doubleDiv(x: Rep[Double], y: Rep[Double]): Rep[Double] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x / y case _ => super.doubleDiv(x,y) } override def doubleMod(x: Rep[Double], y: Rep[Double]): Rep[Double] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x % y case _ => super.doubleMod(x,y) } override def doubleLess(x: Rep[Double], y: Rep[Double]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x < y case _ => super.doubleLess(x,y) } override def doubleLessEqual(x: Rep[Double], y: Rep[Double]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x <= y case _ => super.doubleLessEqual(x,y) } override def doubleGreater(x: Rep[Double], y: Rep[Double]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x > y case _ => super.doubleGreater(x,y) } override def doubleGreaterEqual(x: Rep[Double], y: Rep[Double]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x >= y case _ => super.doubleGreaterEqual(x,y) } override def doubleEqual(x: Rep[Double], y: Rep[Double]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x == y case _ => super.doubleEqual(x,y) } override def doubleNotEqual(x: Rep[Double], y: Rep[Double]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x != y case _ => super.doubleNotEqual(x,y) } // object ops override def objectEqual(x: Rep[Object], y: Rep[Object]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x eq y case (Partial(fs), Const(null)) => false case _ => super.objectEqual(x,y) } override def objectNotEqual(x: Rep[Object], y: Rep[Object]): Rep[Boolean] = (eval(x),eval(y)) match { case (Const(x), Const(y)) => x ne y case (Partial(fs), Const(null)) => true case _ => super.objectNotEqual(x,y) } override def objectAsInstanceOf[T:TypeRep](x: Rep[Object]): Rep[T] = eval(x) match { case Const(x) => liftConst(x.asInstanceOf[T]) case _ => super.objectAsInstanceOf[T](x) } override def objectIsInstanceOf[T:TypeRep](x: Rep[Object]): Rep[Boolean] = eval(x) match { //case Const(x) => liftConst(x.isInstanceOf[T]) // FIXME: eliminated by erasure !! case _ => super.objectIsInstanceOf[T](x) } override def if_[T:TypeRep](x: Rep[Boolean])(y: =>Rep[T])(z: =>Rep[T]): Rep[T] = eval(x) match { case Const(x) => if (x) y else z case _ => super.if_(x)(y)(z) } }
agpl-3.0
emitter-io/emitter
internal/errors/error.go
2895
/********************************************************************************** * Copyright (c) 2009-2019 Misakai Ltd. * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Affero General Public License as published by the Free Software * Foundation, either version 3 of the License, or(at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see<http://www.gnu.org/licenses/>. ************************************************************************************/ package errors // New creates a new error func New(msg string) *Error { return &Error{ Status: 500, Message: msg, } } // Error represents an event code which provides a more details. type Error struct { Request uint16 `json:"req,omitempty"` Status int `json:"status"` Message string `json:"message"` } // Error implements error interface. func (e *Error) Error() string { return e.Message } // Copy clones the error object. func (e *Error) Copy() *Error { copyErr := *e return &copyErr } // ForRequest returns an error for a specific request. func (e *Error) ForRequest(requestID uint16) { e.Request = requestID } // Represents a set of errors used in the handlers. var ( ErrBadRequest = &Error{Status: 400, Message: "the request was invalid or cannot be otherwise served"} ErrUnauthorized = &Error{Status: 401, Message: "the security key provided is not authorized to perform this operation"} ErrPaymentRequired = &Error{Status: 402, Message: "the request can not be served, as the payment is required to proceed"} ErrForbidden = &Error{Status: 403, Message: "the request is understood, but it has been refused or access is not allowed"} ErrNotFound = &Error{Status: 404, Message: "the resource requested does not exist"} ErrServerError = &Error{Status: 500, Message: "an unexpected condition was encountered and no more specific message is suitable"} ErrNotImplemented = &Error{Status: 501, Message: "the server either does not recognize the request method, or it lacks the ability to fulfill the request"} ErrTargetInvalid = &Error{Status: 400, Message: "channel should end with `/` for strict types or `/#/` for wildcards"} ErrTargetTooLong = &Error{Status: 400, Message: "channel can not have more than 23 parts"} ErrLinkInvalid = &Error{Status: 400, Message: "the link must be an alphanumeric string of 1 or 2 characters"} ErrUnauthorizedExt = &Error{Status: 401, Message: "the security key with extend permission can only be used for private links"} )
agpl-3.0
dpausp/arguments
src/ekklesia_portal/concepts/argument_relation/argument_relation_views.py
3692
import logging from ekklesia_common.lid import LID from morepath import redirect from webob.exc import HTTPBadRequest from ekklesia_portal.app import App from ekklesia_portal.datamodel import Argument, ArgumentRelation, ArgumentVote, Proposition from ekklesia_portal.enums import ArgumentType from ekklesia_portal.permission import CreatePermission, VotePermission from .argument_relation_cells import ArgumentRelationCell, NewArgumentForPropositionCell from .argument_relation_contracts import ArgumentForPropositionForm from .argument_relations import ArgumentRelations logg = logging.getLogger(__name__) @App.permission_rule(model=ArgumentRelations, permission=CreatePermission) def argument_relation_create_permission(identity, model, permission): # All logged-in users may create new arguments. # We will have more restrictions in the future. return True @App.permission_rule(model=ArgumentRelation, permission=VotePermission) def argument_relation_vote_permission(identity, model, permission): # All logged-in users may vote on arguments. # We will have more restrictions in the future. return True @App.path(model=ArgumentRelation, path="/p/{proposition_id}/a/{argument_id}") def argument_relation(request, proposition_id=LID(), argument_id=0): argument_relation = request.q(ArgumentRelation).filter_by( proposition_id=proposition_id, argument_id=argument_id ).scalar() return argument_relation @App.path(model=ArgumentRelations, path="/p/{proposition_id}/a") def argument_relations(request, proposition_id=LID(), relation_type=None): return ArgumentRelations(proposition_id, relation_type) @App.html(model=ArgumentRelation) def show_argument_relation(self, request): return ArgumentRelationCell(self, request).show() @App.html(model=ArgumentRelation, name='vote', request_method='POST', permission=VotePermission) def post_vote(self, request): vote_weight = request.POST.get('weight') if vote_weight not in ('-1', '0', '1'): raise HTTPBadRequest() vote = request.db_session.query(ArgumentVote).filter_by(relation=self, member=request.current_user).scalar() if vote is None: vote = ArgumentVote(relation=self, member=request.current_user, weight=int(vote_weight)) request.db_session.add(vote) else: vote.weight = int(vote_weight) redirect_url = request.link(self.proposition) + '#argument_relation_' + str(self.id) return redirect(redirect_url) @App.html(model=ArgumentRelations, name='new', permission=CreatePermission) def new(self, request): form_data = { 'relation_type': ArgumentType[self.relation_type], 'proposition_id': self.proposition_id, } form = ArgumentForPropositionForm(request, request.link(self)) return NewArgumentForPropositionCell(request, form, form_data, model=self).show() @App.html_form_post( model=ArgumentRelations, form=ArgumentForPropositionForm, cell=NewArgumentForPropositionCell, permission=CreatePermission ) def create(self, request, appstruct): proposition = request.db_session.query(Proposition).get(self.proposition_id) if proposition is None: raise HTTPBadRequest() argument = Argument( title=appstruct['title'], abstract=appstruct['abstract'], details=appstruct['details'], author=request.current_user ) argument_relation = ArgumentRelation( proposition=proposition, argument=argument, argument_type=appstruct['relation_type'] ) request.db_session.add(argument) request.db_session.add(argument_relation) request.db_session.flush() return redirect(request.link(proposition))
agpl-3.0