code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<?php abstract class HpsCardBrand { const MASTERCARD = 'MC'; const AMEX = 'Amex'; const VISA = 'Visa'; const DISCOVER = 'Disc'; }
Cartworks/Platform
core/addons/payment_heartland/include/src/Infrastructure/Enums/HpsCardBrand.php
PHP
mit
161
<?php /* * This file is part of the php-formatter package * * Copyright (c) >=2014 Marc Morera * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> */ declare(strict_types=1); namespace Mmoreram\PHPFormatter\Fixer; use Mmoreram\PHPFormatter\Fixer\Interfaces\FixerInterface; /** * Class HeaderFixer. */ class HeaderFixer implements FixerInterface { /** * @var string * * Header */ private $header; /** * Construct method. * * @param string $header Header */ public function __construct($header) { $this->header = '<?php' . rtrim("\n\n" . trim($header) . "\n\n") . "\n\n"; } /** * Do the fix. Return the fixed code or false if the code has not changed. * * @param string $data * * @return string|false */ public function fix($data) { $regex = '~(?P<group>^\s*<\?php(?:(?:(?:/\*.*?\*/)|(?:(?://|#).*?\n{1})|(?:\s*))*))(?P<other>.*)~s'; preg_match($regex, $data, $results); if (!isset($results['group'])) { return false; } $other = $results['other']; $fixedData = $this->header . ltrim($other); return $fixedData !== $data ? $fixedData : false; } }
mmoreram/php-formatter
src/PHPFormatter/Fixer/HeaderFixer.php
PHP
mit
1,447
# My personal website https://alexputs.github.io This website is based on skinny bones jekyll theme. I've added very simple multilingual support and currently working on introducing new content for this pages. If you are interested in original source please visit: https://github.com/mmistakes/skinny-bones-jekyll
AlexPutz/alexputz.github.io
README.md
Markdown
mit
316
'use strict' var Transform = require('stream').Transform , util = require('util') , Segment = require('./segment') , Message = require('./message') , utils = require('./utils') // MLP end frames var FS = String.fromCharCode(0x1c) , CR = String.fromCharCode(0x0d) exports.Message = Message exports.Segment = Segment exports.Parser = Parser exports.utils = utils /** * Constructor */ function Parser() { var opts = { objectMode: true } if (!(this instanceof Parser)) return new Parser(opts) Transform.call(this, opts) this._messages = [] this.current = null } util.inherits(Parser, Transform) Parser.prototype._tryParseSegment = function _tryParseSegment(data, delims) { var self = this try { return new Segment(data, delims) } catch (err) { self.emit('error', err) return null } } /** * Transform for parser * * **NOTE: The stream should have been pipe through `split()` already** * * @param {Buffer} data The segment as a buffer * @param {String} encoding The encoding of the buffer * @param {Function} cb function(err, res) * @api private */ Parser.prototype._transform = function(data, encoding, done) { var delims = this.current ? this.current.delimiters() : null var segment = this._tryParseSegment(data, delims) if (!segment) return if (segment && segment.parsed) { var isHeader = utils.segmentIsHeader(segment) if (isHeader && this.current) { this.emit('message', this.current) var message = new Message() message.addSegment(segment) this._messages.push(message) this.current = message } else if (isHeader && !this.current) { this.current = new Message() this.current.addSegment(segment) } else { this.current.addSegment(segment) } /* If the message ended with FS+CR, this indicates the end of the message and it should be pushed over the transform stream now. http://www.hl7standards.com/blog/2007/05/02/hl7-mlp-minimum-layer-protocol-defined/ */ if (data.indexOf(FS + CR) !== -1) { this.emit('message', this.current) this.current = null } } done() } Parser.prototype._flush = function(done) { if (this.current && this.current.segments.length) { this.emit('message', this.current) this._messages.push(this.current) this.current = null } this.emit('messages', this._messages) done() }
evanlucas/nodengine-hl7
lib/index.js
JavaScript
mit
2,413
#ifndef __NBA_KNAPP_RMA_HH__ #define __NBA_KNAPP_RMA_HH__ #include <cstdint> #include <scif.h> namespace nba { namespace knapp { class RMABuffer { public: #ifdef __MIC__ RMABuffer(scif_epd_t epd, size_t size); #else RMABuffer(scif_epd_t epd, size_t size, int node_id); #endif RMABuffer(scif_epd_t epd, void *extern_arena, size_t size); virtual ~RMABuffer(); void write(off_t offset, size_t size, bool sync = false); void read(off_t offset, size_t size, bool sync = false); off_t va() const { return _local_va; } off_t ra() const { return _local_ra; } void set_peer_ra(off_t value) { this->_peer_ra = value; } off_t peer_ra() const { return _peer_ra; } #ifndef __MIC__ void set_peer_va(off_t value) { this->_peer_va = value; } off_t peer_va() const { return _peer_va; } #endif private: scif_epd_t _epd; size_t _size; bool _extern_base; off_t _local_va; off_t _local_ra; #ifndef __MIC__ off_t _peer_va; #endif off_t _peer_ra; }; }} //endns(nba::knapp) #endif //__NBA_KNAPP_RMA_HH__ // vim: ts=8 sts=4 sw=4 et
ANLAB-KAIST/NBA
include/nba/engines/knapp/rma.hh
C++
mit
1,094
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.14"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>OxyEngine: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(initResizable); /* @license-end */</script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="logo.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">OxyEngine &#160;<span id="projectnumber">0.2.0</span> </div> <div id="projectbrief">2D full-featured open-source crossplatform game engine</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.14 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(function(){initNavTree('class_oxy_engine_1_1_input_1_1_input_manager.html','');}); /* @license-end */ </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">OxyEngine.Input.InputManager Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html">OxyEngine.Input.InputManager</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#ab1560bdeee5af0ffdeb651d3f59b55aa">GetCursorPosition</a>()</td><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html">OxyEngine.Input.InputManager</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#a0460ae9c31ac412fec6db59b1dc8f500">GetGamePadStick</a>(int gamePad, string stick)</td><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html">OxyEngine.Input.InputManager</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#ac49207da22a7ddadcb4e7975ceb88026">GetGamePadTrigger</a>(int gamePad, string trigger)</td><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html">OxyEngine.Input.InputManager</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#a8835cf218ca877181ce13aa86231cd71">GetMouseWheel</a>()</td><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html">OxyEngine.Input.InputManager</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#aa7dcad85c2dbd97392fea51c7bec7429">IsGamePadButtonPressed</a>(int gamePad, string button)</td><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html">OxyEngine.Input.InputManager</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#a74631e64ca76355a2ea81bf27f8c03ce">IsKeyPressed</a>(string key)</td><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html">OxyEngine.Input.InputManager</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#a4a41b342643088a8be3b100129681f0a">IsMousePressed</a>(string button)</td><td class="entry"><a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html">OxyEngine.Input.InputManager</a></td><td class="entry"></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.14 </li> </ul> </div> </body> </html>
OxyTeam/OxyEngine
docs/html/class_oxy_engine_1_1_input_1_1_input_manager-members.html
HTML
mit
6,688
'use strict'; import imageSearchPage from '../../pageobjects/image-search.page'; module.exports = function() { this.Given(/^I am on the google image search page$/, () => { imageSearchPage.open(); }); // Enter term in search: google.js this.Given(/^I press the image search button$/, () => { imageSearchPage.pressSearchButton(); }); this.Then(/^I see the results of my image search$/, () => { expect(imageSearchPage.searchResults).toBeTruthy(); }); };
rp4rk/ChimpTravisCI
features/step_definitions/search_images.js
JavaScript
mit
507
/** * The MIT License (MIT) * * Copyright (c) 2022 Losant IoT, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ var uriTemplate = require('uri-template'); module.exports = function (options, client) { var internals = {}; /** * Returns the API tokens for an instance * * Authentication: * The client must be configured with a valid api * access token to call this action. The token * must include at least one of the following scopes: * all.Instance, all.Instance.read, all.User, all.User.read, instanceApiTokens.*, or instanceApiTokens.get. * * Parameters: * {string} instanceId - ID associated with the instance * {string} sortField - Field to sort the results by. Accepted values are: name, status, id, creationDate, lastUpdated, expirationDate * {string} sortDirection - Direction to sort the results by. Accepted values are: asc, desc * {string} page - Which page of results to return * {string} perPage - How many items to return per page * {string} filterField - Field to filter the results by. Blank or not provided means no filtering. Accepted values are: name, status * {string} filter - Filter to apply against the filtered field. Supports globbing. Blank or not provided means no filtering. * {string} losantdomain - Domain scope of request (rarely needed) * {boolean} _actions - Return resource actions in response * {boolean} _links - Return resource link in response * {boolean} _embedded - Return embedded resources in response * * Responses: * 200 - Collection of API tokens (https://api.losant.com/#/definitions/apiToken) * * Errors: * 400 - Error if malformed request (https://api.losant.com/#/definitions/error) */ internals.get = function (params, opts, cb) { if ('function' === typeof params) { cb = params; params = {}; opts = {}; } else if ('function' === typeof opts) { cb = opts; opts = {}; } else if (!opts) { opts = {}; } params = params || {}; var tpl = uriTemplate.parse('/instances/{instanceId}/tokens'); var pathParams = {}; var req = { method: 'GET', headers: {}, params: { _actions: false, _links: true, _embedded: true } }; if ('undefined' !== typeof params.instanceId) { pathParams.instanceId = params.instanceId; } if ('undefined' !== typeof params.sortField) { req.params.sortField = params.sortField; } if ('undefined' !== typeof params.sortDirection) { req.params.sortDirection = params.sortDirection; } if ('undefined' !== typeof params.page) { req.params.page = params.page; } if ('undefined' !== typeof params.perPage) { req.params.perPage = params.perPage; } if ('undefined' !== typeof params.filterField) { req.params.filterField = params.filterField; } if ('undefined' !== typeof params.filter) { req.params.filter = params.filter; } if ('undefined' !== typeof params.losantdomain) { req.headers.losantdomain = params.losantdomain; } if ('undefined' !== typeof params._actions) { req.params._actions = params._actions; } if ('undefined' !== typeof params._links) { req.params._links = params._links; } if ('undefined' !== typeof params._embedded) { req.params._embedded = params._embedded; } req.url = tpl.expand(pathParams); return client.request(req, opts, cb); }; /** * Create a new API token for an instance * * Authentication: * The client must be configured with a valid api * access token to call this action. The token * must include at least one of the following scopes: * all.Instance, all.User, instanceApiTokens.*, or instanceApiTokens.post. * * Parameters: * {string} instanceId - ID associated with the instance * {hash} apiToken - API token information (https://api.losant.com/#/definitions/apiTokenPost) * {string} losantdomain - Domain scope of request (rarely needed) * {boolean} _actions - Return resource actions in response * {boolean} _links - Return resource link in response * {boolean} _embedded - Return embedded resources in response * * Responses: * 201 - The successfully created API token (https://api.losant.com/#/definitions/apiToken) * * Errors: * 400 - Error if malformed request (https://api.losant.com/#/definitions/error) */ internals.post = function (params, opts, cb) { if ('function' === typeof params) { cb = params; params = {}; opts = {}; } else if ('function' === typeof opts) { cb = opts; opts = {}; } else if (!opts) { opts = {}; } params = params || {}; var tpl = uriTemplate.parse('/instances/{instanceId}/tokens'); var pathParams = {}; var req = { method: 'POST', data: {}, headers: {}, params: { _actions: false, _links: true, _embedded: true } }; if ('undefined' !== typeof params.instanceId) { pathParams.instanceId = params.instanceId; } if ('undefined' !== typeof params.apiToken) { req.data = params.apiToken; } if ('undefined' !== typeof params.losantdomain) { req.headers.losantdomain = params.losantdomain; } if ('undefined' !== typeof params._actions) { req.params._actions = params._actions; } if ('undefined' !== typeof params._links) { req.params._links = params._links; } if ('undefined' !== typeof params._embedded) { req.params._embedded = params._embedded; } req.url = tpl.expand(pathParams); return client.request(req, opts, cb); }; return internals; };
Losant/losant-rest-js
lib/api/instanceApiTokens.js
JavaScript
mit
6,563
/*! * bd808's github css hacks * © 2015 Bryan Davis and contributors * License: http://opensource.org/licenses/MIT */ /* wide wiki */ #wiki-rightbar { float: none; width: 100%; } .has-rightbar #wiki-body, .has-rightbar #wiki-footer { margin-right: 20px; }
bd808/userscripts
github.user.css
CSS
mit
268
import React from 'react' import { mount, shallow } from 'enzyme' import { Dummy } from './utils' import { withHandlers } from '..' describe('withHandlers', () => { it('passes immutable handlers', () => { const enhance = withHandlers({ handler: () => () => null, }) const EnhancedDummy = enhance(Dummy) expect(EnhancedDummy.displayName).toBe('withHandlers(Dummy)') const wrapper = shallow(<EnhancedDummy />) const handler = wrapper.prop('handler') wrapper.setProps({ foo: 'bar' }) expect(wrapper.prop('foo')).toBe('bar') expect(wrapper.prop('handler')).toBe(handler) }) it('caches handlers properly', () => { const handlerCreationSpy = jest.fn() const handlerCallSpy = jest.fn() const enhance = withHandlers({ handler: props => { handlerCreationSpy(props) return val => { handlerCallSpy(val) } }, }) const EnhancedDummy = enhance(Dummy) const wrapper = shallow(<EnhancedDummy foo="bar" />) const handler = wrapper.prop('handler') // Don't create handler until it is called. expect(handlerCreationSpy).toHaveBeenCalledTimes(0) expect(handlerCallSpy).toHaveBeenCalledTimes(0) handler(1) expect(handlerCreationSpy).toHaveBeenCalledTimes(1) expect(handlerCreationSpy).toHaveBeenCalledWith({ foo: 'bar' }) expect(handlerCallSpy).toHaveBeenCalledTimes(1) expect(handlerCallSpy).toHaveBeenCalledWith(1) // Props haven't changed; should use cached handler. handler(2) expect(handlerCreationSpy).toHaveBeenCalledTimes(1) expect(handlerCallSpy).toHaveBeenCalledTimes(2) expect(handlerCallSpy.mock.calls[1]).toEqual([2]) wrapper.setProps({ foo: 'baz' }) handler(3) // Props did change; handler should be recreated. expect(handlerCreationSpy).toHaveBeenCalledTimes(2) expect(handlerCreationSpy.mock.calls[1]).toEqual([{ foo: 'baz' }]) expect(handlerCallSpy).toHaveBeenCalledTimes(3) expect(handlerCallSpy.mock.calls[2]).toEqual([3]) }) it('throws if handler is not a higher-order function', () => { /* eslint-disable no-console */ const originalError = console.error console.error = jest.fn() const EnhancedDummy = withHandlers({ foo: () => {}, })(Dummy) const wrapper = shallow(<EnhancedDummy />) expect(() => wrapper.prop('foo').call()).toThrowError() expect(console.error).toBeCalledWith( // eslint-disable-line no-console 'withHandlers(): Expected a map of higher-order functions. ' + 'Refer to the docs for more info.', ) console.error = originalError /* eslint-enable no-console */ }) it('allows handers to be a factory', () => { const enhance = withHandlers(initialProps => { let cache return { handler: () => () => { if (cache) { return cache } cache = { ...initialProps } return cache }, } }) const componentHandlers = [] const componentHandlers2 = [] const Component = enhance(({ handler }) => { componentHandlers.push(handler()) return null }) const Component2 = enhance(({ handler }) => { componentHandlers2.push(handler()) return null }) const wrapper = mount(<Component hello="foo" />) wrapper.setProps({ hello: 'bar' }) expect(componentHandlers[0]).toBe(componentHandlers[1]) // check that cache is not shared mount(<Component2 hello="foo" />) expect(componentHandlers[0]).toEqual(componentHandlers2[0]) expect(componentHandlers[0]).not.toBe(componentHandlers2[0]) }) })
neoziro/recompact
src/__tests__/withHandlers.test.js
JavaScript
mit
3,651
package lists // This file is generated by methodGenerator. // DO NOT MOTIFY THIS FILE. import ( "net/url" "github.com/kawaken/go-rtm/methods" ) // GetList returns "rtm.lists.getList" method instance. func GetList() *methods.Method { name := "rtm.lists.getList" p := url.Values{} p.Add("method", name) return &methods.Method{Name: name, Params: p} }
kawaken/go-rtm
methods/lists/get_list.go
GO
mit
363
# - Find libarchive library and headers # The module defines the following variables: # # LibArchive_FOUND - true if libarchive was found # LibArchive_INCLUDE_DIRS - include search path # LibArchive_LIBRARIES - libraries to link # LibArchive_VERSION - libarchive 3-component version number #============================================================================= # Copyright 2010 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) find_path(LibArchive_INCLUDE_DIR NAMES archive.h PATHS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\GnuWin32\\LibArchive;InstallPath]/include" ) find_library(LibArchive_LIBRARY NAMES archive libarchive PATHS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\GnuWin32\\LibArchive;InstallPath]/lib" ) mark_as_advanced(LibArchive_INCLUDE_DIR LibArchive_LIBRARY) # Extract the version number from the header. if(LibArchive_INCLUDE_DIR AND EXISTS "${LibArchive_INCLUDE_DIR}/archive.h") # The version string appears in one of two known formats in the header: # #define ARCHIVE_LIBRARY_VERSION "libarchive 2.4.12" # #define ARCHIVE_VERSION_STRING "libarchive 2.8.4" # Match either format. set(_LibArchive_VERSION_REGEX "^#define[ \t]+ARCHIVE[_A-Z]+VERSION[_A-Z]*[ \t]+\"libarchive +([0-9]+)\\.([0-9]+)\\.([0-9]+)[^\"]*\".*$") file(STRINGS "${LibArchive_INCLUDE_DIR}/archive.h" _LibArchive_VERSION_STRING LIMIT_COUNT 1 REGEX "${_LibArchive_VERSION_REGEX}") if(_LibArchive_VERSION_STRING) string(REGEX REPLACE "${_LibArchive_VERSION_REGEX}" "\\1.\\2.\\3" LibArchive_VERSION "${_LibArchive_VERSION_STRING}") endif() unset(_LibArchive_VERSION_REGEX) unset(_LibArchive_VERSION_STRING) endif() # Handle the QUIETLY and REQUIRED arguments and set LIBARCHIVE_FOUND # to TRUE if all listed variables are TRUE. include("${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake") find_package_handle_standard_args(LibArchive DEFAULT_MSG LibArchive_LIBRARY LibArchive_INCLUDE_DIR ) set(LibArchive_FOUND ${LIBARCHIVE_FOUND}) unset(LIBARCHIVE_FOUND) if(LibArchive_FOUND) set(LibArchive_INCLUDE_DIRS ${LibArchive_INCLUDE_DIR}) set(LibArchive_LIBRARIES ${LibArchive_LIBRARY}) endif()
balaam/dinodeck
lib/physfs/cmake-2.8.3-win32-x86/share/cmake-2.8/Modules/FindLibArchive.cmake
CMake
mit
2,669
#include "../mk.h" static void mk_open_db_on_scandir(uv_fs_t *req) { if (req->result < 0) { fprintf(stderr, "error scanning dir: %s\n", uv_strerror((int)req->result)); return; } uv_dirent_t *dent = malloc(sizeof(dent)); mk_open_db_context *context = (mk_open_db_context*) req->data; mk_db *db = (mk_db*) malloc(sizeof(mk_db)); db->name = context->name; db->name_len = context->name_len; db->collections = malloc(sizeof(mk_collection *) * 16); db->number = 0; int i = 0; while (UV_EOF != uv_fs_scandir_next(req, dent)) { int length = strlen(dent->name); mk_collection *collection = (mk_collection*) malloc(sizeof(mk_collection)); collection->name = strndup(dent->name, length); collection->name_len = length; collection->path = malloc(sizeof(char) * 256); snprintf(collection->path, 256, "%s/%s/%s", MK_DATA_DIR, db->name, dent->name); collection->is_closed = 1; db->collections[i++] = collection; db->number++; } uv_fs_req_cleanup(context->scan_req); free(context->scan_req); free(dent); context->session->db = db; if (context->cb != NULL) { (context->cb)(context->session); } free(context); } static void mk_open_db_on_stat(uv_fs_t *req) { if (req->result < 0) { fprintf(stderr, "error stat dir: %s\n", uv_strerror((int)req->result)); return; } uv_stat_t *stat = (uv_stat_t *) req->ptr; mk_open_db_context *context = (mk_open_db_context*) req->data; if (stat == NULL) { fprintf(stderr, "Database '%s' does not exist\n", context->path); return; } uv_fs_req_cleanup(context->stat_req); free(context->stat_req); context->scan_req = malloc(sizeof(uv_fs_t)); context->scan_req->data = context; uv_fs_scandir(uv_default_loop(), context->scan_req, context->path, 0, mk_open_db_on_scandir); } int mk_open_db(mk_session *session, mk_ast_node *node, on_execute_succeed *cb) { mk_open_db_context *context = malloc(sizeof(mk_open_db_context)); context->path = malloc(sizeof(char) * 256); snprintf(context->path, 256, "%s/%s", MK_DATA_DIR, node->value); fprintf(stderr, "%d %s %s\n", node->type, context->path, node->value); context->session = session; context->cb = cb; context->stat_req = malloc(sizeof(uv_fs_t)); context->stat_req->data = context; context->name = node->value; context->name_len = node->len; uv_fs_stat(uv_default_loop(), context->stat_req, context->path, mk_open_db_on_stat); return SUCCESS; }
andresgutierrez/mazikeen
src/executor/open-db.c
C
mit
2,629
<?php namespace AppBundle\Entity; /** * BinCode */ class BinCode { /** * @var integer */ private $bin; /** * @var string */ private $bank; /** * @var string */ private $card; /** * @var string */ private $type; /** * @var string */ private $level; /** * @var string */ private $country; /** * @var string */ private $countrycode; /** * @var string */ private $website; /** * @var string */ private $phone; /** * @var boolean */ private $valid; /** * @var boolean */ private $ourstate; function getValid() { return $this->valid; } function getOurstate() { return $this->ourstate; } function setValid($valid) { if ($valid == "false"): $this->valid = 0; else: $this->valid = 1; endif; } function setOurstate($ourstate) { $this->ourstate = $ourstate; } /** * Set bin * * @param integer $bin * * @return BinCode */ public function setBin($bin) { $this->bin = $bin; return $this; } /** * Get bin * * @return integer */ public function getBin() { return $this->bin; } /** * Set bank * * @param string $bank * * @return BinCode */ public function setBank($bank) { $this->bank = $bank; return $this; } /** * Get bank * * @return string */ public function getBank() { return $this->bank; } /** * Set card * * @param string $card * * @return BinCode */ public function setCard($card) { $this->card = $card; return $this; } /** * Get card * * @return string */ public function getCard() { return $this->card; } /** * Set type * * @param string $type * * @return BinCode */ public function setType($type) { $this->type = $type; return $this; } /** * Get type * * @return string */ public function getType() { return $this->type; } /** * Set level * * @param string $level * * @return BinCode */ public function setLevel($level) { $this->level = $level; return $this; } /** * Get level * * @return string */ public function getLevel() { return $this->level; } /** * Set country * * @param string $country * * @return BinCode */ public function setCountry($country) { $this->country = $country; return $this; } /** * Get country * * @return string */ public function getCountry() { return $this->country; } /** * Set countrycode * * @param string $countrycode * * @return BinCode */ public function setCountrycode($countrycode) { $this->countrycode = $countrycode; return $this; } /** * Get countrycode * * @return string */ public function getCountrycode() { return $this->countrycode; } /** * Set website * * @param string $website * * @return BinCode */ public function setWebsite($website) { $this->website = $website; return $this; } /** * Get website * * @return string */ public function getWebsite() { return $this->website; } /** * Set phone * * @param string $phone * * @return BinCode */ public function setPhone($phone) { $this->phone = $phone; return $this; } /** * Get phone * * @return string */ public function getPhone() { return $this->phone; } }
luismiguens/parcelaja
src/AppBundle/Entity/BinCode.php
PHP
mit
4,108
var lexer = require('../../index').lex.lexer; var parser = require('../../index').parse.parser; var $ = require('../$'); var testParser = function(stream) { var result = parser.parseStream(stream); return result.body[0].expression; }; exports.empty = function(test) { var result = testParser(lexer.lex("({});")); test.equal(result.properties.length, 0); test.done(); }; exports.init_values = function(test) { var result = testParser(lexer.lex("({ 'a': 0 , 'b': 1, '9': 2});")); test.equal(result.properties.length, 3); test.equal(result.properties[0].type, 'ObjectValue'); $.string(test, result.properties[0].key, 'a'); $.number(test, result.properties[0].value, 0); test.equal(result.properties[1].type, 'ObjectValue'); $.string(test, result.properties[1].key, 'b'); $.number(test, result.properties[1].value, 1); test.equal(result.properties[2].type, 'ObjectValue'); $.string(test, result.properties[2].key, '9'); $.number(test, result.properties[2].value, 2); test.done(); }; exports.init_values = function(test) { var result = testParser(lexer.lex("({ catch: 0 , true: 1, null: 2});")); test.equal(result.properties.length, 3); test.equal(result.properties[0].type, 'ObjectValue'); $.id(test, result.properties[0].key, 'catch'); $.number(test, result.properties[0].value, 0); test.equal(result.properties[1].type, 'ObjectValue'); $.id(test, result.properties[1].key, 'true'); $.number(test, result.properties[1].value, 1); test.equal(result.properties[2].type, 'ObjectValue'); $.id(test, result.properties[2].key, 'null'); $.number(test, result.properties[2].value, 2); test.done(); };
mattbierner/khepri-parse
tests/parse/object_literal.js
JavaScript
mit
1,747
<?php namespace Notepads\Tests; use Notepads\Models\User; use Notepads\Models\UserMapper; use Notepads\Tests\PHPUnit\BaseTestClass; use \Mockery as m; class UserMapperTest extends BaseTestClass { private $database; private $mapper; public function setup() { $this->database = m::mock("\\PDO"); $this->mapper = new UserMapper($this->database); } public function testFindOneById() { $userId = 1; $arr = array( "id" => $userId, "username" => "testusername1", "password" => "testpassword1" ); $user = new User($arr); $stmtMock = m::mock("\\PDOStatement"); $where = "1 AND `id` = :id"; $query = "SELECT * FROM `users` WHERE $where"; $this->database->shouldReceive("prepare") ->with($query) ->andReturn($stmtMock); $stmtMock ->shouldReceive("bindParam") ->with(":id", $userId) ->shouldReceive("execute") ->andReturn(true) ->shouldReceive("fetchObject") ->with("Notepads\\Models\\User") ->andReturn($user); $this->assertEquals( $user, $this->mapper->findOne( new User(array( "id" => $userId )) ) ); } public function testFindOneByUsername() { $username = "testusername1"; $arr = array( "id" => 1, "username" => $username, "password" => "testpassword1" ); $user = new User($arr); $stmtMock = m::mock("\\PDOStatemetnt"); $where = "1 AND `username` = :username"; $query = "SELECT * FROM `users` WHERE $where"; $this->database->shouldReceive("prepare") ->with($query) ->andReturn($stmtMock); $stmtMock ->shouldReceive("bindParam") ->with(":username", $username) ->shouldReceive("execute") ->andReturn(true) ->shouldReceive("fetchObject") ->with("Notepads\\Models\\User") ->andReturn($user); $this->assertEquals( $user, $this->mapper->findOne( new User(array( "username" => $username )) ) ); } public function testFindOneByPassword() { $password = "testusername1"; $arr = array( "id" => 1, "username" => "testusername1", "password" => $password ); $user = new User($arr); $stmtMock = m::mock("\\PDOStatement"); $where = "1 AND `password` = :password"; $query = "SELECT * FROM `users` WHERE $where"; $this->database->shouldReceive("prepare") ->with($query) ->andReturn($stmtMock); $stmtMock ->shouldReceive("bindParam") ->with(":password", $password) ->shouldReceive("execute") ->andReturn(true) ->shouldReceive("fetchObject") ->with("Notepads\\Models\\User") ->andReturn($user); $this->assertEquals( $user, $this->mapper->findOne( new User(array( "password" => $password )) ) ); } public function testfindOneNotFound() { $user = new User(array("id" => 1)); $where = "1 AND `id` = :id"; $query = "SELECT * FROM `users` WHERE $where"; $stmtMock = m::mock("\\PDOStatement"); $this->database->shouldReceive("prepare") ->with($query) ->andReturn($stmtMock); $stmtMock ->shouldReceive("bindParam") ->with(":id", $user->id) ->shouldReceive("execute") ->andReturn(false); $this->assertFalse($this->mapper->findOne($user)); } public function testSaveNewUser() { $user = new User(array( "username" => "testusername1", "password" => "testpassword1" )); $stmtMock = m::mock("\\PDOStatement"); $this->database->shouldReceive("prepare") ->with( "INSERT INTO `users` (`username`, `password`) VALUES(:username, :password)" ) ->andReturn($stmtMock); $stmtMock ->shouldReceive("bindParam") ->with(":username", $user->username) ->shouldReceive("bindParam") ->with(":password", $user->password) ->shouldReceive("execute") ->andReturn(true); $this->assertTrue($this->mapper->save($user)); } public function testSaveUpdateUser() { $user = new User(array( "id" => 1, "name" => "testusername1", "text" => "testpassword1" )); $stmtMock = m::mock("\\PDOStatement"); $this->database->shouldReceive("prepare") ->with( "UPDATE `users` SET `username` = :username, `password` = :password WHERE `id` = :id" ) ->andReturn($stmtMock); $stmtMock ->shouldReceive("bindParam") ->with(":id", $user->id) ->shouldReceive("bindParam") ->with(":username", $user->username) ->shouldReceive("bindParam") ->with(":password", $user->password) ->shouldReceive("execute") ->andReturn(true); $this->assertTrue($this->mapper->save($user)); } public function testDeleteUser() { $user = new User(array("id" => 1)); $stmtMock = m::mock("\\PDOStatement"); $this->database->shouldReceive("prepare") ->with("DELETE FROM `users` WHERE `id` = :id") ->andReturn($stmtMock); $stmtMock ->shouldReceive("bindParam") ->with(":id", $user->id) ->shouldReceive("execute") ->andReturn(true); $this->assertTrue($this->mapper->delete($user)); } }
iliyan-trifonov/mvc-behat-phpunit
tests/UserMapperTest.php
PHP
mit
6,259
require 'spec_helper' module Xcodeproj class Project module Object describe PBXNativeTarget do before :each do @project = double('Project').as_null_object end it 'should be library target type when framework' do target = PBXNativeTarget.new(@project, nil) target.product_type = Constants::PRODUCT_TYPE_UTI[:framework] expect(target.library_target_type?).to eq(true) end it 'should be library target type when static library' do target = PBXNativeTarget.new(@project, nil) target.product_type = Constants::PRODUCT_TYPE_UTI[:static_library] expect(target.library_target_type?).to eq(true) end it 'should be library target type when dynamic library' do target = PBXNativeTarget.new(@project, nil) target.product_type = Constants::PRODUCT_TYPE_UTI[:dynamic_library] expect(target.library_target_type?).to eq(true) end end end end end
jcampbell05/xcake
spec/xcodeproj_ext/PBXNativeTarget_spec.rb
Ruby
mit
1,022
using System; using System.Globalization; using System.Linq; using System.Web.Mvc; using Ninject; using Niqiu.Core.Domain.Config; using Niqiu.Core.Domain.User; using Niqiu.Core.Helpers; using Niqiu.Core.Services; using Portal.MVC.ViewModel; namespace Portal.MVC.Controllers { public class AccountController : BaseController { private readonly IAccountService _accountService; private readonly IUserService _service; private readonly IWorkContext _workContext; public AccountController(IUserService repository, IAccountService accountService,IWorkContext workContext) { _service = repository; _workContext = workContext; _accountService = accountService; } #region 修改密码 public ActionResult ChangePassword() { return View(); } [HttpPost] public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { var user = _workContext.CurrentUser; if (_accountService.ChangePassword(user.Id, model.Password)) { Success(); } else { Error(); } return View(); } Error(); return View(); } public JsonResult CheckPassword(string password) { var user = _workContext.CurrentUser; if (user != null) { var res= _accountService.ValidateUser(user.Username, password); return Json(res == UserLoginResults.Successful,JsonRequestBehavior.AllowGet); } return Json(false, JsonRequestBehavior.AllowGet); } #endregion #region 登陆退出 [HttpGet] public ActionResult Logon(string returnUrl = "") { var model = new LogOnModel(); ViewBag.ReturnUrl = returnUrl; //DataBaseInit(); //if (!_service.GetAllUsers().Any()) //{ // var user = new User // { // UserGuid = Guid.NewGuid(), // Username = "stoneniqiu", // RealName = "stoneniqiu", // Mobile = "15250198031", // Active = true, // //加密存储 // Password = Encrypt.GetMd5Code("admin"), // }; // var role = _service.GetUserRoleBySystemName(SystemUserRoleNames.Administrators); // user.UserRoles.Add(role); // //默认增加注册角色 // // 先插入 // _service.InsertUser(user); //} return View(model); } [HttpPost] public ActionResult Logon(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (model.UserName != null) { model.UserName = model.UserName.Trim(); } UserLoginResults loginResult = _accountService.ValidateUser(model.UserName, model.Password); switch (loginResult) { case UserLoginResults.Successful: { User user = _service.GetUserByUsername(model.UserName); //sign in new customer AuthenticationService.SignIn(user, model.RememberMe); if (String.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl)) return RedirectToAction("Index", "Home"); return Redirect(returnUrl); } case UserLoginResults.UserNotExist: ModelState.AddModelError("", "用户不存在"); break; case UserLoginResults.Deleted: ModelState.AddModelError("", "用户已删除"); break; case UserLoginResults.NotActive: ModelState.AddModelError("", "用户没有激活"); break; case UserLoginResults.NotRegistered: ModelState.AddModelError("", "用户未注册"); break; case UserLoginResults.WrongPassword: default: ModelState.AddModelError("", "密码错误"); break; } } return View(model); } [AllowAnonymous] public ActionResult Register() { var model = new RegisterModel(); return View(model); } /// <summary> /// 注册【加密类型】 /// </summary> /// <param name="model"></param> /// <param name="returnUrl"></param> /// <returns></returns> [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Register(RegisterModel model, string returnUrl) { //如果当前用户再注册别的用户,就让他先退出,加入一个Guest角色用户进来准备。 var user = _service.InsertGuestUser(); if (ModelState.IsValid) { if (model.UserName != null) { model.UserName = model.UserName.Trim(); } var isApprove = true; var registerRequest = new UserRegistrationRequest(user, model.Email, model.Mobile, model.UserName, model.Password, PasswordFormat.Encrypted, isApprove); var registrationResult = _accountService.RegisterUser(registerRequest); if (registrationResult.Success) { if (isApprove) { AuthenticationService.SignIn(user, true); } if (String.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl)) return RedirectToAction("Index", "Home"); return Redirect(returnUrl); } foreach (var error in registrationResult.Errors) { ModelState.AddModelError("", error); } } return View(model); } /// <summary> /// 退出函数 还需要处理,退出时统计退出时间,然后关闭网页。 /// </summary> /// <returns></returns> public ActionResult LogOff() { AuthenticationService.SignOut(); return RedirectToAction("Logon", "Account"); } public ActionResult Unauthorized(string name, string returnUrl) { if (!Request.IsAuthenticated) { return RedirectToAction("Logon", new { returnUrl }); } ViewBag.P = name; return View(); } public ActionResult ValidComplete(string name, string active = "") { if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(active)) { TempData["error"] = "链接有误"; return View(); } string username = Encrypt.DecryptString(name); User user = _service.GetUserByUsername(username); //已经激活 if (user.Active) { return View(); } try { ViewBag.Email = user.Email; string activetime = Encrypt.DecryptString(active); var time = Convert.ToDateTime(activetime); if (DateTime.Now > time.AddHours(1)) { TempData["error"] = "链接已经失效"; } else { user.Active = true; _service.UpdateUser(user); } } catch { TempData["error"] = "验证失败"; } return View(); } public ActionResult ValidMail(string name) { User user = _service.GetUserByUsername(name); if (user == null) return View("NoData"); if (!user.Active) { ViewBag.Email = user.Email; //发送邮件 string relative = Url.Action("ValidComplete", "Account", new { name = Encrypt.EncryptString(user.Username), active = Encrypt.EncryptString(DateTime.Now.ToString(CultureInfo.InvariantCulture)) }); var timenow = DateTime.Now; if (Request.Url != null) { string url = Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + relative; string alink = string.Format("<a href='{0}'>{1}</a>", url, "点击这里确认您的账号"); string content = string.Format("亲爱的用户 {0}: 您好,您已成功注册{4}在线账号,您可以下载{4}相关资料并获得相关资讯和技术支持!<br /> <br />" + "{1}" + " 如果上面的链接点击无效,请将下面的地址复制到浏览器中<br />" + "{2}<br /><br />注意:请您在收到邮件1个小时内({3}前)使用,否则该链接将会失效。<br /><br />", user.Username, alink, url, timenow.AddHours(1), PortalConfig.WebSiteName); _workContext.AsyncSendMail(user.Email, content, "邮箱激活"); } //获得服务器地址 是outlook 就打开邮箱 var str = user.Email.Split('@')[1]; ViewBag.Server = "http://mail." + str; } else { return RedirectToAction("ValidComplete", new { name = Encrypt.EncryptString(user.Username), active = "valided" }); //返回到已经激活页面 } // _portalContext.AsyncSendMail(user.Email, "注册成功!谢谢你的支持", "注册成功"); //用户邮箱 //用户邮箱网站 比如163.com return View(); } #endregion [Inject] public IAuthenticationService AuthenticationService { get; set; } } }
stoneniqiu/Portal.MVC
Portal.MVC/Controllers/AccountController.cs
C#
mit
10,846
<?php Ini_Set( 'display_errors', true ); include '../../init.php'; include 'functions.php'; $plexSessionXML = simplexml_load_file('http://' . $plex_server_ip . ':' . $plex_port . '/status/sessions/?X-Plex-Token=' . $plexToken); $plexcheckfile1 = ROOT_DIR . '/assets/caches/plexcheckfile1.txt'; $plexcheckfile2 = ROOT_DIR . '/assets/caches/plexcheckfile2.txt'; $plexcheckfile1_md5 = md5_file($plexcheckfile1); $plexcheckfile2_md5 = md5_file($plexcheckfile2); $viewers = 0; // See if Plex Media Server is online and how many people are watching. if (!$plexSessionXML): // If Plex Media Server is offline. $plexStatus = 'offline'; else: // If Plex Media Server is online. $plexStatus = 'online'; // Count how many people are watching. if (count($plexSessionXML->Video) > 0) { $viewers = count($plexSessionXML->Video); } endif; // Build an array to hold the values $array = [ 'status' => $plexStatus, 'viewers' => $viewers, ]; // Write the data out to the first Plex check file file_put_contents($plexcheckfile1, $array, LOCK_EX); // Check to see if it's the same as the second Plex check file if ($plexcheckfile1_md5 === $plexcheckfile2_md5) { // if they are the same do nothing } else { // If they are different, update plexcheckfile2 file_put_contents($plexcheckfile2, $array, LOCK_EX); } ?>
Cozza38/PlexMonitor
assets/php/plex_check_ajax.php
PHP
mit
1,344
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package add.records.gui.controller; import data.UserBO; import java.io.IOException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.text.Text; import javafx.stage.Stage; /** * FXML Controller class * * @author Aamir */ public class LoginSceneController implements Initializable { @FXML private TextField userInput; @FXML private PasswordField passInput; @FXML private Button loginButton; @FXML private Text messageText; final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); /** * * @param bytes * @return */ private static String createHexString(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } /** * Initializes the controller class. * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } /** * * @param event */ @FXML private void onLoginButtonPressed(ActionEvent event) throws IOException, InterruptedException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } byte[] thedigest = md.digest(passInput.getText().getBytes()); String passwordHash = createHexString(thedigest); System.out.println(passwordHash); UserBO userBO = new UserBO(); if (userBO.login(userInput.getText(), passwordHash)) { Stage window = (Stage) userInput.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/AddRecordScene.fxml")); Scene mainScene = new Scene((Parent) loader.load(), 854, 480); AddRecordSceneController controller = loader.<AddRecordSceneController>getController(); window.setScene(mainScene); } else { passInput.setText(""); messageText.setVisible(true); } } }
dmagadi/demo
ContactRecordManagment/src/main/java/add/records/gui/controller/LoginSceneController.java
Java
mit
2,822
var locale = require('relative-time-format/locale/sr') module.exports = { locale: locale.locale, // Standard styles. long: locale.long, short: locale.short, narrow: locale.narrow, // Quantifier. quantify: locale.quantify }
halt-hammerzeit/javascript-time-ago
locale/sr/index.js
JavaScript
mit
230
<?php declare(strict_types=1); /** * Copyright (c) 2013-2019 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ $filename = __DIR__ . \preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']); if (PHP_SAPI === 'cli-server' && \is_file($filename)) { return false; } require_once __DIR__ . '/index.php';
GrUSP/opencfp
web/index_dev.php
PHP
mit
447
using Neutronium.MVVMComponents; using Neutronium.MVVMComponents.Relay; using System; using System.Windows; using System.ComponentModel; namespace Neutronium.WPF.ViewModel { public class WindowViewModel : IWindowViewModel { public ISimpleCommand Close { get; } public ISimpleCommand Minimize { get; } public ISimpleCommand Maximize { get; } public ISimpleCommand Normalize { get; } public event PropertyChangedEventHandler PropertyChanged; public WindowState State { get { return _Window.WindowState; } set { _Window.WindowState = value; } } private readonly Window _Window; public WindowViewModel(Window window) { _Window = window; Close = new RelaySimpleCommand(() => _Window.Close()); Minimize = new RelaySimpleCommand(() => State = WindowState.Minimized); Maximize = new RelaySimpleCommand(() => State = WindowState.Maximized); Normalize = new RelaySimpleCommand(() => State = (State == WindowState.Maximized) ? WindowState.Normal : WindowState.Maximized); _Window.StateChanged += StateChanged; } private void StateChanged(object sender, EventArgs e) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(State))); } public void Dispose() { _Window.StateChanged -= StateChanged; } } }
sjoerd222888/MVVM.CEF.Glue
Neutronium.WPF/ViewModel/WindowViewModel.cs
C#
mit
1,489
var baseIteratee = require('./_baseIteratee'), baseSortedIndexBy = require('./_baseSortedIndexBy'); /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted into `array`. * @specs * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, baseIteratee(iteratee), true); } module.exports = sortedLastIndexBy;
mdchristopher/Protractor
node_modules/lodash/sortedLastIndexBy.js
JavaScript
mit
958
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double TKSubmitTransitionSwift3VersionNumber; FOUNDATION_EXPORT const unsigned char TKSubmitTransitionSwift3VersionString[];
usharif/GrapeVyne
Pods/Target Support Files/TKSubmitTransitionSwift3/TKSubmitTransitionSwift3-umbrella.h
C
mit
340
--- layout: docs authors: - blairanderson date: 2014-08-12 22:22:22 title: .keydown() in Javascript - without jQuery description: Bind an event handler to the “keydown” JavaScript event, or trigger that event on an element. method: keydown href: "docs/keydown.html" status: "inactive" --- #### Sorry, we do not have code examples for implementing [keydown](http://api.jquery.com/keydown/) in vanilla javascript. It would be great if you submitted code on [github](https://github.com/blairanderson/without-jquery/blob/master/docs/keydown.md) ### Example: ```javascript //jQuery var i = keydown(taco); //Javascript var i = document[somethingOtherThankeydown](taco); ``` **REASONS:** > Faster, and creates an event upon xyz *example is computer generated, obviously not real.*
blairanderson/without-jquery
docs/keydown.md
Markdown
mit
796
ThinMint.Mixin.Paginate = function() { var _super = {}; _super.init = ThinMint.Util.callback( this.init ); _super.getPage = ThinMint.Util.callback( this.getPage ); _super.setPage = ThinMint.Util.callback( this.setPage ); _super.getPages = ThinMint.Util.callback( this.getPages ); _super.setPages = ThinMint.Util.callback( this.setPages ); _super.pageNext = ThinMint.Util.callback( this.pageNext ); _super.pagePrevious = ThinMint.Util.callback( this.pagePrevious ); _super.pageTo = ThinMint.Util.callback( this.pageTo ); _super.onPage = ThinMint.Util.callback( this.onPage ); // The first page, cannot paginate before this page. this.pageFirst = 1; // The current page. this.page = 1; // How many pages are available. this.pages = 1; this.getPage = function() { return this.page; }; this.setPage = function(page) { this.page = Number(page); return this; }; this.getPages = function() { return this.pages; }; this.setPages = function(pages) { this.pages = Number(pages); return this; }; this.pageNext = function() { if(this.page >= this.pages) { this.console.warn('ThinMint.Mixin.Paginate', 'Already at the max page.'); return; } ++this.page; return this.onPage(); }; this.pagePrevious = function() { if(this.page <= this.pageFirst) { this.console.warn('ThinMint.Mixin.Paginate', 'Already at the first page.'); return; } --this.page; return this.onPage(); }; this.pageTo = function(page) { page = parseInt(page); if(page >= this.pages || page <= this.pageFirst) { this.console.warn('ThinMint.Mixin.Paginate', 'Cannot go outside of the allowed pages.'); return; } this.page = page; return this.onPage(); }; this.onPage = function() { // Each panel will imlement onPage, this is how it // will handle a page change. _super.onPage.apply(this, arguments); }; return this; };
cloudily/thinmint
src/mixin/paginate.js
JavaScript
mit
1,979
const expect = require('chai').expect; const PragmaThanksSpreadsheet = require('../src/PragmaThanksSpreadsheet'); describe('PragmaThanksSpreadsheet', () => { describe('#isEmpty', () => { it('returns true when spreadsheet is empty', () => { const spreadsheetContent = []; const sheet = new PragmaThanksSpreadsheet(spreadsheetContent); expect(sheet.isEmpty()).to.eql(true); }); it('returns true when spreadsheet is undefined', () => { const sheet = new PragmaThanksSpreadsheet(undefined); expect(sheet.isEmpty()).to.eql(true); }); it('returns false when spreadsheet is not empty', () => { const spreadsheetContent = [[1], [2]]; const sheet = new PragmaThanksSpreadsheet(spreadsheetContent); expect(sheet.isEmpty()).to.eql(false); }); }); describe('#getPointsToUse', () => { const spreadsheetContent = [ [], ['foo', 'bar', 'biz'], [], [20, 42, 32], [0, 0], ]; const sheet = new PragmaThanksSpreadsheet(spreadsheetContent); it('returns user balance when it has at least one pragma points', () => { expect(sheet.getPointsToUse('foo')).to.eql(20); }); it('returns the balance for different users', () => { expect(sheet.getPointsToUse('bar')).to.eql(42); }); it('returns zero balance when user is not found', () => { expect(sheet.getPointsToUse('unknown')).to.eql(0); }); }); describe('#getPointsToGive', () => { const spreadsheetContent = [ [], ['foo', 'bar'], [], [0, 0], [30, 44], ]; const sheet = new PragmaThanksSpreadsheet(spreadsheetContent); it('returns the points to give when user has at least one pragma points to give', () => { expect(sheet.getPointsToGive('foo')).to.eql(30); }); it('returns the points to give for different users', () => { expect(sheet.getPointsToGive('bar')).to.eql(44); }); it('returns zero points to give when user is not found', () => { expect(sheet.getPointsToGive('unknown')).to.eql(0); }); }); });
Pragmateam/pragmathanks-get-balance
test/PragmaThanksSpreadsheetTest.js
JavaScript
mit
2,108
tws-to-twee-converter ===================== Converts Twine .tws files to .twee files The python script takes a file as an argument, and prints the resulting Twee file to stdout. To use, do something like: ```` python twsimporter.py twinefile.tws > newtweefile.tw ```` Also accepts a `-twee2` option, which will include the position of each passage in `twee2` output file format: ```` python twsimporter.py twinefile.tws -twee2 > newtweefile.tw2 ````
v21/tws-to-twee-converter
README.md
Markdown
mit
456
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System.Collections.Generic; public class SpAtlas : ScriptableObject { public static int MAX_ATLAS_SIZE = 4096; public bool Dirty = true; public bool AutoUpdate; public bool ForceSquare; public bool DefaultTrim = true; public int DefaultPadSize = 1; public string Identifier; public int Width; public int Height; public SpPadStyle DefaultPadStyle = SpPadStyle.Transparent; public Texture2D Texture; public List<SpSource> Sources = new List<SpSource>(); public List<Sprite> Sprites = new List<Sprite>(); #if UNITY_EDITOR public void Update() { var newWidth = Width; var newHeight = Height; var newRects = default(List<SpRect>); // Remove deleted textures Sources.RemoveAll(s => s.Flag == SpFlag.MarkedForDestruction); EditorUtility.DisplayProgressBar("Updating " + name, "Packing...", 0.25f); // Try to pack if (SpPacker.AutoPack(Sources, ForceSquare, ref newWidth, ref newHeight, ref newRects) == true) { EditorUtility.DisplayProgressBar("Updating " + name, "Pasting...", 0.5f); var pixels = new SpPixels(newWidth, newHeight); var metaDatas = new SpriteMetaData[newRects.Count]; for (var i = newRects.Count - 1; i >= 0; i--) { var rect = newRects[i]; var metaData = default(SpriteMetaData); rect.PasteInto(pixels); metaData.name = rect.Name; metaData.rect = rect.Rect; metaData.pivot = rect.Pivot; metaData.border = rect.Border; metaData.alignment = (int)SpriteAlignment.Custom; metaDatas[i] = metaData; } EditorUtility.SetDirty(this); EditorUtility.DisplayProgressBar("Updating " + name, "Reimporting...", 0.75f); UpdateTextureAsset(metaDatas, pixels.Apply()); } else { Debug.LogError("Failed to pack atlas, because the source textures are too large!"); } EditorUtility.ClearProgressBar(); } public void TryAddSource(string newPath) { if (string.IsNullOrEmpty(newPath) == false) { if (System.IO.Directory.Exists(newPath) == true) { var directories = System.IO.Directory.GetDirectories(newPath); var files = System.IO.Directory.GetFiles(newPath); for (var i = 0; i < directories.Length; i++) { TryAddSource(directories[i]); } for (var i = 0; i < files.Length; i++) { TryAddSource(files[i]); } } else { var newTexture2D = AssetDatabase.LoadMainAssetAtPath(newPath) as Texture2D; if (newTexture2D != null) { var newIdentifier = AssetDatabase.AssetPathToGUID(newPath); if (string.IsNullOrEmpty(newIdentifier) == false && newIdentifier != Identifier) { if (Sources.Find(s => s.Identifier == newIdentifier) == null) { AddSource(newIdentifier); } } } } } } private void AddSource(string newIdentifier) { var newSource = new SpSource(); newSource.Identifier = newIdentifier; newSource.Trim = DefaultTrim; newSource.PadSize = DefaultPadSize; newSource.PadStyle = DefaultPadStyle; Sources.Add(newSource); } private void UpdateTextureAsset(SpriteMetaData[] metaDatas, Texture2D tempTexture) { var path = default(string); var importer = default(TextureImporter); // Try and find the path of an existing if (string.IsNullOrEmpty(Identifier) == false) { path = AssetDatabase.GUIDToAssetPath(Identifier); } // Create asset texture for the first time? if (string.IsNullOrEmpty(path) == true) { path = AssetDatabase.GetAssetPath(this); path = path.Substring(0, path.Length - ".asset".Length); path = AssetDatabase.GenerateUniqueAssetPath(path + ".png"); importer = SpHelper.SaveTextureAsset(tempTexture, path, false); importer.maxTextureSize = SpAtlas.MAX_ATLAS_SIZE; } // Update existing asset texture? else { importer = SpHelper.SaveTextureAsset(tempTexture, path, true); } // Update the atlas settings importer.textureType = TextureImporterType.Sprite; importer.spriteImportMode = SpriteImportMode.Multiple; importer.spritesheet = metaDatas; // Apply new settings SpHelper.ReimportAsset(path); // Update settings Width = tempTexture.width; Height = tempTexture.height; Texture = AssetDatabase.LoadMainAssetAtPath(path) as Texture2D; Identifier = AssetDatabase.AssetPathToGUID(path); // Find all packed sprites Sprites.Clear(); foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path)) { var sprite = asset as Sprite; if (sprite != null) { Sprites.Add(sprite); } } // Destroy temp texture DestroyImmediate(tempTexture); // Unmark dirty Dirty = false; Sources.ForEach(s => { s.Flag = SpFlag.None; s.Dirty = false; }); } #endif }
AlexeyJKoshkin/Dimon_Diplom
Assets/3d/SpritePacker/Scripts/SpAtlas.cs
C#
mit
5,798
module Rubernate class ClassParser attr_accessor :clazz,:bytecode,:proxy_class def initialize(clazz,bytecode) self.clazz = clazz self.bytecode = bytecode self.proxy_class = bytecode.create_class(name) initialize_simples end #TODO need to correct this behaivor def initialize_simples clazz.fields.each do |field| proxy_field = proxy_class.add_simple(field[:type],field[:name].to_s) field[:args].each do |f1| if f1.length > 0 build_id_for proxy_field if f1[0][:id] end end end end def build_id_for(field) self.proxy_class.add_annotation field,"javax/persistence/Id" end def name self.clazz.name end def to_class self.proxy_class.to_class end end end
netmask/rubernate
lib/rubernate/class_parser.rb
Ruby
mit
868
<?php include_once("engine/rp.start.php"); if ($_GET["rpAction"]=="rpRemoveMessage" && $_GET["id"]>0 && $_SESSION["clientID"]) { // hide message $message_result = $rpConnection->query("SELECT id FROM ".$rpSettings->getValue("messagesTable")." WHERE id='".rpSanitize(intval($_GET["id"]))."' && (added_clientid='".rpSanitize(intval($_SESSION["clientID"]))."' OR to_clientid LIKE '%[".rpSanitize(intval($_SESSION["clientID"]))."]%') LIMIT 1"); if (mysql_num_rows($message_result)>0) { if ($rpConnection->query("UPDATE ".$rpSettings->getValue("messagesTable")." SET hide_clientid=concat('[".rpSanitize(intval($_SESSION["clientID"]))."]',hide_clientid) WHERE id='".rpSanitize(intval($_GET["id"]))."' LIMIT 1")) { echo "SUCCESS"; } else {echo "Virhe viestin poistamisessa.";} } else {echo "Viestiä ei löytynyt.";} } if ($_POST["rpAction"]=="rpGetNewMessages" && $_SESSION["clientID"]) { echo rpGetNumOfMessages($_SESSION["clientID"], 0, true); } if ($_GET["rpAction"]=="rpSearchMessages" && $_GET["rpSearchString"]!="" && $_SESSION["clientID"]) { $_GET["rpSearchString"] = substr($_GET["rpSearchString"], 0, 100); rpGetMessages("<div class=\"messageDiv\" id=\"message_[rp(id)]\"><h2><a onmouseover=\"showInfo('Näytä viesti');\" onmouseout=\"hideInfo();\" href=\"javascript:toggleMessage([rp(id)]);\">[rp(title)]</a><a href=\"javascript:removeMessage([rp(id)]);\" class=\"smallFormButton right last\">Poista</a><a href=\"javascript:changeTab('newmsg', [rp(id)]);\" class='smallFormButton right'>Vastaa</a></h2><div id=\"fullMessageDiv_[rp(id)]\"></div>Lähettäjä: [rp(/from)]<a onmouseover=\"showInfo('Näytä käyttäjän profiili');\" onmouseout=\"hideInfo();\" href=\"javascript:showProfile([rp(from_id)]);\">[rp(from_name)]</a>[rp(from/)] ([rp(added_datetime)])<br />Vastaanottajat: [rp(/to)][rp(to)][rp(to/)]</div>", 0, 0, "by added_datetime DESC", "Hakusanalla ei löytynyt viestejä.", $_GET["rpSearchString"]); } if ($_GET["rpAction"]=="rpGetMessage" && $_GET["id"]>0 && $_SESSION["clientID"]) { // get message $message_result = $rpConnection->query("SELECT message, files, seen_clientid, added_clientid, to_clientid FROM ".$rpSettings->getValue("messagesTable")." WHERE id='".rpSanitize(intval($_GET["id"]))."' && (to_clientid LIKE '%[".rpSanitize(intval($_SESSION["clientID"]))."]%' OR added_clientid='".rpSanitize(intval($_SESSION["clientID"]))."') LIMIT 1"); if (mysql_num_rows($message_result)>0) { echo rpUTF8Encode(mysql_result($message_result, 0, "message")); if ($_SESSION["clientID"] != mysql_result($message_result, 0, "added_clientid") && !strstr(mysql_result($message_result, 0, "seen_clientid"), "[".$_SESSION["clientID"]."]")) { $rpConnection->query("UPDATE ".$rpSettings->getValue("messagesTable")." SET seen_clientid=concat('[".rpSanitize(intval($_SESSION["clientID"]))."]',seen_clientid) WHERE id='".rpSanitize(intval($_GET["id"]))."' LIMIT 1"); } if (rpUTF8Encode(mysql_result($message_result, 0, "files"))!="") { echo "<div class=\"clear height10\"></div>"; $files_array = explode("|end|", rpUTF8Encode(mysql_result($message_result, 0, "files"))); foreach ($files_array as $file) { if ($file!="") { $file_array = explode("|=|", $file); echo "Liitetiedosto: <a href=\"_getfile.php?messageid=".intval($_GET["id"])."&checksum=".md5($file)."\" target=\"_blank\">".$file_array[1]."</a><br />"; } } } echo "<div class=\"clear height10\"></div>"; } else {echo "Viestiä ei löytynyt.";} } include_once("engine/rp.end.php"); ?>
Lounaispaikka/Ravinneporssi
html/_message.php
PHP
mit
3,630
using Microsoft.AspNetCore.Mvc; using PersonalWebApp.Models.ViewModels; using PersonalWebApp.Services; namespace PersonalWebApp.Controllers { public class SkillsController : BaseController { private readonly SkillService _skillService; public SkillsController(SkillService skillService) { _skillService = skillService; } public IActionResult Index() { ViewData["Title"] = "My skills"; var viewModel = new SkillsViewModel { Skills = _skillService.GetAll(), Tags = _skillService.GetAllSkillTags() }; return View(viewModel); } } }
OlsonDev/PersonalWebApp
Controllers/SkillsController.cs
C#
mit
586
#include <stdlib.h> #include <string.h> #include "io.h" int *IOcontext_lookupArgFlags(int argc, char* argv[]){ int i; int *pFlags = malloc(255 * sizeof(int)); if (pFlags == NULL){ fprintf(stderr, "Error, could not allocate memory for flags\n"); return NULL; } memset(pFlags, -1, 255 * sizeof(int)); /* Loop over all arguments */ for (i=0; i<argc; i++){ /* Check if flag */ if (argv[i][0] != '-'){ continue; } /* Set flag character's position */ pFlags[ (int) argv[i][1] ] = i; } return pFlags; } FILE *IOcontext_lookupFile( int *pFlags, const char *type, const char *mode, FILE *def, int argc, char *argv[] ){ int i; FILE *file = def; if (pFlags==NULL || type==NULL || mode==NULL){ return NULL; } i = pFlags[ (int) type[0] ]; if (i > -1){ if (i+1 >= argc || argv[i+1][0] == '-'){ fprintf(stderr, "Error, %s file not specified\n", type); return NULL; } file = fopen(argv[i+1], mode); if (file == NULL){ fprintf(stderr, "Error, could not open %s file '%s'\n", type, argv[i+1] ); return NULL; } } return file; } struct IOcontext *IOcontext_create(int argc, char* argv[]){ /* Initialize io context */ struct IOcontext *ioc = malloc(sizeof(struct IOcontext)); if (ioc == NULL){ fprintf(stderr, "Error, could not allocate memory for io\n"); return NULL; } memset(ioc, 0, sizeof(struct IOcontext)); /* Get arg flag lookup */ ioc->pFlags = IOcontext_lookupArgFlags(argc, argv); if (ioc->pFlags == NULL){ IOcontext_free(&ioc); return NULL; } /* Open files, default to stdin/stdout */ ioc->input = IOcontext_lookupFile( ioc->pFlags, "input", "r", stdin, argc, argv ); ioc->output = IOcontext_lookupFile( ioc->pFlags, "output", "w", stdout, argc, argv ); if (ioc->input==NULL || ioc->output==NULL){ IOcontext_free(&ioc); return NULL; } return ioc; } void IOcontext_free(struct IOcontext **pIoc){ struct IOcontext *ioc; if (pIoc == NULL){ return; } ioc = *pIoc; if (ioc == NULL){ return; } /* Close any files */ if (ioc->input != NULL && ioc->input != stdin){ fclose(ioc->input); } if (ioc->output != NULL && ioc->output != stdout){ fclose(ioc->output); } /* Clean up allocated flag buffer */ if (ioc->pFlags != NULL){ free(ioc->pFlags); } free(ioc); *pIoc = NULL; } void IO_readInput(struct IOcontext *ioc){ }
NicolasKiely/tinydex
src/io.c
C
mit
2,683
# Квартира
irnc/kvartira
README.md
Markdown
mit
19
# 2016 Data sets, presentations, and other assets ## Other open data sources in and about Boston http://www.cityofboston.gov/assessing/search/ http://www.bostonredevelopmentauthority.org/research-maps/maps-and-gis/neighborhood-maps http://www.bizjournals.com/boston/research/bol-marketing/ (paid) http://www.bostonpublicschools.org/reports
BITScity/2016
README.md
Markdown
mit
345
<style> input[type="text"], input[type="number"] { font-size: 13px; color: #333333; padding: 3px; border: solid 1px #969696; transition: box-shadow 0.3s, border 0.3s; box-shadow: 0 0 5px 1px white; } input[type="text"]:hover, input[type="text"]:focus, input[type="number"]:hover, input[type="number"]:focus { border: solid 1px #707070; box-shadow: 0 0 5px 1px #969696; } #profileSection{ min-height: 20vh; } #link{ color: rgba(0,0,0,0.6); } #link:hover{ color: #20C39A; } textarea{ min-width:100%; resize: none; width:100%; padding: 3px; display: inline-block; border: 1px solid #969696; border-radius: 4px; box-sizing: border-box; margin-top: 10px; } textarea:hover { border: 1px solid #969696; } textarea:focus { border: 1px solid #969696; } #pageLogoHolder{ border: 1px solid #FF5A5F; border-radius: 4px; color: #FF5A5F; } .pageLogo{ max-height: 50px; } #removebadge{ background: #FF5A5F; } #screenshot{ max-height: 60px; max-width: 60px; } #upload3{ background-color: #F5F5F5; color: #333333; padding: 5px; } #upload3:hover { background: #FF5A5F; color: white; } #upload4{ background: #20C39A; color: white; padding: 10px; } #upload4:hover { background: #29335C; color: white; } .unquestionNoBadge{ background-color: white; border: 1px solid #FF5A5F; padding: 4px; } .questionNoBadge{ background-color: #20C39A; border: 1px solid #FF5A5F; padding: 4px; } #addQuestionBadge{ background-color: #29335C; padding: 8px; } #missingBadge{ background-color: #FF5A5F; padding: 4px; } .disabled{ background-color: #FF5A5F; } .badge{ background: #FF5A5F; } .unselectedbadge{ border: 1px solid #404040; background: white; color: #404040; } .selectedbadge{ background: #20C39A; border: 1px solid #20C39A; } </style> <div layout="row" layout-align="center start" class="width100 paddingTB10"> <div layout="row" layout-align="center center" class="width100 min100vh" flex="5"> <i class="fa fa-chevron-circle-left font48 text-black" aria-hidden="true" ng-click="previousQuestion()" ng-if="toAddQuestion._id"> <md-tooltip>Previous Question</md-tooltip> </i> </div> <div layout="row" layout-align="start start" class="width100" flex> <div layout="column" layout-align="start start" class="width100 smallFont" ng-if="user"> <div layout="column" layout-align="start start" class="width100 paddingB5 headingBottomBorder" > <div layout="column" layout-align="start start" class="width100"> <div layout="row" layout-align="start center" class="width100 gainsboroBottomBorder paddingB5"> <div class="font20 bold marginR40"> Paper: {{test.name}} </div> <div layout="row" layout-align="start center" flex> <a class="" ng-href="{{test.url.question}}" target="_blank" id="link"> <i class="fa fa-file-pdf-o font20" aria-hidden="true"></i>&nbsp;<span class="">Question Paper</span> </a> <a class="marginL10" ng-href="{{test.url.answer}}" target="_blank" id="link" ng-if="test.url.answer"> <i class="fa fa-file-pdf-o font20" aria-hidden="true"></i>&nbsp;<span class="">Answer</span> </a> <div flex layout="row" layout-align="end center" class=""> <div layout="row" layout-align="start center" class="marginL20" ng-if="fullScope" ng-click="flipwatermarked(test._id)"> <i class="fa fa-check-square-o text-primary marginR10 font16" aria-hidden="true" ng-if="test.watermarked"></i> <i class="fa fa-times danger marginR10 font16" aria-hidden="true" ng-if="!test.watermarked"></i> <span class="text-primary" ng-if="test.watermarked">Watermarked</span> <span class="danger" ng-if="!test.watermarked">Not Watermarked</span> </div> <a ng-click="markCreator()" class="marginL20" ng-if="fullScope">Mark Creator</a> </div> </div> </div> <!--<div class="">{{test.description}}</div>--> </div> <div layout="row" layout-align="start center" flex layout-wrap class="marginT10"> <div ng-repeat="testQuestion in thisTestQuestions | orderBy:['_startnumber']" layout="row" layout-align="start center" class="badge marginR2 marginB2 font9 questionNoBadge" ng-click="setQuestion(testQuestion)"> <span> Q. {{testQuestion._startnumber}} </span> <span ng-if="testQuestion._endnumber && testQuestion._endnumber != ''"> - {{testQuestion._endnumber}} </span> <span ng-if="testQuestion.questions.length > 1"> ({{testQuestion.questions.length}}) </span> </div> </div> </div> <div layout="row" layout-align="start center" class="width100 marginTB5" layout-wrap> <!--<a ng-click="markAnswerExists()" class="marginR10">Mark Answered Questions</a>--> <div class="marginR10" ng-if="missingQuestions.length > 0"> Missing Questions: </div> <div ng-repeat="missingQuestion in missingQuestions" layout-wrap class="badge marginB2 marginR2 font9" id="missingBadge" ng-if="missingQuestions.length > 0"> <span> Q. {{missingQuestion}} </span> </div> <div class="marginLR10" ng-if="repeatQuestions.length > 0"> Repeated Questions: </div> <div ng-repeat="repeatQuestion in repeatQuestions" layout-wrap class="badge marginB2 marginR2 font9" id="missingBadge"> <span> Q. {{repeatQuestion}} </span> </div> </div> <div layout="column" layout-align="start start" class="width100 marginTB5" > <div layout="row" layout-align="start center" class="width100 gainsboroBottomBorder paddingB5" layout-wrap> <div layout="row" layout-align="start center" class="font16 bold marginR20"> Question&nbsp;<span ng-if="toAddQuestion._startnumber">{{toAddQuestion._startnumber}}</span><span ng-if="toAddQuestion._endnumber">-{{toAddQuestion._endnumber}}</span> </div> <div layout="row" layout-align="start center" id="addQuestionBadge" class="badge marginR10" ng-click="addNewQuestionSet()"> <i class="fa fa-plus " aria-hidden="true"></i> Add a new Question Set </div> <div flex layout="row" layout-align="end center" class="marginL10 " layout-wrap> <div layout="row" layout-align="start center" class="marginR10"> <md-switch ng-model="toAddQuestion._groupOfQuestions" aria-label="Question Group?" class="margin0 danger bold"> Adding a group of questions? </md-switch> </div> <div layout="row" layout-align="start center" class="danger bold"> <md-switch ng-model="toAddQuestion._hascontext" aria-label="Write Up?" class="margin0"> Is there a paragraph for the set of questions? </md-switch> </div> <div layout="row" layout-align="start center" class="marginL10" ng-if="fullScope" > <a ng-click="splitQuestions()" class="marginR5" ng-if="toAddQuestion.questions.length > 1">Split Questions</a> <span class="badge" ng-click="removeQuestionDialog()"> Delete Question </span> </div> <!--<div layout="row" layout-align="start center" class="marginR10"> <md-switch ng-model="toAddQuestion._multipleCorrect" aria-label="Multiple Correct Answers?" class="margin0"> Multiple Correct Answers? </md-switch> </div>--> </div> </div> <div layout="row" layout-align="end center" class="textDarkGrey width100 paddingTB5" layout-wrap> <div layout="row" layout-align="start center" flex class="h3Font"> Question Set&nbsp;<span ng-if="toAddQuestion._id">has {{toAddQuestion.questions.length}} question(s)</span> <div layout="row" layout-align="start center" layout-wrap> <span ng-repeat="examSection in examSections" class="badge unselectedbadge font8 marginR2 marginB2 marginT2" ng-class="{selectedbadge: examSection._id === toAddQuestion.examsection}" ng-click="setQuestionExamSection(toAddQuestion, examSection)"> {{examSection.name}} </span> </div> <!--<input type="text" class="text-center marginL10" placeholder="Question Section if any" ng-model="toAddQuestion.section"> --> </div> <div class="marginR20 danger"> Add Images in this Question Set </div> <div layout="column" layout-align="center start" class=" textDarkGrey" ngf-select="uploadImage(images)" ng-model="images" multiple="multiple" > <div class="padding5" id="pageLogoHolder"> <span> <i class="fa fa-file-text font20" aria-hidden="true"></i> </span> <span> Upload Images </span> </div> </div> <div layout="row" layout-align="start start" ng-if="toAddQuestion.images && toAddQuestion.images.length > 0" class="paddingL20" layout-wrap> <div layout="column" layout-align="center center" ng-repeat="image in toAddQuestion.images" class="marginR10 marginT10"> <div layout="row" layout-align="center center" class="marginB5"> <a ng-href="{{image}}" target="_blank"> <!--<i class="fa fa-check-square-o text-primary marginR10" aria-hidden="true"></i> Image {{$index}}--> <img ng-src="{{image}}" id="screenshot"/> </a> </div> <div layout="row" layout-align="center center" class="badge" id="removebadge" ng-click="removeImage(image)"> <i class="fa fa-trash" aria-hidden="true"></i> </div> </div> </div> </div> <div layout="row" layout-align="start center" class="width100 marginTB5" ng-if="toAddQuestion._hascontext"> <textarea class="width100 font14" ng-model="toAddQuestion.context" placeholder="Add question context here. Paragraph of RC, etc" rows="4"></textarea> </div> <div layout="column" layout-align="start start" class="boxShadow width100 marginTB10 padding10" ng-repeat="question in toAddQuestion.questions"> <div layout="row" layout-align="start center" class="width100 marginB10"> <div layout="row" layout-align="start center" class="baseFont"> Type subquestion {{$index + 1}} here<span class="marginL20 font10">{{toAddQuestion._id}}</span> </div> <div layout="row" layout-align="start center" ng-click="removeQuestionFromSet(question, $index)" class="marginL20" ng-if="$index > 0"> <i class="fa fa-trash font20" aria-hidden="true"></i> </div> <div flex layout="row" layout-align="end center" class="width100"> <span class="marginLR10" ng-if="question.type =='mcq'"> <md-switch ng-model="question.mcqma" aria-label="MCQ with Multiple Answers?" class="margin0"> MCQ with Multiple Answers? </md-switch> </span> <span class="marginL20 badge" ng-click="numericalType(question)" ng-if="question.type =='mcq'">Flip to Numerical Type</span> <span class="marginL20 badge" ng-click="mcqType(question)" ng-if="question.type =='numerical'">Flip to MCQ</span> </div> <span class="marginL20 badge" ng-click="cloneTest()" ng-if="fullScope">One off</span> <span class="marginL20 badge" ng-click="markAnswerExists()">Mark Answers</span> </div> <div layout="row" layout-align="start start" class="width100"> <div flex layout="column" layout-align="start start" class="width100"> <div layout="row" layout-align="start start" class="marginB10 width100"> <textarea class="width100 font14 margin0" ng-model="question.question" placeholder="Add question text here" rows="4"></textarea> </div> <div layout="column" layout-align="start start" class="width100 paddingLR20" ng-repeat="option in question.options" ng-if="question.type=='mcq'"> <div layout="row" layout-align="start center" class="width100 marginB2"> <div layout="row" layout-align="start center" flex="30"> <div class="font14 marginR20"> Option {{$index+1}} </div> <div> <md-switch ng-model="option._correct" aria-label="Answer?" class="margin0"> Answer? </md-switch> </div> </div> <div flex> <textarea class="width100 font14 margin0" ng-model="option.option" placeholder="Add option here" rows="1"></textarea> </div> <div layout="row" layout-align="center center" class="marginL10"> <div class="badge" id="removebadge" ng-click="removeOption(question, option, $index)"> <i class="fa fa-trash" aria-hidden="true"></i> </div> </div> </div> </div> <div layout="column" layout-align="start start" class="width100 paddingLR20" ng-show="question.type=='numerical'"> <div layout="row" layout-align="start center" class="width100"> <div layout="row" layout-align="start center" flex="40"> <div class="font14 marginR20"> Numerical Answer </div> <div class="paddingLR10"> <md-select ng-model="question.numericalAnswerType" placeholder="Numerical Answer Type" class="margin0"> <md-option ng-value="numericalAnswerType.value" ng-repeat="numericalAnswerType in numericalAnswerTypes" class="margin0"> {{numericalAnswerType.display}} </md-option> </md-select> </div> <span class="badge" ng-click="addNumericalAnswer(question)" ng-if="question.type =='numerical'">Add another answer</span> </div> <div layout="column" layout-align="start center" flex> <!--ng-if="numericalAnswerType == 'Exact'"--> <div layout="row" layout-align="start center" class="width100 marginB5" ng-repeat="numericalAnswer in question.numericalAnswers track by $index" ng-if="question.numericalAnswerType == 'Exact'"> <textarea class="width100 font14 margin0" ng-model="question.numericalAnswers[$index]" placeholder="Add numerical answer here" rows="1"></textarea> <div class="badge marginL10" id="removebadge" ng-click="removeNumericalAnswer(question, $index)"> <i class="fa fa-trash" aria-hidden="true"></i> </div> </div> <div layout="row" layout-align="start center" class="width100" ng-if="question.numericalAnswerType == 'Range'"> <div flex class="paddingLR10"> <input type="number" class="text-center width100" placeholder="Min" ng-model="question.numericalAnswerRange.min"> </div> <div flex class="paddingLR10"> <input type="number" class="text-center width100" placeholder="Max" ng-model="question.numericalAnswerRange.max" > </div> </div> </div> </div> </div> <div layout="row" layout-align="center center" id="upload3" ng-click="addNewOption(question)" class="width100 marginT5" ng-if="question.type=='mcq'"> <span> <i class="fa fa-plus" aria-hidden="true"></i> Add Another Option </span> </div> <div layout="row" layout-align="start center" class="width100 min10vh marginTB5 paddingLR20"> <div layout="row" layout-align="start center" flex="30"> <div class="font14"> Marking for question </div> </div> <div layout="row" layout-align="start center" flex> <div layout="row" layout-align="start center"> <div class="text-primary paddingR10">Correct Answer</div> <div flex class="paddingR10"><input type="text" class="width100 text-center" placeholder="Correct Answer" ng-model="question.marking.correct"></div> </div> <div layout="row" layout-align="start center"> <div class="danger paddingL10">Incorrect Answer</div> <div flex class="paddingL10"> <input type="text" class="width100 text-center" placeholder="Correct Answer" ng-model="question.marking.incorrect"> </div> </div> </div> </div> <div flex layout="row" layout-align="start start" class="marginTB5 paddingLR20 width100"> <div flex class="width100"> <textarea class="width100 font14 margin0" ng-model="question.solution.solution" placeholder="Add solution here (if available)" rows="3"></textarea> </div> <div layout="column" layout-align="start start" class=" paddingL10" > <div layout="column" layout-align="center start" class=" textDarkGrey width100 height100" ngf-select="uploadSolutionImages(question, question.solutionimages)" ng-model="question.solutionimages" multiple="multiple" > <div class="padding10" id="pageLogoHolder"> <span> <i class="fa fa-picture-o font24" aria-hidden="true"></i> </span> <span> Upload Solution Images </span> </div> </div> <div flex layout="row" layout-align="start start" ng-if="question.solution.images && question.solution.images.length > 0" class="paddingL20 width100" layout-wrap> <div layout="column" layout-align="center center" ng-repeat="image in question.solution.images" class="marginR10 marginT10"> <div layout="row" layout-align="center center" class="marginB5"> <a ng-href="{{image}}" target="_blank"> <img ng-src="{{image}}" id="screenshot"/> </a> </div> <div layout="row" layout-align="center center" class="badge" id="removebadge" ng-click="removeSolutionImage(question, image)"> <i class="fa fa-trash" aria-hidden="true"></i> </div> </div> </div> </div> </div> </div> </div> </div> <div layout="row" layout-align="center center" id="upload4" ng-click="addNewQuestion()" class="width100 marginT10"> <span> <i class="fa fa-plus" aria-hidden="true"></i> Add another question to this set </span> </div> </div> <div layout="column" layout-align="start start" class="width100 headingTopBorder2 paddingT20 marginT40" > <div layout="column" layout-align="start start" class="width100 subBaseFont marginTB10 boxShadow padding10" > <div layout="row" layout-align="start center" class="width100 marginTB10 padding10 font24 text-primary" ng-if="test.simulate.ready"> <div class="paddingR20"> <i class="fa fa-check-circle font32" aria-hidden="true"></i>&nbsp;Ready to simulate! </div> <div class="paddingL20"> <md-button class="md-danger md-small font10" ng-click="manualMarkforEBSimulation()" ng-if="!test.simulationactive"> Manually Mark for EB Simulation </md-button> <md-button class="md-next md-small font10" ng-click="manualUnmarkforEBSimulation()" ng-if="test.simulationactive"> Manually Unmark for EB Simulation </md-button> <md-button class="md-danger md-small font10" ng-click="simulateNow()" ng-if="test.simulationactive"> Simulate Now </md-button> </div> </div> <div layout="column" layout-align="start start" class="width100 marginTB10 padding10 assignBackground2" ng-if="test.simulate.comments.length > 0"> <div class="baseFont">Simulation Issues - Need Correction <span class="badge">{{test.simulate.comments.length}}</span> </div> <div layout="column" layout-align="start start" class="width100 marginT5 smallFont textBlack" ng-repeat="comment in test.simulate.comments track by $index" > <div layout="row" layout-align="start center" class="width100"> <div flex="5">{{$index + 1}}</div> <div flex> {{comment}} </div> </div> </div> </div> <div layout="column" layout-align="start start" class="width100 marginTB10"> <div class="h3Font marginB10">Test Simulation Information</div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Test Name </div> <div flex class="paddingL10"> <input type="text" class="width100" placeholder="Name of the Test" ng-model="test.name"> </div> </div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Test Description </div> <div flex class="paddingL10"> <input type="text" class="width100" placeholder="Description of the Test" ng-model="test.description"> </div> </div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Total Number of Questions in the test </div> <div flex class="paddingL10"> <input type="text" class="width100" placeholder="Total Number of Questions" ng-model="test.nQuestions"> </div> </div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Actual Exam Date </div> <div flex class="paddingL10"> <md-datepicker ng-model="test._actualdate" class="margin0" md-placeholder="Actual Exam Date"></md-datepicker> </div> </div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Does the test have detailed solutions to every question? </div> <div flex class="paddingL10"> <md-switch ng-model="test.solutionkey" aria-label="Solution Key?" class="margin0 danger bold"> Solutions (not just correct option) in Answerkey? </md-switch> </div> </div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Can the test be reset & taken again by the candidate? </div> <div flex class="paddingL10"> <md-switch ng-model="test.resettable" aria-label="Resettable?" class="margin0 danger bold"> Resettable test? </md-switch> </div> </div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Can the test be downloaded by the candidate? </div> <div flex class="paddingL10"> <md-switch ng-model="test.downloadable" aria-label="Downloadable?" class="margin0 danger bold"> Downloadable test? </md-switch> </div> </div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Can the test result be analyzed by the candidate? </div> <div flex class="paddingL10"> <md-switch ng-model="test.analyzeable" aria-label="Analyzeable?" class="margin0 danger bold"> Analyzeable test? </md-switch> </div> </div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Total Duration of the test in minutes </div> <div flex class="paddingL10"> <input type="text" class="width100" placeholder="Duration of the test in minutes" ng-model="test.duration"> </div> </div> <div layout="row" layout-align="start center" class="width100 padding10 assignBackground"> <div class="bold paddingR10" flex="40"> Simulation Rank </div> <div flex class="paddingL10"> <input type="number" class="width100" placeholder="Rank while showing for simulation (lower is better)" ng-model="test.simulationrank"> </div> </div> <div layout="column" layout-align="start start" class="width100 marginTB10 padding10 assignBackground"> <div class="baseFont">Test Instructions - Add/Edit</div> <div layout="column" layout-align="start start" class="width100 marginT5" ng-repeat="instruction in test.instructions track by $index" > <div layout="row" layout-align="start center" class="width100 marginB5"> <div flex="5">{{$index + 1}}</div> <div flex><input type="text" class="width100" placeholder="Instruction goes here" ng-model="test.instructions[$index]"></div> <div layout="row" layout-align="end center" flex="5"> <i class="fa fa-trash danger" aria-hidden="true" ng-click="removeTestInstruction($index)"></i> </div> </div> </div> </div> <div layout="row" layout-align="center center" id="upload3" ng-click="addTestInstruction()" class="width100 marginTB5"> <span> <i class="fa fa-plus" aria-hidden="true"></i> Add Instruction </span> </div> <div layout="row" layout-align="end center" class="width100 marginT20"> <md-button class="md-markReview md-small font10" ng-click="showSectionsMarkingDialog()"> Custom Sections </md-button> <md-button class="md-green2 md-small font10" ng-click="showCustomMarkingDialog()"> Custom Marking </md-button> <md-button class="md-danger md-small font10" ng-click="markSimulate()"> Check Simulation Readiness </md-button> <md-button class="md-next md-small font10" ng-click="saveTest()"> Save Simulation Details </md-button> </div> <div layout="column" layout-align="start start" ng-if="showCustomSections" class="width100"> <div layout="row" layout-align="start start" class="width100 h2Font marginT20"> Set sections Questions </div> <div layout="row" layout-align="start start" class="width100 marginB10"> <div layout="column" layout-align="start start" class="width100 padding10" flex="25"> <div layout="column" layout-align="start start" class="width100 padding10 boxShadow font9"> <div class="width100 marginB10"> Not Marked </div> <div class="width100 marginB10" layout="row" layout-align="start start" layout-wrap> <span ng-repeat="testQuestion in thisTestQuestions" layout="row" layout-align="start center" class="badge font8 marginR2 marginB2" ng-class="selectedClass(testQuestion)" ng-if="!testQuestion.examsection" ng-click="addtoSelection(testQuestion)"> <span> Q. {{testQuestion._startnumber}} </span> <span ng-if="testQuestion._endnumber && testQuestion._endnumber != ''"> - {{testQuestion._endnumber}} </span> </span> </div> </div> </div> <div layout="column" layout-align="start start" class="width100 padding10" ng-repeat="examSection in examSections" flex="25"> <div layout="column" layout-align="start start" class="width100 padding10 boxShadow font9"> <div class="width100 marginB10"> {{examSection.name}} </div> <div class="width100 marginB10" layout="row" layout-align="start start" layout-wrap> <span ng-repeat="testQuestion in thisTestQuestions" layout="row" layout-align="start center" class="badge font8 marginR2 marginB2" ng-class="selectedClass(testQuestion)" ng-if="testQuestion.examsection == examSection._id" ng-click="addtoSelection(testQuestion)"> <span> Q. {{testQuestion._startnumber}} </span> <span ng-if="testQuestion._endnumber && testQuestion._endnumber != ''"> - {{testQuestion._endnumber}} </span> </span> </div> <!--<div class="width100 marginB10" layout="row" layout-align="start start"> <div layout="column" layout-align="start start" ng-repeat="thisSection in test.simulate.sections" ng-if="thisSection.name == section" class="width100"> <div class="width100 padding5" layout="row" layout-align="start center"> <div flex>Is this section timed?</div> <div flex> <md-switch ng-model="thisSection.timedSeparately" aria-label="Timed Separately?" class="margin0"> Timed Separately? </md-switch> </div> </div> <div flex class="width100 padding5" ng-if="thisSection.timedSeparately" layout="row" layout-align="start center"> <div flex>Time Duration</div> <div> <input type="text" class="" ng-model="thisSection.time" placeholder="Time for this section"> </div> </div> <div flex class="width100 padding5" ng-if="thisSection.timedSeparately" layout="row" layout-align="start center"> <div flex>Max Break duration after section</div> <div> <input type="text" class="" ng-model="thisSection.break" placeholder="Break duration after section"> </div> </div> <div flex class="width100 padding5" ng-if="thisSection.timedSeparately" layout="row" layout-align="start center"> <div flex>Position in simulation</div> <div> <input type="text" class="" ng-model="thisSection.order" placeholder="Position in simulation"> </div> </div> </div> </div>--> </div> </div> </div> <!--<div layout="row" layout-align="end center" class="width100 marginT20"> <md-button class="md-markReview md-small font10" ng-click="saveTest()"> Save Section Details </md-button> </div>--> <div layout="row" layout-align="start center" class="width100 boxShadow lightGreyBackground padding10 margin10" ng-show="selectedQuestions.length > 0"> <div layout="column" layout-align="start start" flex> <div class="width100"> Set Section Name for: <span class="badge unselectedbadge marginL10" ng-click="clearSelection()"> Clear </span> </div> <div layout="row" layout-align="start start" class="width100" layout-wrap> <span ng-repeat="testQuestion in selectedQuestions | orderBy:['_startnumber']" layout="row" layout-align="start center" class="badge marginR2 marginB2 selectedBadge" ng-click="removeFromSelection(testQuestion)"> <span> Q. {{testQuestion._startnumber}} </span> <span ng-if="testQuestion._endnumber && testQuestion._endnumber != ''"> - {{testQuestion._endnumber}} </span> </span> </div> </div> <div layout="row" layout-align="start center" flex> <md-button class="md-markReview md-small font10" ng-click="bulkSetExamSections(examSection)" ng-repeat="examSection in examSections"> {{examSection.name}} </md-button> <!--<input type="text" class="" ng-model="newSectionName" placeholder="New Section Name">--> </div> </div> </div> </div> </div> </div> </div> <div layout="column" layout-align="start start" class="width100 font20 danger" ng-if="!user"> You are not permitted to access this without logging in! Please login and try again! </div> </div> <div layout="row" layout-align="center center" class="width100 min100vh" flex="5"> <i class="fa fa-chevron-circle-right font48 text-black" aria-hidden="true" ng-click="nextQuestion()" ng-if="toAddQuestion._id"> <md-tooltip>Next Question</md-tooltip> </i> </div> </div> <div class="bottomBar"> <div layout="row" layout-align="start center"> <div hide-xs hide-sm layout="row" layout-align="start center"> <div> Do you want to save your changes to the question? </div> </div> <div layout="row" layout-align="end center" flex> <div class="marginR10"> <div ng-if="!readyToSave()"> <i class="fa fa-check-circle text-primary font20" aria-hidden="true"></i> Good to add! </div> <div ng-if="readyToSave()"> <i class="fa fa-times danger font20" aria-hidden="true"></i> Enter all details before you can add </div> </div> <div layout="row" layout-align="start center" class="marginR10"> <div layout="row" layout-align="start center" class="marginR10"> <input type="text" class="" ng-model="toAddQuestion._startnumber" placeholder="Q.No. in PDF"> </div> <div layout="row" layout-align="start center" class="marginR10" ng-if="toAddQuestion._groupOfQuestions"> <input type="text" class="" ng-model="toAddQuestion._endnumber" placeholder="Ending Q.No. in PDF"> </div> </div> <md-button class="md-green2 md-small font10 width8" ng-click="saveNewQuestion(toAddQuestion)" ng-disabled="readyToSave()"> Save </md-button> <md-button class="md-default md-cancel md-small font10 width8" ng-click="reload()"> Cancel </md-button> </div> </div> </div> <div style="visibility: hidden"> <div class="md-dialog-container" id="savedDialog"> <md-dialog> <div layout="row" layout-xs="column" layout-padding layout-align="center center" id="dialogHeaderWhite" > <div class="margin20 padding10"> <span class="text-primary md-headline"> <i class="fa fa-check-square" aria-hidden="true"></i> </span> <span class="md-title"> Changes Saved! </span> </div> </div> </md-dialog> </div> </div> <div style="visibility: hidden"> <div class="md-dialog-container" id="customMarkingDialog"> <md-dialog class="blog-dialog whiteBackground padding10"> <div layout="column" layout-align="start start" class="width100 padding10 min20vh"> <div layout="column" layout-align="center center" class="h3Font width100 padding10"> Set marking for questions </div> <div layout="row" layout-align="start center" layout-wrap class="paddingTB10 width100"> <div ng-repeat="testQuestion in thisTestQuestions | orderBy:['_startnumber']" layout="row" layout-align="start center" class="badge marginR2 marginB2 font9 questionNoBadge" ng-click="addCustomMarkingQuestion(testQuestion)"> <span> Q. {{testQuestion._startnumber}} </span> <span ng-if="testQuestion._endnumber && testQuestion._endnumber != ''"> - {{testQuestion._endnumber}} </span> <span ng-if="testQuestion.questions.length > 1"> ({{testQuestion.questions.length}}) </span> </div> <div layout="row" layout-align="start center" class="badge marginR2 marginB2 font9 questionNoBadge" ng-click="setAllCustomMarkingQuestion()"> <span> All Questions </span> </div> </div> <div layout="row" layout-align="start center" class="width100 min20vh padding10 h3Font" layout-wrap> <div class="marginR10">Selected Questions</div> <div ng-repeat="testQuestion in customMarkingQuestions | orderBy:['_startnumber']" layout="row" layout-align="start center" class="badge marginR2 marginB2 font9 questionNoBadge" ng-click="removeCustomMarkingQuestion(testQuestion)"> <span> Q. {{testQuestion._startnumber}} </span> <span ng-if="testQuestion._endnumber && testQuestion._endnumber != ''"> - {{testQuestion._endnumber}} </span> <span ng-if="testQuestion.questions.length > 1"> ({{testQuestion.questions.length}}) </span> </div> <div class="marginR2 marginB2 font9" ng-click="removeAllCustomMarkingQuestion()">Clear</div> </div> <div layout="row" layout-align="start center" class="width100"> <div flex class="paddingLR10"> <input type="number" class="width100 text-primary" ng-model="customMarking.correct" placeholder="Marks for correct answer"> </div> <div flex class="paddingLR10"> <input type="number" class="width100 danger" ng-model="customMarking.incorrect" placeholder="Marks for incorrect answer"> </div> </div> </div> <div layout="row" layout-align="center center" class="width100 padding10"> <md-button class="md-danger md-small font10" ng-click="setCustomMarkingForAll()"> Set Custom Marking for all questions </md-button> </div> </md-dialog> </div> </div>
gauravparashar29/exambazaar
views/partials/addQuestion.html
HTML
mit
47,960
#!/bin/sh result=`./log_function_test 2>&1 >/dev/null` count() { word=$1 echo ${result} | tr [:blank:] "\n" | grep ${word} | wc -l } disp=`count DISPLAY` err=`count ERROR` warn=`count WARNING` inf=`count INFO` dbg=`count DEBUG` if [ ${disp} -ne 4 -o ${err} -ne 1 -o ${warn} -ne 1 -o ${inf} -ne 1 -o ${dbg} -ne 1 ]; then echo "invalid output" echo "disp = ${disp}, err = ${err}, warn = ${warn}, info = ${inf}, dbg = ${dbg}" exit 1 fi rm -f ${test_log_file} exit 0
linear-rpc/linear-cpp
test/log_function_test.sh
Shell
mit
487
export function cne(t: string): CurriedCNE; /** * Curried element creation. */ export type CurriedCNE = (P?: HTMLElement) => HTMLElement[];
vangware/micron
lib/cne.d.ts
TypeScript
mit
142
/* PrismJS 1.20.0 https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript+bash+c+cpp+clojure+css-extras+diff+git+java+python+scala+sql+swift+yaml&plugins=line-highlight+line-numbers+show-language+inline-color+command-line+toolbar+copy-to-clipboard+diff-highlight */ /** * prism.js default theme for JavaScript, CSS and HTML * Based on dabblet (http://dabblet.com) * @author Lea Verou */ code[class*="language-"], pre[class*="language-"] { color: black; background: none; text-shadow: 0 1px white; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; font-size: 1em; text-align: left; white-space: pre; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; -webkit-hyphens: none; -moz-hyphens: none; -ms-hyphens: none; hyphens: none; } pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { text-shadow: none; background: #b3d4fc; } pre[class*="language-"]::selection, pre[class*="language-"] ::selection, code[class*="language-"]::selection, code[class*="language-"] ::selection { text-shadow: none; background: #b3d4fc; } @media print { code[class*="language-"], pre[class*="language-"] { text-shadow: none; } } /* Code blocks */ pre[class*="language-"] { padding: 1em; margin: .5em 0; overflow: auto; } :not(pre) > code[class*="language-"], pre[class*="language-"] { background: #f5f2f0; } /* Inline code */ :not(pre) > code[class*="language-"] { padding: .1em; border-radius: .3em; white-space: normal; } .token.comment, .token.prolog, .token.doctype, .token.cdata { color: slategray; } .token.punctuation { color: #999; } .token.namespace { opacity: .7; } .token.property, .token.tag, .token.boolean, .token.number, .token.constant, .token.symbol, .token.deleted { color: #905; } .token.selector, .token.attr-name, .token.string, .token.char, .token.builtin, .token.inserted { color: #690; } .token.operator, .token.entity, .token.url, .language-css .token.string, .style .token.string { color: #9a6e3a; /* This background color was intended by the author of this theme. */ background: hsla(0, 0%, 100%, .5); } .token.atrule, .token.attr-value, .token.keyword { color: #07a; } .token.function, .token.class-name { color: #DD4A68; } .token.regex, .token.important, .token.variable { color: #e90; } .token.important, .token.bold { font-weight: bold; } .token.italic { font-style: italic; } .token.entity { cursor: help; } pre[data-line] { position: relative; padding: 1em 0 1em 3em; } .line-highlight { position: absolute; left: 0; right: 0; padding: inherit 0; margin-top: 1em; /* Same as .prism’s padding-top */ background: hsla(24, 20%, 50%,.08); background: linear-gradient(to right, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); pointer-events: none; line-height: inherit; white-space: pre; } .line-highlight:before, .line-highlight[data-end]:after { content: attr(data-start); position: absolute; top: .4em; left: .6em; min-width: 1em; padding: 0 .5em; background-color: hsla(24, 20%, 50%,.4); color: hsl(24, 20%, 95%); font: bold 65%/1.5 sans-serif; text-align: center; vertical-align: .3em; border-radius: 999px; text-shadow: none; box-shadow: 0 1px white; } .line-highlight[data-end]:after { content: attr(data-end); top: auto; bottom: .4em; } .line-numbers .line-highlight:before, .line-numbers .line-highlight:after { content: none; } pre[id].linkable-line-numbers span.line-numbers-rows { pointer-events: all; } pre[id].linkable-line-numbers span.line-numbers-rows > span:before { cursor: pointer; } pre[id].linkable-line-numbers span.line-numbers-rows > span:hover:before { background-color: rgba(128, 128, 128, .2); } pre[class*="language-"].line-numbers { position: relative; padding-left: 3.8em; counter-reset: linenumber; } pre[class*="language-"].line-numbers > code { position: relative; white-space: inherit; } .line-numbers .line-numbers-rows { position: absolute; pointer-events: none; top: 0; font-size: 100%; left: -3.8em; width: 3em; /* works for line-numbers below 1000 lines */ letter-spacing: -1px; border-right: 1px solid #999; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .line-numbers-rows > span { display: block; counter-increment: linenumber; } .line-numbers-rows > span:before { content: counter(linenumber); color: #999; display: block; padding-right: 0.8em; text-align: right; } div.code-toolbar { position: relative; } div.code-toolbar > .toolbar { position: absolute; top: .3em; right: .2em; transition: opacity 0.3s ease-in-out; opacity: 0; } div.code-toolbar:hover > .toolbar { opacity: 1; } /* Separate line b/c rules are thrown out if selector is invalid. IE11 and old Edge versions don't support :focus-within. */ div.code-toolbar:focus-within > .toolbar { opacity: 1; } div.code-toolbar > .toolbar .toolbar-item { display: inline-block; } div.code-toolbar > .toolbar a { cursor: pointer; } div.code-toolbar > .toolbar button { background: none; border: 0; color: inherit; font: inherit; line-height: normal; overflow: visible; padding: 0; -webkit-user-select: none; /* for button */ -moz-user-select: none; -ms-user-select: none; } div.code-toolbar > .toolbar a, div.code-toolbar > .toolbar button, div.code-toolbar > .toolbar span { color: #bbb; font-size: .8em; padding: 0 .5em; background: #f5f2f0; background: rgba(224, 224, 224, 0.2); box-shadow: 0 2px 0 0 rgba(0,0,0,0.2); border-radius: .5em; } div.code-toolbar > .toolbar a:hover, div.code-toolbar > .toolbar a:focus, div.code-toolbar > .toolbar button:hover, div.code-toolbar > .toolbar button:focus, div.code-toolbar > .toolbar span:hover, div.code-toolbar > .toolbar span:focus { color: inherit; text-decoration: none; } span.inline-color-wrapper { /* * The background image is the following SVG inline in base 64: * * <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2 2"> * <path fill="gray" d="M0 0h2v2H0z"/> * <path fill="white" d="M0 0h1v1H0zM1 1h1v1H1z"/> * </svg> * * SVG-inlining explained: * https://stackoverflow.com/a/21626701/7595472 */ background: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyIDIiPjxwYXRoIGZpbGw9ImdyYXkiIGQ9Ik0wIDBoMnYySDB6Ii8+PHBhdGggZmlsbD0id2hpdGUiIGQ9Ik0wIDBoMXYxSDB6TTEgMWgxdjFIMXoiLz48L3N2Zz4="); /* This is to prevent visual glitches where one pixel from the repeating pattern could be seen. */ background-position: center; background-size: 110%; display: inline-block; height: 1.333ch; width: 1.333ch; margin: 0 .333ch; box-sizing: border-box; border: 1px solid white; outline: 1px solid rgba(0,0,0,.5); overflow: hidden; } span.inline-color { display: block; /* To prevent visual glitches again */ height: 120%; width: 120%; } .command-line-prompt { border-right: 1px solid #999; display: block; float: left; font-size: 100%; letter-spacing: -1px; margin-right: 1em; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .command-line-prompt > span:before { color: #999; content: ' '; display: block; padding-right: 0.8em; } .command-line-prompt > span[data-user]:before { content: "[" attr(data-user) "@" attr(data-host) "] $"; } .command-line-prompt > span[data-user="root"]:before { content: "[" attr(data-user) "@" attr(data-host) "] #"; } .command-line-prompt > span[data-prompt]:before { content: attr(data-prompt); } pre.diff-highlight > code .token.deleted:not(.prefix), pre > code.diff-highlight .token.deleted:not(.prefix) { background-color: rgba(255, 0, 0, .1); color: inherit; display: block; } pre.diff-highlight > code .token.inserted:not(.prefix), pre > code.diff-highlight .token.inserted:not(.prefix) { background-color: rgba(0, 255, 128, .1); color: inherit; display: block; }
manuzhang/manuzhang.github.io
themes/prism.css
CSS
mit
8,166
<?php namespace AppBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class ContractsControllerTest extends WebTestCase { }
RassulYunussov/qvisitorBC-symfony
src/AppBundle/Tests/Controller/ContractsControllerTest.php
PHP
mit
154
import React, { PropTypes } from 'react'; import styled from 'styled-components'; import TextInfo from '../TextInfo'; import CardImage from '../CardImage'; import { Row, Col, Card, Avatar } from 'antd'; import { Panel } from 'react-bootstrap'; /* const CardImage = styled.div` img { display: block; height:200px; } `;*/ class CardRaces extends React.Component { constructor(props) { super(props); } onClick = (id) => { if (this.props.onClick) { this.props.onClick(id); } } render() { const { data } = this.props; return ( <Row gutter={8}> {data.map((race, key) => <Col key={key} md={12} style={{ marginBottom: 5, marginTop: 5 }}> <CardImage imageUrl={race.cardImageUrl} onClick={() => this.onClick(race.id)}> <div > <h3>{race.title}</h3> <TextInfo>{race.description}</TextInfo> </div> </CardImage> </Col> )} </Row> ) } } /* CardRaces.defaultProps = { data: [ { id:'spartan-challenge', title: 'Spartan Challenge', date: '2017-Aug-12', description: 'Spartan Challenge', url:'http://lorempixel.com/400/200/sports/1' }, { id:'takbo-marawi', title: 'Takbo Marawi', date: '2017-Aug-12', description: 'Spartan Challenge', url:'http://lorempixel.com/400/200/sports/2' }, ] }; */ CardRaces.propTypes = { data: PropTypes.arrayOf(PropTypes.shape({ title: PropTypes.string, date: PropTypes.date, description: PropTypes.string, url: PropTypes.string })) }; export default CardRaces;
matapang/virtualraceph2
src/components/CardRaces/index.js
JavaScript
mit
1,802
# ABCBot This is a microservice designed to sit along side teamcity and take requests from the TCWebHook plugin and act upon them. ## Install Install virtualenvwrapper: ``` sudo pip3 install virtualenvwrapper source /usr/local/bin/virtualenvwrapper.sh ``` Presuming you have virtualenvwrapper and python 3.6+ installed already: ```sh mkvirtualenv abcbot workon abcbot pip3 install -r requirements.txt ``` ## Tests Install pytest: ``` pip3 install pytest ``` Run tests: ``` pytest -v ``` ## Deployment The bot is deployed to a secure environment where the necessary secrets are provided to it. For example, if using docker: Setup the .env file: ``` cp .template.env .env vim .env # Edit as needed ``` Build: ``` docker build -t my-docker-tag . ``` Use the .env file when running the container: ``` docker run -it --env-file=.env my-docker-tag ``` ## Running the server locally Running the tests is your best bet for local development. But, if you insist on running a server locally: ``` ./abcbot.py [-l --log-file LOG_FILE] [-p --port PORT] ```
Bitcoin-ABC/bitcoin-abc
contrib/buildbot/README.md
Markdown
mit
1,060
namespace Rules { public enum StatusOfValidation { Success, Worning, Error } }
julianosaless/specification-rules
src/Rules/StatusOfValidation.cs
C#
mit
118
var names = [ 'Whiskers', 'Athena', 'Sir Theodore Tibblesworth', 'Rex' ]; function keyOf (name) { return name.toLowerCase().replace(/\W+/g, '-') } module.exports = function (db) { setInterval(function () { var lives = Math.floor(Math.random() * 9 + 1); var name = names[Math.floor(Math.random() * names.length)]; db.put('cat!' + keyOf(name), { name: name, lives: lives }); }, 1000); };
substack/liver
example/pets/populate.js
JavaScript
mit
419
/** * This file contains Interfaces mapping Travis responses */ declare module TravisJsonResponse { interface Json { id: number; repository_id: number; number: string; state: string; result: number; started_at: Date; finished_at: Date; duration: number; commit: string; branch: string; message: string; event_type: string; } } declare module 'TravisJsonResponse' { export = TravisJsonResponse; }
afranken/simon
src/main/ts/jsonInterfaces/TravisResponse.d.ts
TypeScript
mit
509
<form method="post" action="{{ route('authorSegments.compute') }}"> <form-validator url="{{route('authorSegments.validateTest')}}"></form-validator> <div class="col-md-6"> {{ csrf_field() }} <p class="c-black f-500 m-b-10">Minimal ratio of (author articles/all articles) read by user:</p> <div class="form-group"> <div class="fg-line"> <input id="min_ratio" class="form-control input-sm" value="{{ old('min_ratio') }}" name="min_ratio" required placeholder="e.g. 0.25 (value between 0.0 - 1.0)" type="number" step="0.01" min="0" max="1" /> </div> </div> <p class="c-black f-500 m-b-10">Minimal number of author articles read by user:</p> <div class="form-group"> <div class="fg-line"> <input id="min_views" class="form-control input-sm" value="{{ old('min_views') }}" placeholder="e.g. 5" required name="min_views" min="0" type="number" /> </div> </div> <p class="c-black f-500 m-b-10">Minimal average time spent on author's articles by user (seconds):</p> <div class="form-group"> <div class="fg-line"> <input id="min_average_timespent" class="form-control input-sm" value="{{ old('min_average_timespent') }}" required placeholder="e.g. 120 (value in seconds)" name="min_average_timespent" min="0" type="number" /> </div> </div> <p class="c-black f-500 m-b-10">Use data from the last:</p> <div class="radio m-b-15"> <label> {{ Form::radio('history', '30', true) }} <i class="input-helper"></i> 30 days </label> </div> <div class="radio m-b-15"> <label> {{ Form::radio('history', '60', true) }} <i class="input-helper"></i> 60 days </label> </div> <div class="radio m-b-15"> <label> {{ Form::radio('history', '90', true) }} <i class="input-helper"></i> 90 days </label> </div> <div class="form-group"> <div class="fg-line"> <input id="email" class="form-control input-sm" value="{{ old('email') }}" placeholder="Email to send results" name="email" type="text" required /> </div> </div> <input class="btn palette-Cyan bg waves-effect" type="submit" value="Compute" /> </div> </form>
remp2020/remp
Beam/resources/views/authors/segments/_test_form.blade.php
PHP
mit
2,544
#include "reaction.hpp" /** *Item token print here */ void item_token::print(std::ostream& o)const{ o<< type+" "+subtype<<std::endl; } /** *material things here */ material_token::material_token(Reaction* r):parent(r){} material_token::~material_token(){} void material_token::print(std::ostream& o)const{ o<< get_Type()+" "+get_Sub()<<std::endl; } derived_mat::derived_mat(const std::string& r_id, Reaction *r):material_token(r),r_id(r_id){} derived_mat::~derived_mat(){} void derived_mat::print(std::ostream& o)const{ o<<get_Type()+" "+get_Sub()<<std::endl; } std::string derived_mat::get_Type()const{ return parent->name_mappings[r_id]->mat->get_Type(); } std::string derived_mat::get_Sub()const{ return parent->name_mappings[r_id]->mat->get_Sub(); } known_mat::known_mat(const std::string& type, const std::string& sub,Reaction* i):material_token(i),type(type),sub(sub){ } known_mat::~known_mat(){ } std::string known_mat::get_Type()const{ return type; } std::string known_mat::get_Sub()const{ return sub; } void known_mat::print(std::ostream& o)const{ o<<type<<" "<<sub<<std::endl; } /** *ProductModifier things here */ ProductModifier::ProductModifier(const std::string& n,Product *parent):parent(parent),name(n){} void ProductModifier::affect_product()const{} void ProductModifier::print(std::ostream& o)const{ o<<name<<std::endl; } ToContainer::ToContainer(const std::string &name, const std::string& container_id,Product* p):ProductModifier(name,p),container_id(container_id){} void ToContainer::print(std::ostream& o)const{ o<<name<<" "<<container_id<<std::endl; } /** *Reagent stuff here */ Reagent::Reagent(){} Reagent::Reagent(Reaction* p,const RawTag& tag):parent(p){ this->name=tag.tagvalues[0]; this->quantity=std::stoi(tag.tagvalues[1]); item_token it; it.type=tag.tagvalues[2]; it.type=tag.tagvalues[3]; mat=new known_mat(tag.tagvalues[4],tag.tagvalues[5],parent); } Reagent::~Reagent(){ delete mat; for(auto i:modifiers) delete i; } void Reagent::print(std::ostream& o)const{ o<<"\t\t\t"<<name<<std::endl; o<<"\t\t\t"<<quantity<<std::endl; o<<"\t\t\t\t"; tok.print(o); o<<"\t\t\t\t"; mat->print(o); for(auto i : modifiers){ o<<"\t\t\t\t"; i->print(o); } } /** *Reaction stuff */ Reaction::Reaction(){} Reaction::Reaction(const std::vector<RawTag>& tags){ const RawTag& first = tags[0]; this->id=first.tagvalues[0]; bool wasReagent=false; Reagent *lastReagent=NULL; Product *lastProduct=NULL; for(int i=1;i<tags.size();++i){ const RawTag& tag=tags[i]; if(tag.tagname=="NAME"){ name=tag.tagvalues[0]; }else if(tag.tagname=="BUILDING"){ ReactionBuilding e; e.name=tag.tagvalues[0]; e.key=tag.tagvalues[1]; this->building=e; }else if(tag.tagname=="SKILL"){ this->skill=tag.tagvalues[0]; }else if(tag.tagname=="FUEL"){ fuel=true; }else if(tag.tagname=="REAGENT"){ Reagent *temp=new Reagent(this,tag); this->reagents.push_back(temp); this->name_mappings[temp->name]=temp; lastReagent=temp; wasReagent=true; }else if(tag.tagname=="PRODUCT"){ Product *temp=new Product(this,tag); products.push_back(temp); lastProduct=temp; wasReagent=false; }else if(tag.tagname=="ADVENTURE"){ adventure=true; }else if(tag.tagname=="AUTOMATIC"){ automatic=true; }else{ if(wasReagent&&lastReagent){ ReagentModifier *temp; if(tag.tagvalues.empty()){ temp=new ReagentModifier(tag.tagname,lastReagent); }else{ temp=new TwoPartMod(tag.tagname,tag.tagvalues[0],lastReagent); } lastReagent->modifiers.push_back(temp); }else if(lastProduct){ ProductModifier* temp; if(tag.tagvalues.empty()){ temp = new ProductModifier(tag.tagname,lastProduct); }else{ temp=new ToContainer(tag.tagname,tag.tagvalues[0],lastProduct); } lastProduct->modifiers.push_back(temp); } } } } Reaction::~Reaction(){ for(auto i : reagents) delete i; for(auto i : products) delete i; } void Reaction::print(std::ostream& o)const{ o<<"Reaction:"<<id<<"("<<name<<")"<<std::endl; o<<"\t"<<building.name<<std::endl; o<<"\t"<<building.key<<std::endl; o<<"\t"<<(fuel?"Requires fuel":"Requires no fuel")<<std::endl; o<<"\t"<<(automatic?"Occurs automatically":"Requires manual assignment")<<std::endl; o<<"\t"<<(adventure?"Meant for adventure mode":"Meant for fortress mode")<<std::endl; o<<"\t"<<"REAGENTS:"<<std::endl; for(auto i : reagents) i->print(o); o<<"\t"<<"PRODUCTS:"<<std::endl; for(auto i : products) i->print(o); } /** *Product stuff here */ Product::Product(){} Product::Product(Reaction *p,const RawTag& tag){ const std::vector<std::string>& values=tag.tagvalues; probability = std::stoi(values[0]); quantity = std::stoi(values[1]); item.type=values[2]; item.subtype=values[3]; if(values[4]=="GET_MATERIAL_FROM_REAGENT"){ material=new derived_mat(values[5],p); }else{ material =new known_mat(values[4],values[5],p); } } Product::~Product(){ delete material; for(auto i : modifiers) delete i; } void Product::print(std::ostream& o)const{ o<<probability<<" out of 100 chance to produce "<<quantity<<"units of"<<std::endl; o<<"\t\t\t"; item.print(o); o<<std::endl; o<<"\t\t\t"; material->print(o); o<<std::endl; for(auto i : modifiers){ o<<"\t\t\t\t"; i->print(o); o<<std::endl; } } /** *Reagent modifier stuff */ ReagentModifier::ReagentModifier(const std::string& first,Reagent* par):parent(par),first(first){} TwoPartMod::TwoPartMod(const std::string& first,const std::string& second,Reagent* par):ReagentModifier(first,parent),second(second){} void ReagentModifier::print(std::ostream& o)const{ o<<first<<std::endl; } void TwoPartMod::print(std::ostream& o)const{ o<<first<<" "<<second<<std::endl; }
jaked122/dftools
src/reaction.cpp
C++
mit
5,813
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "VertiCoinrpc.h" using namespace json_spirit; using namespace std; extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out); Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); GenerateVertiCoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "VertiCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "VertiCoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlock.push_back(pblock); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"budget\" : required outputs of the coinbase transaction" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "VertiCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "VertiCoin is downloading blocks..."); static CReserveKey reservekey(pwalletMain); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblock) { delete pblock; pblock = NULL; } pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; CTxDB txdb("r"); BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { mpq nFee = tx.GetValueIn(mapInputs) - tx.GetValueOut(); entry.push_back(Pair("fee", FormatMoney(nFee))); Array deps; BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs) { if (setTxIndex.count(inp.first)) deps.push_back(setTxIndex[inp.first]); } entry.push_back(Pair("depends", deps)); int64_t nSigOps = tx.GetLegacySigOpCount(); nSigOps += tx.GetP2SHSigOpCount(mapInputs); entry.push_back(Pair("sigops", nSigOps)); } transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); Array aBudget; BOOST_FOREACH(const CTxOut& txout, pblock->vtx[0].vout) { if ( txout != pblock->vtx[0].vout[0] ) { Object entry, script; ScriptPubKeyToJSON(txout.scriptPubKey, script); entry.push_back(Pair("scriptPubKey", script)); entry.push_back(Pair("value", (int64_t)txout.nValue)); aBudget.push_back(entry); } } result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("budget", aBudget)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock block; try { ssBlock >> block; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } bool fAccepted = ProcessBlock(NULL, &block); if (!fAccepted) return "rejected"; return Value::null; }
verticoin/verticoin
src/rpcmining.cpp
C++
mit
14,356
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { SkyDefinitionListModule } from '../definition-list.module'; import { SkyDefinitionListTestComponent } from './definition-list.component.fixture'; @NgModule({ declarations: [SkyDefinitionListTestComponent], imports: [CommonModule, SkyDefinitionListModule], exports: [SkyDefinitionListTestComponent], }) export class SkyDefinitionListFixturesModule {}
blackbaud/skyux
libs/components/layout/src/lib/modules/definition-list/fixtures/definition-list-fixtures.module.ts
TypeScript
mit
458
<?php /* * Namespaces: ['_global', 'app', 'auth', 'cache', 'config','db','event', 'key', 'schedule', 'route', 'session', 'vendor', 'view', 'migrate', 'queue', 'make'] * Commands: ['cache:clear', 'etc...'] */ return [ // hide from list 'hide' => [ 'commands' => [ ], 'namespaces' => [ ], ], // disable commands 'disable' => [ 'commands' => [ ], 'namespaces' => [ ], ], // disable commands when app.debug is false 'debug' => [ 'commands' => [ ], 'namespaces' => [ ], ] ];
laradic/console
config/laradic.console.php
PHP
mit
571
THEANO_FLAGS=device=gpu,floatX=float32,cuda.root=/usr/local/cuda/bin python train.py size64 kbasic
skyfallen/SecondDataScienceBowl
Code/Forum_code/Keras/train.sh
Shell
mit
99
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * structs.h * * This header file contains all the structs used in the ISAC codec * */ #ifndef MODULES_AUDIO_CODING_CODECS_ISAC_MAIN_SOURCE_STRUCTS_H_ #define MODULES_AUDIO_CODING_CODECS_ISAC_MAIN_SOURCE_STRUCTS_H_ #include BOSS_WEBRTC_U_modules__audio_coding__codecs__isac__bandwidth_info_h //original-code:"modules/audio_coding/codecs/isac/bandwidth_info.h" #include BOSS_WEBRTC_U_modules__audio_coding__codecs__isac__main__source__settings_h //original-code:"modules/audio_coding/codecs/isac/main/source/settings.h" #include BOSS_WEBRTC_U_modules__third_party__fft__fft_h //original-code:"modules/third_party/fft/fft.h" typedef struct Bitstreamstruct { uint8_t stream[STREAM_SIZE_MAX]; uint32_t W_upper; uint32_t streamval; uint32_t stream_index; } Bitstr; typedef struct { double DataBufferLo[WINLEN]; double DataBufferHi[WINLEN]; double CorrBufLo[ORDERLO + 1]; double CorrBufHi[ORDERHI + 1]; float PreStateLoF[ORDERLO + 1]; float PreStateLoG[ORDERLO + 1]; float PreStateHiF[ORDERHI + 1]; float PreStateHiG[ORDERHI + 1]; float PostStateLoF[ORDERLO + 1]; float PostStateLoG[ORDERLO + 1]; float PostStateHiF[ORDERHI + 1]; float PostStateHiG[ORDERHI + 1]; double OldEnergy; } MaskFiltstr; typedef struct { // state vectors for each of the two analysis filters double INSTAT1[2 * (QORDER - 1)]; double INSTAT2[2 * (QORDER - 1)]; double INSTATLA1[2 * (QORDER - 1)]; double INSTATLA2[2 * (QORDER - 1)]; double INLABUF1[QLOOKAHEAD]; double INLABUF2[QLOOKAHEAD]; float INSTAT1_float[2 * (QORDER - 1)]; float INSTAT2_float[2 * (QORDER - 1)]; float INSTATLA1_float[2 * (QORDER - 1)]; float INSTATLA2_float[2 * (QORDER - 1)]; float INLABUF1_float[QLOOKAHEAD]; float INLABUF2_float[QLOOKAHEAD]; /* High pass filter */ double HPstates[HPORDER]; float HPstates_float[HPORDER]; } PreFiltBankstr; typedef struct { // state vectors for each of the two analysis filters double STATE_0_LOWER[2 * POSTQORDER]; double STATE_0_UPPER[2 * POSTQORDER]; /* High pass filter */ double HPstates1[HPORDER]; double HPstates2[HPORDER]; float STATE_0_LOWER_float[2 * POSTQORDER]; float STATE_0_UPPER_float[2 * POSTQORDER]; float HPstates1_float[HPORDER]; float HPstates2_float[HPORDER]; } PostFiltBankstr; typedef struct { // data buffer for pitch filter double ubuf[PITCH_BUFFSIZE]; // low pass state vector double ystate[PITCH_DAMPORDER]; // old lag and gain double oldlagp[1]; double oldgainp[1]; } PitchFiltstr; typedef struct { // data buffer double buffer[PITCH_WLPCBUFLEN]; // state vectors double istate[PITCH_WLPCORDER]; double weostate[PITCH_WLPCORDER]; double whostate[PITCH_WLPCORDER]; // LPC window -> should be a global array because constant double window[PITCH_WLPCWINLEN]; } WeightFiltstr; typedef struct { // for inital estimator double dec_buffer[PITCH_CORR_LEN2 + PITCH_CORR_STEP2 + PITCH_MAX_LAG / 2 - PITCH_FRAME_LEN / 2 + 2]; double decimator_state[2 * ALLPASSSECTIONS + 1]; double hp_state[2]; double whitened_buf[QLOOKAHEAD]; double inbuf[QLOOKAHEAD]; PitchFiltstr PFstr_wght; PitchFiltstr PFstr; WeightFiltstr Wghtstr; } PitchAnalysisStruct; /* Have instance of struct together with other iSAC structs */ typedef struct { /* Previous frame length (in ms) */ int32_t prev_frame_length; /* Previous RTP timestamp from received packet (in samples relative beginning) */ int32_t prev_rec_rtp_number; /* Send timestamp for previous packet (in ms using timeGetTime()) */ uint32_t prev_rec_send_ts; /* Arrival time for previous packet (in ms using timeGetTime()) */ uint32_t prev_rec_arr_ts; /* rate of previous packet, derived from RTP timestamps (in bits/s) */ float prev_rec_rtp_rate; /* Time sinse the last update of the BN estimate (in ms) */ uint32_t last_update_ts; /* Time sinse the last reduction (in ms) */ uint32_t last_reduction_ts; /* How many times the estimate was update in the beginning */ int32_t count_tot_updates_rec; /* The estimated bottle neck rate from there to here (in bits/s) */ int32_t rec_bw; float rec_bw_inv; float rec_bw_avg; float rec_bw_avg_Q; /* The estimated mean absolute jitter value, as seen on this side (in ms) */ float rec_jitter; float rec_jitter_short_term; float rec_jitter_short_term_abs; float rec_max_delay; float rec_max_delay_avg_Q; /* (assumed) bitrate for headers (bps) */ float rec_header_rate; /* The estimated bottle neck rate from here to there (in bits/s) */ float send_bw_avg; /* The estimated mean absolute jitter value, as seen on the other siee (in ms) */ float send_max_delay_avg; // number of packets received since last update int num_pkts_rec; int num_consec_rec_pkts_over_30k; // flag for marking that a high speed network has been // detected downstream int hsn_detect_rec; int num_consec_snt_pkts_over_30k; // flag for marking that a high speed network has // been detected upstream int hsn_detect_snd; uint32_t start_wait_period; int in_wait_period; int change_to_WB; uint32_t senderTimestamp; uint32_t receiverTimestamp; // enum IsacSamplingRate incomingStreamSampFreq; uint16_t numConsecLatePkts; float consecLatency; int16_t inWaitLatePkts; IsacBandwidthInfo external_bw_info; } BwEstimatorstr; typedef struct { /* boolean, flags if previous packet exceeded B.N. */ int PrevExceed; /* ms */ int ExceedAgo; /* packets left to send in current burst */ int BurstCounter; /* packets */ int InitCounter; /* ms remaining in buffer when next packet will be sent */ double StillBuffered; } RateModel; /* The following strutc is used to store data from encoding, to make it fast and easy to construct a new bitstream with a different Bandwidth estimate. All values (except framelength and minBytes) is double size to handle 60 ms of data. */ typedef struct { /* Used to keep track of if it is first or second part of 60 msec packet */ int startIdx; /* Frame length in samples */ int16_t framelength; /* Pitch Gain */ int pitchGain_index[2]; /* Pitch Lag */ double meanGain[2]; int pitchIndex[PITCH_SUBFRAMES * 2]; /* LPC */ int LPCindex_s[108 * 2]; /* KLT_ORDER_SHAPE = 108 */ int LPCindex_g[12 * 2]; /* KLT_ORDER_GAIN = 12 */ double LPCcoeffs_lo[(ORDERLO + 1) * SUBFRAMES * 2]; double LPCcoeffs_hi[(ORDERHI + 1) * SUBFRAMES * 2]; /* Encode Spec */ int16_t fre[FRAMESAMPLES]; int16_t fim[FRAMESAMPLES]; int16_t AvgPitchGain[2]; /* Used in adaptive mode only */ int minBytes; } IsacSaveEncoderData; typedef struct { int indexLPCShape[UB_LPC_ORDER * UB16_LPC_VEC_PER_FRAME]; double lpcGain[SUBFRAMES << 1]; int lpcGainIndex[SUBFRAMES << 1]; Bitstr bitStreamObj; int16_t realFFT[FRAMESAMPLES_HALF]; int16_t imagFFT[FRAMESAMPLES_HALF]; } ISACUBSaveEncDataStruct; typedef struct { Bitstr bitstr_obj; MaskFiltstr maskfiltstr_obj; PreFiltBankstr prefiltbankstr_obj; PitchFiltstr pitchfiltstr_obj; PitchAnalysisStruct pitchanalysisstr_obj; FFTstr fftstr_obj; IsacSaveEncoderData SaveEnc_obj; int buffer_index; int16_t current_framesamples; float data_buffer_float[FRAMESAMPLES_30ms]; int frame_nb; double bottleneck; int16_t new_framelength; double s2nr; /* Maximum allowed number of bits for a 30 msec packet */ int16_t payloadLimitBytes30; /* Maximum allowed number of bits for a 30 msec packet */ int16_t payloadLimitBytes60; /* Maximum allowed number of bits for both 30 and 60 msec packet */ int16_t maxPayloadBytes; /* Maximum allowed rate in bytes per 30 msec packet */ int16_t maxRateInBytes; /*--- If set to 1 iSAC will not addapt the frame-size, if used in channel-adaptive mode. The initial value will be used for all rates. ---*/ int16_t enforceFrameSize; /*----- This records the BWE index the encoder injected into the bit-stream. It will be used in RCU. The same BWE index of main payload will be in the redundant payload. We can not retrive it from BWE because it is a recursive procedure (WebRtcIsac_GetDownlinkBwJitIndexImpl) and has to be called only once per each encode. -----*/ int16_t lastBWIdx; } ISACLBEncStruct; typedef struct { Bitstr bitstr_obj; MaskFiltstr maskfiltstr_obj; PreFiltBankstr prefiltbankstr_obj; FFTstr fftstr_obj; ISACUBSaveEncDataStruct SaveEnc_obj; int buffer_index; float data_buffer_float[MAX_FRAMESAMPLES + LB_TOTAL_DELAY_SAMPLES]; double bottleneck; /* Maximum allowed number of bits for a 30 msec packet */ // int16_t payloadLimitBytes30; /* Maximum allowed number of bits for both 30 and 60 msec packet */ // int16_t maxPayloadBytes; int16_t maxPayloadSizeBytes; double lastLPCVec[UB_LPC_ORDER]; int16_t numBytesUsed; int16_t lastJitterInfo; } ISACUBEncStruct; typedef struct { Bitstr bitstr_obj; MaskFiltstr maskfiltstr_obj; PostFiltBankstr postfiltbankstr_obj; PitchFiltstr pitchfiltstr_obj; FFTstr fftstr_obj; } ISACLBDecStruct; typedef struct { Bitstr bitstr_obj; MaskFiltstr maskfiltstr_obj; PostFiltBankstr postfiltbankstr_obj; FFTstr fftstr_obj; } ISACUBDecStruct; typedef struct { ISACLBEncStruct ISACencLB_obj; ISACLBDecStruct ISACdecLB_obj; } ISACLBStruct; typedef struct { ISACUBEncStruct ISACencUB_obj; ISACUBDecStruct ISACdecUB_obj; } ISACUBStruct; /* This struct is used to take a snapshot of the entropy coder and LPC gains right before encoding LPC gains. This allows us to go back to that state if we like to limit the payload size. */ typedef struct { /* 6 lower-band & 6 upper-band */ double loFiltGain[SUBFRAMES]; double hiFiltGain[SUBFRAMES]; /* Upper boundary of interval W */ uint32_t W_upper; uint32_t streamval; /* Index to the current position in bytestream */ uint32_t stream_index; uint8_t stream[3]; } transcode_obj; typedef struct { // TODO(kwiberg): The size of these tables could be reduced by storing floats // instead of doubles, and by making use of the identity cos(x) = // sin(x+pi/2). They could also be made global constants that we fill in at // compile time. double costab1[FRAMESAMPLES_HALF]; double sintab1[FRAMESAMPLES_HALF]; double costab2[FRAMESAMPLES_QUARTER]; double sintab2[FRAMESAMPLES_QUARTER]; } TransformTables; typedef struct { // lower-band codec instance ISACLBStruct instLB; // upper-band codec instance ISACUBStruct instUB; // Bandwidth Estimator and model for the rate. BwEstimatorstr bwestimator_obj; RateModel rate_data_obj; double MaxDelay; /* 0 = adaptive; 1 = instantaneous */ int16_t codingMode; // overall bottleneck of the codec int32_t bottleneck; // QMF Filter state int32_t analysisFBState1[FB_STATE_SIZE_WORD32]; int32_t analysisFBState2[FB_STATE_SIZE_WORD32]; int32_t synthesisFBState1[FB_STATE_SIZE_WORD32]; int32_t synthesisFBState2[FB_STATE_SIZE_WORD32]; // Error Code int16_t errorCode; // bandwidth of the encoded audio 8, 12 or 16 kHz enum ISACBandwidth bandwidthKHz; // Sampling rate of audio, encoder and decode, 8 or 16 kHz enum IsacSamplingRate encoderSamplingRateKHz; enum IsacSamplingRate decoderSamplingRateKHz; // Flag to keep track of initializations, lower & upper-band // encoder and decoder. int16_t initFlag; // Flag to to indicate signal bandwidth switch int16_t resetFlag_8kHz; // Maximum allowed rate, measured in Bytes per 30 ms. int16_t maxRateBytesPer30Ms; // Maximum allowed payload-size, measured in Bytes. int16_t maxPayloadSizeBytes; /* The expected sampling rate of the input signal. Valid values are 16000 * and 32000. This is not the operation sampling rate of the codec. */ uint16_t in_sample_rate_hz; // Trig tables for WebRtcIsac_Time2Spec and WebRtcIsac_Spec2time. TransformTables transform_tables; } ISACMainStruct; #endif /* MODULES_AUDIO_CODING_CODECS_ISAC_MAIN_SOURCE_STRUCTS_H_ */
koobonil/Boss2D
Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/audio_coding/codecs/isac/main/source/structs.h
C
mit
12,672
///////////////////////////////////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014-2015 Keld Oelykke // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ///////////////////////////////////////////////////////////////////////////////////////// package starkcoder.failfast.checks.objects.strings; import starkcoder.failfast.checks.ICheck; import starkcoder.failfast.checks.NCheck; import starkcoder.failfast.fails.objects.strings.IObjectStringLessFail; /** * Specifies a less check for String. * * @author Keld Oelykke */ public interface IObjectStringLessCheck extends ICheck { /** * Checks if references are not nulls and A < B. * * @param caller * end-user instance initiating the check * @param referenceA * reference to check against reference B * @param referenceB * argument to check against reference A * @return true, if references are not null and A < B, otherwise false * @throws IllegalArgumentException * if caller is null */ @NCheck(failSpecificationType = IObjectStringLessFail.class) boolean isStringLess(Object caller, String referenceA, String referenceB); }
KeldOelykke/FailFast
Java/FailFast/src/starkcoder/failfast/checks/objects/strings/IObjectStringLessCheck.java
Java
mit
2,254
-- phpMyAdmin SQL Dump -- version 4.2.12deb2+deb8u2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Nov 18, 2016 at 10:18 PM -- Server version: 5.5.53-0+deb8u1 -- PHP Version: 5.6.27-0+deb8u1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `tatui` -- CREATE DATABASE IF NOT EXISTS `tatui` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `tatui`; -- -------------------------------------------------------- -- -- Table structure for table `access_type` -- -- Creation: Nov 14, 2016 at 08:45 PM -- DROP TABLE IF EXISTS `access_type`; CREATE TABLE IF NOT EXISTS `access_type` ( `user_id` varchar(64) NOT NULL, `access_type` varchar(24) NOT NULL, `added_by_id` varchar(64) NOT NULL, `date_changed` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `access_type` -- INSERT INTO `access_type` (`user_id`, `access_type`, `added_by_id`, `date_changed`) VALUES ('admin@rmit.edu.au', 'admin', 'admin@rmit.edu.au', NULL), ('john.long@student.rmit.edu.au', 'student', 'admin@rmit.edu.au', '0000-00-00 00:00:00'), ('lecturer@rmit.edu.au', 'admin', 'admin@rmit.edu.au', '2016-11-15 07:28:38'), ('s1234567@student.rmit.edu.au', 'none', 'admin@rmit.edu.au', '0000-00-00 00:00:00'), ('s1348704@student.rmit.edu.au', 'none', 'admin@rmit.edu.au', '0000-00-00 00:00:00'), ('s5555555@student.rmit.edu.au', 'none', 'admin@rmit.edu.au', '0000-00-00 00:00:00'), ('s7482747@student.rmit.edu.au', 'lecturer', 'admin@rmit.edu.au', '2016-11-15 07:28:59'), ('s7744477@student.rmit.edu.au', 'student', 'admin@rmit.edu.au', '0000-00-00 00:00:00'), ('student@student.rmit.edu.au', 'student', 'admin@rmit.edu.au', NULL); -- -------------------------------------------------------- -- -- Table structure for table `course` -- -- Creation: Nov 09, 2016 at 07:33 AM -- DROP TABLE IF EXISTS `course`; CREATE TABLE IF NOT EXISTS `course` ( `course_id` varchar(32) NOT NULL, `course_name` varchar(32) NOT NULL, `course_description` varchar(45) DEFAULT NULL, `campus` varchar(32) NOT NULL, `study_loading` varchar(32) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `course` -- INSERT INTO `course` (`course_id`, `course_name`, `course_description`, `campus`, `study_loading`) VALUES ('BC', 'Bachelor of Communication', 'Bachelor of Communication', '', NULL), ('BT_FT', 'Bachelor of Technology - Full Ti', 'Bachelor of Technology in computing studies', 'Melbourne', 'Full Time'), ('BT_PT', 'Bachelor of Technology - Part Ti', 'Bachelor of Technology in computing studies', 'Melbourne', 'Full Time'); -- -------------------------------------------------------- -- -- Table structure for table `course_student` -- -- Creation: Nov 12, 2016 at 09:15 PM -- DROP TABLE IF EXISTS `course_student`; CREATE TABLE IF NOT EXISTS `course_student` ( `course_id` varchar(32) NOT NULL, `user_id` varchar(64) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `course_subject` -- -- Creation: Nov 09, 2016 at 07:33 AM -- DROP TABLE IF EXISTS `course_subject`; CREATE TABLE IF NOT EXISTS `course_subject` ( `course_id` varchar(32) NOT NULL, `subject_id` varchar(32) NOT NULL, `semester_id` varchar(32) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `course_subject` -- INSERT INTO `course_subject` (`course_id`, `subject_id`, `semester_id`) VALUES ('BT_FT', 'CPT112', ''), ('BT_FT', 'CPT330', ''), ('ASFDFAS', 'sdf', ''), ('BT_FT', 'cpt111', ''); -- -------------------------------------------------------- -- -- Table structure for table `project` -- -- Creation: Nov 14, 2016 at 08:46 PM -- DROP TABLE IF EXISTS `project`; CREATE TABLE IF NOT EXISTS `project` ( `project_id` varchar(32) NOT NULL, `project_name` varchar(32) DEFAULT NULL, `project_desc` varchar(255) DEFAULT NULL, `course_id` varchar(32) DEFAULT NULL, `subject_id` varchar(32) DEFAULT NULL, `start_date` datetime DEFAULT NULL, `finish_date` datetime DEFAULT NULL, `team_size` int(11) DEFAULT NULL, `date_changed` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `project` -- INSERT INTO `project` (`project_id`, `project_name`, `project_desc`, `course_id`, `subject_id`, `start_date`, `finish_date`, `team_size`, `date_changed`) VALUES ('ADFS', 'Afsd', '', '', '', '1970-01-01 00:00:00', '1970-01-01 00:00:00', 0, NULL), ('GROUP 10', 'Test Red', '', 'BT_FT', NULL, '2016-11-03 00:00:00', '2016-11-29 00:00:00', 4, NULL), ('GROUP 11', 'Android App Project', '', 'BT_FT', 'CPT330', '2016-11-01 00:00:00', '2016-11-30 00:00:00', 4, NULL), ('GROUP 12', 'Algorithm Team', '', 'BT_FT', 'CPT112', '2016-11-01 00:00:00', '2016-11-02 00:00:00', 4, NULL), ('GROUP 13', 'App Group', '', '', '', '1970-01-01 00:00:00', '1970-01-01 00:00:00', 4, NULL), ('GROUP 4', 'Test Red', '', 'BT_FT', 'CPT112', '2016-11-03 00:00:00', '2016-11-29 00:00:00', 4, NULL), ('GROUP 5', 'Blue Test', '', 'BT_FT', 'CPT330', '2016-11-01 00:00:00', '2016-11-27 00:00:00', 4, NULL), ('GROUP 6', 'Red Test', '', 'BT_FT', 'CPT330', '2016-11-01 00:00:00', '2016-11-27 00:00:00', 4, NULL), ('GROUP 9', 'Team Test', '', 'BT_FT', 'CPT330', '2016-11-02 00:00:00', '2016-11-02 00:00:00', 4, NULL), ('group1_2015', 'Team Allocation Tool', 'A tool that allocates teams based on skill levels', 'BT_FT', 'CPT000', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 10, NULL), ('PRO122', 'Project 122', '', 'BT_FT', 'CPT112', '2016-11-10 00:00:00', '2016-12-16 00:00:00', 4, NULL), ('PRO123', 'Project 123', '', 'BT_FT', 'CPT112', '2016-11-10 00:00:00', '2016-12-16 00:00:00', 4, NULL); -- -------------------------------------------------------- -- -- Table structure for table `project_skills` -- -- Creation: Nov 09, 2016 at 07:33 AM -- DROP TABLE IF EXISTS `project_skills`; CREATE TABLE IF NOT EXISTS `project_skills` ( `project_id` varchar(32) NOT NULL, `skill_id` varchar(32) DEFAULT NULL, `skill_level` varchar(32) DEFAULT NULL, `date_added` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `project_skills` -- INSERT INTO `project_skills` (`project_id`, `skill_id`, `skill_level`, `date_added`) VALUES ('GROUP 10', 'C++', 'beginner', NULL), ('GROUP 4', 'C++', 'beginner', NULL), ('GROUP 5', 'C++', 'beginner', NULL), ('GROUP 6', 'C++', 'beginner', NULL), ('PRO122', 'C++', 'expert', NULL), ('PRO123', 'C++', 'expert', NULL), ('tat', 'C#', '1', NULL), ('GROUP 11', 'CSS3', 'beginner', NULL), ('GROUP 11', 'HTML', 'beginner', NULL), ('GROUP 11', 'PROG123', 'beginner', NULL), ('GROUP 12', 'C++', 'beginner', NULL), ('GROUP 12', 'CSS3', 'expert', NULL), ('ASDF', '1234', 'beginner', NULL); -- -------------------------------------------------------- -- -- Table structure for table `semester` -- -- Creation: Nov 15, 2016 at 05:09 AM -- DROP TABLE IF EXISTS `semester`; CREATE TABLE IF NOT EXISTS `semester` ( `semester_id` varchar(32) NOT NULL, `start` varchar(32) DEFAULT NULL, `finish` varchar(32) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `semester` -- INSERT INTO `semester` (`semester_id`, `start`, `finish`) VALUES ('FT_1_2016', '29-01-2016', '29-06-2016'), ('FT_2_2016', '04-07-2016', '24-10-2016'), ('PT_1_2016', '29-02-2016', '29-05-2016'), ('PT_2_2016', '30-05-2016', '28-08-2016'), ('PT_3_2016', '29-08-2016', '27-11-2016'), ('PT_4_2016', '28-11-2016', '26-02-2017'); -- -------------------------------------------------------- -- -- Table structure for table `skill_dictionary` -- -- Creation: Nov 17, 2016 at 07:10 AM -- DROP TABLE IF EXISTS `skill_dictionary`; CREATE TABLE IF NOT EXISTS `skill_dictionary` ( `skill_id` int(32) NOT NULL, `skill_category` varchar(255) DEFAULT NULL, `skill_description` varchar(255) DEFAULT NULL, `skill_added_by` varchar(32) DEFAULT NULL, `date_changed` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB AUTO_INCREMENT=1266 DEFAULT CHARSET=utf8; -- -- Dumping data for table `skill_dictionary` -- INSERT INTO `skill_dictionary` (`skill_id`, `skill_category`, `skill_description`, `skill_added_by`, `date_changed`) VALUES (1264, 'programming', 'programme', 'admin@test.com', '2016-11-17 07:22:12'), (1265, 'programming', 'programme', NULL, '2016-11-17 07:22:36'); -- -------------------------------------------------------- -- -- Table structure for table `student_preferences` -- -- Creation: Nov 15, 2016 at 08:30 PM -- DROP TABLE IF EXISTS `student_preferences`; CREATE TABLE IF NOT EXISTS `student_preferences` ( `user_id` varchar(32) NOT NULL DEFAULT '', `project_choice_1` varchar(255) DEFAULT NULL, `project_choice_2` varchar(255) DEFAULT NULL, `project_choice_3` varchar(255) DEFAULT NULL, `project_choice_4` varchar(255) DEFAULT NULL, `project_choice_5` varchar(255) DEFAULT NULL, `project_choice_6` varchar(255) DEFAULT NULL, `project_choice_7` varchar(255) DEFAULT NULL, `project_choice_8` varchar(255) DEFAULT NULL, `project_choice_9` varchar(255) DEFAULT NULL, `project_choice_10` varchar(255) DEFAULT NULL, `team_member_choice_1` varchar(64) DEFAULT NULL, `team_member_choice_2` varchar(64) DEFAULT NULL, `team_member_choice_3` varchar(64) DEFAULT NULL, `date_changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `student_skill` -- -- Creation: Nov 09, 2016 at 07:33 AM -- DROP TABLE IF EXISTS `student_skill`; CREATE TABLE IF NOT EXISTS `student_skill` ( `user_id` varchar(64) NOT NULL, `skill_id` varchar(32) NOT NULL, `skilllevel` varchar(32) NOT NULL, `date_added` timestamp NULL DEFAULT NULL, `date_changed` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `student_skill` -- INSERT INTO `student_skill` (`user_id`, `skill_id`, `skilllevel`, `date_added`, `date_changed`) VALUES ('1234567@student.rmit.edu.au', 'C#', '1', NULL, NULL); -- -------------------------------------------------------- -- -- Table structure for table `subject` -- -- Creation: Nov 09, 2016 at 07:33 AM -- DROP TABLE IF EXISTS `subject`; CREATE TABLE IF NOT EXISTS `subject` ( `subject_id` varchar(32) NOT NULL, `subject_name` varchar(32) NOT NULL, `subject_description` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `subject` -- INSERT INTO `subject` (`subject_id`, `subject_name`, `subject_description`) VALUES ('CPT000', 'Programming in C#', 'Developement of skills to program in C#'), ('cpt111', 'Test subject', 'Test'), ('CPT112', 'User Centered Design', 'Interface Design'), ('CPT330', 'SE Project Management', 'Project Management '); -- -------------------------------------------------------- -- -- Table structure for table `subject_student` -- -- Creation: Nov 09, 2016 at 07:33 AM -- DROP TABLE IF EXISTS `subject_student`; CREATE TABLE IF NOT EXISTS `subject_student` ( `user_id` varchar(64) NOT NULL, `subject_id` varchar(32) DEFAULT NULL, `subject_mark` varchar(32) DEFAULT NULL, `semester_id` varchar(32) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `user` -- -- Creation: Nov 14, 2016 at 08:44 PM -- DROP TABLE IF EXISTS `user`; CREATE TABLE IF NOT EXISTS `user` ( `user_id` varchar(64) NOT NULL, `password` varchar(32) NOT NULL, `firstname` varchar(32) NOT NULL, `lastname` varchar(32) NOT NULL, `gender` varchar(1) NOT NULL, `location` varchar(32) NOT NULL, `date_changed` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `user` -- INSERT INTO `user` (`user_id`, `password`, `firstname`, `lastname`, `gender`, `location`, `date_changed`) VALUES ('admin@rmit.edu.au', '582a624e4b289', 'Admin', 'User', 'n', 'Sydney', '2016-11-15 01:18:06'), ('john.long@student.rmit.edu.au', '582a624e63849', 'John', 'Long', 'm', 'Sydney', '2016-11-15 01:18:06'), ('lecturer@rmit.edu.au', '582a624e86b72', 'Lecturer', 'User', 'f', 'Sydney', '2016-11-15 01:18:06'), ('s1234567@student.rmit.edu.au', '582a624ea2b9d', 'Jenny', 'Smith', 'f', 'Sydney', '2016-11-15 01:18:06'), ('s1348704@student.rmit.edu.au', '582a624eb4383', 'Adam', 'Haddem', 'm', 'Sydney', '2016-11-15 01:18:06'), ('s5555555@student.rmit.edu.au', '582a624ec1caa', 'Jane', 'Doe', 'f', 'Sydney', '2016-11-15 01:18:06'), ('s7482747@student.rmit.edu.au', '582a624ed899b', 'Gerry', 'Goon', 'm', 'Sydney', '2016-11-15 01:18:06'), ('s7744477@student.rmit.edu.au', '582a624ee52e3', 'Jane', 'Doe', 'f', 'Sydney', '2016-11-15 01:18:06'), ('student@student.rmit.edu.au', '582a624f0266c', 'Jane', 'Doe', 'f', 'Sydney', '2016-11-15 01:18:07'); -- -- Indexes for dumped tables -- -- -- Indexes for table `access_type` -- ALTER TABLE `access_type` ADD PRIMARY KEY (`user_id`); -- -- Indexes for table `course` -- ALTER TABLE `course` ADD PRIMARY KEY (`course_id`); -- -- Indexes for table `project` -- ALTER TABLE `project` ADD PRIMARY KEY (`project_id`); -- -- Indexes for table `semester` -- ALTER TABLE `semester` ADD PRIMARY KEY (`semester_id`); -- -- Indexes for table `skill_dictionary` -- ALTER TABLE `skill_dictionary` ADD PRIMARY KEY (`skill_id`); -- -- Indexes for table `subject` -- ALTER TABLE `subject` ADD PRIMARY KEY (`subject_id`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`user_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `skill_dictionary` -- ALTER TABLE `skill_dictionary` MODIFY `skill_id` int(32) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1266; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
juliemh/tatui
tatui.sql
SQL
mit
14,328
<?php use Symfony\Component\Routing\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\RequestContext; /** * appDevUrlMatcher * * This class has been auto-generated * by the Symfony Routing Component. */ class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher { /** * Constructor. */ public function __construct(RequestContext $context) { $this->context = $context; } public function match($pathinfo) { $allow = array(); $pathinfo = rawurldecode($pathinfo); $context = $this->context; $request = $this->request; if (0 === strpos($pathinfo, '/_')) { // _wdt if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction',)); } if (0 === strpos($pathinfo, '/_profiler')) { // _profiler_home if (rtrim($pathinfo, '/') === '/_profiler') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_profiler_home'); } return array ( '_controller' => 'web_profiler.controller.profiler:homeAction', '_route' => '_profiler_home',); } if (0 === strpos($pathinfo, '/_profiler/search')) { // _profiler_search if ($pathinfo === '/_profiler/search') { return array ( '_controller' => 'web_profiler.controller.profiler:searchAction', '_route' => '_profiler_search',); } // _profiler_search_bar if ($pathinfo === '/_profiler/search_bar') { return array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', '_route' => '_profiler_search_bar',); } } // _profiler_purge if ($pathinfo === '/_profiler/purge') { return array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', '_route' => '_profiler_purge',); } if (0 === strpos($pathinfo, '/_profiler/i')) { // _profiler_info if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array ( '_controller' => 'web_profiler.controller.profiler:infoAction',)); } // _profiler_import if ($pathinfo === '/_profiler/import') { return array ( '_controller' => 'web_profiler.controller.profiler:importAction', '_route' => '_profiler_import',); } } // _profiler_export if (0 === strpos($pathinfo, '/_profiler/export') && preg_match('#^/_profiler/export/(?P<token>[^/\\.]++)\\.txt$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_export')), array ( '_controller' => 'web_profiler.controller.profiler:exportAction',)); } // _profiler_phpinfo if ($pathinfo === '/_profiler/phpinfo') { return array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', '_route' => '_profiler_phpinfo',); } // _profiler_search_results if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction',)); } // _profiler if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array ( '_controller' => 'web_profiler.controller.profiler:panelAction',)); } // _profiler_router if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array ( '_controller' => 'web_profiler.controller.router:panelAction',)); } // _profiler_exception if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array ( '_controller' => 'web_profiler.controller.exception:showAction',)); } // _profiler_exception_css if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array ( '_controller' => 'web_profiler.controller.exception:cssAction',)); } } if (0 === strpos($pathinfo, '/_configurator')) { // _configurator_home if (rtrim($pathinfo, '/') === '/_configurator') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_configurator_home'); } return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction', '_route' => '_configurator_home',); } // _configurator_step if (0 === strpos($pathinfo, '/_configurator/step') && preg_match('#^/_configurator/step/(?P<index>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_configurator_step')), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',)); } // _configurator_final if ($pathinfo === '/_configurator/final') { return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction', '_route' => '_configurator_final',); } } } if (0 === strpos($pathinfo, '/admin')) { // login if ($pathinfo === '/admin') { return array ( '_controller' => 'Ceb\\UserBundle\\Controller\\SecurityController::loginAction', '_route' => 'login',); } if (0 === strpos($pathinfo, '/admin/log')) { // login_check if ($pathinfo === '/admin/login_check') { return array('_route' => 'login_check'); } // logout if ($pathinfo === '/admin/logout') { return array('_route' => 'logout'); } } } if (0 === strpos($pathinfo, '/No')) { // ceb_contact_contact if ($pathinfo === '/Nous-contacter') { return array ( '_controller' => 'Ceb\\AutreBundle\\Controller\\DefaultController::contactAction', '_route' => 'ceb_contact_contact',); } // ceb_partenaire_homepage if ($pathinfo === '/Nos-partenaires') { return array ( '_controller' => 'Ceb\\AutreBundle\\Controller\\DefaultController::partenaireAction', '_route' => 'ceb_partenaire_homepage',); } } // ceb_present_homepage if ($pathinfo === '/Presentation-entreprise') { return array ( '_controller' => 'Ceb\\AutreBundle\\Controller\\DefaultController::presentationAction', '_route' => 'ceb_present_homepage',); } // ceb_goldbook_homepage if ($pathinfo === '/Livre-d\'or') { return array ( '_controller' => 'Ceb\\GoldbookBundle\\Controller\\DefaultController::indexAction', '_route' => 'ceb_goldbook_homepage',); } if (0 === strpos($pathinfo, '/Travaux-')) { // ceb_photo_homepage if ($pathinfo === '/Travaux-finis') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::Travaux_finiAction', '_route' => 'ceb_photo_homepage',); } // ceb_photo_cuisine if ($pathinfo === '/Travaux-cuisines') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::cuisineAction', '_route' => 'ceb_photo_cuisine',); } // ceb_photo_bain if ($pathinfo === '/Travaux-bains') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::bainAction', '_route' => 'ceb_photo_bain',); } } // ceb_photo_finition if ($pathinfo === '/Details-des-finitions') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::finitionAction', '_route' => 'ceb_photo_finition',); } if (0 === strpos($pathinfo, '/admin')) { if (0 === strpos($pathinfo, '/admin/upload')) { // uploadtravaux_fini if ($pathinfo === '/admin/upload/travaux_fini') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\AdmController::uploadtravaux_finiAction', '_route' => 'uploadtravaux_fini',); } // uploadcuisine if ($pathinfo === '/admin/upload/cuisine') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\AdmController::uploadcuisineAction', '_route' => 'uploadcuisine',); } // uploadbain if ($pathinfo === '/admin/upload/bain') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\AdmController::uploadbainAction', '_route' => 'uploadbain',); } // uploadfinition if ($pathinfo === '/admin/upload/finition') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\AdmController::uploadfinitionAction', '_route' => 'uploadfinition',); } } if (0 === strpos($pathinfo, '/admin/succes')) { // succestravaux_fini if ($pathinfo === '/admin/succestravaux_fini') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\AdmController::succestravaux_finiAction', '_route' => 'succestravaux_fini',); } // succescuisine if ($pathinfo === '/admin/succescuisine') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\AdmController::succescuisineAction', '_route' => 'succescuisine',); } // succesbain if ($pathinfo === '/admin/succesbain') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\AdmController::succesbainAction', '_route' => 'succesbain',); } // succesfinition if ($pathinfo === '/admin/succesfinition') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\AdmController::succesfinitionAction', '_route' => 'succesfinition',); } } // erreur_photo if ($pathinfo === '/admin/erreur') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::erreurAction', '_route' => 'erreur_photo',); } if (0 === strpos($pathinfo, '/admin/delete')) { if (0 === strpos($pathinfo, '/admin/delete/bain')) { // deleteBain if ($pathinfo === '/admin/delete/bain') { return array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::deleteBainAction', '_route' => 'deleteBain',); } // destroyBain if (preg_match('#^/admin/delete/bain/(?P<id>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'destroyBain')), array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::DestroyBainAction',)); } } // destroyCuisine if (0 === strpos($pathinfo, '/admin/delete/cuisine') && preg_match('#^/admin/delete/cuisine/(?P<id>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'destroyCuisine')), array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::DestroyCuisineAction',)); } // destroyFinition if (0 === strpos($pathinfo, '/admin/delete/finition') && preg_match('#^/admin/delete/finition/(?P<id>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'destroyFinition')), array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::DestroyFinitionAction',)); } // destroyTravau if (0 === strpos($pathinfo, '/admin/delete/travau') && preg_match('#^/admin/delete/travau/(?P<id>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'destroyTravau')), array ( '_controller' => 'Ceb\\PhotoBundle\\Controller\\DefaultController::DestroyTravauAction',)); } } } // _welcome if (rtrim($pathinfo, '/') === '') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_welcome'); } return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\WelcomeController::indexAction', '_route' => '_welcome',); } if (0 === strpos($pathinfo, '/demo')) { if (0 === strpos($pathinfo, '/demo/secured')) { if (0 === strpos($pathinfo, '/demo/secured/log')) { if (0 === strpos($pathinfo, '/demo/secured/login')) { // _demo_login if ($pathinfo === '/demo/secured/login') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::loginAction', '_route' => '_demo_login',); } // _security_check if ($pathinfo === '/demo/secured/login_check') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::securityCheckAction', '_route' => '_security_check',); } } // _demo_logout if ($pathinfo === '/demo/secured/logout') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::logoutAction', '_route' => '_demo_logout',); } } if (0 === strpos($pathinfo, '/demo/secured/hello')) { // acme_demo_secured_hello if ($pathinfo === '/demo/secured/hello') { return array ( 'name' => 'World', '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction', '_route' => 'acme_demo_secured_hello',); } // _demo_secured_hello if (preg_match('#^/demo/secured/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction',)); } // _demo_secured_hello_admin if (0 === strpos($pathinfo, '/demo/secured/hello/admin') && preg_match('#^/demo/secured/hello/admin/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello_admin')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloadminAction',)); } } } // _demo if (rtrim($pathinfo, '/') === '/demo') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_demo'); } return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::indexAction', '_route' => '_demo',); } // _demo_hello if (0 === strpos($pathinfo, '/demo/hello') && preg_match('#^/demo/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::helloAction',)); } // _demo_contact if ($pathinfo === '/demo/contact') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::contactAction', '_route' => '_demo_contact',); } } throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); } }
Xiangua/deco_cuis
app/cache/dev/appDevUrlMatcher.php
PHP
mit
18,210
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Coq bench</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../../..">Unstable</a></li> <li><a href=".">8.4.5 / contrib:chinese 8.4.dev</a></li> <li class="active"><a href="">2015-02-05 15:34:43</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="../../../../../about.html">About</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href=".">« Up</a> <h1> contrib:chinese <small> 8.4.dev <span class="label label-warning">Error with dependencies</span> </small> </h1> <p><em><script>document.write(moment("2015-02-05 15:34:43 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2015-02-05 15:34:43 UTC)</em><p> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code># Installed packages for system: base-bigarray base Bigarray library distributed with the OCaml compiler base-threads base Threads library distributed with the OCaml compiler base-unix base Unix library distributed with the OCaml compiler camlp5 6.12 Preprocessor-pretty-printer of OCaml coq 8.4.5 Formal proof management system </code></dd> <dt>Return code</dt> <dd>ruby lint.rb unstable ../unstable/packages/coq:contrib:chinese/coq:contrib:chinese.8.4.dev</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>0</pre></dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code></code></dd> <dt>Return code</dt> <dd>opam install -y --show-action coq:contrib:chinese.8.4.dev coq.8.4.5</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>2</pre></dd> </dl> <p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code></code></dd> <dt>Return code</dt> <dd>true</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>0</pre></dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code></code></dd> <dt>Return code</dt> <dd>ulimit -Sv 2000000; timeout 1 opam install -y --deps-only coq:contrib:chinese.8.4.dev</dd> <dt>Duration</dt> <dd>8 h 49 m</dd> <dt>Output</dt> <dd><pre>1</pre></dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code></code></dd> <dt>Return code</dt> <dd>true</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>0</pre></dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code></code></dd> <dt>Return code</dt> <dd>true</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>0</pre></dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io-old
clean/Linux-x86_64-4.02.1-1.2.0/unstable/8.4.5/contrib:chinese/8.4.dev/2015-02-05_15-34-43.html
HTML
mit
6,078
# HUFFMAN Codificação de Huffman na Linguagem C Para mais informações acesse: https://www.amorim.tk:5052/huff
HuffL01T3R5/HUFFMAN
README.md
Markdown
mit
115
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Dashboard for /var/www/php-memcached</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/nv.d3.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="js/html5shiv.min.js"></script> <script src="js/respond.min.js"></script> <![endif]--> </head> <body> <header> <div class="container"> <div class="row"> <div class="col-md-12"> <ol class="breadcrumb"> <li><a href="index.html">/var/www/php-memcached</a></li> <li class="active">(Dashboard)</li> </ol> </div> </div> </div> </header> <div class="container"> <div class="row"> <div class="col-md-12"> <h2>Classes</h2> </div> </div> <div class="row"> <div class="col-md-6"> <h3>Coverage Distribution</h3> <div id="classCoverageDistribution" style="height: 300px;"> <svg></svg> </div> </div> <div class="col-md-6"> <h3>Complexity</h3> <div id="classComplexity" style="height: 300px;"> <svg></svg> </div> </div> </div> <div class="row"> <div class="col-md-6"> <h3>Insufficient Coverage</h3> <div class="scrollbox"> <table class="table"> <thead> <tr> <th>Class</th> <th class="text-right">Coverage</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <div class="col-md-6"> <h3>Project Risks</h3> <div class="scrollbox"> <table class="table"> <thead> <tr> <th>Class</th> <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th> </tr> </thead> <tbody> </tbody> </table> </div> </div> </div> <div class="row"> <div class="col-md-12"> <h2>Methods</h2> </div> </div> <div class="row"> <div class="col-md-6"> <h3>Coverage Distribution</h3> <div id="methodCoverageDistribution" style="height: 300px;"> <svg></svg> </div> </div> <div class="col-md-6"> <h3>Complexity</h3> <div id="methodComplexity" style="height: 300px;"> <svg></svg> </div> </div> </div> <div class="row"> <div class="col-md-6"> <h3>Insufficient Coverage</h3> <div class="scrollbox"> <table class="table"> <thead> <tr> <th>Method</th> <th class="text-right">Coverage</th> </tr> </thead> <tbody> <tr><td><a href="lib/CMemcached.php.html#198"><abbr title="CMemcached::getServerList">getServerList</a></a></td><td class="text-right">0%</td></tr> <tr><td><a href="lib/CMemcached.php.html#163"><abbr title="CMemcached::addServer">addServer</a></a></td><td class="text-right">50%</td></tr> <tr><td><a href="lib/CMemcached.php.html#110"><abbr title="CMemcached::delete">delete</a></a></td><td class="text-right">87%</td></tr> </tbody> </table> </div> </div> <div class="col-md-6"> <h3>Project Risks</h3> <div class="scrollbox"> <table class="table"> <thead> <tr> <th>Method</th> <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th> </tr> </thead> <tbody> <tr><td><a href="lib/CMemcached.php.html#110"><abbr title="CMemcached::delete">delete</abbr></a></td><td class="text-right">3</td></tr> <tr><td><a href="lib/CMemcached.php.html#163"><abbr title="CMemcached::addServer">addServer</abbr></a></td><td class="text-right">2</td></tr> </tbody> </table> </div> </div> </div> <footer> <hr/> <p> <small>Generated by <a href="http://github.com/sebastianbergmann/php-code-coverage" target="_top">PHP_CodeCoverage 2.0.11</a> using <a href="http://php.net/" target="_top">PHP 5.5.3-1ubuntu2.1</a> and <a href="http://phpunit.de/">PHPUnit 4.2.5</a> at Fri Oct 10 16:10:23 IST 2014.</small> </p> </footer> </div> <script src="js/jquery.min.js" type="text/javascript"></script> <script src="js/bootstrap.min.js" type="text/javascript"></script> <script src="js/holder.js" type="text/javascript"></script> <script src="js/d3.min.js" type="text/javascript"></script> <script src="js/nv.d3.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { nv.addGraph(function() { var chart = nv.models.multiBarChart(); chart.tooltips(false) .showControls(false) .showLegend(false) .reduceXTicks(false) .staggerLabels(true) .yAxis.tickFormat(d3.format('d')); d3.select('#classCoverageDistribution svg') .datum(getCoverageDistributionData([0,0,0,0,0,0,0,0,0,0,1,0], "Class Coverage")) .transition().duration(500).call(chart); nv.utils.windowResize(chart.update); return chart; }); nv.addGraph(function() { var chart = nv.models.multiBarChart(); chart.tooltips(false) .showControls(false) .showLegend(false) .reduceXTicks(false) .staggerLabels(true) .yAxis.tickFormat(d3.format('d')); d3.select('#methodCoverageDistribution svg') .datum(getCoverageDistributionData([1,0,0,0,0,0,1,0,0,1,2,6], "Method Coverage")) .transition().duration(500).call(chart); nv.utils.windowResize(chart.update); return chart; }); function getCoverageDistributionData(data, label) { var labels = [ '0%', '0-10%', '10-20%', '20-30%', '30-40%', '40-50%', '50-60%', '60-70%', '70-80%', '80-90%', '90-100%', '100%' ]; var values = []; $.each(labels, function(key) { values.push({x: labels[key], y: data[key]}); }); return [ { key: label, values: values, color: "#4572A7" } ]; } nv.addGraph(function() { var chart = nv.models.scatterChart() .showDistX(true) .showDistY(true) .showLegend(false) .forceX([0, 100]); chart.scatter.onlyCircles(false); chart.tooltipContent(function(key, y, e, graph) { return '<p>' + graph.point.class + '</p>'; }); chart.xAxis.axisLabel('Code Coverage (in percent)'); chart.yAxis.axisLabel('Cyclomatic Complexity'); d3.select('#classComplexity svg') .datum(getComplexityData([[92.307692307692,40,"<a href=\"lib\/CMemcached.php.html#4\">CMemcached<\/a>"]], 'Class Complexity')) .transition() .duration(500) .call(chart); nv.utils.windowResize(chart.update); return chart; }); nv.addGraph(function() { var chart = nv.models.scatterChart() .showDistX(true) .showDistY(true) .showLegend(false) .forceX([0, 100]); chart.scatter.onlyCircles(false); chart.tooltipContent(function(key, y, e, graph) { return '<p>' + graph.point.class + '</p>'; }); chart.xAxis.axisLabel('Code Coverage (in percent)'); chart.yAxis.axisLabel('Method Complexity'); d3.select('#methodComplexity svg') .datum(getComplexityData([[96.153846153846,16,"<a href=\"lib\/CMemcached.php.html#10\">CMemcached::__construct<\/a>"],[92.307692307692,5,"<a href=\"lib\/CMemcached.php.html#51\">CMemcached::add<\/a>"],[100,3,"<a href=\"lib\/CMemcached.php.html#75\">CMemcached::set<\/a>"],[100,3,"<a href=\"lib\/CMemcached.php.html#90\">CMemcached::get<\/a>"],[87.5,3,"<a href=\"lib\/CMemcached.php.html#110\">CMemcached::delete<\/a>"],[100,2,"<a href=\"lib\/CMemcached.php.html#129\">CMemcached::increment<\/a>"],[100,2,"<a href=\"lib\/CMemcached.php.html#147\">CMemcached::decrement<\/a>"],[50,2,"<a href=\"lib\/CMemcached.php.html#163\">CMemcached::addServer<\/a>"],[100,1,"<a href=\"lib\/CMemcached.php.html#185\">CMemcached::createKey<\/a>"],[100,2,"<a href=\"lib\/CMemcached.php.html#191\">CMemcached::logError<\/a>"],[0,1,"<a href=\"lib\/CMemcached.php.html#198\">CMemcached::getServerList<\/a>"]], 'Method Complexity')) .transition() .duration(500) .call(chart); nv.utils.windowResize(chart.update); return chart; }); function getComplexityData(data, label) { var values = []; $.each(data, function(key) { var value = Math.round(data[key][0]*100) / 100; values.push({ x: value, y: data[key][1], class: data[key][2], size: 0.05, shape: 'diamond' }); }); return [ { key: label, values: values, color: "#4572A7" } ]; } }); </script> </body> </html>
pramodpatil812/php-memcached
unittest/code-coverage/dashboard.html
HTML
mit
8,754
<?php class OrderModel extends CI_Model{ function __construct() { parent::__construct(); $this->load->database(); } function userOrder($request){ $sql = "INSERT INTO nham_order(user_id, order_code, product_id, phone, address, quantity, size) VALUES(?, ?, ?, ?, ?, ?, ?)"; $param["user_id"] = $request["user_id"]; $param["order_code"] = $request["order_code"]; $param["product_id"] = $request["product_id"]; $param["user_phone"] = $request["user_phone"]; $param["address"] = $request["address"]; $param["quantity"] = $request["quantity"]; $param["size"] = $request["size"]; $query = $this->db->query($sql , $param); return ($this->db->affected_rows() != 1) ? false : true; } } ?>
SrunSundy/dernham_API
application/models/OrderModel.php
PHP
mit
760
import { Injectable } from '@angular/core'; import { CanActivate, Router } from '@angular/router'; import { Capabilities } from '../../shared/services/capabilities.service'; import { CurrentUser } from '../../shared/services/current-user.model'; import { ErrorActions } from '../../shared/services/error.service'; @Injectable() export class CollectionGuard implements CanActivate { constructor( private userCan: Capabilities, private currentUser: CurrentUser, private router: Router, private error: ErrorActions) { } canActivate() { if (this.currentUser.loggedIn() && this.userCan.viewCollections()) { return true; } else { if (this.currentUser.loggedIn() && !this.userCan.viewCollections()) { this.error.handle({status: 403}); } else { this.error.handle({status: 401}); } return false; } } }
jimmybillings/wazee
src/client/app/+collection/services/collection-guard.ts
TypeScript
mit
895
using System; using System.Collections.Generic; using System.Linq; using System.Speech.Synthesis; using System.Text; using System.Threading.Tasks; namespace K4W.KinectDrone.Core.Speech { public class Narrator { /// <summary> /// Synth instance /// </summary> private static readonly SpeechSynthesizer _speaker = new SpeechSynthesizer(); /// <summary> /// Speak a certain phrase /// </summary> public static void Speak(string phrase) { _speaker.SpeakAsync(phrase); } } }
KinectingForWindows/GIK-KinectingARDrone
src/K4W.KinectDrone.Core/Speech/Narrator.cs
C#
mit
579
'use strict'; var CanvasRenderer = require('./main'); CanvasRenderer.prototype._prepareImages = function () { // Creating the list of images var imagesToPrepare = []; var symbolList = this._extractor._symbolList; var symbols = this._extractor._symbols; for (var s = 0; s < symbolList.length; s += 1) { var symbolId = symbolList[s]; var symbol = symbols[symbolId]; if (symbol.isImage) { imagesToPrepare.push(symbol.swfObject); } var images = symbol.images; if (images) { for (var i = 0; i < images.length; i += 1) { var imageData = images[i]; imagesToPrepare.push(imageData.image); } } } var nImagesToPrepare = imagesToPrepare.length; if (nImagesToPrepare === 0) { this._renderImages(); return; } var nImagesReady = 0; var self = this; var onWrittenCallBack = function (imageData, imageCanvas) { if (imageCanvas.width > 0 && imageCanvas.height > 0) { self._images[imageData.id] = imageCanvas; } else { console.warn('[CanvasRenderer.prepareImages] Image is empty', imageCanvas.width, imageCanvas.height, imageData.id); } nImagesReady += 1; if (nImagesReady === nImagesToPrepare) { self._renderImages(); } }; for (var i = 0; i < imagesToPrepare.length; i += 1) { this._renderImageToCanvas(imagesToPrepare[i], onWrittenCallBack); } };
Wizcorp/Jeff
src/CanvasRenderer/prepareImages.js
JavaScript
mit
1,315
import {bootstrap} from '/node_modules/angular2/platform/browser' import {AppComponent} from './app.component' bootstrap(AppComponent); /* Copyright 2016 Google Inc. All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at http://angular.io/license */
riczat/anglar
resources/views/app/boot.ts
TypeScript
mit
322
module Mutations class Team::RemoveSlack < BaseMutation null true argument :team_id, ID, required: true, description: 'The ID of the team to update' field :team, Types::TeamType, null: true def resolve(team_id:) team = ::Team.find(team_id) team.slack_team_id = nil team.slack_bot_access_token = nil team.channel_id = nil if team.save {team: team} else return Util::ErrorBuilder.build_errors(context, team.errors) end end end end
kabisa/kudo-o-matic
app/graphql/mutations/team/remove_slack.rb
Ruby
mit
515
<h2>List of patients</h2> <table> <tr> <td> <div style="width:1120px; height: 300px; overflow: scroll;"> <table class="table table-striped"> <thead style="text-align: center"> <tr> <th st-sort="firstname" style="width: 158px">First name</th> <th st-sort="lastName" style="width: 158px">Last name</th> <th st-sort="gender" style="width: 158px">Gender</th> <th st-sort="company" style="width: 158px">Company</th> <th st-sort="job" style="width: 178px">Job</th> <th style="text-align: center; width: 158px%">Treatments</th> <th style="width: 158px"></th> </tr> </thead> <tbody> <tr ng-repeat="patient in patients"> <td>{{patient.firstname}}</td> <td>{{patient.lastName}}</td> <td>{{patient.gender}}</td> <td>{{patient.company}}</td> <td>{{patient.job}}</td> <td style="text-align: center">{{patient.treatment.length}}</td> <td><a ng-href="#/addeditPatient?id={{patient.id}}">Edit</a>&nbsp<a href="#" ng-click="deletePatient(patient.id)">Delete</a></td> </tr> </tbody> </table> </div> </td> <tr> <td> <a href="#/addeditPatient" style="float:right;">Add</a><!--editPatient with no id parameter implies a new patient --> </td> </tr> </table>
euasier/ngbp-first-app
src/app/listPatients/listPatients.tpl.html
HTML
mit
1,786
# zelBees
Zelacks/zelBees
README.md
Markdown
mit
9
import { CommonExtensionWindowState } from "../extension/CommonExtensionState"; /* * Copyright 2019 Simon Edwards <simon@simonzone.com> * * This source code is licensed under the MIT license which is detailed in the LICENSE.txt file. */ export const EVENT_CONTEXT_MENU_REQUEST = "EVENT_CONTEXT_MENU_REQUEST"; export enum ContextMenuType { NORMAL, NEW_TERMINAL_TAB, TERMINAL_TAB, WINDOW_MENU, } export type ExtensionContextOverride = Partial<CommonExtensionWindowState>; export interface ContextMenuRequestEventDetail { x: number; y: number, menuType: ContextMenuType; extensionContextOverride: ExtensionContextOverride; } export function dispatchContextMenuRequest(element: HTMLElement, x: number, y: number, menuType=ContextMenuType.NORMAL, extensionContextOverride: ExtensionContextOverride=null): void { const detail: ContextMenuRequestEventDetail = {x, y, menuType, extensionContextOverride}; const commandPaletteRequestEvent = new CustomEvent(EVENT_CONTEXT_MENU_REQUEST, {bubbles: true, composed: true, detail}); commandPaletteRequestEvent.initCustomEvent(EVENT_CONTEXT_MENU_REQUEST, true, true, detail); element.dispatchEvent(commandPaletteRequestEvent); } export const EVENT_HYPERLINK_CLICK = "EVENT_HYPERLINK_CLICK"; export interface HyperlinkEventDetail { url: string; } export function dispatchHyperlinkClick(element: HTMLElement, url: string): void { const detail: HyperlinkEventDetail = { url }; const hyperlinkClickEvent = new CustomEvent(EVENT_HYPERLINK_CLICK, {bubbles: true, composed: true, detail}); hyperlinkClickEvent.initCustomEvent(EVENT_HYPERLINK_CLICK, true, true, detail); element.dispatchEvent(hyperlinkClickEvent); }
sedwards2009/extraterm
extraterm/src/render_process/command/CommandUtils.ts
TypeScript
mit
1,747
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.aad.security; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; // If "azure.activedirectory.tenant-id" is not configured, // this bean will take effect to disable login. @ConditionalOnMissingBean(AADOAuth2LoginSecurityConfig.class) @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class NoLoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/**") .permitAll(); } }
selvasingh/azure-sdk-for-java
sdk/spring/azure-spring-boot-samples/azure-spring-boot-sample-active-directory-backend/src/main/java/com/azure/aad/security/NoLoginSecurityConfig.java
Java
mit
1,084
# KnownRelativeFilePath Enumeration Additional header content Specifies the known relative item path. **Namespace:**&nbsp;<a href="N_iTin_Export_Model">iTin.Export.Model</a><br />**Assembly:**&nbsp;iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0) ## Syntax **C#**<br /> ``` C# [SerializableAttribute] public enum KnownRelativeFilePath ``` **VB**<br /> ``` VB <SerializableAttribute> Public Enumeration KnownRelativeFilePath ``` ## Members &nbsp;<table><tr><th></th><th>Member name</th><th>Value</th><th>Description</th></tr><tr><td /><td target="F:iTin.Export.Model.KnownRelativeFilePath.Template">**Template**</td><td>0</td><td>Template file.</td></tr><tr><td /><td target="F:iTin.Export.Model.KnownRelativeFilePath.Transform">**Transform**</td><td>1</td><td>Transform file.</td></tr><tr><td /><td target="F:iTin.Export.Model.KnownRelativeFilePath.TransformFileBehaviorDir">**TransformFileBehaviorDir**</td><td>2</td><td>Transform file behavior directory.</td></tr><tr><td /><td target="F:iTin.Export.Model.KnownRelativeFilePath.WriterFilter">**WriterFilter**</td><td>3</td><td>Writer Filter file.</td></tr><tr><td /><td target="F:iTin.Export.Model.KnownRelativeFilePath.Output">**Output**</td><td>4</td><td>Output file.</td></tr></table> ## Remarks \[Missing <remarks> documentation for "T:iTin.Export.Model.KnownRelativeFilePath"\] ## See Also #### Reference <a href="N_iTin_Export_Model">iTin.Export.Model Namespace</a><br />
iAJTin/iExportEngine
source/documentation/iTin.Export.Documentation/Documentation/T_iTin_Export_Model_KnownRelativeFilePath.md
Markdown
mit
1,462
<?php namespace rockunit; use rock\validate\Validate; class JsonTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider providerValid */ public function testValid($input) { $v = Validate::json(); $this->assertTrue($v->validate($input)); } public function testInvalid() { $v = Validate::json(); $this->assertFalse($v->validate("{foo:bar}")); } public function providerValid() { return [ ['2'], ['"abc"'], ['[1,2,3]'], ['["foo", "bar", "number", 1]'], ['{"foo": "bar", "number":1}'], ]; } }
romeOz/rock-validate
tests/JsonTest.php
PHP
mit
657
package com.addonovan.ftcext.testing; import com.addonovan.ftcext.control.Devices; import com.addonovan.ftcext.control.OpMode; import com.addonovan.ftcext.control.Register; import com.addonovan.ftcext.hardware.Motor; import com.addonovan.ftcext.hardware.ToggleServo; import com.addonovan.ftcext.utils.MotorAssembly; import com.addonovan.ftcext.utils.MotorType; import com.qualcomm.robotcore.hardware.DcMotor; @Register( name = "JOpMode" ) public class JOpMode extends OpMode { private boolean isRed = get( "red_team", false ); private double motor_speed = get( "motor_speed", 1.0 ); private DcMotor motor_left = motor( "motor_left" ); // if these values appear in the default configurations, then the FalseHardwareMap works! private long value = get( "long_value", 5 ); private boolean isBlue = get( "blue_team", true ); private Motor motor = Devices.< Motor >get( "motor" ).setAssembly( new MotorAssembly( MotorType.TETRIX, 10.16, 1 ) ); private ToggleServo servo = Devices.get( "toggle" ); @Override public void init() { } @Override public void loop() { } }
addonovan/ftc-ext
FtcRobotController/src/main/java/com/addonovan/ftcext/testing/JOpMode.java
Java
mit
1,139
module.exports = { '1.train.spikes': { display: '01', indicator: 'OGB-1', area: 'V1', source: 'Theis et al., 2016' }, '2.train.spikes': { display: '02', indicator: 'OGB-1', area: 'V1', source: 'Theis et al., 2016' }, '3.train.spikes': { display: '03', indicator: 'GCaMP6s', area: 'V1', source: 'Theis et al., 2016' }, '4.train.spikes': { display: '04', indicator: 'OGB-1', area: 'Retina', source: 'Theis et al., 2016' }, '5.train.spikes': { display: '05', indicator: 'GCaMP6s', area: 'V1', source: 'Theis et al., 2016' }, '6.train.spikes': { display: '06', indicator: 'GCaMP5k', area: 'V1', source: 'Akerboom et al., 2012' }, '7.train.spikes': { display: '07', indicator: 'GCaMP6f', area: 'V1', source: 'Chen et al., 2013' }, '8.train.spikes': { display: '08', indicator: 'GCaMP6s', area: 'V1', source: 'Chen et al., 2013' }, '9.train.spikes': { display: '09', indicator: 'jRCAMP1a', area: 'V1', source: 'Dana et al., 2016' }, '10.train.spikes': { display: '10', indicator: 'jRGECO1a', area: 'V1', source: 'Dana et al., 2016' } }
codeneuro/spikefinder
client/metadata.js
JavaScript
mit
1,229
package org.afm.apath.core; import java.util.function.Predicate; /** * A step is an element of a path. <br> * We make use of nesting interfaces and classes for compactness. * Whenever constructors, attributes, or default methods are required an abstract * class is chosen. * * @author afm * */ public interface Step { /** * Applies this step to a node. * * @param node * node of the provided structure (e.g., DOM node, JSON object * etc.) * @param enclosingPath * path enclosing this step, set by the processor * @param currStepNo * step no of this step within {@code enclosingPath} * @return a single selected node of the provided structure (Object) or an * iteration over nodes (Iterator &lt;Object&gt;) */ public abstract Object applyTo(Object node, Path enclosingPath, int currStepNo); public abstract class ChildrenByName implements Step { public interface Namespace { // for future namespace use } protected Namespace namespace; // to serve XML too, deferred protected String name; public ChildrenByName(String name) { this.name = name; } public ChildrenByName setNamespace(Namespace namespace) { this.namespace = namespace; return this; } @Override public String toString() { return "ChildrenByName(" + name + ")"; } } public abstract class ChildByIndex implements Step { protected int i; public ChildByIndex(int i) { this.i = i; } @Override public String toString() { return "ChildByIndex(" + i + ")"; } } public abstract class AllChildren implements Step { @Override public String toString() { return "AllChildren"; } } public abstract class Descendants implements Step { @Override public String toString() { return "Descendants"; } } /** * String representation of a node. */ public abstract class StringValue implements Step { @Override public String toString() { return "StringValue"; } } public abstract class PredicateEval implements Step { protected Predicate<Object> p; public PredicateEval(Predicate<Object> p) { this.p = p; } @Override public String toString() { return "PredicateEval(" + p + ")"; } } }
a-f-m/apath
src/main/java/org/afm/apath/core/Step.java
Java
mit
2,248
from unittest import TestCase from aq.sqlite_util import connect, create_table, insert_all class TestSqliteUtil(TestCase): def test_dict_adapter(self): with connect(':memory:') as conn: conn.execute('CREATE TABLE foo (foo)') conn.execute('INSERT INTO foo (foo) VALUES (?)', ({'bar': 'blah'},)) values = conn.execute('SELECT * FROM foo').fetchone() self.assertEqual(len(values), 1) self.assertEqual(values[0], '{"bar": "blah"}') def test_create_table(self): with connect(':memory:') as conn: create_table(conn, None, 'foo', ('col1', 'col2')) tables = conn.execute("PRAGMA table_info(\'foo\')").fetchall() self.assertEqual(len(tables), 2) self.assertEqual(tables[0][1], 'col1') self.assertEqual(tables[1][1], 'col2') def test_insert_all(self): class Foo(object): def __init__(self, c1, c2): self.c1 = c1 self.c2 = c2 columns = ('c1', 'c2') values = (Foo(1, 2), Foo(3, 4)) with connect(':memory:') as conn: create_table(conn, None, 'foo', columns) insert_all(conn, None, 'foo', columns, values) rows = conn.execute('SELECT * FROM foo').fetchall() self.assertTrue((1, 2) in rows, '(1, 2) in rows') self.assertTrue((3, 4) in rows, '(3, 4) in rows') def test_json_get_field(self): with connect(':memory:') as conn: json_obj = '{"foo": "bar"}' query = "select json_get('{0}', 'foo')".format(json_obj) self.assertEqual(conn.execute(query).fetchone()[0], 'bar') def test_json_get_index(self): with connect(':memory:') as conn: json_obj = '[1, 2, 3]' query = "select json_get('{0}', 1)".format(json_obj) self.assertEqual(conn.execute(query).fetchone()[0], 2) def test_json_get_field_nested(self): with connect(':memory:') as conn: json_obj = '{"foo": {"bar": "blah"}}' query = "select json_get('{0}', 'foo')".format(json_obj) self.assertEqual(conn.execute(query).fetchone()[0], '{"bar": "blah"}') query = "select json_get(json_get('{0}', 'foo'), 'bar')".format(json_obj) self.assertEqual(conn.execute(query).fetchone()[0], 'blah') def test_json_get_field_of_null(self): with connect(':memory:') as conn: query = "select json_get(NULL, 'foo')" self.assertEqual(conn.execute(query).fetchone()[0], None) def test_json_get_field_of_serialized_null(self): with connect(':memory:') as conn: json_obj = 'null' query = "select json_get('{0}', 'foo')".format(json_obj) self.assertEqual(conn.execute(query).fetchone()[0], None)
lebinh/aq
tests/test_sqlite_util.py
Python
mit
2,855
var etc=require("./etc.js"), msgtype=require("./msgtype.js"); function constructMessage(type,args){ var len=6+args.map(function(a){return 4+a.length;}).reduce(function(a,b){return a+b;},0); var buf=new Buffer(len); //console.log("constructing message with len",len) buf.writeUInt32BE(len,0); buf.writeUInt8(type,4); buf.writeUInt8(args.length,5); var cursor=6; for(var i=0;i<args.length;i++){ if(!(args[i] instanceof Buffer))args[i]=new Buffer(""+args[i]); buf.writeUInt32BE(args[i].length,cursor); cursor+=4; args[i].copy(buf,cursor); cursor+=args[i].length; } //console.log("constructing message with len",len,"result:",buf); return buf; } function parseMessage(buf){ var buflen=buf.length; if(buflen<4)return false; var len=buf.readUInt32BE(0); if(buflen<len)return false; console.log(buf.slice(0,len)); var type=buf.readUInt8(4); var numargs=buf.readUInt8(5); var cursor=6; var args=new Array(numargs),arglen; for(var i=0;i<numargs;i++){ //console.log("pM: i="+i); if(cursor+4>len)return {type:null,args:null,len:len}; arglen=buf.readUInt32BE(cursor); cursor+=4; //console.log("pM: cursor="+cursor); if(cursor+arglen>len)return {type:null,args:null,len:len}; args[i]=new Buffer(arglen); buf.copy(args[i],0,cursor,cursor+arglen); cursor+=arglen; } return {type:type,args:args,len:len}; } function makeBufferedProtocolHandler(onmessage,obj){ var buffer=new Buffer(0); return function(data){ if(typeof data=="string")data=new Buffer(data); //console.log("received",data); //first append new data to buffer var tmp=new Buffer(buffer.length+data.length); if(buffer.length)buffer.copy(tmp); data.copy(tmp,buffer.length); buffer=tmp; //console.log("buffer+data",buffer); //then while there's a message in there do { //try to parse it var messageBuffer=new Buffer(buffer.length); buffer.copy(messageBuffer); var msg=parseMessage(messageBuffer); if(msg==false)return; //more data needed //console.log("messageBuffer",messageBuffer); //console.log("msg.len",msg.len); //replace buffer with the data that's left if(buffer.length-msg.len>0){ tmp=new Buffer(buffer.length-msg.len); buffer.copy(tmp,0,msg.len); buffer=tmp; } else { buffer=new Buffer(0); } //console.log("buffer",buffer); //now all administration is done, we've got ourselves a message if(msg.type==null)throw new Error("Invalid message received!"); onmessage(msg,obj,messageBuffer); } while(buffer.length); }; } module.exports.constructMessage=constructMessage; module.exports.parseMessage=parseMessage; module.exports.makeBufferedProtocolHandler=makeBufferedProtocolHandler;
tomsmeding/gvajnez
netio.js
JavaScript
mit
2,684
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="description" content="$description"> <meta name="keywords" content="mavulp, development, programming"> <meta name="author" content="$if{'members'}[[$members[[$name ]]]]$unless{'members'}[[Mavulp]]"> <meta itemprop="image" content="/img/metaicon.png"> <meta name="viewport" content="width=600, initial-scale=0.675"> <title>Mavulp$if{"title"}[[ - $title]]</title> <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="@mavulp"> <meta name="twitter:creator" content="@mavulp"> <meta name="twitter:title" content="Mavulp"> <meta name="twitter:description" content="$description"> <meta name="twitter:image" content="$url/img/metaicon.png"> <meta name="twitter:domain" content="$url"> <meta name="twitter:url" content="$url"> <meta property="og:url" content="$url"> <link rel="shortcut icon" href="/img/icon.png" type="image/x-icon"> <link rel="icon" href="/img/icon.png" type="image/x-icon"> <link rel="apple-touch-icon" href="/img/apple-icon.png"> <link rel="stylesheet" type="text/css" href="/css/style.css"> <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js" type="text/javascript"></script> <script src="/js/main.js" type="text/javascript"></script> <script src="/js/smoothscroll.js" type="text/javascript"></script> $analytics{[[UA-46439485-10]]} </head>
catlinman/mavulp.com
mavulp.com/templates/snippets/head.html
HTML
mit
1,649
cssx( @media screen and (min-width: `minWidthForMediaQuery`px) { `a().reduce(b)` { `getProperty();`: `a + b / c`%; } } )
krasimir/babylon-plugin-cssx
test/cssx/mixed/35/actual.js
JavaScript
mit
126
SELECT video_id FROM videos WHERE video_id IN ( SELECT video_id FROM gitem_video JOIN group_gitem USING (gitem_id) WHERE group_id = ? ) ORDER BY publish_date DESC;
mattwright324/youtube-comment-suite
src/main/resources/io/mattw/youtube/commentsuite/db/sql/dql_get_video_ids_by_group.sql
SQL
mit
175
#Telvue Akamai Push Plugin The Telvue Akamai push plugin allows for an incoming Wowza stream to be pushed to Akamai via RTMP. The plugin supports multiple stream applications, as well as multiple streams per application. All of the specifics are set up through configuration files. ##Required libraries This plugin requires the Wowza SDK and the PushPublish plugin library `com.wowza.wms.plugin.pushpublish.protocol.rtmp.PushPublisherRTMP` ##How to set up First the code must be compiled and added to a .jar file. That jar file is then copied into the lib directory of the WowzaMediaServer folder for your version of Wowza. After this a folder for each Application stream must be created in the conf directory inside of the main Wowza directory. For example, if you had an application called MyLiveStream, and Wowza was installed at `/usr/local/WowzaMediaServer/` then you would create the directory `/usr/local/WowzaMediaServer/conf/MyLiveStream/`. Inside of this directory you need an Application.xml file. A Sample Application.xml has been made available. The key part to note is the modules tag. Inside of this must be the module for the TelvueAkamaiPushPlugin ``` <Module> <Name>TelvueAkamiPushPlugin</Name> <Description>TelvueAkamiPushPlugin</Description> <Class>com.telvue.wowza.TelvueAkamiPushPlugin</Class> </Module> ``` This module entry is what allows the plugin to work with the incoming application stream. ## Configuration files The plugin was designed to be as generic as possible using configuration files to determine where to push the incoming streams to. ### Configuration file layout The layout of the configuration file is very simple. There are 6 key:value pairs that must be included. ``` AkamaiUsername:username AkamaiPassword:password AkamaiHostName:p.epxxxx.i.akamaientrypoint.net AkamaiDstApplicationName:EntryPoint AkamaiDstStreamName:Stream-Name@xxxx AkamaiPort:1935 ``` #### Optional Configuration Settings These settings are the Wowza recommended settings by default, but are configurable. ``` DebugLogging:true SendStreamCloseCommands:true SendReleaseStream:true SendFcPublish:true AdaptiveStreaming:false ``` All pairs are separated by a single ":" character, and reside on their own lines. All configuration files must be named after their stream names, and have the extension ".cnfg". So if there is a stream called MyStream, the configuration file would be "MyStream.cnfg" ### Configuration directory layout The configuration files are placed into a root directory called pushConfigFiles. This directory will hold folders for each of the applications being streamed into Wowza (Just like the conf directory). If Wowza is installed at `/usr/local/WowzaMediaServer/` then the config file directory is `/usr/local/WowzaMediaServer/pushConfigFiles/` If there is an application called MyLiveStream, and it has 3 streams live1, live2, and live3. Then the directory structure is `/usr/local/WowzaMediaServer/pushConfigFiles/MyLiveStream/` and in this directory are 3 files `live1.cnfg`, `live2.cnfg`, and `live3.cnfg`. Each file has the 6 key:value pairs shown above. ### Changing the base directory It is possible (and necessary if you are not running wowza from /usr/local on a Linux box) to change where the plugin looks for the configuration files. Simply modify line 19 of the TelvueAkamiPushPlugin to the location of the pushConfigFiles directory on your server. Just remember to follow the layout within the pushConfigFiles directory and it will work.
telvue/WowzaAkamaiPushPlugin
README.md
Markdown
mit
3,630
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// TaskQueueStatisticsResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Taskrouter.V1.Workspace.TaskQueue { public class TaskQueueStatisticsResource : Resource { private static Request BuildFetchRequest(FetchTaskQueueStatisticsOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Taskrouter, "/v1/Workspaces/" + options.PathWorkspaceSid + "/TaskQueues/" + options.PathTaskQueueSid + "/Statistics", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch TaskQueueStatistics parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TaskQueueStatistics </returns> public static TaskQueueStatisticsResource Fetch(FetchTaskQueueStatisticsOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch TaskQueueStatistics parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TaskQueueStatistics </returns> public static async System.Threading.Tasks.Task<TaskQueueStatisticsResource> FetchAsync(FetchTaskQueueStatisticsOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the TaskQueue to fetch </param> /// <param name="pathTaskQueueSid"> The SID of the TaskQueue for which to fetch statistics </param> /// <param name="endDate"> Only calculate statistics from on or before this date </param> /// <param name="minutes"> Only calculate statistics since this many minutes in the past </param> /// <param name="startDate"> Only calculate statistics from on or after this date </param> /// <param name="taskChannel"> Only calculate real-time and cumulative statistics for the specified TaskChannel </param> /// <param name="splitByWaitTime"> A comma separated list of values that describes the thresholds to calculate /// statistics on </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TaskQueueStatistics </returns> public static TaskQueueStatisticsResource Fetch(string pathWorkspaceSid, string pathTaskQueueSid, DateTime? endDate = null, int? minutes = null, DateTime? startDate = null, string taskChannel = null, string splitByWaitTime = null, ITwilioRestClient client = null) { var options = new FetchTaskQueueStatisticsOptions(pathWorkspaceSid, pathTaskQueueSid){EndDate = endDate, Minutes = minutes, StartDate = startDate, TaskChannel = taskChannel, SplitByWaitTime = splitByWaitTime}; return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the TaskQueue to fetch </param> /// <param name="pathTaskQueueSid"> The SID of the TaskQueue for which to fetch statistics </param> /// <param name="endDate"> Only calculate statistics from on or before this date </param> /// <param name="minutes"> Only calculate statistics since this many minutes in the past </param> /// <param name="startDate"> Only calculate statistics from on or after this date </param> /// <param name="taskChannel"> Only calculate real-time and cumulative statistics for the specified TaskChannel </param> /// <param name="splitByWaitTime"> A comma separated list of values that describes the thresholds to calculate /// statistics on </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TaskQueueStatistics </returns> public static async System.Threading.Tasks.Task<TaskQueueStatisticsResource> FetchAsync(string pathWorkspaceSid, string pathTaskQueueSid, DateTime? endDate = null, int? minutes = null, DateTime? startDate = null, string taskChannel = null, string splitByWaitTime = null, ITwilioRestClient client = null) { var options = new FetchTaskQueueStatisticsOptions(pathWorkspaceSid, pathTaskQueueSid){EndDate = endDate, Minutes = minutes, StartDate = startDate, TaskChannel = taskChannel, SplitByWaitTime = splitByWaitTime}; return await FetchAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a TaskQueueStatisticsResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> TaskQueueStatisticsResource object represented by the provided JSON </returns> public static TaskQueueStatisticsResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<TaskQueueStatisticsResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// An object that contains the cumulative statistics for the TaskQueue /// </summary> [JsonProperty("cumulative")] public object Cumulative { get; private set; } /// <summary> /// An object that contains the real-time statistics for the TaskQueue /// </summary> [JsonProperty("realtime")] public object Realtime { get; private set; } /// <summary> /// The SID of the TaskQueue from which these statistics were calculated /// </summary> [JsonProperty("task_queue_sid")] public string TaskQueueSid { get; private set; } /// <summary> /// The SID of the Workspace that contains the TaskQueue /// </summary> [JsonProperty("workspace_sid")] public string WorkspaceSid { get; private set; } /// <summary> /// The absolute URL of the TaskQueue statistics resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private TaskQueueStatisticsResource() { } } }
twilio/twilio-csharp
src/Twilio/Rest/Taskrouter/V1/Workspace/TaskQueue/TaskQueueStatisticsResource.cs
C#
mit
8,826
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Collections.Generic { /// <summary> /// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>. /// </summary> internal enum InsertionBehavior : byte { /// <summary> /// The default insertion behavior. /// </summary> None = 0, /// <summary> /// Specifies that an existing entry with the same key should be overwritten if encountered. /// </summary> OverwriteExisting = 1, /// <summary> /// Specifies that if an existing entry with the same key is encountered, an exception should be thrown. /// </summary> ThrowOnExisting = 2 } [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback { private struct Entry { public int hashCode; // Lower 31 bits of hash code, -1 if unused public int next; // Index of next entry, -1 if last public TKey key; // Key of entry public TValue value; // Value of entry } private int[] _buckets; private Entry[] _entries; private int _count; private int _freeList; private int _freeCount; private int _version; private IEqualityComparer<TKey> _comparer; private KeyCollection _keys; private ValueCollection _values; private object _syncRoot; // constants for serialization private const string VersionName = "Version"; // Do not rename (binary serialization) private const string HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length private const string KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization) private const string ComparerName = "Comparer"; // Do not rename (binary serialization) public Dictionary() : this(0, null) { } public Dictionary(int capacity) : this(capacity, null) { } public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { } public Dictionary(int capacity, IEqualityComparer<TKey> comparer) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); if (capacity > 0) Initialize(capacity); if (comparer != EqualityComparer<TKey>.Default) { _comparer = comparer; } if (typeof(TKey) == typeof(string) && _comparer == null) { // To start, move off default comparer for string which is randomised _comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default; } } public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : this(dictionary != null ? dictionary.Count : 0, comparer) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } // It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case, // avoid the enumerator allocation and overhead by looping through the entries array directly. // We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain // back-compat with subclasses that may have overridden the enumerator behavior. if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>)) { Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary; int count = d._count; Entry[] entries = d._entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { Add(entries[i].key, entries[i].value); } } return; } foreach (KeyValuePair<TKey, TValue> pair in dictionary) { Add(pair.Key, pair.Value); } } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer) : this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } foreach (KeyValuePair<TKey, TValue> pair in collection) { Add(pair.Key, pair.Value); } } protected Dictionary(SerializationInfo info, StreamingContext context) { // We can't do anything with the keys and values until the entire graph has been deserialized // and we have a resonable estimate that GetHashCode is not going to fail. For the time being, // we'll just cache this. The graph is not valid until OnDeserialization has been called. HashHelpers.SerializationInfoTable.Add(this, info); } public IEqualityComparer<TKey> Comparer { get { return (_comparer == null || _comparer is NonRandomizedStringEqualityComparer) ? EqualityComparer<TKey>.Default : _comparer; } } public int Count { get { return _count - _freeCount; } } public KeyCollection Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } public ValueCollection Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } public TValue this[TKey key] { get { int i = FindEntry(key); if (i >= 0) return _entries[i].value; ThrowHelper.ThrowKeyNotFoundException(key); return default(TValue); } set { bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting); Debug.Assert(modified); } } public void Add(TKey key, TValue value) { bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting); Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown. } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, keyValuePair.Value)) { Remove(keyValuePair.Key); return true; } return false; } public void Clear() { int count = _count; if (count > 0) { Array.Clear(_buckets, 0, _buckets.Length); _count = 0; _freeList = -1; _freeCount = 0; _version++; Array.Clear(_entries, 0, count); } } public bool ContainsKey(TKey key) { return FindEntry(key) >= 0; } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < _count; i++) { if (_entries[i].hashCode >= 0 && _entries[i].value == null) return true; } } else { for (int i = 0; i < _count; i++) { if (_entries[i].hashCode >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, value)) return true; } } return false; } private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _count; Entry[] entries = _entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } public Enumerator GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue(VersionName, _version); info.AddValue(ComparerName, _comparer ?? EqualityComparer<TKey>.Default, typeof(IEqualityComparer<TKey>)); info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array if (_buckets != null) { var array = new KeyValuePair<TKey, TValue>[Count]; CopyTo(array, 0); info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[])); } } private int FindEntry(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } int i = -1; int[] buckets = _buckets; Entry[] entries = _entries; if (buckets != null) { IEqualityComparer<TKey> comparer = _comparer; if (comparer == null) { int hashCode = key.GetHashCode() & 0x7FFFFFFF; // Value in _buckets is 1-based i = buckets[hashCode % buckets.Length] - 1; do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test in if to drop range check for following array access if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key))) { break; } i = entries[i].next; } while (true); } else { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; // Value in _buckets is 1-based i = buckets[hashCode % buckets.Length] - 1; do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test in if to drop range check for following array access if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))) { break; } i = entries[i].next; } while (true); } } return i; } private int Initialize(int capacity) { int size = HashHelpers.GetPrime(capacity); _freeList = -1; _buckets = new int[size]; _entries = new Entry[size]; return size; } private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (_buckets == null) { Initialize(0); } Entry[] entries = _entries; IEqualityComparer<TKey> comparer = _comparer; int hashCode = ((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key)) & 0x7FFFFFFF; int collisionCount = 0; ref int bucket = ref _buckets[hashCode % _buckets.Length]; // Value in _buckets is 1-based int i = bucket - 1; if (comparer == null) { do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test uint in if rather than loop condition to drop range check for following array access if ((uint)i >= (uint)entries.Length) { break; } if (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key)) { if (behavior == InsertionBehavior.OverwriteExisting) { entries[i].value = value; _version++; return true; } if (behavior == InsertionBehavior.ThrowOnExisting) { ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); } return false; } i = entries[i].next; collisionCount++; } while (true); } else { do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test uint in if rather than loop condition to drop range check for following array access if ((uint)i >= (uint)entries.Length) { break; } if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (behavior == InsertionBehavior.OverwriteExisting) { entries[i].value = value; _version++; return true; } if (behavior == InsertionBehavior.ThrowOnExisting) { ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); } return false; } i = entries[i].next; collisionCount++; } while (true); } // Can be improved with "Ref Local Reassignment" // https://github.com/dotnet/csharplang/blob/master/proposals/ref-local-reassignment.md bool resized = false; bool updateFreeList = false; int index; if (_freeCount > 0) { index = _freeList; updateFreeList = true; _freeCount--; } else { int count = _count; if (count == entries.Length) { Resize(); resized = true; } index = count; _count = count + 1; entries = _entries; } ref int targetBucket = ref resized ? ref _buckets[hashCode % _buckets.Length] : ref bucket; ref Entry entry = ref entries[index]; if (updateFreeList) { _freeList = entry.next; } entry.hashCode = hashCode; // Value in _buckets is 1-based entry.next = targetBucket - 1; entry.key = key; entry.value = value; // Value in _buckets is 1-based targetBucket = index + 1; _version++; // Value types never rehash if (default(TKey) == null && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer) { // If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing // i.e. EqualityComparer<string>.Default. _comparer = null; Resize(entries.Length, true); } return true; } public virtual void OnDeserialization(object sender) { SerializationInfo siInfo; HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo); if (siInfo == null) { // We can return immediately if this function is called twice. // Note we remove the serialization info from the table at the end of this method. return; } int realVersion = siInfo.GetInt32(VersionName); int hashsize = siInfo.GetInt32(HashSizeName); _comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>)); if (hashsize != 0) { Initialize(hashsize); KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[]) siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[])); if (array == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys); } for (int i = 0; i < array.Length; i++) { if (array[i].Key == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey); } Add(array[i].Key, array[i].Value); } } else { _buckets = null; } _version = realVersion; HashHelpers.SerializationInfoTable.Remove(this); } private void Resize() { Resize(HashHelpers.ExpandPrime(_count), false); } private void Resize(int newSize, bool forceNewHashCodes) { // Value types never rehash Debug.Assert(!forceNewHashCodes || default(TKey) == null); Debug.Assert(newSize >= _entries.Length); int[] buckets = new int[newSize]; Entry[] entries = new Entry[newSize]; int count = _count; Array.Copy(_entries, 0, entries, 0, count); if (default(TKey) == null && forceNewHashCodes) { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { Debug.Assert(_comparer == null); entries[i].hashCode = (entries[i].key.GetHashCode() & 0x7FFFFFFF); } } } for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { int bucket = entries[i].hashCode % newSize; // Value in _buckets is 1-based entries[i].next = buckets[bucket] - 1; // Value in _buckets is 1-based buckets[bucket] = i + 1; } } _buckets = buckets; _entries = entries; } // The overload Remove(TKey key, out TValue value) is a copy of this method with one additional // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. public bool Remove(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (_buckets != null) { int hashCode = (_comparer?.GetHashCode(key) ?? key.GetHashCode()) & 0x7FFFFFFF; int bucket = hashCode % _buckets.Length; int last = -1; // Value in _buckets is 1-based int i = _buckets[bucket] - 1; while (i >= 0) { ref Entry entry = ref _entries[i]; if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key))) { if (last < 0) { // Value in _buckets is 1-based _buckets[bucket] = entry.next + 1; } else { _entries[last].next = entry.next; } entry.hashCode = -1; entry.next = _freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { entry.key = default(TKey); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { entry.value = default(TValue); } _freeList = i; _freeCount++; _version++; return true; } last = i; i = entry.next; } } return false; } // This overload is a copy of the overload Remove(TKey key) with one additional // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. public bool Remove(TKey key, out TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (_buckets != null) { int hashCode = (_comparer?.GetHashCode(key) ?? key.GetHashCode()) & 0x7FFFFFFF; int bucket = hashCode % _buckets.Length; int last = -1; // Value in _buckets is 1-based int i = _buckets[bucket] - 1; while (i >= 0) { ref Entry entry = ref _entries[i]; if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key))) { if (last < 0) { // Value in _buckets is 1-based _buckets[bucket] = entry.next + 1; } else { _entries[last].next = entry.next; } value = entry.value; entry.hashCode = -1; entry.next = _freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { entry.key = default(TKey); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { entry.value = default(TValue); } _freeList = i; _freeCount++; _version++; return true; } last = i; i = entry.next; } } value = default(TValue); return false; } public bool TryGetValue(TKey key, out TValue value) { int i = FindEntry(key); if (i >= 0) { value = _entries[i].value; return true; } value = default(TValue); return false; } public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None); bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { CopyTo(array, index); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { CopyTo(pairs, index); } else if (array is DictionaryEntry[]) { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; Entry[] entries = _entries; for (int i = 0; i < _count; i++) { if (entries[i].hashCode >= 0) { dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value); } } } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } try { int count = _count; Entry[] entries = _entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } /// <summary> /// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage /// </summary> public int EnsureCapacity(int capacity) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); int currentCapacity = _entries == null ? 0 : _entries.Length; if (currentCapacity >= capacity) return currentCapacity; if (_buckets == null) return Initialize(capacity); int newSize = HashHelpers.GetPrime(capacity); Resize(newSize, forceNewHashCodes: false); return newSize; } /// <summary> /// Sets the capacity of this dictionary to what it would be if it had been originally initialized with all its entries /// /// This method can be used to minimize the memory overhead /// once it is known that no new elements will be added. /// /// To allocate minimum size storage array, execute the following statements: /// /// dictionary.Clear(); /// dictionary.TrimExcess(); /// </summary> public void TrimExcess() { TrimExcess(Count); } /// <summary> /// Sets the capacity of this dictionary to hold up 'capacity' entries without any further expansion of its backing storage /// /// This method can be used to minimize the memory overhead /// once it is known that no new elements will be added. /// </summary> public void TrimExcess(int capacity) { if (capacity < Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); int newSize = HashHelpers.GetPrime(capacity); Entry[] oldEntries = _entries; int currentCapacity = oldEntries == null ? 0 : oldEntries.Length; if (newSize >= currentCapacity) return; int oldCount = _count; Initialize(newSize); Entry[] entries = _entries; int[] buckets = _buckets; int count = 0; for (int i = 0; i < oldCount; i++) { int hashCode = oldEntries[i].hashCode; if (hashCode >= 0) { ref Entry entry = ref entries[count]; entry = oldEntries[i]; int bucket = hashCode % newSize; // Value in _buckets is 1-based entry.next = buckets[bucket] - 1; // Value in _buckets is 1-based buckets[bucket] = count + 1; count++; } } _count = count; _freeCount = 0; } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } ICollection IDictionary.Keys { get { return (ICollection)Keys; } } ICollection IDictionary.Values { get { return (ICollection)Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { int i = FindEntry((TKey)key); if (i >= 0) { return _entries[i].value; } } return null; } set { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } } private static bool IsCompatibleKey(object key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return (key is TKey); } void IDictionary.Add(object key, object value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { Add(tempKey, (TValue)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private Dictionary<TKey, TValue> _dictionary; private int _version; private int _index; private KeyValuePair<TKey, TValue> _current; private int _getEnumeratorRetType; // What should Enumerator.Current return? internal const int DictEntry = 1; internal const int KeyValuePair = 2; internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType) { _dictionary = dictionary; _version = dictionary._version; _index = 0; _getEnumeratorRetType = getEnumeratorRetType; _current = new KeyValuePair<TKey, TValue>(); } public bool MoveNext() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries[_index++]; if (entry.hashCode >= 0) { _current = new KeyValuePair<TKey, TValue>(entry.key, entry.value); return true; } } _index = _dictionary._count + 1; _current = new KeyValuePair<TKey, TValue>(); return false; } public KeyValuePair<TKey, TValue> Current { get { return _current; } } public void Dispose() { } object IEnumerator.Current { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } if (_getEnumeratorRetType == DictEntry) { return new System.Collections.DictionaryEntry(_current.Key, _current.Value); } else { return new KeyValuePair<TKey, TValue>(_current.Key, _current.Value); } } } void IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _current = new KeyValuePair<TKey, TValue>(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return new DictionaryEntry(_current.Key, _current.Value); } } object IDictionaryEnumerator.Key { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _current.Key; } } object IDictionaryEnumerator.Value { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _current.Value; } } } [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private Dictionary<TKey, TValue> _dictionary; public KeyCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } _dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(_dictionary); } public void CopyTo(TKey[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _dictionary._count; Entry[] entries = _dictionary._entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].key; } } public int Count { get { return _dictionary.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } void ICollection<TKey>.Add(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Contains(TKey item) { return _dictionary.ContainsKey(item); } bool ICollection<TKey>.Remove(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); return false; } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return new Enumerator(_dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } TKey[] keys = array as TKey[]; if (keys != null) { CopyTo(keys, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = _dictionary._count; Entry[] entries = _dictionary._entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].key; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dictionary).SyncRoot; } } public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> _dictionary; private int _index; private int _version; private TKey _currentKey; internal Enumerator(Dictionary<TKey, TValue> dictionary) { _dictionary = dictionary; _version = dictionary._version; _index = 0; _currentKey = default(TKey); } public void Dispose() { } public bool MoveNext() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries[_index++]; if (entry.hashCode >= 0) { _currentKey = entry.key; return true; } } _index = _dictionary._count + 1; _currentKey = default(TKey); return false; } public TKey Current { get { return _currentKey; } } object System.Collections.IEnumerator.Current { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _currentKey; } } void System.Collections.IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _currentKey = default(TKey); } } } [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private Dictionary<TKey, TValue> _dictionary; public ValueCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } _dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(_dictionary); } public void CopyTo(TValue[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _dictionary._count; Entry[] entries = _dictionary._entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].value; } } public int Count { get { return _dictionary.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } void ICollection<TValue>.Add(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Remove(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); return false; } void ICollection<TValue>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Contains(TValue item) { return _dictionary.ContainsValue(item); } IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() { return new Enumerator(_dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); TValue[] values = array as TValue[]; if (values != null) { CopyTo(values, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = _dictionary._count; Entry[] entries = _dictionary._entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].value; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dictionary).SyncRoot; } } public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> _dictionary; private int _index; private int _version; private TValue _currentValue; internal Enumerator(Dictionary<TKey, TValue> dictionary) { _dictionary = dictionary; _version = dictionary._version; _index = 0; _currentValue = default(TValue); } public void Dispose() { } public bool MoveNext() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries[_index++]; if (entry.hashCode >= 0) { _currentValue = entry.value; return true; } } _index = _dictionary._count + 1; _currentValue = default(TValue); return false; } public TValue Current { get { return _currentValue; } } object System.Collections.IEnumerator.Current { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _currentValue; } } void System.Collections.IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _currentValue = default(TValue); } } } } }
ruben-ayrapetyan/coreclr
src/mscorlib/shared/System/Collections/Generic/Dictionary.cs
C#
mit
56,845
Pauling ======= | General | Android | iOS | |---------|---------|-----| | [![CircleCI](https://circleci.com/gh/TailorDev/pauling/tree/master.svg?style=svg&circle-token=9df05dcadb0db10e2a6385385cbb62e1500a0e9f)](https://circleci.com/gh/TailorDev/pauling/tree/master) | [![BuddyBuild](https://dashboard.buddybuild.com/api/statusImage?appID=59a965b8c5290b0001524019&branch=master&build=latest)](https://dashboard.buddybuild.com/apps/59a965b8c5290b0001524019/build/latest?branch=master) | [![BuddyBuild](https://dashboard.buddybuild.com/api/statusImage?appID=59a96b15b0d15500017f75fd&branch=master&build=latest)](https://dashboard.buddybuild.com/apps/59a96b15b0d15500017f75fd/build/latest?branch=master) Pauling is an open-source solution to get a better experience with scientific posters. Authors share their poster _via_ the Pauling web application and receive a QR code that should be added next to the poster during the session. Conference attendees use the Pauling mobile application to retrieve the poster and all its information on their mobile phone! This application has been built during a "Le lab" session: * https://tailordev.fr/blog/2017/10/04/le-lab-6-pauling-poster-sharing-mobile-app/ <p align="center"> <a href="https://play.google.com/store/apps/details?id=fr.tailordev.pauling"><img width="200" alt="Get it on Google Play" src="https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png"></a> </p> ## Installation ### API (web app) You have to navigate to the `api/` folder first. 1. Install the project dependencies: ``` $ make boostrap ``` 2. Create a `local_settings.py` file with your own settings: ``` py # flask SECRET_KEY = 'Secr3tK3yF0rD3v' # mailer MAIL_SERVER = '127.0.0.1' MAIL_PORT = 15025 MAIL_LOGIN = '' MAIL_PASSWORD = '' MAIL_USE_TLS = False # upload/cdn CLOUDINARY_URL = 'cloudinary://user:pass@account' CLOUDINARY_BASE_URL = 'https://res.cloudinary.com/account' ``` 3. Start the application in development mode: ``` $ make dev ``` 4. Last but not least, apply the database migrations: ``` $ make flask-db-upgrade ``` You can now browse the application at: http://127.0.0.1:5000/. ### Mobile app You have to navigate to the `mobile/` folder first. 1. Be sure to have the [React Native environment installed first](https://facebook.github.io/react-native/docs/getting-started.html), then install the project dependencies: ``` $ make boostrap ``` 2. Start a Android device of your choice. It can be a virtual device (with `emulator`) or a real device connected to your computer: ``` $ emulator @Nexus_5X_API_25_x86 ``` 3. Start the application in development mode (Android): ``` $ make dev ``` #### Sketch file We use [Git LFS](https://git-lfs.github.com/) to track the Sketch files so that the size of the repository does not get to big too fast. Be sure to have it installed :) You can retrieve the files (if you do not have them) by fetching them: ``` $ git lfs fetch ``` ## Contributing Please, see the [CONTRIBUTING](CONTRIBUTING.md) file. ## Contributor Code of Conduct Please note that this project is released with a [Contributor Code of Conduct](http://contributor-covenant.org/). By participating in this project you agree to abide by its terms. See the [CODE_OF_CONDUCT](CODE_OF_CONDUCT.md) file. ## License Pauling is released under the MIT License. See the bundled [LICENSE](LICENSE) file for details.
TailorDev/pauling
README.md
Markdown
mit
3,433
# encoding: utf-8 require 'devise' require 'devise_imapable/schema' require 'devise_imapable/imap_adapter' require 'devise_imapable/routes' module Devise # imap server address for authentication. mattr_accessor :imap_server @@imap_server = nil # default email suffix mattr_accessor :default_email_suffix @@default_email_suffix = nil end # Add +:imapable+ strategy to defaults. # Devise.add_module(:imapable, :strategy => true, :controller => :sessions, :model => 'devise_imapable/model', :routes => :imapable)
joshk/devise_imapable
lib/devise_imapable.rb
Ruby
mit
601
class Spud::Admin::PhotoGalleriesController < Spud::Admin::ApplicationController before_filter :get_gallery, :only => [:show, :edit, :update, :destroy] before_filter :get_albums, :only => [:new, :create, :edit, :update] add_breadcrumb 'Photo Galleries', :spud_admin_photo_galleries_path respond_to :html, :json, :xml layout 'spud/admin/spud_photos' cache_sweeper :spud_photo_sweeper, :only => [:create, :update, :destroy] def index @photo_galleries = SpudPhotoGallery.all respond_with @photo_galleries end def show respond_with @photo_gallery end def new @photo_gallery = SpudPhotoGallery.new respond_with @photo_gallery end def create @photo_gallery = SpudPhotoGallery.new(params[:spud_photo_gallery]) flash[:notice] = 'SpudPhotoGallery created successfully' if @photo_gallery.save respond_with @photo_gallery, :location => spud_admin_photo_galleries_path end def edit respond_with @photo_gallery end def update @photo_gallery.update_attributes(params[:spud_photo_gallery]) flash[:notice] = 'SpudPhotoGallery updated successfully' if @photo_gallery.save respond_with @photo_gallery, :location => spud_admin_photo_galleries_path end def destroy flash[:notice] = 'SpudPhotoGallery deleted successfully' if @photo_gallery.destroy respond_with @photo_gallery, :location => spud_admin_photo_galleries_path end def get_gallery @photo_gallery = SpudPhotoGallery.find(params[:id]) end def get_albums @photo_albums = SpudPhotoAlbum.all end end
gregawoods/spud_photos
app/controllers/spud/admin/photo_galleries_controller.rb
Ruby
mit
1,570
#ifndef RENDERER_RAYTRACER_HPP #define RENDERER_RAYTRACER_HPP #include "base.hpp" #include "geometry.hpp" #include "material.hpp" #include "light.hpp" #include "camera.hpp" #include "shapes/union.hpp" #include <bitset> namespace renderer { class Shape; class PerspectiveCamera; class Film; class Light; class ShapeUnion; class SceneDesc { public: int threadsPow; int width; int height; int maxReflect; Film* film; PerspectiveCamera camera; MaterialDict matDict; ShapeUnion* shapeUnion; Lights lights; SceneDesc(const PerspectiveCamera& c, ShapeUnion* s) : threadsPow(0), width(1), height(1), maxReflect(0), film(nullptr), camera(c), shapeUnion(s) { } SceneDesc(SceneDesc&& s): threadsPow(s.threadsPow), width(s.width), height(s.height), maxReflect( s.maxReflect), film(s.film), camera(s.camera) { s.film = nullptr; matDict = std::move(s.matDict); lights = std::move(s.lights); shapeUnion = std::move(s.shapeUnion); } ~SceneDesc() { film = nullptr; } void setFilm(Film* f); int threadsNum() { return std::pow(2, threadsPow); } void init(); }; class RayTracer { int preCount; int curRow; public: int pRendered; //rendered pixels int pDispatched; //dispatched pixels, means renderring bool* flags; Color* colorArray; SceneDesc * sceneDesc; std::mutex mtx; std::vector<std::thread*> threads; int countRenderedPixels(); public: RayTracer(SceneDesc* desc): pRendered(0), pDispatched(0), preCount(0), curRow(0), sceneDesc(desc), flags(new bool[desc->width * desc->height]{ false }), colorArray(new Color[desc->width * desc->height]) {} ~RayTracer() { for (int i = 0; i < threads.size(); i++) { delete threads[i]; } if (flags) delete[] flags; if (colorArray) delete[] colorArray; } void rayTrace(Film*, Shape* scene, PerspectiveCamera& camera, Lights&); Color rayTraceRecursive(Shape* scene, Ray& ray, Lights&, int maxReflect); void rayTraceReflection(Film*, Shape* scene, PerspectiveCamera& camera, Lights&, int maxReflect, int x = 0, int y = 0, int w = 0, int h = 0); void rayTraceConcurrence(SceneDesc&); void beginAsyncRender(SceneDesc& desc); void endAsyncRender(); int getRenderRect(SceneDesc& desc, int* x, int* y, int* w, int* h); Color rayTraceAt(SceneDesc&, int x, int y); void renderScene(SceneDesc&); }; } #endif // RENDERER_RAYTRACER_HPP
voyagingmk/renderer
include/raytracer.hpp
C++
mit
2,543
namespace StorageAdapters.WebDAV.Test { using System; using System.Threading.Tasks; using Xunit; public class WebDAVStorageAdapterTests : StorageAdapters.Test.StorageAdapterTests<WebDAVStorageAdapterFixture, WebDAVStorageAdapter> { public WebDAVStorageAdapterTests(WebDAVStorageAdapterFixture fixture) : base(fixture) { } public async override Task ContentIsNotModified(string fileName) { if (string.IsNullOrEmpty(System.IO.Path.GetExtension(fileName))) { return; } await base.ContentIsNotModified(fileName); } public async override Task FileExists(string fileName) { if (string.IsNullOrEmpty(System.IO.Path.GetExtension(fileName))) { return; } await base.FileExists(fileName); } public async override Task GetFileInfo(string fileName) { if (string.IsNullOrEmpty(System.IO.Path.GetExtension(fileName))) { return; } await base.GetFileInfo(fileName); } } public class WebDAVStorageAdapterFixture : StorageAdapters.Test.StorageAdapterFixture<WebDAVStorageAdapter> { protected override WebDAVStorageAdapter CreateAdapter() { return new WebDAVStorageAdapter(new WebDAVConfiguration() { Server = new Uri("http://localhost/WebDAV/", UriKind.Absolute), UserName = "Test", Password = "Test" }); } protected override string CreateTestPath() { var testPath = Guid.NewGuid().ToString(); Adapter.CreateDirectoryAsync(testPath).Wait(); return testPath; } protected override void CleanupTestPath(string testPath) { Adapter.DeleteDirectoryAsync(testPath).Wait(); } } }
NsdWorkBook/StorageAdapters
StorageAdapters.WebDAV.Test/WebDAVStorageAdapterTests.cs
C#
mit
1,987
// Copyright (c) 2011-2013 The Bitcredit Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCREDIT_QT_WALLETVIEW_H #define BITCREDIT_QT_WALLETVIEW_H #include "amount.h" #include <QStackedWidget> class BitcreditGUI; class ClientModel; class OverviewPage; class ReceiveCoinsDialog; class SendCoinsDialog; class SendCoinsRecipient; class TransactionView; class WalletModel; class ExchangeBrowser; class ChatWindow; class BlockBrowser; class BankStatisticsPage; class MessagePage; class InvoicePage; class ReceiptPage; class MessageModel; class SendMessagesDialog; class BanknodeManager; class AddEditAdrenalineNode; QT_BEGIN_NAMESPACE class QModelIndex; class QProgressDialog; QT_END_NAMESPACE /* WalletView class. This class represents the view to a single wallet. It was added to support multiple wallet functionality. Each wallet gets its own WalletView instance. It communicates with both the client and the wallet models to give the user an up-to-date view of the current core state. */ class WalletView : public QStackedWidget { Q_OBJECT public: explicit WalletView(QWidget *parent); ~WalletView(); void setBitcreditGUI(BitcreditGUI *gui); /** Set the client model. The client model represents the part of the core that communicates with the P2P network, and is wallet-agnostic. */ void setClientModel(ClientModel *clientModel); /** Set the wallet model. The wallet model represents a bitcredit wallet, and offers access to the list of transactions, address book and sending functionality. */ void setWalletModel(WalletModel *walletModel); void setMessageModel(MessageModel *messageModel); bool handlePaymentRequest(const SendCoinsRecipient& recipient); void showOutOfSyncWarning(bool fShow); private: ClientModel *clientModel; MessageModel *messageModel; WalletModel *walletModel; ChatWindow *chatWindow; ExchangeBrowser *exchangeBrowser; BanknodeManager *banknodeManagerPage; OverviewPage *overviewPage; QWidget *transactionsPage; ReceiveCoinsDialog *receiveCoinsPage; SendCoinsDialog *sendCoinsPage; BlockBrowser *blockBrowser; BankStatisticsPage *bankstatisticsPage; TransactionView *transactionView; SendMessagesDialog *sendMessagesPage; MessagePage *messagePage; InvoicePage *invoicePage; ReceiptPage *receiptPage; QProgressDialog *progressDialog; public slots: /** Switch to overview (home) page */ void gotoOverviewPage(); /** Switch to history (transactions) page */ void gotoHistoryPage(); /** Switch to chat page */ void gotoChatPage(); /** Switch to exchange browser page */ void gotoExchangeBrowserPage(); /** Switch to receive coins page */ void gotoReceiveCoinsPage(); /** Switch to send coins page */ void gotoSendCoinsPage(QString addr = ""); void gotoBlockBrowser(); void gotoBankStatisticsPage(); void gotoSendMessagesPage(); /** Switch to send anonymous messages page */ /** Switch to view messages page */ void gotoMessagesPage(); /** Switch to invoices page */ void gotoInvoicesPage(); /** Switch to receipt page */ void gotoReceiptPage(); /** Switch to send coins page */ void gotoBanknodeManagerPage(); /** Show Sign/Verify Message dialog and switch to sign message tab */ void gotoSignMessageTab(QString addr = ""); /** Show Sign/Verify Message dialog and switch to verify message tab */ void gotoVerifyMessageTab(QString addr = ""); /** Show incoming transaction notification for new transactions. The new items are those between start and end inclusive, under the given parent item. */ void processNewTransaction(const QModelIndex& parent, int start, int /*end*/); void processNewMessage(const QModelIndex& parent, int start, int /*end*/); /** Encrypt the wallet */ void encryptWallet(bool status); /** Backup the wallet */ void backupWallet(); /** Change encrypted wallet passphrase */ void changePassphrase(); /** Ask for passphrase to unlock wallet temporarily */ void unlockWallet(); /** Open the print paper wallets dialog **/ void printPaperWallets(); /** Show used sending addresses */ void usedSendingAddresses(); /** Show used receiving addresses */ void usedReceivingAddresses(); /** Re-emit encryption status signal */ void updateEncryptionStatus(); /** Show progress dialog e.g. for rescan */ void showProgress(const QString &title, int nProgress); signals: /** Signal that we want to show the main window */ void showNormalIfMinimized(); /** Fired when a message should be reported to the user */ void message(const QString &title, const QString &message, unsigned int style); /** Encryption status of wallet changed */ void encryptionStatusChanged(int status); /** Notify that a new transaction appeared */ void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address); void incomingMessage(const QString& sent_datetime, QString from_address, QString to_address, QString message, int type); }; #endif // BITCREDIT_QT_WALLETVIEW_H
coinkeeper/2015-06-22_19-17_bitcredits
src/qt/walletview.h
C
mit
5,355
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.apimanagement.implementation; import com.azure.core.annotation.BodyParam; import com.azure.core.annotation.Delete; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.Head; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.Put; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.apimanagement.fluent.ApiSchemasClient; import com.azure.resourcemanager.apimanagement.fluent.models.SchemaContractInner; import com.azure.resourcemanager.apimanagement.models.ApiSchemasGetEntityTagResponse; import com.azure.resourcemanager.apimanagement.models.ApiSchemasGetResponse; import com.azure.resourcemanager.apimanagement.models.SchemaCollection; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in ApiSchemasClient. */ public final class ApiSchemasClientImpl implements ApiSchemasClient { private final ClientLogger logger = new ClientLogger(ApiSchemasClientImpl.class); /** The proxy service used to perform REST calls. */ private final ApiSchemasService service; /** The service client containing this operation class. */ private final ApiManagementClientImpl client; /** * Initializes an instance of ApiSchemasClientImpl. * * @param client the instance of the service client containing this operation class. */ ApiSchemasClientImpl(ApiManagementClientImpl client) { this.service = RestProxy.create(ApiSchemasService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for ApiManagementClientApiSchemas to be used by the proxy service to * perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "ApiManagementClientA") private interface ApiSchemasService { @Headers({"Content-Type: application/json"}) @Get( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement" + "/service/{serviceName}/apis/{apiId}/schemas") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<SchemaCollection>> listByApi( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("serviceName") String serviceName, @PathParam("apiId") String apiId, @QueryParam("$filter") String filter, @QueryParam("$top") Integer top, @QueryParam("$skip") Integer skip, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Head( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement" + "/service/{serviceName}/apis/{apiId}/schemas/{schemaId}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<ApiSchemasGetEntityTagResponse> getEntityTag( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("serviceName") String serviceName, @PathParam("apiId") String apiId, @PathParam("schemaId") String schemaId, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement" + "/service/{serviceName}/apis/{apiId}/schemas/{schemaId}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<ApiSchemasGetResponse> get( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("serviceName") String serviceName, @PathParam("apiId") String apiId, @PathParam("schemaId") String schemaId, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Put( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement" + "/service/{serviceName}/apis/{apiId}/schemas/{schemaId}") @ExpectedResponses({200, 201, 202}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<Flux<ByteBuffer>>> createOrUpdate( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("serviceName") String serviceName, @PathParam("apiId") String apiId, @PathParam("schemaId") String schemaId, @HeaderParam("If-Match") String ifMatch, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @BodyParam("application/json") SchemaContractInner parameters, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Delete( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement" + "/service/{serviceName}/apis/{apiId}/schemas/{schemaId}") @ExpectedResponses({200, 204}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<Void>> delete( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("serviceName") String serviceName, @PathParam("apiId") String apiId, @PathParam("schemaId") String schemaId, @QueryParam("force") Boolean force, @HeaderParam("If-Match") String ifMatch, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<SchemaCollection>> listByApiNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param filter | Field | Usage | Supported operators | Supported functions * |&lt;/br&gt;|-------------|-------------|-------------|-------------|&lt;/br&gt;| contentType | filter | ge, * le, eq, ne, gt, lt | substringof, contains, startswith, endswith |&lt;/br&gt;. * @param top Number of records to return. * @param skip Number of records to skip. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<SchemaContractInner>> listByApiSinglePageAsync( String resourceGroupName, String serviceName, String apiId, String filter, Integer top, Integer skip) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service .listByApi( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, filter, top, skip, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context)) .<PagedResponse<SchemaContractInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param filter | Field | Usage | Supported operators | Supported functions * |&lt;/br&gt;|-------------|-------------|-------------|-------------|&lt;/br&gt;| contentType | filter | ge, * le, eq, ne, gt, lt | substringof, contains, startswith, endswith |&lt;/br&gt;. * @param top Number of records to return. * @param skip Number of records to skip. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<SchemaContractInner>> listByApiSinglePageAsync( String resourceGroupName, String serviceName, String apiId, String filter, Integer top, Integer skip, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByApi( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, filter, top, skip, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param filter | Field | Usage | Supported operators | Supported functions * |&lt;/br&gt;|-------------|-------------|-------------|-------------|&lt;/br&gt;| contentType | filter | ge, * le, eq, ne, gt, lt | substringof, contains, startswith, endswith |&lt;/br&gt;. * @param top Number of records to return. * @param skip Number of records to skip. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<SchemaContractInner> listByApiAsync( String resourceGroupName, String serviceName, String apiId, String filter, Integer top, Integer skip) { return new PagedFlux<>( () -> listByApiSinglePageAsync(resourceGroupName, serviceName, apiId, filter, top, skip), nextLink -> listByApiNextSinglePageAsync(nextLink)); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<SchemaContractInner> listByApiAsync(String resourceGroupName, String serviceName, String apiId) { final String filter = null; final Integer top = null; final Integer skip = null; return new PagedFlux<>( () -> listByApiSinglePageAsync(resourceGroupName, serviceName, apiId, filter, top, skip), nextLink -> listByApiNextSinglePageAsync(nextLink)); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param filter | Field | Usage | Supported operators | Supported functions * |&lt;/br&gt;|-------------|-------------|-------------|-------------|&lt;/br&gt;| contentType | filter | ge, * le, eq, ne, gt, lt | substringof, contains, startswith, endswith |&lt;/br&gt;. * @param top Number of records to return. * @param skip Number of records to skip. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<SchemaContractInner> listByApiAsync( String resourceGroupName, String serviceName, String apiId, String filter, Integer top, Integer skip, Context context) { return new PagedFlux<>( () -> listByApiSinglePageAsync(resourceGroupName, serviceName, apiId, filter, top, skip, context), nextLink -> listByApiNextSinglePageAsync(nextLink, context)); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SchemaContractInner> listByApi(String resourceGroupName, String serviceName, String apiId) { final String filter = null; final Integer top = null; final Integer skip = null; return new PagedIterable<>(listByApiAsync(resourceGroupName, serviceName, apiId, filter, top, skip)); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param filter | Field | Usage | Supported operators | Supported functions * |&lt;/br&gt;|-------------|-------------|-------------|-------------|&lt;/br&gt;| contentType | filter | ge, * le, eq, ne, gt, lt | substringof, contains, startswith, endswith |&lt;/br&gt;. * @param top Number of records to return. * @param skip Number of records to skip. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<SchemaContractInner> listByApi( String resourceGroupName, String serviceName, String apiId, String filter, Integer top, Integer skip, Context context) { return new PagedIterable<>(listByApiAsync(resourceGroupName, serviceName, apiId, filter, top, skip, context)); } /** * Gets the entity state (Etag) version of the schema specified by its identifier. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the entity state (Etag) version of the schema specified by its identifier. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<ApiSchemasGetEntityTagResponse> getEntityTagWithResponseAsync( String resourceGroupName, String serviceName, String apiId, String schemaId) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (schemaId == null) { return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service .getEntityTag( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, schemaId, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Gets the entity state (Etag) version of the schema specified by its identifier. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the entity state (Etag) version of the schema specified by its identifier. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<ApiSchemasGetEntityTagResponse> getEntityTagWithResponseAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (schemaId == null) { return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .getEntityTag( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, schemaId, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context); } /** * Gets the entity state (Etag) version of the schema specified by its identifier. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the entity state (Etag) version of the schema specified by its identifier. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Void> getEntityTagAsync(String resourceGroupName, String serviceName, String apiId, String schemaId) { return getEntityTagWithResponseAsync(resourceGroupName, serviceName, apiId, schemaId) .flatMap((ApiSchemasGetEntityTagResponse res) -> Mono.empty()); } /** * Gets the entity state (Etag) version of the schema specified by its identifier. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public void getEntityTag(String resourceGroupName, String serviceName, String apiId, String schemaId) { getEntityTagAsync(resourceGroupName, serviceName, apiId, schemaId).block(); } /** * Gets the entity state (Etag) version of the schema specified by its identifier. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the entity state (Etag) version of the schema specified by its identifier. */ @ServiceMethod(returns = ReturnType.SINGLE) public ApiSchemasGetEntityTagResponse getEntityTagWithResponse( String resourceGroupName, String serviceName, String apiId, String schemaId, Context context) { return getEntityTagWithResponseAsync(resourceGroupName, serviceName, apiId, schemaId, context).block(); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<ApiSchemasGetResponse> getWithResponseAsync( String resourceGroupName, String serviceName, String apiId, String schemaId) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (schemaId == null) { return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service .get( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, schemaId, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<ApiSchemasGetResponse> getWithResponseAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (schemaId == null) { return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .get( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, schemaId, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<SchemaContractInner> getAsync( String resourceGroupName, String serviceName, String apiId, String schemaId) { return getWithResponseAsync(resourceGroupName, serviceName, apiId, schemaId) .flatMap( (ApiSchemasGetResponse res) -> { if (res.getValue() != null) { return Mono.just(res.getValue()); } else { return Mono.empty(); } }); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.SINGLE) public SchemaContractInner get(String resourceGroupName, String serviceName, String apiId, String schemaId) { return getAsync(resourceGroupName, serviceName, apiId, schemaId).block(); } /** * Get the schema configuration at the API level. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the schema configuration at the API level. */ @ServiceMethod(returns = ReturnType.SINGLE) public ApiSchemasGetResponse getWithResponse( String resourceGroupName, String serviceName, String apiId, String schemaId, Context context) { return getWithResponseAsync(resourceGroupName, serviceName, apiId, schemaId, context).block(); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (schemaId == null) { return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (parameters == null) { return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); } else { parameters.validate(); } final String accept = "application/json"; return FluxUtil .withContext( context -> service .createOrUpdate( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, schemaId, ifMatch, this.client.getApiVersion(), this.client.getSubscriptionId(), parameters, accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (schemaId == null) { return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (parameters == null) { return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); } else { parameters.validate(); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .createOrUpdate( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, schemaId, ifMatch, this.client.getApiVersion(), this.client.getSubscriptionId(), parameters, accept, context); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) private PollerFlux<PollResult<SchemaContractInner>, SchemaContractInner> beginCreateOrUpdateAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch) { Mono<Response<Flux<ByteBuffer>>> mono = createOrUpdateWithResponseAsync(resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch); return this .client .<SchemaContractInner, SchemaContractInner>getLroResult( mono, this.client.getHttpPipeline(), SchemaContractInner.class, SchemaContractInner.class, Context.NONE); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) private PollerFlux<PollResult<SchemaContractInner>, SchemaContractInner> beginCreateOrUpdateAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch, Context context) { context = this.client.mergeContext(context); Mono<Response<Flux<ByteBuffer>>> mono = createOrUpdateWithResponseAsync( resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch, context); return this .client .<SchemaContractInner, SchemaContractInner>getLroResult( mono, this.client.getHttpPipeline(), SchemaContractInner.class, SchemaContractInner.class, context); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) public SyncPoller<PollResult<SchemaContractInner>, SchemaContractInner> beginCreateOrUpdate( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch) { return beginCreateOrUpdateAsync(resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch) .getSyncPoller(); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) public SyncPoller<PollResult<SchemaContractInner>, SchemaContractInner> beginCreateOrUpdate( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch, Context context) { return beginCreateOrUpdateAsync(resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch, context) .getSyncPoller(); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<SchemaContractInner> createOrUpdateAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch) { return beginCreateOrUpdateAsync(resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch) .last() .flatMap(this.client::getLroFinalResultOrError); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<SchemaContractInner> createOrUpdateAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters) { final String ifMatch = null; return beginCreateOrUpdateAsync(resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch) .last() .flatMap(this.client::getLroFinalResultOrError); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<SchemaContractInner> createOrUpdateAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch, Context context) { return beginCreateOrUpdateAsync(resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch, context) .last() .flatMap(this.client::getLroFinalResultOrError); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) public SchemaContractInner createOrUpdate( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch) { return createOrUpdateAsync(resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch).block(); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) public SchemaContractInner createOrUpdate( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters) { final String ifMatch = null; return createOrUpdateAsync(resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch).block(); } /** * Creates or updates schema configuration for the API. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param parameters The schema contents to apply. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return schema Contract details. */ @ServiceMethod(returns = ReturnType.SINGLE) public SchemaContractInner createOrUpdate( String resourceGroupName, String serviceName, String apiId, String schemaId, SchemaContractInner parameters, String ifMatch, Context context) { return createOrUpdateAsync(resourceGroupName, serviceName, apiId, schemaId, parameters, ifMatch, context) .block(); } /** * Deletes the schema configuration at the Api. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET * request or it should be * for unconditional update. * @param force If true removes all references to the schema before deleting it. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<Void>> deleteWithResponseAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, String ifMatch, Boolean force) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (schemaId == null) { return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); } if (ifMatch == null) { return Mono.error(new IllegalArgumentException("Parameter ifMatch is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service .delete( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, schemaId, force, ifMatch, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Deletes the schema configuration at the Api. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET * request or it should be * for unconditional update. * @param force If true removes all references to the schema before deleting it. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<Void>> deleteWithResponseAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, String ifMatch, Boolean force, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (serviceName == null) { return Mono.error(new IllegalArgumentException("Parameter serviceName is required and cannot be null.")); } if (apiId == null) { return Mono.error(new IllegalArgumentException("Parameter apiId is required and cannot be null.")); } if (schemaId == null) { return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); } if (ifMatch == null) { return Mono.error(new IllegalArgumentException("Parameter ifMatch is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .delete( this.client.getEndpoint(), resourceGroupName, serviceName, apiId, schemaId, force, ifMatch, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context); } /** * Deletes the schema configuration at the Api. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET * request or it should be * for unconditional update. * @param force If true removes all references to the schema before deleting it. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Void> deleteAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, String ifMatch, Boolean force) { return deleteWithResponseAsync(resourceGroupName, serviceName, apiId, schemaId, ifMatch, force) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Deletes the schema configuration at the Api. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET * request or it should be * for unconditional update. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Void> deleteAsync( String resourceGroupName, String serviceName, String apiId, String schemaId, String ifMatch) { final Boolean force = null; return deleteWithResponseAsync(resourceGroupName, serviceName, apiId, schemaId, ifMatch, force) .flatMap((Response<Void> res) -> Mono.empty()); } /** * Deletes the schema configuration at the Api. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET * request or it should be * for unconditional update. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public void delete(String resourceGroupName, String serviceName, String apiId, String schemaId, String ifMatch) { final Boolean force = null; deleteAsync(resourceGroupName, serviceName, apiId, schemaId, ifMatch, force).block(); } /** * Deletes the schema configuration at the Api. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. Non-current * revision has ;rev=n as a suffix where n is the revision number. * @param schemaId Schema identifier within an API. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET * request or it should be * for unconditional update. * @param force If true removes all references to the schema before deleting it. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteWithResponse( String resourceGroupName, String serviceName, String apiId, String schemaId, String ifMatch, Boolean force, Context context) { return deleteWithResponseAsync(resourceGroupName, serviceName, apiId, schemaId, ifMatch, force, context) .block(); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response of the list schema operation. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<SchemaContractInner>> listByApiNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext(context -> service.listByApiNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<SchemaContractInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response of the list schema operation. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<SchemaContractInner>> listByApiNextSinglePageAsync(String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByApiNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } }
Azure/azure-sdk-for-java
sdk/apimanagement/azure-resourcemanager-apimanagement/src/main/java/com/azure/resourcemanager/apimanagement/implementation/ApiSchemasClientImpl.java
Java
mit
79,226
const fs = require('fs'); const path = require('path'); const EventEmitter = require('events'); const cors = require('cors'); const bodyParser = require('body-parser'); const compression = require('compression'); const cookieParser = require('cookie-parser'); const express = require('express'); const http = require('http'); const https = require('https'); const randomstring = require('randomstring'); const config = require('../config'); const reloadProvider = require('./reloadProviders'); const controllers = require('./controllers'); const socketServer = require('./socketServer'); const purchaseWebservices = require('./lib/purchaseWebservices'); const logger = require('./lib/log'); const bookshelf = require('./lib/bookshelf'); const APIError = require('./errors/APIError'); const sslConfig = require('../scripts/sslConfig'); const { addDevice } = require('../scripts/addDevice'); const log = logger(module); const LOCK_FILE = path.join(__dirname, '..', 'ready.lock'); const app = express(); app.locals.config = config; app.locals.models = bookshelf.models; /** * Middlewares */ app.use(cors({ allowedHeaders: ['content-type', 'Authorization'], credentials : true, exposedHeaders: ['device', 'point', 'pointName', 'event', 'eventName'], origin : true })); app.use(bodyParser.json({ limit: '5mb' })); app.use(cookieParser()); app.use(compression()); /** * Routes */ app.use(controllers); reloadProvider(app) .catch(() => { console.error('No reload provider provided'); process.exit(1); }); /** * Error handling */ // 404 app.use((req, res, next) => { next(new APIError(module, 404, 'Not Found')); }); // Internal error app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars let error = err; /* istanbul ignore next */ if (!(err instanceof APIError)) { log.error(err, req.details); error = new APIError(module, 500, 'Unknown error'); } else { logger(err.module).error(err.message, err.details); } res .status(error.status || 500) .send(error.toJSON ? error.toJSON() : JSON.stringify(error)) .end(); }); app.start = () => { const sslFilesPath = { key : './ssl/certificates/server/server-key.pem', cert: './ssl/certificates/server/server-crt.pem', ca : './ssl/certificates/ca/ca-crt.pem' }; let startingQueue = bookshelf .waitForDb(2, 15) // 15 retries, one every 2 seconds .then(() => bookshelf.sync()); /* istanbul ignore if */ if (!fs.existsSync(sslFilesPath.key) || !fs.existsSync(sslFilesPath.cert) || !fs.existsSync(sslFilesPath.ca)) { startingQueue = startingQueue .then(() => { log.info('No SSL certificates found, generating new ones...'); const result = sslConfig(null, null, true); log.info(`[ chalPassword ] ${result.chalPassword}`); log.info(`[ outPassword ] ${result.outPassword}`); }) .then(() => { log.info('Seeding database...'); return bookshelf.knex.seed.run(); }) .then(() => { log.info('Creating admin device...'); const password = process.env.NODE_ENV === 'development' ? 'development' : randomstring.generate(); return addDevice({ admin: true, deviceName: 'admin', password }); }) .then((adminPassword) => { log.info(`[ admin .p12 password ] ${adminPassword}`); }) .then(() => { log.info('Creating manager certificate...'); return addDevice({ admin: true, deviceName: 'manager', password: 'manager' }); }); } return startingQueue.then(() => { const server = process.env.SERVER_PROTOCOL === 'http' ? http.createServer(app) : https.createServer({ key : fs.readFileSync(sslFilesPath.key), cert : fs.readFileSync(sslFilesPath.cert), ca : fs.readFileSync(sslFilesPath.ca), requestCert : true, rejectUnauthorized: false }, app); app.locals.modelChanges = new EventEmitter(); app.locals.server = server; socketServer.ioServer(server, app); purchaseWebservices(app); return new Promise((resolve, reject) => { server.listen(config.http.port, config.http.host, (err) => { /* istanbul ignore if */ if (err) { return reject(err); } log.info( 'Server is listening %s://%s:%d', process.env.SERVER_PROTOCOL, config.http.host, config.http.port ); fs.writeFileSync(LOCK_FILE, '1'); resolve(app); }); }); }); }; /* istanbul ignore next */ const clearLock = (status) => { if (status instanceof Error) { log.error(status); } try { fs.unlinkSync(LOCK_FILE); } catch (e) { process.exit(1); } process.exit(status || 0); }; /* istanbul ignore next */ process.on('unhandledRejection', (err) => { if (err.name === 'ReqlDriverError' && err.message === 'None of the pools have an opened connection and failed to open a new one.') { log.error('Cannot open connection to database'); process.exit(1); } }); module.exports = app; // Start the application /* istanbul ignore if */ if (require.main === module) { process.on('exit', clearLock); process.on('SIGINT', clearLock); process.on('SIGTERM', clearLock); process.on('uncaughtException', clearLock); process.on('unhandledRejection', clearLock); app .start() .catch((err) => { log.error('Start error: %s', err); }); }
buckless-team/server
src/app.js
JavaScript
mit
6,179
Template.orderListItem.helpers({ //statusName: function(status) { // var names = { // ongoing: '进行', // finished: '完成', // canceled: '终止' // }; // return names[status] || '未知'; //}, statusColor: function () { var colors = { '进行': 'bg-primary', '完成': 'bg-success', '终止': 'bg-warning' }; return colors[this.status] || 'bg-danger'; }, customerName: function () { var customer = Customers.findOne(this.customer); if (customer && customer.name) { return customer.name; } return this.customer; }, stationName: function () { var station = Stations.findOne(this.stationId); return station && station.name; } }); Template.addOrder.helpers({ hasError: function (field) { return !!Session.get('orderManagementSubmitErrors')[field] ? 'has-error' : ''; } }); Template.orderManagement.onCreated(function () { Session.set('orderManagementSubmitErrors', {}); }); Template.orderManagement.onRendered(function () { var key = this.data.filterKey; //console.log('key: ' + key); this.$('.order-keyword').val(key); var target = $('#add-order'); target.hide(); }); Template.orderManagement.events({ 'keypress .order-keyword': function (e) { // 绑定回车键 if (e.keyCode == '13') { e.preventDefault(); var keyword = $('.order-keyword').val(); keyword = keyword ? '?keyword=' + keyword : ''; //console.log('keyword: ' + keyword); //alert('contents: ' + $('.order-keyword').val()); Router.go(location.pathname + keyword); } }, 'click .filter-order': function (e) { e.preventDefault(); var keyword = $('.order-keyword').val(); keyword = keyword ? '?keyword=' + keyword : ''; Router.go(location.pathname + keyword); }, 'click .condition .today': function(e) { e.preventDefault(); e.stopPropagation(); setPeriod('today'); }, 'click .condition .yesterday': function(e) { e.preventDefault(); e.stopPropagation(); setPeriod('yesterday'); }, 'click .condition .month': function(e) { e.preventDefault(); e.stopPropagation(); setPeriod('month'); }, 'click .condition .pre-month': function(e) { e.preventDefault(); e.stopPropagation(); setPeriod('pre-month'); }, 'click .condition .30days': function(e) { e.preventDefault(); e.stopPropagation(); setPeriod('30days'); }, 'click .condition .year': function(e) { e.preventDefault(); e.stopPropagation(); setPeriod('year'); }, 'click .edit-order': function (e) { e.preventDefault(); // 清空可能遗留的错误信息 Session.set('orderManagementSubmitErrors', {}); var target = $('#add-order'); // 如果设置了覆盖标识(overlap)则清空,否则只是简单的显示/隐藏切换编辑框 //if (target.find('[name=overlap]').val()) { // target.find('[name=overlap]').val(''); //} else { if (target.hasClass('hidden')) { target.removeClass('hidden'); target.slideDown('fast'); } else { target.slideUp('fast', function () { clearForm(target); target.addClass('hidden'); }); } //} }, 'click .update-order': function (e) { e.preventDefault(); // 清空可能遗留的错误信息 Session.set('orderManagementSubmitErrors', {}); // 获取对应数据库条目Id var _id = $(e.currentTarget).attr('href'); //console.log('_id: ' + _id); var form = $('#add-order'); // 显示编辑框 if (form.hasClass('hidden')) { form.removeClass('hidden'); form.slideDown('fast'); } fillForm(_id); }, 'submit .add-order': function (e) { e.preventDefault(); var form = $(e.target); var order = { code: form.find('[name=code]').val(), type: form.find('[name=type]').val(), customer: form.find('[name=customerNameOrId]').val(), phone: form.find('[name=phone]').val(), address: form.find('[name=address]').val(), stationId: form.find('[name=stationId]').val(), comment: form.find('[name=comment]').val() }; // 如果表单中的客户名称和data-customer-id对应的客户名称相同则保存id值 console.log('customer: ' + JSON.stringify(order.customer)); var customerId = form.find('[name=customerNameOrId]').data('customerId'); var customer = Customers.findOne(customerId); console.log('customerId: ' + customerId); if (customer && customer.name == order.customer) { order.customer = customerId; } var userId = Meteor.userId(); order = _.extend(order, { status: '进行', deadline: 0, managerId: userId, disposal: {} }); //console.log('order: ' + JSON.stringify(order)); //var overlap = form.find('[name=overlap]').val(); //console.log('overlap is: ' + overlap); //var data = {order: order, overlap: overlap}; var errors = validateOrderBase(order); if (errors.err) { Session.set('orderManagementSubmitErrors', errors); throwError(getErrorMessage(errors)); return; } Meteor.call('orderInsert', order, function (err) { if (err) { return throwError(err.reason); } // 清除可能遗留的错误信息 Session.set('orderManagementSubmitErrors', {}); var form = $('#add-order'); // 清除表单的内容 clearForm(form); form.slideUp('fast', function () { form.addClass('hidden'); }); }); } }); function setPeriod(span) { $('.order-keyword').val(''); if (!span) { Router.go(location.pathname); return; } var period = '?period=' + span; Router.go(location.pathname + period); } function clearForm(target) { var form = $(target); form.find('[name=code]').val(''); form.find('[name=type]').val(''); form.find('[name=customerNameOrId]').val(''); form.find('[name=phone]').val(''); form.find('[name=address]').val(''); form.find('[name=stationId]').val(defaultStationId()); form.find('[name=comment]').val(''); // 清空隐藏文本框中保存的数据库条目Id,即清空覆盖标识 form.find('[name=overlap]').val(''); } function fillForm(_id) { var data = Orders.findOne(_id); //console.log('data: ' + JSON.stringify(data)); var form = $('#add-order'); form.find('[name=code]').val(data.code); form.find('[name=type]').val(data.type); form.find('[name=customerNameOrId]').val(data.customer); form.find('[name=phone]').val(data.phone); form.find('[name=address]').val(data.address); form.find('[name=stationId]').val(data.stationId); form.find('[name=comment]').val(data.comment); // 将id保存到隐藏的文本框,表示本次操作会强行覆盖对应的数据库条目 form.find('[name=overlap]').val(_id); }
lszhu/saleSys
client/templates/order/list.js
JavaScript
mit
6,812
"""Modulo que contiene la clase directorio de funciones ----------------------------------------------------------------- Compilers Design Project Tec de Monterrey Julio Cesar Aguilar Villanueva A01152537 Jose Fernando Davila Orta A00999281 ----------------------------------------------------------------- DOCUMENTATION: For complete Documentation see UserManual.pdf""" from stack import Stack from function import Function from variable import Variable def get_var_type(var_type): '''retorna el identificador de cada tipo de variable''' if var_type == 'int': return 'i' elif var_type == 'double': return 'd' elif var_type == 'string': return 's' elif var_type == 'bool': return 'b' def get_var_scope(scope): '''retorna el identificador de cada tipo de scope''' if scope == 'global': return 'g' elif scope == 'main': return 'l' else: return 't' def get_var_name(var_type, scope, var_name): '''construct the direccion of a variable based on the type, scope and variable name.''' name_type = get_var_type(var_type) name_scope = get_var_scope(scope) name = name_type + name_scope + var_name return name class FunctionsDir(object): '''Las funciones son entradas en el diccionario functions. Las funciones son objetos con diccionarios de variables. Scope global del programa se inicia con una funcion global sin variables. Scope es el function_id de cada funcion.''' def __init__(self): '''Metodo de inicializacion''' self.functions = {} self.functions['global'] = Function() self.scope = 'global' # Define si se esta evaluando la existencia de variables o se estan agregando al directorio self.evaluating = True # Indica si es necesario acutlaizar la lista de prametros de una funcion self.updating_params = False # Indica si se va a leer variable con funcion read self.reading = False # Ultimo token ID, usado para el read self.last_id = Stack() # Ultimo token de tipo que fue leido por el directorio de funciones self.last_type = None '''Funciones que estan siendo llamadas. Se utiliza una pila para llamadas nesteadas a funciones''' self.call_function = Stack() '''Cantidad de argumentos que estan siendo utilizados al llamar a una funcion. Se utiliza una pilla para llamadas nesteadas''' self.call_arguments = Stack() self.last_read = Stack() def add_function(self, function_id): '''Add function to fuctions directory. Verify if function already exists''' if self.functions.get(function_id, None) is not None: raise NameError('Error: 1001 Function already declared! Function: ' + str(function_id)) else: self.functions[function_id] = Function() def validate_function(self, function_id): '''Validate function exists''' if self.functions.get(function_id, None) is None: raise NameError('Error: 1002 Function not declared! Name: ' + str(function_id)) def increase_expected_arguments(self): '''Manda llamar el metodo increase expected arguments de la clase Function''' self.functions[self.scope].increase_expected_arguments() def update_function_params(self, var_id, var_type): '''Manda llamar metodo update params de la clase Funcion''' self.functions[self.scope].update_params(var_id, var_type) def set_return_type(self, function_return_type): '''Manda llamar el metodo set return type de la clase Function''' self.functions[self.scope].set_return_type(function_return_type) def set_func_quad(self, func_quad): '''Manda llamar el metodo set_func_quad de la clase Function''' self.functions[self.scope].set_func_quad(func_quad) def set_scope(self, scope): '''Cambia el scope actual del directorio de funciones al scope que recibe''' self.scope = scope def reset_scope(self): '''Reset del scope a global scope''' self.scope = 'global' # Add variable to current function scope def add_var(self, variable_id, var_type, value=0, size=1): '''Agrega variable a el diccionario de variables de una Funcion''' if self.functions[self.scope].variables_dict.get(variable_id, None) is None: var_name = get_var_name(var_type, self.scope, variable_id) self.functions[self.scope].variables_dict[variable_id] = Variable(var_name, value, var_type, self.scope, size) else: variable_type = self.functions[self.scope].variables_dict[variable_id].get_type() msg = 'Error 2001: Variable already declared! ' + str(variable_id) + '. TYPE: ' + variable_type raise NameError(msg) def add_for_var(self, variable_id, var_type): '''Agrega variable al diccionario del current scope, si ya existe sobreescribe valor Marca error si existe y no es tipo int''' if self.functions[self.scope].variables_dict.get(variable_id, None) is None: var_name = get_var_name(var_type, self.scope, variable_id) self.functions[self.scope].variables_dict[variable_id] = Variable(var_name, -1, var_type, self.scope, 1) else: variable_type = self.functions[self.scope].variables_dict[variable_id].get_type() if variable_type != 'int': msg = 'Error 2001: Variable already declared! ' + str(variable_id) + '. TYPE: ' + variable_type raise NameError(msg) else: self.functions[self.scope].variables_dict[variable_id].value = -1 def validate_variable(self, variable_id): '''Busca variable en el scope actual''' if self.functions[self.scope].variables_dict.get(variable_id, None) is None: # Busca variable en el scope global if self.functions['global'].variables_dict.get(variable_id, None) is None: raise NameError('Error 2002: Variable not declared! VAR: ' + variable_id) def start_evaluating(self): '''Indica que el directorio de funciones esta evaluando la existencia de variables''' self.evaluating = True def finish_evaluating(self): '''Indica que el directorio de funciones deja de evaluar funciones''' self.evaluating = False def set_type(self, last_type): '''Set del ultimo token de tipo que fue leido''' self.last_type = last_type def get_func_dir(self): '''Obtiene el diccionario de funciones''' return self.functions def get_var(self, variable_id): '''Obtiene la lista con los datos de la variable del diccionario de funciones en el scope actual o el global''' if variable_id in self.functions[self.scope].variables_dict: return self.functions[self.scope].variables_dict.get(variable_id) elif variable_id in self.functions['global'].variables_dict: return self.functions['global'].variables_dict.get(variable_id) return None def set_call_function(self, function_id): '''Set del id de la funcion que esta siendo llamada una vez que se valido su existencia en el diccionario de funciones''' self.call_function.push(function_id) self.call_arguments.push(0) def increase_call_arguments(self): '''# Incrementa la cantidad de argumentos que estan siendo usados para llamar una funcion. Obtiene el tope de la pila, aumenta y vuelve a insertar en la pila''' curr = self.call_arguments.pop() curr += 1 self.call_arguments.push(curr) def update_var_size(self, size): '''Actualiza el size de una variable en caso de ser dimensionada''' if size <= 0: raise ValueError('Error 7005: Array size must be a positive integer') else: self.functions[self.scope].variables_dict[self.last_id.top].size = size self.functions[self.scope].variables_dict[self.last_id.top].is_dim = True def validate_call_arguments(self): '''Funcion que valida que la cantidad de argumentos utilizados en una llamada a funcion sea igual a los parametros que espera recibir''' if self.functions[self.call_function.top].expected_arguments != self.call_arguments.top: if self.functions[self.call_function.top].expected_arguments > self.call_arguments.top: msg = 'Error 3001: Missing arguments in function call for function: ' + str(self.call_function) elif self.functions[self.call_function.top].expected_arguments < self.call_arguments.top: msg = 'Error 3002: Too many arguments in function call for function: ' + str(self.call_function) msg += '. Expected arguments: ' + str(self.functions[self.call_function.top].expected_arguments) + '. Got: ' + str(self.call_arguments.top) self.call_arguments.pop() self.call_function.pop() raise ValueError(msg) else: self.call_arguments.pop() return self.call_function.pop() def validate_arg_type(self, var_type): '''Funcion que valida que el tipo de argumento que se manda sea del tipo esperado''' expected_type = self.functions[self.call_function.top].params[self.call_arguments.top - 1][1] if var_type != expected_type: msg = 'Error 3003: Expected type in function call ' + str(self.scope) + ': ' + expected_type msg += '. Got: ' + var_type raise ValueError(msg) return self.functions[self.call_function.top].params[self.call_arguments.top - 1] def verify_var_dim(self): '''Verifica que el id de una variable sea dimensionada''' var = self.get_var(self.last_id.top) if not var.is_dim: raise ValueError('Error 7003: Variable is not array') @property def current_scope(self): '''Propiedad del directorio de funciones para obtener el scope actual''' return self.scope def printeame(self): '''Funcion auxiliar para imprimir el contenido del directorio de funciones''' print('************ Functions Directory ************\n') for key, val in self.functions.iteritems(): print(str(val.return_type) + ' ' + str(key) + '('), for var in val.params: print(str(var[1]) + ' ' + str(var[0]) + ', '), print('): quad_num ' + str(val.get_function_quad())) for k, vals in val.variables_dict.iteritems(): print('\t' + vals.get_type() + ' ' + k + ' = ' + str(vals.get_value()) + ' size: ' + str(vals.get_size())) print('') print('*********************************************')
davilajose23/ProjectCobra
functions_dir.py
Python
mit
10,907
// generated by jsonenums -type=InKind; DO NOT EDIT package incoming import ( "encoding/json" "fmt" ) var ( _InKindNameToValue = map[string]InKind{ "control": control, "state": state, "checkForUpdates": checkForUpdates, "updateAvailable": updateAvailable, "updateBegin": updateBegin, "updateApply": updateApply, } _InKindValueToName = map[InKind]string{ control: "control", state: "state", checkForUpdates: "checkForUpdates", updateAvailable: "updateAvailable", updateBegin: "updateBegin", updateApply: "updateApply", } ) func init() { var v InKind if _, ok := interface{}(v).(fmt.Stringer); ok { _InKindNameToValue = map[string]InKind{ interface{}(control).(fmt.Stringer).String(): control, interface{}(state).(fmt.Stringer).String(): state, interface{}(checkForUpdates).(fmt.Stringer).String(): checkForUpdates, interface{}(updateAvailable).(fmt.Stringer).String(): updateAvailable, interface{}(updateBegin).(fmt.Stringer).String(): updateBegin, interface{}(updateApply).(fmt.Stringer).String(): updateApply, } } } // MarshalJSON is generated so InKind satisfies json.Marshaler. func (r InKind) MarshalJSON() ([]byte, error) { if s, ok := interface{}(r).(fmt.Stringer); ok { return json.Marshal(s.String()) } s, ok := _InKindValueToName[r] if !ok { return nil, fmt.Errorf("invalid InKind: %d", r) } return json.Marshal(s) } // UnmarshalJSON is generated so InKind satisfies json.Unmarshaler. func (r *InKind) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return fmt.Errorf("InKind should be a string, got %s", data) } v, ok := _InKindNameToValue[s] if !ok { return fmt.Errorf("invalid InKind %q", s) } *r = v return nil }
gamejolt/joltron
network/messages/incoming/inkind_jsonenums.go
GO
mit
1,837
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mod.Core.Cqrs.Api; namespace Mod.Core.Test.Query.MockQuery { public class QueryB: IQuery { public DateTime FromSearch { get; } public QueryB(DateTime fromSearch) { FromSearch = fromSearch; } } }
mtihector/Mod
Mod.Core.Test/Query/MockQuery/QueryB.cs
C#
mit
378
<div class="sidebar"> <div class="container"> <div class="sidebar-about"> <h1> <a href="{{ site.baseurl }}"> {{ site.title }} </a> </h1> <p class="lead">{{ site.description }}</p> </div> <nav class="sidebar-nav"> <a class="sidebar-nav-item{% if page.url == site.baseurl %} active{% endif %}" href="{{ site.baseurl }}">Home</a> {% comment %} The code below dynamically generates a sidebar nav of pages with `layout: page` in the front-matter. See readme for usage. {% endcomment %} {% assign pages_list = site.pages %} {% for node in pages_list %} {% if node.title != null %} {% if node.layout == "page" %} <a class="sidebar-nav-item{% if page.url == node.url %} active{% endif %}" href="{{ node.url }}">{{ node.title }}</a> {% endif %} {% endif %} {% endfor %} </nav> <hr /> <p class="light"><small>By <a href="https://github.com/unframework">Nick Matantsev</a> (<a href="https://twitter.com/unframework">@unframework</a>) and <a href="https://github.com/atesgoral">Ates Goral</a> (<a href="https://twitter.com/atesgoral">@atesgoral</a>)</small></p> </div> </div>
unframework/virtual-dom-gallery
_includes/sidebar.html
HTML
mit
1,241
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pagination</title> <link rel="stylesheet" href="../../node_modules/bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" href="../styles.css"> </head> <body> <div id="app" class="container"> <h4>Default</h4> <div is="uib-pagination" :total-items="totalItems" v-model="pagination1" @change="pageChanged()"></div> <div is="uib-pagination" :boundary-links="true" :total-items="totalItems" v-model="pagination1" class="pagination-sm" previous-text="&lsaquo;" next-text="&rsaquo;" first-text="&laquo;" last-text="&raquo;"></div> <div is="uib-pagination" :direction-links="false" :boundary-links="true" :total-items="totalItems" v-model="pagination1"></div> <div is="uib-pagination" :direction-links="false" :total-items="totalItems" v-model="pagination1"></div> <h6><code>page-label</code> returning <code>raw html</code>:</h6> <div is="uib-pagination" :direction-links="false" :total-items="totalItems" v-model="pagination1" :page-label="pageLabelHtml"></div> <pre>The selected page no: {{pagination1.currentPage}}</pre> <button type="button" class="btn btn-info" @click="setPage(3)">Set current page to: 3</button> <hr> <h4>Limit the maximum visible buttons</h4> <h6><code>rotate</code> defaulted to <code>true</code>:</h6> <uib-pagination :total-items="bigTotalItems" v-model="pagination2" :max-size="maxSize" class="pagination-sm" :boundary-links="true"></uib-pagination> <h6><code>rotate</code> defaulted to <code>true</code> and <code>force-ellipses</code> set to <code>true</code>:</h6> <uib-pagination :total-items="bigTotalItems" v-model="pagination2" :max-size="maxSize" class="pagination-sm" :boundary-links="true" :force-ellipses="true"></uib-pagination> <h6><code>rotate</code> set to <code>false</code>:</h6> <uib-pagination :total-items="bigTotalItems" v-model="pagination2" :max-size="maxSize" class="pagination-sm" :boundary-links="true" :rotate="false"></uib-pagination> <h6><code>boundary-link-numbers</code> set to <code>true</code> and <code>rotate</code> defaulted to <code>true</code>:</h6> <uib-pagination :total-items="bigTotalItems" v-model="pagination2" :max-size="maxSize" class="pagination-sm" :boundary-link-numbers="true"></uib-pagination> <h6><code>boundary-link-numbers</code> set to <code>true</code> and <code>rotate</code> set to <code>false</code>:</h6> <uib-pagination :total-items="bigTotalItems" v-model="pagination2" :max-size="maxSize" class="pagination-sm" :boundary-link-numbers="true" :rotate="false"></uib-pagination> <pre>Page: {{pagination2.currentPage}} / {{pagination2.numPages}}</pre> </div> <script src="dist/main.js"></script> </body> </html>
sant123/vuejs-uib-pagination
demo/commonjs/index.html
HTML
mit
2,889
package org.javacs; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import org.javacs.lsp.*; import org.junit.Assert; public class CompletionsBase { protected static JavaLanguageServer server = LanguageServerFixture.getJavaLanguageServer(); protected void refreshServer() { server = LanguageServerFixture.getJavaLanguageServer(); } protected List<String> insertTemplate(String file, int row, int column) { var items = items(file, row, column); return items.stream().map(CompletionsBase::itemInsertTemplate).collect(Collectors.toList()); } static String itemInsertTemplate(CompletionItem i) { var text = i.insertText; if (text == null) text = i.label; assert text != null : "Either insertText or label must be defined"; return text; } static String itemFilterText(CompletionItem i) { var text = i.filterText; if (text == null) text = i.label; assert text != null : "Either insertText or label must be defined"; return text; } protected List<String> label(String file, int row, int column) { var items = items(file, row, column); return items.stream().map(i -> i.label).collect(Collectors.toList()); } protected List<String> insertText(String file, int row, int column) { var items = items(file, row, column); return items.stream().map(CompletionsBase::itemInsertText).collect(Collectors.toList()); } protected List<String> filterText(String file, int row, int column) { var items = items(file, row, column); return items.stream().map(CompletionsBase::itemFilterText).collect(Collectors.toList()); } protected List<String> detail(String file, int row, int column) { var items = items(file, row, column); var result = new ArrayList<String>(); for (var i : items) { var resolved = resolve(i); result.add(resolved.detail); } return result; } protected Map<String, Integer> insertCount(String file, int row, int column) { var items = items(file, row, column); var result = new HashMap<String, Integer>(); for (var each : items) { var key = itemInsertText(each); var count = result.getOrDefault(key, 0) + 1; result.put(key, count); } return result; } static String itemInsertText(CompletionItem i) { var text = i.insertText; if (text == null) text = i.label; assert text != null : "Either insertText or label must be defined"; return text; } protected List<String> documentation(String file, int row, int column) { var items = items(file, row, column); return items.stream() .flatMap( i -> { if (i.documentation != null) return Stream.of(i.documentation.value.trim()); else return Stream.empty(); }) .collect(Collectors.toList()); } protected List<? extends CompletionItem> items(String file, int row, int column) { var uri = FindResource.uri(file); var position = new TextDocumentPositionParams(new TextDocumentIdentifier(uri), new Position(row - 1, column - 1)); var maybe = server.completion(position); if (!maybe.isPresent()) { Assert.fail("no items"); } return maybe.get().items; } protected CompletionItem resolve(CompletionItem item) { return server.resolveCompletionItem(item); } }
georgewfraser/vscode-javac
src/test/java/org/javacs/CompletionsBase.java
Java
mit
3,707
require_relative '../../../spec_helper' ruby_version_is ''...'2.8' do require 'rexml/document' describe "REXML::Attribute#node_type" do it "always returns :attribute" do attr = REXML::Attribute.new("foo", "bar") attr.node_type.should == :attribute REXML::Attribute.new(attr).node_type.should == :attribute end end end
eregon/rubyspec
library/rexml/attribute/node_type_spec.rb
Ruby
mit
352
using System.Diagnostics.CodeAnalysis; using Microsoft.AspNet.Identity; using NHibernate; namespace Dematt.Airy.Identity.Nhibernate { [SuppressMessage("ReSharper", "UnusedTypeParameter")] public class IdentityUserStore<TUser> : UserStore<IdentityUser, string, IdentityUserLogin, IdentityRole, string, IdentityUserClaim, int>, IUserStore<IdentityUser> where TUser : IdentityUser { public IdentityUserStore(ISession context) : base(context) { } } }
MatthewRudolph/Airy
src/Dematt.Airy.Identity.Nhibernate/IdentityUserStore.cs
C#
mit
528
package com.example.smartify.devices; import com.example.smartify.data.DevicesRepository; /** * Listens to user actions from the UI ({@link DevicesActivity}), retrieves the data and updates the * UI as required. */ class DevicesPresenter implements DevicesContract.UserActionsListener { private final DevicesContract.View mView; private final DevicesRepository mRepository; DevicesPresenter(DevicesContract.View view, DevicesRepository devicesRepository) { mRepository = devicesRepository; mView = view; } @Override public void addDevice() { mView.showAddDevice(); } @Override public void openDeviceDetail(int id, String name) { mView.showDeviceDetail(id, name); } @Override public void close(int id) { mRepository.close(id); } @Override public void open(int id) { mRepository.open(id); } @Override public void deleteDevice(int id) { mRepository.removeDevice(id); } @Override public void loadUI() { mRepository.loadAllDeviceStatuses(); } }
kkuchera/smartify
Smartify/app/src/main/java/com/example/smartify/devices/DevicesPresenter.java
Java
mit
1,104