text
stringlengths
2
1.04M
meta
dict
<?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 330772 $ --> <refentry xml:id="intltimezone.geterrormessage" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <refnamediv> <refname>IntlTimeZone::getErrorMessage</refname> <refname>intltz_get_error_message</refname> <refpurpose>Get last error message on the object</refpurpose> </refnamediv> <refsect1 role="description"> &reftitle.description; <para>&style.oop; (method):</para> <methodsynopsis> <modifier>public</modifier> <type>string</type><methodname>IntlTimeZone::getErrorMessage</methodname> <void /> </methodsynopsis> <para>&style.procedural;:</para> <methodsynopsis role="procedural"> <type>string</type><methodname>intltz_get_error_message</methodname> <void /> </methodsynopsis> <para> </para> &warn.undocumented.func; </refsect1> <refsect1 role="parameters"> &reftitle.parameters; &no.function.parameters; </refsect1> <refsect1 role="returnvalues"> &reftitle.returnvalues; <para> </para> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"~/.phpdoc/manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 -->
{ "content_hash": "8a65337c609ad5f552ae4c4de7ed563c", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 129, "avg_line_length": 23.676923076923078, "alnum_prop": 0.7179987004548408, "repo_name": "mziyut/.vim", "id": "44b5bbf7cadd05abf430f5469f19c4b47f23bf33", "size": "1539", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dict/.neocomplete-php/phpdoc/en/reference/intl/intltimezone/geterrormessage.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2223" }, { "name": "Ruby", "bytes": "939" }, { "name": "Shell", "bytes": "582" }, { "name": "Vim script", "bytes": "22415" } ], "symlink_target": "" }
namespace clang { namespace driver { class ArgList; /// \brief A concrete instance of a particular driver option. /// /// The Arg class encodes just enough information to be able to /// derive the argument values efficiently. In addition, Arg /// instances have an intrusive double linked list which is used by /// ArgList to provide efficient iteration over all instances of a /// particular option. class Arg { Arg(const Arg &) LLVM_DELETED_FUNCTION; void operator=(const Arg &) LLVM_DELETED_FUNCTION; private: /// \brief The option this argument is an instance of. const Option Opt; /// \brief The argument this argument was derived from (during tool chain /// argument translation), if any. const Arg *BaseArg; /// \brief How this instance of the option was spelled. StringRef Spelling; /// \brief The index at which this argument appears in the containing /// ArgList. unsigned Index; /// \brief Was this argument used to affect compilation? /// /// This is used for generating "argument unused" diagnostics. mutable unsigned Claimed : 1; /// \brief Does this argument own its values? mutable unsigned OwnsValues : 1; /// \brief The argument values, as C strings. SmallVector<const char *, 2> Values; public: Arg(const Option Opt, StringRef Spelling, unsigned Index, const Arg *BaseArg = 0); Arg(const Option Opt, StringRef Spelling, unsigned Index, const char *Value0, const Arg *BaseArg = 0); Arg(const Option Opt, StringRef Spelling, unsigned Index, const char *Value0, const char *Value1, const Arg *BaseArg = 0); ~Arg(); Option getOption() const { return Opt; } StringRef getSpelling() const { return Spelling; } unsigned getIndex() const { return Index; } /// \brief Return the base argument which generated this arg. /// /// This is either the argument itself or the argument it was /// derived from during tool chain specific argument translation. const Arg &getBaseArg() const { return BaseArg ? *BaseArg : *this; } void setBaseArg(const Arg *_BaseArg) { BaseArg = _BaseArg; } bool getOwnsValues() const { return OwnsValues; } void setOwnsValues(bool Value) const { OwnsValues = Value; } bool isClaimed() const { return getBaseArg().Claimed; } /// \brief Set the Arg claimed bit. void claim() const { getBaseArg().Claimed = true; } unsigned getNumValues() const { return Values.size(); } const char *getValue(unsigned N = 0) const { return Values[N]; } SmallVectorImpl<const char*> &getValues() { return Values; } bool containsValue(StringRef Value) const { for (unsigned i = 0, e = getNumValues(); i != e; ++i) if (Values[i] == Value) return true; return false; } /// \brief Append the argument onto the given array as strings. void render(const ArgList &Args, ArgStringList &Output) const; /// \brief Append the argument, render as an input, onto the given /// array as strings. /// /// The distinction is that some options only render their values /// when rendered as a input (e.g., Xlinker). void renderAsInput(const ArgList &Args, ArgStringList &Output) const; void dump() const; /// \brief Return a formatted version of the argument and /// its values, for debugging and diagnostics. std::string getAsString(const ArgList &Args) const; }; } // end namespace driver } // end namespace clang #endif
{ "content_hash": "27858a7f27cdae8eefb8ec32ec75c739", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 77, "avg_line_length": 32.53636363636364, "alnum_prop": 0.6624755518301202, "repo_name": "dplbsd/soc2013", "id": "662a2e2c618b3cda275e3ba4ae82bf22d69f4c14", "size": "4283", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "head/contrib/llvm/tools/clang/include/clang/Driver/Arg.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "AGS Script", "bytes": "62471" }, { "name": "Assembly", "bytes": "4478661" }, { "name": "Awk", "bytes": "278525" }, { "name": "Batchfile", "bytes": "20417" }, { "name": "C", "bytes": "383420305" }, { "name": "C++", "bytes": "72796771" }, { "name": "CSS", "bytes": "109748" }, { "name": "ChucK", "bytes": "39" }, { "name": "D", "bytes": "3784" }, { "name": "DIGITAL Command Language", "bytes": "10640" }, { "name": "DTrace", "bytes": "2311027" }, { "name": "Emacs Lisp", "bytes": "65902" }, { "name": "EmberScript", "bytes": "286" }, { "name": "Forth", "bytes": "184405" }, { "name": "GAP", "bytes": "72156" }, { "name": "Groff", "bytes": "32248806" }, { "name": "HTML", "bytes": "6749816" }, { "name": "IGOR Pro", "bytes": "6301" }, { "name": "Java", "bytes": "112547" }, { "name": "KRL", "bytes": "4950" }, { "name": "Lex", "bytes": "398817" }, { "name": "Limbo", "bytes": "3583" }, { "name": "Logos", "bytes": "187900" }, { "name": "Makefile", "bytes": "3551839" }, { "name": "Mathematica", "bytes": "9556" }, { "name": "Max", "bytes": "4178" }, { "name": "Module Management System", "bytes": "817" }, { "name": "NSIS", "bytes": "3383" }, { "name": "Objective-C", "bytes": "836351" }, { "name": "PHP", "bytes": "6649" }, { "name": "Perl", "bytes": "5530761" }, { "name": "Perl6", "bytes": "41802" }, { "name": "PostScript", "bytes": "140088" }, { "name": "Prolog", "bytes": "29514" }, { "name": "Protocol Buffer", "bytes": "61933" }, { "name": "Python", "bytes": "299247" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "Ruby", "bytes": "45958" }, { "name": "Scilab", "bytes": "197" }, { "name": "Shell", "bytes": "10501540" }, { "name": "SourcePawn", "bytes": "463194" }, { "name": "SuperCollider", "bytes": "80208" }, { "name": "Tcl", "bytes": "80913" }, { "name": "TeX", "bytes": "719821" }, { "name": "VimL", "bytes": "22201" }, { "name": "XS", "bytes": "25451" }, { "name": "XSLT", "bytes": "31488" }, { "name": "Yacc", "bytes": "1857830" } ], "symlink_target": "" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Transport.Channels.Embedded { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using DotNetty.Common; using DotNetty.Common.Concurrency; sealed class EmbeddedEventLoop : AbstractScheduledEventExecutor, IEventLoop { readonly Queue<IRunnable> tasks = new Queue<IRunnable>(2); public IEventExecutor Executor => this; public Task RegisterAsync(IChannel channel) => channel.Unsafe.RegisterAsync(this); public override bool IsShuttingDown => false; public override Task TerminationCompletion { get { throw new NotSupportedException(); } } public override bool IsShutdown => false; public override bool IsTerminated => false; public override bool IsInEventLoop(Thread thread) => true; public override void Execute(IRunnable command) { if (command == null) { throw new NullReferenceException("command"); } this.tasks.Enqueue(command); } public override Task ShutdownGracefullyAsync(TimeSpan quietPeriod, TimeSpan timeout) { throw new NotSupportedException(); } internal PreciseTimeSpan NextScheduledTask() => this.NextScheduledTaskNanos(); internal void RunTasks() { for (;;) { // have to perform an additional check since Queue<T> throws upon empty dequeue in .NET if (this.tasks.Count == 0) { break; } IRunnable task = this.tasks.Dequeue(); if (task == null) { break; } task.Run(); } } internal PreciseTimeSpan RunScheduledTasks() { PreciseTimeSpan time = GetNanos(); for (;;) { IRunnable task = this.PollScheduledTask(time); if (task == null) { return this.NextScheduledTaskNanos(); } task.Run(); } } internal new void CancelScheduledTasks() => base.CancelScheduledTasks(); } }
{ "content_hash": "771e36de856861baef895ae3117df961", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 103, "avg_line_length": 29.702380952380953, "alnum_prop": 0.558316633266533, "repo_name": "dragonphoenix/proto-java-csharp", "id": "15c4edc2bbf426330676c43099980533f2b5d654", "size": "2497", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "DotNetty/DotNetty.Transport/Channels/Embedded/EmbeddedEventLoop.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2395527" }, { "name": "Java", "bytes": "10108" }, { "name": "Protocol Buffer", "bytes": "3343" }, { "name": "Python", "bytes": "1464" } ], "symlink_target": "" }
ActiveRecord::Schema.define(version: 20140626050616543543459000) do create_table "coupons", force: true do |t| t.string "code" t.string "free_trial_length" t.datetime "created_at" t.datetime "updated_at" end create_table "customers", force: true do |t| t.string "email" t.datetime "created_at" t.datetime "updated_at" end create_table "plans", force: true do |t| t.string "name" t.string "stripe_id" t.float "price" t.text "features" t.boolean "highlight" t.integer "display_order" t.datetime "created_at" t.datetime "updated_at" t.string "interval" end create_table "subscriptions", force: true do |t| t.string "stripe_id" t.integer "plan_id" t.string "last_four" t.integer "coupon_id" t.string "card_type" t.float "current_price" t.integer "customer_id" t.datetime "created_at" t.datetime "updated_at" t.string "status" end end
{ "content_hash": "23cd140f30beb71a5b4ab7f112e4a61a", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 67, "avg_line_length": 24.146341463414632, "alnum_prop": 0.6212121212121212, "repo_name": "Papercloud/koudoku", "id": "91fc82d0d2b8f8543e086afdccac3b898dee932a", "size": "1731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/dummy/db/schema.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2279" }, { "name": "JavaScript", "bytes": "1282" }, { "name": "Ruby", "bytes": "51285" } ], "symlink_target": "" }
set projectname=staff.admin set target=%1% if "%target%" == "" ( echo. echo Error: Target is not set. exit 1 ) set arch=%2% if "%arch%" == "" ( echo. echo Error: Arch is not set. exit 1 ) set deploydir=%cd%\..\..\..\deploy\win_%arch% set componentdir=%deploydir%\staff\components\%projectname% if not EXIST %componentdir% mkdir %componentdir% xcopy /Y /S src\*.wsdl %componentdir%\ xcopy /Y /S %target%*.dll %componentdir%\
{ "content_hash": "97645f5697bdf49b89b0bd401e5ae648", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 59, "avg_line_length": 20.17391304347826, "alnum_prop": 0.6206896551724138, "repo_name": "google-code-export/staff", "id": "56c84aabd8b9b011ba163e3beaa699092aaa3fc0", "size": "464", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "staff/components/admin/AccountAdmin/deploy.cmd", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "935" }, { "name": "C", "bytes": "4572171" }, { "name": "C++", "bytes": "1851089" }, { "name": "Groff", "bytes": "4581" }, { "name": "HTML", "bytes": "11894" }, { "name": "Java", "bytes": "32294" }, { "name": "JavaScript", "bytes": "29536" }, { "name": "Makefile", "bytes": "214711" }, { "name": "PLpgSQL", "bytes": "8003" }, { "name": "Protocol Buffer", "bytes": "3274" }, { "name": "QMake", "bytes": "5757" }, { "name": "Shell", "bytes": "63310" } ], "symlink_target": "" }
NS_BEGIN(CORE_MATH_NAMESPACE) namespace scalar{ template<typename T> struct Pi{ static inline void operation(T & a){ a = M_PI; } }; } NS_END(CORE_MATH_NAMESPACE)
{ "content_hash": "f5a1791f51b5267ff7d341616a919a70", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 44, "avg_line_length": 21.6, "alnum_prop": 0.5416666666666666, "repo_name": "toeb/cpp.core", "id": "f2ff862c4f9b7f755613c3b9c9e1d491d9f5c381", "size": "303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core.math/includes/core.math/scalar/operation/Pi.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "33857" }, { "name": "C++", "bytes": "1403314" }, { "name": "CMake", "bytes": "6006" }, { "name": "Objective-C", "bytes": "81" } ], "symlink_target": "" }
import codecs import sys import getopt import os from learning.PageManager import PageManager import json import time import logging logger = logging.getLogger("landmark") # logging.basicConfig(level=logging.INFO) # logger = logging.getLogger("landmark") # handler = logging.FileHandler('landmark.log') # handler.setLevel(logging.INFO) # formatter = logging.Formatter(u'%(asctime)s - %(name)s - %(levelname)s - %(message)s') # handler.setFormatter(formatter) # logger.addHandler(handler) class Usage(Exception): def __init__(self, msg): self.msg = msg def learn_rules_with_markup(markup_file, pages_map): print pages_map for page in pages_map: print page def main(argv=None): if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[1:], "dh", ["debug", "help"]) write_debug_files = False for opt in opts: if opt in [('-d', ''), ('--debug', '')]: write_debug_files = True if opt in [('-h', ''), ('--help', '')]: raise Usage('python -m learning.RuleLearner [OPTIONAL_PARAMS] [TEST_FILES_FOLDER] [MARKUP_FILE]\n\t[OPTIONAL_PARAMS]: -d to get debug stripe html files') except getopt.error, msg: raise Usage(msg) logger.info('Running RuleLearner with file at %s for rules %s', args[0], args[1]) #read the directory location from arg0 page_file_dir = args[0] pageManager = PageManager(write_debug_files) start_time = time.time() for subdir, dirs, files in os.walk(page_file_dir): for the_file in files: if the_file.startswith('.'): continue with codecs.open(os.path.join(subdir, the_file), "r", "utf-8") as myfile: page_str = myfile.read().encode('utf-8') pageManager.addPage(the_file, page_str) logger.info("--- LOAD PAGES: %s seconds ---" % (time.time() - start_time)) #Read the markups from a file... start_time = time.time() markups_file = args[1] with codecs.open(markups_file, "r", "utf-8") as myfile: markup_str = myfile.read().encode('utf-8') markups = json.loads(markup_str) markups.pop("__SCHEMA__", None) markups.pop("__URLS__", None) logger.info("--- LOAD MARKUPS: %s seconds ---" % (time.time() - start_time)) pageManager.learnStripes(markups) start_time = time.time() rule_set = pageManager.learnRulesFromMarkup(markups) logger.info("--- LEARN RULES FROM MARKUP: %s seconds ---" % (time.time() - start_time)) if(len(args) > 2): output_file = args[2] with codecs.open(output_file, "w", "utf-8") as myfile: myfile.write(rule_set.toJson()) myfile.close() else: print rule_set.toJson() except Usage, err: print >>sys.stderr, err.msg print >>sys.stderr, "for help use --help" return 2 if __name__ == '__main__': start_time = time.time() main() logger.info("--- %s seconds ---" % (time.time() - start_time)) # sys.exit(main())
{ "content_hash": "f1517cfd7918c07f035caa19a68d7c3f", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 173, "avg_line_length": 34.43877551020408, "alnum_prop": 0.5466666666666666, "repo_name": "usc-isi-i2/landmark-extraction", "id": "c8024ed2ca0dd7f00e42ebffe28d0ab66f41364d", "size": "3430", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/learning/RuleLearner.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "219901" }, { "name": "HTML", "bytes": "68207" }, { "name": "Python", "bytes": "232643" }, { "name": "Shell", "bytes": "1758" } ], "symlink_target": "" }
Library for network operations.
{ "content_hash": "01723522e9eee4564c739fa860319f56", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 31, "avg_line_length": 32, "alnum_prop": 0.84375, "repo_name": "Xevle/Xevle.Network", "id": "3806ca51f111c493a49fbf29be9cf9328e4fc1b3", "size": "48", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3236" } ], "symlink_target": "" }
@implementation JsonObject @synthesize json; - (id) initWithJson:(id)obj { self = [super init]; if (self) { json = [obj retain]; } return self; } - (id) initWithContentsOfFile:(NSString *)path { NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; if (str) { return [self initWithJson:[str JSONValue]]; } return nil; } - (void) dealloc { [json release]; [super dealloc]; } - (void) writeToFile:(NSString *)path { [[self data] writeToFile:path atomically:YES]; } - (NSData *) data { return [[json JSONRepresentation] dataUsingEncoding:NSUTF8StringEncoding]; } - (id) valueForKey:(NSString *)key { return [json valueForKey:key]; } - (void) merge:(NSDictionary *)d { NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:json]; [mdic addEntriesFromDictionary:d]; [json release]; json = [mdic retain]; } @end
{ "content_hash": "6c012f9b43b41432c22a3f501cffb934", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 98, "avg_line_length": 20, "alnum_prop": 0.7055555555555556, "repo_name": "cathandnya/Pixitail", "id": "d7a2dd31b7e6165b714765cf7ccd7edb6580932a", "size": "1060", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/Tumblr2/JsonObject.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "145135" }, { "name": "Objective-C", "bytes": "4873030" }, { "name": "Ruby", "bytes": "360" }, { "name": "Swift", "bytes": "26459" } ], "symlink_target": "" }
declare module 'react-simplemde-editor' { declare module.exports: any; } declare module 'react-simplemde-editor/dist/simplemde.min.css' { declare module.exports: any; }
{ "content_hash": "8d712ad7601b9a1c77a46c7bd5e912d9", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 64, "avg_line_length": 24.857142857142858, "alnum_prop": 0.7528735632183908, "repo_name": "lbryio/lbry-electron", "id": "7d23780f12b937179a81663bce9c559a10b60b2b", "size": "174", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "flow-typed/react-simplemde-editor.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4033" }, { "name": "PowerShell", "bytes": "698" }, { "name": "Python", "bytes": "8616" }, { "name": "Shell", "bytes": "3646" } ], "symlink_target": "" }
package com.cognifide.apm.api.actions; import com.cognifide.apm.api.exceptions.ActionExecutionException; import javax.jcr.RepositoryException; import javax.jcr.ValueFactory; import javax.jcr.security.AccessControlManager; import org.apache.jackrabbit.api.JackrabbitSession; import org.apache.jackrabbit.api.security.user.Authorizable; import org.apache.jackrabbit.api.security.user.Group; import org.apache.jackrabbit.api.security.user.User; public interface Context { ValueFactory getValueFactory() throws RepositoryException; Authorizable getCurrentAuthorizable() throws ActionExecutionException; Authorizable getCurrentAuthorizableIfExists(); Group getCurrentGroup() throws ActionExecutionException; User getCurrentUser() throws ActionExecutionException; void clearCurrentAuthorizable(); AccessControlManager getAccessControlManager(); AuthorizableManager getAuthorizableManager(); SessionSavingPolicy getSavingPolicy(); JackrabbitSession getSession(); void setCurrentAuthorizable(Authorizable currentAuthorizable); ActionResult createActionResult(); Context newContext(); }
{ "content_hash": "6d9149d202c2627d4f5d0aa1704e577b", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 72, "avg_line_length": 29, "alnum_prop": 0.803448275862069, "repo_name": "Cognifide/APM", "id": "53006a95bb507fbbf744a2d68958ab5fa162d2f7", "size": "1982", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/aem/api/src/main/java/com/cognifide/apm/api/actions/Context.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "3662" }, { "name": "CSS", "bytes": "7787" }, { "name": "Groovy", "bytes": "31249" }, { "name": "HTML", "bytes": "18936" }, { "name": "Java", "bytes": "555816" }, { "name": "JavaScript", "bytes": "37717" }, { "name": "Kotlin", "bytes": "75168" } ], "symlink_target": "" }
namespace http { #ifdef _WIN32 class WinSock final { public: WinSock() { WSADATA wsaData; int error = WSAStartup(MAKEWORD(2, 2), &wsaData); if (error != 0) throw std::system_error(error, std::system_category(), "WSAStartup failed"); if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) throw std::runtime_error("Invalid WinSock version"); started = true; } ~WinSock() { if (started) WSACleanup(); } WinSock(const WinSock &) = delete; WinSock &operator=(const WinSock &) = delete; WinSock(WinSock &&other) : started(other.started) { other.started = false; } WinSock &operator=(WinSock &&other) { if (&other != this) { if (started) WSACleanup(); started = other.started; other.started = false; } return *this; } private: bool started = false; }; #endif inline int getLastError() { #ifdef _WIN32 return WSAGetLastError(); #else return errno; #endif } enum class InternetProtocol : uint8_t { V4, V6 }; inline int getAddressFamily(InternetProtocol internetProtocol) { switch (internetProtocol) { case InternetProtocol::V4: return AF_INET; case InternetProtocol::V6: return AF_INET6; default: throw std::runtime_error("Unsupported protocol"); } } class Socket final { public: Socket(InternetProtocol internetProtocol) : endpoint(socket(getAddressFamily(internetProtocol), SOCK_STREAM, IPPROTO_TCP)) { #ifdef _WIN32 if (endpoint == INVALID_SOCKET) throw std::system_error(WSAGetLastError(), std::system_category(), "Failed to create socket"); #else if (endpoint == -1) throw std::system_error(errno, std::system_category(), "Failed to create socket"); #endif } #ifdef _WIN32 Socket(SOCKET s) : endpoint(s) { } #else Socket(int s): endpoint(s) { } #endif ~Socket() { #ifdef _WIN32 if (endpoint != INVALID_SOCKET) closesocket(endpoint); #else if (endpoint != -1) close(endpoint); #endif } Socket(const Socket &) = delete; Socket &operator=(const Socket &) = delete; Socket(Socket &&other) : endpoint(other.endpoint) { #ifdef _WIN32 other.endpoint = INVALID_SOCKET; #else other.endpoint = -1; #endif } Socket &operator=(Socket &&other) { if (&other != this) { #ifdef _WIN32 if (endpoint != INVALID_SOCKET) closesocket(endpoint); #else if (endpoint != -1) close(endpoint); #endif endpoint = other.endpoint; #ifdef _WIN32 other.endpoint = INVALID_SOCKET; #else other.endpoint = -1; #endif } return *this; } #ifdef _WIN32 operator SOCKET() const { return endpoint; } #else operator int() const { return endpoint; } #endif private: #ifdef _WIN32 SOCKET endpoint = INVALID_SOCKET; #else int endpoint = -1; #endif }; inline std::string urlEncode(const std::string &str) { static const char hexChars[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; std::string result; for (auto i = str.begin(); i != str.end(); ++i) { uint8_t cp = *i & 0xFF; if ((cp >= 0x30 && cp <= 0x39) || // 0-9 (cp >= 0x41 && cp <= 0x5A) || // A-Z (cp >= 0x61 && cp <= 0x7A) || // a-z cp == 0x2D || cp == 0x2E || cp == 0x5F) // - . _ result += static_cast<char>(cp); else if (cp <= 0x7F) // length = 1 result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; else if ((cp >> 5) == 0x6) // length = 2 { result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; if (++i == str.end()) break; result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; } else if ((cp >> 4) == 0xe) // length = 3 { result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; if (++i == str.end()) break; result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; if (++i == str.end()) break; result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; } else if ((cp >> 3) == 0x1e) // length = 4 { result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; if (++i == str.end()) break; result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; if (++i == str.end()) break; result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; if (++i == str.end()) break; result += std::string("%") + hexChars[(*i & 0xF0) >> 4] + hexChars[*i & 0x0F]; } } return result; } struct Response final { enum Status { STATUS_CONTINUE = 100, STATUS_SWITCHINGPROTOCOLS = 101, STATUS_PROCESSING = 102, STATUS_EARLYHINTS = 103, STATUS_OK = 200, STATUS_CREATED = 201, STATUS_ACCEPTED = 202, STATUS_NONAUTHORITATIVEINFORMATION = 203, STATUS_NOCONTENT = 204, STATUS_RESETCONTENT = 205, STATUS_PARTIALCONTENT = 206, STATUS_MULTISTATUS = 207, STATUS_ALREADYREPORTED = 208, STATUS_IMUSED = 226, STATUS_MULTIPLECHOICES = 300, STATUS_MOVEDPERMANENTLY = 301, STATUS_FOUND = 302, STATUS_SEEOTHER = 303, STATUS_NOTMODIFIED = 304, STATUS_USEPROXY = 305, STATUS_TEMPORARYREDIRECT = 307, STATUS_PERMANENTREDIRECT = 308, STATUS_BADREQUEST = 400, STATUS_UNAUTHORIZED = 401, STATUS_PAYMENTREQUIRED = 402, STATUS_FORBIDDEN = 403, STATUS_NOTFOUND = 404, STATUS_METHODNOTALLOWED = 405, STATUS_NOTACCEPTABLE = 406, STATUS_PROXYAUTHENTICATIONREQUIRED = 407, STATUS_REQUESTTIMEOUT = 408, STATUS_CONFLICT = 409, STATUS_GONE = 410, STATUS_LENGTHREQUIRED = 411, STATUS_PRECONDITIONFAILED = 412, STATUS_PAYLOADTOOLARGE = 413, STATUS_URITOOLONG = 414, STATUS_UNSUPPORTEDMEDIATYPE = 415, STATUS_RANGENOTSATISFIABLE = 416, STATUS_EXPECTATIONFAILED = 417, STATUS_IMATEAPOT = 418, STATUS_MISDIRECTEDREQUEST = 421, STATUS_UNPROCESSABLEENTITY = 422, STATUS_LOCKED = 423, STATUS_FAILEDDEPENDENCY = 424, STATUS_TOOEARLY = 425, STATUS_UPGRADEREQUIRED = 426, STATUS_PRECONDITIONREQUIRED = 428, STATUS_TOOMANYREQUESTS = 429, STATUS_REQUESTHEADERFIELDSTOOLARGE = 431, STATUS_UNAVAILABLEFORLEGALREASONS = 451, STATUS_INTERNALSERVERERROR = 500, STATUS_NOTIMPLEMENTED = 501, STATUS_BADGATEWAY = 502, STATUS_SERVICEUNAVAILABLE = 503, STATUS_GATEWAYTIMEOUT = 504, STATUS_HTTPVERSIONNOTSUPPORTED = 505, STATUS_VARIANTALSONEGOTIATES = 506, STATUS_INSUFFICIENTSTORAGE = 507, STATUS_LOOPDETECTED = 508, STATUS_NOTEXTENDED = 510, STATUS_NETWORKAUTHENTICATIONREQUIRED = 511 }; int status = 0; std::vector<std::string> headers; std::vector<uint8_t> body; }; class Request final { public: Request(const std::string &url, InternetProtocol protocol = InternetProtocol::V4) : internetProtocol(protocol) { const size_t schemeEndPosition = url.find("://"); if (schemeEndPosition != std::string::npos) { scheme = url.substr(0, schemeEndPosition); path = url.substr(schemeEndPosition + 3); } else { scheme = "http"; path = url; } const size_t fragmentPosition = path.find('#'); // remove the fragment part if (fragmentPosition != std::string::npos) path.resize(fragmentPosition); const std::string::size_type pathPosition = path.find('/'); if (pathPosition == std::string::npos) { domain = path; path = "/"; } else { domain = path.substr(0, pathPosition); path = path.substr(pathPosition); } const std::string::size_type portPosition = domain.find(':'); if (portPosition != std::string::npos) { port = domain.substr(portPosition + 1); domain.resize(portPosition); } else port = "80"; } Response send(const std::string &method, const std::map<std::string, std::string> &parameters, const std::vector<std::string> &headers = {}) { std::string body; bool first = true; for (const auto &parameter : parameters) { if (!first) body += "&"; first = false; body += urlEncode(parameter.first) + "=" + urlEncode(parameter.second); } return send(method, body, headers); } Response send(const std::string &method = "GET", const std::string &body = "", const std::vector<std::string> &headers = {}) { Response response; if (scheme != "http") throw std::runtime_error("Only HTTP scheme is supported"); addrinfo hints = {}; hints.ai_family = getAddressFamily(internetProtocol); hints.ai_socktype = SOCK_STREAM; addrinfo *info; if (getaddrinfo(domain.c_str(), port.c_str(), &hints, &info) != 0) throw std::system_error(getLastError(), std::system_category(), "Failed to get address info of " + domain); Socket socket(internetProtocol); // take the first address from the list if (::connect(socket, info->ai_addr, info->ai_addrlen) < 0) { freeaddrinfo(info); throw std::system_error(getLastError(), std::system_category(), "Failed to connect to " + domain + ":" + port); } freeaddrinfo(info); std::string requestData = method + " " + path + " HTTP/1.1\r\n"; for (const std::string &header : headers) requestData += header + "\r\n"; requestData += "Host: " + domain + "\r\n"; requestData += "Content-Length: " + std::to_string(body.size()) + "\r\n"; requestData += "\r\n"; requestData += body; #if defined(__APPLE__) || defined(_WIN32) const int flags = 0; #else const int flags = MSG_NOSIGNAL; #endif #ifdef _WIN32 int remaining = static_cast<int>(requestData.size()); int sent = 0; int size; #else ssize_t remaining = static_cast<ssize_t>(requestData.size()); ssize_t sent = 0; ssize_t size; #endif do { size = ::send(socket, requestData.data() + sent, static_cast<size_t>(remaining), flags); if (size < 0) throw std::system_error(getLastError(), std::system_category(), "Failed to send data to " + domain + ":" + port); remaining -= size; sent += size; } while (remaining > 0); uint8_t TEMP_BUFFER[65536]; static const uint8_t clrf[] = {'\r', '\n'}; std::vector<uint8_t> responseData; bool firstLine = true; bool parsedHeaders = false; int contentSize = -1; bool chunkedResponse = false; size_t expectedChunkSize = 0; bool removeCLRFAfterChunk = false; do { size = recv(socket, reinterpret_cast<char *>(TEMP_BUFFER), sizeof(TEMP_BUFFER), flags); if (size < 0) throw std::system_error(getLastError(), std::system_category(), "Failed to read data from " + domain + ":" + port); else if (size == 0) break; // disconnected responseData.insert(responseData.end(), TEMP_BUFFER, TEMP_BUFFER + size); if (!parsedHeaders) { for (;;) { auto i = std::search(responseData.begin(), responseData.end(), std::begin(clrf), std::end(clrf)); // didn't find a newline if (i == responseData.end()) break; std::string line(responseData.begin(), i); responseData.erase(responseData.begin(), i + 2); // empty line indicates the end of the header section if (line.empty()) { parsedHeaders = true; break; } else if (firstLine) // first line { firstLine = false; std::string::size_type pos, lastPos = 0, length = line.length(); std::vector<std::string> parts; // tokenize first line while (lastPos < length + 1) { pos = line.find(' ', lastPos); if (pos == std::string::npos) pos = length; if (pos != lastPos) parts.emplace_back(line.data() + lastPos, static_cast<std::vector<std::string>::size_type>(pos) - lastPos); lastPos = pos + 1; } if (parts.size() >= 2) response.status = std::stoi(parts[1]); } else // headers { response.headers.push_back(line); std::string::size_type pos = line.find(':'); if (pos != std::string::npos) { std::string headerName = line.substr(0, pos); std::string headerValue = line.substr(pos + 1); // ltrim headerValue.erase(headerValue.begin(), std::find_if(headerValue.begin(), headerValue.end(), [](int c) { return !std::isspace(c); })); // rtrim headerValue.erase(std::find_if(headerValue.rbegin(), headerValue.rend(), [](int c) { return !std::isspace(c); }).base(), headerValue.end()); if (headerName == "Content-Length") contentSize = std::stoi(headerValue); else if (headerName == "Transfer-Encoding" && headerValue == "chunked") chunkedResponse = true; } } } } if (parsedHeaders) { if (chunkedResponse) { bool dataReceived = false; for (;;) { if (expectedChunkSize > 0) { auto toWrite = std::min(expectedChunkSize, responseData.size()); response.body.insert(response.body.end(), responseData.begin(), responseData.begin() + static_cast<ptrdiff_t>(toWrite)); responseData.erase(responseData.begin(), responseData.begin() + static_cast<ptrdiff_t>(toWrite)); expectedChunkSize -= toWrite; if (expectedChunkSize == 0) removeCLRFAfterChunk = true; if (responseData.empty()) break; } else { if (removeCLRFAfterChunk) { if (responseData.size() >= 2) { removeCLRFAfterChunk = false; responseData.erase(responseData.begin(), responseData.begin() + 2); } else break; } auto i = std::search(responseData.begin(), responseData.end(), std::begin(clrf), std::end(clrf)); if (i == responseData.end()) break; std::string line(responseData.begin(), i); responseData.erase(responseData.begin(), i + 2); expectedChunkSize = std::stoul(line, 0, 16); if (expectedChunkSize == 0) { dataReceived = true; break; } } } if (dataReceived) break; } else { response.body.insert(response.body.end(), responseData.begin(), responseData.end()); responseData.clear(); // got the whole content if (contentSize == -1 || response.body.size() >= static_cast<size_t>(contentSize)) break; } } } while (size > 0); return response; } private: #ifdef _WIN32 WinSock winSock; #endif InternetProtocol internetProtocol; std::string scheme; std::string domain; std::string port; std::string path; }; } #endif
{ "content_hash": "3443a67ac60d383a28b2614a9de4b3e5", "timestamp": "", "source": "github", "line_count": 546, "max_line_length": 120, "avg_line_length": 35.8021978021978, "alnum_prop": 0.44920196439533455, "repo_name": "richkmeli/Richkware", "id": "795b622496773aee863ce1d58cbe72d97ff489db", "size": "20282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/HTTPRequest.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "116561" }, { "name": "CMake", "bytes": "628" }, { "name": "Makefile", "bytes": "1467" } ], "symlink_target": "" }
package gov.nih.nci.caadapter.common.validation; import gov.nih.nci.caadapter.common.ApplicationException; /** * An application exception that that occurs when business rules are violated. * * @author OWNER: Matthew Giordano * @author LAST UPDATE $Author: phadkes $ * @version $Revision: 1.3 $ * @since caAdapter v1.2 */ public class ValidationException extends ApplicationException { public ValidationException(String message, Throwable cause) { super(message, cause); } public ValidationException(String message, Throwable cause, String severity) { super(message, cause, severity); } } /** * HISTORY : $Log: not supported by cvs2svn $ */
{ "content_hash": "e311c4b4ab32e26d45b495eb1d94125f", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 78, "avg_line_length": 21.612903225806452, "alnum_prop": 0.7343283582089553, "repo_name": "NCIP/caadapter", "id": "664cb6a762d26a2c1775c46150c80a4ab9cc7397", "size": "840", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "software/caadapter/src/java/gov/nih/nci/caadapter/common/validation/ValidationException.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "5177" }, { "name": "CSS", "bytes": "140722" }, { "name": "Java", "bytes": "8275293" }, { "name": "JavaScript", "bytes": "224288" }, { "name": "Shell", "bytes": "8013" }, { "name": "XQuery", "bytes": "41953" }, { "name": "XSLT", "bytes": "269567" } ], "symlink_target": "" }
<!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" xml:lang="null" lang="null"> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /><title>JspEncodingTest xref</title> <link type="text/css" rel="stylesheet" href="../../../../../../stylesheet.css" /> </head> <body> <pre> <a name="1" href="#1">1</a> <strong>package</strong> test.net.sourceforge.pmd.jsp.rules; <a name="2" href="#2">2</a> <a name="3" href="#3">3</a> <strong>import</strong> org.junit.Before; <a name="4" href="#4">4</a> <a name="5" href="#5">5</a> <strong>import</strong> test.net.sourceforge.pmd.testframework.SimpleAggregatorTst; <a name="6" href="#6">6</a> <a name="7" href="#7">7</a> <strong>public</strong> <strong>class</strong> <a href="../../../../../../test/net/sourceforge/pmd/jsp/rules/JspEncodingTest.html">JspEncodingTest</a> <strong>extends</strong> <a href="../../../../../../test/net/sourceforge/pmd/testframework/SimpleAggregatorTst.html">SimpleAggregatorTst</a> { <a name="8" href="#8">8</a> <a name="9" href="#9">9</a> @Before <a name="10" href="#10">10</a> <strong>public</strong> <strong>void</strong> setUp() { <a name="11" href="#11">11</a> addRule(<span class="string">"jsp"</span>, <span class="string">"JspEncoding"</span>); <a name="12" href="#12">12</a> } <a name="13" href="#13">13</a> <a name="14" href="#14">14</a> <strong>public</strong> <strong>static</strong> junit.framework.Test suite() { <a name="15" href="#15">15</a> <strong>return</strong> <strong>new</strong> junit.framework.JUnit4TestAdapter(JspEncodingTest.<strong>class</strong>); <a name="16" href="#16">16</a> } <a name="17" href="#17">17</a> } <a name="18" href="#18">18</a> </pre> <hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body> </html>
{ "content_hash": "5ce91c42a93efd854a2054ecda8a4b4a", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 323, "avg_line_length": 64.16129032258064, "alnum_prop": 0.6269482151835093, "repo_name": "pscadiz/pmd-4.2.6-gds", "id": "418fa1a5605a84ecc6ad99cc3112905eb861138e", "size": "1989", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "docs/xref-test/test/net/sourceforge/pmd/jsp/rules/JspEncodingTest.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3336" }, { "name": "CSS", "bytes": "1241" }, { "name": "HTML", "bytes": "440" }, { "name": "Java", "bytes": "2602537" }, { "name": "JavaScript", "bytes": "7987" }, { "name": "Ruby", "bytes": "845" }, { "name": "Shell", "bytes": "19634" }, { "name": "XSLT", "bytes": "60577" } ], "symlink_target": "" }
import datetime from django import template from django.core.urlresolvers import reverse as urlreverse from django.conf import settings from django.db.models import Q from django.utils.safestring import mark_safe from ietf.ietfauth.utils import user_is_person, has_role from ietf.doc.models import BallotDocEvent, BallotPositionDocEvent, IESG_BALLOT_ACTIVE_STATES, IESG_SUBSTATE_TAGS register = template.Library() def render_ballot_icon(user, doc): if not doc: return "" # FIXME: temporary backwards-compatibility hack from ietf.doc.models import Document if not isinstance(doc, Document): doc = doc._draft if doc.type_id == "draft": if doc.get_state_slug("draft-iesg") not in IESG_BALLOT_ACTIVE_STATES: return "" elif doc.type_id == "charter": if doc.get_state_slug() not in ("intrev", "iesgrev"): return "" elif doc.type_id == "conflrev": if doc.get_state_slug() not in ("iesgeval","defer"): return "" elif doc.type_id == "statchg": if doc.get_state_slug() not in ("iesgeval","defer"): return "" ballot = doc.active_ballot() if not ballot: return "" def sort_key(t): _, pos = t if not pos: return (2, 0) elif pos.pos.blocking: return (0, pos.pos.order) else: return (1, pos.pos.order) positions = list(doc.active_ballot().active_ad_positions().items()) positions.sort(key=sort_key) edit_position_url = "" if has_role(user, "Area Director"): edit_position_url = urlreverse('ietf.idrfc.views_ballot.edit_position', kwargs=dict(name=doc.name, ballot_id=ballot.pk)) title = "IESG positions (click to show more%s)" % (", right-click to edit position" if edit_position_url else "") res = ['<a href="%s" data-popup="%s" data-edit="%s" title="%s" class="ballot-icon"><table>' % ( urlreverse("doc_ballot", kwargs=dict(name=doc.name, ballot_id=ballot.pk)), urlreverse("ietf.doc.views_doc.ballot_popup", kwargs=dict(name=doc.name, ballot_id=ballot.pk)), edit_position_url, title )] res.append("<tr>") for i, (ad, pos) in enumerate(positions): if i > 0 and i % 5 == 0: res.append("</tr>") res.append("<tr>") c = "position-%s" % (pos.pos.slug if pos else "norecord") if user_is_person(user, ad): c += " my" res.append('<td class="%s" />' % c) res.append("</tr>") res.append("</table></a>") return "".join(res) class BallotIconNode(template.Node): def __init__(self, doc_var): self.doc_var = doc_var def render(self, context): doc = template.resolve_variable(self.doc_var, context) return render_ballot_icon(context.get("user"), doc) def do_ballot_icon(parser, token): try: tag_name, doc_name = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0] return BallotIconNode(doc_name) register.tag('ballot_icon', do_ballot_icon) @register.filter def my_position(doc, user): if not has_role(user, "Area Director"): return None # FIXME: temporary backwards-compatibility hack from ietf.doc.models import Document if not isinstance(doc, Document): doc = doc._draft ballot = doc.active_ballot() pos = "No Record" if ballot: changed_pos = doc.latest_event(BallotPositionDocEvent, type="changed_ballot_position", ad__user=user, ballot=ballot) if changed_pos: pos = changed_pos.pos.name; return pos @register.filter() def state_age_colored(doc): # FIXME: temporary backwards-compatibility hack from ietf.doc.models import Document if not isinstance(doc, Document): doc = doc._draft if doc.type_id == 'draft': if not doc.get_state_slug() in ["active", "rfc"]: # Don't show anything for expired/withdrawn/replaced drafts return "" main_state = doc.get_state_slug('draft-iesg') if not main_state: return "" if main_state in ["dead", "watching", "pub"]: return "" try: state_date = doc.docevent_set.filter( Q(desc__istartswith="Draft Added by ")| Q(desc__istartswith="Draft Added in state ")| Q(desc__istartswith="Draft added in state ")| Q(desc__istartswith="State changed to ")| Q(desc__istartswith="State Changes to ")| Q(desc__istartswith="Sub state has been changed to ")| Q(desc__istartswith="State has been changed to ")| Q(desc__istartswith="IESG has approved and state has been changed to")| Q(desc__istartswith="IESG process started in state") ).order_by('-time')[0].time.date() except IndexError: state_date = datetime.date(1990,1,1) days = (datetime.date.today() - state_date).days # loosely based on # http://trac.tools.ietf.org/group/iesg/trac/wiki/PublishPath if main_state == "lc": goal1 = 30 goal2 = 30 elif main_state == "rfcqueue": goal1 = 60 goal2 = 120 elif main_state in ["lc-req", "ann"]: goal1 = 4 goal2 = 7 elif 'need-rev' in [x.slug for x in doc.tags.all()]: goal1 = 14 goal2 = 28 elif main_state == "pub-req": goal1 = 7 goal2 = 14 elif main_state == "ad-eval": goal1 = 14 goal2 = 28 else: goal1 = 14 goal2 = 28 if days > goal2: class_name = "ietf-small ietf-highlight-r" elif days > goal1: class_name = "ietf-small ietf-highlight-y" else: class_name = "ietf-small" if days > goal1: title = ' title="Goal is &lt;%d days"' % (goal1,) else: title = '' return mark_safe('<span class="%s"%s>(for&nbsp;%d&nbsp;day%s)</span>' % ( class_name, title, days, 's' if days != 1 else '')) else: return ""
{ "content_hash": "c8ddb3929ef410f8f5feafdb73c59d97", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 128, "avg_line_length": 34.57754010695187, "alnum_prop": 0.559851531085679, "repo_name": "mcr/ietfdb", "id": "29f0b79e7273539a543d8edc13923fcfa460be2d", "size": "8139", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ietf/idrfc/templatetags/ballot_icon_redesign.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "239198" }, { "name": "JavaScript", "bytes": "450755" }, { "name": "Perl", "bytes": "3223" }, { "name": "Python", "bytes": "10286676" }, { "name": "Ruby", "bytes": "3468" }, { "name": "Shell", "bytes": "39950" }, { "name": "TeX", "bytes": "23944" } ], "symlink_target": "" }
var path = require('path'); var assert = require('assert'); describe('confo', function() { beforeEach(function() { this.confo = require('..'); }); afterEach(function() { this.confo = undefined; }); it('should add _confo property in test environment', function() { assert.equal(typeof this.confo._confo, 'object'); }); it('should not add _confo property in other environments', function() { var confo = this.confo._confo.load({ NODE_ENV: 'dev' });; assert.equal(confo._confo, undefined); }); it('should use right env', function() { assert.equal(this.confo._confo.env, 'test'); }); it('should respect CONFO_FILE env variable', function() { assert.equal(this.confo._confo.rcPath, process.env.CONFO_FILE); }); it('should throw an error if rc file was not found', function() { assert.throws(function() { this.confo._confo.load({ CONFO_FILE: 'invalid_path.json' }); }, Error); }); it('should throw an error if rc file cant be parsed', function() { assert.throws(function() { this.confo._confo.load({ CONFO_FILE: 'confo_invalid.json' }); }, Error); }); it('should throw an error if path for current env was not found', function() { assert.throws(function() { this.confo._confo.load({ NODE_ENV: 'invalid' }); }, Error); }); it('should throw an error if config file was not found', function() { assert.throws(function() { this.confo._confo.load({ NODE_ENV: 'production' }); }, Error); }); it('should throw an error if config file cant be parsed', function() { assert.throws(function() { this.confo._confo.load({ NODE_ENV: 'errenv' }); }, Error); }); it('should set config values properly', function() { var config = this.confo._confo.load({ NODE_ENV: 'dev' }); assert.equal(config.db.host, '127.0.0.1'); assert.equal(config.db.port, 28017); }); });
{ "content_hash": "7ab0a557c669b512063cac7e5752fd4a", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 80, "avg_line_length": 34.232142857142854, "alnum_prop": 0.6181533646322379, "repo_name": "ssbb/confo", "id": "77bed4c1b25fa267e3dcfec2be3c3339950347ff", "size": "1917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3304" } ], "symlink_target": "" }
#ifndef _CONS_H_ #define _CONS_H_ #define IO_KEYBOARD 1 #define IO_SERIAL 2 extern uint8_t ioctrl; void putc(int c); void xputc(int c); void putchar(int c); int getc(int fn); int xgetc(int fn); int keyhit(unsigned int secs); void getstr(char *cmdstr, size_t cmdstrsize); #endif /* !_CONS_H_ */
{ "content_hash": "7152a1d33f8b0780b4f7c77cde4d9fd8", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 45, "avg_line_length": 15.789473684210526, "alnum_prop": 0.6866666666666666, "repo_name": "dplbsd/zcaplib", "id": "a491e77b8cff2080f7168387a0f7452d32954f47", "size": "879", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "head/sys/boot/i386/common/cons.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "AGS Script", "bytes": "62471" }, { "name": "Assembly", "bytes": "4478661" }, { "name": "Awk", "bytes": "278525" }, { "name": "Batchfile", "bytes": "20417" }, { "name": "C", "bytes": "383420305" }, { "name": "C++", "bytes": "72796771" }, { "name": "CSS", "bytes": "109748" }, { "name": "ChucK", "bytes": "39" }, { "name": "D", "bytes": "3784" }, { "name": "DIGITAL Command Language", "bytes": "10640" }, { "name": "DTrace", "bytes": "2311027" }, { "name": "Emacs Lisp", "bytes": "65902" }, { "name": "EmberScript", "bytes": "286" }, { "name": "Forth", "bytes": "184405" }, { "name": "GAP", "bytes": "72156" }, { "name": "Groff", "bytes": "32248806" }, { "name": "HTML", "bytes": "6749816" }, { "name": "IGOR Pro", "bytes": "6301" }, { "name": "Java", "bytes": "112547" }, { "name": "KRL", "bytes": "4950" }, { "name": "Lex", "bytes": "398817" }, { "name": "Limbo", "bytes": "3583" }, { "name": "Logos", "bytes": "187900" }, { "name": "Makefile", "bytes": "3551839" }, { "name": "Mathematica", "bytes": "9556" }, { "name": "Max", "bytes": "4178" }, { "name": "Module Management System", "bytes": "817" }, { "name": "NSIS", "bytes": "3383" }, { "name": "Objective-C", "bytes": "836351" }, { "name": "PHP", "bytes": "6649" }, { "name": "Perl", "bytes": "5530761" }, { "name": "Perl6", "bytes": "41802" }, { "name": "PostScript", "bytes": "140088" }, { "name": "Prolog", "bytes": "29514" }, { "name": "Protocol Buffer", "bytes": "61933" }, { "name": "Python", "bytes": "299247" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "Ruby", "bytes": "45958" }, { "name": "Scilab", "bytes": "197" }, { "name": "Shell", "bytes": "10501540" }, { "name": "SourcePawn", "bytes": "463194" }, { "name": "SuperCollider", "bytes": "80208" }, { "name": "Tcl", "bytes": "80913" }, { "name": "TeX", "bytes": "719821" }, { "name": "VimL", "bytes": "22201" }, { "name": "XS", "bytes": "25451" }, { "name": "XSLT", "bytes": "31488" }, { "name": "Yacc", "bytes": "1857830" } ], "symlink_target": "" }
using CommandLine; using Google.Cloud.Firestore; using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; namespace GoogleCloudSamples { public class AddData { public static string Usage = @"Usage: C:\> dotnet run command YOUR_PROJECT_ID Where command is one of add-doc-as-map update-create-if-missing add-doc-data-types add-simple-doc-as-entity set-requires-id add-doc-data-with-auto-id add-doc-data-after-auto-id update-doc update-nested-fields update-server-timestamp update-document-array "; private static async Task AddDocAsMap(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_from_map] DocumentReference docRef = db.Collection("cities").Document("LA"); Dictionary<string, object> city = new Dictionary<string, object> { { "name", "Los Angeles" }, { "state", "CA" }, { "country", "USA" } }; await docRef.SetAsync(city); // [END firestore_data_set_from_map] Console.WriteLine("Added data to the LA document in the cities collection."); } private static async Task UpdateCreateIfMissing(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_doc_upsert] DocumentReference docRef = db.Collection("cities").Document("LA"); Dictionary<string, object> update = new Dictionary<string, object> { { "capital", false } }; await docRef.SetAsync(update, SetOptions.MergeAll); // [END firestore_data_set_doc_upsert] Console.WriteLine("Merged data into the LA document in the cities collection."); } private static async Task AddDocDataTypes(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_from_map_nested] DocumentReference docRef = db.Collection("data").Document("one"); Dictionary<string, object> docData = new Dictionary<string, object> { { "stringExample", "Hello World" }, { "booleanExample", false }, { "numberExample", 3.14159265 }, { "nullExample", null }, }; ArrayList arrayExample = new ArrayList(); arrayExample.Add(5); arrayExample.Add(true); arrayExample.Add("Hello"); docData.Add("arrayExample", arrayExample); Dictionary<string, object> objectExample = new Dictionary<string, object> { { "a", 5 }, { "b", true }, }; docData.Add("objectExample", objectExample); await docRef.SetAsync(docData); // [END firestore_data_set_from_map_nested] Console.WriteLine("Set multiple data-type data for the one document in the data collection."); } // [START firestore_data_custom_type_definition] [FirestoreData] public class City { [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public string State { get; set; } [FirestoreProperty] public string Country { get; set; } [FirestoreProperty] public bool Capital { get; set; } [FirestoreProperty] public long Population { get; set; } } // [END firestore_data_custom_type_definition] private static async Task AddSimpleDocAsEntity(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_from_custom_type] DocumentReference docRef = db.Collection("cities").Document("LA"); City city = new City { Name = "Los Angeles", State = "CA", Country = "USA", Capital = false, Population = 3900000L }; await docRef.SetAsync(city); // [END firestore_data_set_from_custom_type] Console.WriteLine("Added custom City object to the cities collection."); } private static async Task SetRequiresId(string project) { FirestoreDb db = FirestoreDb.Create(project); Dictionary<string, object> city = new Dictionary<string, object> { { "Name", "Phuket" }, { "Country", "Thailand" } }; // [START firestore_data_set_id_specified] await db.Collection("cities").Document("new-city-id").SetAsync(city); // [END firestore_data_set_id_specified] Console.WriteLine("Added document with ID: new-city-id."); } private static async Task AddDocDataWithAutoId(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_id_random_collection] Dictionary<string, object> city = new Dictionary<string, object> { { "Name", "Tokyo" }, { "Country", "Japan" } }; DocumentReference addedDocRef = await db.Collection("cities").AddAsync(city); Console.WriteLine("Added document with ID: {0}.", addedDocRef.Id); // [END firestore_data_set_id_random_collection] } private static async Task AddDocDataAfterAutoId(string project) { FirestoreDb db = FirestoreDb.Create(project); Dictionary<string, object> city = new Dictionary<string, object> { { "Name", "Moscow" }, { "Country", "Russia" } }; // [START firestore_data_set_id_random_document_ref] DocumentReference addedDocRef = db.Collection("cities").Document(); Console.WriteLine("Added document with ID: {0}.", addedDocRef.Id); await addedDocRef.SetAsync(city); // [END firestore_data_set_id_random_document_ref] Console.WriteLine("Added data to the {0} document in the cities collection.", addedDocRef.Id); } private static async Task UpdateDoc(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_field] DocumentReference cityRef = db.Collection("cities").Document("new-city-id"); Dictionary<string, object> updates = new Dictionary<string, object> { { "Capital", false } }; await cityRef.UpdateAsync(updates); // You can also update a single field with: await cityRef.UpdateAsync("Capital", false); // [END firestore_data_set_field] Console.WriteLine("Updated the Capital field of the new-city-id document in the cities collection."); } private static async Task UpdateNestedFields(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_nested_fields] DocumentReference frankDocRef = db.Collection("users").Document("frank"); Dictionary<string, object> initialData = new Dictionary<string, object> { { "Name", "Frank" }, { "Age", 12 } }; Dictionary<string, object> favorites = new Dictionary<string, object> { { "Food", "Pizza" }, { "Color", "Blue" }, { "Subject", "Recess" }, }; initialData.Add("Favorites", favorites); await frankDocRef.SetAsync(initialData); // Update age and favorite color Dictionary<string, object> updates = new Dictionary<string, object> { { "Age", 13 }, { "Favorites.Color", "Red" }, }; // Asynchronously update the document await frankDocRef.UpdateAsync(updates); // [END firestore_data_set_nested_fields] Console.WriteLine("Updated the age and favorite color fields of the Frank document in the users collection."); } private static async Task UpdateServerTimestamp(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_server_timestamp] DocumentReference cityRef = db.Collection("cities").Document("new-city-id"); await cityRef.UpdateAsync("Timestamp", Timestamp.GetCurrentTimestamp()); // [END firestore_data_set_server_timestamp] Console.WriteLine("Updated the Timestamp field of the new-city-id document in the cities collection."); } private static async Task UpdateDocumentArray(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_array_operations] DocumentReference washingtonRef = db.Collection("cities").Document("DC"); // Atomically add a new region to the "regions" array field. await washingtonRef.UpdateAsync("Regions", FieldValue.ArrayUnion("greater_virginia")); // Atomically remove a region from the "regions" array field. await washingtonRef.UpdateAsync("Regions", FieldValue.ArrayRemove("east_coast")); // [END firestore_data_set_array_operations] Console.WriteLine("Updated the Regions array of the DC document in the cities collection."); } private static async Task UpdateDocumentIncrement(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START firestore_data_set_numeric_increment] DocumentReference washingtonRef = db.Collection("cities").Document("DC"); // Atomically increment the population of the city by 50. await washingtonRef.UpdateAsync("Regions", FieldValue.Increment(50)); // [END firestore_data_set_numeric_increment] Console.WriteLine("Updated the population of the DC document in the cities collection."); } public static void Main(string[] args) { if (args.Length < 2) { Console.Write(Usage); return; } string command = args[0].ToLower(); string project = string.Join(" ", new ArraySegment<string>(args, 1, args.Length - 1)); switch (command) { case "add-doc-as-map": AddDocAsMap(project).Wait(); break; case "update-create-if-missing": UpdateCreateIfMissing(project).Wait(); break; case "add-doc-data-types": AddDocDataTypes(project).Wait(); break; case "add-simple-doc-as-entity": AddSimpleDocAsEntity(project).Wait(); break; case "set-requires-id": SetRequiresId(project).Wait(); break; case "add-doc-data-with-auto-id": AddDocDataWithAutoId(project).Wait(); break; case "add-doc-data-after-auto-id": AddDocDataAfterAutoId(project).Wait(); break; case "update-doc": UpdateDoc(project).Wait(); break; case "update-nested-fields": UpdateNestedFields(project).Wait(); break; case "update-server-timestamp": UpdateServerTimestamp(project).Wait(); break; case "update-document-array": UpdateDocumentArray(project).Wait(); break; case "update-document-increment": UpdateDocumentIncrement(project).Wait(); break; default: Console.Write(Usage); return; } } } }
{ "content_hash": "e606573a9f27fa2f2807c77867fd514d", "timestamp": "", "source": "github", "line_count": 324, "max_line_length": 122, "avg_line_length": 38.57716049382716, "alnum_prop": 0.5513241059284743, "repo_name": "GoogleCloudPlatform/dotnet-docs-samples", "id": "0071ea58cd7bd8236a853257b75c1cb0fd92cf47", "size": "13087", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "firestore/api/AddData/Program.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "44935" }, { "name": "Batchfile", "bytes": "2016" }, { "name": "C#", "bytes": "3481210" }, { "name": "CSS", "bytes": "17293" }, { "name": "Dockerfile", "bytes": "16003" }, { "name": "F#", "bytes": "7661" }, { "name": "HTML", "bytes": "148172" }, { "name": "JavaScript", "bytes": "202743" }, { "name": "PowerShell", "bytes": "259637" }, { "name": "Shell", "bytes": "7852" }, { "name": "Visual Basic .NET", "bytes": "2494" } ], "symlink_target": "" }
(function(){ /* global d3 */ "use strict"; var margin = {top: 20, right: 80, bottom: 30, left: 50}, width = 860 - margin.left - margin.right, height = 400 - margin.top - margin.bottom, MAX_BANK_RADIUS=30, parseDate = d3.time.format("%d/%m/%Y").parse, x = d3.time.scale() .range([0, width]), y = d3.scale.linear() .range([height, 0]), color = d3.scale.category10(), xAxis = d3.svg.axis() .scale(x) .orient("bottom"), yAxis = d3.svg.axis() .scale(y) .orient("left"), line = d3.svg.line() .interpolate("basis") .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.rate); }), svg = d3.select("#viz").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.csv("data/libor_data_3M.csv", function(error, data) { var k, i, aggregateTheft = {}, resetAggregateTheft; color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; })); data.forEach(function(d) { d.date = parseDate(d.date); }); resetAggregateTheft = function(){ for(var k in data[0]){ if(k !== 'date'){ aggregateTheft[k] = 0.0;} } }; resetAggregateTheft(); var banks = color.domain().map(function(name) { return { name: name, values: data.map(function(d) { return {date: d.date, rate: +d[name]}; }) }; }); x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([ d3.min(banks, function(c) { return d3.min(c.values, function(v) { return v.rate; }); }), d3.max(banks, function(c) { return d3.max(c.values, function(v) { return v.rate; }); }) ]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Dollar rate"); var bank = svg.selectAll(".bank") .data(banks) .enter().append("g") .attr("class", "bank"); var node = svg.selectAll(".node") .data(banks) .enter().append("g") .attr("class", "node") .attr("transform", function(d,i){return "translate(" + width/2 + "," + i*MAX_BANK_RADIUS + ")";}); node.append("circle") .attr("r", 4.5); node.append("text") .attr("dx", 12) .attr("dy", ".35em") .text(function(d) { return d.name; }); node.append("line") .attr("stroke", function(d) { return color(d.name); }) .attr("x1", -40) .attr("x2", -20); bank.append("path") .attr("class", "line") .attr("d", function(d) { return line(d.values); }) .style("stroke", function(d) { return color(d.name); }); // bank.append("text") // .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; }) // .attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.rate) + ")"; }) // .attr("x", 3) // .attr("dy", ".35em") // .text(function(d) { return d.name; }); var time_line = svg.append("svg:line") .style('stroke', '#00e') .attr('y1', 0) .attr('y2', height), time_line_messages = [ {date: new Date('01-01-2005'), text: 'Between January 2005 and June 2009, Barclays derivatives traders made a total of 257 requests to fix Libor and Euribor rates, according to a report by the FSA.</p><p>One Barclays trader told a trader from another bank in relation to three-month dollar Libor: "duuuude... what\'s up with ur guys 34.5 3m fix... tell him to get it up!".' }, {date: new Date('05-01-2007'), text: "At the onset of the financial crisis in September 2007 with the collapse of Northern Rock, liquidity concerns drew public scrutiny towards Libor. Barclays manipulated Libor submissions to give a healthier picture of the bank's credit quality and its ability to raise funds. A lower submission would deflect concerns it had problems borrowing cash from the markets."}, {date: new Date('11-28-2007'), text: 'On 28 November, a senior submitter at Barclays wrote in an internal email that "Libors are not reflecting the true cost of money", according to the FSA.</p><p>In early December, the CFTC said that the Barclays employee responsible for submitting the bank\'s dollar Libor rates contacted it to complain that Barclays was not setting "honest" rates.'}, // {date: new Date('12-10-2007'), text: 'In early December, the CFTC said that the Barclays employee responsible for submitting the bank\'s dollar Libor rates contacted it to complain that Barclays was not setting "honest" rates.'}, {date: new Date('04-01-2008'), text: 'In April the New York Fed queries a Barclays employee over Libor reporting.</p><p>The Wall Street Journal publishes the first article questioning the integrity of Libor.</p>'}, // {date: new Date('05-01-2008'), text: 'The Wall Street Journal publishes the first article questioning the integrity of Libor.'}, {date: new Date('07-01-2008'), text: "Following the WSJ report, Barclays is contacted by the British Bankers' Association over concerns about the accuracy of its Libor submissions.</p><p>Later in the year, the Fed meets to begin inquiry. Fed boss Tim Geithner gives Bank of England governor Sir Mervyn King a note listing proposals to tackle Libor problems."}, {date: new Date('01-01-2012'), text: ''} ], time_line_index = 0; var reposition = function(index){ var msg, k, currentRate = data[index]['FIX - USD'], RADIUS_WEIGHTING = 5.0, d = data[index]; if(index === 0){ resetAggregateTheft(); time_line_index = 0; } msg = time_line_messages[time_line_index]; if(d.date > msg.date){ time_line_index++; $('#message-box').html('<p>' + msg.text + '</p>').hide().fadeIn(2000); } time_line.attr('x1', x(d.date)) .attr('x2', x(d.date)) .transition(100); for(k in aggregateTheft){ aggregateTheft[k] += d[k] - currentRate; } node.select('circle') .attr('r', function(d){return RADIUS_WEIGHTING * Math.abs(aggregateTheft[d.name]);}) .attr('fill', function(d){ if(aggregateTheft[d.name] > 0.0){ return 'red'; } return 'green'; }); }; subscribe('tick', reposition); reposition(0); var currentIndex = 0; var ticker = function () { publish('tick', [currentIndex]); currentIndex += 1; if (currentIndex === data.length) { currentIndex = 0; window.setTimeout(ticker, 5000); } else{ window.setTimeout(ticker, 100); } }; window.setTimeout(ticker, 25); }); })();
{ "content_hash": "2b60ffaed2d14db08825751826acd5e1", "timestamp": "", "source": "github", "line_count": 190, "max_line_length": 417, "avg_line_length": 41.94210526315789, "alnum_prop": 0.5242815911657673, "repo_name": "Kyrand/BrightonHackathon", "id": "e8ee470933e550004333bca32cdcee0802256643", "size": "7969", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vizlibor.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "7969" }, { "name": "Python", "bytes": "1020" } ], "symlink_target": "" }
define(['dojo/_base/declare', 'dojo/Deferred', 'dojo/_base/lang', 'dojo/_base/array', 'jimu/LayerInfos/LayerInfos', 'dijit/form/Select', 'esri/tasks/query', 'esri/tasks/QueryTask', 'dijit/_TemplatedMixin', '../BaseEditor' ], function(declare, Deferred, lang, array, LayerInfos, Select, Query, QueryTask, _TemplatedMixin, BaseEditor){ var clazz = declare([BaseEditor, _TemplatedMixin], { templateString: '<div>' + '<div class="recordset-editor" data-dojo-attach-point="tableChooseNode"></div>' + '</div>', editorName: 'SelectRecordSetFromTable', postCreate: function(){ this.inherited(arguments); var layerInfos = LayerInfos.getInstanceSync(); var tableInfos = layerInfos.getTableInfoArray(); var options = [{ label: this.nls.chooseATable, value: '', selected: true }]; array.forEach(tableInfos, function(tableInfo) { options.push({ label: tableInfo.title || tableInfo.name, value: tableInfo }); }); this.selectDijit = new Select({ name: 'tableSelctor', 'class': 'table-select', options: options }); this.selectDijit.placeAt(this.tableChooseNode).startup(); }, getGPValue: function(){ var def = new Deferred(); var tableInfo = this.selectDijit.get('value'); if(tableInfo) { tableInfo.getLayerObject().then(lang.hitch(this, function(layerObject) { if(!layerObject) { def.resolve(null); return; } if (layerObject.featureCollectionData){ def.resolve(layerObject.featureCollectionData); } else if (layerObject.url) { var queryTask = new QueryTask(layerObject.url); var query = new Query(); query.where = '1=1'; query.outFields = ['*']; queryTask.execute(query, function(featureSet) { def.resolve(featureSet); }, function(error) { def.reject(error); }); } else { def.resolve(null); } })); } else { def.resolve(null); } return def; } }); return clazz; });
{ "content_hash": "125097dfd7091b46e360b1b40e5f5d63", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 111, "avg_line_length": 29.42105263157895, "alnum_prop": 0.5684257602862254, "repo_name": "tmcgee/cmv-wab-widgets", "id": "4e99c07c3a44421a4caefaa1b5b73287d4de748a", "size": "2988", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "wab/2.15/widgets/Geoprocessing/editors/SelectRecordSetFromTable.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1198579" }, { "name": "HTML", "bytes": "946685" }, { "name": "JavaScript", "bytes": "22190423" }, { "name": "Pascal", "bytes": "4207" }, { "name": "TypeScript", "bytes": "102918" } ], "symlink_target": "" }
class Api::V1::ReviewsController < ApplicationController def index render json: Review.where(art_label_id: params[:art_label_id]) end def show # render json: Review.find(params[:id]) review_data = { review: Review.find(params[:id]), current_user: current_user, votes: Vote.where(review_id: params[:id]) } render json: review_data end end
{ "content_hash": "0ea62afcd6597e6a5ca34425c5675d13", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 66, "avg_line_length": 27.5, "alnum_prop": 0.6571428571428571, "repo_name": "koscim/beer-art-reviews", "id": "cc3c7f1b72ef2a1e9869e4b26cc6181c366a340a", "size": "385", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/api/v1/reviews_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7740" }, { "name": "HTML", "bytes": "32600" }, { "name": "JavaScript", "bytes": "40789" }, { "name": "Ruby", "bytes": "109908" } ], "symlink_target": "" }
package aci import ( "archive/tar" "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "strings" "time" "github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/aci" "github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/schema" "github.com/coreos/rkt/Godeps/_workspace/src/golang.org/x/crypto/openpgp" ) type ACIEntry struct { Header *tar.Header Contents string } type imageArchiveWriter struct { *tar.Writer am *schema.ImageManifest } // NewImageWriter creates a new ArchiveWriter which will generate an App // Container Image based on the given manifest and write it to the given // tar.Writer // TODO(sgotti) this is a copy of appc/spec/aci.imageArchiveWriter with // addFileNow changed to create the file with the current user. needed for // testing as non root user. func NewImageWriter(am schema.ImageManifest, w *tar.Writer) aci.ArchiveWriter { aw := &imageArchiveWriter{ w, &am, } return aw } func (aw *imageArchiveWriter) AddFile(hdr *tar.Header, r io.Reader) error { err := aw.Writer.WriteHeader(hdr) if err != nil { return err } if r != nil { _, err := io.Copy(aw.Writer, r) if err != nil { return err } } return nil } func (aw *imageArchiveWriter) addFileNow(path string, contents []byte) error { buf := bytes.NewBuffer(contents) now := time.Now() hdr := tar.Header{ Name: path, Mode: 0644, Uid: os.Getuid(), Gid: os.Getgid(), Size: int64(buf.Len()), ModTime: now, Typeflag: tar.TypeReg, ChangeTime: now, } return aw.AddFile(&hdr, buf) } func (aw *imageArchiveWriter) addManifest(name string, m json.Marshaler) error { out, err := m.MarshalJSON() if err != nil { return err } return aw.addFileNow(name, out) } func (aw *imageArchiveWriter) Close() error { if err := aw.addManifest(aci.ManifestFile, aw.am); err != nil { return err } return aw.Writer.Close() } // NewBasicACI creates a new ACI in the given directory with the given name. // Used for testing. func NewBasicACI(dir string, name string) (*os.File, error) { manifest := fmt.Sprintf(`{"acKind":"ImageManifest","acVersion":"0.7.1","name":"%s"}`, name) return NewACI(dir, manifest, nil) } // NewACI creates a new ACI in the given directory with the given image // manifest and entries. // Used for testing. func NewACI(dir string, manifest string, entries []*ACIEntry) (*os.File, error) { var im schema.ImageManifest if err := im.UnmarshalJSON([]byte(manifest)); err != nil { return nil, fmt.Errorf("invalid image manifest: %v", err) } tf, err := ioutil.TempFile(dir, "") if err != nil { return nil, err } defer os.Remove(tf.Name()) tw := tar.NewWriter(tf) aw := NewImageWriter(im, tw) for _, entry := range entries { // Add default mode if entry.Header.Mode == 0 { if entry.Header.Typeflag == tar.TypeDir { entry.Header.Mode = 0755 } else { entry.Header.Mode = 0644 } } // Add calling user uid and gid or tests will fail entry.Header.Uid = os.Getuid() entry.Header.Gid = os.Getgid() sr := strings.NewReader(entry.Contents) if err := aw.AddFile(entry.Header, sr); err != nil { return nil, err } } if err := aw.Close(); err != nil { return nil, err } return tf, nil } // NewDetachedSignature creates a new openpgp armored detached signature for the given ACI // signed with armoredPrivateKey. func NewDetachedSignature(armoredPrivateKey string, aci io.Reader) (io.Reader, error) { entityList, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey)) if err != nil { return nil, err } if len(entityList) < 1 { return nil, errors.New("empty entity list") } signature := &bytes.Buffer{} if err := openpgp.ArmoredDetachSign(signature, entityList[0], aci, nil); err != nil { return nil, err } return signature, nil }
{ "content_hash": "a679692fa4cf7ff0e54c5d32aed513e5", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 92, "avg_line_length": 24.748387096774195, "alnum_prop": 0.6819603753910324, "repo_name": "jzelinskie/rkt", "id": "3f16a10d33d5583cb294f84927a49ecd49875ecd", "size": "4494", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pkg/aci/aci.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "23687" }, { "name": "Go", "bytes": "901712" }, { "name": "Makefile", "bytes": "123598" }, { "name": "Protocol Buffer", "bytes": "15635" }, { "name": "Shell", "bytes": "35724" } ], "symlink_target": "" }
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md) **Assembly:** OfficeDevPnP.Core.dll ## Syntax ```C# public Preferences() ``` ## See also - [Preferences](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Preferences.md) - [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md)
{ "content_hash": "17f100266cf7f2c8ffa61cdc66cbdf97", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 148, "avg_line_length": 43, "alnum_prop": 0.7928118393234672, "repo_name": "PaoloPia/PnP-Guidance", "id": "88ca0b6015fdc71846fb9fa1509770088a9e8291", "size": "508", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sitescore/OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Preferences.ctor1.md", "mode": "33188", "license": "mit", "language": [ { "name": "PowerShell", "bytes": "783" } ], "symlink_target": "" }
#ifndef DB_LINEMOD_H_ #define DB_LINEMOD_H_ #include <object_recognition_core/db/document.h> #include <opencv2/objdetect/objdetect.hpp> namespace object_recognition_core { namespace db { // Specializations for cv::linemod::Detector template<> void object_recognition_core::db::DummyDocument::get_attachment<cv::linemod::Detector>(const AttachmentName& attachment_name, cv::linemod::Detector& value) const; template<> void object_recognition_core::db::Document::get_attachment_and_cache<cv::linemod::Detector>( const AttachmentName& attachment_name, cv::linemod::Detector& value); template<> void object_recognition_core::db::DummyDocument::set_attachment<cv::linemod::Detector>(const AttachmentName& attachment_name, const cv::linemod::Detector& value); // Specializations for std::vector<cv::Mat> // Actually not needed anymore but you never know .... template<> void object_recognition_core::db::DummyDocument::get_attachment<std::vector<cv::Mat> >(const AttachmentName& attachment_name, std::vector<cv::Mat>& value) const; template<> void object_recognition_core::db::Document::get_attachment_and_cache<std::vector<cv::Mat> >( const AttachmentName& attachment_name, std::vector<cv::Mat>& value); template<> void object_recognition_core::db::DummyDocument::set_attachment<std::vector<cv::Mat> >(const AttachmentName& attachment_name, const std::vector<cv::Mat>& value); // Specializations for std::vector<float> // Actually not needed anymore but you never know .... template<> void object_recognition_core::db::DummyDocument::get_attachment<std::vector<float> >(const AttachmentName& attachment_name, std::vector<float>& value) const; template<> void object_recognition_core::db::Document::get_attachment_and_cache<std::vector<float> >( const AttachmentName& attachment_name, std::vector<float>& value); template<> void object_recognition_core::db::DummyDocument::set_attachment<std::vector<float> >(const AttachmentName& attachment_name, const std::vector<float>& value); /** Struct for detected objects info*/ struct ObjData{ ObjData( std::vector<cv::Vec3f> _pts_ref, std::vector<cv::Vec3f> _pts_model, std::string _match_class, const float _match_sim, const float _icp_dist, const float _icp_px_match, const cv::Matx33f _r, const cv::Vec3f _t){ pts_ref = _pts_ref; pts_model = _pts_model; match_class = _match_class; match_sim = _match_sim; icp_dist = _icp_dist; icp_px_match = _icp_px_match, r = _r; t = _t; check_done = false; } std::vector<cv::Vec3f> pts_ref; std::vector<cv::Vec3f> pts_model; std::string match_class; float match_sim; float icp_dist; float icp_px_match; cv::Matx33f r; cv::Vec3f t; bool check_done; }; } } #endif /* DB_LINEMOD_H_ */
{ "content_hash": "2f76e9e6eb3c7e30e1b9dd56609a8b8e", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 124, "avg_line_length": 36.54081632653061, "alnum_prop": 0.5548729405194079, "repo_name": "WalkingMachine/sara_commun", "id": "d74549ae4b052ae4129194d0d5c7690bcaa9c673", "size": "5251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wm_ork/linemod/src/db_linemod.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CMake", "bytes": "6113" } ], "symlink_target": "" }
require "rails_helper" describe Admin::BackupsController do it "is a subclass of AdminController" do expect(Admin::BackupsController < Admin::AdminController).to eq(true) end let(:backup_filename) { "2014-02-10-065935.tar.gz" } context "while logged in as an admin" do before { @admin = log_in(:admin) } describe ".index" do context "html format" do it "preloads important data" do Backup.expects(:all).returns([]) subject.expects(:store_preloaded).with("backups", "[]") BackupRestore.expects(:operations_status).returns({}) subject.expects(:store_preloaded).with("operations_status", "{}") BackupRestore.expects(:logs).returns([]) subject.expects(:store_preloaded).with("logs", "[]") xhr :get, :index, format: :html expect(response).to be_success end end context "json format" do it "returns a list of all the backups" do Backup.expects(:all).returns([Backup.new("backup1"), Backup.new("backup2")]) xhr :get, :index, format: :json expect(response).to be_success json = JSON.parse(response.body) expect(json[0]["filename"]).to eq("backup1") expect(json[1]["filename"]).to eq("backup2") end end end describe ".status" do it "returns the current backups status" do BackupRestore.expects(:operations_status) xhr :get, :status expect(response).to be_success end end describe ".create" do it "starts a backup" do BackupRestore.expects(:backup!).with(@admin.id, publish_to_message_bus: true, with_uploads: false, client_id: "foo") xhr :post, :create, with_uploads: false, client_id: "foo" expect(response).to be_success end end describe ".cancel" do it "cancels an export" do BackupRestore.expects(:cancel!) xhr :delete, :cancel expect(response).to be_success end end describe ".show" do it "uses send_file to transmit the backup" do FileUtils.mkdir_p Backup.base_directory File.open(Backup.base_directory << "/" << backup_filename, "w") do |f| f.write("hello") end Backup.create_from_filename(backup_filename) get :show, id: backup_filename expect(response.headers['Content-Length']).to eq(5) expect(response.headers['Content-Disposition']).to match(/attachment; filename/) end it "returns 404 when the backup does not exist" do Backup.expects(:[]).returns(nil) get :show, id: backup_filename expect(response).to be_not_found end end describe ".destroy" do let(:b) { Backup.new(backup_filename) } it "removes the backup if found" do Backup.expects(:[]).with(backup_filename).returns(b) b.expects(:remove) xhr :delete, :destroy, id: backup_filename expect(response).to be_success end it "doesn't remove the backup if not found" do Backup.expects(:[]).with(backup_filename).returns(nil) b.expects(:remove).never xhr :delete, :destroy, id: backup_filename expect(response).not_to be_success end end describe ".logs" do it "preloads important data" do BackupRestore.expects(:operations_status).returns({}) subject.expects(:store_preloaded).with("operations_status", "{}") BackupRestore.expects(:logs).returns([]) subject.expects(:store_preloaded).with("logs", "[]") xhr :get, :logs, format: :html expect(response).to be_success end end describe ".restore" do it "starts a restore" do BackupRestore.expects(:restore!).with(@admin.id, filename: backup_filename, publish_to_message_bus: true, client_id: "foo") xhr :post, :restore, id: backup_filename, client_id: "foo" expect(response).to be_success end end describe ".rollback" do it "rolls back to previous working state" do BackupRestore.expects(:rollback!) xhr :get, :rollback expect(response).to be_success end end describe ".readonly" do it "enables readonly mode" do Discourse.expects(:enable_readonly_mode) xhr :put, :readonly, enable: true expect(response).to be_success end it "disables readonly mode" do Discourse.expects(:disable_readonly_mode) xhr :put, :readonly, enable: false expect(response).to be_success end end end end
{ "content_hash": "4c6db585faafe0c430e44ac4806fbc53", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 131, "avg_line_length": 23.685279187817258, "alnum_prop": 0.6056579511358765, "repo_name": "rokn/Count_Words_2015", "id": "050201a6ab098b942b71302bcec0ae65cfd95615", "size": "4666", "binary": false, "copies": "25", "ref": "refs/heads/master", "path": "fetched_code/ruby/backups_controller_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "61802" }, { "name": "Ruby", "bytes": "18888605" } ], "symlink_target": "" }
import map from 'lodash/map'; import get from 'lodash/get'; import uniq from 'lodash/uniq'; import meanBy from 'lodash/meanBy'; import flatten from 'lodash/flatten'; import { STATUSES } from './constants'; const keyMap = { [STATUSES.completed]: 'completed', [STATUSES.started]: 'started', [STATUSES.notStarted]: 'notStarted', [STATUSES.helpNeeded]: 'helpNeeded', }; function notStartedStatusObj() { // create a dummy status object return { status: STATUSES.notStarted }; } /* * Getters that return lookup functions * Implemented as getters for easy access to the store */ export default { /* * Return array of group names given an array of group IDs */ getGroupNames(state) { return function(groupIds) { if (!Array.isArray(groupIds)) { throw new Error('getGroupNames: invalid parameter(s)'); } return groupIds.map(id => state.groupMap[id].name); }; }, /* * Return array of group names given a learner ID */ getGroupNamesForLearner(state, getters) { return function(learnerId) { if (!learnerId) { throw new Error('getGroupNamesForLearner: invalid parameter(s)'); } return getters.groups .filter(group => group.member_ids.includes(learnerId)) .map(group => group.name); }; }, /* * Return array of learner IDs given an array of group IDs. * An empty list is considered the whole class in the context of assignment. */ getLearnersForGroups(state) { return function(groupIds) { if (!Array.isArray(groupIds)) { throw new Error('getLearnersForGroups: invalid parameter(s)'); } if (!groupIds.length) { return map(state.learnerMap, 'id'); } return uniq(flatten(map(groupIds, id => state.groupMap[id].member_ids))); }; }, /* * Return a STATUSES constant given a content ID and a learner ID */ getContentStatusObjForLearner(state) { return function(contentId, learnerId) { if (!contentId || !learnerId) { throw new Error('getContentStatusObjForLearner: invalid parameter(s)'); } return get(state.contentLearnerStatusMap, [contentId, learnerId], notStartedStatusObj()); }; }, /* * Return a 'tally object' given a content ID and an array of learner IDs */ getContentStatusTally(state, getters) { return function(contentId, learnerIds) { if (!contentId || !Array.isArray(learnerIds)) { throw new Error('getContentStatusTally: invalid parameter(s)'); } const tallies = { started: 0, notStarted: 0, completed: 0, helpNeeded: 0, }; learnerIds.forEach(learnerId => { const status = getters.getContentStatusObjForLearner(contentId, learnerId).status; tallies[keyMap[status]] += 1; }); return tallies; }; }, /* * Return a STATUSES constant given an exam ID and a learner ID */ getExamStatusObjForLearner(state) { return function(examId, learnerId) { if (!examId || !learnerId) { throw new Error('getExamStatusObjForLearner: invalid parameter(s)'); } return get(state.examLearnerStatusMap, [examId, learnerId], notStartedStatusObj()); }; }, /* * Return a 'tally object' given an exam ID and an array of learner IDs */ getExamStatusTally(state, getters) { return function(examId, learnerIds) { if (!examId || !Array.isArray(learnerIds)) { throw new Error('getExamStatusTally: invalid parameter(s)'); } const tallies = { started: 0, notStarted: 0, completed: 0, helpNeeded: 0, }; learnerIds.forEach(learnerId => { const status = getters.getExamStatusObjForLearner(examId, learnerId); tallies[keyMap[status.status]] += 1; }); return tallies; }; }, /* * Return a STATUSES constant given a lesson ID and a learner ID */ getLessonStatusStringForLearner(state, getters) { return function(lessonId, learnerId) { if (!lessonId || !learnerId) { throw new Error('getLessonStatusStringForLearner: invalid parameter(s)'); } return get( getters.lessonLearnerStatusMap, [lessonId, learnerId, 'status'], STATUSES.notStarted ); }; }, /* * Return a 'tally object' given a lesson ID and an array of learner IDs */ getLessonStatusTally(state, getters) { return function(lessonId, learnerIds) { if (!lessonId || !Array.isArray(learnerIds)) { throw new Error('getLessonStatusTally: invalid parameter(s)'); } const tallies = { started: 0, notStarted: 0, completed: 0, helpNeeded: 0, }; learnerIds.forEach(learnerId => { const status = getters.getLessonStatusStringForLearner(lessonId, learnerId); tallies[keyMap[status]] += 1; }); return tallies; }; }, /* * Return a number (in seconds) given a content ID and an array of learner IDs */ getContentAvgTimeSpent(state, getters) { return function(contentId, learnerIds) { if (!contentId || !Array.isArray(learnerIds)) { throw new Error('getContentAvgTimeSpent: invalid parameter(s)'); } const statusObjects = []; learnerIds.forEach(learnerId => { const statusObj = getters.getContentStatusObjForLearner(contentId, learnerId); if (statusObj.status !== STATUSES.notStarted) { statusObjects.push(statusObj); } }); if (!statusObjects.length) { return undefined; } return meanBy(statusObjects, 'time_spent'); }; }, /* * Return a number (0-1) given an exam ID and an array of learner IDs */ getExamAvgScore(state, getters) { return function(examId, learnerIds) { if (!examId || !Array.isArray(learnerIds)) { throw new Error('getExamAvgScore: invalid parameter(s)'); } const statusObjects = []; learnerIds.forEach(learnerId => { const statusObj = getters.getExamStatusObjForLearner(examId, learnerId); if (statusObj.status === STATUSES.completed) { statusObjects.push(statusObj); } }); if (!statusObjects.length) { return undefined; } return meanBy(statusObjects, 'score'); }; }, };
{ "content_hash": "47e0e16f7dadb8a9f64c305693fe3a87", "timestamp": "", "source": "github", "line_count": 207, "max_line_length": 95, "avg_line_length": 30.594202898550726, "alnum_prop": 0.6292436444023369, "repo_name": "lyw07/kolibri", "id": "a2d5935a487c5cdaec98528183a9870d3e808644", "size": "6333", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "kolibri/plugins/coach/assets/src/modules/classSummary/dataHelpers.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "601" }, { "name": "CSS", "bytes": "2007902" }, { "name": "Dockerfile", "bytes": "6930" }, { "name": "Gherkin", "bytes": "199214" }, { "name": "HTML", "bytes": "34393" }, { "name": "JavaScript", "bytes": "1376767" }, { "name": "Makefile", "bytes": "11718" }, { "name": "Python", "bytes": "1896793" }, { "name": "Shell", "bytes": "11350" }, { "name": "Vue", "bytes": "1278479" } ], "symlink_target": "" }
//================================================================================================= //================================================================================================= #ifndef _BLAZE_MATH_FUNCTORS_RIGHTSHIFTASSIGN_H_ #define _BLAZE_MATH_FUNCTORS_RIGHTSHIFTASSIGN_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blaze/system/Inline.h> namespace blaze { //================================================================================================= // // CLASS DEFINITION // //================================================================================================= //************************************************************************************************* /*!\brief Generic wrapper for bitwise right-shift assignment. // \ingroup functors */ struct RightShiftAssign { //********************************************************************************************** /*!\brief Performs a bitwise right-shift assignment with the given objects/values. // // \param a The target left-hand side object/value. // \param b The right-hand side object/value for the bitwise right-shift operation. // \return void */ template< typename T1, typename T2 > BLAZE_ALWAYS_INLINE void operator()( T1& a, const T2& b ) const { a >>= b; } //********************************************************************************************** }; //************************************************************************************************* } // namespace blaze #endif
{ "content_hash": "aa97d793c9fa704133499d6b8bf51f12", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 99, "avg_line_length": 36.104166666666664, "alnum_prop": 0.2890940565493364, "repo_name": "camillescott/boink", "id": "61d594f9123ae5699bb4e3db91d099a0b2e1dff5", "size": "3588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/goetia/sketches/sketch/vec/blaze/blaze/math/functors/RightShiftAssign.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "100250" }, { "name": "C++", "bytes": "1054510" }, { "name": "CMake", "bytes": "302273" }, { "name": "Jupyter Notebook", "bytes": "17489756" }, { "name": "Python", "bytes": "267582" }, { "name": "Shell", "bytes": "98" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `pthread_mutexattr_t` struct in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, pthread_mutexattr_t"> <title>libc::pthread_mutexattr_t - Rust</title> <link rel="stylesheet" type="text/css" href="../normalize.css"> <link rel="stylesheet" type="text/css" href="../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc struct"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='index.html'>libc</a></p><script>window.sidebarCurrent = {name: 'pthread_mutexattr_t', ty: 'struct', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content"> <h1 class='fqn'><span class='in-band'>Struct <a href='index.html'>libc</a>::<wbr><a class="struct" href=''>pthread_mutexattr_t</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a class='srclink' href='../src/libc/macros.rs.html#42' title='goto source code'>[src]</a></span></h1> <pre class='rust struct'><div class="docblock attributes">#[repr(C)] </div>pub struct pthread_mutexattr_t { /* fields omitted */ }</pre><h2 id='implementations'>Trait Implementations</h2><h3 class='impl'><span class='in-band'><code>impl <a class="trait" href="https://doc.rust-lang.org/nightly/core/marker/trait.Copy.html" title="trait core::marker::Copy">Copy</a> for <a class="struct" href="../libc/struct.pthread_mutexattr_t.html" title="struct libc::pthread_mutexattr_t">pthread_mutexattr_t</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../src/libc/macros.rs.html#44' title='goto source code'>[src]</a></span></h3> <div class='impl-items'></div><h3 class='impl'><span class='in-band'><code>impl <a class="trait" href="https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html" title="trait core::clone::Clone">Clone</a> for <a class="struct" href="../libc/struct.pthread_mutexattr_t.html" title="struct libc::pthread_mutexattr_t">pthread_mutexattr_t</a></code></span><span class='out-of-band'><div class='ghost'></div><a class='srclink' href='../src/libc/macros.rs.html#45-47' title='goto source code'>[src]</a></span></h3> <div class='impl-items'><h4 id='method.clone' class="method"><span id='clone.v' class='invisible'><code>fn <a href='https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html#tymethod.clone' class='fnname'>clone</a>(&amp;self) -&gt; <a class="struct" href="../libc/struct.pthread_mutexattr_t.html" title="struct libc::pthread_mutexattr_t">pthread_mutexattr_t</a></code></span></h4> <div class='docblock'><p>Returns a copy of the value. <a href="https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html#tymethod.clone">Read more</a></p> </div><h4 id='method.clone_from' class="method"><span id='clone_from.v' class='invisible'><code>fn <a href='https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html#method.clone_from' class='fnname'>clone_from</a>(&amp;mut self, source: &amp;Self)</code><div class='since' title='Stable since Rust version 1.0.0'>1.0.0</div></span></h4> <div class='docblock'><p>Performs copy-assignment from <code>source</code>. <a href="https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html#method.clone_from">Read more</a></p> </div></div></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../"; window.currentCrate = "libc"; </script> <script src="../jquery.js"></script> <script src="../main.js"></script> <script defer src="../search-index.js"></script> </body> </html>
{ "content_hash": "af912b469b80728ce18fc070c58d8a6c", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 596, "avg_line_length": 53.5, "alnum_prop": 0.5778816199376947, "repo_name": "nitro-devs/nitro-game-engine", "id": "a9d93ce32545f5ad9d4f8c6c6362c0b409254442", "size": "6430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/libc/struct.pthread_mutexattr_t.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CMake", "bytes": "1032" }, { "name": "Rust", "bytes": "59380" } ], "symlink_target": "" }
<?php /* * 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. */ namespace IE\NylasSEClient\Authentication; use IE\NylasSEClient\Model\Account; /** * * @author jose.muriano */ interface AuthenticationInterface { public function authorize(); public function login(); public function getAccount(); public function getAPIUrl(); }
{ "content_hash": "a1125d5e62a994276d88406ad0398220", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 79, "avg_line_length": 20.12, "alnum_prop": 0.6878727634194831, "repo_name": "Muriano/ie-nylas-se-php-client", "id": "29273f560680f9f95f5763704a67d98ca46af5cd", "size": "503", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Authentication/AuthenticationInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "79503" } ], "symlink_target": "" }
================ Write New Layers ================ This tutorial will guide you to write customized layers in PaddlePaddle. We will utilize fully connected layer as an example to guide you through the following steps for writing a new layer. - Derive equations for the forward and backward part of the layer. - Implement C++ class for the layer. - Write gradient check unit test to make sure the gradients are correctly computed. - Implement Python wrapper for the layer. Derive Equations ================ First we need to derive equations of the *forward* and *backward* part of the layer. The forward part computes the output given an input. The backward part computes the gradients of the input and the parameters given the the gradients of the output. The illustration of a fully connected layer is shown in the following figure. In a fully connected layer, all output nodes are connected to all the input nodes. .. image:: FullyConnected.jpg :align: center :scale: 60 % The *forward part* of a layer transforms an input into the corresponding output. Fully connected layer takes a dense input vector with dimension :math:`D_i`. It uses a transformation matrix :math:`W` with size :math:`D_i \times D_o` to project :math:`x` into a :math:`D_o` dimensional vector, and add a bias vector :math:`b` with dimension :math:`D_o` to the vector. .. math:: y = f(W^T x + b) where :math:`f(.)` is an nonlinear *activation* function, such as sigmoid, tanh, and Relu. The transformation matrix :math:`W` and bias vector :math:`b` are the *parameters* of the layer. The *parameters* of a layer are learned during training in the *backward pass*. The backward pass computes the gradients of the output function with respect to all parameters and inputs. The optimizer can use chain rule to compute the gradients of the loss function with respect to each parameter. Suppose our loss function is :math:`c(y)`, then .. math:: \frac{\partial c(y)}{\partial x} = \frac{\partial c(y)}{\partial y} \frac{\partial y}{\partial x} Suppose :math:`z = W^T x + b`, then .. math:: \frac{\partial y}{\partial z} = \frac{\partial f(z)}{\partial z} This derivative can be automatically computed by our base layer class. Then, for fully connected layer, we need to compute: .. math:: \frac{\partial z}{\partial x} = W, \frac{\partial z_j}{\partial W_{ij}} = x_i, \frac{\partial z}{\partial b} = \mathbf 1 where :math:`\mathbf 1` is an all one vector, :math:`W_{ij}` is the number at the i-th row and j-th column of the matrix :math:`W`, :math:`z_j` is the j-th component of the vector :math:`z`, and :math:`x_i` is the i-th component of the vector :math:`x`. Finally we can use chain rule to calculate :math:`\frac{\partial z}{\partial x}`, and :math:`\frac{\partial z}{\partial W}`. The details of the computation will be given in the next section. Implement C++ Class =================== The C++ class of the layer implements the initialization, forward, and backward part of the layer. The fully connected layer is at :code:`paddle/gserver/layers/FullyConnectedLayer.h` and :code:`paddle/gserver/layers/FullyConnectedLayer.cpp`. We list simplified version of the code below. It needs to derive the base class :code:`paddle::Layer`, and it needs to override the following functions: - constructor and destructor. - :code:`init` function. It is used to initialize the parameters and settings. - :code:`forward`. It implements the forward part of the layer. - :code:`backward`. It implements the backward part of the layer. - :code:`prefetch`. It is utilized to determine the rows corresponding parameter matrix to prefetch from parameter server. You do not need to override this function if your layer does not need remote sparse update. (most layers do not need to support remote sparse update) The header file is listed below: .. code-block:: c++ namespace paddle { /** * A layer has full connections to all neurons in the previous layer. * It computes an inner product with a set of learned weights, and * (optionally) adds biases. * * The config file api is fc_layer. */ class FullyConnectedLayer : public Layer { protected: WeightList weights_; std::unique_ptr<Weight> biases_; public: explicit FullyConnectedLayer(const LayerConfig& config) : Layer(config) {} ~FullyConnectedLayer() {} bool init(const LayerMap& layerMap, const ParameterMap& parameterMap); Weight& getWeight(int idx) { return *weights_[idx]; } void prefetch(); void forward(PassType passType); void backward(const UpdateCallback& callback = nullptr); }; } // namespace paddle It defines the parameters as class variables. We use :code:`Weight` class as abstraction of parameters. It supports multi-thread update. The details of this class will be described in details in the implementations. - :code:`weights_` is a list of weights for the transformation matrices. The current implementation can have more than one inputs. Thus, it has a list of weights. One weight corresponds to an input. - :code:`biases_` is a weight for the bias vector. The fully connected layer does not have layer configuration hyper-parameters. If there are some layer hyper-parameters, a common practice is to store it in :code:`LayerConfig& config`, and put it into a class variable in the constructor. The following code snippet implements the :code:`init` function. - First, every :code:`init` function must call the :code:`init` function of the base class :code:`Layer::init(layerMap, parameterMap);`. This statement will initialize the required variables and connections for each layer. - The it initializes all the weights matrices :math:`W`. The current implementation can have more than one inputs. Thus, it has a list of weights. - Finally, it initializes the bias. .. code-block:: c++ bool FullyConnectedLayer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { /* Initialize the basic parent class */ Layer::init(layerMap, parameterMap); /* initialize the weightList */ CHECK(inputLayers_.size() == parameters_.size()); for (size_t i = 0; i < inputLayers_.size(); i++) { // Option the parameters size_t height = inputLayers_[i]->getSize(); size_t width = getSize(); // create a new weight if (parameters_[i]->isSparse()) { CHECK_LE(parameters_[i]->getSize(), width * height); } else { CHECK_EQ(parameters_[i]->getSize(), width * height); } Weight* w = new Weight(height, width, parameters_[i]); // append the new weight to the list weights_.emplace_back(w); } /* initialize biases_ */ if (biasParameter_.get() != NULL) { biases_ = std::unique_ptr<Weight>(new Weight(1, getSize(), biasParameter_)); } return true; } The implementation of the forward part has the following steps. - Every layer must call :code:`Layer::forward(passType);` at the beginning of its :code:`forward` function. - Then it allocates memory for the output using :code:`reserveOutput(batchSize, size);`. This step is necessary because we support the batches to have different batch sizes. :code:`reserveOutput` will change the size of the output accordingly. For the sake of efficiency, we will allocate new memory if we want to expand the matrix, but we will reuse the existing memory block if we want to shrink the matrix. - Then it computes :math:`\sum_i W_i x + b` using Matrix operations. :code:`getInput(i).value` retrieve the matrix of the i-th input. Each input is a :math:`batchSize \times dim` matrix, where each row represents an single input in a batch. For a complete lists of supported matrix operations, please refer to :code:`paddle/math/Matrix.h` and :code:`paddle/math/BaseMatrix.h`. - Finally it applies the activation function using :code:`forwardActivation();`. It will automatically applies the corresponding activation function specifies in the network configuration. .. code-block:: c++ void FullyConnectedLayer::forward(PassType passType) { Layer::forward(passType); /* malloc memory for the output_ if necessary */ int batchSize = getInput(0).getBatchSize(); int size = getSize(); { // Settup the size of the output. reserveOutput(batchSize, size); } MatrixPtr outV = getOutputValue(); // Apply the the transformation matrix to each input. for (size_t i = 0; i != inputLayers_.size(); ++i) { auto input = getInput(i); CHECK(input.value) << "The input of 'fc' layer must be matrix"; i == 0 ? outV->mul(input.value, weights_[i]->getW(), 1, 0) : outV->mul(input.value, weights_[i]->getW(), 1, 1); } /* add the bias-vector */ if (biases_.get() != NULL) { outV->addBias(*(biases_->getW()), 1); } /* activation */ { forwardActivation(); } } The implementation of the backward part has the following steps. - :code:`backwardActivation()` computes the gradients of the activation. The gradients will be multiplies in place to the gradients of the output, which can be retrieved using :code:`getOutputGrad()`. - Compute the gradients of bias. Notice that we an use :code:`biases_->getWGrad()` to get the gradient matrix of the corresponding parameter. After the gradient of one parameter is updated, it **MUST** call :code:`getParameterPtr()->incUpdate(callback);`. This is utilize for parameter update over multiple threads or multiple machines. - Then it computes the gradients of the transformation matrices and inputs, and it calls :code:`incUpdate` for the corresponding parameter. This gives the framework the chance to know whether it has gathered all the gradient to one parameter so that it can do some overlapping work (e.g., network communication) .. code-block:: c++ void FullyConnectedLayer::backward(const UpdateCallback& callback) { /* Do derivation for activations.*/ { backwardActivation(); } if (biases_ && biases_->getWGrad()) { biases_->getWGrad()->collectBias(*getOutputGrad(), 1); biases_->getParameterPtr()->incUpdate(callback); } bool syncFlag = hl_get_sync_flag(); for (size_t i = 0; i != inputLayers_.size(); ++i) { /* Calculate the W-gradient for the current layer */ if (weights_[i]->getWGrad()) { MatrixPtr input_T = getInputValue(i)->getTranspose(); MatrixPtr oGrad = getOutputGrad(); { weights_[i]->getWGrad()->mul(input_T, oGrad, 1, 1); } } /* Calculate the input layers error */ MatrixPtr preGrad = getInputGrad(i); if (NULL != preGrad) { MatrixPtr weights_T = weights_[i]->getW()->getTranspose(); preGrad->mul(getOutputGrad(), weights_T, 1, 1); } { weights_[i]->getParameterPtr()->incUpdate(callback); } } } The :code:`prefetch` function specifies the rows that need to be fetched from parameter server during training. It is only useful for remote sparse training. In remote sparse training, the full parameter matrix is stored distributedly at the parameter server. When the layer uses a batch for training, only a subset of locations of the input is non-zero in this batch. Thus, this layer only needs the rows of the transformation matrix corresponding to the locations of these non-zero entries. The :code:`prefetch` function specifies the ids of these rows. Most of the layers do not need remote sparse training function. You do not need to override this function in this case. .. code-block:: c++ void FullyConnectedLayer::prefetch() { for (size_t i = 0; i != inputLayers_.size(); ++i) { auto* sparseParam = dynamic_cast<SparsePrefetchRowCpuMatrix*>(weights_[i]->getW().get()); if (sparseParam) { MatrixPtr input = getInputValue(i); sparseParam->addRows(input); } } } Finally, you can use :code:`REGISTER_LAYER(fc, FullyConnectedLayer);` to register the layer. :code:`fc` is the identifier of the layer, and :code:`FullyConnectedLayer` is the class name of the layer. .. code-block:: c++ namespace paddle { REGISTER_LAYER(fc, FullyConnectedLayer); } If the :code:`cpp` file is put into :code:`paddle/gserver/layers`, it will be automatically added to the compilation list. Write Gradient Check Unit Test =============================== An easy way to verify the correctness of new layer's implementation is to write a gradient check unit test. Gradient check unit test utilizes finite difference method to verify the gradient of a layer. It modifies the input with a small perturbation :math:`\Delta x` and observes the changes of output :math:`\Delta y`, the gradient can be computed as :math:`\frac{\Delta y}{\Delta x }`. This gradient can be compared with the gradient computed by the :code:`backward` function of the layer to ensure the correctness of the gradient computation. Notice that the gradient check only tests the correctness of the gradient computation, it does not necessarily guarantee the correctness of the implementation of the :code:`forward` and :code:`backward` function. You need to write more sophisticated unit tests to make sure your layer is implemented correctly. All the gradient check unit tests are located in :code:`paddle/gserver/tests/test_LayerGrad.cpp`. You are recommended to put your test into a new test file if you are planning to write a new layer. The gradient test of the gradient check unit test of the fully connected layer is listed below. It has the following steps. + Create layer configuration. A layer configuration can include the following attributes: - size of the bias parameter. (4096 in our example) - type of the layer. (fc in our example) - size of the layer. (4096 in our example) - activation type. (softmax in our example) - dropout rate. (0.1 in our example) + configure the input of the layer. In our example, we have only one input. - type of the input (:code:`INPUT_DATA`) in our example. It can be one of the following types - :code:`INPUT_DATA`: dense vector. - :code:`INPUT_LABEL`: integer. - :code:`INPUT_DATA_TARGET`: dense vector, but it does not used to compute gradient. - :code:`INPUT_SEQUENCE_DATA`: dense vector with sequence information. - :code:`INPUT_HASSUB_SEQUENCE_DATA`: dense vector with both sequence and sub-sequence information. - :code:`INPUT_SEQUENCE_LABEL`: integer with sequence information. - :code:`INPUT_SPARSE_NON_VALUE_DATA`: 0-1 sparse data. - :code:`INPUT_SPARSE_FLOAT_VALUE_DATA`: float sparse data. - name of the input. (:code:`layer_0` in our example) - size of the input. (8192 in our example) - number of non-zeros, only useful for sparse inputs. - format of sparse data, only useful for sparse inputs. + each inputs needs to call :code:`config.layerConfig.add_inputs();` once. + call :code:`testLayerGrad` to perform gradient checks. It has the following arguments. - layer and input configurations. (:code:`config` in our example) - type of the layer. (:code:`fc` in our example) - batch size of the gradient check. (100 in our example) - whether the input is transpose. Most layers need to set it to :code:`false`. (:code:`false` in our example) - whether to use weights. Some layers or activations perform normalization so that the sum of their output is a constant. For example, the sum of output of a softmax activation is one. In this case, we cannot correctly compute the gradients using regular gradient check techniques. A weighted sum of the output, which is not a constant, is utilized to compute the gradients. (:code:`true` in our example, because the activation of a fully connected layer can be softmax) .. code-block:: c++ void testFcLayer(string format, size_t nnz) { // Create layer configuration. TestConfig config; config.biasSize = 4096; config.layerConfig.set_type("fc"); config.layerConfig.set_size(4096); config.layerConfig.set_active_type("softmax"); config.layerConfig.set_drop_rate(0.1); // Setup inputs. config.inputDefs.push_back( {INPUT_DATA, "layer_0", 8192, nnz, ParaSparse(format)}); config.layerConfig.add_inputs(); LOG(INFO) << config.inputDefs[0].sparse.sparse << " " << config.inputDefs[0].sparse.format; for (auto useGpu : {false, true}) { testLayerGrad(config, "fc", 100, /* trans */ false, useGpu, /* weight */ true); } } If you are creating a new file for the test, such as :code:`paddle/gserver/tests/testFCGrad.cpp`, you need to add the file to :code:`paddle/gserver/tests/CMakeLists.txt`. An example is given below. All the unit tests will run when you execute the command :code:`make tests`. Notice that some layers might need high accuracy for the gradient check unit tests to work well. You need to configure :code:`WITH_DOUBLE` to `ON` when configuring cmake. .. code-block:: bash add_unittest_without_exec(test_FCGrad test_FCGrad.cpp LayerGradUtil.cpp TestUtil.cpp) add_test(NAME test_FCGrad COMMAND test_FCGrad) Implement Python Wrapper ======================== Implementing Python wrapper allows us to use the added layer in configuration files. All the Python wrappers are in file :code:`python/paddle/trainer/config_parser.py`. An example of the Python wrapper for fully connected layer is listed below. It has the following steps: - Use :code:`@config_layer('fc')` at the decorator for all the Python wrapper class. :code:`fc` is the identifier of the layer. - Implements :code:`__init__` constructor function. - It first call :code:`super(FCLayer, self).__init__(name, 'fc', size, inputs=inputs, **xargs)` base constructor function. :code:`FCLayer` is the Python wrapper class name, and :code:`fc` is the layer identifier name. They must be correct in order for the wrapper to work. - Then it computes the size and format (whether sparse) of each transformation matrix as well as the size. .. code-block:: python @config_layer('fc') class FCLayer(LayerBase): def __init__( self, name, size, inputs, bias=True, **xargs): super(FCLayer, self).__init__(name, 'fc', size, inputs=inputs, **xargs) for input_index in xrange(len(self.inputs)): input_layer = self.get_input_layer(input_index) psize = self.config.size * input_layer.size dims = [input_layer.size, self.config.size] format = self.inputs[input_index].format sparse = format == "csr" or format == "csc" if sparse: psize = self.inputs[input_index].nnz self.create_input_parameter(input_index, psize, dims, sparse, format) self.create_bias_parameter(bias, self.config.size) In network configuration, the layer can be specifies using the following code snippets. The arguments of this class are: - :code:`name` is the name identifier of the layer instance. - :code:`type` is the type of the layer, specified using layer identifier. - :code:`size` is the output size of the layer. - :code:`bias` specifies whether this layer instance has bias. - :code:`inputs` specifies a list of layer instance names as inputs. .. code-block:: python Layer( name = "fc1", type = "fc", size = 64, bias = True, inputs = [Input("pool3")] ) You are also recommended to implement a helper for the Python wrapper, which makes it easier to write models. You can refer to :code:`python/paddle/trainer_config_helpers/layers.py` for examples.
{ "content_hash": "c789e811ad0d67e1b979104ff2fc62c6", "timestamp": "", "source": "github", "line_count": 390, "max_line_length": 856, "avg_line_length": 51.44615384615385, "alnum_prop": 0.687200956937799, "repo_name": "yu239/Paddle", "id": "110a9fb38f890a766bb4480e91feb22d3b0838a5", "size": "20064", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "doc/howto/dev/new_layer_en.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "260981" }, { "name": "C++", "bytes": "4147051" }, { "name": "CMake", "bytes": "187456" }, { "name": "CSS", "bytes": "21730" }, { "name": "Cuda", "bytes": "624060" }, { "name": "Go", "bytes": "99765" }, { "name": "HTML", "bytes": "8941" }, { "name": "JavaScript", "bytes": "1025" }, { "name": "Perl", "bytes": "11452" }, { "name": "Python", "bytes": "1408875" }, { "name": "Shell", "bytes": "132549" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!-- This file is part of the Dutch Taxonomy (Nederlandse Taxonomie; NT) Intellectual Property of the State of the Netherlands Architecture: NT11 Version: 20161214 Release date: Wed Dec 14 09:00:00 2016 --> <link:linkbase xmlns:link="http://www.xbrl.org/2003/linkbase" xmlns:xlink="http://www.w3.org/1999/xlink"> <link:roleRef roleURI="urn:kvk:linkrole:notes-accounting-principles-result" xlink:href="../dictionary/kvk-linkroles.xsd#kvk-lr_NotesAccountingPrinciplesResult" xlink:type="simple"/> <link:presentationLink xlink:role="urn:kvk:linkrole:notes-accounting-principles-result" xlink:type="extended"> <link:loc xlink:href="kvk-abstracts.xsd#kvk-abstr_AccountingPoliciesTitle" xlink:label="kvk-abstr_AccountingPoliciesTitle_loc" xlink:type="locator"/> <link:loc xlink:href="../../../rj/20161214/dictionary/rj-data.xsd#rj-i_EarningsPerSharePolicy" xlink:label="rj-i_EarningsPerSharePolicy_loc" xlink:type="locator"/> <link:presentationArc order="43" xlink:arcrole="http://www.xbrl.org/2003/arcrole/parent-child" xlink:from="kvk-abstr_AccountingPoliciesTitle_loc" xlink:to="rj-i_EarningsPerSharePolicy_loc" xlink:type="arc"/> </link:presentationLink> </link:linkbase>
{ "content_hash": "c8df0c6b830a972e8f1087f883ff01da", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 211, "avg_line_length": 79.375, "alnum_prop": 0.752755905511811, "repo_name": "dvreeze/tqa-workshop", "id": "2f1c4b4891590807fb739c265bb39bd97790f212", "size": "1270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/resources/taxonomy/www.nltaxonomie.nl/nt11/kvk/20161214/presentation/kvk-notes-accounting-principles-result_m_g-pre.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "234693" } ], "symlink_target": "" }
#include "UnitTestFramework.h" #include "InFnImageInitialization.h" #include <sstream> DEFINE_CATALOG_TABLE( InFnImageInitializationCatalog ) CATALOG_ENTRY( Catalog_Convert ) END_CATALOG_TABLE( InFnImageInitializationCatalog )
{ "content_hash": "6d47726869ee4c2000da4577000d672b", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 54, "avg_line_length": 24.1, "alnum_prop": 0.7842323651452282, "repo_name": "svn2github/framewave-trunk", "id": "fabffd634289d9cbde17ef217169352f06d0fda4", "size": "376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "UnitTest/UnitTestCollection/InFnImageInitialization/InFnImageInitialization.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5304240" }, { "name": "C++", "bytes": "14293223" }, { "name": "CSS", "bytes": "6874" }, { "name": "Objective-C", "bytes": "569589" }, { "name": "Perl", "bytes": "2099" }, { "name": "Python", "bytes": "87597" }, { "name": "Shell", "bytes": "13161" }, { "name": "XSLT", "bytes": "49906" } ], "symlink_target": "" }
#pragma once #include "String.h" #include <type_traits> namespace m { class SharedObject { public: SharedObject(); SharedObject(const String &name); ~SharedObject(); bool load(const String &name); template<typename T> T addressOf(const char *fname) const { static_assert(std::is_pointer<T>::value, "expected function pointer"); return reinterpret_cast<T>(_addr(fname)); } template<typename T> T addressOf(const String &fname) const { static_assert(std::is_pointer<T>::value, "expected function pointer"); return reinterpret_cast<T>(_addr(fname.raw())); } bool isOpen() const { return m_so != nullptr; } private: void *_addr(const char *name) const; void *m_so; }; }
{ "content_hash": "093a7c1485bed41503f6191c273ea945", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 82, "avg_line_length": 21.875, "alnum_prop": 0.5531428571428572, "repo_name": "montoyo/mgpcl", "id": "c784cc5df6bbc8e8ab3aa035ee567203a122a1c6", "size": "1986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/mgpcl/SharedObject.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2351" }, { "name": "C++", "bytes": "1093454" }, { "name": "CMake", "bytes": "4302" }, { "name": "Java", "bytes": "19829" }, { "name": "Lua", "bytes": "766" } ], "symlink_target": "" }
package org.apache.cassandra.db; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import com.codahale.metrics.Histogram; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.cache.IMeasurableMemory; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.io.ISerializer; import org.apache.cassandra.io.sstable.IndexInfo; import org.apache.cassandra.io.sstable.format.Version; import org.apache.cassandra.io.util.DataInputPlus; import org.apache.cassandra.io.util.DataOutputBuffer; import org.apache.cassandra.io.util.DataOutputPlus; import org.apache.cassandra.io.util.FileDataInput; import org.apache.cassandra.io.util.FileHandle; import org.apache.cassandra.io.util.TrackedDataInputPlus; import org.apache.cassandra.metrics.DefaultNameFactory; import org.apache.cassandra.metrics.MetricNameFactory; import org.apache.cassandra.utils.ObjectSizes; import org.apache.cassandra.utils.vint.VIntCoding; import org.github.jamm.Unmetered; import static org.apache.cassandra.metrics.CassandraMetricsRegistry.Metrics; /** * Binary format of {@code RowIndexEntry} is defined as follows: * {@code * (long) position (64 bit long, vint encoded) * (int) serialized size of data that follows (32 bit int, vint encoded) * -- following for indexed entries only (so serialized size > 0) * (int) DeletionTime.localDeletionTime * (long) DeletionTime.markedForDeletionAt * (int) number of IndexInfo objects (32 bit int, vint encoded) * (*) serialized IndexInfo objects, see below * (*) offsets of serialized IndexInfo objects, since version "ma" (3.0) * Each IndexInfo object's offset is relative to the first IndexInfo object. * } * <p> * See {@link IndexInfo} for a description of the serialized format. * </p> * * <p> * For each partition, the layout of the index file looks like this: * </p> * <ol> * <li>partition key - prefixed with {@code short} length</li> * <li>serialized {@code RowIndexEntry} objects</li> * </ol> * * <p> * Generally, we distinguish between index entries that have <i>index * samples</i> (list of {@link IndexInfo} objects) and those who don't. * For each <i>portion</i> of data for a single partition in the data file, * an index sample is created. The size of that <i>portion</i> is defined * by {@link org.apache.cassandra.config.Config#column_index_size_in_kb}. * </p> * <p> * Index entries with less than 2 index samples, will just store the * position in the data file. * </p> * <p> * Note: legacy sstables for index entries are those sstable formats that * do <i>not</i> have an offsets table to index samples ({@link IndexInfo} * objects). These are those sstables created on Cassandra versions * earlier than 3.0. * </p> * <p> * For index entries with index samples we store the index samples * ({@link IndexInfo} objects). The bigger the partition, the more * index samples are created. Since a huge amount of index samples * will "pollute" the heap and cause huge GC pressure, Cassandra 3.6 * (CASSANDRA-11206) distinguishes between index entries with an * "acceptable" amount of index samples per partition and those * with an "enormous" amount of index samples. The barrier * is controlled by the configuration parameter * {@link org.apache.cassandra.config.Config#column_index_cache_size_in_kb}. * Index entries with a total serialized size of index samples up to * {@code column_index_cache_size_in_kb} will be held in an array. * Index entries exceeding that value will always be accessed from * disk. * </p> * <p> * This results in these classes: * </p> * <ul> * <li>{@link RowIndexEntry} just stores the offset in the data file.</li> * <li>{@link IndexedEntry} is for index entries with index samples * and used for both current and legacy sstables, which do not exceed * {@link org.apache.cassandra.config.Config#column_index_cache_size_in_kb}.</li> * <li>{@link ShallowIndexedEntry} is for index entries with index samples * that exceed {@link org.apache.cassandra.config.Config#column_index_cache_size_in_kb} * for sstables with an offset table to the index samples.</li> * <li>{@link LegacyShallowIndexedEntry} is for index entries with index samples * that exceed {@link org.apache.cassandra.config.Config#column_index_cache_size_in_kb} * but for legacy sstables.</li> * </ul> * <p> * Since access to index samples on disk (obviously) requires some file * reader, that functionality is encapsulated in implementations of * {@link IndexInfoRetriever}. There is an implementation to access * index samples of legacy sstables (without the offsets table), * an implementation of access sstables with an offsets table. * </p> * <p> * Until now (Cassandra 3.x), we still support reading from <i>legacy</i> sstables - * i.e. sstables created by Cassandra &lt; 3.0 (see {@link org.apache.cassandra.io.sstable.format.big.BigFormat}. * </p> * */ public class RowIndexEntry<T> implements IMeasurableMemory { private static final long EMPTY_SIZE = ObjectSizes.measure(new RowIndexEntry(0)); // constants for type of row-index-entry as serialized for saved-cache static final int CACHE_NOT_INDEXED = 0; static final int CACHE_INDEXED = 1; static final int CACHE_INDEXED_SHALLOW = 2; static final Histogram indexEntrySizeHistogram; static final Histogram indexInfoCountHistogram; static final Histogram indexInfoGetsHistogram; static { MetricNameFactory factory = new DefaultNameFactory("Index", "RowIndexEntry"); indexEntrySizeHistogram = Metrics.histogram(factory.createMetricName("IndexedEntrySize"), false); indexInfoCountHistogram = Metrics.histogram(factory.createMetricName("IndexInfoCount"), false); indexInfoGetsHistogram = Metrics.histogram(factory.createMetricName("IndexInfoGets"), false); } public final long position; public RowIndexEntry(long position) { this.position = position; } /** * @return true if this index entry contains the row-level tombstone and column summary. Otherwise, * caller should fetch these from the row header. */ public boolean isIndexed() { return columnsIndexCount() > 1; } public boolean indexOnHeap() { return false; } public DeletionTime deletionTime() { throw new UnsupportedOperationException(); } /** * The length of the row header (partition key, partition deletion and static row). * This value is only provided for indexed entries and this method will throw * {@code UnsupportedOperationException} if {@code !isIndexed()}. */ public long headerLength() { throw new UnsupportedOperationException(); } public int columnsIndexCount() { return 0; } public long unsharedHeapSize() { return EMPTY_SIZE; } /** * @param dataFilePosition position of the partition in the {@link org.apache.cassandra.io.sstable.Component.Type#DATA} file * @param indexFilePosition position in the {@link org.apache.cassandra.io.sstable.Component.Type#PRIMARY_INDEX} of the {@link RowIndexEntry} * @param deletionTime deletion time of {@link RowIndexEntry} * @param headerLength deletion time of {@link RowIndexEntry} * @param columnIndexCount number of {@link IndexInfo} entries in the {@link RowIndexEntry} * @param indexedPartSize serialized size of all serialized {@link IndexInfo} objects and their offsets * @param indexSamples list with IndexInfo offsets (if total serialized size is less than {@link org.apache.cassandra.config.Config#column_index_cache_size_in_kb} * @param offsets offsets of IndexInfo offsets * @param idxInfoSerializer the {@link IndexInfo} serializer */ public static RowIndexEntry<IndexInfo> create(long dataFilePosition, long indexFilePosition, DeletionTime deletionTime, long headerLength, int columnIndexCount, int indexedPartSize, List<IndexInfo> indexSamples, int[] offsets, ISerializer<IndexInfo> idxInfoSerializer) { // If the "partition building code" in BigTableWriter.append() via ColumnIndex returns a list // of IndexInfo objects, which is the case if the serialized size is less than // Config.column_index_cache_size_in_kb, AND we have more than one IndexInfo object, we // construct an IndexedEntry object. (note: indexSamples.size() and columnIndexCount have the same meaning) if (indexSamples != null && indexSamples.size() > 1) return new IndexedEntry(dataFilePosition, deletionTime, headerLength, indexSamples.toArray(new IndexInfo[indexSamples.size()]), offsets, indexedPartSize, idxInfoSerializer); // Here we have to decide whether we have serialized IndexInfo objects that exceeds // Config.column_index_cache_size_in_kb (not exceeding case covered above). // Such a "big" indexed-entry is represented as a shallow one. if (columnIndexCount > 1) return new ShallowIndexedEntry(dataFilePosition, indexFilePosition, deletionTime, headerLength, columnIndexCount, indexedPartSize, idxInfoSerializer); // Last case is that there are no index samples. return new RowIndexEntry<>(dataFilePosition); } public IndexInfoRetriever openWithIndex(FileHandle indexFile) { return null; } public interface IndexSerializer<T> { void serialize(RowIndexEntry<T> rie, DataOutputPlus out, ByteBuffer indexInfo) throws IOException; RowIndexEntry<T> deserialize(DataInputPlus in, long indexFilePosition) throws IOException; void serializeForCache(RowIndexEntry<T> rie, DataOutputPlus out) throws IOException; RowIndexEntry<T> deserializeForCache(DataInputPlus in) throws IOException; long deserializePositionAndSkip(DataInputPlus in) throws IOException; ISerializer<T> indexInfoSerializer(); } public static final class Serializer implements IndexSerializer<IndexInfo> { private final IndexInfo.Serializer idxInfoSerializer; private final Version version; public Serializer(CFMetaData metadata, Version version, SerializationHeader header) { this.idxInfoSerializer = IndexInfo.serializer(version, header); this.version = version; } public IndexInfo.Serializer indexInfoSerializer() { return idxInfoSerializer; } public void serialize(RowIndexEntry<IndexInfo> rie, DataOutputPlus out, ByteBuffer indexInfo) throws IOException { rie.serialize(out, idxInfoSerializer, indexInfo); } public void serializeForCache(RowIndexEntry<IndexInfo> rie, DataOutputPlus out) throws IOException { rie.serializeForCache(out); } public RowIndexEntry<IndexInfo> deserializeForCache(DataInputPlus in) throws IOException { long position = in.readUnsignedVInt(); switch (in.readByte()) { case CACHE_NOT_INDEXED: return new RowIndexEntry<>(position); case CACHE_INDEXED: return new IndexedEntry(position, in, idxInfoSerializer, version); case CACHE_INDEXED_SHALLOW: return new ShallowIndexedEntry(position, in, idxInfoSerializer); default: throw new AssertionError(); } } public static void skipForCache(DataInputPlus in, Version version) throws IOException { /* long position = */in.readUnsignedVInt(); switch (in.readByte()) { case CACHE_NOT_INDEXED: break; case CACHE_INDEXED: IndexedEntry.skipForCache(in); break; case CACHE_INDEXED_SHALLOW: ShallowIndexedEntry.skipForCache(in); break; default: assert false; } } public RowIndexEntry<IndexInfo> deserialize(DataInputPlus in, long indexFilePosition) throws IOException { long position = in.readUnsignedVInt(); int size = (int)in.readUnsignedVInt(); if (size == 0) { return new RowIndexEntry<>(position); } else { long headerLength = in.readUnsignedVInt(); DeletionTime deletionTime = DeletionTime.serializer.deserialize(in); int columnsIndexCount = (int) in.readUnsignedVInt(); int indexedPartSize = size - serializedSize(deletionTime, headerLength, columnsIndexCount); if (size <= DatabaseDescriptor.getColumnIndexCacheSize()) { return new IndexedEntry(position, in, deletionTime, headerLength, columnsIndexCount, idxInfoSerializer, version, indexedPartSize); } else { in.skipBytes(indexedPartSize); return new ShallowIndexedEntry(position, indexFilePosition, deletionTime, headerLength, columnsIndexCount, indexedPartSize, idxInfoSerializer); } } } public long deserializePositionAndSkip(DataInputPlus in) throws IOException { return ShallowIndexedEntry.deserializePositionAndSkip(in); } /** * Reads only the data 'position' of the index entry and returns it. Note that this left 'in' in the middle * of reading an entry, so this is only useful if you know what you are doing and in most case 'deserialize' * should be used instead. */ public static long readPosition(DataInputPlus in, Version version) throws IOException { return in.readUnsignedVInt(); } public static void skip(DataInputPlus in, Version version) throws IOException { readPosition(in, version); skipPromotedIndex(in, version); } private static void skipPromotedIndex(DataInputPlus in, Version version) throws IOException { int size = (int)in.readUnsignedVInt(); if (size <= 0) return; in.skipBytesFully(size); } public static void serializeOffsets(DataOutputBuffer out, int[] indexOffsets, int columnIndexCount) throws IOException { for (int i = 0; i < columnIndexCount; i++) out.writeInt(indexOffsets[i]); } } private static int serializedSize(DeletionTime deletionTime, long headerLength, int columnIndexCount) { return TypeSizes.sizeofUnsignedVInt(headerLength) + (int) DeletionTime.serializer.serializedSize(deletionTime) + TypeSizes.sizeofUnsignedVInt(columnIndexCount); } public void serialize(DataOutputPlus out, IndexInfo.Serializer idxInfoSerializer, ByteBuffer indexInfo) throws IOException { out.writeUnsignedVInt(position); out.writeUnsignedVInt(0); } public void serializeForCache(DataOutputPlus out) throws IOException { out.writeUnsignedVInt(position); out.writeByte(CACHE_NOT_INDEXED); } /** * An entry in the row index for a row whose columns are indexed - used for both legacy and current formats. */ private static final class IndexedEntry extends RowIndexEntry<IndexInfo> { private static final long BASE_SIZE; static { BASE_SIZE = ObjectSizes.measure(new IndexedEntry(0, DeletionTime.LIVE, 0, null, null, 0, null)); } private final DeletionTime deletionTime; private final long headerLength; private final IndexInfo[] columnsIndex; private final int[] offsets; private final int indexedPartSize; @Unmetered private final ISerializer<IndexInfo> idxInfoSerializer; private IndexedEntry(long dataFilePosition, DeletionTime deletionTime, long headerLength, IndexInfo[] columnsIndex, int[] offsets, int indexedPartSize, ISerializer<IndexInfo> idxInfoSerializer) { super(dataFilePosition); this.headerLength = headerLength; this.deletionTime = deletionTime; this.columnsIndex = columnsIndex; this.offsets = offsets; this.indexedPartSize = indexedPartSize; this.idxInfoSerializer = idxInfoSerializer; } private IndexedEntry(long dataFilePosition, DataInputPlus in, DeletionTime deletionTime, long headerLength, int columnIndexCount, IndexInfo.Serializer idxInfoSerializer, Version version, int indexedPartSize) throws IOException { super(dataFilePosition); this.headerLength = headerLength; this.deletionTime = deletionTime; int columnsIndexCount = columnIndexCount; this.columnsIndex = new IndexInfo[columnsIndexCount]; for (int i = 0; i < columnsIndexCount; i++) this.columnsIndex[i] = idxInfoSerializer.deserialize(in); this.offsets = new int[this.columnsIndex.length]; for (int i = 0; i < offsets.length; i++) offsets[i] = in.readInt(); this.indexedPartSize = indexedPartSize; this.idxInfoSerializer = idxInfoSerializer; } /** * Constructor called from {@link Serializer#deserializeForCache(org.apache.cassandra.io.util.DataInputPlus)}. */ private IndexedEntry(long dataFilePosition, DataInputPlus in, IndexInfo.Serializer idxInfoSerializer, Version version) throws IOException { super(dataFilePosition); this.headerLength = in.readUnsignedVInt(); this.deletionTime = DeletionTime.serializer.deserialize(in); int columnsIndexCount = (int) in.readUnsignedVInt(); TrackedDataInputPlus trackedIn = new TrackedDataInputPlus(in); this.columnsIndex = new IndexInfo[columnsIndexCount]; for (int i = 0; i < columnsIndexCount; i++) this.columnsIndex[i] = idxInfoSerializer.deserialize(trackedIn); this.offsets = null; this.indexedPartSize = (int) trackedIn.getBytesRead(); this.idxInfoSerializer = idxInfoSerializer; } /** * Constructor called from {@link LegacyShallowIndexedEntry#deserialize(org.apache.cassandra.io.util.DataInputPlus, long, org.apache.cassandra.io.sstable.IndexInfo.Serializer)}. * Only for legacy sstables. */ private IndexedEntry(long dataFilePosition, DataInputPlus in, IndexInfo.Serializer idxInfoSerializer) throws IOException { super(dataFilePosition); long headerLength = 0; this.deletionTime = DeletionTime.serializer.deserialize(in); int columnsIndexCount = in.readInt(); TrackedDataInputPlus trackedIn = new TrackedDataInputPlus(in); this.columnsIndex = new IndexInfo[columnsIndexCount]; for (int i = 0; i < columnsIndexCount; i++) { this.columnsIndex[i] = idxInfoSerializer.deserialize(trackedIn); if (i == 0) headerLength = this.columnsIndex[i].offset; } this.headerLength = headerLength; this.offsets = null; this.indexedPartSize = (int) trackedIn.getBytesRead(); this.idxInfoSerializer = idxInfoSerializer; } @Override public boolean indexOnHeap() { return true; } @Override public int columnsIndexCount() { return columnsIndex.length; } @Override public DeletionTime deletionTime() { return deletionTime; } @Override public long headerLength() { return headerLength; } @Override public IndexInfoRetriever openWithIndex(FileHandle indexFile) { indexEntrySizeHistogram.update(serializedSize(deletionTime, headerLength, columnsIndex.length) + indexedPartSize); indexInfoCountHistogram.update(columnsIndex.length); return new IndexInfoRetriever() { private int retrievals; @Override public IndexInfo columnsIndex(int index) { retrievals++; return columnsIndex[index]; } public void close() { indexInfoGetsHistogram.update(retrievals); } }; } @Override public long unsharedHeapSize() { long entrySize = 0; for (IndexInfo idx : columnsIndex) entrySize += idx.unsharedHeapSize(); return BASE_SIZE + entrySize + ObjectSizes.sizeOfReferenceArray(columnsIndex.length); } @Override public void serialize(DataOutputPlus out, IndexInfo.Serializer idxInfoSerializer, ByteBuffer indexInfo) throws IOException { assert indexedPartSize != Integer.MIN_VALUE; out.writeUnsignedVInt(position); out.writeUnsignedVInt(serializedSize(deletionTime, headerLength, columnsIndex.length) + indexedPartSize); out.writeUnsignedVInt(headerLength); DeletionTime.serializer.serialize(deletionTime, out); out.writeUnsignedVInt(columnsIndex.length); for (IndexInfo info : columnsIndex) idxInfoSerializer.serialize(info, out); for (int offset : offsets) out.writeInt(offset); } @Override public void serializeForCache(DataOutputPlus out) throws IOException { out.writeUnsignedVInt(position); out.writeByte(CACHE_INDEXED); out.writeUnsignedVInt(headerLength); DeletionTime.serializer.serialize(deletionTime, out); out.writeUnsignedVInt(columnsIndexCount()); for (IndexInfo indexInfo : columnsIndex) idxInfoSerializer.serialize(indexInfo, out); } static void skipForCache(DataInputPlus in) throws IOException { /*long headerLength =*/in.readUnsignedVInt(); /*DeletionTime deletionTime = */DeletionTime.serializer.skip(in); /*int columnsIndexCount = (int)*/in.readUnsignedVInt(); /*int indexedPartSize = (int)*/in.readUnsignedVInt(); } } /** * An entry in the row index for a row whose columns are indexed and the {@link IndexInfo} objects * are not read into the key cache. */ private static final class ShallowIndexedEntry extends RowIndexEntry<IndexInfo> { private static final long BASE_SIZE; static { BASE_SIZE = ObjectSizes.measure(new ShallowIndexedEntry(0, 0, DeletionTime.LIVE, 0, 10, 0, null)); } private final long indexFilePosition; private final DeletionTime deletionTime; private final long headerLength; private final int columnsIndexCount; private final int indexedPartSize; private final int offsetsOffset; @Unmetered private final ISerializer<IndexInfo> idxInfoSerializer; private final int fieldsSerializedSize; /** * See {@link #create(long, long, DeletionTime, long, int, int, List, int[], ISerializer)} for a description * of the parameters. */ private ShallowIndexedEntry(long dataFilePosition, long indexFilePosition, DeletionTime deletionTime, long headerLength, int columnIndexCount, int indexedPartSize, ISerializer<IndexInfo> idxInfoSerializer) { super(dataFilePosition); assert columnIndexCount > 1; this.indexFilePosition = indexFilePosition; this.headerLength = headerLength; this.deletionTime = deletionTime; this.columnsIndexCount = columnIndexCount; this.indexedPartSize = indexedPartSize; this.idxInfoSerializer = idxInfoSerializer; this.fieldsSerializedSize = serializedSize(deletionTime, headerLength, columnIndexCount); this.offsetsOffset = indexedPartSize + fieldsSerializedSize - columnsIndexCount * TypeSizes.sizeof(0); } /** * Constructor for key-cache deserialization */ private ShallowIndexedEntry(long dataFilePosition, DataInputPlus in, IndexInfo.Serializer idxInfoSerializer) throws IOException { super(dataFilePosition); this.indexFilePosition = in.readUnsignedVInt(); this.headerLength = in.readUnsignedVInt(); this.deletionTime = DeletionTime.serializer.deserialize(in); this.columnsIndexCount = (int) in.readUnsignedVInt(); this.indexedPartSize = (int) in.readUnsignedVInt(); this.idxInfoSerializer = idxInfoSerializer; this.fieldsSerializedSize = serializedSize(deletionTime, headerLength, columnsIndexCount); this.offsetsOffset = indexedPartSize + fieldsSerializedSize - columnsIndexCount * TypeSizes.sizeof(0); } @Override public int columnsIndexCount() { return columnsIndexCount; } @Override public DeletionTime deletionTime() { return deletionTime; } @Override public long headerLength() { return headerLength; } @Override public IndexInfoRetriever openWithIndex(FileHandle indexFile) { indexEntrySizeHistogram.update(indexedPartSize + fieldsSerializedSize); indexInfoCountHistogram.update(columnsIndexCount); return new ShallowInfoRetriever(indexFilePosition + VIntCoding.computeUnsignedVIntSize(position) + VIntCoding.computeUnsignedVIntSize(indexedPartSize + fieldsSerializedSize) + fieldsSerializedSize, offsetsOffset - fieldsSerializedSize, indexFile.createReader(), idxInfoSerializer); } @Override public long unsharedHeapSize() { return BASE_SIZE; } @Override public void serialize(DataOutputPlus out, IndexInfo.Serializer idxInfoSerializer, ByteBuffer indexInfo) throws IOException { out.writeUnsignedVInt(position); out.writeUnsignedVInt(fieldsSerializedSize + indexInfo.limit()); out.writeUnsignedVInt(headerLength); DeletionTime.serializer.serialize(deletionTime, out); out.writeUnsignedVInt(columnsIndexCount); out.write(indexInfo); } static long deserializePositionAndSkip(DataInputPlus in) throws IOException { long position = in.readUnsignedVInt(); int size = (int) in.readUnsignedVInt(); if (size > 0) in.skipBytesFully(size); return position; } @Override public void serializeForCache(DataOutputPlus out) throws IOException { out.writeUnsignedVInt(position); out.writeByte(CACHE_INDEXED_SHALLOW); out.writeUnsignedVInt(indexFilePosition); out.writeUnsignedVInt(headerLength); DeletionTime.serializer.serialize(deletionTime, out); out.writeUnsignedVInt(columnsIndexCount); out.writeUnsignedVInt(indexedPartSize); } static void skipForCache(DataInputPlus in) throws IOException { /*long indexFilePosition =*/in.readUnsignedVInt(); /*long headerLength =*/in.readUnsignedVInt(); /*DeletionTime deletionTime = */DeletionTime.serializer.skip(in); /*int columnsIndexCount = (int)*/in.readUnsignedVInt(); /*int indexedPartSize = (int)*/in.readUnsignedVInt(); } } private static final class ShallowInfoRetriever extends FileIndexInfoRetriever { private final int offsetsOffset; private ShallowInfoRetriever(long indexInfoFilePosition, int offsetsOffset, FileDataInput indexReader, ISerializer<IndexInfo> idxInfoSerializer) { super(indexInfoFilePosition, indexReader, idxInfoSerializer); this.offsetsOffset = offsetsOffset; } IndexInfo fetchIndex(int index) throws IOException { retrievals++; // seek to position in "offsets to IndexInfo" table indexReader.seek(indexInfoFilePosition + offsetsOffset + index * TypeSizes.sizeof(0)); // read offset of IndexInfo int indexInfoPos = indexReader.readInt(); // seek to posision of IndexInfo indexReader.seek(indexInfoFilePosition + indexInfoPos); // finally, deserialize IndexInfo return idxInfoSerializer.deserialize(indexReader); } } /** * Base class to access {@link IndexInfo} objects. */ public interface IndexInfoRetriever extends AutoCloseable { IndexInfo columnsIndex(int index) throws IOException; void close() throws IOException; } /** * Base class to access {@link IndexInfo} objects on disk that keeps already * read {@link IndexInfo} on heap. */ private abstract static class FileIndexInfoRetriever implements IndexInfoRetriever { final long indexInfoFilePosition; final ISerializer<IndexInfo> idxInfoSerializer; final FileDataInput indexReader; int retrievals; /** * * @param indexInfoFilePosition offset of first serialized {@link IndexInfo} object * @param indexReader file data input to access the index file, closed by this instance * @param idxInfoSerializer the index serializer to deserialize {@link IndexInfo} objects */ FileIndexInfoRetriever(long indexInfoFilePosition, FileDataInput indexReader, ISerializer<IndexInfo> idxInfoSerializer) { this.indexInfoFilePosition = indexInfoFilePosition; this.idxInfoSerializer = idxInfoSerializer; this.indexReader = indexReader; } public final IndexInfo columnsIndex(int index) throws IOException { return fetchIndex(index); } abstract IndexInfo fetchIndex(int index) throws IOException; public void close() throws IOException { indexReader.close(); indexInfoGetsHistogram.update(retrievals); } } }
{ "content_hash": "4e81afb00f5d31a72025b52daed6abd4", "timestamp": "", "source": "github", "line_count": 836, "max_line_length": 185, "avg_line_length": 38.520334928229666, "alnum_prop": 0.6325497624444928, "repo_name": "mambocab/cassandra", "id": "a709ec399e251b12a6911645ea6eac65a5292dd6", "size": "33008", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "src/java/org/apache/cassandra/db/RowIndexEntry.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "801" }, { "name": "Batchfile", "bytes": "23782" }, { "name": "GAP", "bytes": "84392" }, { "name": "Java", "bytes": "17033690" }, { "name": "Lex", "bytes": "10154" }, { "name": "PowerShell", "bytes": "40545" }, { "name": "Python", "bytes": "510317" }, { "name": "Shell", "bytes": "54699" }, { "name": "Thrift", "bytes": "40290" } ], "symlink_target": "" }
<?php namespace Mailgun\Model\Suppression\Bounce; use Mailgun\Model\Suppression\BaseResponse; /** * @author Sean Johnson <sean@mailgun.com> */ final class CreateResponse extends BaseResponse { }
{ "content_hash": "c8c04a6d12a7338889fa9cb699532d71", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 47, "avg_line_length": 14.428571428571429, "alnum_prop": 0.7574257425742574, "repo_name": "qisimah/web", "id": "e91d5e887312912172df54052dc866825989ac6d", "size": "368", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "qisimah/vendor/mailgun/mailgun-php/src/Mailgun/Model/Suppression/Bounce/CreateResponse.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4367332" }, { "name": "CoffeeScript", "bytes": "204316" }, { "name": "HTML", "bytes": "668989" }, { "name": "JavaScript", "bytes": "3255623" }, { "name": "Makefile", "bytes": "266" }, { "name": "PHP", "bytes": "864812" }, { "name": "PowerShell", "bytes": "1404" }, { "name": "Python", "bytes": "48843" }, { "name": "Ruby", "bytes": "696" }, { "name": "Shell", "bytes": "6223" }, { "name": "Vue", "bytes": "563" } ], "symlink_target": "" }
- Supported usage - [ ] Atom - [ ] Sublime - [ ] CLI - [ ] Core (Node.js API) - [ ] Core - [ ] Standard Options & Languages - [ ] Add Option - Option has fields: - `key` (unique) - `description` - `default` - `type` - ... - [ ] Add Language - Language has fields: - `name` (unique) - `namespace` (unique) - `extensions` - `options` - [ ] Add Beautifier - Supported languages and options - Given `({ text, language, options, filePath, projectPath })` - Beautifiers run in their own processes - Beautifier queue limiting number of simultaneous processes - [ ] Add Configurer - Configurer will obtain values for the options - [ ] CLI - [ ] Find beautifiers globally installed named `beautifier-${name}` - See https://github.com/yeoman/environment/blob/f9468481911c31673378b38e63872f57a1163f38/lib/resolver.js#L63 - [ ] Atom - [ ] Configurers - [ ] Atom Editor Settings - [ ] - [ ] External Beautifiers - [ ] Services (Consumer/Provider) API - [ ] Sublime - Use CLI Models: - Options - Languages - name - namespace - extensions - atomGrammars (for Atom) - sublimeSyntax (for Sublime) - Beautifiers - hasMany Options - hasMany Languages - [ ] Can update Beautifier independently - [ ] Can update Language Separate Options registry (centralized) Separate Languages registry (centralized) Separate Beautifiers (no registry, decentralized) - Peer/Atom dependencies: - Goal: NPM Global ```bash npm install --global unibeautify npm install --global beautifier-js-beautify unibeautify --language JavaScript ``` Goal: Atom ```bash apm install unibeautify apm install beautifier-js-beautify ```
{ "content_hash": "58f200c95c05e0c4831462c9c8dd9270", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 113, "avg_line_length": 21.20731707317073, "alnum_prop": 0.6532489936745256, "repo_name": "Unibeautify/unibeautify", "id": "b3df329c3146ec2b4decea0a9820d9c4811fc67b", "size": "1760", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ROADMAP.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1062" }, { "name": "TypeScript", "bytes": "130200" } ], "symlink_target": "" }
<tool id="iwtomics_testandplot" name="IWTomics Test" version="@VERSION@.0"> <description>and Plot</description> <xrefs> <xref type="bio.tools">iwtomics</xref> </xrefs> <macros> <import>macros.xml</import> </macros> <expand macro="requirements" /> <command detect_errors="exit_code"> <![CDATA[ Rscript '$__tool_directory__/testandplot.R' adjustedpvaluematrix='${adjustedpvaluematrix}' iwtomicsrespdf='${iwtomicsrespdf}' iwtomicssumpdf='${iwtomicssumpdf}' iwtomicsrdata='${iwtomicsrdata}' iwtomicstests='${iwtomicstests}' iwtomicsselectedfeatures='${iwtomicsselectedfeatures}' regionids='${regionids}' featureids='${featureids}' rdatafile='${rdata}' #set region1 = ','.join( [ str( $r.region0 ) for $r in $regionssection.regions ] ) #set region2 = ','.join( [ str( $r.region1 ) for $r in $regionssection.regions ] ) region1='c(${region1})' region2='c(${region2})' features_subset='c(${featureslist})' statistics="'${conditionalstatistics.statistics}'" #if $conditionalstatistics.statistics == "quantile": #set probabilities = ','.join( [ str( $p.qprob ) for $p in $conditionalstatistics.quantilesection.qprobabilities ] ) testprobs='c(${probabilities})' #end if B='${permutations}' testalpha='${plotres.alpha}' average='${plotres.average}' size='${plotres.size}' plottype="'${plotres.conditionalplottype.plottype}'" #if $plotres.conditionalplottype.plottype == "boxplot": #set probs = ','.join( [ str( $p.prob ) for $p in $plotres.conditionalplottype.probabilitiessection.probabilities ] ) #if $probs != "": probs='c(${plotres.conditionalplottype.probabilitiessection.prob0},${plotres.conditionalplottype.probabilitiessection.prob1},${plotres.conditionalplottype.probabilitiessection.prob2},${probs})' #else: probs='c(${plotres.conditionalplottype.probabilitiessection.prob0},${plotres.conditionalplottype.probabilitiessection.prob1},${plotres.conditionalplottype.probabilitiessection.prob2})' #end if #end if groupby="'${plotsum.conditionalgroupby.groupby}'" #if $plotsum.conditionalgroupby.groupby == "test": summaryalpha='${plotsum.conditionalgroupby.testalphaplot}' only_significant='${plotsum.conditionalgroupby.testonlysig}' #elif $plotsum.conditionalgroupby.groupby == "feature": summaryalpha='${plotsum.conditionalgroupby.featurealphaplot}' only_significant='${plotsum.conditionalgroupby.featureonlysig}' #end if ]]> </command> <inputs> <!-- RData --> <param format="rdata" name="rdata" type="data" label="Select IWTomicsData object" help="File created by 'IWTomics Load Smooth and Plot'." /> <!-- region IDs --> <param format="tabular" name="regionids" type="data" label="Select region dataset IDs" help="File created by 'IWTomics Load Smooth and Plot'." /> <!-- feature IDs --> <param format="tabular" name="featureids" type="data" label="Select feature IDs" help="File created by 'IWTomics Load Smooth and Plot'." /> <!-- repeat region ids --> <section name="regionssection" title="Select regions for Interval-Wise Testing" expanded="True" help="IDs of the region datasets to be tested."> <repeat name="regions" title="Two-sample test" min="1"> <param name="region0" type="data_column" data_ref="regionids" numerical="False" label="Region 1" multiple="False" use_header_names="True" /> <param name="region1" type="data_column" data_ref="regionids" numerical="False" label="Region 2" multiple="False" use_header_names="True" /> </repeat> </section> <!-- feature ids list --> <param name="featureslist" type="data_column" data_ref="featureids" numerical="False" label="Select features" multiple="True" use_header_names="True" help="IDs of the features to be tested." /> <!-- conditional statistics --> <conditional name="conditionalstatistics"> <!-- statistics --> <param name="statistics" type="select" label="Test statistics"> <option value="mean">Mean difference</option> <option value="median">Median difference</option> <option value="variance">Variance ratio</option> <option value="quantile">Quantile difference(s)</option> </param> <!-- conditional choice: statistics=quantile --> <when value="mean" /> <when value="median" /> <when value="variance" /> <when value="quantile"> <section name="quantilesection" title="Probabilities" expanded="True" help="Probabilities corresponding to the quantiles in test statistics."> <repeat name="qprobabilities" title="Probabilities" min="1"> <param name="qprob" size="4" type="float" value="0.5" min="0.0" max="1.0" label="Probability" /> </repeat> </section> </when> </conditional> <!-- permutations --> <param name="permutations" type="integer" value="1000" min="1" label="Number of permutations" /> <!-- plot IWTomics results --> <section name="plotres" title="Plot IWTomics test results" expanded="True"> <!-- alpha --> <param name="alpha" size="3" type="float" value="0.05" min="0.0" max="1.0" label="Level of the test (alpha)" /> <expand macro="plot-params" /> </section> <!-- summary plot --> <expand macro="plot-sum" /> </inputs> <outputs> <data format="txt" name="adjustedpvaluematrix" label="${tool.name} on ${on_string}: Adjusted p-value Matrix" from_work_dir="iwtomics.testandplot.adjustedpvalue.matrix.txt" /> <data format="pdf" name="iwtomicsrespdf" label="${tool.name} on ${on_string}: Plotted Test Results" from_work_dir="iwtomics.testandplot.iwtomicstestresults.pdf" /> <data format="pdf" name="iwtomicssumpdf" label="${tool.name} on ${on_string}: Summary Plot" from_work_dir="iwtomics.testandplot.summaryplot.pdf" /> <data format="rdata" name="iwtomicsrdata" label="${tool.name} on ${on_string}: IWTomicsData Object with Test Results" from_work_dir="iwtomics.testandplot.RData" /> <data format="tabular" name="iwtomicstests" label="${tool.name} on ${on_string}: Test IDs" from_work_dir="iwtomics.testandplot.tests.txt" /> <data format="tabular" name="iwtomicsselectedfeatures" label="${tool.name} on ${on_string}: Feature IDs" from_work_dir="iwtomics.testandplot.selectedfeatures.txt" /> </outputs> <tests> <test> <param name="rdata" value="output_loadandplot/iwtomics.loadandplot.RData" ftype="rdata" /> <param name="regionids" value="output_loadandplot/iwtomics.loadandplot.regions.txt" ftype="tabular" /> <param name="featureids" value="output_loadandplot/iwtomics.loadandplot.features.txt" ftype="tabular" /> <repeat name="regions"> <param name="region0" value="2" /> <param name="region1" value="1" /> </repeat> <repeat name="regions"> <param name="region0" value="3" /> <param name="region1" value="1" /> </repeat> <repeat name="regions"> <param name="region0" value="4" /> <param name="region1" value="1" /> </repeat> <param name="featureslist" value="1,2" /> <param name="statistics" value="mean" /> <param name="permutations" value="1000" /> <param name="alpha" value="0.05" /> <param name="average" value="TRUE" /> <param name="size" value="TRUE" /> <param name="plottype" value="boxplot" /> <param name="prob0" value="0.25" /> <param name="prob1" value="0.5" /> <param name="prob2" value="0.75" /> <param name="groupby" value="feature" /> <param name="featurealphaplot" value="0.05" /> <param name="featureonlysig" value="TRUE" /> <output name="adjustedpvaluematrix" file="output_testandplot/iwtomics.testandplot.adjustedpvalue.matrix.txt" compare="sim_size" /> <output name="iwtomicsrespdf" file="output_testandplot/iwtomics.testandplot.iwtomicstestresults.pdf" compare="sim_size" /> <output name="iwtomicssumpdf" file="output_testandplot/iwtomics.testandplot.summaryplot.pdf" compare="sim_size" /> <output name="iwtomicsrdata" file="output_testandplot/iwtomics.testandplot.RData" compare="sim_size" /> <output name="iwtomicstests" file="output_testandplot/iwtomics.testandplot.tests.txt" /> <output name="iwtomicsselectedfeatures" file="output_testandplot/iwtomics.testandplot.selectedfeatures.txt" /> </test> </tests> <help><![CDATA[ This tool statistically evaluates differences in genomic features between groups of regions along the genome. In particular, it implements the Interval-Wise Testing for omics data, an extended version of the Interval-Wise Testing for functional data presented in Pini and Vantini (2017). It allows to perform multiple two sample permutation tests between pairs of region datasets, on several features. It returns the adjusted p-value curves for every test and all possible scales. Moreover, it creates a graphical representation of the Interval-Wise Testing results and a summary plot (optional) with p-values at the maximum scale. The tool *IWTomics Plot with Threshold on Test Scale* permits to select the scale to be used in the plots. ----- **Input files** RData file with the IWTomicsData object, tabular files with region dataset IDs and feature IDs. These files are created by the tool *IWTomics Load Smooth and Plot*. ----- **Output** The tool returns: 1. TXT file with an adjusted p-value matrix for every test performed. Each matrix contains a p-value curve (row) for every scale considered in the test; 2. PDF file with the plotted test results; 3. PDF file with the summary plot; 4. RData with the IWTomicsData object with the test results; 5. Test identifiers; 6. Feature identifiers. 4-6 can be used as input of the tool *IWTomics Plot with Threshold on Test Scale* ----- .. class:: infomark **Notes** This Galaxy tool has been developed by Fabio Cumbo (Third University of Rome, Italy) and Marzia A. Cremona (The Pennsylvania State University, USA). It implements a simplified version of the function *IWTomicsTest*, *plotTest* and *plotSummary* for *IWTomicsData* objects. The complete version can be found in the *R/Bioconductor* package *IWTomics* (see vignette_). .. _vignette: https://bioconductor.org/packages/release/bioc/vignettes/IWTomics/inst/doc/IWTomics.pdf ]]></help> <expand macro="citations" /> </tool>
{ "content_hash": "0ca29d3ad10449b7e37e98df5ac32111", "timestamp": "", "source": "github", "line_count": 207, "max_line_length": 285, "avg_line_length": 50.772946859903385, "alnum_prop": 0.6825880114176974, "repo_name": "blankenberg/tools-iuc", "id": "843697565a150e4535a7db2fd727012c47e14c5a", "size": "10510", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "tools/iwtomics/testandplot.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "4232" }, { "name": "HTML", "bytes": "22337199" }, { "name": "HyPhy", "bytes": "5740" }, { "name": "JavaScript", "bytes": "63170" }, { "name": "Mako", "bytes": "2116" }, { "name": "Max", "bytes": "140358" }, { "name": "OpenEdge ABL", "bytes": "1960016" }, { "name": "Pep8", "bytes": "76028" }, { "name": "Perl", "bytes": "85273" }, { "name": "Python", "bytes": "1465681" }, { "name": "R", "bytes": "340002" }, { "name": "Roff", "bytes": "418688" }, { "name": "Shell", "bytes": "100379" }, { "name": "UnrealScript", "bytes": "660637" }, { "name": "eC", "bytes": "24" } ], "symlink_target": "" }
<productinfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="optional"> <?xml-stylesheet type="text/xsl"href="optional"?> <matlabrelease>2014a</matlabrelease> <name>Robotics</name> <type>toolbox</type> <icon></icon> <help_location>info</help_location> <help_contents_icon>$toolbox/matlab/icons/bookicon.gif</help_contents_icon> </productinfo>
{ "content_hash": "f08d09f3bdc402ea982b2d4a575a3b2b", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 75, "avg_line_length": 35.45454545454545, "alnum_prop": 0.7538461538461538, "repo_name": "madratman/riss_bingham", "id": "3c142343693f3a292756333f6efc3e47b79c9269", "size": "390", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "matlab/robot-9.10/rvctools/robot/info.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "17198129" }, { "name": "C++", "bytes": "22178342" }, { "name": "CSS", "bytes": "14525" }, { "name": "Fortran", "bytes": "285254" }, { "name": "HTML", "bytes": "3452018" }, { "name": "Java", "bytes": "36102" }, { "name": "JavaScript", "bytes": "22349" }, { "name": "Lua", "bytes": "29317" }, { "name": "M", "bytes": "3179" }, { "name": "Makefile", "bytes": "7138" }, { "name": "Mathematica", "bytes": "465" }, { "name": "Matlab", "bytes": "3540588" }, { "name": "Mercury", "bytes": "201" }, { "name": "Perl", "bytes": "2698" }, { "name": "R", "bytes": "2166" } ], "symlink_target": "" }
<?php namespace League\CLImate\Settings; class Manager { /** * An array of settings that have been... set * * @var array $settings */ protected $settings = []; /** * Check and see if the requested setting is a valid, registered setting * * @param string $name * * @return boolean */ public function exists($name) { return class_exists($this->getPath($name)); } /** * Add a setting * * @param string $name * @param mixed $value */ public function add($name, $value) { $setting = $this->getPath($name); $key = $this->getClassName($name); // If the current key doesn't exist in the settings array, set it up if (!array_key_exists($name, $this->settings)) { $this->settings[$key] = new $setting(); } $this->settings[$key]->add($value); } /** * Get the value of the requested setting if it exists * * @param string $key * * @return mixed */ public function get($key) { if (array_key_exists($key, $this->settings)) { return $this->settings[$key]; } return false; } /** * Get the short name for the requested settings class * * @param string $name * * @return string */ protected function getPath($name) { return '\\League\CLImate\\Settings\\' . $this->getClassName($name); } /** * Get the short class name for the setting * * @param string $name * * @return string */ protected function getClassName($name) { return ucwords(str_replace('add_', '', $name)); } }
{ "content_hash": "85cad5b07d16711db0a4498f1a7636a5", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 76, "avg_line_length": 20.576470588235296, "alnum_prop": 0.5214408233276158, "repo_name": "j-froehlich/magento2_wk", "id": "e69a393faa602d1e83a0e15b92b6c2b80bbcf156", "size": "1749", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "vendor/league/climate/src/Settings/Manager.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "13636" }, { "name": "CSS", "bytes": "2076720" }, { "name": "HTML", "bytes": "6151072" }, { "name": "JavaScript", "bytes": "2488727" }, { "name": "PHP", "bytes": "12466046" }, { "name": "Shell", "bytes": "6088" }, { "name": "XSLT", "bytes": "19979" } ], "symlink_target": "" }
local Dict = torch.class("Dict") function Dict:__init(data) self.idxToLabel = {} self.labelToIdx = {} self.frequencies = {} self.freqTensor = nil -- Special entries will not be pruned. self.special = {} if data ~= nil then if type(data) == "string" then -- File to load. self:loadFile(data) else self:addSpecials(data) end end end --[[ Return the number of entries in the dictionary. ]] function Dict:size() return #self.idxToLabel end --[[ Load entries from a file. ]] function Dict:loadFile(filename) local reader = onmt.utils.FileReader.new(filename) while true do local fields = reader:next() if not fields then break end local label = fields[1] local idx = tonumber(fields[2]) self:add(label, idx) end reader:close() end --[[ Write entries to a file. ]] function Dict:writeFile(filename) local file = assert(io.open(filename, 'w')) for i = 1, self:size() do local label = self.idxToLabel[i] if self.frequencies then file:write(label .. ' ' .. i .. ' ' .. (self.frequencies[i] or 0) .. '\n') elseif self.freqTensor then file:write(label .. ' ' .. i .. ' ' .. self.freqTensor[i] .. '\n') else file:write(label .. ' ' .. i .. '\n') end end file:close() end --[[ Drop or serialize the frequency tensor. ]] function Dict:prepFrequency(keep) if not keep then self.freqTensor = nil else self.freqTensor = torch.Tensor(self.frequencies) end self.frequencies = nil end --[[ Lookup `key` in the dictionary: it can be an index or a string. ]] function Dict:lookup(key) if type(key) == "string" then return self.labelToIdx[key] else return self.idxToLabel[key] end end --[[ Mark this `label` and `idx` as special (i.e. will not be pruned). ]] function Dict:addSpecial(label, idx, frequency) idx = self:add(label, idx, frequency) table.insert(self.special, idx) end --[[ Mark all labels in `labels` as specials (i.e. will not be pruned). ]] function Dict:addSpecials(labels) for i = 1, #labels do self:addSpecial(labels[i], nil, 0) end end --[[ Check if idx is index for special label ]] function Dict:isSpecialIdx(idx) for _,v in ipairs(self.special) do if idx == v then return true end end return false end --[[ Set the frequency of a vocab. ]] function Dict:setFrequency(label, frequency) local idx = self.labelToIdx[label] if idx then self.frequencies[idx] = frequency end end --[[ Add `label` in the dictionary. Use `idx` as its index if given. ]] function Dict:add(label, idx, frequency) if not frequency then frequency = 1 end if idx ~= nil then self.idxToLabel[idx] = label self.labelToIdx[label] = idx else idx = self.labelToIdx[label] if idx == nil then idx = #self.idxToLabel + 1 self.idxToLabel[idx] = label self.labelToIdx[label] = idx end end if self.frequencies[idx] == nil then self.frequencies[idx] = frequency else self.frequencies[idx] = self.frequencies[idx] + frequency end return idx end --[[ Return a new dictionary with the `size` most frequent entries. ]] function Dict:prune(size) if size >= self:size()-#self.special then return self end -- Only keep the `size` most frequent entries. local freq = torch.Tensor(self.frequencies) local _, idx = torch.sort(freq, 1, true) local newDict = Dict.new() -- Add special entries in all cases. for i = 1, #self.special do local thevocab = self.idxToLabel[self.special[i]] local thefreq = self.frequencies[self.special[i]] newDict:addSpecial(thevocab, nil, thefreq) end local i = 1 local count = 0 while count ~= size do if not self:isSpecialIdx(idx[i]) then newDict:add(self.idxToLabel[idx[i]], nil, self.frequencies[idx[i]]) count = count + 1 end i = i + 1 end -- set UNK frequency newDict:setFrequency(onmt.Constants.UNK_WORD, freq:sum()-torch.Tensor(newDict.frequencies):sum()) return newDict end --[[ Return a new dictionary with entries appearing at least `minFrequency` times. ]] function Dict:pruneByMinFrequency(minFrequency) if minFrequency < 2 then return self end local freq = torch.Tensor(self.frequencies) local sortedFreq, idx = torch.sort(freq, 1, true) local newDict = Dict.new() -- Add special entries in all cases. for i = 1, #self.special do local thevocab = self.idxToLabel[self.special[i]] local thefreq = self.frequencies[self.special[i]] newDict:addSpecial(thevocab, nil, thefreq) end for i = 1, self:size() do if sortedFreq[i] < minFrequency then break end newDict:add(self.idxToLabel[idx[i]], nil, sortedFreq[i]) end -- set UNK frequency newDict:setFrequency(onmt.Constants.UNK_WORD, freq:sum()-torch.Tensor(newDict.frequencies):sum()) return newDict end --[[ Add frequency to current dictionary from provided dictionary ]] function Dict:getFrequencies(dict) local newDict = Dict.new() for i = 1, dict:size() do local token = dict.idxToLabel[i] local idx = self.labelToIdx[token] local frequency = 0 if idx then frequency = self.frequencies[idx] end newDict:add(token, i) newDict.frequencies[i] = frequency end -- set UNK frequency newDict:setFrequency(onmt.Constants.UNK_WORD, torch.Tensor(self.frequencies):sum()-torch.Tensor(newDict.frequencies):sum()); return newDict end --[[ Convert `labels` to indices. Use `unkWord` if not found. Optionally insert `bosWord` at the beginning and `eosWord` at the end. ]] function Dict:convertToIdx(labels, unkWord, bosWord, eosWord) local vec = {} if bosWord ~= nil then table.insert(vec, self:lookup(bosWord)) end for i = 1, #labels do local idx = self:lookup(labels[i]) if idx == nil then idx = self:lookup(unkWord) end table.insert(vec, idx) end if eosWord ~= nil then table.insert(vec, self:lookup(eosWord)) end return torch.IntTensor(vec) end --[[ Convert `idx` to labels. If index `stop` is reached, convert it and return. ]] function Dict:convertToLabels(idx, stop) local labels = {} for i = 1, #idx do table.insert(labels, self:lookup(idx[i])) if idx[i] == stop then break end end return labels end return Dict
{ "content_hash": "1c757c8f2dbc5bf5a8910f4021535fca", "timestamp": "", "source": "github", "line_count": 266, "max_line_length": 100, "avg_line_length": 23.80827067669173, "alnum_prop": 0.6624032843833886, "repo_name": "monsieurzhang/OpenNMT", "id": "b6e5baeda8548aa6541fcc52eaae6fdda808a17a", "size": "6333", "binary": false, "copies": "1", "ref": "refs/heads/dual", "path": "onmt/utils/Dict.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "480951" }, { "name": "Perl", "bytes": "6984" }, { "name": "Python", "bytes": "5597" }, { "name": "Shell", "bytes": "4992" } ], "symlink_target": "" }
/* -- talk.js Helpers function for talking. */ function TLK_tauntEnemy(target) { var enemyName = getName(target); var taunts = [ "Bagdad Gaming !", "Ca sent le sapin.", "Et d'la main gauche !", "As-tu déja ramassé tes dents avec les doigts cassés " + enemyName + "?", "Je pue peut-être, mais j'ai un gros flingue.", "Je met les pieds où je veux " + enemyName + ", et c'est souvent dans la geule." ]; say(taunts[ randInt(0, count(taunts))]); }
{ "content_hash": "5d187398acfaa4aba9f10f51da872c21", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 82, "avg_line_length": 24.31578947368421, "alnum_prop": 0.645021645021645, "repo_name": "jleloup/leek-scripts", "id": "16ad2752e22ad6faccb0efa803ae047151a07df9", "size": "467", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Helpers/talk.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "7654" } ], "symlink_target": "" }
package org.apache.druid.server.coordination; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import org.apache.druid.discovery.NodeRole; import org.apache.druid.java.util.common.StringUtils; /** * This enum represents types of druid services that hold segments. * <p> * These types are externally visible (e.g., from the output of {@link * org.apache.druid.server.http.ServersResource#makeSimpleServer}). * <p> * For backwards compatibility, when presenting these types externally, the toString() representation * of the enum should be used. * <p> * The toString() method converts the enum name() to lowercase and replaces underscores with hyphens, * which is the format expected for the server type string prior to the patch that introduced ServerType: * https://github.com/apache/druid/pull/4148 * * This is a historical occasion that this enum is different from {@link NodeRole} because * they are essentially the same abstraction, but merging them could only increase the complexity and drop the code * safety, because they name the same types differently ("indexer-executor" - "peon" and "realtime" - "middleManager") * and both expose them via JSON APIs. * * These abstractions can probably be merged when Druid updates to Jackson 2.9 that supports JsonAliases, see * see https://github.com/apache/druid/issues/7152. */ public enum ServerType { HISTORICAL, BRIDGE, INDEXER_EXECUTOR { @Override public boolean isSegmentReplicationTarget() { return false; } }, REALTIME { @Override public boolean isSegmentReplicationTarget() { return false; } }, BROKER { @Override public boolean isSegmentReplicationTarget() { return false; } }; /** * Indicates this type of node is able to be a target of segment replication. * * @return true if it is available for replication * * @see org.apache.druid.server.coordinator.rules.LoadRule */ public boolean isSegmentReplicationTarget() { return true; } /** * Indicates this type of node is able to be a target of segment broadcast. * * @return true if it is available for broadcast. */ public boolean isSegmentBroadcastTarget() { return true; } @JsonCreator public static ServerType fromString(String type) { return ServerType.valueOf(StringUtils.toUpperCase(type).replace('-', '_')); } @Override @JsonValue public String toString() { return StringUtils.toLowerCase(name()).replace('_', '-'); } }
{ "content_hash": "65f283a15b2a1e6cc3b0c7870a3f083a", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 118, "avg_line_length": 27.795698924731184, "alnum_prop": 0.7137330754352031, "repo_name": "leventov/druid", "id": "0b860a1b0afe8ab4983305b48e6273ef15a6ffb4", "size": "3392", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/src/main/java/org/apache/druid/server/coordination/ServerType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1158" }, { "name": "CSS", "bytes": "11623" }, { "name": "Groff", "bytes": "3617" }, { "name": "HTML", "bytes": "18353" }, { "name": "Java", "bytes": "11910863" }, { "name": "JavaScript", "bytes": "292710" }, { "name": "Makefile", "bytes": "659" }, { "name": "PostScript", "bytes": "5" }, { "name": "Protocol Buffer", "bytes": "552" }, { "name": "R", "bytes": "17002" }, { "name": "Shell", "bytes": "3997" }, { "name": "TeX", "bytes": "399444" } ], "symlink_target": "" }
#ifndef AVUTIL_AVUTIL_H #define AVUTIL_AVUTIL_H /** * @file * external API header */ #define AV_STRINGIFY(s) AV_TOSTRING(s) #define AV_TOSTRING(s) #s #define AV_GLUE(a, b) a ## b #define AV_JOIN(a, b) AV_GLUE(a, b) #define AV_PRAGMA(s) _Pragma(#s) #define AV_VERSION_INT(a, b, c) (a<<16 | b<<8 | c) #define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c #define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c) #define LIBAVUTIL_VERSION_MAJOR 50 #define LIBAVUTIL_VERSION_MINOR 15 #define LIBAVUTIL_VERSION_MICRO 1 #define LIBAVUTIL_VERSION_INT AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \ LIBAVUTIL_VERSION_MINOR, \ LIBAVUTIL_VERSION_MICRO) #define LIBAVUTIL_VERSION AV_VERSION(LIBAVUTIL_VERSION_MAJOR, \ LIBAVUTIL_VERSION_MINOR, \ LIBAVUTIL_VERSION_MICRO) #define LIBAVUTIL_BUILD LIBAVUTIL_VERSION_INT #define LIBAVUTIL_IDENT "Lavu" AV_STRINGIFY(LIBAVUTIL_VERSION) /** * Returns the LIBAVUTIL_VERSION_INT constant. */ unsigned avutil_version(void); /** * Returns the libavutil build-time configuration. */ const char *avutil_configuration(void); /** * Returns the libavutil license. */ const char *avutil_license(void); enum AVMediaType { AVMEDIA_TYPE_UNKNOWN = -1, AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA, AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_ATTACHMENT, AVMEDIA_TYPE_NB }; #include "common.h" #include "error.h" #include "mathematics.h" #include "rational.h" #include "intfloat_readwrite.h" #include "log.h" #include "pixfmt.h" #endif /* AVUTIL_AVUTIL_H */
{ "content_hash": "78e055d30f1ef3c7b1d08ce1f7837998", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 73, "avg_line_length": 24.507042253521128, "alnum_prop": 0.6155172413793103, "repo_name": "eirTony/INDI1", "id": "e9e07b92fd4cfa407ddf134875c39e68172dac64", "size": "2566", "binary": false, "copies": "33", "ref": "refs/heads/develop", "path": "to/lang/OpenCV-2.2.0/3rdparty/include/ffmpeg_/libavutil/avutil.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2182" }, { "name": "C", "bytes": "987751" }, { "name": "C++", "bytes": "25614243" }, { "name": "CMake", "bytes": "723934" }, { "name": "CSS", "bytes": "175949" }, { "name": "Cuda", "bytes": "311879" }, { "name": "HTML", "bytes": "839417" }, { "name": "Java", "bytes": "127925" }, { "name": "JavaScript", "bytes": "199216" }, { "name": "M4", "bytes": "200" }, { "name": "Makefile", "bytes": "6245411" }, { "name": "Mathematica", "bytes": "284" }, { "name": "Objective-C++", "bytes": "53970" }, { "name": "Prolog", "bytes": "2474" }, { "name": "Python", "bytes": "415039" }, { "name": "QMake", "bytes": "173988" }, { "name": "Shell", "bytes": "3748" }, { "name": "TeX", "bytes": "1530252" } ], "symlink_target": "" }
import unittest from base_test_class import BaseTestCase from selenium.webdriver.common.by import By import sys class VariousPagesTest(BaseTestCase): def test_user_status(self): driver = self.driver driver.get(self.base_url + "user") def test_calendar_status(self): driver = self.driver driver.get(self.base_url + "calendar") # click apply to see if this helps webdriver to catch the javascript errors we're seeing driver.find_element(By.CSS_SELECTOR, "input.btn.btn-primary").click() def suite(): suite = unittest.TestSuite() suite.addTest(BaseTestCase('test_login')) suite.addTest(VariousPagesTest('test_user_status')) suite.addTest(VariousPagesTest('test_calendar_status')) return suite if __name__ == "__main__": runner = unittest.TextTestRunner(descriptions=True, failfast=True, verbosity=2) ret = not runner.run(suite()).wasSuccessful() BaseTestCase.tearDownDriver() sys.exit(ret)
{ "content_hash": "db37b925200b1757b7065a8b2d3e5148", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 96, "avg_line_length": 31.806451612903224, "alnum_prop": 0.6987829614604463, "repo_name": "rackerlabs/django-DefectDojo", "id": "0e2275d61ac59cf9bd51e49f73a9343e6e6f73ed", "size": "986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/check_various_pages.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "18132" }, { "name": "Groff", "bytes": "91" }, { "name": "HTML", "bytes": "666571" }, { "name": "JavaScript", "bytes": "6393" }, { "name": "Python", "bytes": "524728" }, { "name": "Shell", "bytes": "20558" }, { "name": "XSLT", "bytes": "6624" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Bepasty</title> <!-- Bootstrap styles --> <link rel="stylesheet" href="{{ url_for('bepasty.xstatic', name='bootstrap', filename='css/bootstrap.min.css') }}" type="text/css"> <!-- jQuery UI styles --> <link rel="stylesheet" href="{{ url_for('bepasty.xstatic', name='jquery_ui', filename='themes/smoothness/jquery-ui.css') }}" type="text/css"> <!-- Bepasty styles --> <link rel="stylesheet" href="{{ url_for('static', filename='app/css/style.css' ) }}" type="text/css"> {% block extra_link %}{% endblock %} </head> <body> <div id="wrapper"> <!-- Begin header --> <div id="header"> <div class="container"> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse"> <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="/"> {{ config.SITENAME }} (Permissions: {{ flaskg.permissions | join(',') }}) </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="http://bepasty-server.readthedocs.org/en/latest/">Documentation</a></li> {% if may(LIST) %} <li><a href="{{ url_for('bepasty.filelist') }}">List all Items</a></li> {% endif %} </ul> {% if flaskg.logged_in %} <form class="navbar-form navbar-right" role="form" method="post" action="/+logout"> <input class="btn btn-default" type="submit" value="Logout"> </form> {% else %} <form class="navbar-form navbar-right form-inline" role="form" method="post" action="/+login"> <div class="form-group"> <input class="form-control" type="password" name="token" autofocus> </div> <button type="submit" class="btn btn-default">Login</button> </form> {% endif %} </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> </div> </div> <!-- /.header --> <!-- Begin page content --> <div class="container"> {% block content %}{% endblock %} </div> <!-- /.container --> </div> <!-- /.wrapper --> <!-- Begin footer --> <div id="footer"> <div class="container"> </div> </div> <!-- /.footer --> <!-- jQuery --> <script src="{{ url_for('bepasty.xstatic', name='jquery', filename='jquery.min.js') }}" type="text/javascript"></script> <!-- jQuery UI --> <script src="{{ url_for('bepasty.xstatic', name='jquery_ui', filename='jquery-ui.min.js') }}" type="text/javascript"></script> <!-- Bootstrap --> <script src="{{ url_for('bepasty.xstatic', name='bootstrap', filename='js/bootstrap.min.js') }}" type="text/javascript"></script> {% block extra_script %}{% endblock %} </body> </html>
{ "content_hash": "a7f85d3c1aa4531bff261caf9e2b7d9a", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 149, "avg_line_length": 51.49438202247191, "alnum_prop": 0.4270128736635392, "repo_name": "makefu/bepasty-server", "id": "69e8b9ad0078420401804ece2837c2ea8db8a6b4", "size": "4583", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bepasty/templates/_layout.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "1724" }, { "name": "HTML", "bytes": "19453" }, { "name": "JavaScript", "bytes": "5860" }, { "name": "Python", "bytes": "84481" } ], "symlink_target": "" }
package org.wso2.carbon.event.publisher.core.internal.util.helper; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.wso2.carbon.event.publisher.core.exception.EventPublisherConfigurationException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; /** * Pretty-prints xml, supplied as a string. * <p/> * eg. * <code> * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>"); * </code> */ public class XmlFormatter { public XmlFormatter() { } public static String format(String unformattedXml) throws EventPublisherConfigurationException { try { final Document document = parseXmlFile(unformattedXml); OutputFormat format = new OutputFormat(document); format.setLineWidth(65); format.setIndenting(true); format.setIndent(2); Writer out = new StringWriter(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(document); return out.toString(); } catch (IOException e) { throw new EventPublisherConfigurationException(e); } } private static Document parseXmlFile(String in) throws EventPublisherConfigurationException { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(in)); return db.parse(is); } catch (ParserConfigurationException e) { throw new EventPublisherConfigurationException(e); } catch (SAXException e) { throw new EventPublisherConfigurationException(e); } catch (IOException e) { throw new EventPublisherConfigurationException(e); } } }
{ "content_hash": "6501b79bfa538aa794edd32d8f41ed68", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 97, "avg_line_length": 33.417910447761194, "alnum_prop": 0.6761947297900849, "repo_name": "kasungayan/carbon-analytics-common", "id": "05c73133f50b20270d617d5eabf9ecda244ed15c", "size": "2880", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "components/event-publisher/org.wso2.carbon.event.publisher.core/src/main/java/org/wso2/carbon/event/publisher/core/internal/util/helper/XmlFormatter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25747" }, { "name": "HTML", "bytes": "30510" }, { "name": "Java", "bytes": "3719136" }, { "name": "JavaScript", "bytes": "615279" }, { "name": "Thrift", "bytes": "3745" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- include aframe --> <script src="vendor/aframe.js"></script> <!-- include aframe-artoolkit --> <script src="../build/aframe-ar.js"></script> <body style='margin : 0px; overflow: hidden; font-family: Monospace;'><div style='position: fixed; top: 10px; width:inherit; text-align: center; z-index: 1;'> <a href="https://github.com/jeromeetienne/AR.js/" target="_blank">AR.js</a> - mobile performance in a-frame <br/> Contact me any time at <a href='https://twitter.com/jerome_etienne' target='_blank'>@jerome_etienne</a> </div> <!-- enable artoolkit on this scene --> <a-scene stats embedded artoolkit='sourceType: webcam; detectionMode: mono; maxDetectionRate: 30; canvasWidth: 240; canvasHeight: 180'> <!-- define the object which gonna be put on this marker --> <a-box position='0 0 0.5' material='opacity: 0.5; side: double'> <a-torus-knot radius='0.27' radius-tubular='0.05'> <a-animation attribute="rotation" to="360 0 0" dur="3000" easing='linear' repeat="indefinite"></a-animation> </a-torus-knot> </a-box> <a-marker-camera preset='hiro'></a-marker-camera> </a-scene> </body> </html>
{ "content_hash": "8f0cf268bb4aa05aac37b0ba07c70119", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 158, "avg_line_length": 45.48, "alnum_prop": 0.6798592788038699, "repo_name": "zhangjialiang/ar-test", "id": "721daadaa2e69d6df2278103106e83fc738b942f", "size": "1137", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aframe/examples/mobile-performance.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "176384" }, { "name": "JavaScript", "bytes": "106116" }, { "name": "Makefile", "bytes": "823" } ], "symlink_target": "" }
from __future__ import absolute_import from datetime import timedelta from django.http import HttpResponse from django.test import TestCase from django.test.client import RequestFactory from django.contrib.auth.models import AnonymousUser from django.contrib.auth import get_user_model from django.contrib.sessions.backends.db import SessionStore as DatabaseSession from django.utils import timezone from experiments import conf from experiments.experiment_counters import ExperimentCounter from experiments.middleware import ExperimentsRetentionMiddleware from experiments.models import Experiment, ENABLED_STATE, Enrollment from experiments.conf import CONTROL_GROUP, VISIT_PRESENT_COUNT_GOAL, VISIT_NOT_PRESENT_COUNT_GOAL from experiments.signal_handlers import transfer_enrollments_to_user from experiments.utils import participant from mock import patch import random request_factory = RequestFactory() TEST_ALTERNATIVE = 'blue' TEST_GOAL = 'buy' EXPERIMENT_NAME = 'backgroundcolor' class WebUserTests(object): def setUp(self): self.experiment = Experiment(name=EXPERIMENT_NAME, state=ENABLED_STATE) self.experiment.save() self.request = request_factory.get('/') self.request.session = DatabaseSession() self.experiment_counter = ExperimentCounter() def tearDown(self): self.experiment_counter.delete(self.experiment) def test_enrollment_initially_control(self): experiment_user = participant(self.request) self.assertEqual(experiment_user.get_alternative(EXPERIMENT_NAME), 'control', "Default Enrollment wasn't control") def test_user_enrolls(self): experiment_user = participant(self.request) experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(experiment_user.get_alternative(EXPERIMENT_NAME), TEST_ALTERNATIVE, "Wrong Alternative Set") def test_record_goal_increments_counts(self): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 0) experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 1, "Did not increment Goal count") def test_can_record_goal_multiple_times(self): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.goal(TEST_GOAL) experiment_user.goal(TEST_GOAL) experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 1, "Did not increment goal count correctly") self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), {3: 1}, "Incorrect goal count distribution") def test_counts_increment_immediately_once_confirmed_human(self): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 1, "Did not count participant after confirm human") def test_visit_increases_goal(self): thetime = timezone.now() with patch('experiments.utils.now', return_value=thetime): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.visit() self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_NOT_PRESENT_COUNT_GOAL), {1: 1}, "Not Present Visit was not correctly counted") self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_PRESENT_COUNT_GOAL), {}, "Present Visit was not correctly counted") with patch('experiments.utils.now', return_value=thetime + timedelta(hours=7)): experiment_user.visit() self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_NOT_PRESENT_COUNT_GOAL), {2: 1}, "No Present Visit was not correctly counted") self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_PRESENT_COUNT_GOAL), {1: 1}, "Present Visit was not correctly counted") def test_visit_twice_increases_once(self): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.visit() experiment_user.visit() self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_NOT_PRESENT_COUNT_GOAL), {1: 1}, "Visit was not correctly counted") self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_PRESENT_COUNT_GOAL), {}, "Present Visit was not correctly counted") def test_user_force_enrolls(self): experiment_user = participant(self.request) experiment_user.enroll(EXPERIMENT_NAME, ['control', 'alternative1', 'alternative2'], force_alternative='alternative2') self.assertEqual(experiment_user.get_alternative(EXPERIMENT_NAME), 'alternative2') def test_user_does_not_force_enroll_to_new_alternative(self): alternatives = ['control', 'alternative1', 'alternative2'] experiment_user = participant(self.request) experiment_user.enroll(EXPERIMENT_NAME, alternatives) alternative = experiment_user.get_alternative(EXPERIMENT_NAME) self.assertIsNotNone(alternative) other_alternative = random.choice(list(set(alternatives) - set(alternative))) experiment_user.enroll(EXPERIMENT_NAME, alternatives, force_alternative=other_alternative) self.assertEqual(alternative, experiment_user.get_alternative(EXPERIMENT_NAME)) def test_second_force_enroll_does_not_change_alternative(self): alternatives = ['control', 'alternative1', 'alternative2'] experiment_user = participant(self.request) experiment_user.enroll(EXPERIMENT_NAME, alternatives, force_alternative='alternative1') alternative = experiment_user.get_alternative(EXPERIMENT_NAME) self.assertIsNotNone(alternative) other_alternative = random.choice(list(set(alternatives) - set(alternative))) experiment_user.enroll(EXPERIMENT_NAME, alternatives, force_alternative=other_alternative) self.assertEqual(alternative, experiment_user.get_alternative(EXPERIMENT_NAME)) class WebUserAnonymousTestCase(WebUserTests, TestCase): def setUp(self): super(WebUserAnonymousTestCase, self).setUp() self.request.user = AnonymousUser() def test_confirm_human_increments_participant_count(self): experiment_user = participant(self.request) experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 0, "Counted participant before confirmed human") experiment_user.confirm_human() self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 1, "Did not count participant after confirm human") def test_confirm_human_increments_goal_count(self): experiment_user = participant(self.request) experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 0, "Counted goal before confirmed human") experiment_user.confirm_human() self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 1, "Did not count goal after confirm human") class WebUserAuthenticatedTestCase(WebUserTests, TestCase): def setUp(self): super(WebUserAuthenticatedTestCase, self).setUp() User = get_user_model() self.request.user = User(username='brian') self.request.user.save() class BotTests(object): def setUp(self): self.experiment = Experiment(name='backgroundcolor', state=ENABLED_STATE) self.experiment.save() self.experiment_counter = ExperimentCounter() def test_user_does_not_enroll(self): self.experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 0, "Bot counted towards results") def test_user_does_not_fire_goals(self): self.experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 0, "Bot counted towards results") def test_bot_in_control_group(self): self.experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(self.experiment_user.get_alternative(EXPERIMENT_NAME), 'control', "Bot enrolled in a group") self.assertEqual(self.experiment_user.is_enrolled(self.experiment.name, TEST_ALTERNATIVE), False, "Bot in test alternative") self.assertEqual(self.experiment_user.is_enrolled(self.experiment.name, CONTROL_GROUP), True, "Bot not in control group") def tearDown(self): self.experiment_counter.delete(self.experiment) class LoggedOutBotTestCase(BotTests, TestCase): def setUp(self): super(LoggedOutBotTestCase, self).setUp() self.request = request_factory.get('/', HTTP_USER_AGENT='GoogleBot/2.1') self.experiment_user = participant(self.request) class LoggedInBotTestCase(BotTests, TestCase): def setUp(self): super(LoggedInBotTestCase, self).setUp() User = get_user_model() self.user = User(username='brian') self.user.is_confirmed_human = False self.user.save() self.experiment_user = participant(user=self.user) class ParticipantCacheTestCase(TestCase): def setUp(self): self.experiment = Experiment.objects.create(name='test_experiment1', state=ENABLED_STATE) self.experiment_counter = ExperimentCounter() def tearDown(self): self.experiment_counter.delete(self.experiment) def test_transfer_enrollments(self): User = get_user_model() user = User.objects.create(username='test') request = request_factory.get('/') request.session = DatabaseSession() participant(request).enroll('test_experiment1', ['alternative']) request.user = user transfer_enrollments_to_user(None, request, user) # the call to the middleware will set last_seen on the experiment # if the participant cache hasn't been wiped appropriately then the # session experiment user will be impacted instead of the authenticated # experiment user ExperimentsRetentionMiddleware().process_response(request, HttpResponse()) self.assertIsNotNone(Enrollment.objects.all()[0].last_seen) class ConfirmHumanTestCase(TestCase): def setUp(self): self.experiment = Experiment.objects.create(name='test_experiment1', state=ENABLED_STATE) self.experiment_counter = ExperimentCounter() self.experiment_user = participant(session=DatabaseSession()) self.alternative = self.experiment_user.enroll(self.experiment.name, ['alternative']) self.experiment_user.goal('my_goal') def tearDown(self): self.experiment_counter.delete(self.experiment) def test_confirm_human_updates_experiment(self): self.assertIn('experiments_goals', self.experiment_user.session) self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 0) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 0) self.experiment_user.confirm_human() self.assertNotIn('experiments_goals', self.experiment_user.session) self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 1) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 1) def test_confirm_human_called_twice(self): """ Ensuring that counters aren't incremented twice """ self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 0) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 0) self.experiment_user.confirm_human() self.experiment_user.confirm_human() self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 1) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 1) def test_confirm_human_sets_session(self): self.assertFalse(self.experiment_user.session.get(conf.CONFIRM_HUMAN_SESSION_KEY, False)) self.experiment_user.confirm_human() self.assertTrue(self.experiment_user.session.get(conf.CONFIRM_HUMAN_SESSION_KEY, False)) def test_session_already_confirmed(self): """ Testing that confirm_human works even if code outside of django-experiments updates the key """ self.experiment_user.session[conf.CONFIRM_HUMAN_SESSION_KEY] = True self.experiment_user.confirm_human() self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 1) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 1) class DefaultAlternativeTestCase(TestCase): def test_default_alternative(self): experiment = Experiment.objects.create(name='test_default') self.assertEqual(experiment.default_alternative, conf.CONTROL_GROUP) experiment.ensure_alternative_exists('alt1') experiment.ensure_alternative_exists('alt2') self.assertEqual(conf.CONTROL_GROUP, participant(session=DatabaseSession()).enroll('test_default', ['alt1', 'alt2'])) experiment.set_default_alternative('alt2') experiment.save() self.assertEqual('alt2', participant(session=DatabaseSession()).enroll('test_default', ['alt1', 'alt2'])) experiment.set_default_alternative('alt1') experiment.save() self.assertEqual('alt1', participant(session=DatabaseSession()).enroll('test_default', ['alt1', 'alt2']))
{ "content_hash": "a295d88783bd489d57a8f314ca426850", "timestamp": "", "source": "github", "line_count": 292, "max_line_length": 191, "avg_line_length": 51.39383561643836, "alnum_prop": 0.7265276204437929, "repo_name": "uhuramedia/django-experiments", "id": "5a09c2540906d68f040c5975d57c4bff68ba0dad", "size": "15007", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "experiments/tests/test_webuser.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1597" }, { "name": "HTML", "bytes": "10966" }, { "name": "JavaScript", "bytes": "9580" }, { "name": "Python", "bytes": "124496" } ], "symlink_target": "" }
'use strict'; const fs = require('hexo-fs'); const Promise = require('bluebird'); const pathFn = require('path'); const chalk = require('chalk'); function assetGenerator(locals) { const self = this; function process(name) { return Promise.filter(self.model(name).toArray(), asset => fs.exists(asset.source).then(exist => { if (exist) return exist; return asset.remove().thenReturn(exist); })).map(asset => { const source = asset.source; let path = asset.path; const data = { modified: asset.modified }; if (asset.renderable && self.render.isRenderable(path)) { // Replace extension name if the asset is renderable const extname = pathFn.extname(path); const filename = path.substring(0, path.length - extname.length); path = `${filename}.${self.render.getOutput(path)}`; data.data = () => self.render.render({ path: source, toString: true }).catch(err => { self.log.error({err}, 'Asset render failed: %s', chalk.magenta(path)); }); } else { data.data = () => fs.createReadStream(source); } return { path, data }; }); } return Promise.all([ process('Asset'), process('PostAsset') ]).then(data => Array.prototype.concat.apply([], data)); } module.exports = assetGenerator;
{ "content_hash": "85e37c5d0a1f1a0c2dc6575f5331e2b4", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 102, "avg_line_length": 26.807692307692307, "alnum_prop": 0.5868005738880918, "repo_name": "shadow000902/blog_source", "id": "dce1b0c9470fad2ece0a52b463bf1b5fba13d623", "size": "1394", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "node_modules/hexo/lib/plugins/generator/asset.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7617146" }, { "name": "JavaScript", "bytes": "443074" }, { "name": "Objective-C", "bytes": "2466" }, { "name": "Python", "bytes": "2376" }, { "name": "Shell", "bytes": "162" } ], "symlink_target": "" }
Boucle d'événements : particularité NodeJS ![Event loop](assets/img/NodeJS-EventedIOAsyncIO_latest.png)
{ "content_hash": "aa7196bbcccf203550d14d4c7ec111c2", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 60, "avg_line_length": 34.666666666666664, "alnum_prop": 0.8173076923076923, "repo_name": "openhoat/lab-nodejs", "id": "10ccaed3c4cbe3ebe9a1568bcdb0b0c1a3223699", "size": "107", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "etc/slideshow/slides/2/3.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "189152" }, { "name": "HTML", "bytes": "4500" }, { "name": "JavaScript", "bytes": "147873" } ], "symlink_target": "" }
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import { refType } from '@material-ui/utils'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import { alpha } from '@material-ui/system'; import SwitchBase from '../internal/SwitchBase'; import CheckBoxOutlineBlankIcon from '../internal/svg-icons/CheckBoxOutlineBlank'; import CheckBoxIcon from '../internal/svg-icons/CheckBox'; import IndeterminateCheckBoxIcon from '../internal/svg-icons/IndeterminateCheckBox'; import capitalize from '../utils/capitalize'; import useThemeProps from '../styles/useThemeProps'; import styled, { rootShouldForwardProp } from '../styles/styled'; import checkboxClasses, { getCheckboxUtilityClass } from './checkboxClasses'; import { jsx as _jsx } from "react/jsx-runtime"; var useUtilityClasses = function useUtilityClasses(styleProps) { var classes = styleProps.classes, indeterminate = styleProps.indeterminate, color = styleProps.color; var slots = { root: ['root', indeterminate && 'indeterminate', "color".concat(capitalize(color))] }; var composedClasses = composeClasses(slots, getCheckboxUtilityClass, classes); return _extends({}, classes, composedClasses); }; var CheckboxRoot = styled(SwitchBase, { shouldForwardProp: function shouldForwardProp(prop) { return rootShouldForwardProp(prop) || prop === 'classes'; }, name: 'MuiCheckbox', slot: 'Root', overridesResolver: function overridesResolver(props, styles) { var styleProps = props.styleProps; return [styles.root, styleProps.indeterminate && styles.indeterminate, styleProps.color !== 'default' && styles["color".concat(capitalize(styleProps.color))]]; } })(function (_ref) { var _ref2; var theme = _ref.theme, styleProps = _ref.styleProps; return _extends({ color: theme.palette.text.secondary }, !styleProps.disableRipple && { '&:hover': { backgroundColor: alpha(styleProps.color === 'default' ? theme.palette.action.active : theme.palette[styleProps.color].main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, styleProps.color !== 'default' && (_ref2 = {}, _defineProperty(_ref2, "&.".concat(checkboxClasses.checked, ", &.").concat(checkboxClasses.indeterminate), { color: theme.palette[styleProps.color].main }), _defineProperty(_ref2, "&.".concat(checkboxClasses.disabled), { color: theme.palette.action.disabled }), _ref2)); }); var defaultCheckedIcon = /*#__PURE__*/_jsx(CheckBoxIcon, {}); var defaultIcon = /*#__PURE__*/_jsx(CheckBoxOutlineBlankIcon, {}); var defaultIndeterminateIcon = /*#__PURE__*/_jsx(IndeterminateCheckBoxIcon, {}); var Checkbox = /*#__PURE__*/React.forwardRef(function Checkbox(inProps, ref) { var _icon$props$fontSize, _indeterminateIcon$pr; var props = useThemeProps({ props: inProps, name: 'MuiCheckbox' }); var _props$checkedIcon = props.checkedIcon, checkedIcon = _props$checkedIcon === void 0 ? defaultCheckedIcon : _props$checkedIcon, _props$color = props.color, color = _props$color === void 0 ? 'primary' : _props$color, _props$icon = props.icon, iconProp = _props$icon === void 0 ? defaultIcon : _props$icon, _props$indeterminate = props.indeterminate, indeterminate = _props$indeterminate === void 0 ? false : _props$indeterminate, _props$indeterminateI = props.indeterminateIcon, indeterminateIconProp = _props$indeterminateI === void 0 ? defaultIndeterminateIcon : _props$indeterminateI, inputProps = props.inputProps, _props$size = props.size, size = _props$size === void 0 ? 'medium' : _props$size, other = _objectWithoutProperties(props, ["checkedIcon", "color", "icon", "indeterminate", "indeterminateIcon", "inputProps", "size"]); var icon = indeterminate ? indeterminateIconProp : iconProp; var indeterminateIcon = indeterminate ? indeterminateIconProp : checkedIcon; var styleProps = _extends({}, props, { color: color, indeterminate: indeterminate, size: size }); var classes = useUtilityClasses(styleProps); return /*#__PURE__*/_jsx(CheckboxRoot, _extends({ type: "checkbox", inputProps: _extends({ 'data-indeterminate': indeterminate }, inputProps), icon: /*#__PURE__*/React.cloneElement(icon, { fontSize: (_icon$props$fontSize = icon.props.fontSize) != null ? _icon$props$fontSize : size }), checkedIcon: /*#__PURE__*/React.cloneElement(indeterminateIcon, { fontSize: (_indeterminateIcon$pr = indeterminateIcon.props.fontSize) != null ? _indeterminateIcon$pr : size }), styleProps: styleProps, ref: ref }, other, { classes: classes })); }); process.env.NODE_ENV !== "production" ? Checkbox.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * If `true`, the component is checked. */ checked: PropTypes.bool, /** * The icon to display when the component is checked. * @default <CheckBoxIcon /> */ checkedIcon: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * The color of the component. It supports those theme colors that make sense for this component. * @default 'primary' */ color: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['default', 'primary', 'secondary', 'error', 'info', 'succes', 'warning']), PropTypes.string]), /** * The default checked state. Use when the component is not controlled. */ defaultChecked: PropTypes.bool, /** * If `true`, the component is disabled. */ disabled: PropTypes.bool, /** * If `true`, the ripple effect is disabled. */ disableRipple: PropTypes.bool, /** * The icon to display when the component is unchecked. * @default <CheckBoxOutlineBlankIcon /> */ icon: PropTypes.node, /** * The id of the `input` element. */ id: PropTypes.string, /** * If `true`, the component appears indeterminate. * This does not set the native input element to indeterminate due * to inconsistent behavior across browsers. * However, we set a `data-indeterminate` attribute on the `input`. * @default false */ indeterminate: PropTypes.bool, /** * The icon to display when the component is indeterminate. * @default <IndeterminateCheckBoxIcon /> */ indeterminateIcon: PropTypes.node, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * Callback fired when the state is changed. * * @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback. * You can pull out the new checked state by accessing `event.target.checked` (boolean). */ onChange: PropTypes.func, /** * If `true`, the `input` element is required. */ required: PropTypes.bool, /** * The size of the component. * `small` is equivalent to the dense checkbox styling. * @default 'medium' */ size: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]), /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * The value of the component. The DOM API casts this to a string. * The browser uses "on" as the default value. */ value: PropTypes.any } : void 0; export default Checkbox;
{ "content_hash": "c10ddb786c40331cf6ef2599bd207f57", "timestamp": "", "source": "github", "line_count": 234, "max_line_length": 165, "avg_line_length": 35.14529914529915, "alnum_prop": 0.6723005836575876, "repo_name": "cdnjs/cdnjs", "id": "47b13b38f5c65b9cec42c0dfd2ecbe6eb6a6ac72", "size": "8224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/material-ui/5.0.0-beta.4/legacy/Checkbox/Checkbox.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
from __future__ import absolute_import, division, print_function, unicode_literals from c7n.manager import resources from c7n.query import QueryResourceManager @resources.register('step-machine') class StepFunction(QueryResourceManager): """AWS Step Functions State Machine""" class resource_type(object): service = 'stepfunctions' enum_spec = ('list_state_machines', 'stateMachines', None) id = 'stateMachineArn' name = 'name' date = 'creationDate' dimension = None detail_spec = ( "describe_state_machine", "stateMachineArn", 'stateMachineArn', None)
{ "content_hash": "625908f45c350292d4644b17483ef68f", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 82, "avg_line_length": 32.25, "alnum_prop": 0.6651162790697674, "repo_name": "jdubs/cloud-custodian", "id": "f637ca4c66443e3a13e6d5236d32dc48fc06cf0f", "size": "1235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "c7n/resources/sfn.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1251" }, { "name": "Python", "bytes": "1557818" } ], "symlink_target": "" }
package org.apache.geode.cache.query.internal.cq; import org.apache.logging.log4j.Logger; import org.apache.geode.StatisticDescriptor; import org.apache.geode.Statistics; import org.apache.geode.StatisticsFactory; import org.apache.geode.StatisticsType; import org.apache.geode.StatisticsTypeFactory; import org.apache.geode.cache.query.CqException; import org.apache.geode.cache.query.CqQuery; import org.apache.geode.cache.query.internal.DefaultQueryService; import org.apache.geode.internal.NanoTimer; import org.apache.geode.internal.cache.FilterProfile; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.statistics.StatisticsTypeFactoryImpl; /** * This class tracks GemFire statistics related to CqService. Specifically the following statistics * are tracked: Number of CQs created Number of active CQs Number of CQs suspended or stopped Number * of CQs closed Number of CQs on a client * * @since GemFire 5.5 */ public class CqServiceVsdStats { private static final Logger logger = LogService.getLogger(); /** The <code>StatisticsType</code> of the statistics */ private static final StatisticsType _type; /** Name of the created CQs statistic */ private static final String CQS_CREATED = "numCqsCreated"; /** Name of the active CQs statistic */ private static final String CQS_ACTIVE = "numCqsActive"; /** Name of the stopped CQs statistic */ private static final String CQS_STOPPED = "numCqsStopped"; /** Name of the closed CQs statistic */ private static final String CQS_CLOSED = "numCqsClosed"; /** Name of the client's CQs statistic */ private static final String CQS_ON_CLIENT = "numCqsOnClient"; /** Number of clients with CQs statistic */ private static final String CLIENTS_WITH_CQS = "numClientsWithCqs"; /** CQ query execution time. */ private static final String CQ_QUERY_EXECUTION_TIME = "cqQueryExecutionTime"; /** CQ query execution in progress */ private static final String CQ_QUERY_EXECUTION_IN_PROGRESS = "cqQueryExecutionInProgress"; /** Completed CQ query executions */ private static final String CQ_QUERY_EXECUTIONS_COMPLETED = "cqQueryExecutionsCompleted"; /** Unique CQs, number of different CQ queries */ private static final String UNIQUE_CQ_QUERY = "numUniqueCqQuery"; /** Id of the CQs created statistic */ private static final int _numCqsCreatedId; /** Id of the active CQs statistic */ private static final int _numCqsActiveId; /** Id of the stopped CQs statistic */ private static final int _numCqsStoppedId; /** Id of the closed CQs statistic */ private static final int _numCqsClosedId; /** Id of the CQs on client statistic */ private static final int _numCqsOnClientId; /** Id of the Clients with Cqs statistic */ private static final int _numClientsWithCqsId; /** Id for the CQ query execution time. */ private static final int _cqQueryExecutionTimeId; /** Id for the CQ query execution in progress */ private static final int _cqQueryExecutionInProgressId; /** Id for completed CQ query executions */ private static final int _cqQueryExecutionsCompletedId; /** Id for unique CQs, difference in CQ queries */ private static final int _numUniqueCqQuery; /* * Static initializer to create and initialize the <code>StatisticsType</code> */ static { String statName = "CqServiceStats"; StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton(); _type = f.createType(statName, statName, new StatisticDescriptor[] { f.createLongCounter(CQS_CREATED, "Number of CQs created.", "operations"), f.createLongCounter(CQS_ACTIVE, "Number of CQS actively executing.", "operations"), f.createLongCounter(CQS_STOPPED, "Number of CQs stopped.", "operations"), f.createLongCounter(CQS_CLOSED, "Number of CQs closed.", "operations"), f.createLongCounter(CQS_ON_CLIENT, "Number of CQs on the client.", "operations"), f.createLongCounter(CLIENTS_WITH_CQS, "Number of Clients with CQs.", "operations"), f.createLongCounter(CQ_QUERY_EXECUTION_TIME, "Time taken for CQ Query Execution.", "nanoseconds"), f.createLongCounter(CQ_QUERY_EXECUTIONS_COMPLETED, "Number of CQ Query Executions.", "operations"), f.createIntGauge(CQ_QUERY_EXECUTION_IN_PROGRESS, "CQ Query Execution In Progress.", "operations"), f.createIntGauge(UNIQUE_CQ_QUERY, "Number of Unique CQ Querys.", "Queries"), }); // Initialize id fields _numCqsCreatedId = _type.nameToId(CQS_CREATED); _numCqsActiveId = _type.nameToId(CQS_ACTIVE); _numCqsStoppedId = _type.nameToId(CQS_STOPPED); _numCqsClosedId = _type.nameToId(CQS_CLOSED); _numCqsOnClientId = _type.nameToId(CQS_ON_CLIENT); _numClientsWithCqsId = _type.nameToId(CLIENTS_WITH_CQS); _cqQueryExecutionTimeId = _type.nameToId(CQ_QUERY_EXECUTION_TIME); _cqQueryExecutionsCompletedId = _type.nameToId(CQ_QUERY_EXECUTIONS_COMPLETED); _cqQueryExecutionInProgressId = _type.nameToId(CQ_QUERY_EXECUTION_IN_PROGRESS); _numUniqueCqQuery = _type.nameToId(UNIQUE_CQ_QUERY); } /** The <code>Statistics</code> instance to which most behavior is delegated */ private final Statistics _stats; /** * Constructor. * * @param factory The <code>StatisticsFactory</code> which creates the <code>Statistics</code> * instance */ CqServiceVsdStats(StatisticsFactory factory) { this._stats = factory.createAtomicStatistics(_type, "CqServiceStats"); } /** * Closes the <code>HARegionQueueStats</code>. */ public void close() { this._stats.close(); } /** * Returns the current value of the "numCqsCreated" stat. * * @return the current value of the "numCqsCreated" stat */ long getNumCqsCreated() { return this._stats.getLong(_numCqsCreatedId); } /** * Increments the "numCqsCreated" stat by 1. */ void incCqsCreated() { this._stats.incLong(_numCqsCreatedId, 1); } /** * Returns the current value of the "numCqsActive" stat. * * @return the current value of the "numCqsActive" stat */ long getNumCqsActive() { return this._stats.getLong(_numCqsActiveId); } /** * Increments the "numCqsActive" stat by 1. */ void incCqsActive() { this._stats.incLong(_numCqsActiveId, 1); } /** * Decrements the "numCqsActive" stat by 1. */ void decCqsActive() { this._stats.incLong(_numCqsActiveId, -1); } /** * Returns the current value of the "numCqsStopped" stat. * * @return the current value of the "numCqsStopped" stat */ long getNumCqsStopped() { return this._stats.getLong(_numCqsStoppedId); } /** * Increments the "numCqsStopped" stat by 1. */ void incCqsStopped() { this._stats.incLong(_numCqsStoppedId, 1); } /** * Decrements the "numCqsStopped" stat by 1. */ void decCqsStopped() { this._stats.incLong(_numCqsStoppedId, -1); } /** * Returns the current value of the "numCqsClosed" stat. * * @return the current value of the "numCqsClosed" stat */ long getNumCqsClosed() { return this._stats.getLong(_numCqsClosedId); } /** * Increments the "numCqsClosed" stat by 1. */ void incCqsClosed() { this._stats.incLong(_numCqsClosedId, 1); } /** * Returns the current value of the "numCqsOnClient" stat. * * @return the current value of the "numCqsOnClient" stat */ long getNumCqsOnClient() { return this._stats.getLong(_numCqsOnClientId); } /** * Increments the "numCqsOnClient" stat by 1. */ void incCqsOnClient() { this._stats.incLong(_numCqsOnClientId, 1); } /** * Decrements the "numCqsOnClient" stat by 1. */ void decCqsOnClient() { this._stats.incLong(_numCqsOnClientId, -1); } /** * Returns the current value of the "numClientsWithCqs" stat. * * @return the current value of the "numClientsWithCqs" stat */ public long getNumClientsWithCqs() { return this._stats.getLong(_numClientsWithCqsId); } /** * Increments the "numClientsWithCqs" stat by 1. */ void incClientsWithCqs() { this._stats.incLong(_numClientsWithCqsId, 1); } /** * Decrements the "numCqsOnClient" stat by 1. */ void decClientsWithCqs() { this._stats.incLong(_numClientsWithCqsId, -1); } /** * Start the CQ Query Execution time. */ long startCqQueryExecution() { this._stats.incInt(_cqQueryExecutionInProgressId, 1); return NanoTimer.getTime(); } /** * End CQ Query Execution Time. * * @param start long time value. */ void endCqQueryExecution(long start) { long ts = NanoTimer.getTime(); this._stats.incLong(_cqQueryExecutionTimeId, ts - start); this._stats.incInt(_cqQueryExecutionInProgressId, -1); this._stats.incLong(_cqQueryExecutionsCompletedId, 1); } /** * Returns the total time spent executing the CQ Queries. * * @return long time spent. */ public long getCqQueryExecutionTime() { return this._stats.getLong(_cqQueryExecutionTimeId); } /** * Increments number of Unique queries. */ void incUniqueCqQuery() { this._stats.incInt(_numUniqueCqQuery, 1); } /** * Decrements number of unique Queries. */ void decUniqueCqQuery() { this._stats.incInt(_numUniqueCqQuery, -1); } /** * This is a test method. It silently ignores exceptions and should not be used outside of unit * tests. * <p> * Returns the number of CQs (active + suspended) on the given region. */ public long numCqsOnRegion(final InternalCache cache, String regionName) { if (cache == null) { return 0; } DefaultQueryService queryService = (DefaultQueryService) cache.getQueryService(); CqService cqService = null; try { cqService = queryService.getCqService(); } catch (CqException e) { if (logger.isDebugEnabled()) { logger.debug("Failed to get CqService {}", e.getLocalizedMessage()); } e.printStackTrace(); return -1; // We're confused } if (((CqServiceImpl) cqService).isServer()) { // If we are on the server, look at the number of CQs in the filter profile. try { FilterProfile fp = cache.getFilterProfile(regionName); if (fp == null) { return 0; } return fp.getCqCount(); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to get serverside CQ count for region: {} {}", regionName, ex.getLocalizedMessage()); } } } else { try { CqQuery[] cqs = queryService.getCqs(regionName); if (cqs != null) { return cqs.length; } } catch (Exception ex) { // Dont do anything. } } return 0; } }
{ "content_hash": "2d8e2b030b55ae1ecd8f046a90626b10", "timestamp": "", "source": "github", "line_count": 367, "max_line_length": 100, "avg_line_length": 29.920980926430516, "alnum_prop": 0.6748019306074128, "repo_name": "smanvi-pivotal/geode", "id": "1688de7a664da1a808b2dd46c9d3bcde9572d617", "size": "11770", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "geode-cq/src/main/java/org/apache/geode/cache/query/internal/cq/CqServiceVsdStats.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "106707" }, { "name": "Groovy", "bytes": "2928" }, { "name": "HTML", "bytes": "3998074" }, { "name": "Java", "bytes": "26700079" }, { "name": "JavaScript", "bytes": "1781013" }, { "name": "Ruby", "bytes": "6751" }, { "name": "Shell", "bytes": "21891" } ], "symlink_target": "" }
using System.Globalization; using System.Net.Security; using System.Runtime.InteropServices; namespace System.Net { // Need a global so we can pass the interfaces as variables. internal static class GlobalSSPI { internal static SSPIInterface SSPIAuth = new SSPIAuthType(); internal static SSPIInterface SSPISecureChannel = new SSPISecureChannelType(); } // Used to define the interface for security to use. internal interface SSPIInterface { SecurityPackageInfoClass[] SecurityPackages { get; set; } int EnumerateSecurityPackages(out int pkgnum, out SafeFreeContextBuffer pkgArray); int AcquireCredentialsHandle(string moduleName, Interop.Secur32.CredentialUse usage, ref Interop.Secur32.AuthIdentity authdata, out SafeFreeCredentials outCredential); int AcquireCredentialsHandle(string moduleName, Interop.Secur32.CredentialUse usage, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential); int AcquireDefaultCredential(string moduleName, Interop.Secur32.CredentialUse usage, out SafeFreeCredentials outCredential); int AcquireCredentialsHandle(string moduleName, Interop.Secur32.CredentialUse usage, ref Interop.Secur32.SecureCredential authdata, out SafeFreeCredentials outCredential); int AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer inputBuffer, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags); int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags); int InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags); int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags); int EncryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber); int DecryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber); int MakeSignature(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber); int VerifySignature(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber); int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute attribute, out SafeFreeContextBufferChannelBinding refHandle); int QueryContextAttributes(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute attribute, byte[] buffer, Type handleType, out SafeHandle refHandle); int SetContextAttributes(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute attribute, byte[] buffer); int QuerySecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle phToken); int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers); } // For SSL connections: internal class SSPISecureChannelType : SSPIInterface { private static volatile SecurityPackageInfoClass[] s_securityPackages; public SecurityPackageInfoClass[] SecurityPackages { get { return s_securityPackages; } set { s_securityPackages = value; } } public int EnumerateSecurityPackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { GlobalLog.Print("SSPISecureChannelType::EnumerateSecurityPackages()"); return SafeFreeContextBuffer.EnumeratePackages(out pkgnum, out pkgArray); } public int AcquireCredentialsHandle(string moduleName, Interop.Secur32.CredentialUse usage, ref Interop.Secur32.AuthIdentity authdata, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } public int AcquireCredentialsHandle(string moduleName, Interop.Secur32.CredentialUse usage, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } public int AcquireDefaultCredential(string moduleName, Interop.Secur32.CredentialUse usage, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireDefaultCredential(moduleName, usage, out outCredential); } public int AcquireCredentialsHandle(string moduleName, Interop.Secur32.CredentialUse usage, ref Interop.Secur32.SecureCredential authdata, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } public int AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer inputBuffer, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, inputBuffer, null, outputBuffer, ref outFlags); } public int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags); } public int InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, inputBuffer, null, outputBuffer, ref outFlags); } public int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags); } public int EncryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { try { bool ignore = false; context.DangerousAddRef(ref ignore); return Interop.Secur32.EncryptMessage(ref context._handle, 0, inputOutput, sequenceNumber); } finally { context.DangerousRelease(); } } public unsafe int DecryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { try { bool ignore = false; context.DangerousAddRef(ref ignore); return Interop.Secur32.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, null); } finally { context.DangerousRelease(); } } public int MakeSignature(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } public int VerifySignature(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } public unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute attribute, out SafeFreeContextBufferChannelBinding refHandle) { refHandle = SafeFreeContextBufferChannelBinding.CreateEmptyHandle(); // Bindings is on the stack, so there's no need for a fixed block. Bindings bindings = new Bindings(); return SafeFreeContextBufferChannelBinding.QueryContextChannelBinding(phContext, attribute, &bindings, refHandle); } public unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute attribute, byte[] buffer, Type handleType, out SafeHandle refHandle) { refHandle = null; if (handleType != null) { if (handleType == typeof(SafeFreeContextBuffer)) { refHandle = SafeFreeContextBuffer.CreateEmptyHandle(); } else if (handleType == typeof(SafeFreeCertContext)) { refHandle = new SafeFreeCertContext(); } else { throw new ArgumentException(SR.Format(SR.SSPIInvalidHandleType, handleType.FullName), "handleType"); } } fixed (byte* bufferPtr = buffer) { return SafeFreeContextBuffer.QueryContextAttributes(phContext, attribute, bufferPtr, refHandle); } } public int SetContextAttributes(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute attribute, byte[] buffer) { return SafeFreeContextBuffer.SetContextAttributes(phContext, attribute, buffer); } public int QuerySecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle phToken) { throw new NotSupportedException(); } public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers) { throw new NotSupportedException(); } } // For Authentication (Kerberos, NTLM, Negotiate and WDigest): internal class SSPIAuthType : SSPIInterface { private static volatile SecurityPackageInfoClass[] s_securityPackages; public SecurityPackageInfoClass[] SecurityPackages { get { return s_securityPackages; } set { s_securityPackages = value; } } public int EnumerateSecurityPackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { GlobalLog.Print("SSPIAuthType::EnumerateSecurityPackages()"); return SafeFreeContextBuffer.EnumeratePackages(out pkgnum, out pkgArray); } public int AcquireCredentialsHandle(string moduleName, Interop.Secur32.CredentialUse usage, ref Interop.Secur32.AuthIdentity authdata, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } public int AcquireCredentialsHandle(string moduleName, Interop.Secur32.CredentialUse usage, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } public int AcquireDefaultCredential(string moduleName, Interop.Secur32.CredentialUse usage, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireDefaultCredential(moduleName, usage, out outCredential); } public int AcquireCredentialsHandle(string moduleName, Interop.Secur32.CredentialUse usage, ref Interop.Secur32.SecureCredential authdata, out SafeFreeCredentials outCredential) { return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, usage, ref authdata, out outCredential); } public int AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer inputBuffer, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, inputBuffer, null, outputBuffer, ref outFlags); } public int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags); } public int InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, inputBuffer, null, outputBuffer, ref outFlags); } public int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { return SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags); } public int EncryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { try { bool ignore = false; context.DangerousAddRef(ref ignore); return Interop.Secur32.EncryptMessage(ref context._handle, 0, inputOutput, sequenceNumber); } finally { context.DangerousRelease(); } } public unsafe int DecryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { int status = (int)Interop.SecurityStatus.InvalidHandle; uint qop = 0; try { bool ignore = false; context.DangerousAddRef(ref ignore); status = Interop.Secur32.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, &qop); } finally { context.DangerousRelease(); } if (status == 0 && qop == Interop.Secur32.SECQOP_WRAP_NO_ENCRYPT) { GlobalLog.Assert("Secur32.DecryptMessage", "Expected qop = 0, returned value = " + qop.ToString("x", CultureInfo.InvariantCulture)); throw new InvalidOperationException(SR.net_auth_message_not_encrypted); } return status; } public int MakeSignature(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { try { bool ignore = false; context.DangerousAddRef(ref ignore); return Interop.Secur32.EncryptMessage(ref context._handle, Interop.Secur32.SECQOP_WRAP_NO_ENCRYPT, inputOutput, sequenceNumber); } finally { context.DangerousRelease(); } } public unsafe int VerifySignature(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber) { try { bool ignore = false; uint qop = 0; context.DangerousAddRef(ref ignore); return Interop.Secur32.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, &qop); } finally { context.DangerousRelease(); } } public int QueryContextChannelBinding(SafeDeleteContext context, Interop.Secur32.ContextAttribute attribute, out SafeFreeContextBufferChannelBinding binding) { // Querying an auth SSP for a CBT doesn't make sense binding = null; throw new NotSupportedException(); } public unsafe int QueryContextAttributes(SafeDeleteContext context, Interop.Secur32.ContextAttribute attribute, byte[] buffer, Type handleType, out SafeHandle refHandle) { refHandle = null; if (handleType != null) { if (handleType == typeof(SafeFreeContextBuffer)) { refHandle = SafeFreeContextBuffer.CreateEmptyHandle(); } else if (handleType == typeof(SafeFreeCertContext)) { refHandle = new SafeFreeCertContext(); } else { throw new ArgumentException(SR.Format(SR.SSPIInvalidHandleType, handleType.FullName), "handleType"); } } fixed (byte* bufferPtr = buffer) { return SafeFreeContextBuffer.QueryContextAttributes(context, attribute, bufferPtr, refHandle); } } public int SetContextAttributes(SafeDeleteContext context, Interop.Secur32.ContextAttribute attribute, byte[] buffer) { throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } public int QuerySecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle phToken) { return GetSecurityContextToken(phContext, out phToken); } public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers) { return SafeDeleteContext.CompleteAuthToken(ref refContext, inputBuffers); } private static int GetSecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle safeHandle) { safeHandle = null; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); return Interop.Secur32.QuerySecurityContextToken(ref phContext._handle, out safeHandle); } finally { phContext.DangerousRelease(); } } } }
{ "content_hash": "3594a354f257ce65e9869bc6ca24ab7a", "timestamp": "", "source": "github", "line_count": 392, "max_line_length": 307, "avg_line_length": 51.2219387755102, "alnum_prop": 0.693162010060262, "repo_name": "matthubin/corefx", "id": "209675c6d671a9c6c4d803c6f3785ccc9b05a8d3", "size": "20231", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "src/System.Net.Security/src/System/Net/_NativeSSPI.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1568" }, { "name": "C", "bytes": "65006" }, { "name": "C#", "bytes": "92992308" }, { "name": "C++", "bytes": "81269" }, { "name": "CMake", "bytes": "5616" }, { "name": "Groovy", "bytes": "1495" }, { "name": "Shell", "bytes": "26019" }, { "name": "Smalltalk", "bytes": "1768" }, { "name": "Visual Basic", "bytes": "827616" } ], "symlink_target": "" }
import configurationVault from '@utils/configurationVault' describe('index', () => { it('should match the module', () => { expect(configurationVault).toMatchSnapshot() }) describe('defaults', () => { it('should return the default value for autoAdd', () => { expect(configurationVault.getAutoAdd()).toEqual(false) }) it('should return the default value for emojiFormat', () => { expect(configurationVault.getEmojiFormat()).toEqual('code') }) it('should return the default value for scopePrompt', () => { expect(configurationVault.getScopePrompt()).toEqual(false) }) it('should return the default value for gitmojisUrl', () => { expect(configurationVault.getGitmojisUrl()).toEqual( 'https://gitmoji.dev/api/gitmojis' ) }) }) })
{ "content_hash": "8cb37ac214b9cd2ff27340bf25b93b9b", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 65, "avg_line_length": 30.11111111111111, "alnum_prop": 0.6457564575645757, "repo_name": "carloscuesta/gitmoji-cli", "id": "78e1ed7597ce405f44b0007e3a0337c109b7448e", "size": "813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/utils/configurationVault/defaults.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "79157" }, { "name": "Shell", "bytes": "132" } ], "symlink_target": "" }
template<armnn::DataType ArmnnType, typename T> LayerTestResult<T, 2> Sqrt2dTest( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory) { const unsigned int inputShape[] = { 2, 2 }; std::vector<float> inputValues { 1.f, 4.f, 16.f, 25.f }; std::vector<float> expectedOutputValues { 1.f, 2.f, 4.f, 5.f }; return ElementwiseUnaryTestHelper<2, ArmnnType>( workloadFactory, memoryManager, armnn::UnaryOperation::Sqrt, inputShape, inputValues, inputShape, expectedOutputValues, tensorHandleFactory); } template<armnn::DataType ArmnnType, typename T> LayerTestResult<T, 3> Sqrt3dTest( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory) { const unsigned int inputShape[] = { 3, 1, 2 }; std::vector<float> inputValues { 1.f, 4.f, 16.f, 25.f, 64.f, 100.f }; std::vector<float> expectedOutputValues { 1.f, 2.f, 4.f, 5.f, 8.f, 10.f }; return ElementwiseUnaryTestHelper<3, ArmnnType>( workloadFactory, memoryManager, armnn::UnaryOperation::Sqrt, inputShape, inputValues, inputShape, expectedOutputValues, tensorHandleFactory); } template<armnn::DataType ArmnnType, typename T> LayerTestResult<T, 2> SqrtZeroTest( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory) { const unsigned int inputShape[] = { 1, 2 }; std::vector<float> inputValues { 0.f, -0.f }; std::vector<float> expectedOutputValues { 0, 0 }; return ElementwiseUnaryTestHelper<2, ArmnnType>( workloadFactory, memoryManager, armnn::UnaryOperation::Sqrt, inputShape, inputValues, inputShape, expectedOutputValues, tensorHandleFactory); } template<armnn::DataType ArmnnType, typename T> LayerTestResult<T, 2> SqrtNegativeTest( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory) { const unsigned int inputShape[] = { 1, 2 }; std::vector<float> inputValues { -25.f, -16.f }; std::vector<float> expectedOutputValues { -NAN, -NAN }; return ElementwiseUnaryTestHelper<2, ArmnnType>( workloadFactory, memoryManager, armnn::UnaryOperation::Sqrt, inputShape, inputValues, inputShape, expectedOutputValues, tensorHandleFactory); } // // Explicit template specializations // template LayerTestResult<armnn::ResolveType<armnn::DataType::Float32>, 2> Sqrt2dTest<armnn::DataType::Float32>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::Float16>, 2> Sqrt2dTest<armnn::DataType::Float16>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::QAsymmS8>, 2> Sqrt2dTest<armnn::DataType::QAsymmS8>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::QAsymmU8>, 2> Sqrt2dTest<armnn::DataType::QAsymmU8>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::QSymmS16>, 2> Sqrt2dTest<armnn::DataType::QSymmS16>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::Float32>, 3> Sqrt3dTest<armnn::DataType::Float32>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::Float16>, 3> Sqrt3dTest<armnn::DataType::Float16>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::QAsymmS8>, 3> Sqrt3dTest<armnn::DataType::QAsymmS8>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::QAsymmU8>, 3> Sqrt3dTest<armnn::DataType::QAsymmU8>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::QSymmS16>, 3> Sqrt3dTest<armnn::DataType::QSymmS16>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::Float32>, 2> SqrtZeroTest<armnn::DataType::Float32>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory); template LayerTestResult<armnn::ResolveType<armnn::DataType::Float32>, 2> SqrtNegativeTest<armnn::DataType::Float32>( armnn::IWorkloadFactory& workloadFactory, const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager, const armnn::ITensorHandleFactory& tensorHandleFactory);
{ "content_hash": "9ab6fbec0f0608e19be346da3a40f0d4", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 78, "avg_line_length": 33.97435897435897, "alnum_prop": 0.7278490566037736, "repo_name": "ARM-software/armnn", "id": "d0a6b81de928644ebcb0530eb1c8d0738ce1a5fa", "size": "6807", "binary": false, "copies": "1", "ref": "refs/heads/branches/armnn_22_08", "path": "src/backends/backendsCommon/test/layerTests/SqrtTestImpl.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "450" }, { "name": "C++", "bytes": "14537033" }, { "name": "CMake", "bytes": "227419" }, { "name": "Dockerfile", "bytes": "2687" }, { "name": "Makefile", "bytes": "44285" }, { "name": "Mako", "bytes": "1448" }, { "name": "Python", "bytes": "306177" }, { "name": "SWIG", "bytes": "163524" }, { "name": "Shell", "bytes": "51132" } ], "symlink_target": "" }
package main import ( "bytes" "github.com/golang/glog" "io/ioutil" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/kops/cmd/kops/util" "k8s.io/kops/pkg/apis/kops" "k8s.io/kops/pkg/diff" "path" "strings" "testing" "time" ) var MagicTimestamp = metav1.Time{Time: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC)} // TestCreateClusterMinimal runs kops create cluster minimal.example.com --zones us-test-1a func TestCreateClusterMinimal(t *testing.T) { runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/minimal", "v1alpha1") runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/minimal", "v1alpha2") } // TestCreateClusterHA runs kops create cluster ha.example.com --zones us-test-1a,us-test-1b,us-test-1c --master-zones us-test-1a,us-test-1b,us-test-1c func TestCreateClusterHA(t *testing.T) { runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/ha", "v1alpha1") runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/ha", "v1alpha2") runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/ha_encrypt", "v1alpha1") runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/ha_encrypt", "v1alpha2") } // TestCreateClusterHASharedZones tests kops create cluster when the master count is bigger than the numebr of zones func TestCreateClusterHASharedZones(t *testing.T) { // Cannot be expressed in v1alpha1 API: runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/ha_shared_zones", "v1alpha1") runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/ha_shared_zones", "v1alpha2") } // TestCreateClusterPrivate runs kops create cluster private.example.com --zones us-test-1a --master-zones us-test-1a func TestCreateClusterPrivate(t *testing.T) { runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/private", "v1alpha1") runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/private", "v1alpha2") } // TestCreateClusterWithNGWSpecified runs kops create cluster private.example.com --zones us-test-1a --master-zones us-test-1a func TestCreateClusterWithNGWSpecified(t *testing.T) { runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/ngwspecified", "v1alpha1") runCreateClusterIntegrationTest(t, "../../tests/integration/create_cluster/ngwspecified", "v1alpha2") } func runCreateClusterIntegrationTest(t *testing.T, srcDir string, version string) { var stdout bytes.Buffer optionsYAML := "options.yaml" expectedClusterPath := "expected-" + version + ".yaml" factoryOptions := &util.FactoryOptions{} factoryOptions.RegistryPath = "memfs://tests" h := NewIntegrationTestHarness(t) defer h.Close() h.SetupMockAWS() publicKeyPath := path.Join(h.TempDir, "id_rsa.pub") privateKeyPath := path.Join(h.TempDir, "id_rsa") { if err := MakeSSHKeyPair(publicKeyPath, privateKeyPath); err != nil { t.Fatalf("error making SSH keypair: %v", err) } } factory := util.NewFactory(factoryOptions) { optionsBytes, err := ioutil.ReadFile(path.Join(srcDir, optionsYAML)) if err != nil { t.Fatalf("error reading options file: %v", err) } options := &CreateClusterOptions{} options.InitDefaults() err = kops.ParseRawYaml(optionsBytes, options) if err != nil { t.Fatalf("error parsing options: %v", err) } // No preview options.Target = "" // Use the public key we produced options.SSHPublicKey = publicKeyPath err = RunCreateCluster(factory, &stdout, options) if err != nil { t.Fatalf("error running create cluster: %v", err) } } clientset, err := factory.Clientset() if err != nil { t.Fatalf("error getting clientset: %v", err) } // Compare cluster clusters, err := clientset.Clusters().List(metav1.ListOptions{}) if err != nil { t.Fatalf("error listing clusters: %v", err) } if len(clusters.Items) != 1 { t.Fatalf("expected one cluster, found %d", len(clusters.Items)) } var yamlAll []string for _, cluster := range clusters.Items { cluster.ObjectMeta.CreationTimestamp = MagicTimestamp actualYAMLBytes, err := kops.ToVersionedYamlWithVersion(&cluster, version) if err != nil { t.Fatalf("unexpected error serializing cluster: %v", err) } actualYAML := strings.TrimSpace(string(actualYAMLBytes)) yamlAll = append(yamlAll, actualYAML) } // Compare instance groups instanceGroups, err := clientset.InstanceGroups(clusters.Items[0].ObjectMeta.Name).List(metav1.ListOptions{}) if err != nil { t.Fatalf("error listing instance groups: %v", err) } for _, ig := range instanceGroups.Items { ig.ObjectMeta.CreationTimestamp = MagicTimestamp actualYAMLBytes, err := kops.ToVersionedYamlWithVersion(&ig, version) if err != nil { t.Fatalf("unexpected error serializing InstanceGroup: %v", err) } actualYAML := strings.TrimSpace(string(actualYAMLBytes)) yamlAll = append(yamlAll, actualYAML) } expectedYAMLBytes, err := ioutil.ReadFile(path.Join(srcDir, expectedClusterPath)) if err != nil { t.Fatalf("unexpected error reading expected YAML: %v", err) } expectedYAML := strings.TrimSpace(string(expectedYAMLBytes)) actualYAML := strings.Join(yamlAll, "\n\n---\n\n") if actualYAML != expectedYAML { glog.Infof("Actual YAML:\n%s\n", actualYAML) diffString := diff.FormatDiff(expectedYAML, actualYAML) t.Logf("diff:\n%s\n", diffString) t.Fatalf("YAML differed from expected") } }
{ "content_hash": "6b00bc56737229e6d0438575497c3673", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 151, "avg_line_length": 32.54761904761905, "alnum_prop": 0.7302487198244331, "repo_name": "leandrocr/kops", "id": "2df1dc081e87c4743c3c928cedc5f8b8e638a2fc", "size": "6037", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "cmd/kops/create_cluster_integration_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2481615" }, { "name": "HCL", "bytes": "211932" }, { "name": "Makefile", "bytes": "17354" }, { "name": "Python", "bytes": "15199" }, { "name": "Ruby", "bytes": "1027" }, { "name": "Shell", "bytes": "20870" } ], "symlink_target": "" }
<?php class HTMLPurifier_ChildDef_CustomTest extends HTMLPurifier_ChildDefHarness { public function setUp() { parent::setUp(); } public function test() { $this->obj = new HTMLPurifier_ChildDef_Custom('(a,b?,c*,d+,(a,b)*)'); $this->assertEqual($this->obj->elements, array( 'a' => true, 'b' => true, 'c' => true, 'd' => true )); $this->assertResult('', false); $this->assertResult('<a /><a />', false); $this->assertResult('<a /><b /><c /><d /><a /><b />'); $this->assertResult('<a /><d>Dob</d><a /><b>foo</b>' . '<a href="moo" /><b>foo</b>'); } public function testNesting() { $this->obj = new HTMLPurifier_ChildDef_Custom('(a,b,(c|d))+'); $this->assertEqual($this->obj->elements, array( 'a' => true, 'b' => true, 'c' => true, 'd' => true )); $this->assertResult('', false); $this->assertResult('<a /><b /><c /><a /><b /><d />'); $this->assertResult('<a /><b /><c /><d />', false); } public function testNestedEitherOr() { $this->obj = new HTMLPurifier_ChildDef_Custom('b,(a|(c|d))+'); $this->assertEqual($this->obj->elements, array( 'a' => true, 'b' => true, 'c' => true, 'd' => true )); $this->assertResult('', false); $this->assertResult('<b /><a /><c /><d />'); $this->assertResult('<b /><d /><a /><a />'); $this->assertResult('<b /><a />'); $this->assertResult('<acd />', false); } public function testNestedQuantifier() { $this->obj = new HTMLPurifier_ChildDef_Custom('(b,c+)*'); $this->assertEqual($this->obj->elements, array('b' => true, 'c' => true)); $this->assertResult(''); $this->assertResult('<b /><c />'); $this->assertResult('<b /><c /><c /><c />'); $this->assertResult('<b /><c /><b /><c />'); $this->assertResult('<b /><c /><b />', false); } public function testEitherOr() { $this->obj = new HTMLPurifier_ChildDef_Custom('a|b'); $this->assertEqual($this->obj->elements, array('a' => true, 'b' => true)); $this->assertResult('', false); $this->assertResult('<a />'); $this->assertResult('<b />'); $this->assertResult('<a /><b />', false); } public function testCommafication() { $this->obj = new HTMLPurifier_ChildDef_Custom('a,b'); $this->assertEqual($this->obj->elements, array('a' => true, 'b' => true)); $this->assertResult('<a /><b />'); $this->assertResult('<ab />', false); } public function testPcdata() { $this->obj = new HTMLPurifier_ChildDef_Custom('#PCDATA,a'); $this->assertEqual($this->obj->elements, array('#PCDATA' => true, 'a' => true)); $this->assertResult('foo<a />'); $this->assertResult('<a />', false); } public function testWhitespace() { $this->obj = new HTMLPurifier_ChildDef_Custom('a'); $this->assertEqual($this->obj->elements, array('a' => true)); $this->assertResult('foo<a />', false); $this->assertResult('<a />'); $this->assertResult(' <a />'); } } // vim: et sw=4 sts=4
{ "content_hash": "48868309501df3938beb062c2f79a1aa", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 88, "avg_line_length": 30.513513513513512, "alnum_prop": 0.4824328314142309, "repo_name": "fayvlad/learn_yii2", "id": "d0cc87bbab05ed0df90a4fde4040bca958995322", "size": "3387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/ezyang/htmlpurifier/tests/HTMLPurifier/ChildDef/CustomTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "218" }, { "name": "CSS", "bytes": "1364" }, { "name": "PHP", "bytes": "47301" }, { "name": "Shell", "bytes": "1030" } ], "symlink_target": "" }
#pragma once #include <cstdint> #include <list> #include <memory> #include "envoy/network/connection_handler.h" #include "envoy/network/filter.h" #include "envoy/network/listen_socket.h" #include "envoy/network/listener.h" #include "source/common/network/utility.h" #include "source/server/active_listener_base.h" namespace Envoy { namespace Server { #define ALL_UDP_LISTENER_STATS(COUNTER) COUNTER(downstream_rx_datagram_dropped) /** * Wrapper struct for UDP listener stats. @see stats_macros.h */ struct UdpListenerStats { ALL_UDP_LISTENER_STATS(GENERATE_COUNTER_STRUCT) }; class ActiveUdpListenerBase : public ActiveListenerImplBase, public Network::ConnectionHandler::ActiveUdpListener { public: ActiveUdpListenerBase(uint32_t worker_index, uint32_t concurrency, Network::UdpConnectionHandler& parent, Network::Socket& listen_socket, Network::UdpListenerPtr&& listener, Network::ListenerConfig* config); ~ActiveUdpListenerBase() override; // Network::UdpListenerCallbacks void onData(Network::UdpRecvData&& data) final; uint32_t workerIndex() const final { return worker_index_; } void post(Network::UdpRecvData&& data) final; void onDatagramsDropped(uint32_t dropped) final { udp_stats_.downstream_rx_datagram_dropped_.add(dropped); } // ActiveListenerImplBase Network::Listener* listener() override { return udp_listener_.get(); } protected: uint32_t destination(const Network::UdpRecvData& /*data*/) const override { // By default, route to the current worker. return worker_index_; } const uint32_t worker_index_; const uint32_t concurrency_; Network::UdpConnectionHandler& parent_; Network::Socket& listen_socket_; Network::UdpListenerPtr udp_listener_; UdpListenerStats udp_stats_; }; /** * Wrapper for an active udp listener owned by this handler. */ class ActiveRawUdpListener : public ActiveUdpListenerBase, public Network::UdpListenerFilterManager, public Network::UdpReadFilterCallbacks, Logger::Loggable<Logger::Id::conn_handler> { public: ActiveRawUdpListener(uint32_t worker_index, uint32_t concurrency, Network::UdpConnectionHandler& parent, Event::Dispatcher& dispatcher, Network::ListenerConfig& config); ActiveRawUdpListener(uint32_t worker_index, uint32_t concurrency, Network::UdpConnectionHandler& parent, Network::SocketSharedPtr listen_socket_ptr, Event::Dispatcher& dispatcher, Network::ListenerConfig& config); ActiveRawUdpListener(uint32_t worker_index, uint32_t concurrency, Network::UdpConnectionHandler& parent, Network::Socket& listen_socket, Network::SocketSharedPtr listen_socket_ptr, Event::Dispatcher& dispatcher, Network::ListenerConfig& config); ActiveRawUdpListener(uint32_t worker_index, uint32_t concurrency, Network::UdpConnectionHandler& parent, Network::Socket& listen_socket, Network::UdpListenerPtr&& listener, Network::ListenerConfig& config); // Network::UdpListenerCallbacks void onReadReady() override; void onWriteReady(const Network::Socket& socket) override; void onReceiveError(Api::IoError::IoErrorCode error_code) override; Network::UdpPacketWriter& udpPacketWriter() override { return *udp_packet_writer_; } size_t numPacketsExpectedPerEventLoop() const final { // TODO(mattklein123) change this to a reasonable number if needed. return Network::MAX_NUM_PACKETS_PER_EVENT_LOOP; } // Network::UdpWorker void onDataWorker(Network::UdpRecvData&& data) override; // ActiveListenerImplBase void pauseListening() override { udp_listener_->disable(); } void resumeListening() override { udp_listener_->enable(); } void shutdownListener() override { // The read filter should be deleted before the UDP listener is deleted. // The read filter refers to the UDP listener to send packets to downstream. // If the UDP listener is deleted before the read filter, the read filter may try to use it // after deletion. read_filters_.clear(); udp_listener_.reset(); } // These two are unreachable because a config will be rejected if it configures both this listener // and any L4 filter chain. void updateListenerConfig(Network::ListenerConfig&) override { NOT_REACHED_GCOVR_EXCL_LINE; } void onFilterChainDraining(const std::list<const Network::FilterChain*>&) override { NOT_REACHED_GCOVR_EXCL_LINE; } // Network::UdpListenerFilterManager void addReadFilter(Network::UdpListenerReadFilterPtr&& filter) override; // Network::UdpReadFilterCallbacks Network::UdpListener& udpListener() override; private: std::list<Network::UdpListenerReadFilterPtr> read_filters_; Network::UdpPacketWriterPtr udp_packet_writer_; }; } // namespace Server } // namespace Envoy
{ "content_hash": "05e4f4ea65232c4b9f7c2fdb686cb3ec", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 100, "avg_line_length": 40.182539682539684, "alnum_prop": 0.7057080782144973, "repo_name": "lyft/envoy", "id": "e3dd74bfb95f9f7da9e1b14fc96ac5e7e828827a", "size": "5063", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "source/server/active_udp_listener.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "439" }, { "name": "C", "bytes": "9840" }, { "name": "C++", "bytes": "30180292" }, { "name": "Dockerfile", "bytes": "891" }, { "name": "Emacs Lisp", "bytes": "966" }, { "name": "Go", "bytes": "558" }, { "name": "Jinja", "bytes": "46306" }, { "name": "Makefile", "bytes": "303" }, { "name": "PureBasic", "bytes": "472" }, { "name": "Python", "bytes": "659418" }, { "name": "Rust", "bytes": "38417" }, { "name": "Shell", "bytes": "177423" }, { "name": "Starlark", "bytes": "1743784" }, { "name": "Thrift", "bytes": "748" } ], "symlink_target": "" }
package org.apache.druid.segment.data; import org.apache.druid.common.utils.ByteUtils; import org.apache.druid.java.util.common.io.smoosh.FileSmoosher; import org.apache.druid.segment.IndexIO; import org.apache.druid.segment.serde.MetaSerdeHelper; import org.apache.druid.segment.writeout.SegmentWriteOutMedium; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.WritableByteChannel; /** * Streams array of integers out in the binary format described by {@link CompressedVSizeColumnarIntsSupplier} */ public class CompressedVSizeColumnarIntsSerializer extends SingleValueColumnarIntsSerializer { private static final byte VERSION = CompressedVSizeColumnarIntsSupplier.VERSION; private static final MetaSerdeHelper<CompressedVSizeColumnarIntsSerializer> metaSerdeHelper = MetaSerdeHelper .firstWriteByte((CompressedVSizeColumnarIntsSerializer x) -> VERSION) .writeByte(x -> ByteUtils.checkedCast(x.numBytes)) .writeInt(x -> x.numInserted) .writeInt(x -> x.chunkFactor) .writeByte(x -> x.compression.getId()); public static CompressedVSizeColumnarIntsSerializer create( final SegmentWriteOutMedium segmentWriteOutMedium, final String filenameBase, final int maxValue, final CompressionStrategy compression ) { return new CompressedVSizeColumnarIntsSerializer( segmentWriteOutMedium, filenameBase, maxValue, CompressedVSizeColumnarIntsSupplier.maxIntsInBufferForValue(maxValue), IndexIO.BYTE_ORDER, compression ); } private final int numBytes; private final int chunkFactor; private final boolean isBigEndian; private final CompressionStrategy compression; private final GenericIndexedWriter<ByteBuffer> flattener; private final ByteBuffer intBuffer; private ByteBuffer endBuffer; private int numInserted; CompressedVSizeColumnarIntsSerializer( final SegmentWriteOutMedium segmentWriteOutMedium, final String filenameBase, final int maxValue, final int chunkFactor, final ByteOrder byteOrder, final CompressionStrategy compression ) { this( segmentWriteOutMedium, maxValue, chunkFactor, byteOrder, compression, GenericIndexedWriter.ofCompressedByteBuffers( segmentWriteOutMedium, filenameBase, compression, sizePer(maxValue, chunkFactor) ) ); } CompressedVSizeColumnarIntsSerializer( final SegmentWriteOutMedium segmentWriteOutMedium, final int maxValue, final int chunkFactor, final ByteOrder byteOrder, final CompressionStrategy compression, final GenericIndexedWriter<ByteBuffer> flattener ) { this.numBytes = VSizeColumnarInts.getNumBytesForMax(maxValue); this.chunkFactor = chunkFactor; int chunkBytes = chunkFactor * numBytes; this.isBigEndian = byteOrder.equals(ByteOrder.BIG_ENDIAN); this.compression = compression; this.flattener = flattener; this.intBuffer = ByteBuffer.allocate(Integer.BYTES).order(byteOrder); CompressionStrategy.Compressor compressor = compression.getCompressor(); this.endBuffer = compressor.allocateInBuffer(chunkBytes, segmentWriteOutMedium.getCloser()).order(byteOrder); this.numInserted = 0; } private static int sizePer(int maxValue, int chunkFactor) { return chunkFactor * VSizeColumnarInts.getNumBytesForMax(maxValue) + CompressedVSizeColumnarIntsSupplier.bufferPadding(VSizeColumnarInts.getNumBytesForMax(maxValue)); } @Override public void open() throws IOException { flattener.open(); } @Override public void addValue(int val) throws IOException { if (endBuffer == null) { throw new IllegalStateException("written out already"); } if (!endBuffer.hasRemaining()) { endBuffer.rewind(); flattener.write(endBuffer); endBuffer.clear(); } intBuffer.putInt(0, val); if (isBigEndian) { endBuffer.put(intBuffer.array(), Integer.BYTES - numBytes, numBytes); } else { endBuffer.put(intBuffer.array(), 0, numBytes); } numInserted++; } @Override public long getSerializedSize() throws IOException { writeEndBuffer(); return metaSerdeHelper.size(this) + flattener.getSerializedSize(); } @Override public void writeTo(WritableByteChannel channel, FileSmoosher smoosher) throws IOException { writeEndBuffer(); metaSerdeHelper.writeTo(channel, this); flattener.writeTo(channel, smoosher); } private void writeEndBuffer() throws IOException { if (endBuffer != null) { endBuffer.flip(); if (endBuffer.remaining() > 0) { flattener.write(endBuffer); } endBuffer = null; } } }
{ "content_hash": "c1a6fae5236e4e229c80a29317697b1c", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 113, "avg_line_length": 30.452830188679247, "alnum_prop": 0.7257331681123502, "repo_name": "dkhwangbo/druid", "id": "ffc1ee84a6cdabcb15ff25141e551af4a81cdfb7", "size": "5649", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "processing/src/main/java/org/apache/druid/segment/data/CompressedVSizeColumnarIntsSerializer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "3345" }, { "name": "CSS", "bytes": "15658" }, { "name": "Dockerfile", "bytes": "4856" }, { "name": "HTML", "bytes": "19754" }, { "name": "Java", "bytes": "21183046" }, { "name": "JavaScript", "bytes": "304058" }, { "name": "Makefile", "bytes": "659" }, { "name": "PostScript", "bytes": "5" }, { "name": "R", "bytes": "17002" }, { "name": "Roff", "bytes": "3617" }, { "name": "Shell", "bytes": "28297" }, { "name": "TeX", "bytes": "399508" }, { "name": "Thrift", "bytes": "207" } ], "symlink_target": "" }
FileAdaptor.loadTiddlyWikiCallback = function(status,context,responseText,url,xhr) { context.status = status; if(!status) { context.statusText = "Error reading file"; } else { //# Load the content into a TiddlyWiki() object context.adaptor.store = new TiddlyWiki(); if(!context.adaptor.store.importTiddlyWiki(responseText)) { context.statusText = config.messages.invalidFileError.format([url]); context.status = false; } } context.complete(context,context.userParams); };
{ "content_hash": "f459a70f080b96db7492e3fbfd0dc521", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 82, "avg_line_length": 30.875, "alnum_prop": 0.7388663967611336, "repo_name": "TeravoxelTwoPhotonTomography/nd", "id": "30ee96b2c98f614c9a4abc24c8c8a461d2b1b045", "size": "543", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/node_modules/tiddlywiki/editions/tw2/source/tiddlywiki/deprecated/FileAdaptor.js", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "228427" }, { "name": "C++", "bytes": "19062" }, { "name": "CMake", "bytes": "21256" }, { "name": "Cuda", "bytes": "40093" } ], "symlink_target": "" }
/** This script makes the Hall of Fame for the elapsed month. * It should be run every 1st day of the month, in the working tree, and * then a commit with the changes should be pushed to scala-lang. */ import java.net.URL import scala.annotation.switch import scala.io.Source import scala.util.parsing.json._ object MakeHallOfFame { object Category extends Enumeration { val Typesafe, EPFL, Community = Value } type Category = Category.Value // TODO Expand (and maintain) that list - or fetch it from some source val TypesafePeople = Set( "adriaanm", "dragos", "gkossakowski", "JamesIry", "jsuereth", "paulp", "phaller", "retronym", "huitseeker", "jboner", "viktorklang", "patriknw", "rkuhn", "bantonsson", "pvlugter", "henrikengstrom", "szeiger" ) // TODO Expand (and maintain) that list - or fetch it from some source val EPFLPeople = Set( "axel22", "heathermiller", "hubertp", "lrytz", "magarciaEPFL", "namin", "odersky", "TiarkRompf", "VladUreche", "xeno-by", "namin", "cvogt", "manojo", "vjovanov", "sjrd", "sstucki" ) class Author(val username: String, val gravatar: String) { val category: Category = if (TypesafePeople(username)) Category.Typesafe else if (EPFLPeople(username)) Category.EPFL else Category.Community var commits: Int = 0 var linesAdded: Int = 0 var linesDeleted: Int = 0 var isNewContributor: Boolean = false } var thisYear: Int = 0 var thisMonth: Int = 0 var thisMonthStr: String = "" def isWeekOfThisMonth(week: String): Boolean = week startsWith thisMonthStr def main(args: Array[String]) { val (year, month) = { if (args.size >= 2) (args(0).toInt, args(1).toInt) else getYearAndMonth() } thisYear = year thisMonth = month thisMonthStr = "%04d-%02d" format (year, month) progress(s"Building data for $thisMonthStr") val sourceDataString = loadSourceDataString() val sourceData = parseSourceData(sourceDataString) val authors = buildDataFromJSON(sourceData) progress("Sorting by category") val byCategory = authors.groupBy(_.category) val sorted = byCategory.mapValues(_.sortBy(-_.commits)) val output = buildOutput(sorted) writeOutputToFile(output) } def progress(msg: String) { Console.err.println(msg) } def getYearAndMonth(): (Int, Int) = { import java.util.Calendar._ val cal = new java.util.GregorianCalendar cal.set(DAY_OF_MONTH, 0) // this will wrap to the Month (and Year if necessary) (cal.get(YEAR), cal.get(MONTH)+1) } def timestampToDateStr(timestamp: Long): String = { import java.util.Calendar._ val date = new java.util.Date(timestamp) val cal = new java.util.GregorianCalendar() cal.setTime(date) "%04d-%02d-%02d" format (cal.get(YEAR), cal.get(MONTH)+1, cal.get(DAY_OF_MONTH)) } def loadSourceDataString(): String = { progress("Downloading source data") val source = Source.fromURL(new URL( "https://github.com/scala/scala/graphs/contributors-data")) try source.mkString finally source.close() } def parseSourceData(str: String): Any = { progress("Parsing JSON in source data") JSON.parseFull(str) getOrElse { throw new Exception("Parse error") } } def buildDataFromJSON(jsonAuthors: Any): List[Author] = { progress("Building my data") val L(authors) = jsonAuthors val all = for { M(author0) <- authors M(authorData) = author0("author") S(username) = authorData("login") S(gravatar) = authorData("avatar") I(totalCommits) = author0("total") L(jsonWeeks) = author0("weeks") } yield { val author = new Author(username, gravatar) for { M(week) <- jsonWeeks D(dateTimestamp) = week("w") date = timestampToDateStr(dateTimestamp.toLong * 1000) if isWeekOfThisMonth(date) I(commits) = week("c") I(added) = week("a") I(deleted) = week("d") } yield { author.commits += commits author.linesAdded += added author.linesDeleted += deleted } author.isNewContributor = author.commits == totalCommits author } all filter (_.commits != 0) } def buildOutput(authorsByCategory: Map[Category, List[Author]]) = { progress("Outputting") val result = new scala.collection.mutable.ListBuffer[String] def outln(line: String) = result += line val thisMonthText = getMonthName(thisMonth) outln("---") outln("layout: famearchive") outln("title: Contributors of " + thisMonthText + " " + thisYear) outln("fame-year: " + thisYear) outln("fame-month: " + thisMonth) outln("fame-month-str: " + thisMonthText) outln("fame-categories:") for { category <- Seq(Category.Typesafe, Category.EPFL, Category.Community) } { outln(" - category: " + category.toString()) outln(" authors:") var rank = 0 var rankCommits = -1 for (author <- authorsByCategory.getOrElse(category, Nil)) { if (author.commits != rankCommits) { rank += 1 rankCommits = author.commits } outln(" - username: " + author.username) outln(" gravatar: " + author.gravatar) outln(" commits: " + author.commits) outln(" linesAdded: " + author.linesAdded) outln(" linesDeleted: " + author.linesDeleted) outln(" rank: " + rank) outln(" newContributor: " + author.isNewContributor) } } outln("---") result.toList } def writeOutputToFile(output: List[String]) { val (postYear, postMonth) = { import java.util.Calendar._ val cal = new java.util.GregorianCalendar(thisYear, thisMonth-1, 1) cal.add(MONTH, 1) (cal.get(YEAR), cal.get(MONTH)+1) } val postDateStr = "%04d-%02d-01" format (postYear, postMonth) val fileName = s"../../contribute/scala-fame-data/_posts/${postDateStr}-scala-fame-${thisMonthStr}.md" progress("Writing output to " + fileName) val writer = new java.io.PrintWriter(fileName) try output foreach writer.println finally writer.close() } def getMonthName(month: Int): String = (month: @switch) match { case 1 => "January" case 2 => "February" case 3 => "March" case 4 => "April" case 5 => "May" case 6 => "June" case 7 => "July" case 8 => "August" case 9 => "September" case 10 => "October" case 11 => "November" case 12 => "December" } // JSON extractors class CC[T] { def unapply(a: Any): Option[T] = Some(a.asInstanceOf[T]) } object M extends CC[Map[String, Any]] object L extends CC[List[Any]] object S extends CC[String] object D extends CC[Double] object B extends CC[Boolean] object I { def unapply(a: Any): Option[Int] = Some(a.asInstanceOf[Double].toInt) } }
{ "content_hash": "1c8d6d2cb8c3f0e5fc2f5e84b683c2a8", "timestamp": "", "source": "github", "line_count": 261, "max_line_length": 106, "avg_line_length": 27.21455938697318, "alnum_prop": 0.616640855976348, "repo_name": "boldradius/scala-lang", "id": "8a875c6233679b71f4f01efe17b2b97ae5eb17d4", "size": "7103", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "_tools/hall-of-fame/MakeHallOfFame.scala", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "61756" }, { "name": "HTML", "bytes": "55677" }, { "name": "JavaScript", "bytes": "18125" }, { "name": "PHP", "bytes": "289" }, { "name": "Ruby", "bytes": "1087" }, { "name": "Scala", "bytes": "7103" } ], "symlink_target": "" }
package com.linecorp.armeria.client.circuitbreaker; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; class EventCountTest { @Test void testCounts() { assertThat(EventCount.of(0, 0).success()).isEqualTo(0L); assertThat(EventCount.of(1, 0).success()).isEqualTo(1L); assertThat(EventCount.of(1, 1).success()).isEqualTo(1L); assertThat(EventCount.of(0, 0).failure()).isEqualTo(0L); assertThat(EventCount.of(0, 1).failure()).isEqualTo(1L); assertThat(EventCount.of(1, 1).failure()).isEqualTo(1L); assertThat(EventCount.of(0, 0).total()).isEqualTo(0L); assertThat(EventCount.of(1, 1).total()).isEqualTo(2L); } @Test void testRates() { assertThatThrownBy(() -> EventCount.of(0, 0).successRate()).isInstanceOf(ArithmeticException.class); assertThat(EventCount.of(1, 0).successRate()).isEqualTo(1.0); assertThat(EventCount.of(1, 1).successRate()).isEqualTo(0.5); assertThatThrownBy(() -> EventCount.of(0, 0).failureRate()).isInstanceOf(ArithmeticException.class); assertThat(EventCount.of(0, 1).failureRate()).isEqualTo(1.0); assertThat(EventCount.of(1, 1).failureRate()).isEqualTo(0.5); } @Test void testInvalidArguments() { assertThatThrownBy(() -> EventCount.of(-1, 0)).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> EventCount.of(0, -1)).isInstanceOf(IllegalArgumentException.class); } @Test void testEquals() { final EventCount ec = EventCount.of(1, 1); assertThat(ec).isEqualTo(ec); assertThat(EventCount.of(0, 0)).isEqualTo(EventCount.of(0, 0)); assertThat(EventCount.of(1, 0)).isNotEqualTo(EventCount.of(0, 0)); assertThat(EventCount.of(1, 0)).isNotEqualTo(new Object()); } }
{ "content_hash": "c4da8d51810584dcd824ffa09494fcd0", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 108, "avg_line_length": 37.98039215686274, "alnum_prop": 0.6685596282911719, "repo_name": "kojilin/armeria", "id": "c0d178f93378a6631c3b63613f8aab3714a980aa", "size": "2570", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "core/src/test/java/com/linecorp/armeria/client/circuitbreaker/EventCountTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7197" }, { "name": "HTML", "bytes": "1222" }, { "name": "Java", "bytes": "17111554" }, { "name": "JavaScript", "bytes": "26583" }, { "name": "Kotlin", "bytes": "95340" }, { "name": "Less", "bytes": "35092" }, { "name": "Scala", "bytes": "230968" }, { "name": "Shell", "bytes": "2062" }, { "name": "Thrift", "bytes": "252456" }, { "name": "TypeScript", "bytes": "255034" } ], "symlink_target": "" }
@implementation FLCommand (Floc) - (FLCFInterceptionCommandBlock)intercept { return ^FLInterceptionCommand *(FLCommand *success, FLCommand *error) { return [[FLInterceptionCommand alloc] initWithTarget:self success:success error:error]; }; } - (FLCFMasterSlaveCommandBlock)slave { return ^FLMasterSlaveCommand *(FLCommand *slave) { return [[FLMasterSlaveCommand alloc] initWithMaster:self slave:slave]; }; } - (FLCFParallelCommandBlock)parallel { return ^FLSequenceCommand *(FLCommand *firstCommand, ...) { va_list args; va_start(args, firstCommand); NSMutableArray *commands = [[NSMutableArray alloc] init]; for (FLCommand *command = firstCommand; command != nil; command = va_arg(args, FLCommand *)) [commands addObject:command]; va_end(args); return [[FLSequenceCommand alloc] initWithCommands:@[self, [[FLParallelCommand alloc] initWithCommands:commands]]]; }; } - (FLCFRepeatBlock)repeat { return ^FLRepeatCommand *(NSInteger repeat) { return [[FLRepeatCommand alloc] initWithCommand:self repeat:repeat]; }; } - (FLCFRetryBlock)retry { return ^FLRetryCommand *(NSInteger retry) { return [[FLRetryCommand alloc] initWithCommand:self retry:retry]; }; } - (FLCFSequenceCommandBlock)sequence { return ^FLSequenceCommand *(FLCommand *firstCommand, ...) { va_list args; va_start(args, firstCommand); NSMutableArray *commands = [[NSMutableArray alloc] init]; for (FLCommand *command = firstCommand; command != nil; command = va_arg(args, FLCommand *)) [commands addObject:command]; va_end(args); return [[FLSequenceCommand alloc] initWithCommands:@[self, [[FLSequenceCommand alloc] initWithCommands:commands]]]; }; } @end
{ "content_hash": "a222f6121828f55845fd82a0d8259002", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 100, "avg_line_length": 35.075471698113205, "alnum_prop": 0.6691769768692846, "repo_name": "sschmid/Floc-Commands", "id": "e0c1d93b63a2daac0dae91c1f62152344f7bcf3e", "size": "2129", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Floc-Commands/Classes/Additions/FLCommand+Floc.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "178783" }, { "name": "Ruby", "bytes": "697" } ], "symlink_target": "" }
import os import sys import argparse import logging logger = logging.getLogger() from counterpartylib.lib import log log.set_logger(logger) from counterpartylib import server from counterpartylib.lib import config from counterpartycli.util import add_config_arguments, bootstrap from counterpartycli.setup import generate_config_files from counterpartycli import APP_VERSION APP_NAME = 'counterparty-server' CONFIG_ARGS = [ [('-v', '--verbose'), {'dest': 'verbose', 'action': 'store_true', 'default': False, 'help': 'sets log level to DEBUG instead of WARNING'}], [('--testnet',), {'action': 'store_true', 'default': False, 'help': 'use {} testnet addresses and block numbers'.format(config.BTC_NAME)}], [('--testcoin',), {'action': 'store_true', 'default': False, 'help': 'use the test {} network on every blockchain'.format(config.XCP_NAME)}], [('--regtest',), {'action': 'store_true', 'default': False, 'help': 'use {} regtest addresses and block numbers'.format(config.BTC_NAME)}], [('--customnet',), {'default': '', 'help': 'use a custom network (specify as UNSPENDABLE_ADDRESS|ADDRESSVERSION|P2SH_ADDRESSVERSION with version bytes in HH hex format)'}], [('--api-limit-rows',), {'type': int, 'default': 1000, 'help': 'limit api calls to the set results (defaults to 1000). Setting to 0 removes the limit.'}], [('--backend-name',), {'default': 'addrindex', 'help': 'the backend name to connect to'}], [('--backend-connect',), {'default': 'localhost', 'help': 'the hostname or IP of the backend server'}], [('--backend-port',), {'type': int, 'help': 'the backend port to connect to'}], [('--backend-user',), {'default': 'bitcoinrpc', 'help': 'the username used to communicate with backend'}], [('--backend-password',), {'help': 'the password used to communicate with backend'}], [('--backend-ssl',), {'action': 'store_true', 'default': False, 'help': 'use SSL to connect to backend (default: false)'}], [('--backend-ssl-no-verify',), {'action': 'store_true', 'default': False, 'help': 'verify SSL certificate of backend; disallow use of self‐signed certificates (default: true)'}], [('--backend-poll-interval',), {'type': float, 'default': 0.5, 'help': 'poll interval, in seconds (default: 0.5)'}], [('--no-check-asset-conservation',), {'action': 'store_true', 'default': False, 'help': 'Skip asset conservation checking (default: false)'}], [('--p2sh-dust-return-pubkey',), {'help': 'pubkey to receive dust when multisig encoding is used for P2SH source (default: none)'}], [('--indexd-connect',), {'default': 'localhost', 'help': 'the hostname or IP of the indexd server'}], [('--indexd-port',), {'type': int, 'help': 'the indexd server port to connect to'}], [('--rpc-host',), {'default': 'localhost', 'help': 'the IP of the interface to bind to for providing JSON-RPC API access (0.0.0.0 for all interfaces)'}], [('--rpc-port',), {'type': int, 'help': 'port on which to provide the {} JSON-RPC API'.format(config.APP_NAME)}], [('--rpc-user',), {'default': 'rpc', 'help': 'required username to use the {} JSON-RPC API (via HTTP basic auth)'.format(config.APP_NAME)}], [('--rpc-password',), {'help': 'required password (for rpc-user) to use the {} JSON-RPC API (via HTTP basic auth)'.format(config.APP_NAME)}], [('--rpc-no-allow-cors',), {'action': 'store_true', 'default': False, 'help': 'allow ajax cross domain request'}], [('--rpc-batch-size',), {'type': int, 'default': config.DEFAULT_RPC_BATCH_SIZE, 'help': 'number of RPC queries by batch (default: {})'.format(config.DEFAULT_RPC_BATCH_SIZE)}], [('--requests-timeout',), {'type': int, 'default': config.DEFAULT_REQUESTS_TIMEOUT, 'help': 'timeout value (in seconds) used for all HTTP requests (default: 5)'}], [('--force',), {'action': 'store_true', 'default': False, 'help': 'skip backend check, version check, process lock (NOT FOR USE ON PRODUCTION SYSTEMS)'}], [('--database-file',), {'default': None, 'help': 'the path to the SQLite3 database file'}], [('--log-file',), {'nargs': '?', 'const': None, 'default': False, 'help': 'log to the specified file (specify option without filename to use the default location)'}], [('--api-log-file',), {'nargs': '?', 'const': None, 'default': False, 'help': 'log API requests to the specified file (specify option without filename to use the default location)'}], [('--utxo-locks-max-addresses',), {'type': int, 'default': config.DEFAULT_UTXO_LOCKS_MAX_ADDRESSES, 'help': 'max number of addresses for which to track UTXO locks'}], [('--utxo-locks-max-age',), {'type': int, 'default': config.DEFAULT_UTXO_LOCKS_MAX_AGE, 'help': 'how long to keep a lock on a UTXO being tracked'}] ] class VersionError(Exception): pass def main(): if os.name == 'nt': from counterpartylib.lib import util_windows #patch up cmd.exe's "challenged" (i.e. broken/non-existent) UTF-8 logging util_windows.fix_win32_unicode() # Post installation tasks generate_config_files() # Parse command-line arguments. parser = argparse.ArgumentParser(prog=APP_NAME, description='Server for the {} protocol'.format(config.XCP_NAME), add_help=False) parser.add_argument('-h', '--help', dest='help', action='store_true', help='show this help message and exit') parser.add_argument('-V', '--version', action='version', version="{} v{}; {} v{}".format(APP_NAME, APP_VERSION, 'counterparty-lib', config.VERSION_STRING)) parser.add_argument('--config-file', help='the path to the configuration file') add_config_arguments(parser, CONFIG_ARGS, 'server.conf') subparsers = parser.add_subparsers(dest='action', help='the action to be taken') parser_server = subparsers.add_parser('start', help='run the server') parser_reparse = subparsers.add_parser('reparse', help='reparse all transactions in the database') parser_vacuum = subparsers.add_parser('vacuum', help='VACUUM the database (to improve performance)') parser_rollback = subparsers.add_parser('rollback', help='rollback database') parser_rollback.add_argument('block_index', type=int, help='the index of the last known good block') parser_kickstart = subparsers.add_parser('kickstart', help='rapidly build database by reading from Bitcoin Core blockchain') parser_kickstart.add_argument('--bitcoind-dir', help='Bitcoin Core data directory') parser_bootstrap = subparsers.add_parser('bootstrap', help='bootstrap database with hosted snapshot') parser_bootstrap.add_argument('-q', '--quiet', dest='quiet', action='store_true', help='suppress progress bar') #parser_bootstrap.add_argument('--branch', help='use a different branch for bootstrap db pulling') args = parser.parse_args() log.set_up(log.ROOT_LOGGER, verbose=args.verbose, console_logfilter=os.environ.get('COUNTERPARTY_LOGGING', None)) logger.info('Running v{} of {}.'.format(APP_VERSION, APP_NAME)) # Help message if args.help: parser.print_help() sys.exit() # Bootstrapping if args.action == 'bootstrap': bootstrap(testnet=args.testnet, quiet=args.quiet) sys.exit() def init_with_catch(fn, init_args): try: return fn(**init_args) except TypeError as e: if 'unexpected keyword argument' in str(e): raise VersionError('Unsupported Server Parameter. CLI/Library Version Incompatibility.') else: raise e # Configuration COMMANDS_WITH_DB = ['reparse', 'rollback', 'kickstart', 'start', 'vacuum'] COMMANDS_WITH_CONFIG = ['debug_config'] if args.action in COMMANDS_WITH_DB or args.action in COMMANDS_WITH_CONFIG: init_args = dict(database_file=args.database_file, log_file=args.log_file, api_log_file=args.api_log_file, testnet=args.testnet, testcoin=args.testcoin, regtest=args.regtest, customnet=args.customnet, api_limit_rows=args.api_limit_rows, backend_name=args.backend_name, backend_connect=args.backend_connect, backend_port=args.backend_port, backend_user=args.backend_user, backend_password=args.backend_password, backend_ssl=args.backend_ssl, backend_ssl_no_verify=args.backend_ssl_no_verify, backend_poll_interval=args.backend_poll_interval, indexd_connect=args.indexd_connect, indexd_port=args.indexd_port, rpc_host=args.rpc_host, rpc_port=args.rpc_port, rpc_user=args.rpc_user, rpc_password=args.rpc_password, rpc_no_allow_cors=args.rpc_no_allow_cors, requests_timeout=args.requests_timeout, rpc_batch_size=args.rpc_batch_size, check_asset_conservation=not args.no_check_asset_conservation, force=args.force, verbose=args.verbose, console_logfilter=os.environ.get('COUNTERPARTY_LOGGING', None), p2sh_dust_return_pubkey=args.p2sh_dust_return_pubkey, utxo_locks_max_addresses=args.utxo_locks_max_addresses, utxo_locks_max_age=args.utxo_locks_max_age) #,broadcast_tx_mainnet=args.broadcast_tx_mainnet) if args.action in COMMANDS_WITH_DB: db = init_with_catch(server.initialise, init_args) elif args.action in COMMANDS_WITH_CONFIG: init_with_catch(server.initialise_config, init_args) # PARSING if args.action == 'reparse': server.reparse(db) elif args.action == 'rollback': server.reparse(db, block_index=args.block_index) elif args.action == 'kickstart': server.kickstart(db, bitcoind_dir=args.bitcoind_dir) elif args.action == 'start': server.start_all(db) elif args.action == 'debug_config': server.debug_config() elif args.action == 'vacuum': server.vacuum(db) else: parser.print_help() # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
{ "content_hash": "5a2d8ed298335ac3f692d0649ce90a8d", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 187, "avg_line_length": 59.52571428571429, "alnum_prop": 0.6304118268215417, "repo_name": "CounterpartyXCP/counterparty-cli", "id": "9248dacb4ec290f65fff157385a2b53cbe14ae71", "size": "10444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "counterpartycli/server.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "91627" } ], "symlink_target": "" }
from lxml import etree from xml.etree.ElementTree import iterparse # coding: utf-8 from sqlalchemy import Table, Column,Integer,String,Float , DateTime, create_engine,MetaData,or_ from sqlalchemy.orm import mapper, sessionmaker # import loadText as lt import os import pprint import re import os import sys import shutil #from gensim import corpora,models,similarities import itertools import threading, time from sets import Set import cStringIO from lxml import etree, html from xml.etree.ElementTree import iterparse import HTMLParser import datetime import pandas as pd import numpy as np import colorsys import threading, Queue # import xapian # from xapian import SimpleStopper import networkx as nx from networkx.readwrite import json_graph import json singlelock = threading.Lock() html_parser = HTMLParser.HTMLParser() entities = [ ('&-',''), ('&|','')] def create_text_db(text_folder): engine = create_engine('sqlite:///%s/W3C.db'%(text_folder), echo=True) metadata = MetaData(bind=engine) documents_table = Table('Messages', metadata, Column('Id', String(150), primary_key=True), Column('Subject', String ), Column('Text', String), Column('AuthorID', String), Column('AuthorName', String), Column('AuthorEmail', String), Column('ThreadID', String), Column('Date', DateTime), Column('Type', String), Column('ResponseTo', String), Column('URL', String), Column('Level', String), Column ('SubjectChanged',String), Column('FromOtherList', String) ) metadata.create_all() class Message(object): pass def init(): folder=os.path.join('') engine = create_engine('sqlite:///' + os.path.join(folder, 'w3c.db'), echo=False) metadata = MetaData(bind=engine) global Session Session=sessionmaker(bind=engine) global message_table message_table= Table('Messages', metadata, autoload=True) try: mapper(Message, message_table) except: pass base='http://lists.w3.org/Archives/Public/public-html/{0}/{1}.html' def create_threads(size=10): init() session=Session() messages=session.query(Message).all() # messages=session.query(Message).all() print len(messages) G=nx.DiGraph() for message in messages: if message.ResponseTo !='': G.add_node(message.ResponseTo, name=message.AuthorName[0:20]) G.add_node(message.Id, name=message.AuthorName[0:20]) G.add_edge(message.ResponseTo, message.Id) threads=nx.weakly_connected_component_subgraphs(G) threads=[t for t in threads if len(t)>size] thread_info=[] for thread in threads: root=nx.topological_sort(thread)[0] m=session.query(Message).filter(or_(Message.Id==str(root), Message.ResponseTo==str(root)) ).first() thread_info.append((len(thread), m.Subject, root, thread )) return thread_info def json_thread(size=100): threads=create_threads(size=size) for thread_size, thread_subject, root, t_thread in threads: names= [d['name'] for n, d in t_thread.nodes(data=True)] unique_names=list(set(names)) colors=pick_color(len(unique_names)) col_pallette=dict(zip(unique_names, colors)) for n,d in t_thread.nodes(data=True): d['color']=col_pallette[d['name']] # root=nx.topological_sort(t_thread)[0] file='%s_%s.json'%(thread_size, thread_subject) file=re.sub('/',':', file ) data = json_graph.tree_data(t_thread,root=root) with open(os.path.join('json', file), 'w') as outfile: json.dump(data,outfile) def pick_color(n=1): h = np.random.random() # use random start value golden_ratio_conjugate = 0.618033988749895 hexcolors=[] for i in range(n): h += golden_ratio_conjugate h %= 1 rgb_tuple=colorsys.hsv_to_rgb(h, .5, .95) rgb_tuple=tuple( map(lambda x: int(x*256), rgb_tuple)) hexcolors.append('#%02x%02x%02x' % rgb_tuple) return hexcolors # def hsv_to_rgb(h, s, v): # # h_i = int(h*6) # f = h*6 - h_i # p = v * (1 - s) # q = v * (1 - f*s) # t = v * (1 - (1 - f) * s) # # if h_i==0: r, g, b = v, t, p # if h_i==1: r, g, b = q, v, p # if h_i==2: r, g, b = p, v, t # if h_i==3: r, g, b = p, q, v # if h_i==4: r, g, b = t, p, v # if h_i==5: r, g, b = v, p, q # return int(r*256), int(g*256), int(b*256) ################### #POPULATE class updater(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): global files_being_proccessed while True: # gets the url from the queue doci = self.queue.get() period,id=doci.split('~') # save doc try: self.process(period, id) except: print 'error @', period, id # send a signal to the queue that the job is done self.queue.task_done() singlelock.acquire() print period, id, ' Done..' singlelock.release() # rem_files= [file for file in files_being_proccessed if file!=doc] # files_being_proccessed=rem_files # update_remaining(files_being_proccessed) def process(self, period, id): murl=base.format(period,"%04d" % (int(id))) print murl # xmldata=re.sub(r' (\w+)=[A-Z0-9-]+>','>',xmldata) # # for before, after in entities: # xmldata = xmldata.replace(before, after.encode('utf-8')) # xmldatafile=cStringIO.StringIO(xmldata) # context = etree.iterparse( xmldatafile, tag='DOC' ) try: doc = html.parse(murl) except: print 'Missing page, ', id return comments=doc.getroot().xpath("//comment()") comments_dict={} for comment in comments: comment=html_parser.unescape(unicode(comment)) tag=re.findall(r"(?<=\s).*?(?==)", comment)[0] value=re.findall(r"(?<=\").*?(?=\")", comment)[0] comments_dict[tag]= unicode(value) #ID m_id= comments_dict['id'] # m_id= doc.getroot().xpath("//span[@id='message-id']/text()")[0] # try: # m_id= re.findall(r"(?<=<).*?(?=>)",m_id)[0] # except: # m_id=doc.getroot().xpath("//span[@id='message-id']/text()")[0].strip() # #SUBJECT subject= comments_dict['subject'] #subject=doc.getroot().xpath("//meta[@name='Subject']/@content")[0] #AUTHOR author_name=comments_dict.get('name', '') author_email=comments_dict['email'] #author=doc.getroot().xpath("//meta[@name='Author']/@content") #DATE m_date=doc.getroot().xpath("//meta[@name='Date']/@content")[0] m_date_array=map(int, m_date.split('-')) m_date=datetime.date(m_date_array[0],m_date_array[1],m_date_array[2]) print m_date #TYPE type_='Message' if '[BUG]' in subject: type_='Bug' #RESPONSETO responseto=comments_dict.get('inreplyto', '') #TEXT o_text= ' '.join(doc.getroot().xpath("//pre[@id='body']/text()")) text=re.sub(r'>+.*\n', '',o_text) text=re.sub(r'On.*wrote:\n', '',text) text=re.sub(r'\s+',' ', text) #URL i = message_table.insert() q = i.execute({'Id':m_id, 'Text':text, 'AuthorEmail':author_email, 'AuthorName':author_name, 'Subject':subject, 'Date':m_date, 'Type': type_, 'ResponseTo':responseto, 'URL': murl}) del doc if __name__ == '__main__': # files=[] file='htmlmessages.csv' message_list=pd.read_csv(file) queue = Queue.Queue() for j in range(10): t=updater(queue) t.setDaemon(True) t.start() init() print 'starting' ids=range(0,20) for i, r in message_list.iterrows(): for j in range(r['count']): queue.put(r['period']+'~'+str(j)) # for i in ids: # # queue.put(str(ids[i])+'~'+str(ids[i])) queue.join() # db_pass.flush() # db_doc.flush() print 'Finished...', i
{ "content_hash": "df11e9f573cd52e63fe9423116e8af53", "timestamp": "", "source": "github", "line_count": 379, "max_line_length": 107, "avg_line_length": 24.947229551451187, "alnum_prop": 0.5032258064516129, "repo_name": "ygenc/ygenc.github.io", "id": "9a3a8938fca807487c1380eaa5a0f1e8c834025e", "size": "9455", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/html5/html5.py", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "317848" }, { "name": "HTML", "bytes": "10311204" }, { "name": "Hack", "bytes": "2670" }, { "name": "JavaScript", "bytes": "2135171" }, { "name": "PHP", "bytes": "14402" }, { "name": "Python", "bytes": "9455" }, { "name": "Ruby", "bytes": "87" }, { "name": "SCSS", "bytes": "4670" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>HTML, CSS AND THE DOM: PART 1</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css"> <link rel="stylesheet" href="../styles/main.css"> <link href='https://fonts.googleapis.com/css?family=Harmattan' rel='stylesheet' type='text/css'> <script src="../styles/events.js"></script> </head> <body> <div class="navigation"> <ul> <a href="http:/nick-shanks.github.io/index.html"> <li>Home</li> </a> <li>About</li> </ul> </div> <div class="header"> <h1 class="HTMLtitle">HTML, CSS AND THE DOM: PART 1</h1> <img class="headerblogpicture" src="../image.jpg"/> </div> <div class="blog"> <h4><em>7 July 2016</em></h4> <p id="title"> What is HTML, CSS and the DOM? Part.1 </p> <p> How's everyone going? I know you are all thinking, what on earth is HTML, CSS and DOM? So, I'm going to try to explain as easy as I can. HTML is what puts structure to a webpage. Think of it as the same as how a tree truck puts structure to a tree. The more of it, the bigger the tree is. The more HTML the more a webpage will be. Pretty simple right? </p> <p> OK, on to CSS. Think of CSS as the leaves on a tree. Leaves cover the trunk and makes it look good. You can use CSS to make a webpage look as beautiful as you want! Different fonts and colours can be added to make a page stand out. The more colourful leaves on a tree the more beautiful it looks! </p> <p> The DOM (Document Object Model) is like the tree's branches. The DOM categorises sections inside a HTML and let's each section have it's own branch, the more sections within a section, the more branches off the main branch. Kind of like a family tree! </p> <p> Boxifying a design a tool a web developer can use when given a mock design and told to turn it into a webpage. You take the design and draw boxes around all the different parts you see on the mock e.g around the top header, the image inside the header, around the body and the text inside the body. This makes it easy to know how many different sections you will need to create when turning the design in to a web page. </p> <p> The box model is inside Dev Tools and when a section is highlighted will tell you how much margin, border, padding and content that section currently has. </p> </div> </body> </html>
{ "content_hash": "d0a13435279f4650caed9d360164efad", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 427, "avg_line_length": 51.22641509433962, "alnum_prop": 0.6685082872928176, "repo_name": "nick-shanks/nick-shanks.github.io", "id": "981a474d8d3dede6b142a66e217026e9a8535fe5", "size": "2715", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blog/t2-html-css-dom-p1.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3662" }, { "name": "HTML", "bytes": "70712" }, { "name": "JavaScript", "bytes": "573" } ], "symlink_target": "" }
.class Landroid/view/accessibility/IAccessibilityManagerClient$Stub$Proxy; .super Ljava/lang/Object; .source "IAccessibilityManagerClient.java" # interfaces .implements Landroid/view/accessibility/IAccessibilityManagerClient; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/view/accessibility/IAccessibilityManagerClient$Stub; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0xa name = "Proxy" .end annotation # instance fields .field private mRemote:Landroid/os/IBinder; # direct methods .method constructor <init>(Landroid/os/IBinder;)V .locals 0 .parameter "remote" .prologue .line 66 invoke-direct {p0}, Ljava/lang/Object;-><init>()V .line 67 iput-object p1, p0, Landroid/view/accessibility/IAccessibilityManagerClient$Stub$Proxy;->mRemote:Landroid/os/IBinder; .line 68 return-void .end method # virtual methods .method public asBinder()Landroid/os/IBinder; .locals 1 .prologue .line 71 iget-object v0, p0, Landroid/view/accessibility/IAccessibilityManagerClient$Stub$Proxy;->mRemote:Landroid/os/IBinder; return-object v0 .end method .method public getInterfaceDescriptor()Ljava/lang/String; .locals 1 .prologue .line 75 const-string v0, "android.view.accessibility.IAccessibilityManagerClient" return-object v0 .end method .method public setState(I)V .locals 5 .parameter "stateFlags" .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue .line 79 invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel; move-result-object v0 .line 81 .local v0, _data:Landroid/os/Parcel; :try_start_0 const-string v1, "android.view.accessibility.IAccessibilityManagerClient" invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V .line 82 invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V .line 83 iget-object v1, p0, Landroid/view/accessibility/IAccessibilityManagerClient$Stub$Proxy;->mRemote:Landroid/os/IBinder; const/4 v2, 0x1 const/4 v3, 0x0 const/4 v4, 0x1 invoke-interface {v1, v2, v0, v3, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 .line 86 invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V .line 88 return-void .line 86 :catchall_0 move-exception v1 invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V throw v1 .end method
{ "content_hash": "25e68a89eb8fadde68e9bf7feb052af9", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 121, "avg_line_length": 23.734513274336283, "alnum_prop": 0.709545115585384, "repo_name": "baidurom/devices-g520", "id": "44fb2c950feeb73ffb835820e07bc3569d85020f", "size": "2682", "binary": false, "copies": "7", "ref": "refs/heads/coron-4.1", "path": "vendor/aosp/secondary-framework.jar.out/smali/android/view/accessibility/IAccessibilityManagerClient$Stub$Proxy.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "12575" }, { "name": "Python", "bytes": "1261" }, { "name": "Shell", "bytes": "2159" } ], "symlink_target": "" }
namespace aura { class FocusManager; class RootWindow; namespace client { class ActivationChangeObserver; } } namespace views { // An activation client that handles activation events in a single // RootWindow. Used only on the Desktop where there can be multiple RootWindow // objects. class VIEWS_EXPORT DesktopActivationClient : public aura::client::ActivationClient, public aura::WindowObserver, public aura::FocusChangeObserver { public: explicit DesktopActivationClient(aura::RootWindow* root_window); virtual ~DesktopActivationClient(); // ActivationClient: virtual void AddObserver( aura::client::ActivationChangeObserver* observer) OVERRIDE; virtual void RemoveObserver( aura::client::ActivationChangeObserver* observer) OVERRIDE; virtual void ActivateWindow(aura::Window* window) OVERRIDE; virtual void DeactivateWindow(aura::Window* window) OVERRIDE; virtual aura::Window* GetActiveWindow() OVERRIDE; virtual bool OnWillFocusWindow(aura::Window* window, const ui::Event* event) OVERRIDE; virtual bool CanActivateWindow(aura::Window* window) const OVERRIDE; // Overridden from aura::WindowObserver: virtual void OnWindowDestroying(aura::Window* window) OVERRIDE; // Overridden from aura::FocusChangeObserver: virtual void OnWindowFocused(aura::Window* window) OVERRIDE; private: // Walks up the chain to find the correct parent window to activate when we // try to activate |window|. aura::Window* GetActivatableWindow(aura::Window* window); aura::RootWindow* root_window_; // The current active window. aura::Window* current_active_; // True inside ActivateWindow(). Used to prevent recursion of focus // change notifications causing activation. bool updating_activation_; ObserverList<aura::client::ActivationChangeObserver> observers_; ScopedObserver<aura::Window, aura::WindowObserver> observer_manager_; DISALLOW_COPY_AND_ASSIGN(DesktopActivationClient); }; } // namespace views #endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESTKOP_ACTIVATION_CLIENT_H_
{ "content_hash": "d1963d68e570b5912753f26ee40b4e36", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 78, "avg_line_length": 32.703125, "alnum_prop": 0.7534639273769709, "repo_name": "leighpauls/k2cro4", "id": "b63f2250f048f439218577bb4f6556d4afb19802", "size": "2729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui/views/widget/desktop_aura/desktop_activation_client.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "3062" }, { "name": "AppleScript", "bytes": "25392" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "68131038" }, { "name": "C", "bytes": "242794338" }, { "name": "C#", "bytes": "11024" }, { "name": "C++", "bytes": "353525184" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "F#", "bytes": "4992" }, { "name": "FORTRAN", "bytes": "10404" }, { "name": "Java", "bytes": "3845159" }, { "name": "JavaScript", "bytes": "39146656" }, { "name": "Lua", "bytes": "13768" }, { "name": "Matlab", "bytes": "22373" }, { "name": "Objective-C", "bytes": "21887598" }, { "name": "PHP", "bytes": "2344144" }, { "name": "Perl", "bytes": "49033099" }, { "name": "Prolog", "bytes": "2926122" }, { "name": "Python", "bytes": "39863959" }, { "name": "R", "bytes": "262" }, { "name": "Racket", "bytes": "359" }, { "name": "Ruby", "bytes": "304063" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "9195117" }, { "name": "Tcl", "bytes": "1919771" }, { "name": "Verilog", "bytes": "3092" }, { "name": "Visual Basic", "bytes": "1430" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
//--------------------------------------------------------------------- // <copyright file="InitializeRoutes.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // <summary>The route ininitialization</summary> //--------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------------------------------- namespace Sitecore.Reference.Storefront.SitecorePipelines { using System.Web.Http; using Sitecore.Pipelines; using System.Web.Routing; /// <summary> /// The initialize routes. /// </summary> public class InitializeRoutes { /// <summary> /// The process. /// </summary> /// <param name="args"> /// The args. /// </param> public void Process(PipelineArgs args) { if (!Context.IsUnitTesting) { RouteConfig.RegisterRoutes(RouteTable.Routes); WebApiConfig.Register(GlobalConfiguration.Configuration); } } } }
{ "content_hash": "cb778239dea03707a51759376b5b9738", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 94, "avg_line_length": 38.77272727272727, "alnum_prop": 0.5638921453692849, "repo_name": "Sitecore/sccs-demo", "id": "ab940ed96ff031a493e1c4909a277435586708db", "size": "1708", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CS/CSF/SitecorePipelines/InitializeRoutes.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "1179" }, { "name": "C#", "bytes": "1572445" }, { "name": "CSS", "bytes": "43813" }, { "name": "HTML", "bytes": "253367" }, { "name": "JavaScript", "bytes": "381220" }, { "name": "Smalltalk", "bytes": "77392" } ], "symlink_target": "" }
<?php if (!defined('ELK')) die('No access...'); /** * Database driver interface */ interface Database { /** * Fix up the prefix so it doesn't require the database to be selected. * * @param string $db_prefix * @param string $db_name * * @return string */ function fix_prefix($db_prefix, $db_name); /** * Callback for preg_replace_callback on the query. * It allows to replace on the fly a few pre-defined strings, for convenience ('query_see_board', 'query_wanna_see_board'), with * their current values from $user_info. * In addition, it performs checks and sanitization on the values sent to the database. * * @param $matches */ function replacement__callback($matches); /** * This function works like $db->query(), escapes and quotes a string, * but it doesn't execute the query. * * @param string $db_string * @param array $db_values * @param resource $connection = null */ function quote($db_string, $db_values, $connection = null); /** * Do a query. Takes care of errors too. * * @param string $identifier * @param string $db_string * @param array $db_values = array() * @param resource $connection = null */ function query($identifier, $db_string, $db_values = array(), $connection = null); /** * Fetch next result as association. * * @param resource $request * @param mixed $counter = false */ function fetch_assoc($request, $counter = false); /** * Fetch a row from the resultset given as parameter. * * @param resource $result * @param $counter = false */ function fetch_row($result, $counter = false); /** * Free the resultset. * * @param resource $result */ function free_result($result); /** * Get the number of rows in the result. * * @param resource $result */ function num_rows($result); /** * Get the number of fields in the resultset. * * @param resource $request */ function num_fields($request); /** * Reset the internal result pointer. * * @param $request * @param $counter */ function data_seek($request, $counter); /** * Returns count of affected rows from the last transaction. */ function affected_rows(); /** * Last insert id * * @param string $table * @param string $field = null * @param resource $connection = null */ function insert_id($table, $field = null, $connection = null); /** * Do a transaction. * * @param string $type - the step to perform (i.e. 'begin', 'commit', 'rollback') * @param resource $connection = null */ function db_transaction($type = 'commit', $connection = null); /** * Database error. * Backtrace, log, try to fix. * * @param string $db_string * @param resource $connection = null */ function error($db_string, $connection = null); /** * Insert data. * * @param string $method - options 'replace', 'ignore', 'insert' * @param $table * @param $columns * @param $data * @param $keys * @param bool $disable_trans = false * @param resource $connection = null */ function insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null); /** * This function tries to work out additional error information from a back trace. * * @param $error_message * @param $log_message * @param $error_type * @param $file * @param $line */ function error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null); /** * Escape string for the database input * * @param string $string */ function escape_string($string); /** * Escape the LIKE wildcards so that they match the character and not the wildcard. * * @param $string * @param bool $translate_human_wildcards = false, if true, turns human readable wildcards into SQL wildcards. */ function escape_wildcard_string($string, $translate_human_wildcards=false); /** * Unescape an escaped string. * * @param string $string */ function unescape_string($string); /** * Return last error string from the database server * * @param resource $connection = null */ function last_error($connection = null); /** * Returns whether the database system supports ignore. * * @return bool */ function support_ignore(); /** * Get the name (title) of the database system. */ function db_title(); /** * Whether the database system is case sensitive. * * @return bool */ function db_case_sensitive(); /** * Gets all the necessary INSERTs for the table named table_name. * It goes in 250 row segments. * * @param string $tableName - the table to create the inserts for. * @param bool $new_table * @return string the query to insert the data back in, or an empty string if the table was empty. */ function insert_sql($tableName, $new_table = false); /** * Select database. * * @param string $dbName = null * @param resource $connection = null */ function select_db($dbName = null, $connection = null); }
{ "content_hash": "33a75bae86bd9ba8c5cf214754ac40e8", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 129, "avg_line_length": 22.89908256880734, "alnum_prop": 0.6472355769230769, "repo_name": "wizardaf/elkarte.net", "id": "fc3ace35f10ec40cd2df391485696d3e2a1d6427", "size": "5230", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "elk/community/sources/database/Db.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "279" }, { "name": "CSS", "bytes": "403702" }, { "name": "HTML", "bytes": "45" }, { "name": "JavaScript", "bytes": "830175" }, { "name": "PHP", "bytes": "7024438" } ], "symlink_target": "" }
package app.exam.io; import app.exam.io.interfaces.ConsoleIO; import org.springframework.stereotype.Component; @Component public class ConsoleIOImpl implements ConsoleIO { @Override public void write(String line) { System.out.println(line); } }
{ "content_hash": "7bfa00ea79d07225deed33ead57fa11c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 49, "avg_line_length": 20.615384615384617, "alnum_prop": 0.7388059701492538, "repo_name": "ivelin1936/Studing-SoftUni-", "id": "3d611e13a46e4fa40e4e36f3048ba64bed57a458", "size": "268", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Databases Frameworks - Hibernate & Spring Data - март 2018/UTILS/io/ConsoleIOImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7178" }, { "name": "Java", "bytes": "2592247" }, { "name": "SQLPL", "bytes": "797" } ], "symlink_target": "" }
.. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at .. http://www.apache.org/licenses/LICENSE-2.0 .. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. .. _howto/connection:oracle: Oracle Connection ================= The Oracle connection type provides connection to a Oracle database. Configuring the Connection -------------------------- Host (optional) The host to connect to. Schema (optional) Specify the schema name to be used in the database. Login (optional) Specify the user name to connect. Password (optional) Specify the password to connect. Extra (optional) Specify the extra parameters (as json dictionary) that can be used in Oracle connection. The following parameters are supported: * ``encoding`` - The encoding to use for regular database strings. If not specified, the environment variable ``NLS_LANG`` is used. If the environment variable ``NLS_LANG`` is not set, ``ASCII`` is used. * ``nencoding`` - The encoding to use for national character set database strings. If not specified, the environment variable ``NLS_NCHAR`` is used. If the environment variable ``NLS_NCHAR`` is not used, the environment variable ``NLS_LANG`` is used instead, and if the environment variable ``NLS_LANG`` is not set, ``ASCII`` is used. * ``threaded`` - Whether or not Oracle should wrap accesses to connections with a mutex. Default value is False. * ``events`` - Whether or not to initialize Oracle in events mode. * ``mode`` - one of ``sysdba``, ``sysasm``, ``sysoper``, ``sysbkp``, ``sysdgd``, ``syskmt`` or ``sysrac`` which are defined at the module level, Default mode is connecting. * ``purity`` - one of ``new``, ``self``, ``default``. Specify the session acquired from the pool. configuration parameter. * ``dsn``. Specify a Data Source Name (and ignore Host). * ``sid`` or ``service_name``. Use to form DSN instead of Schema. Connect using `dsn`, Host and `sid`, Host and `service_name`, or only Host `(OracleHook.getconn Documentation) <https://airflow.apache.org/docs/apache-airflow-providers-oracle/stable/_modules/airflow/providers/oracle/hooks/oracle.html#OracleHook.get_conn>`_. For example: .. code-block:: python Host = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=dbhost.example.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orclpdb1)))" or .. code-block:: python Host = "dbhost.example.com" Schema = "orclpdb1" or .. code-block:: python Host = "dbhost.example.com" Schema = "orcl" More details on all Oracle connect parameters supported can be found in `cx_Oracle documentation <https://cx-oracle.readthedocs.io/en/latest/api_manual/module.html#cx_Oracle.connect>`_. Information on creating an Oracle Connection through the web user interface can be found in Airflow's :doc:`Managing Connections Documentation <apache-airflow:howto/connection>`. Example "extras" field: .. code-block:: json { "encoding": "UTF-8", "nencoding": "UTF-8", "threaded": false, "events": false, "mode": "sysdba", "purity": "new" } When specifying the connection as URI (in :envvar:`AIRFLOW_CONN_{CONN_ID}` variable) you should specify it following the standard syntax of DB connections, where extras are passed as parameters of the URI (note that all components of the URI should be URL-encoded). For example: .. code-block:: bash export AIRFLOW_CONN_ORACLE_DEFAULT='oracle://oracle_user:XXXXXXXXXXXX@1.1.1.1:1521?encoding=UTF-8&nencoding=UTF-8&threaded=False&events=False&mode=sysdba&purity=new'
{ "content_hash": "5564873a1b6a333f1cbc947c725c8591", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 262, "avg_line_length": 39.080357142857146, "alnum_prop": 0.684715558601782, "repo_name": "dhuang/incubator-airflow", "id": "4a26c36b3142a044c3ae69b78b2bde11cfa88749", "size": "4377", "binary": false, "copies": "14", "ref": "refs/heads/main", "path": "docs/apache-airflow-providers-oracle/connections/oracle.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "109698" }, { "name": "HTML", "bytes": "264851" }, { "name": "JavaScript", "bytes": "1988427" }, { "name": "Mako", "bytes": "1037" }, { "name": "Python", "bytes": "3357958" }, { "name": "Shell", "bytes": "34442" } ], "symlink_target": "" }
printf "\nStop any already-running server." assert_ok "$FLOW" stop . printf "\nCheck with munge_underscores = false (by default) should return no errors:\n" assert_ok "$FLOW" check --no-flowlib . printf "\nCheck with --munge-underscore-members flag should return one error on the _x update:\n" assert_errors "$FLOW" check --no-flowlib --munge-underscore-members . # set 'munge_underscores = true' in .flowconfig cp .flowconfig.munge_underscores_true .flowconfig printf "\nCheck with munge_underscores=true in .flowconfig should return one error on the _x update:\n" assert_errors "$FLOW" check --no-flowlib . # prevent munge via pragma sed -i'.orig' -e '1s/^/\/\/ @preventMunge\\n\n/' class.js printf "\nCheck with preventMunge via pragma (overrides .flowconfig option) should return no errors:\n" assert_ok "$FLOW" check --no-flowlib .
{ "content_hash": "5ed3d004ae6bab0bfd221ea565916036", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 103, "avg_line_length": 42.15, "alnum_prop": 0.7354685646500593, "repo_name": "nmote/flow", "id": "d2e732ec4bc739c307f529c8ce5744122c017ae0", "size": "1033", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/types_first_munge_underscores/test.sh", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "112238" }, { "name": "C++", "bytes": "5813" }, { "name": "Dockerfile", "bytes": "4611" }, { "name": "HTML", "bytes": "35768" }, { "name": "JavaScript", "bytes": "3020230" }, { "name": "Liquid", "bytes": "17387" }, { "name": "Makefile", "bytes": "27684" }, { "name": "OCaml", "bytes": "8222343" }, { "name": "Python", "bytes": "3830" }, { "name": "Ruby", "bytes": "21863" }, { "name": "SCSS", "bytes": "45501" }, { "name": "Shell", "bytes": "268938" }, { "name": "Standard ML", "bytes": "17465" } ], "symlink_target": "" }
/* This file was generated automatically by Zephir do not modify it! */ #ifndef PHP_ICE_H #define PHP_ICE_H 1 #ifdef PHP_WIN32 #define ZEPHIR_RELEASE 1 #endif #include "kernel/globals.h" #define PHP_ICE_NAME "ice" #define PHP_ICE_VERSION "1.7.0" #define PHP_ICE_EXTNAME "ice" #define PHP_ICE_AUTHOR "Ice Team" #define PHP_ICE_ZEPVERSION "0.12.18-$Id$" #define PHP_ICE_DESCRIPTION "Simple and fast PHP framework delivered as C-extension.<br>Copyright (c) 2014-2020 Ice Team." ZEND_BEGIN_MODULE_GLOBALS(ice) int initialized; /** Function cache */ HashTable *fcache; zephir_fcall_cache_entry *scache[ZEPHIR_MAX_CACHE_SLOTS]; /* Cache enabled */ unsigned int cache_enabled; /* Max recursion control */ unsigned int recursive_lock; zend_bool cli_colors; ZEND_END_MODULE_GLOBALS(ice) #ifdef ZTS #include "TSRM.h" #endif ZEND_EXTERN_MODULE_GLOBALS(ice) #ifdef ZTS #define ZEPHIR_GLOBAL(v) ZEND_MODULE_GLOBALS_ACCESSOR(ice, v) #else #define ZEPHIR_GLOBAL(v) (ice_globals.v) #endif #ifdef ZTS ZEND_TSRMLS_CACHE_EXTERN() #define ZEPHIR_VGLOBAL ((zend_ice_globals *) (*((void ***) tsrm_get_ls_cache()))[TSRM_UNSHUFFLE_RSRC_ID(ice_globals_id)]) #else #define ZEPHIR_VGLOBAL &(ice_globals) #endif #define ZEPHIR_API ZEND_API #define zephir_globals_def ice_globals #define zend_zephir_globals_def zend_ice_globals extern zend_module_entry ice_module_entry; #define phpext_ice_ptr &ice_module_entry #endif
{ "content_hash": "5550fc55800e1d3a40f99162fce12284", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 122, "avg_line_length": 20.742857142857144, "alnum_prop": 0.7196969696969697, "repo_name": "mruz/framework", "id": "68d8cbff1f0816c15231dec48dcfcbe469d4811b", "size": "1452", "binary": false, "copies": "2", "ref": "refs/heads/dev", "path": "build/php7/php_ice.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1237434" }, { "name": "M4", "bytes": "15425" }, { "name": "PHP", "bytes": "64699" }, { "name": "Shell", "bytes": "2813" }, { "name": "Zephir", "bytes": "528610" } ], "symlink_target": "" }
lightline-hybrid ================ Overview -------- lightline-hybrid brings awesome color scheme [vim-hybrid](https://github.com/w0ng/vim-hybrid) into [lightline.vim](https://github.com/itchyny/lightline.vim). Setup ----- Put `lightline-hybrid.vim` into your plugin directory. Or if you are mad about [NeoBundle](https://github.com/Shougo/neobundle.vim), add the following line to your `.vimrc`: ```vim NeoBundle 'cocopon/lightline-hybrid.vim' ``` Finally, set color scheme of lightline in `.vimrc`: ```vim let g:lightline = {} let g:lightline.colorscheme = 'hybrid' ``` Screenshots ----------- ![default](http://cocopon.me/app/lightline-hybrid/img/default.png) If you prefer a simple one, how about a plain style? ![plain](http://cocopon.me/app/lightline-hybrid/img/plain.png) ```vim let g:lightline_hybrid_style = 'plain' ``` License ------- MIT License. See LICENSE.txt for more information.
{ "content_hash": "d86f5d134dd6c2df157beb5c1d9184e6", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 157, "avg_line_length": 21.61904761904762, "alnum_prop": 0.7004405286343612, "repo_name": "cocopon/lightline-hybrid.vim", "id": "f1ff50362b3238ca80b25c5ca9e69010b817f52e", "size": "908", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Vim script", "bytes": "3085" } ], "symlink_target": "" }
require 'test_helper' class UsersApiTest < ActionController::TestCase include ApiAuthTestHelper def setup @controller = UsersController.new add_auth_token_to_header end def user @user ||= User.create( name: 'Donald Cerrone', email: 'cowboy@cerrone.com', password: '123456', password_confirmation: '123456', ) end def test_updating_profile_via_json patch :update, id: user.id, user: { name: 'Bob' }, format: :json assert_response :success assert_template :show assert_equal 'Bob', assigns(:user).name end def test_update_failure_via_json patch :update, id: user.id, user: { password: '123456', password_confirmation: '123' }, format: :json assert_response 422 expects = {"password_confirmation"=>["doesn't match Password"]} assert_equal expects, parse_body end end
{ "content_hash": "7e9d2717cbacdee12fc90aa13ba16758", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 67, "avg_line_length": 23.425, "alnum_prop": 0.6147278548559232, "repo_name": "revans/diesel", "id": "d33abc87a7d76f437d916454c05d5725e4514f4e", "size": "937", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/generators/auth/templates/test/controllers/users_api_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "38851" }, { "name": "HTML", "bytes": "38262" }, { "name": "Ruby", "bytes": "85202" }, { "name": "Shell", "bytes": "247" } ], "symlink_target": "" }
package com.jk.util.model.table; import java.text.Format; import java.util.Vector; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import com.jk.util.JKNumbersUtil; import com.jk.util.model.table.JKTableRecord.RecordStatus; // TODO: Auto-generated Javadoc /** * The Class JKTableModel. * * @author Jalal Kiswani */ public class JKTableModel extends AbstractTableModel { /** * The Class ColumnVisiblityManagar. * * @author jalal */ class ColumnVisiblityManagar { /** The columns. */ final Vector<JKTableColumn> columns; /** * Instantiates a new column visiblity managar. * * @param columns the columns */ // /////////////////////////////////////////////////////////// public ColumnVisiblityManagar(final Vector<JKTableColumn> columns) { this.columns = columns; refreshVisibility(); } /** * Gets the actual index from visible index. * * @param visibleIndex the visible index * @return the actual index from visible index */ // /////////////////////////////////////////////////////////// public int getActualIndexFromVisibleIndex(final int visibleIndex) { return getFSTableColumnFromVisibleIndex(visibleIndex).getIndex(); } /** * Gets the columns. * * @return the columns */ // /////////////////////////////////////////////////////////// public Vector<JKTableColumn> getColumns() { return this.columns; } /** * Gets the FS table column from visible index. * * @param visibleIndex the visible index * @return the FS table column from visible index */ // /////////////////////////////////////////////////////////// public JKTableColumn getFSTableColumnFromVisibleIndex(final int visibleIndex) { for (final JKTableColumn col : this.columns) { if (col.getVisibleIndex() == visibleIndex) { return col; } } throw new ArrayIndexOutOfBoundsException(visibleIndex); } // /////////////////////////////////////////////////////////// /** * Gets the visible column count. * * @return the visible column count */ public int getVisibleColumnCount() { int count = 0; for (final JKTableColumn col : this.columns) { if (col.isVisible()) { count++; } } return count; } /** * Gets the visible index from actual index. * * @param actualIndex the actual index * @return the visible index from actual index */ // /////////////////////////////////////////////////////////// public int getVisibleIndexFromActualIndex(final int actualIndex) { return this.columns.get(actualIndex).getVisibleIndex(); } /** * Refresh visibility. */ // /////////////////////////////////////////////////////////// protected void refreshVisibility() { int visibleIndex = 0; for (final JKTableColumn col : this.columns) { if (col.isVisible()) { col.setVisibleIndex(visibleIndex++); } else { col.setVisibleIndex(-1); } } } } /** The Constant serialVersionUID. */ private static final long serialVersionUID = -6003811835691538215L; /** The table columns. */ private final Vector<JKTableColumn> tableColumns = new Vector<JKTableColumn>(); /** The records. */ private final Vector<JKTableRecord> records = new Vector<JKTableRecord>(); /** The visibility manager. */ private final ColumnVisiblityManagar visibilityManager = new ColumnVisiblityManagar(this.tableColumns); /** The deleted records. */ private final Vector<JKTableRecord> deletedRecords = new Vector<JKTableRecord>(); /** The modified. */ boolean modified; /** The allow delete. */ boolean allowDelete; /** * Instantiates a new JK table model. */ // ///////////////////////////////////////////////////////////////////////// public JKTableModel() { } /** * Adds the JK table column. * * @param col the col */ // /////////////////////////////////////////////////////////////////// public void addJKTableColumn(final JKTableColumn col) { col.setIndex(this.tableColumns.size()); this.tableColumns.add(col); this.visibilityManager.refreshVisibility(); fireTableStructureChanged(); } /** * Adds the record. * * @return the JK table record */ // /////////////////////////////////////////////////////////////////////////////////////// public JKTableRecord addRecord() { final JKTableRecord record = createEmptyRecord(); addRecord(record); return record; } /** * Adds the record. * * @param record the record */ // /////////////////////////////////////////////////////////////////////////////////////// public void addRecord(final JKTableRecord record) { geteRecords().add(record); fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1); } /** * Clear records. */ // ////////////////////////////////////////////////////////////////////// public void clearRecords() { this.records.clear(); fireTableDataChanged(); } /** * Creates the empty record. * * @return the JK table record */ // ///////////////////////////////////////////////////////// protected JKTableRecord createEmptyRecord() { final JKTableRecord record = new JKTableRecord(); record.addEmptyValues(this.tableColumns); record.setStatus(RecordStatus.NEW); return record; } /** * Delete row. * * @param selectedRow the selected row * @return the JK table record */ // ///////////////////////////////////////////////////////// public JKTableRecord deleteRow(final int selectedRow) { final JKTableRecord removed = removeRecord(selectedRow); removed.setStatus(RecordStatus.DELETED); // Object removed = getDataVector().remove(selectedRow); if (removed != null) { this.deletedRecords.add(removed); } fireTableRowsDeleted(selectedRow, selectedRow); return removed; } /** * Delete rows. * * @param rows the rows */ // ////////////////////////////////////////////////////////////////////// public void deleteRows(final int[] rows) { for (int i = rows.length - 1; i >= 0; i--) { deleteRow(rows[i]); } } // /////////////////////////////////////////////////////////////////////////////////////// /** * Fire table column data changed. * * @param col the col */ public void fireTableColumnDataChanged(final int col) { for (int i = 0; i < getRowCount(); i++) { fireTableCellUpdated(i, col); } } /** * Gets the actual column count. * * @return the actual column count */ public int getActualColumnCount() { return this.tableColumns.size(); } /** * Gets the actual column index from visible. * * @param visibleIndex the visible index * @return the actual column index from visible */ public int getActualColumnIndexFromVisible(final int visibleIndex) { return getTableColumn(visibleIndex, true).getIndex(); } /** * Gets the actual column name. * * @param index the index * @return the actual column name */ // ///////////////////////////////////////////////////////////////////// public String getActualColumnName(final int index) { return getTableColumn(index).getName(); } /** * Gets the cell editor. * * @param column the column * @return the cell editor */ // ///////////////////////////////////////////////////////// public TableCellEditor getCellEditor(final int column) { return getTableColumn(column).getEditor(); } /** * Gets the cell renderer. * * @param column the column * @return the cell renderer */ // ///////////////////////////////////////////////////////// public TableCellRenderer getCellRenderer(final int column) { return getTableColumn(column).getRenderer(); } /* * (non-Javadoc) * * @see javax.swing.table.AbstractTableModel#getColumnClass(int) */ // /////////////////////////////////////////////////////////////////////////////// @Override public Class getColumnClass(final int columnIndex) { return getTableColumn(columnIndex).getColumnClass(); // try { // String columnClassName = // getTableColumn(columnIndex).getColumnClassName(); // // // System.out.println("Coluinm name : "+getColumnName(columnIndex)+" // class = "+ // // columnClassName); // Class<?> clas = Class.forName(columnClassName); // if (clas.isInstance(BigDecimal.class)) { // return Double.class; // } // return clas; // } catch (Exception e) { // ExceptionUtil.handle(e); // return null; // } } // // ///////////////////////////////////////////////////////// // public FSTableColumn getTableColumn(int col) { // return getTableColumn(col, true); // } /* * (non-Javadoc) * * @see javax.swing.table.TableModel#getColumnCount() */ // ///////////////////////////////////////////////////////////////////// @Override public int getColumnCount() { return this.visibilityManager.getVisibleColumnCount(); } /* * (non-Javadoc) * * @see javax.swing.table.AbstractTableModel#getColumnName(int) */ @Override public String getColumnName(final int visibleColumnIndex) { // FSTableColumn tableColumn = getTableColumn(visibleColumnIndex); // return // tableColumn.getHumanName()+"-"+tableColumn.getVisibleIndex()+'-'+tableColumn.getIndex(); return getTableColumn(visibleColumnIndex).getHumanName(); } /** * Gets the column type. * * @param col the col * @return the column type */ // ///////////////////////////////////////////////////////////////////// public int getColumnType(final int col) { return getTableColumn(col).getColumnType(); } /** * Gets the colunm index. * * @param name the name * @return the colunm index */ // ///////////////////////////////////////////////////////////////////// public int getColunmIndex(final String name) { for (int i = 0; i < getColumnCount(); i++) { if (getActualColumnName(i).trim().equalsIgnoreCase(name)) { return i; } } return -1; } /** * Gets the colunm index by name. * * @param colName the col name * @return the colunm index by name */ // ///////////////////////////////////////////////////////////////////////////// public int getColunmIndexByName(final String colName) { for (final JKTableColumn col : this.tableColumns) { if (col.getName().equalsIgnoreCase(colName)) { return col.getVisibleIndex(); } } return -1; } /** * Gets the colunm sum. * * @param col the col * @return the colunm sum */ // ///////////////////////////////////////////////////////////////////////// public double getColunmSum(final int col) { double sum = 0; for (int i = 0; i < getRowCount(); i++) { final double number = getValueAtAsDouble(i, col); sum = JKNumbersUtil.addAmounts(sum, number); } return sum; } /** * Gets the deleted records. * * @return the deleted records */ // ///////////////////////////////////////////////////////// public Vector<JKTableRecord> getDeletedRecords() { return this.deletedRecords; } /** * Gets the deleted records as data vector. * * @return the deleted records as data vector */ // /////////////////////////////////////////////////////////////////// public Vector<Vector> getDeletedRecordsAsDataVector() { final Vector<Vector> data = new Vector<Vector>(); for (final JKTableRecord rec : this.deletedRecords) { data.add(rec.toValuesVector()); } return data; } /** * Gets the e records. * * @return the e records */ private Vector<JKTableRecord> geteRecords() { return this.records; } /** * Gets the formatter. * * @param col the col * @return the formatter */ // ///////////////////////////////////////////////////////// public Format getFormatter(final int col) { return getTableColumn(col).getFormatter(); } /** * Gets the integer colunm sum. * * @param col the col * @return the integer colunm sum */ // ///////////////////////////////////////////////////////////////////////// public int getIntegerColunmSum(final int col) { return (int) getColunmSum(col); } /** * Gets the preffered width. * * @param column the column * @return the preffered width */ // ///////////////////////////////////////////////////////// public int getPrefferedWidth(final int column) { return getTableColumn(column).getPreferredWidth(); } /** * Gets the record. * * @param row the row * @return the record */ // ///////////////////////////////////////////////////////////////////////////// public JKTableRecord getRecord(final int row) { if (row >= getRowCount()) { throw new IllegalStateException("Row : " + row + " is out of index"); } return this.records.get(row); } /** * Gets the records. * * @return the records */ // /////////////////////////////////////////////////////////////////// public Vector<JKTableRecord> getRecords() { return this.records; } /** * Gets the records as data vector. * * @return the records as data vector */ // /////////////////////////////////////////////////////////////////// public Vector<Vector> getRecordsAsDataVector() { final Vector<Vector> data = new Vector<Vector>(); for (final JKTableRecord rec : this.records) { data.add(rec.toValuesVector()); } return data; } // // ///////////////////////////////////////////////////////// // public Vector<FSTableColumn> getTableColumns() { // return tableColumns; // } /* * (non-Javadoc) * * @see javax.swing.table.TableModel#getRowCount() */ // ///////////////////////////////////////////////////////////////////////////// @Override public int getRowCount() { return this.tableColumns.size() == 0 || this.records == null ? 0 : this.records.size(); } /** * Gets the table column. * * @param visibleColumnIndex the visible column index * @return the table column */ // ///////////////////////////////////////////////////////////////////////////// public JKTableColumn getTableColumn(final int visibleColumnIndex) { return getTableColumn(visibleColumnIndex, true); } // ///////////////////////////////////////////////////////// /** * return NULL of col is out of bound. * * @param col the col * @param visibleIndex the visible index * @return the table column */ public JKTableColumn getTableColumn(final int col, final boolean visibleIndex) { int actualIndex; if (visibleIndex) { actualIndex = this.visibilityManager.getActualIndexFromVisibleIndex(col); } else { actualIndex = col; } return this.tableColumns.get(actualIndex); } /* * (non-Javadoc) * * @see javax.swing.table.TableModel#getValueAt(int, int) */ // ///////////////////////////////////////////////////////////////////////////// @Override public Object getValueAt(final int row, final int visibleColumnIndex) { final int actualIndex = this.visibilityManager.getActualIndexFromVisibleIndex(visibleColumnIndex); return getRecords().get(row).getColumnValue(actualIndex); } /** * Gets the value at as double. * * @param row the row * @param col the col * @return the value at as double */ // /////////////////////////////////////////////////////////////////////////////////////// public double getValueAtAsDouble(final int row, final int col) { final Object valueAt = getValueAt(row, col); double number = 0; if (valueAt != null && !valueAt.toString().equals("")) { number = Double.parseDouble(valueAt.toString().trim()); } return number; } /** * Gets the value at as float. * * @param row the row * @param col the col * @return the value at as float */ // /////////////////////////////////////////////////////////////////////////////////////// public float getValueAtAsFloat(final int row, final int col) { final Object valueAt = getValueAt(row, col); float number = 0; if (valueAt != null && !valueAt.toString().equals("")) { number = Float.parseFloat(valueAt.toString().trim()); } return number; } /** * Gets the value at as integer. * * @param row the row * @param col the col * @return the value at as integer */ public int getValueAtAsInteger(final int row, final int col) { final Object valueAt = getValueAt(row, col); int number = 0; if (valueAt != null && !valueAt.toString().equals("")) { number = Integer.parseInt(valueAt.toString().trim()); } return number; } /** * Gets the visible column index from actual. * * @param actualIndex the actual index * @return the visible column index from actual */ // ////////////////////////////////////////////////////////////////////// public int getVisibleColumnIndexFromActual(final int actualIndex) { return getTableColumn(actualIndex, false).getVisibleIndex(); } // // // ///////////////////////////////////////////////////////////////////////////// // public FSTableColumn getTableColumn(int index, boolean createIfNotExists) // { // if (index < tableColumns.size()) { // return tableColumns.get(index); // } // if (create) { // FSTableColumn col = createTableColumn(index); // addFSTableColumn(col); // return col; // } // throw new ArrayIndexOutOfBoundsException(index); // } /** * Insert record. * * @param selectedRow the selected row */ // ///////////////////////////////////////////////////////// public void insertRecord(final int selectedRow) { insertRecord(selectedRow, createEmptyRecord()); } /** * Insert record. * * @param row the row * @param record the record */ // ///////////////////////////////////////////////////////// public void insertRecord(final int row, final JKTableRecord record) { this.records.insertElementAt(record, row); fireTableRowsInserted(row, row); } /** * Checks if is all data valid. * * @return true, if is all data valid */ // ///////////////////////////////////////////////////////// public boolean isAllDataValid() { // Make this method smatert for (final JKTableColumn col : this.tableColumns) { final int lastRow = getRowCount() - 1; if (col.isVisible() && col.isRequired()) { final Object colValue = getValueAt(lastRow, col.getIndex()); if (colValue == null || colValue.toString().equals("")) { return false;// dont allow } } } return true; } /** * Checks if is allow delete. * * @return true, if is allow delete */ // ////////////////////////////////////////////////////////////////////// public boolean isAllowDelete() { return this.allowDelete || isEditable(); } /** * Checks if is data modified. * * @return true, if is data modified */ // ///////////////////////////////////////////////////////// public boolean isDataModified() { if (this.deletedRecords.size() > 0) { return true; } for (final JKTableRecord rec : this.records) { if (rec.getStatus() == RecordStatus.MODIFIED) { return true; } } return false; } /** * Checks if is editable. * * @return true, if is editable */ // ///////////////////////////////////////////////////////// public boolean isEditable() { // return true if any cell is editable for (final JKTableColumn col : this.tableColumns) { if (col.isEditable()) { return true; } } return false; } /** * Checks if is editable. * * @param column the column * @return true, if is editable */ // ///////////////////////////////////////////////////////// public boolean isEditable(final int column) { return getTableColumn(column).isEditable(); } /** * Checks if is editable. * * @param row the row * @param column the column * @return true, if is editable */ public boolean isEditable(final int row, final int column) { if (isEditable(column)) { final int actualIndex = getTableColumn(column).getIndex(); final JKTableRecord record = getRecord(row); return record.isColumnEnabled(actualIndex); } return false; } /** * Checks if is numeric clumn. * * @param visibleColIndex the visible col index * @return true, if is numeric clumn */ // /////////////////////////////////////////////////////////////////////////////////////// public boolean isNumericClumn(final int visibleColIndex) { return getTableColumn(visibleColIndex).isNumeric(); } /** * Checks if is valid table column index. * * @param actualIndex the actual index * @return true, if is valid table column index */ // ///////////////////////////////////////////////////////// protected boolean isValidTableColumnIndex(final int actualIndex) { return actualIndex >= 0 && actualIndex < this.tableColumns.size(); } /** * Checks if is visible. * * @param col the col * @return true, if is visible */ // ///////////////////////////////////////////////////////////////////// public boolean isVisible(final int col) { return getTableColumn(col).isVisible(); } /** * Refresh visibility. */ public void refreshVisibility() { this.visibilityManager.refreshVisibility(); fireTableStructureChanged(); } // ///////////////////////////////////////////////////////////////////// /** * Removes the record. * * @param row the row * @return the JK table record */ // ///////////////////////////////////////////////////////// public JKTableRecord removeRecord(final int row) { return this.records.remove(row); } /** * Reset records. */ // /////////////////////////////////////////////////////////////////// public void resetRecords() { this.records.clear(); // fireTableDataChanged(); } /** * Sets the allow delete. * * @param allowDelete the new allow delete */ // ////////////////////////////////////////////////////////////////////// public void setAllowDelete(final boolean allowDelete) { this.allowDelete = allowDelete; } /** * Sets the column value. * * @param row the row * @param col the col * @param value the value * @param visibleIndex the visible index */ // ////////////////////////////////////////////////////////////////////////////////// public void setColumnValue(final int row, final int col, final Object value, final boolean visibleIndex) { int actualColumn = col; if (visibleIndex) { actualColumn = getActualColumnIndexFromVisible(col); } getRecord(row).setColumnValue(actualColumn, value); fireTableCellUpdated(row, col); } /** * Sets the editable. * * @param editable the new editable */ // ///////////////////////////////////////////////////////// public void setEditable(final boolean editable) { for (final JKTableColumn col : this.tableColumns) { col.setEditable(editable); } } /** * Sets the editable. * * @param column the column * @param editable the editable */ // ///////////////////////////////////////////////////////// public void setEditable(final int column, final boolean editable) { getTableColumn(column).setEditable(editable); } /** * Sets the editable. * * @param row the row * @param col the col * @param enable the enable */ public void setEditable(final int row, final int col, final boolean enable) { final int actualIndex = getTableColumn(col).getIndex(); getRecord(row).setColumnEnabled(actualIndex, enable); } /** * Sets the editor. * * @param colunm the colunm * @param cellEditor the cell editor */ // ///////////////////////////////////////////////////////// public void setEditor(final int colunm, final TableCellEditor cellEditor) { getTableColumn(colunm).setEditor(cellEditor); } /** * Sets the formatter. * * @param col the col * @param formatter the formatter */ // ///////////////////////////////////////////////////////// public void setFormatter(final int col, final Format formatter) { getTableColumn(col).setFormatter(formatter); } /** * Sets the preferred width. * * @param col the col * @param width the width */ // ///////////////////////////////////////////////////////// public void setPreferredWidth(final int col, final int width) { getTableColumn(col).setPreferredWidth(width); } /** * Sets the renderer. * * @param col the col * @param cellRenderer the cell renderer */ // ///////////////////////////////////////////////////////// public void setRenderer(final int col, final TableCellRenderer cellRenderer) { getTableColumn(col).setRenderer(cellRenderer); } /** * Sets the required. * * @param col the col * @param required the required */ // ///////////////////////////////////////////////////////// public void setRequired(final int col, final boolean required) { getTableColumn(col).setRequired(required); } /* * (non-Javadoc) * * @see javax.swing.table.AbstractTableModel#setValueAt(java.lang.Object, int, * int) */ // ///////////////////////////////////////////////////////// @Override public void setValueAt(final Object value, final int rowIndex, final int visibleIndex) { final int actualColIndex = this.visibilityManager.getActualIndexFromVisibleIndex(visibleIndex); final JKTableRecord record = this.records.get(rowIndex); record.setColumnValue(actualColIndex, value); record.setStatus(RecordStatus.MODIFIED); fireTableCellUpdated(rowIndex, visibleIndex); this.modified = true; } /** * Sets the visible. * * @param col the col * @param visible the visible */ // ///////////////////////////////////////////////////////// public void setVisible(final int col, final boolean visible) { getTableColumn(col).setVisible(visible); refreshVisibility(); } /** * Sets the visible by actual index. * * @param colunmIndex the colunm index * @param visible the visible */ // ////////////////////////////////////////////////////////////////////// public void setVisibleByActualIndex(final int colunmIndex, final boolean visible) { getTableColumn(colunmIndex, false).setVisible(visible); refreshVisibility(); } /** * Adds the JK table column. * * @param keyLabel the key label */ public void addJKTableColumn(String keyLabel) { JKTableColumn col = new JKTableColumn(); col.setName(keyLabel); addJKTableColumn(col); } }
{ "content_hash": "dd3109e7607dd3c3a7697c4d865cc3b6", "timestamp": "", "source": "github", "line_count": 1003, "max_line_length": 107, "avg_line_length": 26.94416749750748, "alnum_prop": 0.5299537465309898, "repo_name": "kiswanij/jk-util", "id": "6d48df5f899e2a07b0d6208929d6f7b4fefab99b", "size": "27674", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/jk/util/model/table/JKTableModel.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "579106" } ], "symlink_target": "" }
require 'rubygems' require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end require 'test/unit' require 'shoulda' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'elo_ratings' class Test::Unit::TestCase include EloRatings end
{ "content_hash": "d787541072d4d8895b4b73c8ace29367", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 66, "avg_line_length": 23.842105263157894, "alnum_prop": 0.7284768211920529, "repo_name": "phillc/elo-ratings", "id": "ef430e1f016560d14d5456701b6c29c0345c02d1", "size": "453", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "60711" }, { "name": "C++", "bytes": "162936" }, { "name": "Ruby", "bytes": "10731" } ], "symlink_target": "" }
<html> <head> <meta name="description" content="Pmw - a toolkit for building high-level compound widgets in Python"> <meta name="content" content="python, megawidget, mega widget, compound widget, gui, tkinter"> <title>Pmw functions reference manual</title> </head> <body bgcolor="#ffffff" text="#000000" link="#0000ee" vlink="551a8b" alink="ff0000"> <h1 ALIGN="CENTER">Pmw functions</h1> <dl> <dt> <strong>Pmw.aboutcontact</strong>(<em>value</em>)</dt><dd> <p> The value passed to this function is used to construct the text displayed by <a href="AboutDialog.html">Pmw.AboutDialog</a> megawidgets created subsequently.</p> <p></p> </dd> <dt> <strong>Pmw.aboutcopyright</strong>(<em>value</em>)</dt><dd> <p> The value passed to this function is used to construct the text displayed by <a href="AboutDialog.html">Pmw.AboutDialog</a> megawidgets created subsequently.</p> <p></p> </dd> <dt> <strong>Pmw.aboutversion</strong>(<em>value</em>)</dt><dd> <p> The value passed to this function is used to construct the text displayed by <a href="AboutDialog.html">Pmw.AboutDialog</a> megawidgets created subsequently.</p> <p></p> </dd> <dt> <strong>Pmw.aligngrouptags</strong>(<em>groups</em>)</dt><dd> <p> This function takes a sequence of <a href="Group.html">Pmw.Group</a>s and adjusts the vertical position of the tags in each group so that they all have the height of the tallest tag. This can be used when groups are positioned side-by-side but the natural height of the tags are different because, for example, different fonts with different sizes are used.</p> <p></p> </dd> <dt> <strong>Pmw.alignlabels</strong>(<em>widgets</em>, <em>sticky</em> = <strong>None</strong>)</dt><dd> <p> Adjust the size of the labels of all the <em>widgets</em> to be equal, so that the body of each widget lines up vertically. This assumes that each widget is a megawidget with a <strong>label</strong> component in column 0 (ie, the <strong>labelpos</strong> option was set to <strong>'w'</strong>, <strong>'wn'</strong> or <strong>'ws'</strong>). If <em>sticky</em> is set to a combination of <strong>'n'</strong>, <strong>'s'</strong>, <strong>'e'</strong> and <strong>'w'</strong>, the label will be positioned within its cell accordingly. For example to make labels right justified, set <em>sticky</em> to <strong>'e'</strong>, <strong>'ne'</strong> or <strong>'se'</strong>.</p> <p></p> </dd> <dt> <strong>Pmw.alphabeticvalidator</strong>(<em>text</em>)</dt><dd> <p> Validator function for <a href="EntryField.html">Pmw.EntryField</a> <strong>alphabetic</strong> standard validator.</p> <p></p> </dd> <dt> <strong>Pmw.alphanumericvalidator</strong>(<em>text</em>)</dt><dd> <p> Validator function for <a href="EntryField.html">Pmw.EntryField</a> <strong>alphanumeric</strong> standard validator.</p> <p></p> </dd> <dt> <strong>Pmw.busycallback</strong>(<em>command</em>, <em>updateFunction</em> = <strong>None</strong>)</dt><dd> <p> Create a wrapper function which displays a busy cursor while executing <em>command</em> and return the wrapper. When the wrapper function is called, it first calls <code>Pmw.showbusycursor()</code>, then the <em>command</em> (passing any arguments to it), then <code>Pmw.hidebusycursor()</code>. The return value of <em>command</em> is returned from the wrapper.</p> <p> If <em>updateFunction</em> is specified, it is called just before the call to <code>Pmw.hidebusycursor()</code>. This is intended to be the Tkinter <code>update()</code> method, in which case it will clear any events that may have occurred while <em>command</em> was executing. An example of this usage is in the <code>ShowBusy</code> demonstration: run the demonstration, click on the entry widget then click on the button and type some characters while the busy cursor is displayed. No characters should appear in the entry widget.</p> <p> Note that the Tkinter <code>update()</code> method should only be called when it is known that it can be safely called. One case where a problem has been found is when a filehandler has been created (on a non-blocking Oracle database connection), but the filehandler does not read from the connection. The connection is read (by a call to the Oracle fetch function <em>ofen</em>) in a loop which also contains a call to <code>_tkinter.dooneevent()</code>. If <code>update()</code> is called from <code>dooneevent()</code> and there is data to be read on the connection, then the filehandler will be called continuously, thus hanging the application.</p> <p></p> </dd> <dt> <strong>Pmw.clearbusycursor</strong>()</dt><dd> <p> Unconditionally remove the event block and busy cursor from all windows. This undoes all outstanding calls to <code>Pmw.showbusycursor()</code>.</p> <p></p> </dd> <dt> <strong>Pmw.datestringtojdn</strong>(<em>text</em>, <em>format</em> = <strong>'ymd'</strong>, <em>separator</em> = <strong>'/'</strong>)</dt><dd> <p> Return the Julian Day Number corresponding to the date in <em>text</em>. A Julian Day Number is defined as the number of days since 1 Jan 4713 BC. The date must be specified as three integers separated by the <em>separator</em> character. The integers must be in the order specified by <em>format</em>, which must be a combination of <strong>'d'</strong>, <strong>'m'</strong> and <strong>'y'</strong> in any order. These give the order of the day, month and year fields. Examples of valid input are:</p> <dl><dd><pre> 'dmy': 31/01/99 31/1/1999 31/1/99 'mdy': 01/31/99 1/31/1999 1/31/99 'ymd': 99/01/31 1999/1/31 99/1/31</pre></dd></dl> <p> If the application's <em>pivot</em> year (default 50) is not <strong>None</strong> and the year specified in <em>text</em> has only one or two digits, then the year is converted to a four digit year. If it is less than or equal to the pivot year, then it is incremented by the application's <em>century</em> value (default 2000). If it is more than the pivot year then it is incremented by the <em>century</em> value less 100.</p> <p> The function <code>Pmw.setyearpivot()</code> can be used to change the default values for the application's <em>pivot</em> and <em>century</em>.</p> <p></p> </dd> <dt> <strong>Pmw.datevalidator</strong>(<em>text</em>, <em>format</em> = <strong>'ymd'</strong>, <em>separator</em> = <strong>'/'</strong>)</dt><dd> <p> Validator function for <a href="EntryField.html">Pmw.EntryField</a> <strong>date</strong> standard validator.</p> <p></p> </dd> <dt> <strong>Pmw.displayerror</strong>(<em>text</em>)</dt><dd> <p> This is a general purpose method for displaying background errors to the user. The errors would normally be programming errors and may be caused by errors in Tk callbacks or functions called by other asynchronous events.</p> <p> If the global error report file (set by calling <code>Pmw.reporterrorstofile()</code>) is <strong>None</strong>, the error message `text` is written to standard error and also shown in a text window. If <code>displayerror</code> is called while previous error messages are being displayed, the window is raised and the new error is queued. The queued errors may be viewed by the user or ignored by dismissing the window.</p> <p> If the global error report file is not <strong>None</strong>, `text` is written to the file. <em>file</em> may be any object with a <code>write()</code> method, such as <code>sys.stderr</code>.</p> <p></p> </dd> <dt> <strong>Pmw.drawarrow</strong>(<em>canvas</em>, <em>color</em>, <em>direction</em>, <em>tag</em>, <em>baseOffset</em> = <strong>0.25</strong>, <em>edgeOffset</em> = <strong>0.15</strong>)</dt><dd> <p> Draw a triangle in the Tkinter.Canvas <em>canvas</em> in the given <em>color</em>. The value of <em>direction</em> may be <strong>'up'</strong>, <strong>'down'</strong>, <strong>'left'</strong> or <strong>'right'</strong> and specifies which direction the arrow should point. The values of <em>baseOffset</em> and <em>edgeOffset</em> specify how far from the edges of the canvas the points of the triangles are as a fraction of the size of the canvas.</p> <p></p> </dd> <dt> <strong>Pmw.forwardmethods</strong>(<em>fromClass</em>, <em>toClass</em>, <em>toPart</em>, <em>exclude</em> = <strong>()</strong>)</dt><dd> <p> Forward methods from one class to another.</p> <p> This function adds methods to the class <em>fromClass</em>. The names of the methods added are the names of the methods of the class <em>toClass</em> (and its base classes) except those which are already defined by <em>fromClass</em> or are found in the <em>exclude</em> list. Special methods with one or more leading or trailing underscores are also excluded.</p> <p> When one of the added methods is called, the method of the same name is called on an instance defined by <em>toPart</em> and the return value passed back. If <em>toPart</em> is a string, then it specifies the name of an attribute (<em>not</em> a component) of the <em>fromClass</em> object. The class of this attribute should be <em>toClass</em>. If <em>toPart</em> is not a string, it must be a function taking a <em>fromClass</em> object and returning a <em>toClass</em> object.</p> <p> This function must be called outside of and after the definition of <em>fromClass</em>.</p> <p> For example:</p> <dl><dd><pre>class MyClass: def __init__(self): ... self.__target = TargetClass() ... def foo(self): pass def findtarget(self): return self.__target Pmw.forwardmethods(MyClass, TargetClass, '__target', ['dangerous1', 'dangerous2']) # ...or... Pmw.forwardmethods(MyClass, TargetClass, MyClass.findtarget, ['dangerous1', 'dangerous2'])</pre></dd></dl> <p> In both cases, all <code>TargetClass</code> methods will be forwarded from <code>MyClass</code> except for <code>dangerous1</code>, <code>dangerous2</code>, special methods like <code>__str__</code>, and pre-existing methods like <code>foo</code>.</p> <p></p> </dd> <dt> <strong>Pmw.grabstacktopwindow</strong>()</dt><dd> <p> Return the window at the top of the grab stack (the window currently with the grab) or <strong>None</strong> if the grab stack is empty (no window has the grab). See also <code>pushgrab()</code>.</p> <p></p> </dd> <dt> <strong>Pmw.hexadecimalvalidator</strong>(<em>text</em>)</dt><dd> <p> Validator function for <a href="EntryField.html">Pmw.EntryField</a> <strong>hexadecimal</strong> standard validator.</p> <p></p> </dd> <dt> <strong>Pmw.hidebusycursor</strong>(<em>forceFocusRestore</em> = <strong>0</strong>)</dt><dd> <p> Undo one call to <code>Pmw.showbusycursor()</code>. If there are no outstanding calls to <code>Pmw.showbusycursor()</code>, remove the event block and busy cursor.</p> <p> If the focus window has not been changed since the corresponding call to <code>Pmw.showbusycursor()</code>, or if <em>forceFocusRestore</em> is true, then the focus is restored to that saved by <code>Pmw.showbusycursor()</code>.</p> <p></p> </dd> <dt> <strong>Pmw.initialise</strong>(<em>root</em> = <strong>None</strong>, <em>size</em> = <strong>None</strong>, <em>fontScheme</em> = <strong>None</strong>, <em>useTkOptionDb</em> = <strong>0</strong>, <em>noBltBusy</em> = <strong>0</strong>, <em>disableKeyboardWhileBusy</em> = <strong>None</strong>)</dt><dd> <p> Initialise Pmw. This performs several functions:</p> <ul><li><p>Set up a trap in the Tkinter Toplevel constructor so that a list of Toplevels can be maintained. A list of all Toplevel windows needs to be kept so that <code>Pmw.showbusycursor()</code> can create busy cursors for them.</p> </li> <li><p>Set up a trap in the Tkinter Toplevel and Frame destructors so that Pmw is notified when these widgets are destroyed. This allows Pmw to destroy megawidgets when their hull widget is destroyed and to prune the list of Toplevels.</p> </li> <li><p>Modify Tkinter's CallWrapper class to improve the display of errors which occur in callbacks. If an error occurs, the new CallWrapper class calls <code>Pmw.clearbusycursor()</code> to remove any outstanding busy cursors and calls <code>Pmw.displayerror()</code> to display the error.</p> </li> <li><p>Using the window given by <em>root</em>, set the <strong>WM_DELETE_WINDOW</strong> root window protocol to destroy the root window. This means that the root window is destroyed if the window manager deletes it. This is only done if the protocol has not been set before the call to <code>Pmw.initialise()</code>. This protocol is required if there is a modal dialog displayed and the window manager deletes the root window. Otherwise the application will not exit, even though there are no windows.</p> </li> <li><p>Set the base font size for the application to <em>size</em>. This is used by <code>Pmw.logicalfont()</code> as the default point size for fonts. If this is not given, the default is <strong>14</strong>, except under NT where it is <strong>16</strong>. These are reasonable default sizes for most screens, but for unusually high or low screen resolutions, an appropriate size should be supplied. Note that Tk's definition of <em>point size</em>, is somewhat idiosyncratic.</p> </li> <li><p>Set the Tk option database for <em>root</em> according to <em>fontScheme</em>. This changes the default fonts set by Tk. <em>fontScheme</em> may be one of</p> <dl><dt><strong>None</strong> </dt><dd>Do not change the Tk defaults.<p></p> </dd> <dt><strong>'pmw1'</strong> </dt><dd>If running under posix (Unix), set the default font to be Helvetica with bold italic menus, italic scales and a special balloon font 6 points smaller than the base font size and with the <strong>'pixel'</strong> field set to <strong>'12'</strong>. For other operating systems (such as NT or Macintosh), simply set the default font to be Helvetica. All fonts are as returned by calls to <code>Pmw.logicalfont()</code>.<p></p> </dd> <dt><strong>'pmw2'</strong> </dt><dd>This is the same as <strong>'pmw1'</strong> except that under posix the balloon font is 2 points smaller than the base font size and the <strong>'pixel'</strong> field is not set.<p></p> </dd> <dt><strong>'default'</strong> </dt><dd>This sets the default fonts using the Tk font naming convention, rather than that returned by <code>Pmw.logicalfont()</code>. The default font is bold Helvetica. The font for entry widgets is Helvetica. The font for text widgets is Courier The size of all fonts is the application base font size as described above.<p></p> </dd></dl> </li> <li><p>If <em>root</em> is <strong>None</strong>, use the Tkinter default root window as the root, if it has been created, or create a new Tk root window. The <code>initialise()</code> method returns this <em>root</em>.</p> </li> <li><p>If <em>useTkOptionDb</em> is true, then, when a megawidget is created, the Tk option database will be queried to get the initial values of the options which have not been set in the call to the constructor. The resource name used in the query is the same as the option name and the resource class is the option name with the first letter capitalised. If <em>useTkOptionDb</em> is false, then options for newly created megawidgets will be initialised to default values.</p> </li> <li><p>If <em>noBltBusy</em> is true, then <code>Pmw.showbusycursor()</code> will not display a busy cursor, even if the BLT busy command is present.</p> </li> <li><p>If <em>disableKeyboardWhileBusy</em> is false, then do not disable keyboard input while displaying the busy cursor. Normally, Pmw ignores keyboard input while displaying the busy cursor by setting the focus for each toplevel window to the Blt busy window. However, under NT, this may cause the toplevel windows to be raised. If this is not acceptable, programs running on NT can request show/hidebusycursor to not ignore keyboard input by setting <em>disableKeyboardWhileBusy</em> to true in <code>Pmw.initialise()</code>.</p> </li></ul> <p> It is not absolutely necessary to call this function to be able to use Pmw. However, some functionality will be lost. Most importantly, Pmw megawidgets will not be notified when their hull widget is destroyed. This may prevent the megawidget from cleaning up timers which will try to access the widget, hence causing a background error to occur.</p> <p></p> </dd> <dt> <strong>Pmw.installedversions</strong>(<em>alpha</em> = <strong>0</strong>)</dt><dd> <p> If <em>alpha</em> is false, return the list of base versions of Pmw that are currently installed and available for use. If <em>alpha</em> is true, return the list of alpha versions.</p> <p></p> </dd> <dt> <strong>Pmw.integervalidator</strong>(<em>text</em>)</dt><dd> <p> Validator function for <a href="EntryField.html">Pmw.EntryField</a> <strong>integer</strong> standard validator.</p> <p></p> </dd> <dt> <strong>Pmw.jdntoymd</strong>(<em>jdn</em>, <em>julian</em> = <strong>-1</strong>, <em>papal</em> = <strong>1</strong>)</dt><dd> <p> Return the year, month and day of the Julian Day Number <em>jdn</em>. If <em>julian</em> is <strong>1</strong>, then the date returned will be in the Julian calendar. If <em>julian</em> is <strong>0</strong>, then the date returned will be in the modern calendar. If <em>julian</em> is <strong>-1</strong>, then which calendar to use will be automatically determined by the value of <em>jdn</em> and <em>papal</em>. If <em>papal</em> is true, then the date set by Pope Gregory XIII's decree (4 October 1582) will be used as the last day to use the Julian calendar. If <em>papal</em> is false, then the last day to use the Julian calendar will be according to British-American usage (2 September 1752).</p> <p></p> </dd> <dt> <strong>Pmw.logicalfont</strong>(<em>name</em> = <strong>'Helvetica'</strong>, <em>sizeIncr</em> = <strong>0</strong>, **<em>kw</em>)</dt><dd> <p> Return the full name of a Tk font, being a hyphen-separated list of font properties. The <em>logical</em> name of the font is given by <em>name</em> and may be one of <strong>'Helvetica'</strong>, <strong>'Times'</strong>, <strong>'Fixed'</strong>, <strong>'Courier'</strong> or <strong>'Typewriter'</strong>. Pmw uses this name to define the default values of many of the font properties. The size of the font is the base font size for the application specified in the call to <code>Pmw.initialise()</code> increased or decreased by the value of <em>sizeIncr</em>. The other properties of the font may be specified by other named arguments. These may be <strong>'registry'</strong>, <strong>'foundry'</strong>, <strong>'family'</strong>, <strong>'weight'</strong>, <strong>'slant'</strong>, <strong>'width'</strong>, <strong>'style'</strong>, <strong>'pixel'</strong>, <strong>'size'</strong>, <strong>'xres'</strong>, <strong>'yres'</strong>, <strong>'spacing'</strong>, <strong>'avgwidth'</strong>, <strong>'charset'</strong> and <strong>'encoding'</strong>.</p> <p></p> </dd> <dt> <strong>Pmw.logicalfontnames</strong>()</dt><dd> <p> Return the list of known logical font names that can be given to <code>Pmw.logicalfont()</code>.</p> <p></p> </dd> <dt> <strong>Pmw.numericvalidator</strong>(<em>text</em>)</dt><dd> <p> Validator function for <a href="EntryField.html">Pmw.EntryField</a> <strong>numeric</strong> standard validator.</p> <p></p> </dd> <dt> <strong>Pmw.popgrab</strong>(<em>window</em>)</dt><dd> <p> Remove <em>window</em> from the grab stack. If there are not more windows in the grab stack, release the grab. Otherwise set the grab and the focus to the next window in the grab stack. See also <code>pushgrab()</code>.</p> <p></p> </dd> <dt> <strong>Pmw.pushgrab</strong>(<em>grabWindow</em>, <em>globalMode</em>, <em>deactivateFunction</em>)</dt><dd> <p> The grab functions (<code>pushgrab()</code>, <code>popgrab()</code>, <code>releasegrabs()</code> and <code>grabstacktopwindow()</code>) are an interface to the Tk <strong>grab</strong> command which implements simple pointer and keyboard grabs. When a grab is set for a particular window, Tk restricts all pointer events to the grab window and its descendants in Tk's window hierarchy. The functions are used by the <code>activate()</code> and <code>deactivate()</code> methods to implement modal dialogs.</p> <p> Pmw maintains a stack of grabbed windows, where the window on the top of the stack is the window currently with the grab. The grab stack allows nested modal dialogs, where one modal dialog can be activated while another modal dialog is activated. When the second dialog is deactivated, the first dialog becomes active again.</p> <p> Use <code>pushgrab()</code> to add <em>grabWindow</em> to the grab stack. This releases the grab by the window currently on top of the stack (if there is one) and gives the grab and focus to the <em>grabWindow</em>. If <em>globalMode</em> is true, perform a global grab, otherwise perform a local grab. The value of <em>deactivateFunction</em> specifies a function to call (usually grabWindow.deactivate) if popgrab() is called (usually from a deactivate() method) on a window which is not at the top of the stack (that is, does not have the grab or focus). For example, if a modal dialog is deleted by the window manager or deactivated by a timer. In this case, all dialogs above and including this one are deactivated, starting at the top of the stack.</p> <p> For more information, see the Tk grab manual page.</p> <p></p> </dd> <dt> <strong>Pmw.realvalidator</strong>(<em>text</em>, <em>separator</em> = <strong>'.'</strong>)</dt><dd> <p> Validator function for <a href="EntryField.html">Pmw.EntryField</a> <strong>real</strong> standard validator.</p> <p></p> </dd> <dt> <strong>Pmw.releasegrabs</strong>()</dt><dd> <p> Release grab and clear the grab stack. This should normally not be used, use <code>popgrab()</code> instead. See also <code>pushgrab()</code>.</p> <p></p> </dd> <dt> <strong>Pmw.reporterrorstofile</strong>(<em>file</em> = <strong>None</strong>)</dt><dd> <p> Sets the global error report file, which is initially <strong>None</strong>. See <code>Pmw.displayerror()</code></p> <p></p> </dd> <dt> <strong>Pmw.setalphaversions</strong>(*<em>alpha_versions</em>)</dt><dd> <p> Set the list of alpha versions of Pmw to use for this session to the arguments. When searching for Pmw classes and functions, these alpha versions will be searched, in the order given, before the base version. This must be called before any other Pmw class or function, except functions setting or querying versions.</p> <p></p> </dd> <dt> <strong>Pmw.setbusycursorattributes</strong>(<em>window</em>, **<em>kw</em>)</dt><dd> <p> Use the keyword arguments to set attributes controlling the effect on <em>window</em> (which must be a <strong>Tkinter.Toplevel</strong>) of future calls to <code>Pmw.showbusycursor()</code>. The attributes are:</p> <dl><dt><strong>exclude</strong></dt><dd>a boolean value which specifies whether the window will be affected by calls to <code>Pmw.showbusycursor()</code>. If a window is excluded, then the cursor will not be changed to a busy cursor and events will still be delivered to the window. By default, windows are affected by calls to <code>Pmw.showbusycursor()</code>.<p></p> </dd> <dt><strong>cursorName</strong></dt><dd>the name of the cursor to use when displaying the busy cursor. If <strong>None</strong>, then the default cursor is used.<p></p> </dd></dl> <p></p> </dd> <dt> <strong>Pmw.setgeometryanddeiconify</strong>(<em>window</em>, <em>geom</em>)</dt><dd> <p> Deiconify and raise the toplevel <em>window</em> and set its position and size according to <em>geom</em>. This overcomes some problems with the window flashing under X and correctly positions the window under NT (caused by Tk bugs).</p> <p></p> </dd> <dt> <strong>Pmw.setversion</strong>(<em>version</em>)</dt><dd> <p> Set the version of Pmw to use for this session to <em>version</em>. If <code>Pmw.setversion()</code> is not called, the latest installed version of Pmw will be used. This must be called before any other Pmw class or function, except functions setting or querying versions.</p> <p></p> </dd> <dt> <strong>Pmw.setyearpivot</strong>(<em>pivot</em>, <em>century</em> = <strong>None</strong>)</dt><dd> <p> Set the pivot year and century for the application's date processing. These values are used in the <code>datestringtojdn()</code> method, which is used by <a href="Counter.html">Pmw.Counter</a> and <a href="EntryField.html">Pmw.EntryField</a> and derived classes. The initial values of <em>pivot</em> and <em>century</em> are <strong>50</strong> and <strong>2000</strong> repectively. Return a tuple containing the old values of <em>pivot</em> and <em>century</em>.</p> <p></p> </dd> <dt> <strong>Pmw.showbusycursor</strong>()</dt><dd> <p> Block events to and display a busy cursor over all windows in this application that are in the state <strong>'normal'</strong> or <strong>'iconic'</strong>, except those windows whose <strong>exclude</strong> busycursor attribute has been set to true by a call to <code>Pmw.setbusycursorattributes()</code>.</p> <p> If a window and its contents have just been created, <code>update_idletasks()</code> may have to be called before <code>Pmw.showbusycursor()</code> so that the window is mapped to the screen. Windows created or deiconified after calling <code>Pmw.showbusycursor()</code> will not be blocked.</p> <p> To unblock events and remove the busy cursor, use <code>Pmw.hidebusycursor()</code>. Nested calls to <code>Pmw.showbusycursor()</code> may be made. In this case, a matching number of calls to <code>Pmw.hidebusycursor()</code> must be made before the event block and busy cursor are removed.</p> <p> If the BLT extension to Tk is not present, this function has no effect other than to save the value of the current focus window, to be later restored by <code>Pmw.hidebusycursor()</code>.</p> <p></p> </dd> <dt> <strong>Pmw.stringtoreal</strong>(<em>text</em>, <em>separator</em> = <strong>'.'</strong>)</dt><dd> <p> Return the real number represented by <em>text</em>. This is similar to <code>string.atof()</code> except that the character representing the decimal point in <em>text</em> is given by <em>separator</em>.</p> <p></p> </dd> <dt> <strong>Pmw.timestringtoseconds</strong>(<em>text</em>, <em>separator</em> = <strong>':'</strong>)</dt><dd> <p> Return the number of seconds corresponding to the time in <em>text</em>. The time must be specified as three integers separated by the <em>separator</em> character and must be in the order hours, minutes and seconds. The first number may be negative, indicating a negative time.</p> <p></p> </dd> <dt> <strong>Pmw.timevalidator</strong>(<em>text</em>, <em>separator</em> = <strong>':'</strong>)</dt><dd> <p> Validator function for <a href="EntryField.html">Pmw.EntryField</a> <strong>time</strong> standard validator.</p> <p></p> </dd> <dt> <strong>Pmw.tracetk</strong>(<em>root</em> = <strong>None</strong>, <em>on</em> = <strong>1</strong>, <em>withStackTrace</em> = <strong>0</strong>, <em>file</em> = <strong>None</strong>)</dt><dd> <p> Print debugging trace of calls to, and callbacks from, the Tk interpreter associated with the <em>root</em> window . If <em>root</em> is <strong>None</strong>, use the Tkinter default root. If <em>on</em> is true, start tracing, otherwise stop tracing. If <em>withStackTrace</em> is true, print a python function call stacktrace after the trace for each call to Tk. If <em>file</em> is <strong>None</strong>, print to standard error, otherwise print to the file given by <em>file</em>.</p> <p> For each call to Tk, the Tk command and its options are printed as a python tuple, followed by the return value of the command (if not the empty string). For example:</p> <dl><dd><pre>python executed: button = Tkinter.Button() button.configure(text = 'Hi') tracetk output: CALL TK&gt; 1: ('button', '.3662448') -&gt; '.3662448' CALL TK&gt; 1: ('.3662448', 'configure', '-text', 'Hi')</pre></dd></dl> <p> Some calls from python to Tk (such as <strong>update</strong>, <strong>tkwait</strong>, <strong>invoke</strong>, etc) result in the execution of callbacks from Tk to python. These python callbacks can then recursively call into Tk. When displayed by <strong>tracetk()</strong>, these recursive calls are indented proportionally to the depth of recursion. The depth is also printed as a leading number. The return value of a call to Tk which generated recursive calls is printed on a separate line at the end of the recursion. For example:</p> <dl><dd><pre>python executed: def callback(): button.configure(text = 'Bye') return 'Got me!' button = Tkinter.Button() button.configure(command = callback) button.invoke()</pre></dd></dl> <dl><dd><pre>tracetk output: CALL TK&gt; 1: ('button', '.3587144') -&gt; '.3587144' CALL TK&gt; 1: ('.3587144', 'configure', '-command', '3638368callback') CALL TK&gt; 1: ('.3587144', 'invoke') CALLBACK&gt; 2: callback() CALL TK&gt; 2: ('.3587144', 'configure', '-text', 'Bye') CALL RTN&gt; 1: -&gt; 'Got me!'</pre></dd></dl> <p> <strong>Pmw.initialise()</strong> must be called before <strong>tracetk()</strong> so that hooks are put into the Tkinter CallWrapper class to trace callbacks from Tk to python and also to handle recursive calls correctly.</p> <p></p> </dd> <dt> <strong>Pmw.version</strong>(<em>alpha</em> = <strong>0</strong>)</dt><dd> <p> If <em>alpha</em> is false, return the base version of Pmw being used for this session. If <code>Pmw.setversion()</code> has not been called, this will be the latest installed version of Pmw. If <em>alpha</em> is true, return the list of alpha versions of Pmw being used for this session, in search order. If <code>Pmw.setalphaversions()</code> has not been called, this will be the empty list.</p> <p></p> </dd> <dt> <strong>Pmw.ymdtojdn</strong>(<em>year</em>, <em>month</em>, <em>day</em>, <em>julian</em> = <strong>-1</strong>, <em>papal</em> = <strong>1</strong>)</dt><dd> <p> Return the Julian Day Number corresponding to <em>year</em>, <em>month</em> and <em>day</em>. See <code>jdntoymd()</code> for description of other arguments)</p> <p></p> </dd> </dl> <center><P ALIGN="CENTER"> <IMG SRC = blue_line.gif ALT = "" WIDTH=320 HEIGHT=5> </p></center> <font size=-1> <center><P ALIGN="CENTER"> Pmw 1.3 - 7 Aug 2007 - <a href="index.html">Home</a> </p></center> </font> </body> </html>
{ "content_hash": "e25d04e4f5799c4dfd363269584697b6", "timestamp": "", "source": "github", "line_count": 765, "max_line_length": 313, "avg_line_length": 42.257516339869284, "alnum_prop": 0.6721007207597365, "repo_name": "eflowbeach/draw-your-taf", "id": "628fea4110f7bb7fa0a3ea8b16be2c5f4f8ac61f", "size": "32328", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pmw/Pmw_1_3/doc/PmwFunctions.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "646416" }, { "name": "Python", "bytes": "795255" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <Package xmlns="http://schemas.microsoft.com/appx/2010/manifest" xmlns:build="http://schemas.microsoft.com/developer/appx/2012/build" IgnorableNamespaces="build"> <!-- THIS PACKAGE MANIFEST FILE IS GENERATED BY THE BUILD PROCESS. Changes to this file will be lost when it is regenerated. To correct errors in this file, edit the source .appxmanifest file. For more information on package manifest files, see http://go.microsoft.com/fwlink/?LinkID=241727 --> <Identity Name="SumoBlocks" Publisher="CN=DefaultCompany" Version="1.0.0.0" ProcessorArchitecture="x86" /> <Properties> <DisplayName>SumoBlocks</DisplayName> <PublisherDisplayName>DefaultCompany</PublisherDisplayName> <Logo>Assets\StoreLogo.png</Logo> </Properties> <Prerequisites> <OSMinVersion>6.3.0</OSMinVersion> <OSMaxVersionTested>6.3.0</OSMaxVersionTested> </Prerequisites> <Resources> <Resource Language="EN-US" /> </Resources> <Applications> <Application Id="App" Executable="Template.exe" EntryPoint="SumoBlocks.App"> <VisualElements DisplayName="SumoBlocks" Logo="Assets\SquareTile.png" SmallLogo="Assets\SmallTile.png" Description="SumoBlocks" ForegroundText="light" BackgroundColor="#000000"> <DefaultTile ShortName="SumoBlocks" ShowName="allLogos" /> <SplashScreen Image="Assets\SplashScreen.png" /> </VisualElements> </Application> </Applications> <Capabilities /> <Dependencies> <PackageDependency Name="Microsoft.VCLibs.120.00" MinVersion="12.0.21005.1" /> </Dependencies> <Extensions> <Extension Category="windows.activatableClass.inProcessServer"> <InProcessServer> <Path>UnityEngineDelegates.dll</Path> <ActivatableClass ActivatableClassId="UnityEngineDelegates.FunctionDefsDictionary" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="UnityEngineDelegates.PlatformInvoke" ThreadingModel="both" /> </InProcessServer> </Extension> <Extension Category="windows.activatableClass.inProcessServer"> <InProcessServer> <Path>UnityPlayer.dll</Path> <ActivatableClass ActivatableClassId="UnityPlayer.AppCallbacks" ThreadingModel="both" /> </InProcessServer> </Extension> <Extension Category="windows.activatableClass.inProcessServer"> <InProcessServer> <Path>CLRHost.dll</Path> <ActivatableClass ActivatableClassId="WinRTBridge.ScriptingClassWrapper" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.SerializationWriter" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.Marshalling" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.StringTools" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.UnityEngineObjectTools" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.TypeInformation" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.GCHandledObjects" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.GCHandles" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.ScriptingPinnedArray" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.SerializationReader" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.ExceptionHandling" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.MonoBehaviourSerialization" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.MethodTools" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.Utils" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.ObjectInstantiation" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.WinRTBridge" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.ArrayTools" ThreadingModel="both" /> <ActivatableClass ActivatableClassId="WinRTBridge.ScriptingMethodWrapper" ThreadingModel="both" /> </InProcessServer> </Extension> </Extensions> <build:Metadata> <build:Item Name="TargetFrameworkMoniker" Value=".NETCore,Version=v4.5.1" /> <build:Item Name="VisualStudio" Version="12.0" /> <build:Item Name="VisualStudioEdition" Value="Microsoft Visual Studio Ultimate 2013" /> <build:Item Name="OperatingSystem" Version="6.3.9600.16384 (winblue_rtm.130821-1623)" /> <build:Item Name="Microsoft.Build.AppxPackage.dll" Version="12.0.21005.1" /> <build:Item Name="Microsoft.Windows.UI.Xaml.Build.Tasks.dll" Version="12.0.21005.1" /> <build:Item Name="MakePri.exe" Version="6.3.9600.16384 (winblue_rtm.130821-1623)" /> </build:Metadata> </Package>
{ "content_hash": "311a8f7cd57e092b6984b5d842e4ebb6", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 183, "avg_line_length": 59.853658536585364, "alnum_prop": 0.7442950285248574, "repo_name": "ScruffyFurn/SumoBlocks", "id": "46e901902aca5a5318908c23e157c74877edd1a6", "size": "4910", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Windows Store Build/SumoBlocks/bin/x86/Master/AppxManifest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "56905" } ], "symlink_target": "" }
namespace boost { namespace unit_test { // ************************************************************************** // // ************** test_unit_fixture ************** // // ************************************************************************** // class BOOST_TEST_DECL test_unit_fixture { public: virtual ~test_unit_fixture() {} // Fixture interface virtual void setup() = 0; virtual void teardown() = 0; }; typedef shared_ptr<test_unit_fixture> test_unit_fixture_ptr; // ************************************************************************** // // ************** fixture helper functions ************** // // ************************************************************************** // namespace impl_fixture { #if defined(BOOST_NO_CXX11_DECLTYPE) || defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES) template<typename U, void (U::*)()> struct fixture_detect {}; template<typename T> struct has_setup { private: template<typename U> static char Test(fixture_detect<U, &U::setup>*); template<typename U> static int Test(...); public: static const bool value = sizeof(Test<T>(0)) == sizeof(char); }; template<typename T> struct has_teardown { private: template<typename U> static char Test(fixture_detect<U, &U::teardown>*); template<typename U> static int Test(...); public: static const bool value = sizeof(Test<T>(0)) == sizeof(char); }; #else template<typename U> struct fixture_detect { typedef char type; }; template<typename T> struct has_setup { private: template<typename U> static auto Test(U*) -> typename fixture_detect<decltype(boost::declval<U>().setup())>::type; template<typename U> static int Test(...); public: static const bool value = sizeof(Test<T>(0)) == sizeof(char); }; template<typename T> struct has_teardown { private: template<typename U> static auto Test(U*) -> typename fixture_detect<decltype(boost::declval<U>().teardown())>::type; template<typename U> static int Test(...); public: static const bool value = sizeof(Test<T>(0)) == sizeof(char); }; #endif template <bool has_setup = false> struct call_setup { template <class U> void operator()(U& ) { } }; template <> struct call_setup<true> { template <class U> void operator()(U& u) { u.setup(); } }; template <bool has_teardown = false> struct call_teardown { template <class U> void operator()(U& ) { } }; template <> struct call_teardown<true> { template <class U> void operator()(U& u) { u.teardown(); } }; } //! Calls the fixture "setup" if detected by the compiler, otherwise does nothing. template <class U> void setup_conditional(U& u) { return impl_fixture::call_setup<impl_fixture::has_setup<U>::value>()(u); } //! Calls the fixture "teardown" if detected by the compiler, otherwise does nothing. template <class U> void teardown_conditional(U& u) { return impl_fixture::call_teardown<impl_fixture::has_teardown<U>::value>()(u); } // ************************************************************************** // // ************** class_based_fixture ************** // // ************************************************************************** // template<typename F, typename Arg=void> class class_based_fixture : public test_unit_fixture { public: // Constructor explicit class_based_fixture( Arg const& arg ) : m_inst(), m_arg( arg ) {} private: // Fixture interface void setup() BOOST_OVERRIDE { m_inst.reset( new F( m_arg ) ); setup_conditional(*m_inst); } void teardown() BOOST_OVERRIDE { teardown_conditional(*m_inst); m_inst.reset(); } // Data members scoped_ptr<F> m_inst; Arg m_arg; }; //____________________________________________________________________________// template<typename F> class class_based_fixture<F,void> : public test_unit_fixture { public: // Constructor class_based_fixture() : m_inst( 0 ) {} private: // Fixture interface void setup() BOOST_OVERRIDE { m_inst.reset( new F ); setup_conditional(*m_inst); } void teardown() BOOST_OVERRIDE { teardown_conditional(*m_inst); m_inst.reset(); } // Data members scoped_ptr<F> m_inst; }; //____________________________________________________________________________// // ************************************************************************** // // ************** function_based_fixture ************** // // ************************************************************************** // class function_based_fixture : public test_unit_fixture { public: // Constructor function_based_fixture( boost::function<void ()> const& setup_, boost::function<void ()> const& teardown_ ) : m_setup( setup_ ) , m_teardown( teardown_ ) { } private: // Fixture interface void setup() BOOST_OVERRIDE { if( m_setup ) m_setup(); } void teardown() BOOST_OVERRIDE { if( m_teardown ) m_teardown(); } // Data members boost::function<void ()> m_setup; boost::function<void ()> m_teardown; }; } // namespace unit_test } // namespace boost #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_TEST_TREE_FIXTURE_HPP_100311GER
{ "content_hash": "dea4434c5718c5fed4ed0fbdaf8cb9d2", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 125, "avg_line_length": 33.676829268292686, "alnum_prop": 0.5082382762991128, "repo_name": "SketchUp/sketchup-ruby-debugger", "id": "a297ad9e9b32139dcd790d778d94cc73917713f1", "size": "6365", "binary": false, "copies": "16", "ref": "refs/heads/main", "path": "ThirdParty/include/boost/test/tree/fixture.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1079" }, { "name": "C", "bytes": "2639" }, { "name": "C++", "bytes": "80802" } ], "symlink_target": "" }
'use strict'; /* * hostProperties object module: * Holds data and/or conversion information about each hosting property. * Strongly coupled with hostMath.js */ // Library for arbitrary precision in numbers const BigNumber = require('bignumber.js'); // Ensure precision BigNumber.config({ DECIMAL_PLACES: 24 }); BigNumber.config({ EXPONENTIAL_AT: 1e+9 }); // Units // Bytes per GB const B_per_GB = new BigNumber('1e+9'); // Hastings per Siacoin const H_per_S = new BigNumber('1e+24'); // Blocks per Hour const BLOCKS_per_HOUR = new BigNumber(6); // Blocks per Day const BLOCKS_per_DAY = BLOCKS_per_HOUR.times(24); // Blocks per 30-day Month const BLOCKS_per_MONTH = BLOCKS_per_DAY.times(30); // Hastings per Siacoin (1e24) / B per GB (1e9) / Blocks per 30-day month (4320) const MONTHLY_DATA_COST = H_per_S.div(B_per_GB).div(BLOCKS_per_MONTH); // Exports organized information about all the host status properties var props = { anticipatedrevenue: { descr: 'Revenue to be Earned', unit: 'S', conversion: H_per_S, }, collateral: { descr: 'Collateral', unit: 'S/GB/month', conversion: MONTHLY_DATA_COST, }, lostrevenue: { descr: 'Revenue Lost', unit: 'S', conversion: H_per_S, }, maxduration: { descr: 'Maximum Duration', unit: 'Days', conversion: BLOCKS_per_DAY, }, minduration: { descr: 'Minimum Duration', unit: 'Days', conversion: BLOCKS_per_DAY, }, netaddress: { descr: 'Network Address', unit: 'IP Address', }, numcontracts: { descr: 'Number of File Contracts', unit: 'Contracts', }, price: { descr: 'Price', unit: 'S/GB/month', conversion: MONTHLY_DATA_COST, }, revenue: { descr: 'Revenue Earned', unit: 'S', conversion: H_per_S, }, storageremaining: { descr: 'Total Storage', unit: 'GB', conversion: B_per_GB, }, totalstorage: { descr: 'Total Storage', unit: 'GB', conversion: B_per_GB, }, unlockhash: { descr: 'Payout Address', unit: 'Hex', }, windowsize: { descr: 'Time Window for Storage Proof', unit: 'Hours', conversion: BLOCKS_per_HOUR, }, }; module.exports = props;
{ "content_hash": "74aa2cfbf11b5a41a07b5fb980811237", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 80, "avg_line_length": 21.989473684210527, "alnum_prop": 0.6634753470560076, "repo_name": "pmknutsen/Sia-UI", "id": "809017e3889e26df866f15222e8d830116c069b6", "size": "2089", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "plugins/Hosting/js/hostProperties.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16162" }, { "name": "HTML", "bytes": "15477" }, { "name": "JavaScript", "bytes": "124234" }, { "name": "Shell", "bytes": "2204" } ], "symlink_target": "" }
This is what you run on your computer. Make sure this runs FIRST before the client! NOTE: Unlike the client, you can run this on any OS you can build it on.
{ "content_hash": "bd880ca3f97def111a95941f357d5720", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 83, "avg_line_length": 52.666666666666664, "alnum_prop": 0.759493670886076, "repo_name": "Megalegacy98/TheUltimatePrankProgram", "id": "dcd8bfaaea37f58a5c7aefbc0896e03110fb25ac", "size": "167", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Server/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "7706" } ], "symlink_target": "" }
require 'formula' class Openfst < Formula homepage 'http://www.openfst.org/' url 'http://openfst.cs.nyu.edu/twiki/pub/FST/FstDownload/openfst-1.3.4.tar.gz' sha1 '21972c05896b2154a3fa1bdca5c9a56350194b38' def install ENV.libstdcxx if ENV.compiler == :clang && MacOS.version >= :mavericks system "./configure", "--prefix=#{prefix}", "--disable-dependency-tracking", "--enable-far", "--enable-pdt" system "make install" end end
{ "content_hash": "56c8a7099de59578025cb28b2f6f7b85", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 80, "avg_line_length": 32.9375, "alnum_prop": 0.5977229601518027, "repo_name": "JayBenzzz/homebrew", "id": "db60df0e10f1eb3756407bb522dfa1c72db223b9", "size": "527", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Library/Formula/openfst.rb", "mode": "33188", "license": "bsd-2-clause", "language": [], "symlink_target": "" }
import os import subprocess import signal import struct import csv try: import pandas except ImportError: pandas = None from wlauto import Instrument, Parameter, Executable from wlauto.exceptions import InstrumentError, ConfigError from wlauto.utils.types import list_of_numbers class EnergyProbe(Instrument): name = 'energy_probe' description = """Collects power traces using the ARM energy probe. This instrument requires ``caiman`` utility to be installed in the workload automation host and be in the PATH. Caiman is part of DS-5 and should be in ``/path/to/DS-5/bin/`` . Energy probe can simultaneously collect energy from up to 3 power rails. To connect the energy probe on a rail, connect the white wire to the pin that is closer to the Voltage source and the black wire to the pin that is closer to the load (the SoC or the device you are probing). Between the pins there should be a shunt resistor of known resistance in the range of 5 to 20 mOhm. The resistance of the shunt resistors is a mandatory parameter ``resistor_values``. .. note:: This instrument can process results a lot faster if python pandas is installed. """ parameters = [ Parameter('resistor_values', kind=list_of_numbers, default=[], description="""The value of shunt resistors. This is a mandatory parameter."""), Parameter('labels', kind=list, default=[], description="""Meaningful labels for each of the monitored rails."""), Parameter('device_entry', kind=str, default='/dev/ttyACM0', description="""Path to /dev entry for the energy probe (it should be /dev/ttyACMx)"""), ] MAX_CHANNELS = 3 def __init__(self, device, **kwargs): super(EnergyProbe, self).__init__(device, **kwargs) self.attributes_per_sample = 3 self.bytes_per_sample = self.attributes_per_sample * 4 self.attributes = ['power', 'voltage', 'current'] for i, val in enumerate(self.resistor_values): self.resistor_values[i] = int(1000 * float(val)) def validate(self): if subprocess.call('which caiman', stdout=subprocess.PIPE, shell=True): raise InstrumentError('caiman not in PATH. Cannot enable energy probe') if not self.resistor_values: raise ConfigError('At least one resistor value must be specified') if len(self.resistor_values) > self.MAX_CHANNELS: raise ConfigError('{} Channels where specified when Energy Probe supports up to {}' .format(len(self.resistor_values), self.MAX_CHANNELS)) if pandas is None: self.logger.warning("pandas package will significantly speed up this instrument") self.logger.warning("to install it try: pip install pandas") def setup(self, context): if not self.labels: self.labels = ["PORT_{}".format(channel) for channel, _ in enumerate(self.resistor_values)] self.output_directory = os.path.join(context.output_directory, 'energy_probe') rstring = "" for i, rval in enumerate(self.resistor_values): rstring += '-r {}:{} '.format(i, rval) self.command = 'caiman -d {} -l {} {}'.format(self.device_entry, rstring, self.output_directory) os.makedirs(self.output_directory) def start(self, context): self.logger.debug(self.command) self.caiman = subprocess.Popen(self.command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, preexec_fn=os.setpgrp, shell=True) def stop(self, context): os.killpg(self.caiman.pid, signal.SIGTERM) def update_result(self, context): # pylint: disable=too-many-locals num_of_channels = len(self.resistor_values) processed_data = [[] for _ in xrange(num_of_channels)] filenames = [os.path.join(self.output_directory, '{}.csv'.format(label)) for label in self.labels] struct_format = '{}I'.format(num_of_channels * self.attributes_per_sample) not_a_full_row_seen = False with open(os.path.join(self.output_directory, "0000000000"), "rb") as bfile: while True: data = bfile.read(num_of_channels * self.bytes_per_sample) if data == '': break try: unpacked_data = struct.unpack(struct_format, data) except struct.error: if not_a_full_row_seen: self.logger.warn('possibly missaligned caiman raw data, row contained {} bytes'.format(len(data))) continue else: not_a_full_row_seen = True for i in xrange(num_of_channels): index = i * self.attributes_per_sample processed_data[i].append({attr: val for attr, val in zip(self.attributes, unpacked_data[index:index + self.attributes_per_sample])}) for i, path in enumerate(filenames): with open(path, 'w') as f: if pandas is not None: self._pandas_produce_csv(processed_data[i], f) else: self._slow_produce_csv(processed_data[i], f) # pylint: disable=R0201 def _pandas_produce_csv(self, data, f): dframe = pandas.DataFrame(data) dframe = dframe / 1000.0 dframe.to_csv(f) def _slow_produce_csv(self, data, f): new_data = [] for entry in data: new_data.append({key: val / 1000.0 for key, val in entry.items()}) writer = csv.DictWriter(f, self.attributes) writer.writeheader() writer.writerows(new_data)
{ "content_hash": "619a6d4fcb9da9acb0957c171b5e81ea", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 125, "avg_line_length": 47.689922480620154, "alnum_prop": 0.5832249674902471, "repo_name": "jimboatarm/workload-automation", "id": "6fc229ee28cf13aa87655a5292521c1a536bc50f", "size": "6832", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "wlauto/instrumentation/energy_probe/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "40003" }, { "name": "HTML", "bytes": "243720" }, { "name": "Java", "bytes": "227178" }, { "name": "JavaScript", "bytes": "6578" }, { "name": "Jupyter Notebook", "bytes": "1322" }, { "name": "Makefile", "bytes": "430" }, { "name": "Python", "bytes": "1557762" }, { "name": "Shell", "bytes": "39222" }, { "name": "Vim script", "bytes": "901" } ], "symlink_target": "" }
#ifndef _WLC_SURFACE_H_ #define _WLC_SURFACE_H_ #include <stdbool.h> #include <wayland-util.h> #include <pixman.h> #include <wlc/geometry.h> #include <chck/pool/pool.h> #include <wlc/wlc-render.h> #include "resources/resources.h" struct wlc_buffer; struct wlc_output; struct wlc_view; struct wlc_surface_state { struct chck_iter_pool frame_cbs; pixman_region32_t opaque; pixman_region32_t input; pixman_region32_t damage; struct wlc_point offset; struct wlc_point subsurface_position; wlc_resource buffer; int32_t scale; enum wl_output_transform transform; bool attached; }; struct wlc_coordinate_scale { double w, h; }; struct wlc_surface { struct wlc_source buffers, callbacks; struct wlc_surface_state pending; struct wlc_surface_state commit; struct wlc_size size; struct wlc_coordinate_scale coordinate_transform; /* Parent surface for subsurface interface */ wlc_resource parent; /* list of subsurfaces */ struct chck_iter_pool subsurface_list; /* Set if this surface is bind to view */ wlc_handle view; /* The view this surface belongs to, e.g also subsurfaces */ wlc_handle parent_view; /* Current output the surface is attached to */ wlc_handle output; /** * "Texture" as we use OpenGL terminology, but can be id to anything. * Managed by the renderer. */ uint32_t textures[3]; /** * Images, contains hw surfaces that can be anything (For example EGL KHR Images in EGL/gles2 renderer). * Managed by the renderer. */ void *images[3]; enum wlc_surface_format format; bool synchronized, parent_synchronized; }; WLC_NONULLV(2,3) bool wlc_surface_get_opaque(struct wlc_surface *surface, const struct wlc_point *offset, struct wlc_geometry *out_opaque); WLC_NONULLV(2,3) void wlc_surface_get_input(struct wlc_surface *surface, const struct wlc_point *offset, struct wlc_geometry *out_input); struct wlc_buffer* wlc_surface_get_buffer(struct wlc_surface *surface); void wlc_surface_attach_to_view(struct wlc_surface *surface, struct wlc_view *view); bool wlc_surface_attach_to_output(struct wlc_surface *surface, struct wlc_output *output, struct wlc_buffer *buffer); void wlc_surface_set_parent(struct wlc_surface *surface, struct wlc_surface *parent); void wlc_surface_invalidate(struct wlc_surface *surface); void wlc_surface_release(struct wlc_surface *surface); void wlc_surface_commit(struct wlc_surface *surface); WLC_NONULL bool wlc_surface(struct wlc_surface *surface); const struct wl_surface_interface* wlc_surface_implementation(void); #endif /* _WLC_SURFACE_H_ */
{ "content_hash": "2ab67bb9e414648d80bd5d4fa315069a", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 139, "avg_line_length": 30.776470588235295, "alnum_prop": 0.7270642201834863, "repo_name": "Cloudef/wlc", "id": "c77b3925e6e02fb5b6bb6762979f259b4b63fa13", "size": "2616", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/resources/types/surface.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "582338" }, { "name": "C++", "bytes": "2780" }, { "name": "CMake", "bytes": "50714" } ], "symlink_target": "" }
package artie /** Type class to map raw jsons to instances of `A`. */ trait Read[A] extends (String => Either[String, A])
{ "content_hash": "6ad51c2851ab5a2966037d277b996e90", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 55, "avg_line_length": 30.75, "alnum_prop": 0.6829268292682927, "repo_name": "pheymann/artie", "id": "ac039bc7b4274ad884d3ed1a64b3e08ef4f0b4c1", "size": "123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/scala/artie/Read.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "77600" } ], "symlink_target": "" }
#ifndef NFC_DB_NET_CLIENT_MODULE_H #define NFC_DB_NET_CLIENT_MODULE_H #include "NFComm/NFMessageDefine/NFMsgDefine.h" #include "NFComm/NFPluginModule/NFIWorldToMasterModule.h" #include "NFComm/NFPluginModule/NFIWorldLogicModule.h" #include "NFComm/NFPluginModule/NFINetModule.h" #include "NFComm/NFPluginModule/NFIClassModule.h" #include "NFComm/NFPluginModule/NFIElementModule.h" #include "NFComm/NFPluginModule/NFILogModule.h" #include "NFComm/NFPluginModule/NFIWorldNet_ServerModule.h" #include "NFComm/NFPluginModule/NFINetClientModule.h" #include "NFComm/NFPluginModule/NFISecurityModule.h" class NFIDBToWorldModule : public NFIModule { }; class NFCDBToWorldModule : public NFIDBToWorldModule { public: NFCDBToWorldModule(NFIPluginManager* p) { pPluginManager = p; mLastReportTime = 0; } virtual bool Init(); virtual bool BeforeShut(); virtual bool Shut(); virtual bool Execute(); virtual bool AfterInit(); protected: void OnSocketMSEvent(const NFSOCK nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet); void OnClientDisconnect(const NFSOCK nAddress); void OnClientConnected(const NFSOCK nAddress); virtual void LogServerInfo(const std::string& strServerInfo); void Register(NFINet* pNet); void ServerReport(); void OnServerInfoProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void InvalidMessage(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); private: NFINT64 mLastReportTime; NFILogModule* m_pLogModule; NFIElementModule* m_pElementModule; NFIClassModule* m_pClassModule; NFINetClientModule* m_pNetClientModule; NFINetModule* m_pNetModule; NFISecurityModule* m_pSecurityModule; }; #endif
{ "content_hash": "b93fdb367da34b116267452d9c259066", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 107, "avg_line_length": 26.060606060606062, "alnum_prop": 0.7953488372093023, "repo_name": "lightningkay/NoahGameFrame", "id": "10684890a059d49a8f69cee0bfe56c72aaf21925", "size": "2678", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NFServer/NFDBNet_ClientPlugin/NFCDBToWorldModule.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "138199" }, { "name": "Batchfile", "bytes": "6207" }, { "name": "C", "bytes": "2004787" }, { "name": "C#", "bytes": "1139753" }, { "name": "C++", "bytes": "3019884" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "73250" }, { "name": "DIGITAL Command Language", "bytes": "27303" }, { "name": "Dockerfile", "bytes": "744" }, { "name": "HTML", "bytes": "29824" }, { "name": "Java", "bytes": "53467" }, { "name": "Lua", "bytes": "12544" }, { "name": "M4", "bytes": "1572" }, { "name": "Makefile", "bytes": "35030" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "Objective-C", "bytes": "21403" }, { "name": "Pascal", "bytes": "70297" }, { "name": "Perl", "bytes": "3895" }, { "name": "Roff", "bytes": "7559" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "10681" }, { "name": "XSLT", "bytes": "82915" } ], "symlink_target": "" }
Breakout ======== Another HTML5 experiment to implement BREAKOUT in a `<canvas>` * You can find the [game here](http://codeincomplete.com/posts/2011/6/11/javascript_breakout/demo.html) * You can find out [how it works](http://codeincomplete.com/posts/2011/6/11/javascript_breakout/index.html) * [Managing Game State](http://codeincomplete.com/posts/2011/6/12/game_state_in_breakout/) * [Rendering Performance](http://codeincomplete.com/posts/2011/6/12/rendering_breakout/) * [Collision Detection](http://codeincomplete.com/posts/2011/6/12/collision_detection_in_breakout/) * [Gameplay Balance](http://codeincomplete.com/posts/2011/6/13/gameplay_in_breakout/) * [Adding Sound](http://codeincomplete.com/posts/2011/6/16/adding_sound_to_breakout/) * [Touch Events](http://codeincomplete.com/posts/2011/6/24/adding_touch_to_breakout/)
{ "content_hash": "7d9a8ceaa8673c0e451890d218717b6e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 108, "avg_line_length": 65.61538461538461, "alnum_prop": 0.7444314185228605, "repo_name": "Sattanaso/CodeAndGames", "id": "143645c39eb11755966ff9b00cb5252256039712", "size": "853", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/public/games/breakout/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "35149" }, { "name": "HTML", "bytes": "45268" }, { "name": "JavaScript", "bytes": "1103262" } ], "symlink_target": "" }
<?php return [ 'adminEmail' => 'admin@example.com', 'supportEmail' => 'support@example.com', 'user.passwordResetTokenExpire' => 3600, 'logo' => '' ];
{ "content_hash": "9c7d764b9ed9088235096fe8f3a46f23", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 44, "avg_line_length": 24, "alnum_prop": 0.5892857142857143, "repo_name": "BoBRoID/plochadka", "id": "e4c61586af25048c86c8cefb3913b62985ce5a67", "size": "168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/config/params.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "227" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "213980" }, { "name": "JavaScript", "bytes": "67639" }, { "name": "PHP", "bytes": "337539" } ], "symlink_target": "" }
package org.ebookdroid.core.views; import org.ebookdroid.R; import org.ebookdroid.core.IBrowserActivity; import org.ebookdroid.core.bitmaps.BitmapManager; import org.ebookdroid.core.presentation.BookNode; import org.ebookdroid.core.presentation.BookShelfAdapter; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.StateListDrawable; import android.net.Uri; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import java.io.File; import java.util.Calendar; import java.util.GregorianCalendar; public class BookshelfView extends GridView implements OnItemClickListener { private Bitmap mShelfBackground; private Bitmap mShelfBackgroundLeft; private Bitmap mShelfBackgroundRight; private int mShelfWidth; private int mShelfHeight; private Bitmap mWebLeft; private Bitmap mWebRight; private Bitmap mPineLeft; private Bitmap mPineRight; private final IBrowserActivity base; private final BookShelfAdapter adapter; final String path; public BookshelfView(final IBrowserActivity base, final View shelves, final BookShelfAdapter adapter) { super(base.getContext()); this.base = base; this.adapter = adapter; this.path = adapter != null ? adapter.getPath() : ""; setCacheColorHint(0); setSelector(android.R.color.transparent); setNumColumns(AUTO_FIT); setStretchMode(STRETCH_SPACING); if (adapter != null) { setAdapter(adapter); } setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); final Resources r = getResources(); final float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160, r.getDisplayMetrics()); setColumnWidth((int) px); init(base.getContext()); setOnItemClickListener(this); } private void init(final Context context) { final Bitmap shelfBackground = BitmapManager.getResource(R.drawable.shelf_panel1); if (shelfBackground != null) { mShelfWidth = shelfBackground.getWidth(); mShelfHeight = shelfBackground.getHeight(); mShelfBackground = shelfBackground; } Log.i("panda", "======mShelfWidth========"+mShelfWidth); Log.i("panda", "======mShelfHeight========"+mShelfHeight); mShelfBackgroundLeft = BitmapManager.getResource(R.drawable.shelf_panel1_left); mShelfBackgroundRight = BitmapManager.getResource(R.drawable.shelf_panel1_right); mWebLeft = BitmapManager.getResource(R.drawable.web_left); mWebRight = BitmapManager.getResource(R.drawable.web_right); mPineLeft = BitmapManager.getResource(R.drawable.pine_left); mPineRight = BitmapManager.getResource(R.drawable.pine_right); final StateListDrawable drawable = new StateListDrawable(); final SpotlightDrawable start = new SpotlightDrawable(context, this); start.disableOffset(); final SpotlightDrawable end = new SpotlightDrawable(context, this, R.drawable.spotlight_blue); end.disableOffset(); final TransitionDrawable transition = new TransitionDrawable(start, end); drawable.addState(new int[] { android.R.attr.state_pressed }, transition); final SpotlightDrawable normal = new SpotlightDrawable(context, this); drawable.addState(new int[] {}, normal); normal.setParent(drawable); transition.setParent(drawable); setSelector(drawable); setDrawSelectorOnTop(false); } @Override protected void dispatchDraw(final Canvas canvas) { final int count = getChildCount(); int top = count > 0 ? getChildAt(0).getTop() : 0; final int shelfWidth = mShelfWidth; final int shelfHeight = mShelfHeight; final int width = getWidth(); final int height = getHeight(); Log.i("panda", "++++++++++++"+getWidth()); Log.i("panda", "++++++++++++"+getHeight()); for (int y = top; y < height; y += shelfHeight) { for (int x = 0; x < width; x += shelfWidth) { canvas.drawBitmap(mShelfBackground, x, y, null); } canvas.drawBitmap(mShelfBackgroundLeft, 0, y, null); canvas.drawBitmap(mShelfBackgroundRight, width - 15, y, null); } top = (count > 0) ? getChildAt(count - 1).getTop() + shelfHeight : 0; drawDecorations(canvas, top, shelfHeight, width); super.dispatchDraw(canvas); } public void drawDecorations(final Canvas canvas, final int top, final int shelfHeight, final int width) { final Calendar now = new GregorianCalendar(); Bitmap left; Bitmap right; int lOffset; int rOffset; final int date = now.get(Calendar.DATE); final int month = now.get(Calendar.MONTH); if ((date >= 23 && month == Calendar.DECEMBER) || (date <= 13 && month == Calendar.JANUARY)) { // New year left = mPineLeft; right = mPineRight; lOffset = 0; rOffset = mPineRight.getWidth(); } else { left = mWebLeft; right = mWebRight; lOffset = 15; rOffset = mWebRight.getWidth() + 15; } canvas.drawBitmap(left, lOffset, top + 1, null); canvas.drawBitmap(right, width - rOffset, top + shelfHeight + 1, null); } @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { final BookNode node = adapter != null ? (BookNode) adapter.getItem(position) : null; if (node != null) { final File file = new File(node.path); if (!file.isDirectory()) { base.showDocument(Uri.fromFile(file)); } } } }
{ "content_hash": "1ba2be94c7fc7a772827ba07e621f6f8", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 110, "avg_line_length": 37.00606060606061, "alnum_prop": 0.6531280707500818, "repo_name": "hk0792/UsefulClass", "id": "6193827a6b88f513c1ab1aad9965f1b55fc7eabe", "size": "6704", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EBookDroid/src/org/ebookdroid/core/views/BookshelfView.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "8693" }, { "name": "C", "bytes": "25042659" }, { "name": "C++", "bytes": "2621254" }, { "name": "Groff", "bytes": "37925" }, { "name": "HTML", "bytes": "10860" }, { "name": "Java", "bytes": "1137678" }, { "name": "Makefile", "bytes": "122637" }, { "name": "Module Management System", "bytes": "13919" }, { "name": "Objective-C", "bytes": "16685" }, { "name": "Python", "bytes": "180856" }, { "name": "SAS", "bytes": "14500" }, { "name": "Shell", "bytes": "663120" }, { "name": "Smalltalk", "bytes": "2632" } ], "symlink_target": "" }
package org.elasticsearch.index.mapper; import org.apache.lucene.document.Field; import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.Term; import org.apache.lucene.search.MultiTermQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.RegexpQuery; import org.apache.lucene.util.BytesRef; import org.elasticsearch.Version; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.plain.DocValuesIndexFieldData; import org.elasticsearch.index.fielddata.plain.PagedBytesIndexFieldData; import org.elasticsearch.index.query.QueryShardContext; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import static org.apache.lucene.index.IndexOptions.NONE; import static org.elasticsearch.index.mapper.TypeParsers.parseTextField; public class StringFieldMapper extends FieldMapper implements AllFieldMapper.IncludeInAll { public static final String CONTENT_TYPE = "string"; private static final int POSITION_INCREMENT_GAP_USE_ANALYZER = -1; // If a string field is created on 5.x and all parameters are in this list then we // will automatically upgrade to a text/keyword field. Otherwise we will just fail // saying that string fields are not supported anymore. private static final Set<String> SUPPORTED_PARAMETERS_FOR_AUTO_UPGRADE_TO_KEYWORD = new HashSet<>(Arrays.asList( "type", // common keyword parameters, for which the upgrade is straightforward "index", "store", "doc_values", "omit_norms", "norms", "fields", "copy_to", "fielddata", "include_in_all", "ignore_above")); private static final Set<String> SUPPORTED_PARAMETERS_FOR_AUTO_UPGRADE_TO_TEXT = new HashSet<>(Arrays.asList( "type", // common text parameters, for which the upgrade is straightforward "index", "store", "doc_values", "omit_norms", "norms", "fields", "copy_to", "fielddata", "include_in_all", "analyzer", "search_analyzer", "search_quote_analyzer")); public static class Defaults { public static double FIELDDATA_MIN_FREQUENCY = 0; public static double FIELDDATA_MAX_FREQUENCY = Integer.MAX_VALUE; public static int FIELDDATA_MIN_SEGMENT_SIZE = 0; public static final MappedFieldType FIELD_TYPE = new StringFieldType(); static { FIELD_TYPE.freeze(); } // NOTE, when adding defaults here, make sure you add them in the builder public static final String NULL_VALUE = null; public static final int IGNORE_ABOVE = -1; } public static class Builder extends FieldMapper.Builder<Builder, StringFieldMapper> { protected String nullValue = Defaults.NULL_VALUE; /** * The distance between tokens from different values in the same field. * POSITION_INCREMENT_GAP_USE_ANALYZER means default to the analyzer's * setting which in turn defaults to Defaults.POSITION_INCREMENT_GAP. */ protected int positionIncrementGap = POSITION_INCREMENT_GAP_USE_ANALYZER; protected int ignoreAbove = Defaults.IGNORE_ABOVE; public Builder(String name) { super(name, Defaults.FIELD_TYPE, Defaults.FIELD_TYPE); builder = this; } @Override public StringFieldType fieldType() { return (StringFieldType) super.fieldType(); } @Override public Builder searchAnalyzer(NamedAnalyzer searchAnalyzer) { super.searchAnalyzer(searchAnalyzer); return this; } public Builder positionIncrementGap(int positionIncrementGap) { this.positionIncrementGap = positionIncrementGap; return this; } public Builder ignoreAbove(int ignoreAbove) { this.ignoreAbove = ignoreAbove; return this; } public Builder fielddata(boolean fielddata) { fieldType().setFielddata(fielddata); return builder; } public Builder eagerGlobalOrdinals(boolean eagerGlobalOrdinals) { fieldType().setEagerGlobalOrdinals(eagerGlobalOrdinals); return builder; } public Builder fielddataFrequencyFilter(double minFreq, double maxFreq, int minSegmentSize) { fieldType().setFielddataMinFrequency(minFreq); fieldType().setFielddataMaxFrequency(maxFreq); fieldType().setFielddataMinSegmentSize(minSegmentSize); return builder; } @Override protected void setupFieldType(BuilderContext context) { super.setupFieldType(context); if (fieldType().hasDocValues() && ((StringFieldType) fieldType()).fielddata()) { ((StringFieldType) fieldType()).setFielddata(false); } } @Override public StringFieldMapper build(BuilderContext context) { // if the field is not analyzed, then by default, we should omit norms and have docs only // index options, as probably what the user really wants // if they are set explicitly, we will use those values // we also change the values on the default field type so that toXContent emits what // differs from the defaults if (fieldType.indexOptions() != IndexOptions.NONE && !fieldType.tokenized()) { defaultFieldType.setOmitNorms(true); defaultFieldType.setIndexOptions(IndexOptions.DOCS); if (!omitNormsSet && fieldType.boost() == 1.0f) { fieldType.setOmitNorms(true); } if (!indexOptionsSet) { fieldType.setIndexOptions(IndexOptions.DOCS); } } if (positionIncrementGap != POSITION_INCREMENT_GAP_USE_ANALYZER) { if (fieldType.indexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) { throw new IllegalArgumentException("Cannot set position_increment_gap on field [" + name + "] without positions enabled"); } fieldType.setIndexAnalyzer(new NamedAnalyzer(fieldType.indexAnalyzer(), positionIncrementGap)); fieldType.setSearchAnalyzer(new NamedAnalyzer(fieldType.searchAnalyzer(), positionIncrementGap)); fieldType.setSearchQuoteAnalyzer(new NamedAnalyzer(fieldType.searchQuoteAnalyzer(), positionIncrementGap)); } setupFieldType(context); StringFieldMapper fieldMapper = new StringFieldMapper( name, fieldType(), defaultFieldType, positionIncrementGap, ignoreAbove, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); return fieldMapper.includeInAll(includeInAll); } } public static class TypeParser implements Mapper.TypeParser { private final DeprecationLogger deprecationLogger; public TypeParser() { ESLogger logger = Loggers.getLogger(getClass()); this.deprecationLogger = new DeprecationLogger(logger); } @Override public Mapper.Builder parse(String fieldName, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { if (parserContext.indexVersionCreated().onOrAfter(Version.V_5_0_0_alpha1)) { final Object index = node.get("index"); if (Arrays.asList(null, "no", "not_analyzed", "analyzed").contains(index) == false) { throw new IllegalArgumentException("Can't parse [index] value [" + index + "] for field [" + fieldName + "], expected [no], [not_analyzed] or [analyzed]"); } final boolean keyword = index != null && "analyzed".equals(index) == false; // Automatically upgrade simple mappings for ease of upgrade, otherwise fail Set<String> autoUpgradeParameters = keyword ? SUPPORTED_PARAMETERS_FOR_AUTO_UPGRADE_TO_KEYWORD : SUPPORTED_PARAMETERS_FOR_AUTO_UPGRADE_TO_TEXT; if (autoUpgradeParameters.containsAll(node.keySet())) { deprecationLogger.deprecated("The [string] field is deprecated, please use [text] or [keyword] instead on [{}]", fieldName); { // upgrade the index setting node.put("index", "no".equals(index) == false); } { // upgrade norms settings Object norms = node.remove("norms"); if (norms instanceof Map) { norms = ((Map<?,?>) norms).get("enabled"); } if (norms != null) { node.put("norms", TypeParsers.nodeBooleanValue("norms", norms, parserContext)); } Object omitNorms = node.remove("omit_norms"); if (omitNorms != null) { node.put("norms", TypeParsers.nodeBooleanValue("omit_norms", omitNorms, parserContext) == false); } } { // upgrade fielddata settings Object fielddataO = node.get("fielddata"); if (fielddataO instanceof Map) { Map<?,?> fielddata = (Map<?, ?>) fielddataO; if (keyword == false) { node.put("fielddata", "disabled".equals(fielddata.get("format")) == false); Map<?,?> fielddataFilter = (Map<?, ?>) fielddata.get("filter"); if (fielddataFilter != null) { Map<?,?> frequencyFilter = (Map<?, ?>) fielddataFilter.get("frequency"); frequencyFilter.keySet().retainAll(Arrays.asList("min", "max", "min_segment_size")); node.put("fielddata_frequency_filter", frequencyFilter); } } else { node.remove("fielddata"); } final Object loading = fielddata.get("loading"); if (loading != null) { node.put("eager_global_ordinals", "eager_global_ordinals".equals(loading)); } } } if (keyword) { return new KeywordFieldMapper.TypeParser().parse(fieldName, node, parserContext); } else { return new TextFieldMapper.TypeParser().parse(fieldName, node, parserContext); } } throw new IllegalArgumentException("The [string] type is removed in 5.0. You should now use either a [text] " + "or [keyword] field instead for field [" + fieldName + "]"); } StringFieldMapper.Builder builder = new StringFieldMapper.Builder(fieldName); // hack for the fact that string can't just accept true/false for // the index property and still accepts no/not_analyzed/analyzed final Object index = node.remove("index"); if (index != null) { final String normalizedIndex = index.toString(); switch (normalizedIndex) { case "analyzed": builder.tokenized(true); node.put("index", true); break; case "not_analyzed": builder.tokenized(false); node.put("index", true); break; case "no": node.put("index", false); break; default: throw new IllegalArgumentException("Can't parse [index] value [" + index + "] for field [" + fieldName + "], expected [no], [not_analyzed] or [analyzed]"); } } final Object fielddataObject = node.get("fielddata"); if (fielddataObject instanceof Map) { Map<?,?> fielddata = (Map<?, ?>) fielddataObject; final Object loading = fielddata.get("loading"); if (loading != null) { node.put("eager_global_ordinals", "eager_global_ordinals".equals(loading)); } Map<?,?> fielddataFilter = (Map<?, ?>) fielddata.get("filter"); if (fielddataFilter != null) { Map<?,?> frequencyFilter = (Map<?, ?>) fielddataFilter.get("frequency"); frequencyFilter.keySet().retainAll(Arrays.asList("min", "max", "min_segment_size")); node.put("fielddata_frequency_filter", frequencyFilter); } node.put("fielddata", "disabled".equals(fielddata.get("format")) == false); } parseTextField(builder, fieldName, node, parserContext); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String propName = entry.getKey(); Object propNode = entry.getValue(); if (propName.equals("null_value")) { if (propNode == null) { throw new MapperParsingException("Property [null_value] cannot be null."); } builder.nullValue(propNode.toString()); iterator.remove(); } else if (propName.equals("position_increment_gap")) { int newPositionIncrementGap = XContentMapValues.nodeIntegerValue(propNode, -1); if (newPositionIncrementGap < 0) { throw new MapperParsingException("positions_increment_gap less than 0 aren't allowed."); } builder.positionIncrementGap(newPositionIncrementGap); // we need to update to actual analyzers if they are not set in this case... // so we can inject the position increment gap... if (builder.fieldType().indexAnalyzer() == null) { builder.fieldType().setIndexAnalyzer(parserContext.analysisService().defaultIndexAnalyzer()); } if (builder.fieldType().searchAnalyzer() == null) { builder.fieldType().setSearchAnalyzer(parserContext.analysisService().defaultSearchAnalyzer()); } if (builder.fieldType().searchQuoteAnalyzer() == null) { builder.fieldType().setSearchQuoteAnalyzer(parserContext.analysisService().defaultSearchQuoteAnalyzer()); } iterator.remove(); } else if (propName.equals("ignore_above")) { builder.ignoreAbove(XContentMapValues.nodeIntegerValue(propNode, -1)); iterator.remove(); } else if (propName.equals("fielddata")) { builder.fielddata(XContentMapValues.nodeBooleanValue(propNode)); iterator.remove(); } else if (propName.equals("eager_global_ordinals")) { builder.eagerGlobalOrdinals(XContentMapValues.nodeBooleanValue(propNode)); iterator.remove(); } else if (propName.equals("fielddata_frequency_filter")) { Map<?,?> frequencyFilter = (Map<?, ?>) propNode; double minFrequency = XContentMapValues.nodeDoubleValue(frequencyFilter.remove("min"), 0); double maxFrequency = XContentMapValues.nodeDoubleValue(frequencyFilter.remove("max"), Integer.MAX_VALUE); int minSegmentSize = XContentMapValues.nodeIntegerValue(frequencyFilter.remove("min_segment_size"), 0); builder.fielddataFrequencyFilter(minFrequency, maxFrequency, minSegmentSize); DocumentMapperParser.checkNoRemainingFields(propName, frequencyFilter, parserContext.indexVersionCreated()); iterator.remove(); } } return builder; } } public static final class StringFieldType extends org.elasticsearch.index.mapper.StringFieldType { private boolean fielddata; private double fielddataMinFrequency; private double fielddataMaxFrequency; private int fielddataMinSegmentSize; public StringFieldType() { fielddata = true; fielddataMinFrequency = Defaults.FIELDDATA_MIN_FREQUENCY; fielddataMaxFrequency = Defaults.FIELDDATA_MAX_FREQUENCY; fielddataMinSegmentSize = Defaults.FIELDDATA_MIN_SEGMENT_SIZE; } protected StringFieldType(StringFieldType ref) { super(ref); this.fielddata = ref.fielddata; this.fielddataMinFrequency = ref.fielddataMinFrequency; this.fielddataMaxFrequency = ref.fielddataMaxFrequency; this.fielddataMinSegmentSize = ref.fielddataMinSegmentSize; } @Override public boolean equals(Object o) { if (super.equals(o) == false) { return false; } StringFieldType that = (StringFieldType) o; return fielddata == that.fielddata && fielddataMinFrequency == that.fielddataMinFrequency && fielddataMaxFrequency == that.fielddataMaxFrequency && fielddataMinSegmentSize == that.fielddataMinSegmentSize; } @Override public int hashCode() { return Objects.hash(super.hashCode(), fielddata, fielddataMinFrequency, fielddataMaxFrequency, fielddataMinSegmentSize); } public StringFieldType clone() { return new StringFieldType(this); } @Override public String typeName() { return CONTENT_TYPE; } @Override public void checkCompatibility(MappedFieldType other, List<String> conflicts, boolean strict) { super.checkCompatibility(other, conflicts, strict); StringFieldType otherType = (StringFieldType) other; if (strict) { if (fielddata() != otherType.fielddata()) { conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update [fielddata] " + "across all types."); } if (fielddataMinFrequency() != otherType.fielddataMinFrequency()) { conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update " + "[fielddata_frequency_filter.min] across all types."); } if (fielddataMaxFrequency() != otherType.fielddataMaxFrequency()) { conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update " + "[fielddata_frequency_filter.max] across all types."); } if (fielddataMinSegmentSize() != otherType.fielddataMinSegmentSize()) { conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update " + "[fielddata_frequency_filter.min_segment_size] across all types."); } } } public boolean fielddata() { return fielddata; } public void setFielddata(boolean fielddata) { checkIfFrozen(); this.fielddata = fielddata; } public double fielddataMinFrequency() { return fielddataMinFrequency; } public void setFielddataMinFrequency(double fielddataMinFrequency) { checkIfFrozen(); this.fielddataMinFrequency = fielddataMinFrequency; } public double fielddataMaxFrequency() { return fielddataMaxFrequency; } public void setFielddataMaxFrequency(double fielddataMaxFrequency) { checkIfFrozen(); this.fielddataMaxFrequency = fielddataMaxFrequency; } public int fielddataMinSegmentSize() { return fielddataMinSegmentSize; } public void setFielddataMinSegmentSize(int fielddataMinSegmentSize) { checkIfFrozen(); this.fielddataMinSegmentSize = fielddataMinSegmentSize; } @Override public Query nullValueQuery() { if (nullValue() == null) { return null; } return termQuery(nullValue(), null); } @Override public IndexFieldData.Builder fielddataBuilder() { if (hasDocValues()) { return new DocValuesIndexFieldData.Builder(); } else if (fielddata) { return new PagedBytesIndexFieldData.Builder(fielddataMinFrequency, fielddataMaxFrequency, fielddataMinSegmentSize); } else { throw new IllegalArgumentException("Fielddata is disabled on analyzed string fields by default. Set fielddata=true on [" + name() + "] in order to load fielddata in memory by uninverting the inverted index. Note that this can however " + "use significant memory."); } } } private Boolean includeInAll; private int positionIncrementGap; private int ignoreAbove; protected StringFieldMapper(String simpleName, StringFieldType fieldType, MappedFieldType defaultFieldType, int positionIncrementGap, int ignoreAbove, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(simpleName, fieldType, defaultFieldType, indexSettings, multiFields, copyTo); if (Version.indexCreated(indexSettings).onOrAfter(Version.V_5_0_0_alpha1)) { throw new IllegalArgumentException("The [string] type is removed in 5.0. You should now use either a [text] " + "or [keyword] field instead for field [" + fieldType.name() + "]"); } if (fieldType.tokenized() && fieldType.indexOptions() != NONE && fieldType().hasDocValues()) { throw new MapperParsingException("Field [" + fieldType.name() + "] cannot be analyzed and have doc values"); } if (fieldType.hasDocValues() && ( fieldType.fielddataMinFrequency() != Defaults.FIELDDATA_MIN_FREQUENCY || fieldType.fielddataMaxFrequency() != Defaults.FIELDDATA_MAX_FREQUENCY || fieldType.fielddataMinSegmentSize() != Defaults.FIELDDATA_MIN_SEGMENT_SIZE)) { throw new MapperParsingException("Field [" + fieldType.name() + "] cannot have doc values and use fielddata filtering"); } this.positionIncrementGap = positionIncrementGap; this.ignoreAbove = ignoreAbove; } @Override protected StringFieldMapper clone() { return (StringFieldMapper) super.clone(); } @Override public StringFieldMapper includeInAll(Boolean includeInAll) { if (includeInAll != null) { StringFieldMapper clone = clone(); clone.includeInAll = includeInAll; return clone; } else { return this; } } @Override public StringFieldMapper includeInAllIfNotSet(Boolean includeInAll) { if (includeInAll != null && this.includeInAll == null) { StringFieldMapper clone = clone(); clone.includeInAll = includeInAll; return clone; } else { return this; } } @Override public StringFieldMapper unsetIncludeInAll() { if (includeInAll != null) { StringFieldMapper clone = clone(); clone.includeInAll = null; return clone; } else { return this; } } @Override protected boolean customBoost() { return true; } public int getPositionIncrementGap() { return this.positionIncrementGap; } public int getIgnoreAbove() { return ignoreAbove; } @Override protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException { ValueAndBoost valueAndBoost = parseCreateFieldForString(context, fieldType().nullValueAsString(), fieldType().boost()); if (valueAndBoost.value() == null) { return; } if (ignoreAbove > 0 && valueAndBoost.value().length() > ignoreAbove) { return; } if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(fieldType().name(), valueAndBoost.value(), valueAndBoost.boost()); } if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) { Field field = new Field(fieldType().name(), valueAndBoost.value(), fieldType()); if (valueAndBoost.boost() != 1f && Version.indexCreated(context.indexSettings()).before(Version.V_5_0_0_alpha1)) { field.setBoost(valueAndBoost.boost()); } fields.add(field); } if (fieldType().hasDocValues()) { fields.add(new SortedSetDocValuesField(fieldType().name(), new BytesRef(valueAndBoost.value()))); } } /** * Parse a field as though it were a string. * @param context parse context used during parsing * @param nullValue value to use for null * @param defaultBoost default boost value returned unless overwritten in the field * @return the parsed field and the boost either parsed or defaulted * @throws IOException if thrown while parsing */ public static ValueAndBoost parseCreateFieldForString(ParseContext context, String nullValue, float defaultBoost) throws IOException { if (context.externalValueSet()) { return new ValueAndBoost(context.externalValue().toString(), defaultBoost); } XContentParser parser = context.parser(); if (parser.currentToken() == XContentParser.Token.VALUE_NULL) { return new ValueAndBoost(nullValue, defaultBoost); } if (parser.currentToken() == XContentParser.Token.START_OBJECT && Version.indexCreated(context.indexSettings()).before(Version.V_5_0_0_alpha1)) { XContentParser.Token token; String currentFieldName = null; String value = nullValue; float boost = defaultBoost; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) { value = parser.textOrNull(); } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) { boost = parser.floatValue(); } else { throw new IllegalArgumentException("unknown property [" + currentFieldName + "]"); } } } return new ValueAndBoost(value, boost); } return new ValueAndBoost(parser.textOrNull(), defaultBoost); } @Override protected String contentType() { return CONTENT_TYPE; } @Override protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); this.includeInAll = ((StringFieldMapper) mergeWith).includeInAll; this.ignoreAbove = ((StringFieldMapper) mergeWith).ignoreAbove; } @Override protected String indexTokenizeOption(boolean indexed, boolean tokenized) { if (!indexed) { return "no"; } else if (tokenized) { return "analyzed"; } else { return "not_analyzed"; } } @Override public StringFieldType fieldType() { return (StringFieldType) super.fieldType(); } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); doXContentAnalyzers(builder, includeDefaults); if (includeDefaults || fieldType().nullValue() != null) { builder.field("null_value", fieldType().nullValue()); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } else if (includeDefaults) { builder.field("include_in_all", false); } if (includeDefaults || positionIncrementGap != POSITION_INCREMENT_GAP_USE_ANALYZER) { builder.field("position_increment_gap", positionIncrementGap); } if (includeDefaults || ignoreAbove != Defaults.IGNORE_ABOVE) { builder.field("ignore_above", ignoreAbove); } if (includeDefaults || fieldType().fielddata() != ((StringFieldType) defaultFieldType).fielddata()) { builder.field("fielddata", fieldType().fielddata()); } if (fieldType().fielddata()) { if (includeDefaults || fieldType().fielddataMinFrequency() != Defaults.FIELDDATA_MIN_FREQUENCY || fieldType().fielddataMaxFrequency() != Defaults.FIELDDATA_MAX_FREQUENCY || fieldType().fielddataMinSegmentSize() != Defaults.FIELDDATA_MIN_SEGMENT_SIZE) { builder.startObject("fielddata_frequency_filter"); if (includeDefaults || fieldType().fielddataMinFrequency() != Defaults.FIELDDATA_MIN_FREQUENCY) { builder.field("min", fieldType().fielddataMinFrequency()); } if (includeDefaults || fieldType().fielddataMaxFrequency() != Defaults.FIELDDATA_MAX_FREQUENCY) { builder.field("max", fieldType().fielddataMaxFrequency()); } if (includeDefaults || fieldType().fielddataMinSegmentSize() != Defaults.FIELDDATA_MIN_SEGMENT_SIZE) { builder.field("min_segment_size", fieldType().fielddataMinSegmentSize()); } builder.endObject(); } } } /** * Parsed value and boost to be returned from {@link #parseCreateFieldForString}. */ public static class ValueAndBoost { private final String value; private final float boost; public ValueAndBoost(String value, float boost) { this.value = value; this.boost = boost; } /** * Value of string field. * @return value of string field */ public String value() { return value; } /** * Boost either parsed from the document or defaulted. * @return boost either parsed from the document or defaulted */ public float boost() { return boost; } } }
{ "content_hash": "4edf150a53e1724528357e9ebcc20e7d", "timestamp": "", "source": "github", "line_count": 711, "max_line_length": 175, "avg_line_length": 45.829817158931085, "alnum_prop": 0.5887678379622525, "repo_name": "zkidkid/elasticsearch", "id": "6f529c82ea119f38d127a911932527b6885be9ec", "size": "33373", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/org/elasticsearch/index/mapper/StringFieldMapper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "299" }, { "name": "Java", "bytes": "25758712" }, { "name": "Perl", "bytes": "6858" }, { "name": "Python", "bytes": "61062" }, { "name": "Ruby", "bytes": "32034" }, { "name": "Shell", "bytes": "27524" } ], "symlink_target": "" }
#ifndef _INTEL_DPLL_MGR_H_ #define _INTEL_DPLL_MGR_H_ /*FIXME: Move this to a more appropriate place. */ #define abs_diff(a, b) ({ \ typeof(a) __a = (a); \ typeof(b) __b = (b); \ (void) (&__a == &__b); \ __a > __b ? (__a - __b) : (__b - __a); }) struct drm_i915_private; struct intel_crtc; struct intel_crtc_state; struct intel_encoder; struct intel_shared_dpll; struct intel_dpll_mgr; enum intel_dpll_id { DPLL_ID_PRIVATE = -1, /* non-shared dpll in use */ /* real shared dpll ids must be >= 0 */ DPLL_ID_PCH_PLL_A = 0, DPLL_ID_PCH_PLL_B = 1, /* hsw/bdw */ DPLL_ID_WRPLL1 = 0, DPLL_ID_WRPLL2 = 1, DPLL_ID_SPLL = 2, DPLL_ID_LCPLL_810 = 3, DPLL_ID_LCPLL_1350 = 4, DPLL_ID_LCPLL_2700 = 5, /* skl */ DPLL_ID_SKL_DPLL0 = 0, DPLL_ID_SKL_DPLL1 = 1, DPLL_ID_SKL_DPLL2 = 2, DPLL_ID_SKL_DPLL3 = 3, }; #define I915_NUM_PLLS 6 /** Inform the state checker that the DPLL is kept enabled even if not * in use by any crtc. */ #define INTEL_DPLL_ALWAYS_ON (1 << 0) struct intel_dpll_hw_state { /* i9xx, pch plls */ uint32_t dpll; uint32_t dpll_md; uint32_t fp0; uint32_t fp1; /* hsw, bdw */ uint32_t wrpll; uint32_t spll; /* skl */ /* * DPLL_CTRL1 has 6 bits for each each this DPLL. We store those in * lower part of ctrl1 and they get shifted into position when writing * the register. This allows us to easily compare the state to share * the DPLL. */ uint32_t ctrl1; /* HDMI only, 0 when used for DP */ uint32_t cfgcr1, cfgcr2; /* bxt */ uint32_t ebb0, ebb4, pll0, pll1, pll2, pll3, pll6, pll8, pll9, pll10, pcsdw12; }; struct intel_shared_dpll_config { unsigned crtc_mask; /* mask of CRTCs sharing this PLL */ struct intel_dpll_hw_state hw_state; }; struct intel_shared_dpll_funcs { /* The mode_set hook is optional and should be used together with the * intel_prepare_shared_dpll function. */ void (*mode_set)(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll); void (*enable)(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll); void (*disable)(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll); bool (*get_hw_state)(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, struct intel_dpll_hw_state *hw_state); }; struct intel_shared_dpll { struct intel_shared_dpll_config config; unsigned active_mask; /* mask of active CRTCs (i.e. DPMS on) */ bool on; /* is the PLL actually active? Disabled during modeset */ const char *name; /* should match the index in the dev_priv->shared_dplls array */ enum intel_dpll_id id; struct intel_shared_dpll_funcs funcs; uint32_t flags; }; #define SKL_DPLL0 0 #define SKL_DPLL1 1 #define SKL_DPLL2 2 #define SKL_DPLL3 3 /* shared dpll functions */ struct intel_shared_dpll * intel_get_shared_dpll_by_id(struct drm_i915_private *dev_priv, enum intel_dpll_id id); enum intel_dpll_id intel_get_shared_dpll_id(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll); void intel_shared_dpll_config_get(struct intel_shared_dpll_config *config, struct intel_shared_dpll *pll, struct intel_crtc *crtc); void intel_shared_dpll_config_put(struct intel_shared_dpll_config *config, struct intel_shared_dpll *pll, struct intel_crtc *crtc); void assert_shared_dpll(struct drm_i915_private *dev_priv, struct intel_shared_dpll *pll, bool state); #define assert_shared_dpll_enabled(d, p) assert_shared_dpll(d, p, true) #define assert_shared_dpll_disabled(d, p) assert_shared_dpll(d, p, false) struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc, struct intel_crtc_state *state, struct intel_encoder *encoder); void intel_prepare_shared_dpll(struct intel_crtc *crtc); void intel_enable_shared_dpll(struct intel_crtc *crtc); void intel_disable_shared_dpll(struct intel_crtc *crtc); void intel_shared_dpll_commit(struct drm_atomic_state *state); void intel_shared_dpll_init(struct drm_device *dev); #endif /* _INTEL_DPLL_MGR_H_ */
{ "content_hash": "c24d2a79f364a9cb5ea641043f6062a5", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 73, "avg_line_length": 28.274647887323944, "alnum_prop": 0.6801992528019926, "repo_name": "AlbandeCrevoisier/ldd-athens", "id": "89c5ada1a3157003c165dae6f9af67908e3152cf", "size": "5178", "binary": false, "copies": "103", "ref": "refs/heads/master", "path": "linux-socfpga/drivers/gpu/drm/i915/intel_dpll_mgr.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "10184236" }, { "name": "Awk", "bytes": "40418" }, { "name": "Batchfile", "bytes": "81753" }, { "name": "C", "bytes": "566858455" }, { "name": "C++", "bytes": "21399133" }, { "name": "Clojure", "bytes": "971" }, { "name": "Cucumber", "bytes": "5998" }, { "name": "FORTRAN", "bytes": "11832" }, { "name": "GDB", "bytes": "18113" }, { "name": "Groff", "bytes": "2686457" }, { "name": "HTML", "bytes": "34688334" }, { "name": "Lex", "bytes": "56961" }, { "name": "Logos", "bytes": "133810" }, { "name": "M4", "bytes": "3325" }, { "name": "Makefile", "bytes": "1685015" }, { "name": "Objective-C", "bytes": "920162" }, { "name": "Perl", "bytes": "752477" }, { "name": "Perl6", "bytes": "3783" }, { "name": "Python", "bytes": "533352" }, { "name": "Shell", "bytes": "468244" }, { "name": "SourcePawn", "bytes": "2711" }, { "name": "UnrealScript", "bytes": "12824" }, { "name": "XC", "bytes": "33970" }, { "name": "XS", "bytes": "34909" }, { "name": "Yacc", "bytes": "113516" } ], "symlink_target": "" }
%% Introduction to *wavelet_2d* % *wavelet_2d* is a function able to compute the wavelet transform of a % signal. Given $$ J \in \bf{N} $$, the wavelet transform of a signal % $$ x \in \bf{R}^N $$ % is given by % % $$ Wf(x) =\{x\ast \phi_J, x\ast\psi_{\lambda}\}_{\lambda \in \mathcal{P}} $$ % where in our case $\mathcal{P}=\{\lambda=2^{-j}r,r \in G_+, j<J\}$ is the % index of a set of filters. % %% Usage % [x_phi, x_psi] = *wavelet_2d*(x, filters, options) (see % <matlab:doc('wavelet_2d') wavelet_2d>). % %% Description % It is possible to create some wavelet filters with wavelet_factory_2d for % instance. The filter size have to be adapted to the size of the input % signal $x$. % clear all; src = 'C:/testImages/Perception/WaterSurface/WaterSurface1600.bmp'; x = im2double(rgb2gray(imread(src))); filters = morlet_filter_bank_2d(size(x)); [x_phi,x_psi]=wavelet_2d(x,filters); figure; colormap gray; subplot(1,2,1) imagesc(real(x_psi{1})) axis square axis off title({'Real part of the first';'wavelet transform coefficient'}); subplot(1,2,2) imagesc(imag(x_psi{1})) axis square axis off title({'Imaginary part of the first';'wavelet transform coefficient'}); %% Options % Several options are available with wavelet_2d that allow the user to % change the output or the way to compute it. % % * options.x_resolution = 0 changes the resolution on which % the wavelet transform is computed by a factor 2. % * options.precision = 'single' allows to compute either with 'double' or % 'single'. % * options.oversampling = 1 oversamples the signal by a factor 2. % * options.psi_mask = [1 ... 1] is of a size the number of filters and % allows to compute the signal only when the corresponding wavelet has a % '1' in its respective psi_mask.
{ "content_hash": "a4de2ed46ffef698e3668c4858c7ab51", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 78, "avg_line_length": 35.31372549019608, "alnum_prop": 0.6762909494725152, "repo_name": "sc1991327/scatnet-0.2", "id": "9fcc841eedd64bdb45571978f386719c5f7ae460", "size": "1801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test_wavelet_2d.m", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Matlab", "bytes": "449993" } ], "symlink_target": "" }
using ColossalFramework.UI; using UnityEngine; namespace EptuiTlmIntegration { public class AutoLineInfoCloser : MonoBehaviour { public int lineID; public UIPanel panel ; public void Update() { if (!panel.isVisible) { Destroy(gameObject); } if (TransportManager.instance.m_lines.m_buffer[lineID].m_flags != TransportLine.Flags.None) { return; } panel.Hide(); Destroy(gameObject); } } }
{ "content_hash": "d73190f83d8f19c9a3e833c66b1d84f0", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 103, "avg_line_length": 21.923076923076923, "alnum_prop": 0.5210526315789473, "repo_name": "earalov/Skylines-EPTUI-TLM-integration", "id": "c59ef8ca80fc54528bc06b0164364f80bdc6a816", "size": "572", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EptuiTlmIntegration/AutoLineInfoCloser.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "12650" } ], "symlink_target": "" }
/* * SOURCE FILE GENERATATED BY JACOB CHANNEL CLASS GENERATOR * * !!! DO NOT EDIT !!!! * * Generated On : Thu Jun 24 22:35:42 EST 2010 * For Interface : org.apache.ode.bpel.runtime.channels.Termination */ package org.apache.ode.bpel.runtime.channels; /** * An auto-generated channel interface for the channel type * {@link org.apache.ode.bpel.runtime.channels.Termination}. * @see org.apache.ode.bpel.runtime.channels.Termination * @see org.apache.ode.bpel.runtime.channels.TerminationChannelListener */ public interface TerminationChannel extends org.apache.ode.jacob.Channel, org.apache.ode.bpel.runtime.channels.Termination {}
{ "content_hash": "b0a15a0118e8b54ffb43988282250a97", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 71, "avg_line_length": 32.333333333333336, "alnum_prop": 0.7172312223858616, "repo_name": "thiliA/wso2-ode", "id": "85ce4814ecaf0a0a8ada5cb73f90acb22c572699", "size": "679", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/channels/TerminationChannel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "35889" }, { "name": "Groovy", "bytes": "3604" }, { "name": "Java", "bytes": "6966679" }, { "name": "JavaScript", "bytes": "250490" }, { "name": "Ruby", "bytes": "74333" }, { "name": "Shell", "bytes": "10136" }, { "name": "XSLT", "bytes": "10201" } ], "symlink_target": "" }
from mongoengine.connection import get_db class query_counter(object): """ Query_counter contextmanager to get the number of queries. """ def __init__(self): """ Construct the query_counter. """ self.counter = 0 self.db = get_db() def __enter__(self): """ On every with block we need to drop the profile collection. """ self.db.set_profiling_level(0) self.db.system.profile.really_drop() self.db.set_profiling_level(2) return self def __exit__(self, t, value, traceback): """ Reset the profiling level. """ self.db.set_profiling_level(0) def __eq__(self, value): """ == Compare querycounter. """ return value == self._get_count() def __ne__(self, value): """ != Compare querycounter. """ return not self.__eq__(value) def __lt__(self, value): """ < Compare querycounter. """ return self._get_count() < value def __le__(self, value): """ <= Compare querycounter. """ return self._get_count() <= value def __gt__(self, value): """ > Compare querycounter. """ return self._get_count() > value def __ge__(self, value): """ >= Compare querycounter. """ return self._get_count() >= value def __int__(self): """ int representation. """ return self._get_count() def __repr__(self): """ repr query_counter as the number of queries. """ return u"%s" % self._get_count() def _get_count(self): """ Get the number of queries. """ count = self.db.system.profile.find().count() - self.counter self.counter += 1 return count
{ "content_hash": "4e01255d02684f578907cafc801a4215", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 75, "avg_line_length": 29.06779661016949, "alnum_prop": 0.5440233236151604, "repo_name": "colinhowe/mongoengine", "id": "20620eba3cdfce08087c91c01989ea0f2b045aa2", "size": "1715", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "mongoengine/tests.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "516347" } ], "symlink_target": "" }
package org.adonai.plugin.publish.fx.initstep; import javafx.stage.Stage; import javafx.stage.StageStyle; import lombok.extern.slf4j.Slf4j; import org.adonai.ApplicationEnvironment; import org.adonai.api.InitStep; import org.adonai.fx.Mask; import org.adonai.fx.MaskLoader; import org.adonai.fx.ScreenManager; import org.adonai.online.FileStore; @Slf4j public class SynchRemoteDataInitStep implements InitStep { private final MaskLoader<SynchRemoteDataController> maskLoader = new MaskLoader<>(); public void execute (ApplicationEnvironment applicationEnvironment) { Stage initStepStage = new Stage(); Mask<SynchRemoteDataController> mask = maskLoader.loadWithStage("synchRemoteData", getClass().getClassLoader()); SynchRemoteDataController controller = mask.getController(); controller.setStage(initStepStage); controller.setApplicationEnvironment(applicationEnvironment); initStepStage.setScene(mask.getScene()); ScreenManager screenManager = new ScreenManager(); initStepStage.initStyle(StageStyle.UNDECORATED); screenManager.layoutOnScreen(initStepStage, 200, screenManager.getPrimary()); initStepStage.toFront(); initStepStage.showAndWait(); } @Override public boolean isExecuted(ApplicationEnvironment applicationEnvironment) { FileStore fileStore = new FileStore(); return false; // if (true) { //TODO // try { // File tenantPath = applicationEnvironment.getServices().getModelService().getTenantPath(applicationEnvironment.getCurrentTenant()); // FileStoreState remoteState = fileStore.getRemoteState(tenantPath); // log.error("The following remote items after newer: " + remoteState.getItemsRemoteNewer()); // return !remoteState.getItemsRemoteNewer().isEmpty(); // // } catch (IOException e) { // log.error("Error when reading remote state: " + e.getLocalizedMessage(), e); // return true; // } // } // else // return false; } }
{ "content_hash": "688388cb02784e697482b235da772189", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 140, "avg_line_length": 38.05769230769231, "alnum_prop": 0.7448206164729662, "repo_name": "moley/adonai", "id": "62f65314b9ff1336844cd87ce46798b675d0a009", "size": "1979", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/adonai/plugin/publish/fx/initstep/SynchRemoteDataInitStep.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2411" }, { "name": "Java", "bytes": "701005" } ], "symlink_target": "" }
<html> <head> <title> Francis Chu's Home Page </title> </head> <body background="./gif/texture.gif"> <img src="http://www.cs.cornell.edu/Info/People/fcc/gif/mandel.gif"> <h1> Francis Chu </h1> <h2> CS Graduate Student </h2> <hr> <img src="http://www.cs.cornell.edu/Info/People/fcc/gif/blueball.gif"> <a href="http://www.berkeley.edu/"> University of California at Berkeley </a> <br> <img src="http://www.cs.cornell.edu/Info/People/fcc/gif/blueball.gif"> <a href="http://math.berkeley.edu/"> Mathematics Department </a> <br> <img src="http://www.cs.cornell.edu/Info/People/fcc/gif/blueball.gif"> <a href="http://www.cs.berkeley.edu/"> Computer Science Department </a> <br> <img src="http://www.cs.cornell.edu/Info/People/fcc/gif/redball.gif"> <a href="http://www.cornell.edu/"> Cornell University </a> <br> <img src="http://www.cs.cornell.edu/Info/People/fcc/gif/redball.gif"> <a href="http://www.cs.cornell.edu/"> Computer Science Department </a> <br> <hr> <img src="http://www.cs.cornell.edu/Info/People/fcc/gif/greenball.gif"> <a href="http://www.cs.cornell.edu/Info/People/fcc/humor/humor.html"> Humor </a> <br> <hr> <address> <a href="mailto:fcc@cs.cornell.edu"> fcc@cs.cornell.edu </a> </address> </body> </html>
{ "content_hash": "b35dc00591db1aad2f8214f16f4919a7", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 71, "avg_line_length": 19.296875, "alnum_prop": 0.6850202429149798, "repo_name": "ML-SWAT/Web2KnowledgeBase", "id": "930453172755581256209a55adfeb4eebdae59c3", "size": "1235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "course-cotrain-data/fulltext/non-course/http:^^www.cs.cornell.edu^Info^People^fcc^fcc.html", "mode": "33261", "license": "mit", "language": [ { "name": "Groff", "bytes": "641" }, { "name": "HTML", "bytes": "34381871" }, { "name": "Perl", "bytes": "14786" }, { "name": "Perl6", "bytes": "18697" }, { "name": "Python", "bytes": "10084" } ], "symlink_target": "" }